@contractspec/bundle.workspace 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/contracts/operations/init.operation.d.ts +1 -1
  2. package/dist/index.js +771 -526
  3. package/dist/node/index.js +771 -526
  4. package/dist/services/build.d.ts +36 -1
  5. package/dist/services/connect/init.d.ts +2 -6
  6. package/dist/services/connect/types.d.ts +10 -0
  7. package/dist/services/contractsrc-schema-ref.d.ts +4 -0
  8. package/dist/services/deps.d.ts +2 -0
  9. package/dist/services/discover.d.ts +15 -0
  10. package/dist/services/discover.test.d.ts +1 -0
  11. package/dist/services/generate-artifacts.d.ts +4 -0
  12. package/dist/services/index.d.ts +3 -0
  13. package/dist/services/integrity.d.ts +2 -0
  14. package/dist/services/module-loader.d.ts +25 -0
  15. package/dist/services/module-loader.test.d.ts +1 -0
  16. package/dist/services/package-scaffold.d.ts +22 -0
  17. package/dist/services/setup/config-generators.d.ts +1 -1
  18. package/dist/services/setup/gitignore.d.ts +10 -0
  19. package/dist/services/setup/gitignore.test.d.ts +1 -0
  20. package/dist/services/setup/index.d.ts +2 -0
  21. package/dist/services/setup/presets.d.ts +16 -0
  22. package/dist/services/setup/targets/cli-config.test.d.ts +1 -0
  23. package/dist/services/setup/types.d.ts +36 -2
  24. package/dist/services/update.test.d.ts +1 -0
  25. package/dist/services/validate/index.d.ts +1 -0
  26. package/dist/services/validate/module-loader-usage.test.d.ts +1 -0
  27. package/dist/services/validate/package-scaffold-validator.d.ts +8 -0
  28. package/dist/services/validate/package-scaffold-validator.test.d.ts +1 -0
  29. package/dist/services/validate/spec-validator.d.ts +6 -1
  30. package/dist/services/vibe/definitions.test.d.ts +1 -0
  31. package/dist/templates/data-view-renderer.template.d.ts +6 -0
  32. package/dist/templates/feature.template.d.ts +7 -6
  33. package/dist/templates/form.template.d.ts +16 -0
  34. package/dist/templates/form.template.test.d.ts +1 -0
  35. package/dist/templates/index.d.ts +3 -0
  36. package/dist/templates/workflow-devkit.template.d.ts +11 -0
  37. package/dist/utils/index.d.ts +0 -1
  38. package/package.json +8 -8
  39. package/dist/utils/module-loader.d.ts +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- var _6=Object.defineProperty;var L6=($)=>$;function I6($,W){this[$]=L6.bind(null,W)}var P=($,W)=>{for(var j in W)_6($,j,{get:W[j],enumerable:!0,configurable:!0,set:I6.bind(W,j)})};var xj=($,W)=>()=>($&&(W=$($=0)),W);var K$=import.meta.require;import{ContractsrcSchema as Y9,DEFAULT_CONTRACTSRC as f0}from"@contractspec/lib.contracts-spec/workspace-config";async function a($,W){let j=$.join(W??".",".contractsrc.json");if(!await $.exists(j))return f0;try{let Z=await $.readFile(j),B=JSON.parse(Z),X=Y9.safeParse(B);return{...f0,...X.data,conventions:{...f0.conventions,...X.data?.conventions||{}}}}catch{return f0}}function D5($){switch($){case"claude":return process.env.ANTHROPIC_API_KEY;case"openai":return process.env.OPENAI_API_KEY;case"custom":return process.env.CONTRACTSPEC_LLM_API_KEY;case"ollama":return;default:return}}var B$=()=>{};var U4={};P(U4,{AIGenerator:()=>$W});import{createProvider as $B}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as WB,buildEventSpecPrompt as jB,buildFormPrompt as QB,buildHandlerPrompt as ZB,buildOperationSpecPrompt as BB,buildPresentationSpecPrompt as XB,buildTestPrompt as YB,getCodeGenSystemPrompt as B0,getSystemPrompt as c1}from"@contractspec/module.workspace";import{generateObject as l1,generateText as e0,streamText as qB}from"ai";import*as E from"zod";class $W{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,W=this.config.customApiKey||D5(this.config.aiProvider),j={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:W,baseUrl:this.config.customEndpoint||void 0};return $B(j).getModel()}async generateOperationSpec($,W){let j=this.getModel(),Q=E.object({name:E.string().describe('Dot notation name like "domain.operation"'),version:E.number().int().positive().default(1),description:E.string().describe("Clear, concise summary"),goal:E.string().describe("Business purpose"),context:E.string().describe("Background and constraints"),stability:E.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:E.array(E.string()).describe("Team/person owners with @ prefix"),tags:E.array(E.string()).describe("Categorization tags"),auth:E.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:E.string().describe("Description of input structure"),outputShape:E.string().describe("Description of output structure"),flags:E.array(E.string()).describe("Feature flags").default([]),possibleEvents:E.array(E.string()).describe("Events this may emit").default([]),analytics:E.array(E.string()).describe("Analytics events to track").default([])}),Z=BB($,W);return(await l1({model:j,schema:Q,prompt:Z,system:c1()})).object}async generateEventSpec($){let W=this.getModel(),j=E.object({name:E.string().describe('Dot notation name like "domain.event_name"'),version:E.number().int().positive().default(1),description:E.string().describe("When this event is emitted"),stability:E.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:E.array(E.string()).default([]),tags:E.array(E.string()).default([]),payloadShape:E.string().describe("Description of event payload"),piiFields:E.array(E.string()).describe("PII field paths").default([])}),Q=jB($);return(await l1({model:W,schema:j,prompt:Q,system:c1()})).object}async generatePresentationSpec($,W){let j=this.getModel(),Q=E.object({name:E.string(),version:E.number().int().positive().default(1),description:E.string(),stability:E.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:E.array(E.string()).default([]),tags:E.array(E.string()).default([]),componentKey:E.string().optional(),propsShape:E.string().optional(),content:E.string().optional(),mimeType:E.string().optional(),dataShape:E.string().optional()}),Z=XB($,W);return(await l1({model:j,schema:Q,prompt:Z,system:c1()})).object}async generateHandler($){let W=this.getModel();return(await e0({model:W,prompt:ZB($),system:B0()})).text}async generateComponent($){let W=this.getModel();return(await e0({model:W,prompt:WB($),system:B0()})).text}async generateForm($){let W=this.getModel();return(await e0({model:W,prompt:QB($),system:B0()})).text}async generateTests($,W,j){let Q=this.getModel();return(await e0({model:Q,prompt:YB($,W,j),system:B0()})).text}async streamCodeGeneration($,W){let j=this.getModel(),Q=await qB({model:j,prompt:$,system:B0()}),Z="";for await(let B of Q.textStream)Z+=B,W(B);return Z}}var WW=xj(()=>{B$()});import*as PC from"@contractspec/module.workspace";import{anthropic as O6}from"@ai-sdk/anthropic";import{openai as Tj}from"@ai-sdk/openai";import{DEFAULT_MODELS as vj}from"@contractspec/lib.ai-providers/models";import{generateObject as b6,generateText as w6,streamText as C6}from"ai";import{ollama as S6}from"ollama-ai-provider";function yj($){return{async validateProvider(W){try{let{aiProvider:j}=W;if(j==="ollama")return{success:!0};if(j==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(j==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}},async generateText(W){let j=DW($);return{text:(await w6({model:j,prompt:W.prompt,system:W.systemPrompt})).text}},async generateStructured(W){let Q={model:DW($),schema:W.schema,prompt:W.prompt,system:W.systemPrompt};return{object:(await b6(Q)).object}},async streamText(W,j){let Q=DW($),Z=await C6({model:Q,prompt:W.prompt,system:W.systemPrompt}),B="";for await(let X of Z.textStream)B+=X,j(X);return B}}}function DW($){let{aiProvider:W,aiModel:j,customEndpoint:Q}=$;switch(W){case"claude":{let Z=j??vj.anthropic;return O6(Z)}case"openai":{let Z=j??vj.openai;return Tj(Z)}case"ollama":return S6(j??"codellama");case"custom":{if(!Q)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return Tj(j??"default")}default:throw Error(`Unknown AI provider: ${W}`)}}import{DEFAULT_CONTRACTSRC as f6}from"@contractspec/lib.contracts-spec/workspace-config";import{access as E6,stat as M6,mkdir as Pj,readFile as N6,rm as R6,writeFile as D6}from"fs/promises";import{basename as F6,dirname as mj,isAbsolute as x6,join as T6,relative as v6,resolve as kj}from"path";import{glob as y6}from"glob";var U$=["**/*.command.ts","**/*.query.ts","**/*.operation.ts","**/*.operations.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts","**/*.capability.ts","**/*.workflow.ts","**/*.data-view.ts","**/*.form.ts","**/*.migration.ts","**/*.telemetry.ts","**/*.experiment.ts","**/*.app-config.ts","**/*.integration.ts","**/*.knowledge.ts","**/*.policy.ts","**/*.test-spec.ts","**/contracts/*.ts","**/contracts/index.ts","**/commands/*.ts","**/commands/index.ts","**/queries/*.ts","**/queries/index.ts","**/operations/*.ts","**/operations/index.ts","**/operations.ts","**/events.ts","**/presentations.ts","**/events/index.ts","**/presentations/index.ts","**/tests/*.ts","**/tests/*.test-spec.ts"],_$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function gj($){let W=$??process.cwd();return{async exists(Q){try{return await E6(j(Q)),!0}catch{return!1}},async readFile(Q){return N6(j(Q),"utf-8")},async writeFile(Q,Z){let B=j(Q),X=mj(B);await Pj(X,{recursive:!0}),await D6(B,Z,"utf-8")},async remove(Q){await R6(j(Q),{recursive:!0,force:!0})},async stat(Q){let Z=await M6(j(Q));return{size:Z.size,isFile:Z.isFile(),isDirectory:Z.isDirectory(),mtime:Z.mtime}},async mkdir(Q){await Pj(j(Q),{recursive:!0})},async glob(Q){let Z=Q.patterns??(Q.pattern?[Q.pattern]:U$),B=Q.ignore??_$,X=Q.cwd??W,Y=Q.absolute??!0;return(await y6(Z,{cwd:X,ignore:B,absolute:Y})).sort((A,H)=>A.localeCompare(H))},resolve(...Q){let[Z,...B]=Q;if(!Z)return W;return kj(W,Z,...B)},dirname(Q){return mj(Q)},basename(Q){return F6(Q)},join(...Q){return T6(...Q)},relative(Q,Z){return v6(Q,Z)}};function j(Q){return x6(Q)?Q:kj(W,Q)}}import{execFileSync as n$}from"child_process";import{access as P6}from"fs/promises";import{resolve as hj}from"path";function fj($){let W=$??process.cwd();return{async currentBranch(){try{let j=n$("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();return j.length>0?j:void 0}catch{return}},async showFile(j,Q){try{return n$("git",["show",`${j}:${Q}`],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}catch(Z){throw Error(`Could not load ${Q} at ref ${j}: ${Z instanceof Error?Z.message:String(Z)}`)}},async clean(j){let Q=[];if(j?.force)Q.push("-f");if(j?.directories)Q.push("-d");if(j?.ignored)Q.push("-x");if(j?.dryRun)Q.push("--dry-run");n$("git",["clean",...Q],{cwd:W,stdio:"inherit"})},async isGitRepo(j){let Q=j?hj(W,j):W;try{return await P6(hj(Q,".git")),!0}catch{return!1}},async log(j){let Q=j??"HEAD~10",Z="--format=%H|||%s|||%an|||%aI";try{let B=n$("git",["log",`${Q}..HEAD`,"--format=%H|||%s|||%an|||%aI"],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}),X=[];for(let Y of B.trim().split(`
3
- `)){if(!Y)continue;let[q,A,H,V]=Y.split("|||");if(q&&A)X.push({hash:q,message:A,author:H,date:V})}return X}catch{return[]}},async diffFiles(j,Q){try{let Z=Q&&Q.length>0?["--",...Q]:[];return n$("git",["diff","--name-only",`${j}...HEAD`,...Z],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim().split(`
4
- `).filter(Boolean)}catch{return[]}}}}function uj(){return{debug($,W){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,W??"")},info($,W){console.info(`[INFO] ${$}`,W??"")},warn($,W){console.warn(`[WARN] ${$}`,W??"")},error($,W){console.error(`[ERROR] ${$}`,W??"")},createProgress(){return m6()}}}function dj(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:k6}}function m6(){return{start($){console.warn(`\u23F3 ${$}`)},update($){let W=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${W}`)},succeed($){console.warn(`\u2705 ${$??"Done"}`)},fail($){console.error(`\u274C ${$??"Failed"}`)},warn($){console.warn(`\u26A0\uFE0F ${$??"Warning"}`)},stop(){}}}function k6(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import g6 from"chokidar";var h6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function nj($){let W=$??process.cwd();return{watch(j){let Q=[],Z,B=g6.watch(j.pattern,{cwd:W,ignored:j.ignore??h6,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),X=(Y)=>{if(j.debounceMs&&j.debounceMs>0)clearTimeout(Z),Z=setTimeout(()=>{Q.forEach((q)=>q(Y))},j.debounceMs);else Q.forEach((q)=>q(Y))};return B.on("add",(Y)=>{X({type:"add",path:Y})}),B.on("change",(Y)=>{X({type:"change",path:Y})}),B.on("unlink",(Y)=>{X({type:"unlink",path:Y})}),{on(Y){Q.push(Y)},async close(){clearTimeout(Z),await B.close()}}}}}function Kq($={}){let{cwd:W,config:j,silent:Q}=$,Z=j??f6;return{fs:gj(W),git:fj(W),watcher:nj(W),ai:yj(Z),logger:Q?dj():uj()}}import{stat as u6,mkdir as d6}from"fs/promises";import{basename as n6,dirname as c6,isAbsolute as l6,join as r6,relative as o6,resolve as cj}from"path";import{glob as p6}from"glob";function bq($){let W=$??process.cwd();return{async exists(Q){let Z=Bun.file(j(Q));try{return await Z.exists(),!0}catch{return!1}},async readFile(Q){return Bun.file(j(Q)).text()},async writeFile(Q,Z){let B=j(Q);await Bun.write(B,Z)},async remove(Q){await Bun.file(j(Q)).delete()},async stat(Q){let Z=await u6(j(Q));return{size:Z.size,isFile:Z.isFile(),isDirectory:Z.isDirectory(),mtime:Z.mtime}},async mkdir(Q){await d6(j(Q),{recursive:!0})},async glob(Q){let Z=Q.patterns??(Q.pattern?[Q.pattern]:U$),B=Q.ignore??_$,X=Q.cwd??W,Y=Q.absolute??!0;return await p6(Z,{cwd:X,ignore:B,absolute:Y})},resolve(...Q){let[Z,...B]=Q;if(!Z)return W;return cj(W,Z,...B)},dirname(Q){return c6(Q)},basename(Q){return n6(Q)},join(...Q){return r6(...Q)},relative(Q,Z){return o6(Q,Z)}};function j(Q){return l6(Q)?Q:cj(W,Q)}}import{existsSync as m,readFileSync as q$}from"fs";import{tmpdir as i6}from"os";import{dirname as FW,isAbsolute as a6,join as v,relative as t6,resolve as D$}from"path";var lj={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},rj=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function s6($,W){let j=t6(W,$);return j===""||!j.startsWith("..")&&!a6(j)}function xW($){let W=D$($),j=D$(i6());return s6(W,j)?j:void 0}function k($=process.cwd()){let W=D$($),j=xW($);while(!0){if(m(v(W,"package.json")))return W;let Q=FW(W);if(Q===W||W===j)break;W=Q}return $}function R($=process.cwd()){let W=D$($),j=null,Q=xW($);while(!0){for(let X of rj)if(m(v(W,X)))return W;let Z=v(W,"package.json");if(m(Z)){j=W;try{if(JSON.parse(q$(Z,"utf-8")).workspaces)return W}catch{}}for(let X of Object.keys(lj))if(m(v(W,X)))return W;let B=FW(W);if(B===W||W===Q)break;W=B}return j??$}function F$($=process.cwd()){let W=["bun","pnpm","yarn","npm"];for(let Q of W){let Z=Object.entries(lj).filter(([,B])=>B===Q);for(let[B]of Z)if(m(v($,B)))return Q}let j=v($,"package.json");if(m(j))try{let Q=JSON.parse(q$(j,"utf-8"));if(Q.packageManager){let Z=Q.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(Z)return Z[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function c$($=process.cwd()){for(let j of rj)if(m(v($,j)))return!0;let W=v($,"package.json");if(m(W))try{if(JSON.parse(q$(W,"utf-8")).workspaces)return!0}catch{}return!1}function e6($){let W=v($,"pnpm-workspace.yaml");if(m(W))try{let Z=q$(W,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(Z?.[1])return Z[1].split(`
5
- `).map((X)=>X.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let j=v($,"package.json");if(m(j))try{let Q=JSON.parse(q$(j,"utf-8"));if(Array.isArray(Q.workspaces))return Q.workspaces;if(Q.workspaces?.packages&&Array.isArray(Q.workspaces.packages))return Q.workspaces.packages}catch{}return}function L$($){let W=v($,"package.json");if(m(W))try{return JSON.parse(q$(W,"utf-8")).name}catch{}return}function oj($){let W=v($,".gitmodules");if(!m(W))return[];try{let j=q$(W,"utf-8"),Q=[],Z=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,B;while((B=Z.exec(j))!==null){let[,X,Y,q]=B;if(X&&Y&&q){let A=v($,Y),H=m(v(A,"package.json"))&&$7(A);Q.push({name:X,path:Y,url:q,absolutePath:A,hasWorkspaces:H})}}return Q}catch{return[]}}function $7($){let W=v($,"package.json");if(m(W))try{let j=JSON.parse(q$(W,"utf-8"));return Boolean(j.workspaces)}catch{}return m(v($,"pnpm-workspace.yaml"))}function pj($){let W=D$($),j=xW($);while(!0){if(m(v(W,".gitmodules")))return W;let Q=FW(W);if(Q===W||W===j)break;W=Q}return}function W7($){let W=pj($);if(!W)return;let j=oj(W);if(j.length===0)return;let Q=D$($),Z=j.find((B)=>Q.startsWith(B.absolutePath));return{root:W,submodules:j,activeSubmodule:Z}}function j7($,W){let j=pj($);if(j){if(oj(j).length>0)return"meta-repo"}if(W)return"monorepo";return"classic"}function ij($=process.cwd()){let W=k($),j=R($),Q=F$(j),Z=c$(j),B=Z?e6(j):void 0,X=L$(W),Y=j7($,Z),q=Y==="meta-repo"?W7($):void 0;return{packageManager:Q,workspaceRoot:j,packageRoot:W,isMonorepo:Z,packages:B,packageName:X,repositoryType:Y,metaRepo:q}}function Mq($,W){switch($){case"bun":return`bun run ${W}`;case"pnpm":return`pnpm run ${W}`;case"yarn":return`yarn ${W}`;case"npm":return`npm run ${W}`}}function Nq($,W){switch($){case"bun":return`bunx ${W}`;case"pnpm":return`pnpm exec ${W}`;case"yarn":return`yarn ${W}`;case"npm":return`npx ${W}`}}function aj($,W=!1){let j=W?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${j}`.trim();case"pnpm":return`pnpm add ${j}`.trim();case"yarn":return`yarn add ${j}`.trim();case"npm":return`npm install ${j}`.trim()}}import{anthropic as tj}from"@ai-sdk/anthropic";import{generateText as sj}from"ai";class L0{name="claude-code";apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set. Claude Code agent requires API access."]};try{let W=tj("claude-3-7-sonnet-20250219"),j=this.buildSystemPrompt($),Q=this.buildUserPrompt($),Z=await sj({model:W,prompt:Q,system:j,temperature:0.2});return{success:!0,code:this.extractCode(Z.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:Z.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let W=tj("claude-3-7-sonnet-20250219"),j=`
2
+ var UA=Object.defineProperty;var LA=($)=>$;function OA($,W){this[$]=LA.bind(null,W)}var h=($,W)=>{for(var j in W)UA($,j,{get:W[j],enumerable:!0,configurable:!0,set:OA.bind(W,j)})};var B5=($,W)=>()=>($&&(W=$($=0)),W);var O$=import.meta.require;import{ContractsrcSchema as nZ,DEFAULT_CONTRACTSRC as AW}from"@contractspec/lib.contracts-spec/workspace-config";async function m($,W){let j=$.join(W??".",".contractsrc.json");if(!await $.exists(j))return AW;try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=nZ.safeParse(Z);return{...AW,...X.data,conventions:{...AW.conventions,...X.data?.conventions||{}}}}catch{return AW}}function J8($){switch($){case"claude":return process.env.ANTHROPIC_API_KEY;case"openai":return process.env.OPENAI_API_KEY;case"custom":return process.env.CONTRACTSPEC_LLM_API_KEY;case"ollama":return;default:return}}var i=()=>{};var D4={};h(D4,{AIGenerator:()=>CW});import{createProvider as U2}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as L2,buildEventSpecPrompt as O2,buildFormPrompt as S2,buildHandlerPrompt as I2,buildOperationSpecPrompt as M2,buildPresentationSpecPrompt as E2,buildTestPrompt as N2,getCodeGenSystemPrompt as O0,getSystemPrompt as Oj}from"@contractspec/module.workspace";import{generateObject as Sj,generateText as RW,streamText as R2}from"ai";import*as N from"zod";class CW{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,W=this.config.customApiKey||J8(this.config.aiProvider),j={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:W,baseUrl:this.config.customEndpoint||void 0};return U2(j).getModel()}async generateOperationSpec($,W){let j=this.getModel(),A=N.object({name:N.string().describe('Dot notation name like "domain.operation"'),version:N.number().int().positive().default(1),description:N.string().describe("Clear, concise summary"),goal:N.string().describe("Business purpose"),context:N.string().describe("Background and constraints"),stability:N.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:N.array(N.string()).describe("Team/person owners with @ prefix"),tags:N.array(N.string()).describe("Categorization tags"),auth:N.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:N.string().describe("Description of input structure"),outputShape:N.string().describe("Description of output structure"),flags:N.array(N.string()).describe("Feature flags").default([]),possibleEvents:N.array(N.string()).describe("Events this may emit").default([]),analytics:N.array(N.string()).describe("Analytics events to track").default([])}),Q=M2($,W);return(await Sj({model:j,schema:A,prompt:Q,system:Oj()})).object}async generateEventSpec($){let W=this.getModel(),j=N.object({name:N.string().describe('Dot notation name like "domain.event_name"'),version:N.number().int().positive().default(1),description:N.string().describe("When this event is emitted"),stability:N.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:N.array(N.string()).default([]),tags:N.array(N.string()).default([]),payloadShape:N.string().describe("Description of event payload"),piiFields:N.array(N.string()).describe("PII field paths").default([])}),A=O2($);return(await Sj({model:W,schema:j,prompt:A,system:Oj()})).object}async generatePresentationSpec($,W){let j=this.getModel(),A=N.object({name:N.string(),version:N.number().int().positive().default(1),description:N.string(),stability:N.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:N.array(N.string()).default([]),tags:N.array(N.string()).default([]),componentKey:N.string().optional(),propsShape:N.string().optional(),content:N.string().optional(),mimeType:N.string().optional(),dataShape:N.string().optional()}),Q=E2($,W);return(await Sj({model:j,schema:A,prompt:Q,system:Oj()})).object}async generateHandler($){let W=this.getModel();return(await RW({model:W,prompt:I2($),system:O0()})).text}async generateComponent($){let W=this.getModel();return(await RW({model:W,prompt:L2($),system:O0()})).text}async generateForm($){let W=this.getModel();return(await RW({model:W,prompt:S2($),system:O0()})).text}async generateTests($,W,j){let A=this.getModel();return(await RW({model:A,prompt:N2($,W,j),system:O0()})).text}async streamCodeGeneration($,W){let j=this.getModel(),A=await R2({model:j,prompt:$,system:O0()}),Q="";for await(let Z of A.textStream)Q+=Z,W(Z);return Q}}var DW=B5(()=>{i()});import*as QR from"@contractspec/module.workspace";import{anthropic as SA}from"@ai-sdk/anthropic";import{openai as q5}from"@ai-sdk/openai";import{DEFAULT_MODELS as H5}from"@contractspec/lib.ai-providers/models";import{generateObject as IA,generateText as MA,streamText as EA}from"ai";import{ollama as NA}from"ollama-ai-provider";function V5($){return{async validateProvider(W){try{let{aiProvider:j}=W;if(j==="ollama")return{success:!0};if(j==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(j==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}},async generateText(W){let j=W1($);return{text:(await MA({model:j,prompt:W.prompt,system:W.systemPrompt})).text}},async generateStructured(W){let A={model:W1($),schema:W.schema,prompt:W.prompt,system:W.systemPrompt};return{object:(await IA(A)).object}},async streamText(W,j){let A=W1($),Q=await EA({model:A,prompt:W.prompt,system:W.systemPrompt}),Z="";for await(let X of Q.textStream)Z+=X,j(X);return Z}}}function W1($){let{aiProvider:W,aiModel:j,customEndpoint:A}=$;switch(W){case"claude":{let Q=j??H5.anthropic;return SA(Q)}case"openai":{let Q=j??H5.openai;return q5(Q)}case"ollama":return NA(j??"codellama");case"custom":{if(!A)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return q5(j??"default")}default:throw Error(`Unknown AI provider: ${W}`)}}import{DEFAULT_CONTRACTSRC as dA}from"@contractspec/lib.contracts-spec/workspace-config";import{access as RA,stat as CA,mkdir as G5,readFile as DA,rm as TA,writeFile as FA}from"fs/promises";import{basename as xA,dirname as J5,isAbsolute as yA,join as vA,relative as mA,resolve as b5}from"path";import{glob as PA}from"glob";var Y$=["**/*.command.ts","**/*.query.ts","**/*.operation.ts","**/*.operations.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts","**/*.capability.ts","**/*.workflow.ts","**/*.data-view.ts","**/*.form.ts","**/*.migration.ts","**/*.telemetry.ts","**/*.experiment.ts","**/*.app-config.ts","**/*.integration.ts","**/*.knowledge.ts","**/*.policy.ts","**/*.test-spec.ts","**/contracts/*.ts","**/contracts/index.ts","**/commands/*.ts","**/commands/index.ts","**/queries/*.ts","**/queries/index.ts","**/operations/*.ts","**/operations/index.ts","**/operations.ts","**/events.ts","**/presentations.ts","**/events/index.ts","**/presentations/index.ts","**/tests/*.ts","**/tests/*.test-spec.ts"],S$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function w5($){let W=$??process.cwd();return{async exists(A){try{return await RA(j(A)),!0}catch{return!1}},async readFile(A){return DA(j(A),"utf-8")},async writeFile(A,Q){let Z=j(A),X=J5(Z);await G5(X,{recursive:!0}),await FA(Z,Q,"utf-8")},async remove(A){await TA(j(A),{recursive:!0,force:!0})},async stat(A){let Q=await CA(j(A));return{size:Q.size,isFile:Q.isFile(),isDirectory:Q.isDirectory(),mtime:Q.mtime}},async mkdir(A){await G5(j(A),{recursive:!0})},async glob(A){let Q=A.patterns??(A.pattern?[A.pattern]:Y$),Z=A.ignore??S$,X=A.cwd??W,Y=A.absolute??!0;return(await PA(Q,{cwd:X,ignore:Z,absolute:Y})).sort((q,H)=>q.localeCompare(H))},resolve(...A){let[Q,...Z]=A;if(!Q)return W;return b5(W,Q,...Z)},dirname(A){return J5(A)},basename(A){return xA(A)},join(...A){return vA(...A)},relative(A,Q){return mA(A,Q)}};function j(A){return yA(A)?A:b5(W,A)}}import{execFileSync as s$}from"child_process";import{access as kA}from"fs/promises";import{resolve as K5}from"path";function _5($){let W=$??process.cwd();return{async currentBranch(){try{let j=s$("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();return j.length>0?j:void 0}catch{return}},async showFile(j,A){try{return s$("git",["show",`${j}:${A}`],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}catch(Q){throw Error(`Could not load ${A} at ref ${j}: ${Q instanceof Error?Q.message:String(Q)}`)}},async clean(j){let A=[];if(j?.force)A.push("-f");if(j?.directories)A.push("-d");if(j?.ignored)A.push("-x");if(j?.dryRun)A.push("--dry-run");s$("git",["clean",...A],{cwd:W,stdio:"inherit"})},async isGitRepo(j){let A=j?K5(W,j):W;try{return await kA(K5(A,".git")),!0}catch{return!1}},async log(j){let A=j??"HEAD~10",Q="--format=%H|||%s|||%an|||%aI";try{let Z=s$("git",["log",`${A}..HEAD`,"--format=%H|||%s|||%an|||%aI"],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}),X=[];for(let Y of Z.trim().split(`
3
+ `)){if(!Y)continue;let[B,q,H,V]=Y.split("|||");if(B&&q)X.push({hash:B,message:q,author:H,date:V})}return X}catch{return[]}},async diffFiles(j,A){try{let Q=A&&A.length>0?["--",...A]:[];return s$("git",["diff","--name-only",`${j}...HEAD`,...Q],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim().split(`
4
+ `).filter(Boolean)}catch{return[]}}}}function z5(){return{debug($,W){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,W??"")},info($,W){console.info(`[INFO] ${$}`,W??"")},warn($,W){console.warn(`[WARN] ${$}`,W??"")},error($,W){console.error(`[ERROR] ${$}`,W??"")},createProgress(){return hA()}}}function U5(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:gA}}function hA(){return{start($){console.warn(`\u23F3 ${$}`)},update($){let W=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${W}`)},succeed($){console.warn(`\u2705 ${$??"Done"}`)},fail($){console.error(`\u274C ${$??"Failed"}`)},warn($){console.warn(`\u26A0\uFE0F ${$??"Warning"}`)},stop(){}}}function gA(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import fA from"chokidar";var uA=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function L5($){let W=$??process.cwd();return{watch(j){let A=[],Q,Z=fA.watch(j.pattern,{cwd:W,ignored:j.ignore??uA,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),X=(Y)=>{if(j.debounceMs&&j.debounceMs>0)clearTimeout(Q),Q=setTimeout(()=>{A.forEach((B)=>B(Y))},j.debounceMs);else A.forEach((B)=>B(Y))};return Z.on("add",(Y)=>{X({type:"add",path:Y})}),Z.on("change",(Y)=>{X({type:"change",path:Y})}),Z.on("unlink",(Y)=>{X({type:"unlink",path:Y})}),{on(Y){A.push(Y)},async close(){clearTimeout(Q),await Z.close()}}}}}function mH($={}){let{cwd:W,config:j,silent:A}=$,Q=j??dA;return{fs:w5(W),git:_5(W),watcher:L5(W),ai:V5(Q),logger:A?U5():z5()}}import{stat as nA,mkdir as cA}from"fs/promises";import{basename as rA,dirname as lA,isAbsolute as oA,join as iA,relative as pA,resolve as O5}from"path";import{glob as tA}from"glob";function uH($){let W=$??process.cwd();return{async exists(A){let Q=Bun.file(j(A));try{return await Q.exists(),!0}catch{return!1}},async readFile(A){return Bun.file(j(A)).text()},async writeFile(A,Q){let Z=j(A);await Bun.write(Z,Q)},async remove(A){await Bun.file(j(A)).delete()},async stat(A){let Q=await nA(j(A));return{size:Q.size,isFile:Q.isFile(),isDirectory:Q.isDirectory(),mtime:Q.mtime}},async mkdir(A){await cA(j(A),{recursive:!0})},async glob(A){let Q=A.patterns??(A.pattern?[A.pattern]:Y$),Z=A.ignore??S$,X=A.cwd??W,Y=A.absolute??!0;return await tA(Q,{cwd:X,ignore:Z,absolute:Y})},resolve(...A){let[Q,...Z]=A;if(!Q)return W;return O5(W,Q,...Z)},dirname(A){return lA(A)},basename(A){return rA(A)},join(...A){return iA(...A)},relative(A,Q){return pA(A,Q)}};function j(A){return oA(A)?A:O5(W,A)}}import{existsSync as g,readFileSync as G$}from"fs";import{tmpdir as aA}from"os";import{dirname as j1,isAbsolute as sA,join as k,relative as eA,resolve as P$}from"path";var S5={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},I5=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function $Q($,W){let j=eA(W,$);return j===""||!j.startsWith("..")&&!sA(j)}function A1($){let W=P$($),j=P$(aA());return $Q(W,j)?j:void 0}function f($=process.cwd()){let W=P$($),j=A1($);while(!0){if(g(k(W,"package.json")))return W;let A=j1(W);if(A===W||W===j)break;W=A}return $}function D($=process.cwd()){let W=P$($),j=null,A=A1($);while(!0){for(let X of I5)if(g(k(W,X)))return W;let Q=k(W,"package.json");if(g(Q)){j=W;try{if(JSON.parse(G$(Q,"utf-8")).workspaces)return W}catch{}}for(let X of Object.keys(S5))if(g(k(W,X)))return W;let Z=j1(W);if(Z===W||W===A)break;W=Z}return j??$}function k$($=process.cwd()){let W=["bun","pnpm","yarn","npm"];for(let A of W){let Q=Object.entries(S5).filter(([,Z])=>Z===A);for(let[Z]of Q)if(g(k($,Z)))return A}let j=k($,"package.json");if(g(j))try{let A=JSON.parse(G$(j,"utf-8"));if(A.packageManager){let Q=A.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(Q)return Q[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function e$($=process.cwd()){for(let j of I5)if(g(k($,j)))return!0;let W=k($,"package.json");if(g(W))try{if(JSON.parse(G$(W,"utf-8")).workspaces)return!0}catch{}return!1}function WQ($){let W=k($,"pnpm-workspace.yaml");if(g(W))try{let Q=G$(W,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(Q?.[1])return Q[1].split(`
5
+ `).map((X)=>X.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let j=k($,"package.json");if(g(j))try{let A=JSON.parse(G$(j,"utf-8"));if(Array.isArray(A.workspaces))return A.workspaces;if(A.workspaces?.packages&&Array.isArray(A.workspaces.packages))return A.workspaces.packages}catch{}return}function I$($){let W=k($,"package.json");if(g(W))try{return JSON.parse(G$(W,"utf-8")).name}catch{}return}function M5($){let W=k($,".gitmodules");if(!g(W))return[];try{let j=G$(W,"utf-8"),A=[],Q=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,Z;while((Z=Q.exec(j))!==null){let[,X,Y,B]=Z;if(X&&Y&&B){let q=k($,Y),H=g(k(q,"package.json"))&&jQ(q);A.push({name:X,path:Y,url:B,absolutePath:q,hasWorkspaces:H})}}return A}catch{return[]}}function jQ($){let W=k($,"package.json");if(g(W))try{let j=JSON.parse(G$(W,"utf-8"));return Boolean(j.workspaces)}catch{}return g(k($,"pnpm-workspace.yaml"))}function E5($){let W=P$($),j=A1($);while(!0){if(g(k(W,".gitmodules")))return W;let A=j1(W);if(A===W||W===j)break;W=A}return}function AQ($){let W=E5($);if(!W)return;let j=M5(W);if(j.length===0)return;let A=P$($),Q=j.find((Z)=>A.startsWith(Z.absolutePath));return{root:W,submodules:j,activeSubmodule:Q}}function QQ($,W){let j=E5($);if(j){if(M5(j).length>0)return"meta-repo"}if(W)return"monorepo";return"classic"}function N5($=process.cwd()){let W=f($),j=D($),A=k$(j),Q=e$(j),Z=Q?WQ(j):void 0,X=I$(W),Y=QQ($,Q),B=Y==="meta-repo"?AQ($):void 0;return{packageManager:A,workspaceRoot:j,packageRoot:W,isMonorepo:Q,packages:Z,packageName:X,repositoryType:Y,metaRepo:B}}function lH($,W){switch($){case"bun":return`bun run ${W}`;case"pnpm":return`pnpm run ${W}`;case"yarn":return`yarn ${W}`;case"npm":return`npm run ${W}`}}function oH($,W){switch($){case"bun":return`bunx ${W}`;case"pnpm":return`pnpm exec ${W}`;case"yarn":return`yarn ${W}`;case"npm":return`npx ${W}`}}function R5($,W=!1){let j=W?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${j}`.trim();case"pnpm":return`pnpm add ${j}`.trim();case"yarn":return`yarn add ${j}`.trim();case"npm":return`npm install ${j}`.trim()}}import{anthropic as C5}from"@ai-sdk/anthropic";import{generateText as D5}from"ai";class m0{name="claude-code";apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set. Claude Code agent requires API access."]};try{let W=C5("claude-3-7-sonnet-20250219"),j=this.buildSystemPrompt($),A=this.buildUserPrompt($),Q=await D5({model:W,prompt:A,system:j,temperature:0.2});return{success:!0,code:this.extractCode(Q.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:Q.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let W=C5("claude-3-7-sonnet-20250219"),j=`
6
6
  You are an expert code reviewer. Carefully analyze this implementation against its specification.
7
7
 
8
8
  SPECIFICATION:
@@ -31,7 +31,7 @@ Provide a structured validation report:
31
31
  - Are there any missing edge cases?
32
32
 
33
33
  Be thorough and precise. Use a critical but constructive tone.
34
- `,Q=await sj({model:W,prompt:j,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),Z=this.detectIssues(Q.text);return{success:!Z,code:Q.text,errors:Z?this.extractErrors(Q.text):[],warnings:this.extractWarnings(Q.text),suggestions:this.extractSuggestions(Q.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
34
+ `,A=await D5({model:W,prompt:j,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),Q=this.detectIssues(A.text);return{success:!Q,code:A.text,errors:Q?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),suggestions:this.extractSuggestions(A.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
35
35
 
36
36
  Your code is:
37
37
  - Type-safe with comprehensive TypeScript types
@@ -74,10 +74,10 @@ Spec:
74
74
  ${$.specCode}
75
75
 
76
76
  Code:
77
- ${$.existingCode}`};return W[$.type]||W.generate}extractCode($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W&&W[1])return W[1];return $}detectIssues($){let W=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],j=$.toLowerCase();return W.some((Q)=>j.includes(Q))}extractErrors($){let W=[],j=$.split(`
78
- `);for(let Q of j){let Z=Q.toLowerCase();if(Z.includes("error")||Z.includes("bug")||Z.includes("incorrect")||Z.includes("missing"))W.push(Q.trim())}return W.length>0?W:["Code review identified issues"]}extractWarnings($){let W=[],j=$.split(`
79
- `);for(let Q of j){let Z=Q.toLowerCase();if(Z.includes("warning")||Z.includes("should")||Z.includes("consider"))W.push(Q.trim())}return W}extractSuggestions($){let W=[],j=$.split(`
80
- `);for(let Q of j){let Z=Q.toLowerCase();if(Z.includes("suggest")||Z.includes("recommend")||Z.includes("could")||Z.includes("improvement"))W.push(Q.trim())}return W}}import{spawn as Q7}from"child_process";import{existsSync as ej}from"fs";import{mkdir as $5,readFile as Z7,rm as B7,writeFile as W$}from"fs/promises";import{homedir as TW,tmpdir as W5}from"os";import{join as g}from"path";class I0{name="cursor";cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||"3000",this.detectEnvironment()}canHandle($){return this.isCursorAvailable()}async generate($){try{let W=g(W5(),`cursor-agent-${Date.now()}`);await $5(W,{recursive:!0});let j=await this.executeWithBestMethod($,W);return await this.cleanupWorkDir(W),j}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){try{let W=g(W5(),`cursor-validate-${Date.now()}`);await $5(W,{recursive:!0}),await this.setupValidationWorkspace($,W);let j=await this.executeWithBestMethod({...$,type:"validate"},W);return await this.cleanupWorkDir(W),j}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",g(TW(),".cursor","cursor"),g(TW(),"AppData","Local","Programs","cursor","Cursor.exe"),g(TW(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let W of $)if(W.includes("cursor")||W.includes("Cursor")||W.includes("windsurf")||W.includes("Windsurf"))try{if(ej(W)){this.cursorPath=W;break}}catch{continue}}async executeWithBestMethod($,W){let j=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,W)},{name:"file-based",fn:()=>this.useFileBasedApproach($,W)}];for(let Q of j)try{let Z=await Q.fn();if(Z.success)return Z}catch(Z){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,W){if(!this.cursorPath)throw Error("Cursor executable not found");let j=g(W,"spec.ts"),Q=g(W,"output.ts"),Z=g(W,"INSTRUCTIONS.md");if(await W$(j,$.specCode),await W$(Z,this.buildDetailedPrompt($)),$.existingCode)await W$(g(W,"existing.ts"),$.existingCode);return new Promise((B,X)=>{let Y=["--wait","--new-window",W],q=Q7(this.cursorPath,Y,{cwd:W,stdio:"pipe",detached:!1}),A="",H="";q.stdout?.on("data",(V)=>{A+=V.toString()}),q.stderr?.on("data",(V)=>{H+=V.toString()}),q.on("error",(V)=>{X(V)}),q.on("close",async(V)=>{if(ej(Q))try{let G=await Z7(Q,"utf-8");B({success:!0,code:G,metadata:{agentMode:"cursor",method:"cli",exitCode:V}})}catch(G){X(Error("Failed to read generated output"))}else X(Error(`Cursor CLI exited with code ${V}. No output generated.`))}),setTimeout(()=>{q.kill(),X(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,W){let j=g(W,"SPECIFICATION.ts"),Q=g(W,"INSTRUCTIONS.md"),Z=g(W,"template.ts");return await W$(j,$.specCode),await W$(Q,this.buildDetailedPrompt($)),await W$(Z,this.generateTemplate($)),await W$(g(W,"README.md"),`# Cursor Agent Workspace
77
+ ${$.existingCode}`};return W[$.type]||W.generate}extractCode($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W&&W[1])return W[1];return $}detectIssues($){let W=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],j=$.toLowerCase();return W.some((A)=>j.includes(A))}extractErrors($){let W=[],j=$.split(`
78
+ `);for(let A of j){let Q=A.toLowerCase();if(Q.includes("error")||Q.includes("bug")||Q.includes("incorrect")||Q.includes("missing"))W.push(A.trim())}return W.length>0?W:["Code review identified issues"]}extractWarnings($){let W=[],j=$.split(`
79
+ `);for(let A of j){let Q=A.toLowerCase();if(Q.includes("warning")||Q.includes("should")||Q.includes("consider"))W.push(A.trim())}return W}extractSuggestions($){let W=[],j=$.split(`
80
+ `);for(let A of j){let Q=A.toLowerCase();if(Q.includes("suggest")||Q.includes("recommend")||Q.includes("could")||Q.includes("improvement"))W.push(A.trim())}return W}}import{spawn as ZQ}from"child_process";import{existsSync as T5}from"fs";import{mkdir as F5,readFile as XQ,rm as YQ,writeFile as Z$}from"fs/promises";import{homedir as Q1,tmpdir as x5}from"os";import{join as u}from"path";class P0{name="cursor";cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||"3000",this.detectEnvironment()}canHandle($){return this.isCursorAvailable()}async generate($){try{let W=u(x5(),`cursor-agent-${Date.now()}`);await F5(W,{recursive:!0});let j=await this.executeWithBestMethod($,W);return await this.cleanupWorkDir(W),j}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){try{let W=u(x5(),`cursor-validate-${Date.now()}`);await F5(W,{recursive:!0}),await this.setupValidationWorkspace($,W);let j=await this.executeWithBestMethod({...$,type:"validate"},W);return await this.cleanupWorkDir(W),j}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",u(Q1(),".cursor","cursor"),u(Q1(),"AppData","Local","Programs","cursor","Cursor.exe"),u(Q1(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let W of $)if(W.includes("cursor")||W.includes("Cursor")||W.includes("windsurf")||W.includes("Windsurf"))try{if(T5(W)){this.cursorPath=W;break}}catch{continue}}async executeWithBestMethod($,W){let j=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,W)},{name:"file-based",fn:()=>this.useFileBasedApproach($,W)}];for(let A of j)try{let Q=await A.fn();if(Q.success)return Q}catch(Q){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,W){if(!this.cursorPath)throw Error("Cursor executable not found");let j=u(W,"spec.ts"),A=u(W,"output.ts"),Q=u(W,"INSTRUCTIONS.md");if(await Z$(j,$.specCode),await Z$(Q,this.buildDetailedPrompt($)),$.existingCode)await Z$(u(W,"existing.ts"),$.existingCode);return new Promise((Z,X)=>{let Y=["--wait","--new-window",W],B=ZQ(this.cursorPath,Y,{cwd:W,stdio:"pipe",detached:!1}),q="",H="";B.stdout?.on("data",(V)=>{q+=V.toString()}),B.stderr?.on("data",(V)=>{H+=V.toString()}),B.on("error",(V)=>{X(V)}),B.on("close",async(V)=>{if(T5(A))try{let G=await XQ(A,"utf-8");Z({success:!0,code:G,metadata:{agentMode:"cursor",method:"cli",exitCode:V}})}catch(G){X(Error("Failed to read generated output"))}else X(Error(`Cursor CLI exited with code ${V}. No output generated.`))}),setTimeout(()=>{B.kill(),X(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,W){let j=u(W,"SPECIFICATION.ts"),A=u(W,"INSTRUCTIONS.md"),Q=u(W,"template.ts");return await Z$(j,$.specCode),await Z$(A,this.buildDetailedPrompt($)),await Z$(Q,this.generateTemplate($)),await Z$(u(W,"README.md"),`# Cursor Agent Workspace
81
81
 
82
82
  This workspace was prepared for Cursor AI code generation.
83
83
 
@@ -93,7 +93,7 @@ This workspace was prepared for Cursor AI code generation.
93
93
  4. Save the result as output.ts
94
94
 
95
95
  Workspace path: ${W}
96
- `),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${W}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:W}}}async setupValidationWorkspace($,W){await W$(g(W,"specification.ts"),$.specCode),await W$(g(W,"implementation.ts"),$.existingCode||"// No implementation"),await W$(g(W,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,W){let j=[{path:"spec.ts",content:$.specCode}];if($.existingCode)j.push({path:"existing.ts",content:$.existingCode});return j}buildDetailedPrompt($){let W=`# AI Code Generation Task - Cursor Agent
96
+ `),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${W}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:W}}}async setupValidationWorkspace($,W){await Z$(u(W,"specification.ts"),$.specCode),await Z$(u(W,"implementation.ts"),$.existingCode||"// No implementation"),await Z$(u(W,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,W){let j=[{path:"spec.ts",content:$.specCode}];if($.existingCode)j.push({path:"existing.ts",content:$.existingCode});return j}buildDetailedPrompt($){let W=`# AI Code Generation Task - Cursor Agent
97
97
 
98
98
  **Task Type:** ${$.type}
99
99
  **Generated:** ${new Date().toISOString()}
@@ -104,7 +104,7 @@ Workspace path: ${W}
104
104
  ${$.specCode}
105
105
  \`\`\`
106
106
 
107
- `,Q={generate:`## Task: Generate Implementation
107
+ `,A={generate:`## Task: Generate Implementation
108
108
 
109
109
  ### Requirements:
110
110
  1. **Type Safety**: Use strict TypeScript with comprehensive types
@@ -197,7 +197,7 @@ ${$.existingCode||""}
197
197
  - Enhance error messages
198
198
 
199
199
  ### Output Format:
200
- Refactored code that maintains functionality while improving quality.`};return W+j+(Q[$.type]||Q.generate)}buildValidationPrompt($){return`# Implementation Validation Report
200
+ Refactored code that maintains functionality while improving quality.`};return W+j+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
201
201
 
202
202
  ## Specification
203
203
  \`\`\`typescript
@@ -255,7 +255,7 @@ export function implementation() {
255
255
  // Implementation goes here
256
256
  throw new Error('Not implemented');
257
257
  }
258
- `}async cleanupWorkDir($){try{await B7($,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}}import{openai as j5}from"@ai-sdk/openai";import{generateText as Q5}from"ai";class O0{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let j=this.isComplexTask($)?"o1":"gpt-5.4",Q=j5(j),Z=this.buildSystemPrompt($),B=this.buildUserPrompt($),X=await Q5({model:Q,prompt:B,system:Z,temperature:0.2});return{success:!0,code:this.extractCode(X.text),metadata:{model:j,agentMode:"openai-codex",usage:X.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let W=j5("gpt-5.4"),j=`
258
+ `}async cleanupWorkDir($){try{await YQ($,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}}import{openai as y5}from"@ai-sdk/openai";import{generateText as v5}from"ai";class k0{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let j=this.isComplexTask($)?"o1":"gpt-5.4",A=y5(j),Q=this.buildSystemPrompt($),Z=this.buildUserPrompt($),X=await v5({model:A,prompt:Z,system:Q,temperature:0.2});return{success:!0,code:this.extractCode(X.text),metadata:{model:j,agentMode:"openai-codex",usage:X.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let W=y5("gpt-5.4"),j=`
259
259
  Review this code implementation against its specification.
260
260
 
261
261
  SPECIFICATION:
@@ -275,7 +275,7 @@ Provide a detailed validation report including:
275
275
  4. Recommendations for improvement
276
276
 
277
277
  Format as a structured report.
278
- `,Q=await Q5({model:W,prompt:j,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),Z=this.detectIssues(Q.text);return{success:!Z,code:Q.text,errors:Z?this.extractErrors(Q.text):[],warnings:this.extractWarnings(Q.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}isComplexTask($){let W=["algorithm","optimization","complex logic","state management","concurrent","distributed"],j=($.specCode+($.existingCode||"")).toLowerCase();return W.some((Q)=>j.includes(Q))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
278
+ `,A=await v5({model:W,prompt:j,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),Q=this.detectIssues(A.text);return{success:!Q,code:A.text,errors:Q?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}isComplexTask($){let W=["algorithm","optimization","complex logic","state management","concurrent","distributed"],j=($.specCode+($.existingCode||"")).toLowerCase();return W.some((A)=>j.includes(A))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
279
279
 
280
280
  Generate production-quality code that is:
281
281
  - Type-safe and well-typed
@@ -312,9 +312,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
312
312
  ${$.existingCode}
313
313
 
314
314
  Spec:
315
- ${$.specCode}`;default:return $.specCode}}extractCode($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return W&&W[1]?W[1]:$}detectIssues($){let W=["issue","problem","bug","error","incorrect","missing","fails","violation"],j=$.toLowerCase();return W.some((Q)=>j.includes(Q))}extractErrors($){let W=[],j=$.split(`
316
- `);for(let Q of j)if(Q.toLowerCase().includes("error")||Q.toLowerCase().includes("bug")||Q.toLowerCase().includes("fails"))W.push(Q.trim());return W}extractWarnings($){let W=[],j=$.split(`
317
- `);for(let Q of j)if(Q.toLowerCase().includes("warning")||Q.toLowerCase().includes("should")||Q.toLowerCase().includes("consider"))W.push(Q.trim());return W}}import I$ from"chalk";import q7 from"ora";import{generateText as Z5}from"ai";var gW={};P(gW,{getCodeGenSystemPrompt:()=>kW,buildTestPrompt:()=>mW,buildHandlerPrompt:()=>vW,buildFormPrompt:()=>PW,buildComponentPrompt:()=>yW});function vW($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
315
+ ${$.specCode}`;default:return $.specCode}}extractCode($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return W&&W[1]?W[1]:$}detectIssues($){let W=["issue","problem","bug","error","incorrect","missing","fails","violation"],j=$.toLowerCase();return W.some((A)=>j.includes(A))}extractErrors($){let W=[],j=$.split(`
316
+ `);for(let A of j)if(A.toLowerCase().includes("error")||A.toLowerCase().includes("bug")||A.toLowerCase().includes("fails"))W.push(A.trim());return W}extractWarnings($){let W=[],j=$.split(`
317
+ `);for(let A of j)if(A.toLowerCase().includes("warning")||A.toLowerCase().includes("should")||A.toLowerCase().includes("consider"))W.push(A.trim());return W}}import M$ from"chalk";import HQ from"ora";import{generateText as m5}from"ai";var H1={};h(H1,{getCodeGenSystemPrompt:()=>q1,buildTestPrompt:()=>B1,buildHandlerPrompt:()=>Z1,buildFormPrompt:()=>Y1,buildComponentPrompt:()=>X1});function Z1($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
318
318
 
319
319
  Here is the contract spec:
320
320
 
@@ -333,7 +333,7 @@ Generate a complete handler implementation that:
333
333
 
334
334
  The handler should be production-ready with proper error handling, logging points, and clear structure.
335
335
 
336
- Return only the TypeScript code for the handler function.`}function yW($){return`You are a senior React developer creating a component for a presentation specification.
336
+ Return only the TypeScript code for the handler function.`}function X1($){return`You are a senior React developer creating a component for a presentation specification.
337
337
 
338
338
  Here is the presentation spec:
339
339
 
@@ -352,7 +352,7 @@ Generate a complete React component that:
352
352
 
353
353
  The component should follow Atomic Design principles and be reusable.
354
354
 
355
- Return only the TypeScript/TSX code for the component.`}function PW($){return`You are a senior React developer creating a form component from a form specification.
355
+ Return only the TypeScript/TSX code for the component.`}function Y1($){return`You are a senior React developer creating a form component from a form specification.
356
356
 
357
357
  Here is the form spec:
358
358
 
@@ -372,7 +372,7 @@ Generate a complete form component using react-hook-form that:
372
372
 
373
373
  The form should provide excellent UX with real-time validation and helpful feedback.
374
374
 
375
- Return only the TypeScript/TSX code for the form component.`}function mW($,W,j){return`You are a senior developer writing comprehensive tests.
375
+ Return only the TypeScript/TSX code for the form component.`}function B1($,W,j){return`You are a senior developer writing comprehensive tests.
376
376
 
377
377
  Spec:
378
378
  \`\`\`typescript
@@ -399,7 +399,7 @@ ${j==="handler"?`
399
399
 
400
400
  Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
401
401
 
402
- Return only the TypeScript test code.`}function kW(){return`You are an expert TypeScript developer with deep knowledge of:
402
+ Return only the TypeScript test code.`}function q1(){return`You are an expert TypeScript developer with deep knowledge of:
403
403
  - Type-safe API design
404
404
  - React and modern hooks
405
405
  - Test-driven development
@@ -413,7 +413,7 @@ Generate production-ready code that is:
413
413
  - Defensive and error-safe
414
414
  - Easy to maintain and extend
415
415
 
416
- Always prioritize code quality, safety, and user experience.`}import{getAIProvider as X7}from"@contractspec/lib.ai-providers";function hW($){let W={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return X7(W)}class b0{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let W=hW(this.config),j=this.buildPrompt($),Q=await Z5({model:W,prompt:j,system:kW()});return{success:!0,code:Q.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:Q.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){try{let W=hW(this.config),j=`
416
+ Always prioritize code quality, safety, and user experience.`}import{getAIProvider as BQ}from"@contractspec/lib.ai-providers";function V1($){let W={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return BQ(W)}class h0{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let W=V1(this.config),j=this.buildPrompt($),A=await m5({model:W,prompt:j,system:q1()});return{success:!0,code:A.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:A.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){try{let W=V1(this.config),j=`
417
417
  Review the following implementation against its specification.
418
418
 
419
419
  Specification:
@@ -427,15 +427,15 @@ Provide a detailed validation report:
427
427
  2. Are there any missing features?
428
428
  3. Are there any bugs or issues?
429
429
  4. Suggestions for improvement
430
- `,Q=await Z5({model:W,prompt:j,system:"You are a code review expert. Provide thorough, constructive feedback."}),Z=Q.text.toLowerCase().includes("error")||Q.text.toLowerCase().includes("missing")||Q.text.toLowerCase().includes("incorrect");return{success:!Z,code:Q.text,warnings:Z?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return vW($.specCode);else if($.specCode.includes(".presentation."))return yW($.specCode);else if($.specCode.includes(".form."))return PW($.specCode);return`Generate implementation for:
431
- ${$.specCode}`;case"test":return mW($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
432
- ${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as Y7}from"@contractspec/lib.ai-agent/agent/unified-agent";class fW{name;agent;constructor($,W,j={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=Y7(j,W)}canHandle($){return!0}async generate($){try{let W=this.buildPrompt($),j=await this.agent.run(W);return{success:!0,code:j.text,metadata:{finishReason:j.finishReason,usage:j.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){return this.generate($)}buildPrompt($){let W="";if($.specCode)W+=`Specification:
430
+ `,A=await m5({model:W,prompt:j,system:"You are a code review expert. Provide thorough, constructive feedback."}),Q=A.text.toLowerCase().includes("error")||A.text.toLowerCase().includes("missing")||A.text.toLowerCase().includes("incorrect");return{success:!Q,code:A.text,warnings:Q?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return Z1($.specCode);else if($.specCode.includes(".presentation."))return X1($.specCode);else if($.specCode.includes(".form."))return Y1($.specCode);return`Generate implementation for:
431
+ ${$.specCode}`;case"test":return B1($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
432
+ ${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as qQ}from"@contractspec/lib.ai-agent/agent/unified-agent";class G1{name;agent;constructor($,W,j={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=qQ(j,W)}canHandle($){return!0}async generate($){try{let W=this.buildPrompt($),j=await this.agent.run(W);return{success:!0,code:j.text,metadata:{finishReason:j.finishReason,usage:j.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){return this.generate($)}buildPrompt($){let W="";if($.specCode)W+=`Specification:
433
433
  ${$.specCode}
434
434
 
435
435
  `;if($.existingCode)W+=`Existing Code:
436
436
  ${$.existingCode}
437
437
 
438
- `;switch($.type){case"generate":W+="Generate implementation code based on the specification above.";break;case"validate":W+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":W+="Refactor the existing code to better match the specification and improve quality.";break;case"test":W+="Generate tests for the existing code based on the specification.";break}return W}}class w0{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let W=new b0($),j=new I0,Q=new L0,Z=new O0;this.agents.set("simple",W),this.agents.set("cursor",j),this.agents.set("claude-code",Q),this.agents.set("openai-codex",Z),this.defaultAgent=W,this.agents.set("opencode-sdk",new fW("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let W=this.getAgentMode(),j=this.agents.get(W);if(!j)return console.log(I$.yellow(`\u26A0\uFE0F Agent '${W}' not found, using simple agent`)),this.defaultAgent.generate($);if(!j.canHandle($))return console.log(I$.yellow(`\u26A0\uFE0F Agent '${W}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let Q=q7(`Executing with ${W} agent...`).start();try{let Z=$.type==="validate"?await j.validate($):await j.generate($);if(Z.success)return Q.succeed(I$.green(`${W} agent completed successfully`)),Z;Q.warn(I$.yellow(`${W} agent failed, trying fallback...`));let B=this.getFallbackMode(W);if(B&&B!==W){let X=this.agents.get(B);if(X&&X.canHandle($))return $.type==="validate"?await X.validate($):await X.generate($)}return Q.info(I$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(Z){return Q.fail(I$.red("Agent execution failed")),console.log(I$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,W){return this.executeTask({type:"generate",specCode:$,targetPath:W})}async generateTests($,W){return this.executeTask({type:"test",specCode:$,existingCode:W})}async validate($,W){return this.executeTask({type:"validate",specCode:$,existingCode:W})}async refactor($,W){return this.executeTask({type:"refactor",specCode:$,existingCode:W})}async getAvailableAgents(){let $=[];for(let[W,j]of this.agents){let Q={type:"generate",specCode:"test"},Z=j.canHandle(Q);$.push({mode:W,available:Z,reason:Z?void 0:"Not configured or dependencies missing"})}return $}getAgentMode(){return this.config.agentMode||"simple"}getFallbackMode($){return{cursor:"claude-code","claude-agent-sdk":"claude-code","claude-code":"openai-codex","openai-codex":"simple",opencode:"opencode-sdk","opencode-sdk":"claude-code",simple:"simple"}[$]}}var B5={};P(B5,{specCreation:()=>uW,codeGeneration:()=>gW});var uW={};P(uW,{getSystemPrompt:()=>G7,buildPresentationSpecPrompt:()=>V7,buildOperationSpecPrompt:()=>A7,buildEventSpecPrompt:()=>H7,addExampleContext:()=>z7});function A7($,W){return`You are a senior software architect creating a contract specification for an operation.
438
+ `;switch($.type){case"generate":W+="Generate implementation code based on the specification above.";break;case"validate":W+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":W+="Refactor the existing code to better match the specification and improve quality.";break;case"test":W+="Generate tests for the existing code based on the specification.";break}return W}}class g0{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let W=new h0($),j=new P0,A=new m0,Q=new k0;this.agents.set("simple",W),this.agents.set("cursor",j),this.agents.set("claude-code",A),this.agents.set("openai-codex",Q),this.defaultAgent=W,this.agents.set("opencode-sdk",new G1("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let W=this.getAgentMode(),j=this.agents.get(W);if(!j)return console.log(M$.yellow(`\u26A0\uFE0F Agent '${W}' not found, using simple agent`)),this.defaultAgent.generate($);if(!j.canHandle($))return console.log(M$.yellow(`\u26A0\uFE0F Agent '${W}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let A=HQ(`Executing with ${W} agent...`).start();try{let Q=$.type==="validate"?await j.validate($):await j.generate($);if(Q.success)return A.succeed(M$.green(`${W} agent completed successfully`)),Q;A.warn(M$.yellow(`${W} agent failed, trying fallback...`));let Z=this.getFallbackMode(W);if(Z&&Z!==W){let X=this.agents.get(Z);if(X&&X.canHandle($))return $.type==="validate"?await X.validate($):await X.generate($)}return A.info(M$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(Q){return A.fail(M$.red("Agent execution failed")),console.log(M$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,W){return this.executeTask({type:"generate",specCode:$,targetPath:W})}async generateTests($,W){return this.executeTask({type:"test",specCode:$,existingCode:W})}async validate($,W){return this.executeTask({type:"validate",specCode:$,existingCode:W})}async refactor($,W){return this.executeTask({type:"refactor",specCode:$,existingCode:W})}async getAvailableAgents(){let $=[];for(let[W,j]of this.agents){let A={type:"generate",specCode:"test"},Q=j.canHandle(A);$.push({mode:W,available:Q,reason:Q?void 0:"Not configured or dependencies missing"})}return $}getAgentMode(){return this.config.agentMode||"simple"}getFallbackMode($){return{cursor:"claude-code","claude-agent-sdk":"claude-code","claude-code":"openai-codex","openai-codex":"simple",opencode:"opencode-sdk","opencode-sdk":"claude-code",simple:"simple"}[$]}}var P5={};h(P5,{specCreation:()=>J1,codeGeneration:()=>H1});var J1={};h(J1,{getSystemPrompt:()=>bQ,buildPresentationSpecPrompt:()=>JQ,buildOperationSpecPrompt:()=>VQ,buildEventSpecPrompt:()=>GQ,addExampleContext:()=>wQ});function VQ($,W){return`You are a senior software architect creating a contract specification for an operation.
439
439
 
440
440
  The operation is a ${W} (${W==="command"?"changes state, has side effects":"read-only, idempotent"}).
441
441
 
@@ -453,7 +453,7 @@ Create a complete contract specification following these guidelines:
453
453
  8. **Feature Flags**: Any flags that gate this operation
454
454
  9. **Side Effects**: What events might be emitted, analytics to track
455
455
 
456
- Respond with a structured spec.`}function H7($){return`You are a senior software architect creating an event specification.
456
+ Respond with a structured spec.`}function GQ($){return`You are a senior software architect creating an event specification.
457
457
 
458
458
  User description: ${$}
459
459
 
@@ -467,7 +467,7 @@ Create a complete event specification following these guidelines:
467
467
 
468
468
  Events represent things that have already happened and should use past tense.
469
469
 
470
- Respond with a structured spec.`}function V7($,W){return`You are a senior software architect creating a presentation specification.
470
+ Respond with a structured spec.`}function JQ($,W){return`You are a senior software architect creating a presentation specification.
471
471
 
472
472
  This is a ${W} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[W]}.
473
473
 
@@ -485,7 +485,7 @@ Create a complete presentation specification following these guidelines:
485
485
  - Target audience`:`- MIME type (e.g., application/json)
486
486
  - Data structure description`}
487
487
 
488
- Respond with a structured spec.`}function G7(){return`You are an expert software architect specializing in API design and contract-driven development.
488
+ Respond with a structured spec.`}function bQ(){return`You are an expert software architect specializing in API design and contract-driven development.
489
489
 
490
490
  You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
491
491
 
@@ -495,7 +495,7 @@ Your specs are:
495
495
  - Business-oriented (capturing the "why" not just "what")
496
496
  - Designed for both humans and AI agents to understand
497
497
 
498
- Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function z7($,W){if(W.length===0)return $;return`${$}
498
+ Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function wQ($,W){if(W.length===0)return $;return`${$}
499
499
 
500
500
  Here are some good examples for reference:
501
501
 
@@ -503,271 +503,103 @@ ${W.join(`
503
503
 
504
504
  `)}
505
505
 
506
- Follow this structure and quality level.`}var q5={};P(q5,{sarifToJson:()=>I7,formatAsTextLines:()=>Y5,formatAsText:()=>O7,formatAsSarif:()=>U7,formatAsJson:()=>J7});function J7($,W={}){let{pretty:j=!0,driftResult:Q}=W,Z=$.issues.map((H)=>({name:H.ruleId,status:H.severity==="error"?"fail":H.severity==="warning"?"warn":"pass",category:H.category,message:H.message,file:H.file,line:H.line,details:H.context})),B=$.categories.filter((H)=>H.passed).length,X=$.totalErrors,Y=$.totalWarnings,q=$.totalNotes,A={schemaVersion:"1.0",success:$.success,checks:Z,categories:$.categories.map((H)=>({category:H.category,label:H.label,passed:H.passed,errors:H.errors,warnings:H.warnings,notes:H.notes,durationMs:H.durationMs})),drift:{status:Q?.hasDrift?"detected":"none",files:Q?.files??[]},summary:{pass:B,fail:X,warn:Y,note:q,total:B+X+Y+q,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return j?JSON.stringify(A,null,2):JSON.stringify(A)}var K7={"spec-structure-error":{name:"Spec Structure Error",description:"Contract specification is missing required structure elements"},"spec-structure-warning":{name:"Spec Structure Warning",description:"Contract specification has recommended but missing elements"},"integrity-orphaned":{name:"Orphaned Spec",description:"Contract specification is not linked to any feature"},"integrity-unresolved-ref":{name:"Unresolved Reference",description:"Contract specification references a non-existent spec"},"integrity-missing-feature":{name:"Missing Feature",description:"Feature referenced by spec does not exist"},"integrity-broken-link":{name:"Broken Link",description:"Link between specs is broken"},"deps-circular":{name:"Circular Dependency",description:"Circular dependency detected between contracts"},"deps-missing":{name:"Missing Dependency",description:"Contract depends on a non-existent contract"},"handler-missing":{name:"Missing Handler",description:"Handler implementation file does not exist for this contract"},"handler-warning":{name:"Handler Warning",description:"Handler implementation has potential issues"},"test-missing":{name:"Missing Test",description:"Test file does not exist for this contract"},"test-warning":{name:"Test Warning",description:"Test implementation has potential issues"}};function U7($,W={}){let{toolName:j="ContractSpec",toolVersion:Q="1.0.0",toolUri:Z="https://contractspec.io",repositoryUri:B,workingDirectory:X}=W,Y=new Map,q=new Map,A=$.issues.filter((z)=>z.file);for(let z of A)if(!Y.has(z.ruleId)){let J=K7[z.ruleId]??{name:z.ruleId,description:`Rule: ${z.ruleId}`},K={id:z.ruleId,name:J.name,shortDescription:{text:J.description},defaultConfiguration:{level:X5(z.severity)}};if(J.helpUri)K.helpUri=J.helpUri;q.set(z.ruleId,Y.size),Y.set(z.ruleId,K)}let H=A.map((z)=>{let J={ruleId:z.ruleId,ruleIndex:q.get(z.ruleId)??0,level:X5(z.severity),message:{text:z.message}},K={physicalLocation:{artifactLocation:{uri:_7(z.file),uriBaseId:"%SRCROOT%"}}};if(z.line!==void 0)K.physicalLocation.region={startLine:z.line,startColumn:z.column??1,endLine:z.endLine??z.line,endColumn:z.endColumn};return J.locations=[K],J.partialFingerprints={primaryLocationLineHash:L7(z)},J}),V=[];if(B)V.push({repositoryUri:B,revisionId:$.commitSha,branch:$.branch});let G={tool:{driver:{name:j,version:Q,informationUri:Z,rules:Array.from(Y.values())}},results:H,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...X&&{workingDirectory:{uri:X}}}]};if(V.length>0)G.versionControlProvenance=V;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[G]}}function X5($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function _7($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function L7($){let W=[$.ruleId,$.file??"",$.message];return Buffer.from(W.join("|")).toString("base64").slice(0,16)}function I7($){return JSON.stringify($,null,2)}function Y5($,W={}){let j=[],{verbose:Q=!1,showTiming:Z=!0,groupByFile:B=!1}=W;if(j.push({text:"",style:"normal"}),j.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),j.push({text:"",style:"normal"}),$.commitSha||$.branch){let Y=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");j.push({text:`Git: ${Y}`,style:"muted"})}j.push({text:"",style:"normal"}),j.push({text:"Check Results:",style:"bold"});for(let Y of $.categories){let q=Y.passed?"\u2713":"\u2717",A=Y.passed?"success":"error",H=b7(Y),V=Z?` (${Y.durationMs}ms)`:"";j.push({text:` ${q} ${Y.label}: ${H}${V}`,style:A})}if($.issues.length>0)if(j.push({text:"",style:"normal"}),j.push({text:"Issues:",style:"bold"}),B){let Y=w7($.issues);for(let[q,A]of Y){j.push({text:"",style:"normal"}),j.push({text:` ${q||"(no file)"}`,style:"bold",indent:1});for(let H of A)j.push(...C0(H,Q,2))}}else{let Y=$.issues.filter((H)=>H.severity==="error"),q=$.issues.filter((H)=>H.severity==="warning"),A=$.issues.filter((H)=>H.severity==="note");if(Y.length>0){j.push({text:"",style:"normal"}),j.push({text:" Errors:",style:"error",indent:1});for(let H of Y)j.push(...C0(H,Q,2))}if(q.length>0){j.push({text:"",style:"normal"}),j.push({text:" Warnings:",style:"warning",indent:1});for(let H of q)j.push(...C0(H,Q,2))}if(A.length>0&&Q){j.push({text:"",style:"normal"}),j.push({text:" Notes:",style:"muted",indent:1});for(let H of A)j.push(...C0(H,Q,2))}}j.push({text:"",style:"normal"}),j.push({text:"\u2500".repeat(50),style:"muted"});let X=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&Q?`${$.totalNotes} note(s)`:null].filter(Boolean);if(X.length>0)j.push({text:`Found: ${X.join(", ")}`,style:$.success?"warning":"error"});if(Z)j.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(j.push({text:"",style:"normal"}),$.success)j.push({text:"\u2705 All CI checks passed!",style:"success"});else j.push({text:"\u274C CI checks failed",style:"error"});return j.push({text:"",style:"normal"}),j}function O7($,W={}){return Y5($,W).map((Q)=>" ".repeat(Q.indent??0)+Q.text).join(`
507
- `)}function b7($){let W=[];if($.errors>0)W.push(`${$.errors} error(s)`);if($.warnings>0)W.push(`${$.warnings} warning(s)`);if(W.length===0)return"passed";return W.join(", ")}function C0($,W,j){let Q=[],Z=$.severity==="error"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",B=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",X=`${Z} ${$.message}`;if($.file){let Y=$.line?`:${$.line}`:"";X+=` (${$.file}${Y})`}if(Q.push({text:X,style:B,indent:j}),W&&$.context){let Y=JSON.stringify($.context);if(Y!=="{}")Q.push({text:`Context: ${Y}`,style:"muted",indent:j+1})}return Q}function w7($){let W=new Map;for(let j of $){let Q=j.file??"";if(!W.has(Q))W.set(Q,[]);let Z=W.get(Q);if(Z)Z.push(j)}return new Map([...W.entries()].sort(([j],[Q])=>j.localeCompare(Q)))}import{OperationSpecRegistry as C7}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as S7}from"@contractspec/lib.contracts-spec/operations/report";function E7(){let $=new C7;return S7($),$}var kA=E7();class M7{buildReportData($){let W=$.existingReportData||{};if(W.contracts=$.contractsJson,W.whatChanged={summary:"Drift check completed.",detailsPath:"",...W.whatChanged},W.risk={status:"unknown",breaking:0,nonBreaking:0,...W.risk},W.validation={status:"skipped",outputPath:"",...W.validation},W.drift={status:$.driftStatus,files:$.driftFiles},!W.nextSteps)W.nextSteps=[];if($.driftStatus==="fail")W.nextSteps.push("Run the generate command locally and commit drift fixes.");return W}finalizeResults($,W){let j=$.drift?.status==="fail",Q=!1;if(j&&W==="fail")Q=!0;return{driftDetected:j,shouldFail:Q}}}function N7($){if(!$)return"\u2014";let W=new Date($),Q=new Date().getTime()-W.getTime(),Z=Math.floor(Q/86400000);if(Z<1)return"today";if(Z===1)return"yesterday";return`${Z} days ago`}class R7{collectChanges($,W,j){if($){let Q=$.endsWith("/")?$:`${$}/`;return j.filter((Z)=>Z.startsWith(Q))}if(W){let Q=new RegExp("^"+W.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return j.filter((Z)=>Q.test(Z))}return j}detectDrift($){let W=$.map((j)=>j.slice(3)).filter((j)=>j&&j.trim().length>0).filter((j)=>j!==".contractspec-ci"&&!j.startsWith(".contractspec-ci/"));return{files:W,status:W.length>0?"fail":"pass"}}deriveImpactStatus($){let W=$?.summary||{},j=W.breaking||0,Q=W.nonBreaking||0,Z=W.total;if(Z===void 0)Z=j+Q;let B=$?.breaking||!1,X="unknown";if($){if(B||j>0)X="breaking",B=!0;else if(Q>0)X="non-breaking";else if(Z===0)X="no-impact"}return{status:X,breaking:B,breakingCount:j,nonBreakingCount:Q,total:Z||0}}buildReportData($){let W=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,j=this.deriveImpactStatus($.impactJson),Q={contracts:$.contractsJson,whatChanged:{summary:W,detailsPath:".contractspec-ci/product-view.md"},risk:{status:j.status,breaking:j.breakingCount,nonBreaking:j.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(Q.validation?.status==="fail")Q.nextSteps?.push("Fix validation errors and rerun the workflow.");if(Q.risk?.status==="breaking")Q.nextSteps?.push("Review breaking changes and plan a migration.");if(Q.risk?.status==="unknown")Q.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(Q.drift?.status==="fail")Q.nextSteps?.push("Run the generate command locally and commit drift fixes.");let Z=this.finalizeResults(Q,$.failOn);if(Z.shouldFail)Q.nextSteps?.unshift(`CI failed: ${Z.failReasons.join(", ")} (fail_on=${$.failOn}).`);return Q}finalizeResults($,W){let j=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,Q=$.drift?.status==="fail",Z=$.validation?.status==="fail",B=$.risk?.status==="unknown",X=[],Y=!1;if(W!=="never"){if(W==="breaking"){if(j)X.push("breaking changes detected");if(B)X.push("impact status unknown")}else if(W==="drift"){if(Q)X.push("drift detected");if(B)X.push("impact status unknown")}else if(W==="any"){if(j)X.push("breaking changes detected");if(Q)X.push("drift detected");if(Z)X.push("validation failed");if(B)X.push("impact status unknown")}else X.push(`invalid fail_on value (${W})`);if(X.length>0)Y=!0}return{driftDetected:Q,breakingChangeDetected:j,validationFailed:Z,shouldFail:Y,failReasons:X}}generateReportMarkdown($,W){let j=(q,A=60000)=>{if(q.length<=A)return q;return`${q.slice(0,A)}
506
+ Follow this structure and quality level.`}var g5={};h(g5,{sarifToJson:()=>OQ,formatAsTextLines:()=>h5,formatAsText:()=>SQ,formatAsSarif:()=>zQ,formatAsJson:()=>KQ});function KQ($,W={}){let{pretty:j=!0,driftResult:A}=W,Q=$.issues.map((H)=>({name:H.ruleId,status:H.severity==="error"?"fail":H.severity==="warning"?"warn":"pass",category:H.category,message:H.message,file:H.file,line:H.line,details:H.context})),Z=$.categories.filter((H)=>H.passed).length,X=$.totalErrors,Y=$.totalWarnings,B=$.totalNotes,q={schemaVersion:"1.0",success:$.success,checks:Q,categories:$.categories.map((H)=>({category:H.category,label:H.label,passed:H.passed,errors:H.errors,warnings:H.warnings,notes:H.notes,durationMs:H.durationMs})),drift:{status:A?.hasDrift?"detected":"none",files:A?.files??[]},summary:{pass:Z,fail:X,warn:Y,note:B,total:Z+X+Y+B,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return j?JSON.stringify(q,null,2):JSON.stringify(q)}var _Q={"spec-structure-error":{name:"Spec Structure Error",description:"Contract specification is missing required structure elements"},"spec-structure-warning":{name:"Spec Structure Warning",description:"Contract specification has recommended but missing elements"},"integrity-orphaned":{name:"Orphaned Spec",description:"Contract specification is not linked to any feature"},"integrity-unresolved-ref":{name:"Unresolved Reference",description:"Contract specification references a non-existent spec"},"integrity-missing-feature":{name:"Missing Feature",description:"Feature referenced by spec does not exist"},"integrity-broken-link":{name:"Broken Link",description:"Link between specs is broken"},"deps-circular":{name:"Circular Dependency",description:"Circular dependency detected between contracts"},"deps-missing":{name:"Missing Dependency",description:"Contract depends on a non-existent contract"},"handler-missing":{name:"Missing Handler",description:"Handler implementation file does not exist for this contract"},"handler-warning":{name:"Handler Warning",description:"Handler implementation has potential issues"},"test-missing":{name:"Missing Test",description:"Test file does not exist for this contract"},"test-warning":{name:"Test Warning",description:"Test implementation has potential issues"}};function zQ($,W={}){let{toolName:j="ContractSpec",toolVersion:A="1.0.0",toolUri:Q="https://contractspec.io",repositoryUri:Z,workingDirectory:X}=W,Y=new Map,B=new Map,q=$.issues.filter((J)=>J.file);for(let J of q)if(!Y.has(J.ruleId)){let b=_Q[J.ruleId]??{name:J.ruleId,description:`Rule: ${J.ruleId}`},w={id:J.ruleId,name:b.name,shortDescription:{text:b.description},defaultConfiguration:{level:k5(J.severity)}};if(b.helpUri)w.helpUri=b.helpUri;B.set(J.ruleId,Y.size),Y.set(J.ruleId,w)}let H=q.map((J)=>{let b={ruleId:J.ruleId,ruleIndex:B.get(J.ruleId)??0,level:k5(J.severity),message:{text:J.message}},w={physicalLocation:{artifactLocation:{uri:UQ(J.file),uriBaseId:"%SRCROOT%"}}};if(J.line!==void 0)w.physicalLocation.region={startLine:J.line,startColumn:J.column??1,endLine:J.endLine??J.line,endColumn:J.endColumn};return b.locations=[w],b.partialFingerprints={primaryLocationLineHash:LQ(J)},b}),V=[];if(Z)V.push({repositoryUri:Z,revisionId:$.commitSha,branch:$.branch});let G={tool:{driver:{name:j,version:A,informationUri:Q,rules:Array.from(Y.values())}},results:H,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...X&&{workingDirectory:{uri:X}}}]};if(V.length>0)G.versionControlProvenance=V;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[G]}}function k5($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function UQ($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function LQ($){let W=[$.ruleId,$.file??"",$.message];return Buffer.from(W.join("|")).toString("base64").slice(0,16)}function OQ($){return JSON.stringify($,null,2)}function h5($,W={}){let j=[],{verbose:A=!1,showTiming:Q=!0,groupByFile:Z=!1}=W;if(j.push({text:"",style:"normal"}),j.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),j.push({text:"",style:"normal"}),$.commitSha||$.branch){let Y=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");j.push({text:`Git: ${Y}`,style:"muted"})}j.push({text:"",style:"normal"}),j.push({text:"Check Results:",style:"bold"});for(let Y of $.categories){let B=Y.passed?"\u2713":"\u2717",q=Y.passed?"success":"error",H=IQ(Y),V=Q?` (${Y.durationMs}ms)`:"";j.push({text:` ${B} ${Y.label}: ${H}${V}`,style:q})}if($.issues.length>0)if(j.push({text:"",style:"normal"}),j.push({text:"Issues:",style:"bold"}),Z){let Y=MQ($.issues);for(let[B,q]of Y){j.push({text:"",style:"normal"}),j.push({text:` ${B||"(no file)"}`,style:"bold",indent:1});for(let H of q)j.push(...f0(H,A,2))}}else{let Y=$.issues.filter((H)=>H.severity==="error"),B=$.issues.filter((H)=>H.severity==="warning"),q=$.issues.filter((H)=>H.severity==="note");if(Y.length>0){j.push({text:"",style:"normal"}),j.push({text:" Errors:",style:"error",indent:1});for(let H of Y)j.push(...f0(H,A,2))}if(B.length>0){j.push({text:"",style:"normal"}),j.push({text:" Warnings:",style:"warning",indent:1});for(let H of B)j.push(...f0(H,A,2))}if(q.length>0&&A){j.push({text:"",style:"normal"}),j.push({text:" Notes:",style:"muted",indent:1});for(let H of q)j.push(...f0(H,A,2))}}j.push({text:"",style:"normal"}),j.push({text:"\u2500".repeat(50),style:"muted"});let X=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&A?`${$.totalNotes} note(s)`:null].filter(Boolean);if(X.length>0)j.push({text:`Found: ${X.join(", ")}`,style:$.success?"warning":"error"});if(Q)j.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(j.push({text:"",style:"normal"}),$.success)j.push({text:"\u2705 All CI checks passed!",style:"success"});else j.push({text:"\u274C CI checks failed",style:"error"});return j.push({text:"",style:"normal"}),j}function SQ($,W={}){return h5($,W).map((A)=>" ".repeat(A.indent??0)+A.text).join(`
507
+ `)}function IQ($){let W=[];if($.errors>0)W.push(`${$.errors} error(s)`);if($.warnings>0)W.push(`${$.warnings} warning(s)`);if(W.length===0)return"passed";return W.join(", ")}function f0($,W,j){let A=[],Q=$.severity==="error"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",Z=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",X=`${Q} ${$.message}`;if($.file){let Y=$.line?`:${$.line}`:"";X+=` (${$.file}${Y})`}if(A.push({text:X,style:Z,indent:j}),W&&$.context){let Y=JSON.stringify($.context);if(Y!=="{}")A.push({text:`Context: ${Y}`,style:"muted",indent:j+1})}return A}function MQ($){let W=new Map;for(let j of $){let A=j.file??"";if(!W.has(A))W.set(A,[]);let Q=W.get(A);if(Q)Q.push(j)}return new Map([...W.entries()].sort(([j],[A])=>j.localeCompare(A)))}import{OperationSpecRegistry as EQ}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as NQ}from"@contractspec/lib.contracts-spec/operations/report";function RQ(){let $=new EQ;return NQ($),$}var AG=RQ();class CQ{buildReportData($){let W=$.existingReportData||{};if(W.contracts=$.contractsJson,W.whatChanged={summary:"Drift check completed.",detailsPath:"",...W.whatChanged},W.risk={status:"unknown",breaking:0,nonBreaking:0,...W.risk},W.validation={status:"skipped",outputPath:"",...W.validation},W.drift={status:$.driftStatus,files:$.driftFiles},!W.nextSteps)W.nextSteps=[];if($.driftStatus==="fail")W.nextSteps.push("Run the generate command locally and commit drift fixes.");return W}finalizeResults($,W){let j=$.drift?.status==="fail",A=!1;if(j&&W==="fail")A=!0;return{driftDetected:j,shouldFail:A}}}function DQ($){if(!$)return"\u2014";let W=new Date($),A=new Date().getTime()-W.getTime(),Q=Math.floor(A/86400000);if(Q<1)return"today";if(Q===1)return"yesterday";return`${Q} days ago`}class TQ{collectChanges($,W,j){if($){let A=$.endsWith("/")?$:`${$}/`;return j.filter((Q)=>Q.startsWith(A))}if(W){let A=new RegExp("^"+W.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return j.filter((Q)=>A.test(Q))}return j}detectDrift($){let W=$.map((j)=>j.slice(3)).filter((j)=>j&&j.trim().length>0).filter((j)=>j!==".contractspec-ci"&&!j.startsWith(".contractspec-ci/"));return{files:W,status:W.length>0?"fail":"pass"}}deriveImpactStatus($){let W=$?.summary||{},j=W.breaking||0,A=W.nonBreaking||0,Q=W.total;if(Q===void 0)Q=j+A;let Z=$?.breaking||!1,X="unknown";if($){if(Z||j>0)X="breaking",Z=!0;else if(A>0)X="non-breaking";else if(Q===0)X="no-impact"}return{status:X,breaking:Z,breakingCount:j,nonBreakingCount:A,total:Q||0}}buildReportData($){let W=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,j=this.deriveImpactStatus($.impactJson),A={contracts:$.contractsJson,whatChanged:{summary:W,detailsPath:".contractspec-ci/product-view.md"},risk:{status:j.status,breaking:j.breakingCount,nonBreaking:j.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(A.validation?.status==="fail")A.nextSteps?.push("Fix validation errors and rerun the workflow.");if(A.risk?.status==="breaking")A.nextSteps?.push("Review breaking changes and plan a migration.");if(A.risk?.status==="unknown")A.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(A.drift?.status==="fail")A.nextSteps?.push("Run the generate command locally and commit drift fixes.");let Q=this.finalizeResults(A,$.failOn);if(Q.shouldFail)A.nextSteps?.unshift(`CI failed: ${Q.failReasons.join(", ")} (fail_on=${$.failOn}).`);return A}finalizeResults($,W){let j=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,A=$.drift?.status==="fail",Q=$.validation?.status==="fail",Z=$.risk?.status==="unknown",X=[],Y=!1;if(W!=="never"){if(W==="breaking"){if(j)X.push("breaking changes detected");if(Z)X.push("impact status unknown")}else if(W==="drift"){if(A)X.push("drift detected");if(Z)X.push("impact status unknown")}else if(W==="any"){if(j)X.push("breaking changes detected");if(A)X.push("drift detected");if(Q)X.push("validation failed");if(Z)X.push("impact status unknown")}else X.push(`invalid fail_on value (${W})`);if(X.length>0)Y=!0}return{driftDetected:A,breakingChangeDetected:j,validationFailed:Q,shouldFail:Y,failReasons:X}}generateReportMarkdown($,W){let j=(B,q=60000)=>{if(B.length<=q)return B;return`${B.slice(0,q)}
508
508
 
509
- *(output truncated)*`},Q=(q)=>{if(!q||q.length===0)return"- None";return q.slice(0,20).map((A)=>`- ${A}`).join(`
510
- `)},Z=j($.whatChanged?.detailsPath?W($.whatChanged.detailsPath):""),B=j($.validation?.outputPath?W($.validation.outputPath):""),X=$.drift?.files??[],Y=[];if(Y.push("## ContractSpec Report"),Y.push(""),$.contracts&&$.contracts.length>0){Y.push("### Overall verification status"),Y.push(""),Y.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),Y.push("| --- | --- | --- | --- | --- |");for(let q of $.contracts){let A=q.lastVerifiedSha??"\u2014",H=N7(q.lastVerifiedDate),V=q.surfaces.join(", ");Y.push(`| ${q.name} | ${H} | ${q.driftMismatches} | ${V} | ${A} |`)}Y.push("")}if(Y.push("### 1) What changed"),$.whatChanged?.summary)Y.push($.whatChanged.summary);else Y.push("No contract changes detected.");if(Z.trim().length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Contract view (product)</summary>"),Y.push(""),Y.push(Z),Y.push(""),Y.push("</details>");if(Y.push(""),Y.push("### 2) Risk classification"),$.risk?.status){let q=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);Y.push(q.join(" | "))}else Y.push("Impact analysis unavailable.");if(Y.push(""),Y.push("### 3) Validation results"),$.validation?.status){if(Y.push(`Status: ${$.validation.status}`),B.trim().length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Validation output</summary>"),Y.push(""),Y.push(B),Y.push(""),Y.push("</details>")}else Y.push("Validation step not run.");if(Y.push(""),Y.push("### 4) Drift results"),$.drift?.status){if(Y.push(`Status: ${$.drift.status}`),X.length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Drifted files</summary>"),Y.push(""),Y.push(Q(X)),Y.push(""),Y.push("</details>")}else Y.push("Drift check not run.");if(Y.push(""),Y.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)Y.push(Q($.nextSteps));else Y.push("- No action required.");return`${Y.join(`
509
+ *(output truncated)*`},A=(B)=>{if(!B||B.length===0)return"- None";return B.slice(0,20).map((q)=>`- ${q}`).join(`
510
+ `)},Q=j($.whatChanged?.detailsPath?W($.whatChanged.detailsPath):""),Z=j($.validation?.outputPath?W($.validation.outputPath):""),X=$.drift?.files??[],Y=[];if(Y.push("## ContractSpec Report"),Y.push(""),$.contracts&&$.contracts.length>0){Y.push("### Overall verification status"),Y.push(""),Y.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),Y.push("| --- | --- | --- | --- | --- |");for(let B of $.contracts){let q=B.lastVerifiedSha??"\u2014",H=DQ(B.lastVerifiedDate),V=B.surfaces.join(", ");Y.push(`| ${B.name} | ${H} | ${B.driftMismatches} | ${V} | ${q} |`)}Y.push("")}if(Y.push("### 1) What changed"),$.whatChanged?.summary)Y.push($.whatChanged.summary);else Y.push("No contract changes detected.");if(Q.trim().length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Contract view (product)</summary>"),Y.push(""),Y.push(Q),Y.push(""),Y.push("</details>");if(Y.push(""),Y.push("### 2) Risk classification"),$.risk?.status){let B=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);Y.push(B.join(" | "))}else Y.push("Impact analysis unavailable.");if(Y.push(""),Y.push("### 3) Validation results"),$.validation?.status){if(Y.push(`Status: ${$.validation.status}`),Z.trim().length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Validation output</summary>"),Y.push(""),Y.push(Z),Y.push(""),Y.push("</details>")}else Y.push("Validation step not run.");if(Y.push(""),Y.push("### 4) Drift results"),$.drift?.status){if(Y.push(`Status: ${$.drift.status}`),X.length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Drifted files</summary>"),Y.push(""),Y.push(A(X)),Y.push(""),Y.push("</details>")}else Y.push("Drift check not run.");if(Y.push(""),Y.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)Y.push(A($.nextSteps));else Y.push("- No action required.");return`${Y.join(`
511
511
  `)}
512
- `}}import{AGENT_SYSTEM_PROMPTS as D7}from"@contractspec/lib.contracts-spec/llm";class S0{agentType="claude-code";formatPlan($){let W=[];if(W.push(`# Implement: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files to Create/Modify"),W.push("");for(let j of $.fileStructure){let Q=j.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";W.push(`${Q} \`${j.path}\``),W.push(` ${j.purpose}`),W.push("")}}W.push("## Implementation Steps"),W.push("");for(let j of $.steps){W.push(`### ${j.order}. ${j.title}`),W.push(""),W.push(j.description),W.push(""),W.push("**Acceptance Criteria:**");for(let Q of j.acceptanceCriteria)W.push(`- [ ] ${Q}`);W.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("### Policy");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("### Security");for(let j of $.constraints.security)W.push(`- \u26A0\uFE0F ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("### PII Handling"),W.push("The following fields contain personally identifiable information:");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}}W.push("## Verification Checklist"),W.push(""),W.push("Before submitting, verify:");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),W.push("## Instructions"),W.push(""),W.push("1. Implement each step in order"),W.push("2. Use TypeScript with strict typing (no `any`)"),W.push("3. Include JSDoc comments for public APIs"),W.push("4. Handle all error cases defined in the spec"),W.push("5. Emit events as specified"),W.push("6. Mark checklist items as you complete them"),W.push(""),{agent:"claude-code",systemPrompt:D7["claude-code"],taskPrompt:W.join(`
512
+ `}}import{AGENT_SYSTEM_PROMPTS as FQ}from"@contractspec/lib.contracts-spec/llm";class u0{agentType="claude-code";formatPlan($){let W=[];if(W.push(`# Implement: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files to Create/Modify"),W.push("");for(let j of $.fileStructure){let A=j.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";W.push(`${A} \`${j.path}\``),W.push(` ${j.purpose}`),W.push("")}}W.push("## Implementation Steps"),W.push("");for(let j of $.steps){W.push(`### ${j.order}. ${j.title}`),W.push(""),W.push(j.description),W.push(""),W.push("**Acceptance Criteria:**");for(let A of j.acceptanceCriteria)W.push(`- [ ] ${A}`);W.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("### Policy");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("### Security");for(let j of $.constraints.security)W.push(`- \u26A0\uFE0F ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("### PII Handling"),W.push("The following fields contain personally identifiable information:");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}}W.push("## Verification Checklist"),W.push(""),W.push("Before submitting, verify:");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),W.push("## Instructions"),W.push(""),W.push("1. Implement each step in order"),W.push("2. Use TypeScript with strict typing (no `any`)"),W.push("3. Include JSDoc comments for public APIs"),W.push("4. Handle all error cases defined in the spec"),W.push("5. Emit events as specified"),W.push("6. Mark checklist items as you complete them"),W.push(""),{agent:"claude-code",systemPrompt:FQ["claude-code"],taskPrompt:W.join(`
513
513
  `)}}generateConfig($){let W=[];return W.push("# ContractSpec Implementation Context"),W.push(""),W.push("This codebase uses ContractSpec for spec-first development."),W.push(""),W.push("## Spec Details"),W.push(""),W.push(`- **Name:** ${$.meta.key}`),W.push(`- **Version:** ${$.meta.version}`),W.push(`- **Kind:** ${$.meta.kind}`),W.push(`- **Stability:** ${$.meta.stability}`),W.push(""),W.push("## Implementation Requirements"),W.push(""),W.push("1. Match input/output types exactly"),W.push("2. Handle all defined error cases"),W.push("3. Emit events as specified"),W.push("4. Respect policy constraints"),W.push(""),W.join(`
514
- `)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};let j=[],Q=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let Z of Q){let B=$.matchAll(Z);for(let X of B)if(X[1])j.push(X[1])}if(j.length>0)return{errors:j};return{code:$}}}var E0=new S0;import{AGENT_SYSTEM_PROMPTS as F7}from"@contractspec/lib.contracts-spec/llm";class M0{agentType="cursor-cli";formatPlan($){let W=[];if(W.push(`# ${$.target.key}.v${$.target.version}`),W.push(""),W.push(`> ${$.context.goal}`),W.push(""),$.fileStructure.length>0){W.push("## Files"),W.push("");for(let Q of $.fileStructure)W.push(`- ${Q.type}: \`${Q.path}\` - ${Q.purpose}`);W.push("")}W.push("## Spec"),W.push(""),W.push($.specMarkdown),W.push(""),W.push("## Steps"),W.push("");for(let Q of $.steps)W.push(`${Q.order}. **${Q.title}**: ${Q.description}`);W.push("");let j=[...$.constraints.policy,...$.constraints.security.map((Q)=>`\u26A0\uFE0F ${Q}`)];if(j.length>0){W.push("## Constraints"),W.push("");for(let Q of j)W.push(`- ${Q}`);W.push("")}if($.constraints.pii.length>0)W.push("## PII Fields"),W.push(""),W.push(`Handle carefully: ${$.constraints.pii.map((Q)=>`\`${Q}\``).join(", ")}`),W.push("");return{agent:"cursor-cli",systemPrompt:F7["cursor-cli"],taskPrompt:W.join(`
515
- `)}}generateConfig($){let W=$.meta,j=[];if(j.push("---"),j.push(`description: Implementation rules for ${W.key}.v${W.version}`),j.push(`globs: ["**/${W.key.replace(/\./g,"/")}/**"]`),j.push("alwaysApply: false"),j.push("---"),j.push(""),j.push(`# ${W.key} Implementation Rules`),j.push(""),j.push(`This ${W.kind} operation must follow the ContractSpec specification.`),j.push(""),j.push("## Goal"),j.push(""),j.push(W.goal),j.push(""),j.push("## Requirements"),j.push(""),j.push("1. Input/output types MUST match the spec schema exactly"),j.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)j.push("3. Events MUST be emitted as specified");if(j.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)j.push(`5. Idempotency: ${$.policy.idempotent}`);if(j.push(""),$.io.errors&&Object.keys($.io.errors).length>0){j.push("## Error Cases"),j.push("");for(let[Q,Z]of Object.entries($.io.errors))j.push(`- \`${Q}\` (HTTP ${Z.http??400}): ${Z.when}`);j.push("")}if($.sideEffects?.emits?.length){j.push("## Events to Emit"),j.push("");for(let Q of $.sideEffects.emits)if("ref"in Q)j.push(`- \`${Q.ref.key}.v${Q.ref.version}\`: ${Q.when}`);else j.push(`- \`${Q.key}.v${Q.version}\`: ${Q.when}`);j.push("")}if($.policy.pii?.length){j.push("## PII Handling"),j.push(""),j.push("These fields contain PII and must be handled with care:");for(let Q of $.policy.pii)j.push(`- \`${Q}\``);j.push("")}if($.acceptance?.scenarios?.length){j.push("## Acceptance Scenarios"),j.push("");for(let Q of $.acceptance.scenarios)j.push(`### ${Q.key}`),j.push(`- Given: ${Q.given.join("; ")}`),j.push(`- When: ${Q.when.join("; ")}`),j.push(`- Then: ${Q.then.join("; ")}`),j.push("")}return j.join(`
516
- `)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};return{code:$}}}var N0=new M0;import{AGENT_SYSTEM_PROMPTS as x7}from"@contractspec/lib.contracts-spec/llm";class R0{agentType="generic-mcp";formatPlan($){let W=[];if(W.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Task"),W.push(""),W.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push(""),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files"),W.push(""),W.push("| Path | Action | Purpose |"),W.push("|------|--------|---------|");for(let j of $.fileStructure)W.push(`| \`${j.path}\` | ${j.type} | ${j.purpose} |`);W.push("")}W.push("## Implementation Steps"),W.push("");for(let j of $.steps)if(W.push(`### Step ${j.order}: ${j.title}`),W.push(""),W.push(j.description),W.push(""),j.acceptanceCriteria.length>0){W.push("**Acceptance Criteria:**"),W.push("");for(let Q of j.acceptanceCriteria)W.push(`- ${Q}`);W.push("")}if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("**Policy:**");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("**Security:**");for(let j of $.constraints.security)W.push(`- ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("**PII Fields (handle with care):**");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}W.push("## Verification"),W.push(""),W.push("After implementation, verify:"),W.push("");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),{agent:"generic-mcp",systemPrompt:x7["generic-mcp"],taskPrompt:W.join(`
514
+ `)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};let j=[],A=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let Q of A){let Z=$.matchAll(Q);for(let X of Z)if(X[1])j.push(X[1])}if(j.length>0)return{errors:j};return{code:$}}}var d0=new u0;import{AGENT_SYSTEM_PROMPTS as xQ}from"@contractspec/lib.contracts-spec/llm";class n0{agentType="cursor-cli";formatPlan($){let W=[];if(W.push(`# ${$.target.key}.v${$.target.version}`),W.push(""),W.push(`> ${$.context.goal}`),W.push(""),$.fileStructure.length>0){W.push("## Files"),W.push("");for(let A of $.fileStructure)W.push(`- ${A.type}: \`${A.path}\` - ${A.purpose}`);W.push("")}W.push("## Spec"),W.push(""),W.push($.specMarkdown),W.push(""),W.push("## Steps"),W.push("");for(let A of $.steps)W.push(`${A.order}. **${A.title}**: ${A.description}`);W.push("");let j=[...$.constraints.policy,...$.constraints.security.map((A)=>`\u26A0\uFE0F ${A}`)];if(j.length>0){W.push("## Constraints"),W.push("");for(let A of j)W.push(`- ${A}`);W.push("")}if($.constraints.pii.length>0)W.push("## PII Fields"),W.push(""),W.push(`Handle carefully: ${$.constraints.pii.map((A)=>`\`${A}\``).join(", ")}`),W.push("");return{agent:"cursor-cli",systemPrompt:xQ["cursor-cli"],taskPrompt:W.join(`
515
+ `)}}generateConfig($){let W=$.meta,j=[];if(j.push("---"),j.push(`description: Implementation rules for ${W.key}.v${W.version}`),j.push(`globs: ["**/${W.key.replace(/\./g,"/")}/**"]`),j.push("alwaysApply: false"),j.push("---"),j.push(""),j.push(`# ${W.key} Implementation Rules`),j.push(""),j.push(`This ${W.kind} operation must follow the ContractSpec specification.`),j.push(""),j.push("## Goal"),j.push(""),j.push(W.goal),j.push(""),j.push("## Requirements"),j.push(""),j.push("1. Input/output types MUST match the spec schema exactly"),j.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)j.push("3. Events MUST be emitted as specified");if(j.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)j.push(`5. Idempotency: ${$.policy.idempotent}`);if(j.push(""),$.io.errors&&Object.keys($.io.errors).length>0){j.push("## Error Cases"),j.push("");for(let[A,Q]of Object.entries($.io.errors))j.push(`- \`${A}\` (HTTP ${Q.http??400}): ${Q.when}`);j.push("")}if($.sideEffects?.emits?.length){j.push("## Events to Emit"),j.push("");for(let A of $.sideEffects.emits)if("ref"in A)j.push(`- \`${A.ref.key}.v${A.ref.version}\`: ${A.when}`);else j.push(`- \`${A.key}.v${A.version}\`: ${A.when}`);j.push("")}if($.policy.pii?.length){j.push("## PII Handling"),j.push(""),j.push("These fields contain PII and must be handled with care:");for(let A of $.policy.pii)j.push(`- \`${A}\``);j.push("")}if($.acceptance?.scenarios?.length){j.push("## Acceptance Scenarios"),j.push("");for(let A of $.acceptance.scenarios)j.push(`### ${A.key}`),j.push(`- Given: ${A.given.join("; ")}`),j.push(`- When: ${A.when.join("; ")}`),j.push(`- Then: ${A.then.join("; ")}`),j.push("")}return j.join(`
516
+ `)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};return{code:$}}}var c0=new n0;import{AGENT_SYSTEM_PROMPTS as yQ}from"@contractspec/lib.contracts-spec/llm";class r0{agentType="generic-mcp";formatPlan($){let W=[];if(W.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Task"),W.push(""),W.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push(""),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files"),W.push(""),W.push("| Path | Action | Purpose |"),W.push("|------|--------|---------|");for(let j of $.fileStructure)W.push(`| \`${j.path}\` | ${j.type} | ${j.purpose} |`);W.push("")}W.push("## Implementation Steps"),W.push("");for(let j of $.steps)if(W.push(`### Step ${j.order}: ${j.title}`),W.push(""),W.push(j.description),W.push(""),j.acceptanceCriteria.length>0){W.push("**Acceptance Criteria:**"),W.push("");for(let A of j.acceptanceCriteria)W.push(`- ${A}`);W.push("")}if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("**Policy:**");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("**Security:**");for(let j of $.constraints.security)W.push(`- ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("**PII Fields (handle with care):**");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}W.push("## Verification"),W.push(""),W.push("After implementation, verify:"),W.push("");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),{agent:"generic-mcp",systemPrompt:yQ["generic-mcp"],taskPrompt:W.join(`
517
517
  `)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let W=$.meta,j=[];return j.push(`# ${W.key} v${W.version}`),j.push(""),j.push(`**Type:** ${W.kind}`),j.push(`**Stability:** ${W.stability}`),j.push(""),j.push("## Goal"),j.push(""),j.push(W.goal),j.push(""),j.push("## Description"),j.push(""),j.push(W.description),j.push(""),j.join(`
518
- `)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};try{let j=JSON.parse($);if(typeof j.code==="string")return{code:j.code};if(typeof j.errors==="object")return{errors:Array.isArray(j.errors)?j.errors:[String(j.errors)]}}catch{}return{code:$}}}var D0=new R0;var dW={"claude-code":E0,"cursor-cli":N0,"generic-mcp":D0};function l$($){let W=dW[$];if(!W)throw Error(`Unknown agent type: ${$}`);return W}function nW(){return Object.keys(dW)}import{featureToMarkdown as cW,generateImplementationPlan as A5,operationSpecToAgentPrompt as T7,operationSpecToFullMarkdown as v7}from"@contractspec/lib.contracts-spec/llm";var y7={defaultAgent:"generic-mcp",verbose:!1};class F0{config;constructor($={}){this.config={...y7,...$}}generateGuide($,W={}){let j=W.agent??this.config.defaultAgent,Q=l$(j),Z=A5($,{projectRoot:this.config.projectRoot,existingFiles:W.targetPath?[W.targetPath]:void 0}),B=Q.formatPlan(Z),X=v7($);return{plan:Z,prompt:B,markdown:X}}generateFeatureGuide($,W,j={}){let Q=j.agent??this.config.defaultAgent,Z=l$(Q),B=$.operations?.[0],X=B?W.specs?.get(B.key,B.version):void 0,Y;if(X)Y=A5(X,{projectRoot:this.config.projectRoot}),Y.target={type:"feature",key:$.meta.key,version:"1.0.0"},Y.context.goal=$.meta.description??Y.context.goal;else Y={target:{type:"feature",key:$.meta.key,version:"1.0.0"},context:{goal:$.meta.description??`Implement feature ${$.meta.key}`,description:$.meta.title??$.meta.key,background:""},specMarkdown:cW($,W),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(Y.specMarkdown=cW($,W,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)Y.steps=$.operations.map((H,V)=>({order:V+1,title:`Implement ${H.key}`,description:`Implement operation ${H.key}.v${H.version}`,acceptanceCriteria:[`Operation ${H.key} works as specified`]}));let q=Z.formatPlan(Y),A=cW($,W);return{plan:Y,prompt:q,markdown:A}}generateAgentConfig($,W){return l$(W??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,W,j="implement",Q){return T7($,{taskType:j,existingCode:Q})}listAgentTypes(){return nW()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function P7($){return new F0($)}var m7=new F0;import{generateComponentTemplate as k7,generateHandlerTemplate as g7,generateTestTemplate as h7,inferSpecTypeFromFilePath as f7,scanSpecSource as u7}from"@contractspec/module.workspace";async function x0($,W,j,Q={}){let{fs:Z,logger:B,workspace:X}=W,Y=X?.scanSpecSource??u7,q=X?.inferSpecTypeFromFilePath??f7,A=X?.generateHandlerTemplate??g7,H=X?.generateComponentTemplate??k7,V=X?.generateTestTemplate??h7,{targets:G=n7($,q),outputDir:z=j.outputDir,overwrite:J=!1,dryRun:K=!1}=Q,_=await Z.readFile($),w=Y(_,$),b=q($);B.info(`Building from spec: ${$}`,{specType:b});let L=[];for(let I of G)try{let U=await d7(I,$,_,w,b,{fs:Z,logger:B},z,J,K,{genHandler:A,genComponent:H,genTest:V});L.push(U)}catch(U){L.push({target:I,outputPath:"",success:!1,error:U instanceof Error?U.message:String(U),skipped:!1})}return{specPath:$,specInfo:w,results:L}}async function d7($,W,j,Q,Z,B,X,Y,q,A){let{fs:H,logger:V}=B,{genHandler:G,genComponent:z,genTest:J}=A,K,_;switch($){case"handler":{if(Z!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${Z})`};let L=Q.kind==="command"||Q.kind==="query"?Q.kind:"command";K=G(Q.key??"unknown",L),_=lW(W,X,"handlers",Q.key??"unknown",".handler.ts",B.fs);break}case"component":{if(Z!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${Z})`};K=z(Q.key??"unknown",Q.description??""),_=lW(W,X,"components",Q.key??"unknown",".tsx",B.fs);break}case"test":{let L=Z==="operation"?"handler":"component";K=J(Q.key??"unknown",L),_=lW(W,X,"__tests__",Q.key??"unknown",".test.ts",B.fs);break}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}if(await H.exists(_)&&!Y)return{target:$,outputPath:_,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(q)return V.info(`[dry-run] Would write: ${_}`),{target:$,outputPath:_,success:!0};let b=H.dirname(_);return await H.mkdir(b),await H.writeFile(_,K),V.info(`Generated: ${_}`),{target:$,outputPath:_,success:!0}}function n7($,W){switch(W($)){case"operation":return["handler"];case"presentation":return["component"];default:return[]}}function lW($,W,j,Q,Z,B){let X=c7(Q.split(".").pop()??"unknown"),Y;if(W.startsWith("."))Y=B.resolve(B.dirname($),"..",W,j);else Y=B.resolve(W,j);return B.join(Y,`${X}${Z}`)}function c7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}import{scanSpecSource as s7}from"@contractspec/module.workspace";import e7 from"micromatch";var z5={};P(z5,{validators:()=>t7,urlSchema:()=>a7,loadTypeScriptModule:()=>r$,isValidVersion:()=>p7,isValidIdentifier:()=>V5,isValidDotName:()=>G5,isTestFile:()=>oW,isLibraryDefinitionFile:()=>pW,emailSchema:()=>i7});import rW from"micromatch";function oW($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return rW.isMatch($,j)}function pW($){let W=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(rW.isMatch($,W))return!1;let j=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return rW.isMatch($,j)}import{readFile as l7}from"fs/promises";import{createRequire as r7}from"module";import{dirname as o7}from"path";import H5 from"vm";import iW from"typescript";async function r$($){let W=await l7($,"utf-8"),j=iW.transpileModule(W,{compilerOptions:{module:iW.ModuleKind.CommonJS,target:iW.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),Q={},Z={exports:Q},B=r7($),X=H5.createContext({module:Z,exports:Q,require:B,__dirname:o7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new H5.Script(j.outputText,{filename:$}).runInContext(X),Z.exports}import*as Z$ from"zod";function V5($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function G5($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function p7($){return Number.isInteger($)&&$>0}var i7=Z$.string().email(),a7=Z$.string().url(),t7={specName:Z$.string().refine(G5,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:Z$.number().int().positive(),identifier:Z$.string().refine(V5,{message:"Must be a valid TypeScript identifier"}),owner:Z$.string().startsWith("@"),tag:Z$.string().min(1)};async function h($,W={}){let{fs:j,scan:Q=s7}=$,Z=W.pattern,B=await j.glob({cwd:W.cwd,pattern:Z}),X=[],Y=Array.isArray(W.type)?W.type:[W.type];for(let q of B){if(q.includes("node_modules")||q.includes("/dist/"))continue;if(W.config?.excludePackages&&e7.isMatch(q,W.config.excludePackages,{contains:!0}))continue;if(oW(q,W.config))continue;if(pW(q))continue;try{let A=await j.readFile(q),H=Q(A,q);if(H.specType==="unknown")continue;if(W.type&&!Y.includes(H.specType))continue;X.push(H)}catch{}}return X}function DH($){let W=new Map;for(let j of $){let Q=W.get(j.specType)??[];Q.push(j),W.set(j.specType,Q)}return W}function A$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function T0($){let W=JSON.parse($),j=new Map,Q=0,Z=0,B=0,X=0,Y=0,q=0,A=0,H=0;for(let[G,z]of Object.entries(W)){let J=$8(G,z);j.set(G,J),Q+=J.statements.total,Z+=J.statements.covered,B+=J.branches.total,X+=J.branches.covered,Y+=J.functions.total,q+=J.functions.covered,A+=J.lines.total,H+=J.lines.covered}let V={statements:{covered:Z,total:Q,pct:A$(Z,Q)},branches:{covered:X,total:B,pct:A$(X,B)},functions:{covered:q,total:Y,pct:A$(q,Y)},lines:{covered:H,total:A,pct:A$(H,A)}};return{files:j,total:V}}function $8($,W){let j=Object.keys(W.statementMap).length,Q=Object.values(W.s).filter((H)=>H>0).length,Z=Object.keys(W.fnMap).length,B=Object.values(W.f).filter((H)=>H>0).length,X=0,Y=0;for(let H of Object.values(W.b))X+=H.length,Y+=H.filter((V)=>V>0).length;let q=new Set,A=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(q.add(G),(W.s[H]??0)>0)A.add(G);return{path:$,statements:{covered:Q,total:j,pct:A$(Q,j)},branches:{covered:Y,total:X,pct:A$(Y,X)},functions:{covered:B,total:Z,pct:A$(B,Z)},lines:{covered:A.size,total:q.size,pct:A$(A.size,q.size)}}}function aW($){switch($){case"istanbul":return{parse:T0};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function tW($,W){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&W?.includes("cobertura"))return"cobertura";return"istanbul"}function sW($,W,j,Q){let Z=[];if(j.statements!==void 0&&Q.statements.pct<j.statements)Z.push({metric:"statements",required:j.statements,actual:Q.statements.pct,message:`Statement coverage ${Q.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&Q.branches.pct<j.branches)Z.push({metric:"branches",required:j.branches,actual:Q.branches.pct,message:`Branch coverage ${Q.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&Q.functions.pct<j.functions)Z.push({metric:"functions",required:j.functions,actual:Q.functions.pct,message:`Function coverage ${Q.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&Q.lines.pct<j.lines)Z.push({metric:"lines",required:j.lines,actual:Q.lines.pct,message:`Line coverage ${Q.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Z.push({metric:"mutations",required:j.mutations,actual:0,message:`Mutation coverage required (${j.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:W,requirement:j,actual:Q,passed:Z.length===0,failures:Z}}async function eW($,W,j){let{fs:Q,logger:Z}=$,B=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],q,A;for(let z of Y)if(await Q.exists(z)){q=await Q.readFile(z),A=z;break}if(!q)return Z.info("No coverage report found, skipping coverage checks"),B;let H=tW(A??"coverage.json"),G=aW(H).parse(q);for(let z of W){if(z.specType!=="test-spec"||!z.key||!z.version||!z.sourceBlock)continue;let J=z.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!J||!J[1])continue;let K=J[1],_={},w=K.match(/statements\s*:\s*(\d+)/);if(w&&w[1])_.statements=parseInt(w[1],10);let b=K.match(/branches\s*:\s*(\d+)/);if(b&&b[1])_.branches=parseInt(b[1],10);let L=K.match(/functions\s*:\s*(\d+)/);if(L&&L[1])_.functions=parseInt(L[1],10);let I=K.match(/lines\s*:\s*(\d+)/);if(I&&I[1])_.lines=parseInt(I[1],10);if(Object.keys(_).length===0)continue;let U=sW(z.key,z.version,_,G.total);for(let O of U.failures)B.push({ruleId:"coverage-below-threshold",severity:"error",message:O.message,category:"coverage",file:z.filePath,context:{specKey:z.key,specVersion:z.version,metric:O.metric,required:O.required,actual:O.actual}})}return B}import{addContractNode as W8,buildReverseEdges as j8,createContractGraph as Q8,detectCycles as Z8,findMissingDependencies as B8,parseImportedSpecNames as X8,toDot as Y8}from"@contractspec/module.workspace";async function J5($,W={}){let{fs:j}=$,Q=await j.glob({pattern:W.pattern}),Z=Q8();for(let Y of Q){let q=await j.readFile(Y),A=j.relative(".",Y),H=j.basename(Y).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",V=X8(q,Y);W8(Z,H,A,V)}j8(Z);let B=Z8(Z),X=B8(Z);return{graph:Z,total:Z.size,cycles:B,missing:X}}function iH($,W){return $.get(W)}function aH($){return Y8($)}function tH($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),Q=W.filter((X)=>X.dependencies.length===0),Z=W.filter((X)=>X.dependents.length>0),B=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:Q.length,used:Z.length,unused:B.length}}async function $1($,W){let j=[],Q=await J5($,{pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" \u2192 ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let B of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${B}`,category:"deps",context:{contract:Z.contract,missing:B}});return j}import{analyzePackageDocBlocks as q8}from"@contractspec/module.workspace";var A8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function H8($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:A8}),Q=new Map;for(let X of j){let Y=$.dirname(X),q=$.join(Y,"src");if(!await $.exists(q))continue;try{let A=JSON.parse(await $.readFile(X));Q.set(Y,{packageName:A.name??$.relative(W,Y),packageRoot:Y,srcRoot:q})}catch{continue}}let Z=$.join(W,"package.json"),B=$.join(W,"src");if(await $.exists(Z)&&await $.exists(B))try{let X=JSON.parse(await $.readFile(Z));Q.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:B})}catch{}return[...Q.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function v0($,W){let j=[],Q=await H8($,W);for(let Z of Q){let B=q8({packageName:Z.packageName,srcRoot:Z.srcRoot});for(let X of B.diagnostics)j.push({...X,packageName:Z.packageName,packageRoot:Z.packageRoot,srcRoot:Z.srcRoot})}return j}async function W1($,W){let j=W.workspaceRoot??process.cwd();return(await v0($.fs,j)).map((Z)=>({ruleId:Z.ruleId,severity:Z.severity==="warning"?"warning":"error",message:Z.message,category:"docs",file:Z.file,line:Z.line,column:Z.column,context:{packageName:Z.packageName,packageRoot:Z.packageRoot,...Z.context}}))}async function j1($,W,j){let Q=[],Z=await V8($,W);if(Q.push(Z),Z.status==="pass")Q.push(await G8($,W,j));return Q}async function V8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");try{if(!await $.exists(j))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let Z=await $.readFile(j),B=JSON.parse(Z),X=B.aiProvider??"claude",Y=B.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${X}, Model: ${Y}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function G8($,W,j){let Q=$.join(W.workspaceRoot,".contractsrc.json");try{let Z=await $.readFile(Q),X=JSON.parse(Z).aiProvider??"claude",q={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!q)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[q])return{category:"ai",name:"API Key",status:"pass",message:`${q} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${q} not set`,details:`Set ${q} in your environment to use AI features`,fix:j?{description:`Set ${q} environment variable`,apply:async()=>{let H=await j.input(`Enter your ${X} API key:`,{password:!0});if(!H)return{success:!1,message:"No API key provided"};let V=$.join(W.workspaceRoot,".env");try{let G="";if(await $.exists(V)){if(G=await $.readFile(V),G.includes(`${q}=`))return{success:!1,message:`${q} already in .env, update manually`};G+=`
519
- `}return G+=`${q}=${H}
520
- `,await $.writeFile(V,G),{success:!0,message:`Added ${q} to .env (restart required)`}}catch(G){return{success:!1,message:`Failed: ${G instanceof Error?G.message:String(G)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as z8}from"child_process";import{promisify as J8}from"util";var y0=J8(z8);async function Q1($,W){let j=[];return j.push(await K8(W)),j.push(await U8(W)),j.push(await _8($,W)),j}async function K8($){try{return await y0("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4}),{category:"cli",name:"CLI Accessible",status:"pass",message:"ContractSpec CLI is accessible"}}catch{return{category:"cli",name:"CLI Accessible",status:"fail",message:"ContractSpec CLI is not accessible",details:'Could not run "bunx contractspec --version"',fix:{description:"Install ContractSpec CLI globally",apply:async()=>{try{return await y0("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(W){return{success:!1,message:`Failed to install: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function U8($){try{let{stdout:W}=await y0("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${W.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function _8($,W){let j=$.join(W.workspaceRoot,"package.json");try{if(!await $.exists(j))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot){let Y=$.join(W.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(Y))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let Z=await $.readFile(j),B=JSON.parse(Z);if(B.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||B.devDependencies?.["@contractspec/app.cli-contractspec"]!==void 0)return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is installed as a project dependency"};return{category:"cli",name:"Local Installation",status:"warn",message:"CLI is not installed as a project dependency",details:"Consider adding @contractspec/app.cli-contractspec to devDependencies",fix:{description:"Add CLI as a dev dependency",apply:async()=>{try{return await y0("npm install -D @contractspec/app.cli-contractspec",{cwd:W.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(Y){return{success:!1,message:`Failed to install: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}function x$($){let W=$.isMonorepo&&$.scope==="package";return{$schema:"https://api.contractspec.io/schemas/contractsrc.json",aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms",features:"contracts/features"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...W&&$.packageName?{package:$.packageName}:{}}}function K5(){return{"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.enabled":!0,"contractspec.validation.validateOnSave":!0,"contractspec.validation.validateOnOpen":!0,"contractspec.codeLens.enabled":!0,"contractspec.diagnostics.showWarnings":!0,"contractspec.diagnostics.showHints":!0,"contractspec.integrity.enabled":!0,"contractspec.integrity.checkOnSave":!0}}function o$(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function U5(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function _5($){let W=$.projectName??"this project",Q=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
521
-
522
- This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
523
-
524
- ## Spec-First Principle
525
-
526
- - **Always update contracts first** before changing implementation code.
527
- - Contracts are the source of truth for operations, events, and presentations.
528
- - Implementation code should be generated or derived from contracts.
529
- ${$.isMonorepo?`
530
- ## Monorepo Structure
531
-
532
- This is a monorepo. Contracts may exist at:
533
- - Package level: \`packages/*/src/contracts/\`
534
- - Workspace level: \`src/contracts/\`
535
-
536
- Check the appropriate level based on the feature scope.
537
- `:""}
538
- ## Contract Locations
539
-
540
- Contracts are located in:
541
- - \`${Q}/operations/\` - Command and query specs
542
- - \`${Q}/events/\` - Event specs
543
- - \`${Q}/presentations/\` - UI presentation specs
544
- - \`${Q}/features/\` - Feature module specs
545
-
546
- ## When Making Changes
547
-
548
- 1. **Before coding**: Check if a contract exists for the feature.
549
- 2. **If contract exists**: Update the contract first, then regenerate code.
550
- 3. **If no contract**: Create a new contract using \`contractspec create\`.
551
- 4. **After changes**: Validate with \`contractspec validate\`.
552
-
553
- ## Key Commands
554
-
555
- - \`contractspec create\` - Scaffold new specs
556
- - \`contractspec validate\` - Validate specs
557
- - \`contractspec build\` - Generate implementation code
558
- - \`contractspec integrity\` - Check contract health
559
-
560
- ## Contract Structure
561
-
562
- Operations follow this pattern:
563
- \`\`\`typescript
564
- defineCommand({
565
- meta: { name: 'service.action', version: '1.0.0', ... },
566
- io: { input: InputSchema, output: OutputSchema },
567
- policy: { auth: 'user', ... },
568
- handler: async (args, ctx) => { ... }
569
- });
570
- \`\`\`
571
-
572
- ## Rules for ${W}
573
-
574
- - All API endpoints must have a corresponding operation contract.
575
- - Events must be declared in contracts before being emitted.
576
- - UI components should reference presentation contracts.
577
- - Feature flags should be defined in feature modules.
578
- `}function L5($){let W=$.projectName??"this project",j=$.isMonorepo&&$.scope==="package",Q=j&&$.packageName?`${$.packageName} package`:W,Z="src/contracts",B=$.isMonorepo?j?`
579
- ## Monorepo Scope
580
-
581
- This guide is scoped to the current package.
582
- - Prefer package-local contracts under \`src/contracts/\`
583
- - Check workspace-level rules only when a change crosses package boundaries.
584
- `:`
585
- ## Monorepo Scope
586
-
587
- This guide is scoped to the workspace root.
588
- - Shared contracts may live in multiple packages under \`packages/*/src/contracts/\`
589
- - Prefer the nearest package guide when working inside a specific package.
590
- `:"";return`# ContractSpec AI Guide
591
-
592
- Scope: \`${Q}\`
593
-
594
- This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
595
-
596
- ## Core Rules
597
-
598
- - Update contracts before implementation code.
599
- - Validate contracts after changes with \`contractspec validate\`.
600
- - Regenerate derived artifacts before considering the work complete.
601
- - Prefer existing package-local guides and READMEs when working in a nested package.
602
- ${B}
603
- ## Contract Locations
604
-
605
- - \`src/contracts/operations/\` - command and query specs
606
- - \`src/contracts/events/\` - domain and integration events
607
- - \`src/contracts/presentations/\` - UI presentation contracts
608
- - \`src/contracts/features/\` - feature module contracts
609
-
610
- ## Recommended Workflow
611
-
612
- 1. Check whether a contract already exists for the change.
613
- 2. Update or create the contract first.
614
- 3. Run validation and generation commands.
615
- 4. Review downstream code and tests affected by the contract update.
616
-
617
- ## Key Commands
618
-
619
- - \`contractspec create\` - scaffold a new contract
620
- - \`contractspec validate\` - validate contract integrity
621
- - \`contractspec build\` - generate implementation artifacts
622
- - \`contractspec doctor\` - verify workspace configuration
623
-
624
- ## Working Agreement
625
-
626
- - Keep changes spec-first, deterministic, and reviewable.
627
- - Do not change generated outputs without updating their source contract.
628
- - When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
629
- `}function P0(){let $=process.platform,W=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${W}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??W}/Claude/claude_desktop_config.json`;default:return`${W}/.config/claude/claude_desktop_config.json`}}function r($,W){let j={...$};for(let Q of Object.keys(W)){let Z=$[Q],B=W[Q];if(Z===void 0)j[Q]=B;else if(m0(Z)&&m0(B))j[Q]=r(Z,B)}return j}function L8($,W){let j={...$};for(let Q of Object.keys(W)){let Z=$[Q],B=W[Q];if(B===void 0)continue;if(m0(Z)&&m0(B))j[Q]=L8(Z,B);else j[Q]=B}return j}function m0($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function j$($){try{return JSON.parse($)}catch{return null}}function D($){return JSON.stringify($,null,2)+`
630
- `}async function Z1($,W){let j=[];return j.push(await I8($,W)),j.push(await O8($,W)),j.push(await b8($,W)),j.push(await w8($,W)),j.push(await C8($,W)),j}async function I8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let Z=x$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,D(Z)),{success:!0,message:"Created .contractsrc.json"}}catch(Z){return{success:!1,message:`Failed to create: ${Z instanceof Error?Z.message:String(Z)}`}}}}}}async function O8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j);return JSON.parse(Z),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Z){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Z instanceof Error?Z.message:String(Z),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=x$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,D(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function b8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z),X=[];if(!B.outputDir)X.push("outputDir");if(!B.conventions)X.push("conventions");if(X.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${X.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let Y=x$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let q of X)if(Y[q]!==void 0)B[q]=Y[q];return await $.writeFile(j,D(B)),{success:!0,message:"Added missing fields"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function w8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z);if(B.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:B.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return B.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,D(B)),{success:!0,message:"Added versioning configuration"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function C8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z);if(B.hooks){let q=B.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(q).length} git hook(s) configured`}}let X=$.join(W.workspaceRoot,".husky");if(await $.exists(X))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return B.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,D(B)),{success:!0,message:"Added hooks configuration"}}catch(q){return{success:!1,message:`Failed: ${q instanceof Error?q.message:String(q)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}import{exec as S8}from"child_process";import{promisify as E8}from"util";var O$=E8(S8);async function B1($,W){let j=[];return j.push(await M8(W)),j.push(await N8(W)),j.push(await R8($,W)),j.push(await D8($,W)),j.push(await F8($,W)),j}async function M8($){try{let{stdout:W}=await O$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${W.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function N8($){try{let{stdout:W}=await O$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${W.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function R8($,W){let j=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],Q=null;for(let{file:Z,name:B}of j){let X=$.join(W.workspaceRoot,Z);if(await $.exists(X)){Q=B;break}}if(!Q){let Z=$.join(W.workspaceRoot,".."),B=$.join(W.workspaceRoot,"../.."),X=[Z,B];for(let Y of X){for(let{file:q,name:A}of j){let H=$.join(Y,q);if(await $.exists(H)){Q=A;break}}if(Q)break}}if(!Q)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await O$(`${Q} --version`,{cwd:W.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${Q}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${Q} detected but not available`,details:`Install ${Q} or use a different package manager`}}}async function D8($,W){let j=$.join(W.workspaceRoot,"node_modules");if(await $.exists(j))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await O$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await O$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}}}async function F8($,W){let j=$.join(W.workspaceRoot,"package.json");try{let Q=await $.readFile(j),Z=JSON.parse(Q),B={...Z.dependencies,...Z.devDependencies};if("@contractspec/lib.contracts-spec"in B)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${B["@contractspec/lib.contracts-spec"]})`};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await O$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await O$("npm install @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function X1($,W){let j=await v0($,W.workspaceRoot);if(j.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return j.map((Q)=>({category:"docs",name:`Same-File DocBlocks (${Q.packageName})`,status:Q.severity==="warning"?"warn":"fail",message:Q.message,details:$.relative(W.workspaceRoot,Q.file),context:{ruleId:Q.ruleId,file:Q.file,line:Q.line,column:Q.column,packageName:Q.packageName}}))}import{isExampleFile as x8,isFeatureFile as T8,scanAllSpecsFromSource as v8,scanExampleSource as y8,scanFeatureSource as P8}from"@contractspec/module.workspace";function m8(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function k0($,W={}){let{fs:j,logger:Q}=$,Z=m8(),B=W.pattern??"**/*.{ts,tsx}";Q.info("Scanning for contract layer files...");let X=await j.glob({pattern:B});for(let q of X){if(q.includes("node_modules")||q.includes("/dist/"))continue;try{let A=await j.readFile(q);if(T8(q)){let H=P8(A,q);Z.features.set(H.key,H);continue}if(x8(q)){let H=y8(A,q);Z.examples.set(H.key,H);continue}if(q.includes(".app-config.")||q.includes(".blueprint.")){let H=v8(A,q);for(let V of H)if(V.specType==="app-config"&&V.key)Z.appConfigs.set(V.key,V)}}catch{}}try{let q=await j.glob({pattern:"**/.contractsrc.json"});for(let A of q){if(A.includes("node_modules"))continue;try{let H=await j.readFile(A),V=JSON.parse(H);Z.workspaceConfigs.set(A,{file:A,config:V,valid:!0,errors:[]})}catch(H){Z.workspaceConfigs.set(A,{file:A,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Z.features.size,examples:Z.examples.size,appConfigs:Z.appConfigs.size,workspaceConfigs:Z.workspaceConfigs.size,total:Z.features.size+Z.examples.size+Z.appConfigs.size+Z.workspaceConfigs.size};return Q.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Z,stats:Y}}function OV($){let W=[];for(let[j,Q]of $.features)W.push({key:j,file:Q.filePath,type:"feature"});for(let[j,Q]of $.examples)W.push({key:j,version:Q.version,file:Q.filePath,type:"example"});for(let[j,Q]of $.appConfigs)W.push({key:j,version:Q.version,file:Q.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function g0($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function Y1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function h0($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let Q=await $.readFile(j),Z=JSON.parse(Q);return{version:typeof Z.version==="number"&&Number.isFinite(Z.version)?Z.version:1,criticalPackages:Y1(Z.criticalPackages).map(g0),criticalFeatureKeys:Y1(Z.criticalFeatureKeys),smokePackages:Y1(Z.smokePackages)}}catch{return}}function I5($,W){let j=g0($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function O5($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function T$($){return g0(`${g0($)}/config/stability-policy.json`)}async function q1($,W){let j=[],Q=await h0($,W.workspaceRoot),Z=await k0({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(k8(Z.stats.features)),j.push(g8(Z.stats.examples)),j.push(h8(Z.inventory.features,Q,W)),j.push(f8(Z.inventory.examples)),j.push(u8(Z.inventory.workspaceConfigs)),j}function k8($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function g8($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function h8($,W,j){let Q=[],Z=[];for(let[B,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(O5(B,W))Z.push(B);else Q.push(B);if(Z.length===0&&Q.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:W?T$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Z.length>0?"fail":"warn",message:Z.length>0?`${Z.length} critical feature(s) missing owners`:`${Q.length} feature(s) missing owners`,details:Z.length>0?`Critical features: ${Z.join(", ")}`:`Features: ${Q.slice(0,3).join(", ")}${Q.length>3?"...":""}`,context:{policyPath:W?T$(j.workspaceRoot):void 0,criticalMissingFeatures:Z,missingFeatures:Q}}}function f8($){let W=[];for(let[j,Q]of $)if(!Q.entrypoints.packageName)W.push(j);if(W.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${W.length} example(s) missing packageName`,details:`Examples: ${W.join(", ")}`}}function u8($){let W=[];for(let[,j]of $)if(!j.valid)W.push(j.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(W.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${W.length} workspace config(s) invalid`,details:`Files: ${W.join(", ")}`}}async function A1($,W){let j=[];return j.push(await d8($,W)),j.push(await n8($,W)),j.push(await c8($,W)),j}async function d8($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(await $.exists(j))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);let B=o$();return await $.writeFile(j,D(B)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}}}async function n8($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(!await $.exists(j))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z);if(B.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let Y=o$(),q=r(B,Y);return await $.writeFile(j,D(q)),{success:!0,message:"Registered MCP server"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function c8($,W){let j=P0();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Z=await $.readFile(j);if(JSON.parse(Z).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var l8=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],b5=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function r8($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,Q])=>{if(typeof Q==="string")W[j]=Q;return W},{})}function o8($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function p8($,W,j){let Q=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:b5}),Z=[];for(let B of Q){let X=$.dirname(B),Y=$.relative(W,X);try{let q=JSON.parse(await $.readFile(B)),A=r8(q.scripts),H=await $.glob({patterns:l8,cwd:X,ignore:b5});Z.push({packageName:q.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof A.build==="string",hasTypecheckScript:typeof A.typecheck==="string",hasLintScript:typeof A.lint==="string"||typeof A["lint:check"]==="string",hasTestScript:typeof A.test==="string",usesPassWithNoTests:o8(A),testFileCount:H.length,tier:I5(Y,j)})}catch{continue}}return Z}function i8($){let W=[];if(!$.hasBuildScript)W.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)W.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)W.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)W.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)W.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)W.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return W}function a8($){let W=[];if($.testFileCount>0&&!$.hasTestScript)W.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)W.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return W}async function w5($,W,j){let Q=await p8($,W,j),Z=[];for(let X of Q){if(X.tier==="critical")Z.push(...i8(X));Z.push(...a8(X))}let B=Q.filter((X)=>X.tier==="critical").map((X)=>({packageName:X.packageName,packagePath:X.packagePath,hasBuildScript:X.hasBuildScript,hasTypecheckScript:X.hasTypecheckScript,hasLintScript:X.hasLintScript,hasTestScript:X.hasTestScript,usesPassWithNoTests:X.usesPassWithNoTests,testFileCount:X.testFileCount}));return{findings:Z,criticalPackages:B}}function S5($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function C5($,W,j,Q){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:Q,context:{findings:[]}};let Z=W.filter((B)=>{return B.tier==="critical"||j.has(B.code)});return{category:"workspace",name:$,status:Z.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:S5(W),context:{findings:W}}}async function E5($,W){let j=await h0($,W.workspaceRoot);if(!j)return[];let Q=await w5($,W.workspaceRoot,j),Z=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),B=Q.findings.filter((q)=>Z.has(q.code)),X=Q.findings.filter((q)=>q.code==="tests-without-test-script"),Y=Q.findings.filter((q)=>q.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:B.length>0?"fail":"pass",message:B.length>0?`${B.length} critical package gate failure(s)`:`All ${Q.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:B.length>0?S5(B):W.verbose?`Policy: ${T$(W.workspaceRoot)}`:void 0,context:{policyPath:T$(W.workspaceRoot),criticalPackages:Q.criticalPackages,findings:B}},C5("Package Test Scripts",X,new Set,"All tested packages expose a test script"),C5("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var t8=["src/contracts","contracts","src/specs","specs"];async function H1($,W){let j=[];return j.push(s8(W)),j.push(await e8($,W)),j.push(await $9($,W)),j.push(await W9($,W)),j.push(await Q9($,W)),j.push(...await E5($,W)),j}function s8($){if($.isMonorepo){let W=$.packageName?` in package "${$.packageName}"`:"",j=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${W}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${j}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function e8($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let Q of j){let Z=$.join(Q,"package.json");if(await $.exists(Z))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.isMonorepo?`Found at: ${Q}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function $9($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],Q=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of t8){let q=$.join(X,Y);if(await $.exists(q)){let A=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${A} level`:void 0}}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let Z=W.isMonorepo?"src/contracts":"src/contracts",B=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Z}/${B} to organize your specs`,fix:{description:`Create ${Z}/ directory${B}`,apply:async()=>{try{let X=$.join(Q,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Z}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function W9($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],Q=W.isMonorepo?W.packageRoot:W.workspaceRoot,Z=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:Q});if(Z.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Z.length} contract file(s)${X}`,details:W.verbose?Z.slice(0,5).join(", "):void 0}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:W.isMonorepo?`No contract files found in package "${W.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function j9($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let Q=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(Q))return{path:Q,root:W.packageRoot,level:"package"}}let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{path:j,root:W.workspaceRoot,level:"workspace"};return null}async function Q9($,W){try{let j=await j9($,W);if(!j)return{category:"workspace",name:"Output Directory",status:"skip",message:W.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let Q=await $.readFile(j.path),Z=JSON.parse(Q),B=Z.outputDir??"./src",X=$.join(j.root,B),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${B}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let A=B==="./src"||B==="src",H=Array.isArray(Z.packages)&&Z.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&A&&(H||j.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:W.verbose?`Resolved default output to packages via ${j.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${B}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${B} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${B}`}}catch(V){return{success:!1,message:`Failed: ${V instanceof Error?V.message:String(V)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var M5=["cli","config","mcp","deps","docs","workspace","ai","layers"],N5={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var Z9={checks:{runCliChecks:Q1,runConfigChecks:Z1,runMcpChecks:A1,runDepsChecks:B1,runDocChecks:X1,runWorkspaceChecks:H1,runAiChecks:j1,runLayerChecks:q1},workspace:{findWorkspaceRoot:R,findPackageRoot:k,isMonorepo:c$,getPackageName:L$}},B9={confirm:async()=>!1,input:async()=>""};async function R5($,W,j=B9,Q=Z9){let{fs:Z,logger:B}=$,X=W.categories??M5,{checks:Y,workspace:q}=Q,A=q.findWorkspaceRoot(W.workspaceRoot),H=q.findPackageRoot(W.workspaceRoot),V=q.isMonorepo(A),G=V?q.getPackageName(H):void 0,z={workspaceRoot:A,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let L=G?` (package: ${G})`:"";B.info(`Detected monorepo${L}`)}let J=[];for(let L of X){if(W.skipAi&&L==="ai")continue;B.info(`Checking ${N5[L]}...`);let I=await X9(L,Z,z,j,Y);for(let U of I){if(U.fix&&(U.status==="fail"||U.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${U.name}"? ${U.fix.description}`)){B.info(`Applying fix: ${U.fix.description}`);let C=await U.fix.apply();if(C.success)B.info(`\u2713 ${C.message}`),U.status="pass",U.message=`Fixed: ${C.message}`,U.fix=void 0;else B.warn(`\u2717 ${C.message}`)}}J.push(U)}}let K=J.filter((L)=>L.status==="pass").length,_=J.filter((L)=>L.status==="warn").length,w=J.filter((L)=>L.status==="fail").length,b=J.filter((L)=>L.status==="skip").length;return{checks:J,passed:K,warnings:_,failures:w,skipped:b,healthy:w===0}}async function X9($,W,j,Q,Z){switch($){case"cli":return Z.runCliChecks(W,j);case"config":return Z.runConfigChecks(W,j);case"mcp":return Z.runMcpChecks(W,j);case"deps":return Z.runDepsChecks(W,j);case"docs":return Z.runDocChecks(W,j);case"workspace":return Z.runWorkspaceChecks(W,j);case"ai":return Z.runAiChecks(W,j,Q);case"layers":return Z.runLayerChecks(W,j);default:return[]}}function iV($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("\u2713 All checks passed!");else W.push("\u2717 Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
631
- `)}function aV($){let j=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)j+=`
632
- ${$.details}`;if($.fix)j+=`
633
- Fix available: ${$.fix.description}`;return j}async function V1($,W){let j=[],Q=W.workspaceRoot??process.cwd(),Z=await R5($,{workspaceRoot:Q,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let B of Z.checks)if(B.status==="fail")j.push({ruleId:`doctor-${B.category}-${B.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${B.name}: ${B.message}`,category:"doctor",context:{details:B.details,...B.context??{}}});else if(B.status==="warn")j.push({ruleId:`doctor-${B.category}-${B.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${B.name}: ${B.message}`,category:"doctor",context:{details:B.details,...B.context??{}}});return j}B$();import{mkdtemp as U9,rm as _9}from"fs/promises";import{tmpdir as L9}from"os";import p$ from"path";import K9 from"path";import{packageDocBlocks as q9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as A9,convertSpecToDocBlock as H9,extractModuleDocData as V9,loadSpecFromSource as G9,scanAllSpecsFromSource as z9,scanSpecSource as J9}from"@contractspec/module.workspace";import z1 from"path";import{dirname as F5,sep as u0}from"path";class G1{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let W of $){let j;if(W.specType==="app-config")j="app-config";else if(W.specType==="example")j="example";else if(W.specType==="feature")j="feature";if(j&&W.key){let Q=F5(W.filePath);this.modules.push({type:j,key:W.key,dirPath:Q})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let W=F5($),j=this.modules.filter((Q)=>{let Z=Q.dirPath.endsWith(u0)?Q.dirPath:Q.dirPath+u0;return(W.endsWith(u0)?W:W+u0).startsWith(Z)||W===Q.dirPath});if(j.length===0)return;return j.sort((Q,Z)=>{let B={"app-config":3,example:2,feature:1},X=B[Q.type],Y=B[Z.type];if(X!==Y)return Y-X;return Z.dirPath.length-Q.dirPath.length}),j[0]}}async function T5($,W,j){let{fs:Q,logger:Z}=j,B=[];if(Z.info(`Generating docs for ${$.length} files...`),W.outputDir)await Q.mkdir(W.outputDir);let X=new G1(j),Y=[];for(let A of $)try{let H=await Q.readFile(A),V=z9(H,A);if(V.length>0)Y.push(...V);else{let G=J9(H,A);if(G.specType!=="unknown")Y.push(G)}}catch(H){}X.initialize(Y);let q=await v5($,j);for(let A of q)if(B.push(A.entry.block),Z.debug(`Loaded authored doc ${A.entry.id}`),W.outputDir)await x5(A.entry.block,A.filePath,W.outputDir,X,Q);for(let A of $)try{let H=await G9(A);if(!H?.length){Z.warn(`Could not parse spec from ${A}`);continue}for(let V of H){let G=H9(V,{rootPath:W.rootPath});if(B.push(G),Z.debug(`Generated doc for ${G.id}`),!W.outputDir)continue;await x5(G,A,W.outputDir,X,Q)}}catch(H){Z.error(`Error processing ${A}: ${H instanceof Error?H.message:String(H)}`)}if(W.outputDir)Z.info(`Wrote ${B.length} doc files to ${W.outputDir}`);return{blocks:B,count:B.length}}async function qG($,W){return(await v5($,W)).map(({entry:Q})=>Q.block)}function AG($,W){return q9(A9({packageName:$,srcRoot:W}))}async function v5($,W){let j=[...new Set($)].sort((Z,B)=>Z.localeCompare(B)),Q=[];for(let Z of j){let B=await W.fs.readFile(Z),X=Z.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),Y=V9(B,Z,X);for(let q of Y.entries)Q.push({entry:q,filePath:Z})}return Q}async function x5($,W,j,Q,Z){let B=Q.resolve(W),X=B?z1.join(j,B.key):z1.join(j,"_common");await Z.mkdir(X);let Y=z1.join(X,`${$.id}.md`),q=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
634
-
635
- ${$.body}`;await Z.writeFile(Y,q)}async function y5($,W,j,Q,Z={}){let B=await $.fs.exists(W),X=Z.scanAllSpecs?Z.specPattern:Z.specPattern??(B?"contracts/**/*.ts":"**/*.ts"),Y=await h($,{cwd:Z.specSearchRoot,pattern:X});if(Y.length===0)return{specsCount:0,docsCount:0};let q=Y.map((V)=>V.filePath),A=K9.join(j,"docs"),H=await T5(q,{outputDir:A,format:"markdown",rootPath:Q},$);return{specsCount:Y.length,docsCount:H.count}}async function d0($,W,j,Q={}){let Z=await U9(p$.join(L9(),"contractspec-drift-"));try{await y5($,W,Z,Q.rootPath,Q.generation);let B=[],X=await import("fs/promises");async function Y(G){let z=await X.readdir(G,{withFileTypes:!0}),J=[];for(let K of z){let _=p$.resolve(G,K.name);if(K.isDirectory())J.push(...await Y(_));else J.push(_)}return J}let q=async(G)=>{if(!await X.stat(G).catch(()=>!1))return[];return(await Y(G)).map((J)=>p$.relative(G,J)).sort()},A=await q(Z),H=await q(j),V=new Set([...A,...H]);for(let G of V){if(!H.includes(G)){B.push(G);continue}if(!A.includes(G)){B.push(G);continue}let z=await X.readFile(p$.join(Z,G)),J=await X.readFile(p$.join(j,G));if(!z.equals(J))B.push(G)}return{hasDrift:B.length>0,files:B}}finally{await _9(Z,{recursive:!0,force:!0})}}async function J1($,W){let{fs:j,logger:Q}=$,Z=[],B=await a(j);if(!B.outputDir)return Q.info("No outputDir configured, skipping drift checks"),Z;let X="./contracts",Y=B.outputDir;if(!await j.exists(Y))return Q.info("Generated directory does not exist, skipping drift checks"),Z;try{let q=await d0($,X,Y);if(q.hasDrift)for(let A of q.files)Z.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${A}`,category:"drift",file:`${Y}/${A}`,context:{file:A}})}catch(q){Q.warn("Drift detection failed",{error:q instanceof Error?q.message:String(q)})}return Z}B$();function I9($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function O9($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}async function n0($,W,j,Q={}){let{fs:Z}=W,B=[],X=[],Y=$.key??Z.basename($.filePath).replace(/\.[jt]s$/,""),q=Q.outputDir??j.outputDir??"./src",A=I9(Y),H={};if($.specType==="operation")H.handlerPath=Z.join(q,"handlers",`${A}.handler.ts`),H.handlerTestPath=Z.join(q,"handlers",`${A}.handler.test.ts`);if($.specType==="presentation")H.componentPath=Z.join(q,"components",`${A}.tsx`),H.componentTestPath=Z.join(q,"components",`${A}.test.tsx`);if($.specType==="form")H.formPath=Z.join(q,"forms",`${A}.form.tsx`),H.formTestPath=Z.join(q,"forms",`${A}.form.test.tsx`);if(Q.checkHandlers&&H.handlerPath)if(!await Z.exists(H.handlerPath))B.push(`Missing handler file: ${H.handlerPath}`);else{let G=await Z.readFile(H.handlerPath),z=`${O9(Y.split(".").pop()??Y)}Spec`,J=/ContractHandler<\s*typeof\s+\w+\s*>/.test(G),K=new RegExp(`typeof\\s+${z}\\b`).test(G);if(!J)X.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${H.handlerPath}`);else if(!K)X.push(`Handler ContractHandler typing does not reference expected spec var (${z}): ${H.handlerPath}`)}if(Q.checkTests){let V=[H.handlerTestPath,H.componentTestPath,H.formTestPath].filter((G)=>typeof G==="string");for(let G of V)if(!await Z.exists(G))B.push(`Missing test file: ${G}`)}return{valid:B.length===0,errors:B,warnings:X,expected:H}}async function K1($,W){let{fs:j}=$,Q=[],Z=await a(j);for(let B of W){if(B.specType!=="operation")continue;let X=await n0(B,{fs:j},Z,{checkHandlers:!0,outputDir:Z.outputDir});for(let Y of X.errors)Q.push({ruleId:"handler-missing",severity:"warning",message:Y,category:"handlers",file:B.filePath});for(let Y of X.warnings)Q.push({ruleId:"handler-warning",severity:"warning",message:Y,category:"handlers",file:B.filePath})}return Q}B$();import{createHash as M9}from"crypto";import N9 from"path";var i$={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},b9={".handler.ts":"handler",".handler.tsx":"handler",".service.ts":"service",".service.tsx":"service",".test.ts":"test",".test.tsx":"test",".spec.ts":"test",".spec.tsx":"test",".component.tsx":"component",".tsx":"component",".form.tsx":"form",".hook.ts":"hook",".hook.tsx":"hook"};function w9($){let W=$.toLowerCase();for(let[j,Q]of Object.entries(b9))if(W.endsWith(j))return Q;if(W.includes("/handlers/"))return"handler";if(W.includes("/services/"))return"service";if(W.includes("/components/"))return"component";if(W.includes("/forms/"))return"form";if(W.includes("/hooks/"))return"hook";if(W.includes("/__tests__/"))return"test";return"other"}function P5($,W){let j=[],Q=new Set,Z=(G,z,J)=>{let K=`${G}:${z}`;if(Q.has(K))return;Q.add(K),j.push({filePath:W,specKey:G,referenceType:z,lineNumber:J,inferredType:w9(W)})},B=(G)=>{return $.substring(0,G).split(`
636
- `).length},X,Y=new RegExp(i$.contractHandler);while((X=Y.exec($))!==null)if(X[1])Z(X[1],"handler",B(X.index));let q=new RegExp(i$.typeofSpec);while((X=q.exec($))!==null)if(X[1])Z(X[1],"typeof",B(X.index));let A=new RegExp(i$.namedImport);while((X=A.exec($))!==null){let z=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(z)for(let J of z)Z(J,"import",B(X.index))}let H=new RegExp(i$.defaultImport);while((X=H.exec($))!==null)if(X[1])Z(X[1],"import",B(X.index));let V=new RegExp(i$.specAssignment);while((X=V.exec($))!==null)if(X[1])Z(X[1],"unknown",B(X.index));return j}var m5=["**/*.ts(x)"];async function c0($,W,j={}){let{fs:Q}=W,Z=j.includePatterns??m5,B=j.excludePatterns??[...new Set([..._$,...U$])],X=[];for(let Y of Z){let q=await Q.glob({pattern:Y,ignore:B});for(let A of q)try{let H=await Q.readFile(A),G=P5(H,A).filter((z)=>z.specKey===$);X.push(...G)}catch{}}return X}async function xG($,W={}){let{fs:j}=$,Q=W.includePatterns??m5,Z=W.excludePatterns??[...new Set([..._$,...U$])],B=new Map;for(let X of Q){let Y=await j.glob({pattern:X,ignore:Z});for(let q of Y)try{let A=await j.readFile(q),H=P5(A,q);for(let V of H){let G=B.get(V.specKey)??[];G.push(V),B.set(V.specKey,G)}}catch{}}return B}function C9($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function k5($,W,j){let Q=C9(W),Z=[];if($==="operation")Z.push({path:`${j}/handlers/${Q}.handler.ts`,type:"handler"}),Z.push({path:`${j}/handlers/${Q}.handler.test.ts`,type:"test"});if($==="presentation")Z.push({path:`${j}/components/${Q}.tsx`,type:"component"}),Z.push({path:`${j}/components/${Q}.test.tsx`,type:"test"});if($==="form")Z.push({path:`${j}/forms/${Q}.form.tsx`,type:"form"}),Z.push({path:`${j}/forms/${Q}.form.test.tsx`,type:"test"});if($==="event")Z.push({path:`${j}/handlers/${Q}.handler.ts`,type:"handler"}),Z.push({path:`${j}/handlers/${Q}.handler.test.ts`,type:"test"});return Z}import{Node as d,Project as S9,SyntaxKind as E9}from"ts-morph";function g5($){let W=[],Q=new S9({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Z=(q)=>{if(!d.isObjectLiteralExpression(q))return;let A=q.getProperty("implementations");if(A&&d.isPropertyAssignment(A)){let H=A.getInitializer();if(H&&d.isArrayLiteralExpression(H)){for(let V of H.getElements())if(d.isObjectLiteralExpression(V)){let G,z,J,K=V.getProperty("path");if(K&&d.isPropertyAssignment(K)){let b=K.getInitializer();if(d.isStringLiteral(b))G=b.getLiteralText()}let _=V.getProperty("type");if(_&&d.isPropertyAssignment(_)){let b=_.getInitializer();if(d.isStringLiteral(b))z=b.getLiteralText()}let w=V.getProperty("description");if(w&&d.isPropertyAssignment(w)){let b=w.getInitializer();if(d.isStringLiteral(b))J=b.getLiteralText()}if(G&&z)W.push({path:G,type:z,description:J})}}}},B=Q.getDescendantsOfKind(E9.CallExpression);for(let q of B){let A=q.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(A)){let H=q.getArguments();if(H.length>0&&d.isObjectLiteralExpression(H[0]))return Z(H[0]),W}}let X=Q.getVariableStatements();for(let q of X)if(q.isExported())for(let A of q.getDeclarations()){let H=A.getInitializer();if(H&&d.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Z(H),W}}let Y=Q.getExportAssignment((q)=>!q.isExportEquals());if(Y){let q=Y.getExpression();if(d.isObjectLiteralExpression(q))Z(q);else if(d.isAsExpression(q)&&d.isObjectLiteralExpression(q.getExpression()))Z(q.getExpression())}return W}function h5($){if($.length===0)return"missing";let W=$.filter((Z)=>Z.exists),j=$.filter((Z)=>Z.type!=="test");if(W.filter((Z)=>Z.type!=="test").length===0)return"missing";if($.every((Z)=>Z.exists))return"implemented";return"partial"}function mG($){let W=$.filter((Z)=>Z.status==="implemented").length,j=$.filter((Z)=>Z.status==="partial").length,Q=$.filter((Z)=>Z.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:Q,coverage:$.length>0?Math.round(W/$.length*100):100}}var R9={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function f5($){return M9("sha256").update($).digest("hex")}async function D9($,W,j,Q={},Z){let B={...R9,...Q},X=B.computeHashes?f5($.sourceBlock||""):void 0,Y=$.key??N9.basename($.filePath).replace(/\.[jt]s$/,""),q=$.version??"1.0.0",{fs:A}=W,H=[],V=new Set,G=async(J,K,_,w)=>{if(V.has(J))return;V.add(J);let b=await A.exists(J),L=void 0,I=void 0;if(b&&B.computeHashes)try{L=await A.readFile(J),I=f5(L)}catch{}H.push({path:J,type:K,source:_,exists:b,implementationSourceContent:L,implementationSourceHash:I,description:w})};if(B.includeExplicit&&$.sourceBlock){if(Z)Z.suffixText="Discover explicit implementations";let J=g5($.sourceBlock);for(let K of J)await G(K.path,K.type,"explicit",K.description)}if(B.includeDiscovered){if(Z)Z.suffixText="Discover implementations";let J=await c0(Y,W,B);for(let K of J){if(K.filePath===$.filePath)continue;await G(K.filePath,K.inferredType,"discovered")}}if(B.includeConvention){if(Z)Z.suffixText="Discover implementations based on conventions";let J=B.outputDir??j.outputDir??"./src",K=k5($.specType,Y,J);for(let{path:_,type:w}of K)await G(_,w,"convention")}if(Z)Z.suffixText="Determine implementation status";let z=h5(H);return{specKey:Y,specVersion:q,specPath:$.filePath,specType:$.specType,implementations:H,status:z,specHash:X}}async function u5($,W,j,Q={},Z){let B=[];for(let X of $){if(Z)Z.text=`Resolving implementation... (${B.length}/${$.length})`;try{let Y=await D9(X,W,j,Q,Z);B.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return B}async function U1($,W,j){let{fs:Q}=$,Z=[],B=await a(Q),X=j.implementation??{},Y=W.filter((A)=>A.specType==="operation"),q=await u5(Y,{fs:Q},B,{computeHashes:X.useCache??!0});for(let A of q){if(X.requireImplemented&&A.status==="missing")Z.push({ruleId:"impl-missing",severity:"error",message:`Spec ${A.specKey} has no implementation`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,specVersion:A.specVersion,status:A.status}});else if(A.status==="missing")Z.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${A.specKey} has no implementation`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,specVersion:A.specVersion,status:A.status}});if(!X.allowPartial&&A.status==="partial"){let V=A.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Z.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${A.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,specVersion:A.specVersion,status:A.status,missingFiles:V}})}let H=A.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Z.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${A.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,missingTests:H.map((V)=>V.path)}})}return Z}import{isFeatureFile as T9,scanAllSpecsFromSource as v9,scanFeatureSource as y9}from"@contractspec/module.workspace";function F9($,W){return`${$}.v${W}`}function _1($,W,j,Q,Z,B={}){let{treatMissingAsError:X=!0}=B;if(!Q||Q.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],q=[],A=[];for(let H of Q){let V=F9(H.key,H.version);if(Z.has(V))Y.push(H);else if(q.push(H),X)A.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:q.length===0,foundTests:Y,missingTests:q,errors:A,specFile:$}}function d5($,W){return`${$}.v${W}`}function n5($,W){let j=new Map,Q=new Map,Z=[],B=[];for(let X of $){if(!X.key||!X.version)continue;let Y=d5(X.key,X.version);if(!X.testTarget){B.push(Y);continue}let{type:q,key:A,version:H}=X.testTarget,V=H??X.version,G=d5(A,V),z=x9(W,q);if(!z||!z.has(G)){Z.push(Y);continue}if(Q.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:Q,orphanedTests:Z,testsWithoutTarget:B}}function x9($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function o($,W){return`${$}.v${W}`}function P9(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function L1($,W){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[W]}async function l0($,W={}){let{fs:j,logger:Q}=$;Q.info("Starting integrity analysis...",{options:W});let Z=await j.glob({pattern:W.pattern,cwd:W.cwd}),B=P9(),X=[],Y=[];for(let U of Z){if((await j.stat(U)).isDirectory)continue;let C=await j.readFile(U);if(T9(U)){let S=y9(C,U);X.push(S)}else{let S=v9(C,U);for(let M of S)if(M.specType!=="unknown"&&M.specType!=="feature"){let u=L1(B,M.specType);if(u&&M.key&&M.version!==void 0){let l=o(M.key,M.version);u.set(l,{key:M.key,version:M.version,file:M.filePath,type:M.specType,stability:M.stability,testTarget:M.testTarget,testCoverage:M.testCoverage})}}}}let q=W.featureKey?X.filter((U)=>U.key===W.featureKey):X,A=new Set;for(let U of q){for(let O of U.operations){let C=o(O.key,O.version);if(A.add(`operation:${C}`),!B.operations.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"operation",ref:O})}for(let O of U.events){let C=o(O.key,O.version);if(A.add(`event:${C}`),!B.events.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"event",ref:O})}for(let O of U.presentations){let C=o(O.key,O.version);if(A.add(`presentation:${C}`),!B.presentations.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"presentation",ref:O})}for(let O of U.experiments){let C=o(O.key,O.version);if(A.add(`experiment:${C}`),!B.experiments.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"experiment",ref:O})}for(let O of U.capabilities.provides){let C=o(O.key,O.version);if(A.add(`capability:${C}`),!B.capabilities.has(C))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"capability",ref:O})}for(let O of U.capabilities.requires){let C=o(O.key,O.version);A.add(`capability:${C}`)}for(let O of U.opToPresentationLinks){let C=o(O.op.key,O.op.version),S=o(O.pres.key,O.pres.version);if(!B.operations.has(C))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${O.op.key}.v${O.op.version} not found`,file:U.filePath,featureKey:U.key,specType:"operation",ref:O.op});if(!B.presentations.has(S))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${O.pres.key}.v${O.pres.version} not found`,file:U.filePath,featureKey:U.key,specType:"presentation",ref:O.pres})}if(U.presentationsTargets)for(let O of U.presentationsTargets){let C=o(O.key,O.version);if(!B.presentations.has(C))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"presentation",ref:{key:O.key,version:O.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let U of V){let O=L1(B,U);if(!O)continue;for(let[C,S]of O)if(!A.has(`${U}:${C}`))H.push(S),Y.push({severity:"warning",type:"orphaned",message:`${U} ${S.key}.v${S.version} is not linked to any feature`,file:S.file,specKey:S.key,specType:S.type})}let G=[];for(let[,U]of B.testSpecs)G.push({filePath:U.file,specType:"test-spec",key:U.key,version:U.version,testTarget:U.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let z=n5(G,B);for(let U of q)for(let O of U.opToPresentationLinks){let C=o(O.op.key,O.op.version),S=z.targetToTests.get(C),M=!1,u=!1;if(S)for(let l of S){let y=B.testSpecs.get(l);if(y?.testCoverage){if(y.testCoverage.hasSuccess)M=!0;if(y.testCoverage.hasError)u=!0}}if(!S||!M||!u){let l=[];if(!M)l.push("success scenario");if(!u)l.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${O.op.key}.v${O.op.version} linked to presentation requires tests covering: ${l.join(", ")}`,file:U.filePath,featureKey:U.key,specType:"operation",ref:O.op})}}let J={},K=0;for(let U of V){let O=L1(B,U);if(!O)continue;let C=O.size,S=0,M=0,u=W.requireTestsFor?.includes(U);for(let[l,y]of O){if(A.has(`${U}:${l}`))S++;if(u){let F=o(y.key,y.version),d$=z.targetToTests.has(F),K6=`${y.key}.test`,U6=B.testSpecs.has(o(K6,y.version));if(!d$&&!U6)M++,K++,Y.push({severity:"warning",type:"missing-test",message:`${U} ${y.key}.v${y.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:y.file,specKey:y.key,specType:y.type})}}J[U]={total:C,covered:S,orphaned:C-S,missingTest:u?M:0}}let _=Object.values(J).reduce((U,O)=>U+O.total,0),w=Object.values(J).reduce((U,O)=>U+O.covered,0),b={total:_,linkedToFeature:w,orphaned:_-w,missingTest:K,byType:J},I=!Y.some((U)=>U.severity==="error");return Q.info("Integrity analysis complete",{features:X.length,totalSpecs:_,orphaned:H.length,issues:Y.length,healthy:I}),{inventory:B,features:q,coverage:b,issues:Y,orphanedSpecs:H,healthy:I}}function jz($){let W=[];for(let j of Object.values($))for(let Q of j.values())W.push(Q);return W}function Qz($,W){return $.filter((j)=>j.type===W)}function Zz($,W){return $.filter((j)=>j.severity===W)}async function I1($,W){let j=[],Q=await l0($,{pattern:W.pattern,all:!0});for(let Z of Q.issues)j.push({ruleId:`integrity-${Z.type}`,severity:Z.severity==="error"?"error":"warning",message:Z.message,category:"integrity",file:Z.file,context:{specKey:Z.specKey,specType:Z.specType,featureKey:Z.featureKey,ref:Z.ref}});return j}async function O1($,W){let j=[],Q=await k0($,{});for(let[Z,B]of Q.inventory.features){if(!B.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:B.filePath,context:{key:Z}});if(!B.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Z}' missing 'owners' field`,category:"layers",file:B.filePath,context:{key:Z}});if(B.operations.length===0&&B.events.length===0&&B.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Z}' has no operations, events, or presentations`,category:"layers",file:B.filePath,context:{key:Z}})}for(let[Z,B]of Q.inventory.examples){if(!B.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Z}' missing 'packageName' in entrypoints`,category:"layers",file:B.filePath,context:{key:Z}});if(!B.surfaces.templates&&!B.surfaces.sandbox.enabled&&!B.surfaces.studio.enabled&&!B.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Z}' has no enabled surfaces`,category:"layers",file:B.filePath,context:{key:Z}})}for(let Z of Q.inventory.workspaceConfigs.values())if(!Z.valid)for(let B of Z.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${B}`,category:"layers",file:Z.file});return j}B$();import{ContractsrcSchema as m9,DEFAULT_CONTRACTSRC as r0}from"@contractspec/lib.contracts-spec/workspace-config";var k9=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,g9=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,h9=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,f9=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,u9=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,d9=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,n9=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function o0($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function c9($,W){let j=$.replaceAll("\\","/"),Q=new Set(["contracts","features",...o0(W?.conventions?.operations),...o0(W?.conventions?.events),...o0(W?.conventions?.presentations),...o0(W?.conventions?.forms)]);return j.split("/").some((Z)=>Q.has(Z))}function l9($,W,j){let Q=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(Q))return!1;if(Q.includes("/node_modules/")||Q.includes("/dist/")||u9.test(Q)||f9.test(Q)||Q.endsWith(".d.ts")||Q.endsWith(".test.ts")||Q.endsWith(".spec.ts"))return!1;if(W.has(Q))return!1;if(c9(Q,j))return!1;return k9.test(Q)}function c5($){return $.replaceAll("\\","/").match(d9)?.[1]??null}function r9($){let W=$.split(`
637
- `).map((j)=>j.trim()).filter((j)=>j.length>0&&!j.startsWith("//")&&!j.startsWith("/*")&&!j.startsWith("*")&&!j.startsWith("*/"));return W.length>0&&W.every((j)=>j.startsWith("import ")||j.startsWith("export *")||j.startsWith("export {")||j.startsWith("export type {")||j==="'use client';"||j==='"use client";'||j==="'use server';"||j==='"use server";')}function o9($){if(!$)return r0;let W=m9.safeParse($),j=W.success?W.data:{};return{...r0,...j,conventions:{...r0.conventions,...j.conventions??{}},ci:{...r0.ci,...j.ci??{}}}}async function b1($,W){let{fs:j,logger:Q}=$,Z=[],B=W.config?o9(W.config):await a(j),X=await h({fs:j},{config:B}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),q=new Set(X.map((H)=>c5(H.filePath)).filter((H)=>Boolean(H))),A=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of A){if(!l9(H,Y,B))continue;try{let V=await j.readFile(H);if(r9(V))continue;let G=c5(H);if(!(G!==null&&n9.test(G)&&q.has(G))&&!h9.test(V))continue;if(g9.test(V))continue;Z.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:H})}catch(V){Q.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Z}import{validateSpecStructure as p9}from"@contractspec/module.workspace";async function w1($){let W=[];for(let j of $){let Q=p9(j);for(let Z of Q.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Z,category:"structure",file:j.filePath});for(let Z of Q.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Z,category:"structure",file:j.filePath})}return W}async function C1($){let W=[],j=new Map,Q=new Map;for(let Z of $){if(!Z.key||!Z.version)continue;if(Z.specType==="test-spec"){let B=`${Z.key}.v${Z.version}`;j.set(B,{key:Z.key,version:Z.version,file:Z.filePath,type:"test-spec"})}if(Z.testRefs&&Z.testRefs.length>0){if(!Q.has(Z.filePath))Q.set(Z.filePath,[]);Q.get(Z.filePath)?.push({key:Z.key,version:Z.version,testRefs:Z.testRefs})}}for(let[Z,B]of Q)for(let X of B){if(!X.testRefs)continue;let Y=_1(Z,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let q of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:q,category:"test-refs",file:Z,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}B$();async function S1($,W){let{fs:j}=$,Q=[],Z=await a(j);for(let B of W){if(B.specType!=="operation")continue;let X=await n0(B,{fs:j},Z,{checkTests:!0,outputDir:Z.outputDir});for(let Y of X.errors)Q.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:B.filePath});for(let Y of X.warnings)Q.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:B.filePath})}return Q}function c($,W,j){let Q={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},Z=W.filter((Y)=>Y.severity==="error").length,B=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:Q[$],errors:Z,warnings:B,notes:X,passed:Z===0,durationMs:j}}async function l5($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),Q=j.match(/^ref: (.+)$/m);if(Q){let B=Q[1]?.replace("refs/heads/",""),X=`.git/${Q[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:B};return{branch:B}}return{commitSha:j.trim()}}catch{return{}}}function r5($){let W=$.config?.ci?.checks,j=W&&W.length>0?[...W]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)j.push("handlers");if($.checkTests)j.push("tests");if($.implementation)j.push("implementation");if($.checkDrift)j.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return j.filter((Q)=>!$.skip?.includes(Q));return j}async function hz($,W={}){let j=Date.now(),{fs:Q,logger:Z}=$,B=[],X=[],Y=r5(W);Z.info("Starting CI checks...",{checks:Y});let q=await h($,{pattern:W.pattern,type:["feature","test-spec"]});if(Y.includes("structure")){let K=Date.now(),_=await w1(q);B.push(..._),X.push(c("structure",_,Date.now()-K))}if(Y.includes("integrity")){let K=Date.now(),_=await I1($,W);B.push(..._),X.push(c("integrity",_,Date.now()-K))}if(Y.includes("deps")){let K=Date.now(),_=await $1($,W);B.push(..._),X.push(c("deps",_,Date.now()-K))}if(Y.includes("doctor")){let K=Date.now(),_=await V1($,W);B.push(..._),X.push(c("doctor",_,Date.now()-K))}if(Y.includes("docs")){let K=Date.now(),_=await W1($,W);B.push(..._),X.push(c("docs",_,Date.now()-K))}if(Y.includes("policy")){let K=Date.now(),_=await b1($,W);B.push(..._),X.push(c("policy",_,Date.now()-K))}if(Y.includes("handlers")||W.checkHandlers){let K=Date.now(),_=await K1($,q);B.push(..._),X.push(c("handlers",_,Date.now()-K))}if(Y.includes("tests")||W.checkTests){let K=Date.now(),_=await S1($,q);B.push(..._),X.push(c("tests",_,Date.now()-K))}if(Y.includes("test-refs")){let K=Date.now(),_=await C1(q);B.push(..._),X.push(c("test-refs",_,Date.now()-K))}if(Y.includes("coverage")){let K=Date.now(),_=await eW($,q,W);B.push(..._),X.push(c("coverage",_,Date.now()-K))}if(Y.includes("implementation")){let K=Date.now(),_=await U1($,q,W);B.push(..._),X.push(c("implementation",_,Date.now()-K))}if(Y.includes("layers")){let K=Date.now(),_=await O1($,W);B.push(..._),X.push(c("layers",_,Date.now()-K))}if(Y.includes("drift")){let K=Date.now(),_=await J1($,W);B.push(..._),X.push(c("drift",_,Date.now()-K))}let A=B.filter((K)=>K.severity==="error").length,H=B.filter((K)=>K.severity==="warning").length,V=B.filter((K)=>K.severity==="note").length,G=W.failOnWarnings?A===0&&H===0:A===0,z=await l5(Q),J={success:G,totalErrors:A,totalWarnings:H,totalNotes:V,issues:B,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...z};return Z.info("CI checks complete",{success:G,errors:A,warnings:H,durationMs:J.durationMs}),J}var uz=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],dz={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function oz($,W={}){let{fs:j,logger:Q}=$,Z=(W.outputDir??"./src").replace(/\\/g,"/"),B=["generated/**","dist/**",".turbo/**"],X=[`${Z}/handlers/**/*.handler.ts`,`${Z}/handlers/**/*.handler.test.ts`,`${Z}/components/**/*.tsx`,`${Z}/components/**/*.test.tsx`,`${Z}/forms/**/*.form.tsx`,`${Z}/forms/**/*.form.test.tsx`,`${Z}/**/*.runner.ts`,`${Z}/**/*.renderer.tsx`],Y=W.generatedOnly?[...B,...X]:[...B,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],q=await j.glob({patterns:Y,ignore:["node_modules/**"]}),A=[],H=[];for(let V of q)try{let G=await j.stat(V),z=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&z<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)Q.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),Q.info("clean.removed",{path:V,size:G.size});A.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:A,skipped:H}}B$();var K4={};P(K4,{writeReviewPacket:()=>f1,writeDecisionEnvelope:()=>j0,withBranch:()=>S$,verifyConnectMutation:()=>aZ,resolveWorkspace:()=>f,resolveStoragePaths:()=>$$,replayConnectDecision:()=>FZ,persistLatestArtifacts:()=>g1,persistDecisionArtifacts:()=>W0,normalizeEvalInput:()=>SZ,matchConfiguredPath:()=>a$,loadStoredDecision:()=>Q0,listStoredReviewPackets:()=>u1,listConnectReviewPackets:()=>xZ,isReviewCommand:()=>E1,isDeniedCommand:()=>M1,isAllowedCommand:()=>p0,initConnectWorkspace:()=>MZ,inferSurfaces:()=>e$,evaluateConnectDecision:()=>wZ,ensureStorage:()=>$0,defaultActor:()=>s$,decisionArtifactRefs:()=>P$,createConnectControlPlaneRuntime:()=>uZ,connectVerdictToPolicy:()=>v$,configuredThreshold:()=>b$,compileConnectPlanPacket:()=>d1,buildConnectContextPack:()=>k1,assessConnectPolicy:()=>t$,assertConnectEnabled:()=>p,artifactRef:()=>X$,appendAuditRecord:()=>h1,analyzeConnectImpact:()=>E$,CONTROL_PLANE_TRACE_GET_REF:()=>i0,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>a0,CONTROL_PLANE_PLAN_VERIFY_REF:()=>F1,CONTROL_PLANE_PLAN_COMPILE_REF:()=>D1,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>R1,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>w$,AGENT_APPROVALS_REF:()=>t0,ACP_TERMINAL_EXEC_REF:()=>s9,ACP_FS_ACCESS_REF:()=>t9});import i9 from"micromatch";function p($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function a$($,W,j){if(!j||j.length===0)return!1;let Q=W.replaceAll("\\","/");return i9.isMatch(Q,j,{contains:!0})}function b$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function p0($,W){return N1($.config.connect?.commands?.allow,W)}function E1($,W){return N1($.config.connect?.commands?.review,W)}function M1($,W){return N1($.config.connect?.commands?.deny,W)}function N1($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function p5($,W){if(W.length===0)return{state:"none"};for(let Q of W)if(M1($,Q))return{commandMatch:Q,state:"deny"};for(let Q of W)if(E1($,Q))return{commandMatch:Q,state:"review"};if(W.every((Q)=>p0($,Q)))return{state:"allow"};let j=W.find(a9);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((Q)=>!p0($,Q)),state:"unknown"}}function a9($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return o5(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return o5(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function o5($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var R1={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},D1={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},F1={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},i0={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},a0={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},w$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},t9={key:"acp.fs.access",version:"1.0.0",kind:"command"},s9={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},t0={key:"agent.approvals",version:"1.0.0",kind:"command"};function t$($,W){let j=W.touchedPaths.find((G)=>a$($,G,$.config.connect?.policy?.immutablePaths)),Q=W.touchedPaths.find((G)=>a$($,G,$.config.connect?.policy?.protectedPaths)),Z=W.touchedPaths.find((G)=>a$($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:B,state:X}=p5($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,q=W.impactAnalysis.driftFiles.length>0,A=e9({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:q,generatedPath:Boolean(Z),immutable:Boolean(j),protectedPath:Boolean(Q),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=$Z({breakingChange:W.impactAnalysis.breakingChange,commandMatch:B,commandState:X,contractDrift:q,protectedPath:Q,unknownPaths:W.impactAnalysis.unknownPaths}),V=v$(A);return{commandMatch:B,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Z,immutablePath:j,protectedPath:Q,requiredApprovals:V.requiresApproval?[{capability:w$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:A}}function v$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function e9($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(b$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(b$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(b$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(b$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(b$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(WZ)[0]??"permit"}function $Z($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function WZ($,W){return i5($)-i5(W)}function i5($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as OZ}from"crypto";var $4={};P($4,{formatPrComment:()=>a5,formatMinimalComment:()=>x1,formatJson:()=>s5,formatCheckRun:()=>t5,detectImpact:()=>C$,ImpactDetectionOverviewDocBlock:()=>YZ});function a5($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)j.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else j.push("\u2705 **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| \u2796 Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let Q=$.deltas.filter((B)=>B.severity==="breaking"),Z=$.deltas.filter((B)=>B.severity==="non_breaking");if(Q.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let B of Q)j.push(`- **${B.specKey}**: ${B.description}`);j.push("")}if(Z.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let B of Z)j.push(`- **${B.specKey}**: ${B.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let Q of $.addedSpecs)j.push(`- \`${Q.key}\` v${Q.version} (${Q.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let Q of $.removedSpecs)j.push(`- \`${Q.key}\` v${Q.version} (${Q.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### \u26A0\uFE0F Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let Q of W.drift.files)j.push(`- \`${Q}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### \u2705 No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
638
- `)}function x1($){if($.hasBreaking)return`\u274C **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`\u26A0\uFE0F **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"\u2705 **No contract impact**"}function t5($,W,j={}){let Q=j.key??"ContractSpec Impact",Z=j.failOnBreaking??!0,B,X;if($.hasBreaking)B=Z?"failure":"neutral",X=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)B="success",X=`Non-breaking changes (${$.summary.nonBreaking})`;else B="success",X="No contract impact";let Y=x1($);return{name:Q,headSha:W,conclusion:B,title:X,summary:Y,annotations:$.deltas.filter((q)=>q.severity==="breaking").slice(0,50).map((q)=>({path:q.path,startLine:1,endLine:1,annotationLevel:"failure",message:q.description,title:`Breaking: ${q.rule}`}))}}function s5($){let W={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((j)=>({type:j.rule,path:j.specKey,summary:j.description,severity:j.severity==="breaking"?"breaking":j.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(W,null,2)}import{classifyImpact as jZ,computeIoDiff as QZ,generateSnapshot as e5}from"@contractspec/module.workspace";async function C$($,W={}){let{fs:j,git:Q,logger:Z}=$,B=W.workspaceRoot??process.cwd();Z.info("Starting impact detection...",{baseline:W.baseline});let Y=(await j.glob({pattern:W.pattern??"**/*.{operation,event}.ts",cwd:B})).filter((z)=>!z.includes(".test.")&&!z.includes(".spec.")&&!z.includes("node_modules"));Z.debug(`Found ${Y.length} spec files`);let q=await ZZ(j,Y,B),A=e5(q),H;if(W.baseline){let z=await BZ(j,Q,Y,W.baseline,B);H=e5(z)}else H={version:"1.0.0",generatedAt:"",specs:[],hash:""};let V=XZ(H.specs,A.specs),G=jZ(H.specs,A.specs,V);return Z.info("Impact detection complete",{status:G.status,breaking:G.summary.breaking,nonBreaking:G.summary.nonBreaking}),{...G,workspaceRoot:B,specsAnalyzed:Y.length,baseRef:W.baseline}}async function ZZ($,W,j){let Q=[];for(let Z of W){let B=await $.readFile(Z);Q.push({path:Z,content:B})}return Q}async function BZ($,W,j,Q,Z){let B=[];for(let X of j)try{let Y=await W.showFile(Q,X);B.push({path:X,content:Y})}catch{}return B}function XZ($,W){let j=[],Q=new Map($.map((B)=>[`${B.key}@${B.version}`,B])),Z=new Map(W.map((B)=>[`${B.key}@${B.version}`,B]));for(let[B,X]of Z){let Y=Q.get(B);if(Y&&X.type==="operation"&&Y.type==="operation"){let q=QZ(Y.io,X.io);j.push(...q)}}return j}var YZ={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
639
- # Contract Impact Detection
640
-
641
- Automated detection and classification of breaking changes in ContractSpec APIs.
642
-
643
- ## Features
644
-
645
- - **Snapshot Generation**: Creates canonical, deterministic representations of contracts
646
- - **Deep Diff Engine**: Field-level comparison of input/output schemas
647
- - **Breaking Change Classification**: Automatic classification using 16 rules
648
- - **Multiple Output Formats**: JSON, Markdown, Text, GitHub Check Run
649
- - **GitHub Integration**: PR comments and check runs
650
- - **CLI Tool**: \`contractspec impact\` command
651
-
652
- ## Quick Start
653
-
654
- ### CLI Usage
655
-
656
- \`\`\`bash
657
- # Basic usage
658
- contractspec impact
659
-
660
- # Compare against specific baseline
661
- contractspec impact --baseline origin/main
662
-
663
- # Get JSON output
664
- contractspec impact --format json
665
- \`\`\`
666
-
667
- ### GitHub Action
668
-
669
- \`\`\`yaml
670
- - uses: lssm-tech/contractspec-action@v1
671
- with:
672
- mode: impact
673
- pr-comment: true
674
- fail-on-breaking: true
675
- \`\`\`
676
-
677
- ## Architecture
678
-
679
- The system consists of three layers:
680
-
681
- 1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
682
- 2. **Impact Service** (bundle package): Orchestration + Formatters
683
- 3. **Integrations**: CLI command + GitHub Action
684
- `,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as j4,readFileSync as Q4}from"fs";import{basename as qZ,join as T1,resolve as AZ}from"path";import{ContractsrcSchema as HZ,DEFAULT_CONTRACTSRC as VZ}from"@contractspec/lib.contracts-spec/workspace-config";function f($={}){let W=AZ($.cwd??process.cwd()),j=$.workspaceRoot??R(W),Q=$.packageRoot??k(W),Z=$.config??GZ(j,Q),B=zZ(Q,j);return{cwd:W,workspaceRoot:j,packageRoot:Q,config:Z,repoId:B,branch:"unknown"}}function S$($,W){return{...$,branch:W&&W.length>0?W:"unknown"}}function s$($,W){return W??{id:`cli:${$}`,type:"human"}}function e$($){let W=new Set;for(let j of $){if(j.includes("/cli-")||j.includes("/apps/cli-"))W.add("cli");if(j.includes("/contracts-spec/")||j.includes("/specs/"))W.add("contract");if(j.includes("/runtime/"))W.add("runtime");if(j.includes("/harness"))W.add("harness");if(j.includes("/ai-agent/"))W.add("agent");if(j.includes("/knowledge/"))W.add("knowledge");if(j.includes("/mcp/"))W.add("mcp")}if(W.size===0)W.add("runtime");return W.add("audit"),[...W].sort()}function GZ($,W){let j={...VZ};if($!==W)j=W4(j,T1($,".contractsrc.json"));return W4(j,T1(W,".contractsrc.json"))}function W4($,W){if(!j4(W))return $;try{let j=Q4(W,"utf-8"),Q=JSON.parse(j),Z=HZ.safeParse(Q);if(!Z.success)return $;return{...$,...Z.data}}catch{return $}}function zZ($,W){let j=T1($,"package.json");if(j4(j))try{let Q=JSON.parse(Q4(j,"utf-8"));if(Q.name)return Q.name}catch{}return qZ(W)}async function E$($,W){let j=await h({fs:$.fs},{config:W.workspace.config}),Q=new Map(j.filter((q)=>typeof q.key==="string").map((q)=>[q.key,q])),Z=W.touchedPaths.map((q)=>JZ($.fs,W.workspace,q,j,Q)),B=W.baseline!=null?await C$({...$,logger:$.logger??B4},{baseline:W.baseline,workspaceRoot:W.workspace.workspaceRoot}):void 0,X=await KZ($,W.workspace,W.touchedPaths),Y=m1([...Z.flatMap((q)=>q.contracts),...(B?.deltas??[]).map((q)=>({key:q.specKey,version:q.specVersion,kind:q.specType==="event"?"event":"command"}))]);return{breakingChange:B?.hasBreaking===!0,driftFiles:X,impactResult:B,impactedContracts:Y,pathImpacts:Z,unknownPaths:Z.filter((q)=>q.contracts.length===0).map((q)=>q.path)}}function JZ($,W,j,Q,Z){let B=$.resolve(W.workspaceRoot,j),X=P1(j),Y=Q.map((J)=>{let K=i($.relative(W.workspaceRoot,J.filePath));return{score:LZ(j,X,K,J.key),spec:J}}).filter((J)=>J.score>=45).sort((J,K)=>K.score-J.score).slice(0,3),q=Q.find((J)=>J.filePath===B),A=q?[{score:100,spec:q}]:Y,H=A.filter((J)=>typeof J.spec.key==="string").map((J)=>y1(J.spec.key,J.spec.version,J.spec.kind)),V=A.flatMap((J)=>[...J.spec.emittedEvents??[],...J.spec.policyRefs??[],...J.spec.testRefs??[]].map((K)=>Z.get(K.key)).filter(Boolean).map((K)=>y1(K.key,K.version,K.kind))),G=m1([...H,...V]),z=m1([{key:"connect.policy",version:"1.0.0",kind:"policy"},...A.flatMap((J)=>J.spec.policyRefs??[]).map((J)=>y1(J.key,J.version,"policy"))]);return{confidence:A[0]?.score===100?"exact":(A[0]?.score??0)>=70?"high":A.length>0?"medium":"none",contracts:G,path:j,policies:z,reasons:A.map((J)=>`${J.spec.key??J.spec.filePath} matched with score ${J.score}`),surfaces:e$([j])}}async function KZ($,W,j){let Q=UZ($.fs,W,j),Z=await Promise.all(Q.map(async(B)=>{let X=$.fs.resolve(W.packageRoot,B.comparisonRoot),Y=await d0({...$,logger:$.logger??B4},W.workspaceRoot,X,{generation:{scanAllSpecs:!0,specSearchRoot:W.workspaceRoot},rootPath:W.workspaceRoot}),q=B.filterPrefix&&B.filterPrefix!==B.comparisonRoot?i($.fs.relative(B.comparisonRoot,B.filterPrefix)):void 0;return Y.files.filter((A)=>q?i(A)===q||i(A).startsWith(`${q}/`):!0).map((A)=>i($.fs.join(B.comparisonRoot,A)))}));return[...new Set(Z.flat())].sort()}function UZ($,W,j){let Q=(W.config.connect?.policy?.generatedPaths??[]).map(IZ).filter(Boolean),Z=W.config.outputDir&&W.config.outputDir!=="./src"?i(W.config.outputDir):void 0,B=new Map;for(let X of j){let Y=i(X);if(Z&&Y.startsWith(Z))B.set(Z,{comparisonRoot:Z});for(let q of Q)if(Y.startsWith(q)){let A=_Z($,Z,q);B.set(`${A}::${q}`,{comparisonRoot:A,filterPrefix:q})}}return[...B.values()]}function _Z($,W,j){if(W&&j.startsWith(W))return W;return $.basename(j)==="docs"?i($.dirname(j)):j}function LZ($,W,j,Q){if(i($)===i(j))return 100;let Z=P1(j),B=P1(Q??""),X=Z4($)===Z4(j)?40:0,Y=v1($.split("/"),j.split("/"),5),q=v1(W,Z,5),A=v1(W,B,4);return X+Y+q+A}function v1($,W,j){let Q=new Set(W);return $.filter((Z)=>Q.has(Z)).length*j}function P1($){return i($).split(/[\/._-]+/).filter(Boolean)}function Z4($){return i($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function IZ($){return i($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function i($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function y1($,W,j){return{key:$,version:String(W??"1.0.0"),kind:j==="query"||j==="event"||j==="policy"||j==="capability"?j:"command"}}function m1($){return[...new Map($.map((W)=>[`${W.key}@${W.version}`,W])).values()]}var B4={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function k1($,W){let j=f(W);p(j),j=S$(j,await $.git.currentBranch());let Q=s$(W.taskId,W.actor),Z=await bZ($,j.workspaceRoot,W),B=await E$($,{baseline:W.baseline,touchedPaths:Z,workspace:j}),X=j.config.connect?.canonPacks??[];return{id:`connect.ctx_${OZ()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:Q,knowledge:X.map((Y)=>({spaceKey:Y.ref,category:"canonical",trustLevel:Y.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:B.impactedContracts,affectedSurfaces:B.pathImpacts.length>0?[...new Set(B.pathImpacts.flatMap((Y)=>Y.surfaces))].sort():e$(Z),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...X.map((Y)=>({key:Y.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...X.map((Y)=>({kind:"canon-pack",ref:Y.ref}))],acceptanceChecks:j.config.connect?.policy?.smokeChecks??[]}}async function bZ($,W,j){let Q=j.paths??[];if(Q.length>0)return Q.map((B)=>X4($.fs,W,B));if(!j.baseline)return[];return(await $.git.diffFiles(j.baseline)).map((B)=>X4($.fs,W,B))}function X4($,W,j){let Q=$.resolve(W,j);return $.relative(W,Q).replaceAll("\\","/")}import{resolve as M$}from"path";function $$($){let W=$.config.connect?.storage,j=M$($.packageRoot,W?.root??".contractspec/connect");return{root:j,contextPack:M$($.packageRoot,W?.contextPack??".contractspec/connect/context-pack.json"),planPacket:M$($.packageRoot,W?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:M$($.packageRoot,W?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:M$($.packageRoot,W?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:M$($.packageRoot,W?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:M$(j,"decisions")}}async function $0($,W){await $.mkdir(W.root),await $.mkdir(W.reviewPacketsDir),await $.mkdir(W.decisionsDir)}async function g1($,W,j){if(j.contextPack)await e($,W.contextPack,j.contextPack);if(j.planPacket)await e($,W.planPacket,j.planPacket);if(j.patchVerdict)await e($,W.patchVerdict,j.patchVerdict)}async function W0($,W,j,Q){let Z=$.join(W.decisionsDir,j);if(await $.mkdir(Z),Q.contextPack)await e($,$.join(Z,"context-pack.json"),Q.contextPack);if(Q.planPacket)await e($,$.join(Z,"plan-packet.json"),Q.planPacket);if(Q.patchVerdict)await e($,$.join(Z,"patch-verdict.json"),Q.patchVerdict);if(Q.reviewPacket)await e($,$.join(Z,"review-packet.json"),Q.reviewPacket);if(Q.evaluationResult!==void 0)await e($,$.join(Z,"evaluation-result.json"),Q.evaluationResult);if(Q.replayBundle!==void 0)await e($,$.join(Z,"replay-bundle.json"),Q.replayBundle);return Z}async function j0($,W,j,Q){let Z=$.join(W.decisionsDir,j,"decision-envelope.json");return await e($,Z,Q),Z}async function h1($,W,j){let Q=await Y4($,W.auditFile)??"",Z=`${JSON.stringify(j)}
685
- `;await $.writeFile(W.auditFile,`${Q}${Z}`)}async function f1($,W,j){let Q=$.join(W.reviewPacketsDir,`${j.id}.json`);return await e($,Q,j),Q}async function Q0($,W,j){let Q=$.join(W.decisionsDir,j);return{historyDir:Q,contextPack:await y$($,$.join(Q,"context-pack.json")),planPacket:await y$($,$.join(Q,"plan-packet.json")),patchVerdict:await y$($,$.join(Q,"patch-verdict.json")),reviewPacket:await y$($,$.join(Q,"review-packet.json")),envelope:await y$($,$.join(Q,"decision-envelope.json"))}}async function u1($,W){let j=await $.glob({pattern:"*.json",cwd:W.reviewPacketsDir,absolute:!0}),Q=[];for(let Z of j){let B=await y$($,Z);if(B)Q.push({filePath:Z,packet:B})}return Q.sort((Z,B)=>Z.packet.id.localeCompare(B.packet.id))}function X$($,W,j){return $.relative(W.packageRoot,$.resolve(j)).replaceAll("\\","/")}function P$($,W,j,Q,Z){let B=$.join(j.decisionsDir,Q);return{contextPack:X$($,W,$.join(B,"context-pack.json")),planPacket:X$($,W,$.join(B,"plan-packet.json")),patchVerdict:X$($,W,$.join(B,"patch-verdict.json")),reviewPacket:Z.reviewPacket?X$($,W,$.join(B,"review-packet.json")):void 0,evaluationResult:Z.evaluationResult?X$($,W,$.join(B,"evaluation-result.json")):void 0,replayBundle:Z.replayBundle?X$($,W,$.join(B,"replay-bundle.json")):void 0}}async function e($,W,j){await $.writeFile(W,`${JSON.stringify(j,null,2)}
686
- `)}async function y$($,W){let j=await Y4($,W);if(!j)return;try{return JSON.parse(j)}catch{return}}async function Y4($,W){if(!await $.exists(W))return;try{return await $.readFile(W)}catch{return}}async function wZ($,W,j){let Q=f(W);if(p(Q),!W.scenarioKey&&!W.suiteKey||W.scenarioKey&&W.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let Z=$$(Q),B=await Q0($.fs,Z,W.decisionId),X=CZ(Q,B),Y=W.scenarioKey?await j.runScenarioEvaluation({scenarioKey:W.scenarioKey,version:W.version,context:X}):await j.runSuiteEvaluation({suiteKey:W.suiteKey??"",version:W.version,context:X}),q=await W0($.fs,Z,W.decisionId,{evaluationResult:Y}),A=await $.fs.exists($.fs.join(q,"replay-bundle.json")),H={artifacts:P$($.fs,Q,Z,W.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:A,reviewPacket:Boolean(B.reviewPacket)}),connectDecisionId:W.decisionId,createdAt:B.envelope?.createdAt??new Date().toISOString(),runtimeLink:B.envelope?.runtimeLink,taskId:B.contextPack?.taskId??W.decisionId,verdict:B.patchVerdict?.verdict??"permit"};return await j0($.fs,Z,W.decisionId,H),{historyDir:q,evaluation:Y,context:X}}function CZ($,W){return{traceId:W.envelope?.runtimeLink?.traceId??W.patchVerdict?.controlPlane.traceId??W.contextPack?.actor.traceId,actorId:W.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:W.envelope?.runtimeLink?.decisionId,controlPlanePlanId:W.envelope?.runtimeLink?.planId??W.planPacket?.id,metadata:{approvalStatus:W.envelope?.runtimeLink?.approvalStatus,decisionId:W.patchVerdict?.decisionId,taskId:W.contextPack?.taskId,branch:W.contextPack?.branch??$.branch}}}function SZ($){return $}import{DEFAULT_CONTRACTSRC as EZ}from"@contractspec/lib.contracts-spec/workspace-config";async function MZ($,W={}){let j=f(W),Q=W.scope==="package"?j.packageRoot:j.workspaceRoot,Z=$.join(Q,".contractsrc.json"),B={connect:{...EZ.connect,enabled:!0}},X="created";if(await $.exists(Z)){let q=j$(await $.readFile(Z)),A=r(q??{},B);if(q?.connect&&typeof q.connect==="object")A.connect.enabled=!0;await $.writeFile(Z,D(A)),X="merged"}else await $.writeFile(Z,D(B));let Y=$$(f({...W,workspaceRoot:Q,packageRoot:Q}));return await $0($,Y),{configPath:Z,targetRoot:Q,action:X}}import{randomUUID as s0}from"crypto";async function d1($,W){let j=f(W);p(j),j=S$(j,await $.git.currentBranch());let{commands:Q,touchedPaths:Z}=NZ(W.candidate),B=await k1($,{...W,paths:Z}),X=s$(W.taskId,W.actor),Y=RZ(W.candidate.steps,W.candidate),q=await E$($,{baseline:W.baseline,touchedPaths:Z,workspace:j}),A=t$(j,{commands:Q,impactAnalysis:q,touchedPaths:Z}),H={id:`connect.plan_${s0()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:B.impactedContracts,affectedSurfaces:B.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:A.requiredApprovals,riskScore:DZ(Z.length,Q.length),verificationStatus:A.verificationStatus,controlPlane:{intentSubmit:R1,planCompile:D1,planVerify:F1,traceId:X.traceId},acpActions:[...Z.length>0?["acp.fs.access"]:[],...Q.length>0?["acp.terminal.exec"]:[]]};return{contextPack:B,planPacket:H}}function NZ($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let Q of $.steps??[]){if(typeof Q==="string")continue;for(let Z of Q.paths??[])W.add(Z);for(let Z of Q.commands??[])j.add(Z)}return{commands:[...j],touchedPaths:[...W]}}function RZ($,W){if(!$||$.length===0)return[{id:`step_${s0()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${s0()}`,summary:j}:{id:`step_${s0()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function DZ($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function FZ($,W,j){let Q=f(W);p(Q);let Z=$$(Q),B=await Q0($.fs,Z,W.decisionId),X={decisionId:B.envelope?.runtimeLink?.decisionId,traceId:B.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,q=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:B.historyDir,contextPack:B.contextPack,planPacket:B.planPacket,patchVerdict:B.patchVerdict,reviewPacket:B.reviewPacket,trace:Y??void 0,replay:q??void 0,source:Y?"local+control-plane":"local"}}async function xZ($,W={}){let j=f(W);return p(j),u1($.fs,$$(j))}import{buildChannelPlanTrace as TZ,compileChannelPlan as vZ,finalizeChannelPlan as yZ,replayExecutionTrace as PZ,resolveChannelExecutionActor as mZ}from"@contractspec/integration.runtime/channel";import{createHash as kZ}from"crypto";var Z0="connect.local",gZ="connect.runtime-link.v1",hZ="connect.adapter.v1",fZ="connect-control-plane-bridge";function uZ($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:Q,patchVerdict:Z,planPacket:B,workspace:X})=>{let Y=new Date(j),q=JSON.stringify({connectDecisionId:W,objective:B.objective,taskId:B.taskId,tool:Q.tool,verdict:Z.verdict}),A={workspaceId:X.repoId,providerKey:Z0,externalEventId:W,eventType:Q.tool==="acp.fs.access"?`connect.fs.${Q.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Z.controlPlane.traceId,thread:{externalThreadId:`connect:${B.taskId}`,externalUserId:B.actor.id},message:{text:lZ(B.objective,Q)},metadata:A4({connectDecisionId:W,connectVerdict:Z.verdict,sessionId:B.actor.sessionId,workflowId:`connect:${B.taskId}`}),rawPayload:q},H=await $.store.claimEventReceipt({workspaceId:A.workspaceId,providerKey:A.providerKey,externalEventId:A.externalEventId,eventType:A.eventType,signatureValid:!0,payloadHash:rZ(q),traceId:A.traceId});if(H.duplicate)return dZ($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:A.workspaceId,providerKey:A.providerKey,externalThreadId:A.thread.externalThreadId,externalUserId:A.thread.externalUserId,occurredAt:Y}),G=mZ(A,{actorId:B.actor.id,actorType:B.actor.type,capabilityGrants:cZ(Z.verdict),capabilitySource:"connect",sessionId:B.actor.sessionId}),z=vZ({event:A,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),J=yZ({plan:z,decision:nZ(Z),approvalTimeoutMs:900000,now:Y}),K=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:J.policy?.verdict??"blocked",riskTier:J.policy?.riskTier??"blocked",confidence:J.policy?.confidence??0.5,modelName:fZ,promptVersion:gZ,policyVersion:hZ,toolTrace:TZ(J),actionPlan:J,requiresApproval:J.approval.required,approvalStatus:J.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:J.approval.required?"pending":"processed",decisionId:K.id,receiptId:H.receiptId,traceId:J.traceId,workspaceId:X.repoId,providerKey:Z0,sessionId:B.actor.sessionId,workflowId:`connect:${B.taskId}`,metadata:A4({connectDecisionId:W,connectVerdict:Z.verdict,tool:Q.tool})}),{approvalStatus:K.approvalStatus,decisionId:K.id,planId:J.id,providerKey:Z0,receiptId:H.receiptId,threadId:V.id,traceId:J.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>q4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await q4($.traceService,W);return j?PZ(j):null}}}async function dZ($,W,j){let Z=(await $.listDecisions({externalEventId:j,limit:1,providerKey:Z0,workspaceId:W}))[0];return Z?{approvalStatus:Z.approvalStatus,decisionId:Z.id,planId:Z.actionPlan.id,providerKey:Z0,receiptId:Z.receiptId,threadId:Z.threadId,traceId:Z.actionPlan.traceId,workspaceId:W}:null}async function q4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function nZ($){let W=v$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((j)=>`${j.status}:${j.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:W.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:W.controlPlaneVerdict}}function cZ($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function lZ($,W){return`${$} [${W.tool}]`}function rZ($){return kZ("sha256").update($).digest("hex")}function A4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as iZ}from"crypto";function H4($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as oZ}from"crypto";function V4($,W,j){let Q=$?`Immutable path: ${$}`:W?`Protected path: ${W}`:j?`Generated path: ${j}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":W||j?"warn":"pass",detail:Q}}function G4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",Q=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:Q}}function z4($,W,j){return{id:"impact-analysis",status:$?"fail":W||j?"warn":"pass",detail:$?"Breaking change detected.":W?"Generated-path drift detected.":j?"Impact could not be resolved.":"Impact resolved."}}function J4($,W,j,Q,Z,B){let X=B.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${B.runtimeLink.decisionId}`:B.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${B.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${oZ()}`,sourceDecisionId:W,objective:Q.objective,reason:B.reason,summary:{paths:Z,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:Q.requiredChecks},evidence:[{type:"context-pack",ref:B.artifactRefs.contextPack},{type:"plan-packet",ref:B.artifactRefs.planPacket},{type:"patch-verdict",ref:B.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:w$.key,reason:B.reason}],controlPlane:{traceQuery:i0,policyExplain:a0,approvalStatus:B.runtimeLink?.approvalStatus,decisionId:B.runtimeLink?.decisionId,traceId:B.runtimeLink?.traceId??j.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function n1($,W,j,Q,Z,B,X,Y,q){let A=v$(X);return{decisionId:$,summary:Q.objective,action:W.tool==="acp.fs.access"?{actionType:W.operation==="write"?"write_file":"edit_file",tool:W.tool,target:W.path}:{actionType:"run_command",tool:W.tool,cwd:W.cwd},impacted:Z,checks:B,verdict:X,controlPlane:{verdict:A.controlPlaneVerdict,requiresApproval:A.requiresApproval,approvalStatus:q?.approvalStatus,decisionId:q?.decisionId,traceId:q?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${w$.key}@${w$.version}`,`${t0.key}@${t0.version}`]:void 0,remediation:pZ(X),reviewPacketRef:Y,replay:{traceQuery:i0,policyExplain:a0}}}function pZ($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function aZ($,W,j={}){let Q=f(W);p(Q),Q=S$(Q,await $.git.currentBranch());let Z=`connect.dec_${iZ()}`,B=(j.now??(()=>new Date))().toISOString(),X=$$(Q);await $0($.fs,X);let{contextPack:Y,planPacket:q}=await d1($,{...W,candidate:tZ(W)}),A=sZ(W),H=await E$($,{baseline:W.baseline,touchedPaths:A,workspace:Q}),V=await eZ(j,Q.config.connect?.policy?.smokeChecks??[],Q.workspaceRoot),G=V.some((S)=>S.id.startsWith("smoke:")&&S.status==="fail"),z=t$(Q,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:A}),J=[V4(z.immutablePath,z.protectedPath,z.generatedPath),G4(z.commandState,z.commandMatch),z4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],K=P$($.fs,Q,X,Z,{contextPack:!0,patchVerdict:!0,planPacket:!0}),_=H.pathImpacts.length>0?H.pathImpacts.map((S)=>({file:S.path,contracts:S.contracts,policies:S.policies,surfaces:S.surfaces})):A.map((S)=>({file:S,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),w=n1(Z,W,Y,q,_,J,z.verdict,void 0),b=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Z,createdAt:B,input:W,patchVerdict:w,planPacket:q,workspace:Q}):null,L=b?{...q,controlPlane:{...q.controlPlane,decisionId:b.decisionId,traceId:b.traceId??q.controlPlane.traceId}}:q,I=z.verdict==="require_review"?J4(Q,Z,Y,L,A,{artifactRefs:K,reason:z.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:b}):void 0,U=n1(Z,W,Y,L,_,J,z.verdict,I?X$($.fs,Q,$.fs.join(X.reviewPacketsDir,`${I.id}.json`)):void 0,b);if(await g1($.fs,X,{contextPack:Y,planPacket:L,patchVerdict:U}),I)await f1($.fs,X,I);let O=await W0($.fs,X,Z,{contextPack:Y,planPacket:L,patchVerdict:U,reviewPacket:I}),C={artifacts:P$($.fs,Q,X,Z,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:Z,createdAt:B,runtimeLink:b??void 0,taskId:W.taskId,verdict:z.verdict};return await j0($.fs,X,Z,C),await h1($.fs,X,H4({contextPack:Y,createdAt:B,envelope:C,reviewPacket:I,verifyInput:W,workspace:Q})),{contextPack:Y,planPacket:L,patchVerdict:U,reviewPacket:I,historyDir:O}}function tZ($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function sZ($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function eZ($,W,j){if(!$.runCommand)return[];let Q=[];for(let Z of W){let B=await $.runCommand(Z,{cwd:j});Q.push({id:`smoke:${Z}`,status:B.exitCode===0?"pass":"fail",detail:B.exitCode===0?`Passed: ${Z}`:`Failed (${B.exitCode}): ${Z}`})}return Q}WW();var o1={};P(o1,{generateWorkflowSpec:()=>m4,generateWorkflowRunnerTemplate:()=>k4,generateTestTemplate:()=>N4,generateTelemetrySpec:()=>P4,generatePresentationSpec:()=>y4,generateOperationSpec:()=>v4,generateMigrationSpec:()=>T4,generateKnowledgeSpaceSpec:()=>F4,generateIntegrationSpec:()=>D4,generateHandlerTemplate:()=>E4,generateFeatureSpec:()=>S4,generateExperimentSpec:()=>C4,generateEventSpec:()=>w4,generateDataViewSpec:()=>b4,generateComponentTemplate:()=>M4,generateAppBlueprintSpec:()=>O4});var g4={};P(g4,{generateWorkflowSpec:()=>m4,generateWorkflowRunnerTemplate:()=>k4,generateTestTemplate:()=>N4,generateTelemetrySpec:()=>P4,generatePresentationSpec:()=>y4,generateOperationSpec:()=>v4,generateMigrationSpec:()=>T4,generateKnowledgeSpaceSpec:()=>F4,generateIntegrationSpec:()=>D4,generateHandlerTemplate:()=>E4,generateFeatureSpec:()=>S4,generateExperimentSpec:()=>C4,generateEventSpec:()=>w4,generateDataViewSpec:()=>b4,generateComponentTemplate:()=>M4,generateAppBlueprintSpec:()=>O4});function O4($){let W=_B($.name.split(".").pop()??"App")+"AppConfig",j=AB($),Q=HB($),Z=_4("dataViews",$.dataViews),B=_4("workflows",$.workflows),X=VB($),Y=GB($),q=zB($),A=JB($),H=KB($),V=UB($),G=$.notes?` notes: '${N($.notes)}',
518
+ `)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};try{let j=JSON.parse($);if(typeof j.code==="string")return{code:j.code};if(typeof j.errors==="object")return{errors:Array.isArray(j.errors)?j.errors:[String(j.errors)]}}catch{}return{code:$}}}var l0=new r0;var b1={"claude-code":d0,"cursor-cli":c0,"generic-mcp":l0};function $0($){let W=b1[$];if(!W)throw Error(`Unknown agent type: ${$}`);return W}function w1(){return Object.keys(b1)}import{featureToMarkdown as K1,generateImplementationPlan as f5,operationSpecToAgentPrompt as vQ,operationSpecToFullMarkdown as mQ}from"@contractspec/lib.contracts-spec/llm";var PQ={defaultAgent:"generic-mcp",verbose:!1};class o0{config;constructor($={}){this.config={...PQ,...$}}generateGuide($,W={}){let j=W.agent??this.config.defaultAgent,A=$0(j),Q=f5($,{projectRoot:this.config.projectRoot,existingFiles:W.targetPath?[W.targetPath]:void 0}),Z=A.formatPlan(Q),X=mQ($);return{plan:Q,prompt:Z,markdown:X}}generateFeatureGuide($,W,j={}){let A=j.agent??this.config.defaultAgent,Q=$0(A),Z=$.operations?.[0],X=Z?W.specs?.get(Z.key,Z.version):void 0,Y;if(X)Y=f5(X,{projectRoot:this.config.projectRoot}),Y.target={type:"feature",key:$.meta.key,version:"1.0.0"},Y.context.goal=$.meta.description??Y.context.goal;else Y={target:{type:"feature",key:$.meta.key,version:"1.0.0"},context:{goal:$.meta.description??`Implement feature ${$.meta.key}`,description:$.meta.title??$.meta.key,background:""},specMarkdown:K1($,W),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(Y.specMarkdown=K1($,W,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)Y.steps=$.operations.map((H,V)=>({order:V+1,title:`Implement ${H.key}`,description:`Implement operation ${H.key}.v${H.version}`,acceptanceCriteria:[`Operation ${H.key} works as specified`]}));let B=Q.formatPlan(Y),q=K1($,W);return{plan:Y,prompt:B,markdown:q}}generateAgentConfig($,W){return $0(W??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,W,j="implement",A){return vQ($,{taskType:j,existingCode:A})}listAgentTypes(){return w1()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function kQ($){return new o0($)}var hQ=new o0;import{detectAuthoringTarget as NZ,generateComponentTemplate as RZ,generateHandlerTemplate as CZ,generateTestTemplate as DZ,getAuthoringTargetDefinition as TZ,inferSpecTypeFromFilePath as FZ,scanSpecSource as xZ}from"@contractspec/module.workspace";var B8={};h(B8,{generateWorkflowSpec:()=>Y8,generateWorkflowRunnerTemplate:()=>jW,generateWorkflowDevkitWorkflowTemplate:()=>a0,generateWorkflowDevkitStreamRouteTemplate:()=>$W,generateWorkflowDevkitStartRouteTemplate:()=>s0,generateWorkflowDevkitGenericTemplate:()=>WW,generateWorkflowDevkitFollowUpRouteTemplate:()=>e0,generateTestTemplate:()=>s5,generateTelemetrySpec:()=>X8,generatePresentationSpec:()=>Z8,generateOperationSpec:()=>Q8,generateMigrationSpec:()=>A8,generateKnowledgeSpaceSpec:()=>W8,generateIntegrationSpec:()=>$8,generateHandlerTemplate:()=>t5,generateFormSpec:()=>p5,generateFeatureSpec:()=>i5,generateExperimentSpec:()=>o5,generateEventSpec:()=>l5,generateDataViewSpec:()=>r5,generateDataViewRendererTemplate:()=>p0,generateComponentTemplate:()=>a5,generateAppBlueprintSpec:()=>c5});function c5($){let W=oQ($.name.split(".").pop()??"App")+"AppConfig",j=gQ($),A=fQ($),Q=u5("dataViews",$.dataViews),Z=u5("workflows",$.workflows),X=uQ($),Y=dQ($),B=nQ($),q=cQ($),H=rQ($),V=lQ($),G=$.notes?` notes: '${T($.notes)}',
687
519
  `:"";return`import type { AppBlueprintSpec } from '@contractspec/lib.contracts-spec/app-config';
688
520
 
689
521
  export const ${W}: AppBlueprintSpec = {
690
522
  meta: {
691
- key: '${N($.name)}',
523
+ key: '${T($.name)}',
692
524
  version: ${$.version},
693
- title: '${N($.title)}',
694
- description: '${N($.description)}',
695
- domain: '${N($.domain)}',
696
- owners: [${$.owners.map((z)=>`'${N(z)}'`).join(", ")}],
697
- tags: [${$.tags.map((z)=>`'${N(z)}'`).join(", ")}],
525
+ title: '${T($.title)}',
526
+ description: '${T($.description)}',
527
+ domain: '${T($.domain)}',
528
+ owners: [${$.owners.map((J)=>`'${T(J)}'`).join(", ")}],
529
+ tags: [${$.tags.map((J)=>`'${T(J)}'`).join(", ")}],
698
530
  stability: '${$.stability}',
699
- appId: '${N($.appId)}',
531
+ appId: '${T($.appId)}',
700
532
  },
701
- ${j}${Q}${Z}${B}${X}${Y}${q}${A}${H}${V}${G}};
702
- `}function AB($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let W=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((Q)=>L4(Q)).join(", ")}],
703
- `:"",j=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((Q)=>L4(Q)).join(", ")}],
533
+ ${j}${A}${Q}${Z}${X}${Y}${B}${q}${H}${V}${G}};
534
+ `}function gQ($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let W=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((A)=>d5(A)).join(", ")}],
535
+ `:"",j=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((A)=>d5(A)).join(", ")}],
704
536
  `:"";return` capabilities: {
705
537
  ${W}${j} },
706
- `}function HB($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let W=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((Q)=>`{ key: '${N(Q)}' }`).join(", ")}],
707
- `:"",j=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((Q)=>`{ key: '${N(Q)}' }`).join(", ")}],
538
+ `}function fQ($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let W=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
539
+ `:"",j=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
708
540
  `:"";return` features: {
709
541
  ${W}${j} },
710
- `}function _4($,W){if(W.length===0)return"";let j=W.map((Q)=>` ${Q.slot}: {
711
- name: '${N(Q.name)}',
712
- ${Q.version!==void 0?`version: '${Q.version}',`:""}
542
+ `}function u5($,W){if(W.length===0)return"";let j=W.map((A)=>` ${A.slot}: {
543
+ name: '${T(A.name)}',
544
+ ${A.version!==void 0?`version: '${A.version}',`:""}
713
545
  }`).join(`,
714
546
  `);return` ${$}: {
715
547
  ${j}
716
548
  },
717
- `}function VB($){if($.policyRefs.length===0)return"";return` policies: [
549
+ `}function uQ($){if($.policyRefs.length===0)return"";return` policies: [
718
550
  ${$.policyRefs.map((j)=>` {
719
- name: '${N(j.name)}'${j.version!==void 0?`,
551
+ name: '${T(j.name)}'${j.version!==void 0?`,
720
552
  version: '${j.version}'`:""}
721
553
  }`).join(`,
722
554
  `)}
723
555
  ],
724
- `}function GB($){if(!$.theme)return"";let W=` primary: { name: '${N($.theme.name)}', version: '${$.theme.version}' },
725
- `,j=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((Q)=>`{ name: '${N(Q.name)}', version: '${Q.version}' }`).join(", ")}],
556
+ `}function dQ($){if(!$.theme)return"";let W=` primary: { name: '${T($.theme.name)}', version: '${$.theme.version}' },
557
+ `,j=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((A)=>`{ name: '${T(A.name)}', version: '${A.version}' }`).join(", ")}],
726
558
  `:"";return` theme: {
727
559
  ${W}${j} },
728
- `}function zB($){if(!$.telemetry)return"";return` telemetry: {
560
+ `}function nQ($){if(!$.telemetry)return"";return` telemetry: {
729
561
  spec: {
730
- name: '${N($.telemetry.name)}'${$.telemetry.version!==void 0?`
562
+ name: '${T($.telemetry.name)}'${$.telemetry.version!==void 0?`
731
563
  version: '${$.telemetry.version}'`:""}
732
564
  },
733
565
  },
734
- `}function JB($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let W=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((Q)=>I4(Q)).join(", ")}],
735
- `:"",j=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((Q)=>I4(Q)).join(", ")}],
566
+ `}function cQ($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let W=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((A)=>n5(A)).join(", ")}],
567
+ `:"",j=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((A)=>n5(A)).join(", ")}],
736
568
  `:"";return` experiments: {
737
569
  ${W}${j} },
738
- `}function KB($){if($.featureFlags.length===0)return"";return` featureFlags: [
570
+ `}function rQ($){if($.featureFlags.length===0)return"";return` featureFlags: [
739
571
  ${$.featureFlags.map((j)=>` {
740
- key: '${N(j.key)}',
572
+ key: '${T(j.key)}',
741
573
  enabled: ${j.enabled},
742
- ${j.variant?`variant: '${N(j.variant)}',`:""}
743
- ${j.description?`description: '${N(j.description)}',`:""}
574
+ ${j.variant?`variant: '${T(j.variant)}',`:""}
575
+ ${j.description?`description: '${T(j.description)}',`:""}
744
576
  }`).join(`,
745
577
  `)}
746
578
  ],
747
- `}function UB($){if($.routes.length===0)return"";return` routes: [
748
- ${$.routes.map((j)=>{return` { ${[`path: '${N(j.path)}'`,j.label?`label: '${N(j.label)}'`:null,j.dataView?`dataView: '${N(j.dataView)}'`:null,j.workflow?`workflow: '${N(j.workflow)}'`:null,j.guardName?`guard: { name: '${N(j.guardName)}'${j.guardVersion!==void 0?`, version: '${j.guardVersion}'`:""} }`:null,j.featureFlag?`featureFlag: '${N(j.featureFlag)}'`:null,j.experimentName?`experiment: { name: '${N(j.experimentName)}'${j.experimentVersion!==void 0?`, version: '${j.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
579
+ `}function lQ($){if($.routes.length===0)return"";return` routes: [
580
+ ${$.routes.map((j)=>{return` { ${[`path: '${T(j.path)}'`,j.label?`label: '${T(j.label)}'`:null,j.dataView?`dataView: '${T(j.dataView)}'`:null,j.workflow?`workflow: '${T(j.workflow)}'`:null,j.guardName?`guard: { name: '${T(j.guardName)}'${j.guardVersion!==void 0?`, version: '${j.guardVersion}'`:""} }`:null,j.featureFlag?`featureFlag: '${T(j.featureFlag)}'`:null,j.experimentName?`experiment: { name: '${T(j.experimentName)}'${j.experimentVersion!==void 0?`, version: '${j.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
749
581
  `)}
750
582
  ],
751
- `}function L4($){return`{ key: '${N($)}' }`}function I4($){let W=$.version!==void 0?`, version: '${$.version}'`:"";return`{ name: '${N($.name)}'${W} }`}function _B($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function N($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function b4($){let W=LB($.name.split(".").pop()??"DataView")+"DataView",j=$.fields.map((B)=>` {
752
- key: '${B.key}',
753
- label: '${jW(B.label)}',
754
- dataPath: '${B.dataPath}',
755
- ${B.format?`format: '${B.format}',`:""}
756
- ${B.sortable?"sortable: true,":""}
757
- ${B.filterable?"filterable: true,":""}
583
+ `}function d5($){return`{ key: '${T($)}' }`}function n5($){let W=$.version!==void 0?`, version: '${$.version}'`:"";return`{ name: '${T($.name)}'${W} }`}function oQ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function r5($){let W=iQ($.name.split(".").pop()??"DataView")+"DataView",j=$.fields.map((Z)=>` {
584
+ key: '${Z.key}',
585
+ label: '${i0(Z.label)}',
586
+ dataPath: '${Z.dataPath}',
587
+ ${Z.format?`format: '${Z.format}',`:""}
588
+ ${Z.sortable?"sortable: true,":""}
589
+ ${Z.filterable?"filterable: true,":""}
758
590
  }`).join(`,
759
- `),Q=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((B)=>`'${B}'`).join(", ")}],`:"",Z=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
591
+ `),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((Z)=>`'${Z}'`).join(", ")}],`:"",Q=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
760
592
 
761
593
  export const ${W}: DataViewSpec = {
762
594
  meta: {
763
595
  key: '${$.name}',
764
596
  version: ${$.version},
765
597
  entity: '${$.entity}',
766
- title: '${jW($.title)}',
767
- description: '${jW($.description||"Describe the purpose of this data view.")}',
768
- domain: '${jW($.domain||$.entity)}',
769
- owners: [${$.owners.map((B)=>`'${B}'`).join(", ")}],
770
- tags: [${$.tags.map((B)=>`'${B}'`).join(", ")}],
598
+ title: '${i0($.title)}',
599
+ description: '${i0($.description||"Describe the purpose of this data view.")}',
600
+ domain: '${i0($.domain||$.entity)}',
601
+ owners: [${$.owners.map((Z)=>`'${Z}'`).join(", ")}],
602
+ tags: [${$.tags.map((Z)=>`'${Z}'`).join(", ")}],
771
603
  stability: '${$.stability}',
772
604
  },
773
605
  source: {
@@ -775,7 +607,7 @@ export const ${W}: DataViewSpec = {
775
607
  name: '${$.primaryOperation.name}',
776
608
  version: ${$.primaryOperation.version},
777
609
  },
778
- ${Z}
610
+ ${Q}
779
611
  refreshEvents: [
780
612
  // { name: 'entity.updated', version: '1.0.0' },
781
613
  ],
@@ -786,7 +618,7 @@ export const ${W}: DataViewSpec = {
786
618
  ${j}
787
619
  ],
788
620
  ${$.primaryField?`primaryField: '${$.primaryField}',`:""}
789
- ${Q}
621
+ ${A}
790
622
  filters: [
791
623
  // Example filter:
792
624
  // { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
@@ -801,12 +633,51 @@ ${j}
801
633
  // error: { name: 'app.data.error', version: '1.0.0' },
802
634
  },
803
635
  };
804
- `}function LB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function jW($){return $.replace(/'/g,"\\'")}function w4($){let{name:W,version:j,description:Q,stability:Z,owners:B,tags:X,piiFields:Y}=$,q=IB(W.replace(/\./g,"_"))+"V"+j,A=q+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
636
+ `}function iQ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function i0($){return $.replace(/'/g,"\\'")}function p0({exportName:$,specImportPath:W,rendererName:j,viewKind:A}){return`'use client';
637
+
638
+ import * as React from 'react';
639
+ import { DataViewRenderer } from '@contractspec/lib.design-system';
640
+ import { ${$} } from '${W}';
641
+
642
+ export interface ${j}Props {
643
+ items?: Record<string, unknown>[];
644
+ item?: Record<string, unknown> | null;
645
+ className?: string;
646
+ renderActions?: (item: Record<string, unknown>) => React.ReactNode;
647
+ onSelect?: (item: Record<string, unknown>) => void;
648
+ onRowClick?: (item: Record<string, unknown>) => void;
649
+ }
650
+
651
+ /**
652
+ * Auto-generated renderer for the "${A}" data view.
653
+ * Customize as needed for app-specific behaviour.
654
+ */
655
+ export function ${j}({
656
+ items = [],
657
+ item = null,
658
+ className,
659
+ renderActions,
660
+ onSelect,
661
+ onRowClick,
662
+ }: ${j}Props) {
663
+ return (
664
+ <DataViewRenderer
665
+ spec={${$}}
666
+ items={items}
667
+ item={item}
668
+ className={className}
669
+ renderActions={renderActions}
670
+ onSelect={onSelect}
671
+ onRowClick={onRowClick}
672
+ />
673
+ );
674
+ }
675
+ `}function l5($){let{name:W,version:j,description:A,stability:Q,owners:Z,tags:X,piiFields:Y}=$,B=pQ(W.replace(/\./g,"_"))+"V"+j,q=B+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
805
676
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
806
677
 
807
678
  // TODO: Define event payload schema
808
- export const ${A} = new SchemaModel({
809
- name: '${A}',
679
+ export const ${q} = new SchemaModel({
680
+ name: '${q}',
810
681
  description: 'Payload for ${W}',
811
682
  fields: {
812
683
  // Add your payload fields here
@@ -814,80 +685,80 @@ export const ${A} = new SchemaModel({
814
685
  },
815
686
  });
816
687
 
817
- export const ${q} = defineEvent({
688
+ export const ${B} = defineEvent({
818
689
  name: '${W}',
819
690
  name: '${W}',
820
691
  version: '${j}',
821
- description: '${Q}',
822
- description: '${Q}',
823
- stability: '${Z}',
824
- owners: [${B.map((H)=>`'${H}'`).join(", ")}],
692
+ description: '${A}',
693
+ description: '${A}',
694
+ stability: '${Q}',
695
+ owners: [${Z.map((H)=>`'${H}'`).join(", ")}],
825
696
  tags: [${X.map((H)=>`'${H}'`).join(", ")}],
826
697
  ${Y.length>0?`pii: [${Y.map((H)=>`'${H}'`).join(", ")}],`:"// pii: [],"}
827
- payload: ${A},
698
+ payload: ${q},
828
699
  });
829
- `}function IB($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function C4($){let W=bB($.name.split(".").pop()??"Experiment")+"Experiment",j=$.variants.map((B)=>{let X=B.overrides?.length?` overrides: [
830
- ${B.overrides.map((Y)=>` {
700
+ `}function pQ($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function o5($){let W=aQ($.name.split(".").pop()??"Experiment")+"Experiment",j=$.variants.map((Z)=>{let X=Z.overrides?.length?` overrides: [
701
+ ${Z.overrides.map((Y)=>` {
831
702
  type: '${Y.type}',
832
- target: '${T(Y.target)}',
703
+ target: '${P(Y.target)}',
833
704
  ${typeof Y.version==="string"?`version: ${Y.version},`:""}
834
705
  }`).join(`,
835
706
  `)}
836
707
  ],`:"";return` {
837
- id: '${T(B.id)}',
838
- name: '${T(B.name)}',
839
- ${B.description?`description: '${T(B.description)}',`:""}
840
- ${typeof B.weight==="number"?`weight: ${B.weight},`:""}
708
+ id: '${P(Z.id)}',
709
+ name: '${P(Z.name)}',
710
+ ${Z.description?`description: '${P(Z.description)}',`:""}
711
+ ${typeof Z.weight==="number"?`weight: ${Z.weight},`:""}
841
712
  ${X}
842
713
  }`}).join(`,
843
- `),Q=OB($.allocation),Z=$.successMetrics?.length?` successMetrics: [
844
- ${$.successMetrics.map((B)=>` {
845
- name: '${T(B.name)}',
846
- telemetryEvent: { name: '${T(B.eventName)}', version: ${typeof B.eventVersion==="string"?`'${B.eventVersion}'`:B.eventVersion} },
847
- aggregation: '${B.aggregation}',
848
- ${typeof B.target==="number"?`target: ${B.target},`:""}
714
+ `),A=tQ($.allocation),Q=$.successMetrics?.length?` successMetrics: [
715
+ ${$.successMetrics.map((Z)=>` {
716
+ name: '${P(Z.name)}',
717
+ telemetryEvent: { name: '${P(Z.eventName)}', version: ${typeof Z.eventVersion==="string"?`'${Z.eventVersion}'`:Z.eventVersion} },
718
+ aggregation: '${Z.aggregation}',
719
+ ${typeof Z.target==="number"?`target: ${Z.target},`:""}
849
720
  }`).join(`,
850
721
  `)}
851
722
  ],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
852
723
 
853
724
  export const ${W}: ExperimentSpec = {
854
725
  meta: {
855
- key: '${T($.name)}',
726
+ key: '${P($.name)}',
856
727
  version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
857
- title: '${T($.name)} experiment',
858
- description: '${T($.description||"Describe the experiment goal.")}',
859
- domain: '${T($.domain)}',
860
- owners: [${$.owners.map((B)=>`'${T(B)}'`).join(", ")}],
861
- tags: [${$.tags.map((B)=>`'${T(B)}'`).join(", ")}],
728
+ title: '${P($.name)} experiment',
729
+ description: '${P($.description||"Describe the experiment goal.")}',
730
+ domain: '${P($.domain)}',
731
+ owners: [${$.owners.map((Z)=>`'${P(Z)}'`).join(", ")}],
732
+ tags: [${$.tags.map((Z)=>`'${P(Z)}'`).join(", ")}],
862
733
  stability: '${$.stability}',
863
734
  },
864
- controlVariant: '${T($.controlVariant)}',
735
+ controlVariant: '${P($.controlVariant)}',
865
736
  variants: [
866
737
  ${j}
867
738
  ],
868
- allocation: ${Q},
869
- ${Z}
739
+ allocation: ${A},
740
+ ${Q}
870
741
  };
871
- `}function OB($){switch($.type){case"random":return`{
742
+ `}function tQ($){switch($.type){case"random":return`{
872
743
  type: 'random',
873
- ${$.salt?`salt: '${T($.salt)}',`:""}
744
+ ${$.salt?`salt: '${P($.salt)}',`:""}
874
745
  }`;case"sticky":return`{
875
746
  type: 'sticky',
876
747
  attribute: '${$.attribute}',
877
- ${$.salt?`salt: '${T($.salt)}',`:""}
748
+ ${$.salt?`salt: '${P($.salt)}',`:""}
878
749
  }`;case"targeted":return`{
879
750
  type: 'targeted',
880
751
  rules: [
881
752
  ${$.rules.map((W)=>` {
882
- variantId: '${T(W.variantId)}',
753
+ variantId: '${P(W.variantId)}',
883
754
  ${typeof W.percentage==="number"?`percentage: ${W.percentage},`:""}
884
- ${W.policy?`policy: { name: '${T(W.policy.name)}'${W.policy.version!==void 0?`, version: ${typeof W.policy.version==="string"?`'${W.policy.version}'`:W.policy.version}`:""} },`:""}
885
- ${W.expression?`expression: '${T(W.expression)}',`:""}
755
+ ${W.policy?`policy: { name: '${P(W.policy.name)}'${W.policy.version!==void 0?`, version: ${typeof W.policy.version==="string"?`'${W.policy.version}'`:W.policy.version}`:""} },`:""}
756
+ ${W.expression?`expression: '${P(W.expression)}',`:""}
886
757
  }`).join(`,
887
758
  `)}
888
759
  ],
889
760
  fallback: '${$.fallback??"control"}',
890
- }`;default:return wB($)}}function bB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function wB($){throw Error(`Unsupported allocation type ${$}`)}function CB($){return $.replace(/-([a-z])/g,(W,j)=>j.toUpperCase())}function S4($){let W=(j)=>j.map((Q)=>` { name: '${Q.name}', version: '${Q.version}' },`).join(`
761
+ }`;default:return sQ($)}}function aQ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function P($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function sQ($){throw Error(`Unsupported allocation type ${$}`)}function eQ($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function i5($){let W=(j)=>j.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
891
762
  `);return`/**
892
763
  * ${$.title} Feature
893
764
  *
@@ -896,13 +767,17 @@ ${$.rules.map((W)=>` {
896
767
 
897
768
  import { defineFeature } from '@contractspec/lib.contracts-spec';
898
769
 
899
- export const ${CB($.key)}Feature = defineFeature({
900
- key: '${$.key}',
901
- title: '${$.title}',
902
- description: '${$.description||"TODO: Add description"}',
903
- stability: '${$.stability||"alpha"}',
904
- owners: [${$.owners.map((j)=>`'${j}'`).join(", ")}],
905
- tags: [${$.tags.map((j)=>`'${j}'`).join(", ")}],
770
+ export const ${eQ($.key)}Feature = defineFeature({
771
+ meta: {
772
+ key: '${$.key}',
773
+ version: '${$.version}',
774
+ title: '${$.title}',
775
+ description: '${$.description||"TODO: Add description"}',
776
+ domain: '${$.domain}',
777
+ owners: [${$.owners.map((j)=>`'${j}'`).join(", ")}],
778
+ tags: [${$.tags.map((j)=>`'${j}'`).join(", ")}],
779
+ stability: '${$.stability||"beta"}',
780
+ },
906
781
 
907
782
  operations: [
908
783
  ${W($.operations)||" // Add operations here"}
@@ -919,19 +794,70 @@ ${W($.presentations)||" // Add presentations here"}
919
794
  experiments: [
920
795
  ${W($.experiments)||" // Add experiments here"}
921
796
  ],
797
+ });
798
+ `}function $Z($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function p5($){let W=$Z($.key),j=`${W}FormModel`,A=`${W}Form`;return`/**
799
+ * ${$.title} Form
800
+ *
801
+ * Auto-generated form spec.
802
+ */
922
803
 
923
- capabilities: {
924
- provides: [],
925
- requires: [],
804
+ import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
805
+ import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
806
+
807
+ const ${j} = defineSchemaModel({
808
+ name: '${j}',
809
+ description: '${$.description||"TODO: Add form model description"}',
810
+ fields: {
811
+ ${$.primaryFieldKey}: {
812
+ type: ScalarTypeEnum.String_unsecure(),
813
+ isOptional: false,
814
+ },
815
+ },
816
+ });
817
+
818
+ export const ${A} = defineFormSpec({
819
+ meta: {
820
+ key: '${$.key}',
821
+ version: '${$.version}',
822
+ title: '${$.title}',
823
+ description: '${$.description||"TODO: Add description"}',
824
+ domain: '${$.domain}',
825
+ owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
826
+ tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
827
+ stability: '${$.stability||"beta"}',
828
+ },
829
+ model: ${j},
830
+ fields: [
831
+ {
832
+ kind: 'text',
833
+ name: '${$.primaryFieldKey}',
834
+ labelI18n: '${$.primaryFieldLabel}',
835
+ placeholderI18n: '${$.primaryFieldPlaceholder||"TODO.placeholder"}',
836
+ required: true,
837
+ },
838
+ ],
839
+ actions: [
840
+ {
841
+ key: '${$.actionKey}',
842
+ labelI18n: '${$.actionLabel}',
843
+ },
844
+ ],
845
+ policy: {
846
+ flags: [],
847
+ pii: [],
848
+ },
849
+ renderHints: {
850
+ ui: 'custom',
851
+ form: 'react-hook-form',
926
852
  },
927
853
  });
928
- `}function E4($,W){let j=SB($.split(".").pop()||"unknown")+"Handler",Q=QW($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
929
- import { ${Q} } from '../contracts/${R4($)}.contracts';
854
+ `}function t5($,W){let j=WZ($.split(".").pop()||"unknown")+"Handler",A=t0($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
855
+ import { ${A} } from '../contracts/${e5($)}.contracts';
930
856
 
931
857
  /**
932
858
  * Handler for ${$}
933
859
  */
934
- export const ${j}: ContractHandler<typeof ${Q}> = async (
860
+ export const ${j}: ContractHandler<typeof ${A}> = async (
935
861
  input,
936
862
  context
937
863
  ) => {
@@ -951,7 +877,7 @@ export const ${j}: ContractHandler<typeof ${Q}> = async (
951
877
  throw error;
952
878
  }
953
879
  };
954
- `}function M4($,W){let j=QW($);return`import React from 'react';
880
+ `}function a5($,W){let j=t0($);return`import React from 'react';
955
881
 
956
882
  interface ${j}Props {
957
883
  // TODO: Define props based on presentation spec
@@ -968,10 +894,10 @@ export const ${j}: React.FC<${j}Props> = (props) => {
968
894
  </div>
969
895
  );
970
896
  };
971
- `}function N4($,W){let j=W==="handler"?"../handlers":"../components",Q=QW($);return`import { describe, it, expect } from 'bun:test';
972
- import { ${Q} } from '${j}/${R4($)}';
897
+ `}function s5($,W){let j=W==="handler"?"../handlers":"../components",A=t0($);return`import { describe, it, expect } from 'bun:test';
898
+ import { ${A} } from '${j}/${e5($)}';
973
899
 
974
- describe('${Q}', () => {
900
+ describe('${A}', () => {
975
901
  it('should ${W==="handler"?"handle valid input":"render correctly"}', async () => {
976
902
  // TODO: Implement test
977
903
  expect(true).toBe(true);
@@ -987,12 +913,12 @@ describe('${Q}', () => {
987
913
  // TODO: Test accessibility
988
914
  });`}
989
915
  });
990
- `}function SB($){let W=QW($);return W.charAt(0).toLowerCase()+W.slice(1)}function QW($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function R4($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function D4($){let W=vB($.name.split(".").pop()??"Integration"),j=`${W}IntegrationSpec`,Q=`register${W}Integration`,Z=$.supportedModes.length?$.supportedModes:["managed"],B=Z.map((K)=>`'${K}'`).join(", "),X=$.capabilitiesProvided.map((K)=>` { key: '${K.key}', version: '${K.version}' }`).join(`,
916
+ `}function WZ($){let W=t0($);return W.charAt(0).toLowerCase()+W.slice(1)}function t0($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function e5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function $8($){let W=HZ($.name.split(".").pop()??"Integration"),j=`${W}IntegrationSpec`,A=`register${W}Integration`,Q=$.supportedModes.length?$.supportedModes:["managed"],Z=Q.map((w)=>`'${w}'`).join(", "),X=$.capabilitiesProvided.map((w)=>` { key: '${w.key}', version: '${w.version}' }`).join(`,
991
917
  `),Y=$.capabilitiesRequired.length>0?` requires: [
992
- ${$.capabilitiesRequired.map((K)=>{let _=K.version!==void 0?`, version: '${K.version}'`:"",w=K.optional?", optional: true":"",b=K.reason?`, reason: '${t(K.reason)}'`:"";return` { key: '${K.key}'${_}${w}${b} }`}).join(`,
918
+ ${$.capabilitiesRequired.map((w)=>{let L=w.version!==void 0?`, version: '${w.version}'`:"",z=w.optional?", optional: true":"",S=w.reason?`, reason: '${e(w.reason)}'`:"";return` { key: '${w.key}'${L}${z}${S} }`}).join(`,
993
919
  `)}
994
- ],`:"",q=EB($.configFields),A=NB($.configFields),H=MB($.secretFields),V=RB($.secretFields),G=$.docsUrl?` docsUrl: '${t($.docsUrl)}',
995
- `:"",z=DB($.rateLimitRpm,$.rateLimitRph),J=FB(Z,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
920
+ ],`:"",B=jZ($.configFields),q=QZ($.configFields),H=AZ($.secretFields),V=ZZ($.secretFields),G=$.docsUrl?` docsUrl: '${e($.docsUrl)}',
921
+ `:"",J=XZ($.rateLimitRpm,$.rateLimitRph),b=YZ(Q,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
996
922
  import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
997
923
  import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
998
924
 
@@ -1001,15 +927,15 @@ export const ${j}: IntegrationSpec = {
1001
927
  key: '${$.name}',
1002
928
  version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
1003
929
  category: '${$.category}',
1004
- displayName: '${t($.displayName)}',
1005
- title: '${t($.title)}',
1006
- description: '${t($.description)}',
1007
- domain: '${t($.domain)}',
1008
- owners: [${$.owners.map((K)=>`'${t(K)}'`).join(", ")}],
1009
- tags: [${$.tags.map((K)=>`'${t(K)}'`).join(", ")}],
1010
- stability: StabilityEnum.${TB($.stability)},
930
+ displayName: '${e($.displayName)}',
931
+ title: '${e($.title)}',
932
+ description: '${e($.description)}',
933
+ domain: '${e($.domain)}',
934
+ owners: [${$.owners.map((w)=>`'${e(w)}'`).join(", ")}],
935
+ tags: [${$.tags.map((w)=>`'${e(w)}'`).join(", ")}],
936
+ stability: StabilityEnum.${qZ($.stability)},
1011
937
  },
1012
- supportedModes: [${B}],
938
+ supportedModes: [${Z}],
1013
939
  capabilities: {
1014
940
  provides: [
1015
941
  ${X}
@@ -1017,57 +943,57 @@ ${X}
1017
943
  ${Y.length>0?`${Y}
1018
944
  `:""} },
1019
945
  configSchema: {
1020
- ${q}
1021
- example: ${A},
946
+ ${B}
947
+ example: ${q},
1022
948
  },
1023
949
  secretSchema: {
1024
950
  ${H}
1025
951
  example: ${V},
1026
952
  },
1027
- ${G}${z}${J} healthCheck: {
953
+ ${G}${J}${b} healthCheck: {
1028
954
  method: '${$.healthCheckMethod}',
1029
955
  timeoutMs: ${$.healthCheckTimeoutMs},
1030
956
  },
1031
957
  };
1032
958
 
1033
- export function ${Q}(
959
+ export function ${A}(
1034
960
  registry: IntegrationSpecRegistry
1035
961
  ): IntegrationSpecRegistry {
1036
962
  return registry.register(${j});
1037
963
  }
1038
- `}function EB($){let W=$.filter((Z)=>Z.required),j=W.length>0?` required: [${W.map((Z)=>`'${Z.key}'`).join(", ")}],
1039
- `:"",Q=$.length?$.map((Z)=>{let B=Z.description?`, description: '${t(Z.description)}'`:"";return` ${Z.key}: { type: '${xB(Z.type)}'${B} }`}).join(`,
964
+ `}function jZ($){let W=$.filter((Q)=>Q.required),j=W.length>0?` required: [${W.map((Q)=>`'${Q.key}'`).join(", ")}],
965
+ `:"",A=$.length?$.map((Q)=>{let Z=Q.description?`, description: '${e(Q.description)}'`:"";return` ${Q.key}: { type: '${BZ(Q.type)}'${Z} }`}).join(`,
1040
966
  `):"";return` schema: {
1041
967
  type: 'object',
1042
968
  ${j} properties: {
1043
- ${Q||" "}
969
+ ${A||" "}
1044
970
  },
1045
971
  },
1046
- `}function MB($){let W=$.filter((Z)=>Z.required),j=W.length>0?` required: [${W.map((Z)=>`'${Z.key}'`).join(", ")}],
1047
- `:"",Q=$.length?$.map((Z)=>{let B=Z.description?`, description: '${t(Z.description)}'`:"";return` ${Z.key}: { type: 'string'${B} }`}).join(`,
972
+ `}function AZ($){let W=$.filter((Q)=>Q.required),j=W.length>0?` required: [${W.map((Q)=>`'${Q.key}'`).join(", ")}],
973
+ `:"",A=$.length?$.map((Q)=>{let Z=Q.description?`, description: '${e(Q.description)}'`:"";return` ${Q.key}: { type: 'string'${Z} }`}).join(`,
1048
974
  `):"";return` schema: {
1049
975
  type: 'object',
1050
976
  ${j} properties: {
1051
- ${Q||" "}
977
+ ${A||" "}
1052
978
  },
1053
979
  },
1054
- `}function NB($){if($.length===0)return"{}";return`{
980
+ `}function QZ($){if($.length===0)return"{}";return`{
1055
981
  ${$.map((j)=>{switch(j.type){case"number":return` ${j.key}: 0`;case"boolean":return` ${j.key}: true`;case"string":default:return` ${j.key}: '${j.key.toUpperCase()}_VALUE'`}}).join(`,
1056
982
  `)}
1057
- }`}function RB($){if($.length===0)return"{}";return`{
983
+ }`}function ZZ($){if($.length===0)return"{}";return`{
1058
984
  ${$.map((j)=>` ${j.key}: '${j.key.toUpperCase()}_SECRET'`).join(`,
1059
985
  `)}
1060
- }`}function DB($,W){if($==null&&W==null)return"";let j=[];if($!=null)j.push(` rpm: ${$}`);if(W!=null)j.push(` rph: ${W}`);return` constraints: {
986
+ }`}function XZ($,W){if($==null&&W==null)return"";let j=[];if($!=null)j.push(` rpm: ${$}`);if(W!=null)j.push(` rph: ${W}`);return` constraints: {
1061
987
  rateLimit: {
1062
988
  ${j.join(`,
1063
989
  `)}
1064
990
  },
1065
991
  },
1066
- `}function FB($,W,j){if(!$.includes("byok"))return"";let Q=W?` setupInstructions: '${t(W)}',
1067
- `:"",Z=j&&j.length?` requiredScopes: [${j.map((B)=>`'${t(B)}'`).join(", ")}],
1068
- `:"";if(!Q&&!Z)return"";return` byokSetup: {
1069
- ${Q}${Z} },
1070
- `}function xB($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function TB($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function vB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function t($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function F4($){let W=gB($.name.split(".").pop()??"KnowledgeSpace"),j=`${W}KnowledgeSpace`,Q=`register${W}KnowledgeSpace`,Z=yB($),B=PB($),X=mB($),Y=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
992
+ `}function YZ($,W,j){if(!$.includes("byok"))return"";let A=W?` setupInstructions: '${e(W)}',
993
+ `:"",Q=j&&j.length?` requiredScopes: [${j.map((Z)=>`'${e(Z)}'`).join(", ")}],
994
+ `:"";if(!A&&!Q)return"";return` byokSetup: {
995
+ ${A}${Q} },
996
+ `}function BZ($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function qZ($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function HZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function e($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function W8($){let W=wZ($.name.split(".").pop()??"KnowledgeSpace"),j=`${W}KnowledgeSpace`,A=`register${W}KnowledgeSpace`,Q=VZ($),Z=GZ($),X=JZ($),Y=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
1071
997
  import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
1072
998
  import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
1073
999
 
@@ -1076,74 +1002,74 @@ export const ${j}: KnowledgeSpaceSpec = {
1076
1002
  key: '${$.name}',
1077
1003
  version: ${$.version},
1078
1004
  category: '${$.category}',
1079
- displayName: '${Y$($.displayName)}',
1080
- title: '${Y$($.title)}',
1081
- description: '${Y$($.description)}',
1082
- domain: '${Y$($.domain)}',
1083
- owners: [${$.owners.map((q)=>`'${Y$(q)}'`).join(", ")}],
1084
- tags: [${$.tags.map((q)=>`'${Y$(q)}'`).join(", ")}],
1085
- stability: StabilityEnum.${kB($.stability)},
1005
+ displayName: '${B$($.displayName)}',
1006
+ title: '${B$($.title)}',
1007
+ description: '${B$($.description)}',
1008
+ domain: '${B$($.domain)}',
1009
+ owners: [${$.owners.map((B)=>`'${B$(B)}'`).join(", ")}],
1010
+ tags: [${$.tags.map((B)=>`'${B$(B)}'`).join(", ")}],
1011
+ stability: StabilityEnum.${bZ($.stability)},
1086
1012
  },
1087
- retention: ${Z},
1013
+ retention: ${Q},
1088
1014
  access: {
1089
- ${B}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${Y}
1015
+ ${Z}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${Y}
1090
1016
  `:""} },
1091
- ${X} description: '${Y$($.description||$.displayName)}',
1017
+ ${X} description: '${B$($.description||$.displayName)}',
1092
1018
  };
1093
1019
 
1094
- export function ${Q}(
1020
+ export function ${A}(
1095
1021
  registry: KnowledgeSpaceRegistry
1096
1022
  ): KnowledgeSpaceRegistry {
1097
1023
  return registry.register(${j});
1098
1024
  }
1099
- `}function yB($){let W=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",j=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${W}${j} }`}function PB($){let W=` trustLevel: '${$.trustLevel}',
1025
+ `}function VZ($){let W=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",j=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${W}${j} }`}function GZ($){let W=` trustLevel: '${$.trustLevel}',
1100
1026
  `,j=` automationWritable: ${$.automationWritable},
1101
- `;return`${W}${j}`}function mB($){let W=[];if($.embeddingModel)W.push(` embeddingModel: '${Y$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")W.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)W.push(` vectorDbIntegration: '${Y$($.vectorDbIntegration)}'`);if(W.length===0)return"";return` indexing: {
1027
+ `;return`${W}${j}`}function JZ($){let W=[];if($.embeddingModel)W.push(` embeddingModel: '${B$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")W.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)W.push(` vectorDbIntegration: '${B$($.vectorDbIntegration)}'`);if(W.length===0)return"";return` indexing: {
1102
1028
  ${W.join(`,
1103
1029
  `)}
1104
1030
  },
1105
- `}function kB($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function gB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function Y$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function T4($){let j=`${hB($.name.split(".").pop()??"Migration")}Migration`,Q=$.dependencies.length>0?`dependencies: [${$.dependencies.map((Z)=>`'${Z}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
1031
+ `}function bZ($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function wZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function B$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function A8($){let j=`${KZ($.name.split(".").pop()??"Migration")}Migration`,A=$.dependencies.length>0?`dependencies: [${$.dependencies.map((Q)=>`'${Q}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
1106
1032
 
1107
1033
  export const ${j}: MigrationSpec = {
1108
1034
  meta: {
1109
1035
  key: '${$.name}',
1110
1036
  version: ${$.version},
1111
- title: '${N$($.title)}',
1112
- description: '${N$($.description??"")}',
1113
- domain: '${N$($.domain)}',
1114
- owners: [${$.owners.map((Z)=>`'${Z}'`).join(", ")}],
1115
- tags: [${$.tags.map((Z)=>`'${Z}'`).join(", ")}],
1037
+ title: '${E$($.title)}',
1038
+ description: '${E$($.description??"")}',
1039
+ domain: '${E$($.domain)}',
1040
+ owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
1041
+ tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
1116
1042
  stability: '${$.stability}',
1117
1043
  },
1118
1044
  plan: {
1119
1045
  up: [
1120
- ${x4($.up)}
1046
+ ${j8($.up)}
1121
1047
  ],${$.down&&$.down.length?`
1122
1048
  down: [
1123
- ${x4($.down)}
1049
+ ${j8($.down)}
1124
1050
  ],`:""}
1125
1051
  },
1126
- ${Q}
1052
+ ${A}
1127
1053
  };
1128
- `}function x4($){return $.map((W)=>{let j=W.description?`description: '${N$(W.description)}',`:"";switch(W.kind){case"schema":return` {
1054
+ `}function j8($){return $.map((W)=>{let j=W.description?`description: '${E$(W.description)}',`:"";switch(W.kind){case"schema":return` {
1129
1055
  kind: 'schema',
1130
1056
  ${j}
1131
- sql: \`${N$(W.sql??"")}\`,
1057
+ sql: \`${E$(W.sql??"")}\`,
1132
1058
  }`;case"data":return` {
1133
1059
  kind: 'data',
1134
1060
  ${j}
1135
- script: \`${N$(W.script??"")}\`,
1061
+ script: \`${E$(W.script??"")}\`,
1136
1062
  }`;case"validation":default:return` {
1137
1063
  kind: 'validation',
1138
1064
  ${j}
1139
- assertion: \`${N$(W.assertion??"")}\`,
1065
+ assertion: \`${E$(W.assertion??"")}\`,
1140
1066
  }`}}).join(`,
1141
- `)}function hB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function N$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function v4($){let{name:W,version:j,kind:Q,description:Z,goal:B,context:X,stability:Y,owners:q,tags:A,auth:H,flags:V}=$,G=fB(W.split(".").pop()||"Unknown")+"Spec",z=G.replace("Spec","Input"),J=G.replace("Spec","Output");return`import { define${r1(Q)} } from '@contractspec/lib.contracts-spec';
1067
+ `)}function KZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function E$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Q8($){let{name:W,version:j,kind:A,description:Q,goal:Z,context:X,stability:Y,owners:B,tags:q,auth:H,flags:V}=$,G=_Z(W.split(".").pop()||"Unknown")+"Spec",J=G.replace("Spec","Input"),b=G.replace("Spec","Output");return`import { define${_1(A)} } from '@contractspec/lib.contracts-spec';
1142
1068
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
1143
1069
 
1144
1070
  // TODO: Define input schema
1145
- export const ${z} = new SchemaModel({
1146
- name: '${z}',
1071
+ export const ${J} = new SchemaModel({
1072
+ name: '${J}',
1147
1073
  description: 'Input for ${W}',
1148
1074
  fields: {
1149
1075
  // Add your fields here
@@ -1152,8 +1078,8 @@ export const ${z} = new SchemaModel({
1152
1078
  });
1153
1079
 
1154
1080
  // TODO: Define output schema
1155
- export const ${J} = new SchemaModel({
1156
- name: '${J}',
1081
+ export const ${b} = new SchemaModel({
1082
+ name: '${b}',
1157
1083
  description: 'Output for ${W}',
1158
1084
  fields: {
1159
1085
  // Add your fields here
@@ -1161,23 +1087,23 @@ export const ${J} = new SchemaModel({
1161
1087
  },
1162
1088
  });
1163
1089
 
1164
- export const ${G} = define${r1(Q)}({
1090
+ export const ${G} = define${_1(A)}({
1165
1091
  meta: {
1166
1092
  key: '${W}',
1167
1093
  key: '${W}',
1168
1094
  version: '${j}',
1169
1095
  stability: '${Y}',
1170
1096
  stability: '${Y}',
1171
- owners: [${q.map((K)=>`'${K}'`).join(", ")}],
1172
- tags: [${A.map((K)=>`'${K}'`).join(", ")}],
1173
- description: '${Z}',
1174
- goal: '${B}',
1097
+ owners: [${B.map((w)=>`'${w}'`).join(", ")}],
1098
+ tags: [${q.map((w)=>`'${w}'`).join(", ")}],
1099
+ description: '${Q}',
1100
+ goal: '${Z}',
1175
1101
  context: '${X}',
1176
1102
  },
1177
1103
 
1178
1104
  io: {
1179
- input: ${z},
1180
- output: ${J},
1105
+ input: ${J},
1106
+ output: ${b},
1181
1107
  errors: {
1182
1108
  // Define possible errors
1183
1109
  // EXAMPLE_ERROR: {
@@ -1190,7 +1116,7 @@ export const ${G} = define${r1(Q)}({
1190
1116
 
1191
1117
  policy: {
1192
1118
  auth: '${H}',
1193
- ${V.length>0?`flags: [${V.map((K)=>`'${K}'`).join(", ")}],`:"// flags: [],"}
1119
+ ${V.length>0?`flags: [${V.map((w)=>`'${w}'`).join(", ")}],`:"// flags: [],"}
1194
1120
  },
1195
1121
 
1196
1122
  sideEffects: {
@@ -1204,7 +1130,7 @@ export const ${G} = define${r1(Q)}({
1204
1130
  },
1205
1131
 
1206
1132
  transport: {
1207
- rest: { method: '${Q==="command"?"POST":"GET"}' },
1133
+ rest: { method: '${A==="command"?"POST":"GET"}' },
1208
1134
  gql: { field: '${W.replace(/\./g,"_")}' },
1209
1135
  mcp: { toolName: '${W.replace(/\./g,"_")}-v${String(j).replace(/\./g,"_")}' },
1210
1136
  },
@@ -1227,12 +1153,12 @@ export const ${G} = define${r1(Q)}({
1227
1153
  ],
1228
1154
  },
1229
1155
  });
1230
- `}function r1($){return $.charAt(0).toUpperCase()+$.slice(1)}function fB($){return $.split(/[-_.]/).map(r1).join("")}function y4($){let{name:W,version:j,description:Q,stability:Z,owners:B,tags:X,presentationKind:Y}=$,q=uB(W.replace(/\./g,"_"))+"Presentation",A="";switch(Y){case"web_component":A=` content: {
1156
+ `}function _1($){return $.charAt(0).toUpperCase()+$.slice(1)}function _Z($){return $.split(/[-_.]/).map(_1).join("")}function Z8($){let{name:W,version:j,description:A,stability:Q,owners:Z,tags:X,presentationKind:Y}=$,B=zZ(W.replace(/\./g,"_"))+"Presentation",q="";switch(Y){case"web_component":q=` content: {
1231
1157
  kind: 'web_component',
1232
1158
  framework: 'react',
1233
1159
  componentKey: '${W.replace(/\./g,"_")}',
1234
1160
  props: new SchemaModel({
1235
- name: '${q}Props',
1161
+ name: '${B}Props',
1236
1162
  description: 'Props for ${W}',
1237
1163
  fields: {
1238
1164
  // TODO: Define component props
@@ -1241,19 +1167,19 @@ export const ${G} = define${r1(Q)}({
1241
1167
  analytics: [
1242
1168
  // TODO: Define analytics events
1243
1169
  ],
1244
- },`;break;case"markdown":A=` content: {
1170
+ },`;break;case"markdown":q=` content: {
1245
1171
  kind: 'markdown',
1246
1172
  content: \`
1247
- # ${Q}
1173
+ # ${A}
1248
1174
 
1249
1175
  TODO: Add markdown content here
1250
1176
  \`,
1251
1177
  // Or use resourceUri: 'feature://${W}/guide.md'
1252
- },`;break;case"data":A=` content: {
1178
+ },`;break;case"data":q=` content: {
1253
1179
  kind: 'data',
1254
1180
  mimeType: 'application/json',
1255
1181
  model: new SchemaModel({
1256
- name: '${q}Data',
1182
+ name: '${B}Data',
1257
1183
  description: 'Data structure for ${W}',
1258
1184
  fields: {
1259
1185
  // TODO: Define data structure
@@ -1262,14 +1188,14 @@ TODO: Add markdown content here
1262
1188
  },`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
1263
1189
  import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
1264
1190
 
1265
- export const ${q}: PresentationSpec = {
1191
+ export const ${B}: PresentationSpec = {
1266
1192
  meta: {
1267
1193
  key: '${W}',
1268
1194
  version: ${j},
1269
- stability: '${Z}',
1270
- owners: [${B.map((H)=>`'${H}'`).join(", ")}],
1195
+ stability: '${Q}',
1196
+ owners: [${Z.map((H)=>`'${H}'`).join(", ")}],
1271
1197
  tags: [${X.map((H)=>`'${H}'`).join(", ")}],
1272
- description: '${Q}',
1198
+ description: '${A}',
1273
1199
  },
1274
1200
 
1275
1201
  policy: {
@@ -1277,52 +1203,52 @@ export const ${q}: PresentationSpec = {
1277
1203
  // pii: [],
1278
1204
  },
1279
1205
 
1280
- ${A}
1206
+ ${q}
1281
1207
  };
1282
- `}function uB($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function P4($){let W=dB($.name.split(".").pop()??"Telemetry")+"Telemetry",j=$.providers?.length?`providers: [
1283
- ${$.providers.map((Z)=>` {
1284
- type: '${Z.type}',
1285
- config: ${nB(Z.config)},
1208
+ `}function zZ($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function X8($){let W=UZ($.name.split(".").pop()??"Telemetry")+"Telemetry",j=$.providers?.length?`providers: [
1209
+ ${$.providers.map((Q)=>` {
1210
+ type: '${Q.type}',
1211
+ config: ${LZ(Q.config)},
1286
1212
  }`).join(`,
1287
1213
  `)}
1288
- ],`:"",Q=$.events.map((Z)=>{let B=Z.properties.map((Y)=>` '${Y.name}': {
1214
+ ],`:"",A=$.events.map((Q)=>{let Z=Q.properties.map((Y)=>` '${Y.name}': {
1289
1215
  type: '${Y.type}',
1290
1216
  ${Y.required?"required: true,":""}
1291
1217
  ${Y.pii?"pii: true,":""}
1292
1218
  ${Y.redact?"redact: true,":""}
1293
1219
  ${Y.description?`description: '${n(Y.description)}',`:""}
1294
1220
  }`).join(`,
1295
- `),X=Z.anomalyRules?.length?` anomalyDetection: {
1221
+ `),X=Q.anomalyRules?.length?` anomalyDetection: {
1296
1222
  enabled: true,
1297
- ${typeof Z.anomalyMinimumSample==="number"?`minimumSample: ${Z.anomalyMinimumSample},`:""}
1223
+ ${typeof Q.anomalyMinimumSample==="number"?`minimumSample: ${Q.anomalyMinimumSample},`:""}
1298
1224
  thresholds: [
1299
- ${Z.anomalyRules.map((Y)=>` {
1225
+ ${Q.anomalyRules.map((Y)=>` {
1300
1226
  metric: '${n(Y.metric)}',
1301
1227
  ${typeof Y.min==="number"?`min: ${Y.min},`:""}
1302
1228
  ${typeof Y.max==="number"?`max: ${Y.max},`:""}
1303
1229
  }`).join(`,
1304
1230
  `)}
1305
1231
  ],
1306
- actions: [${(Z.anomalyActions??[]).map((Y)=>`'${Y}'`).join(", ")}],
1307
- },`:Z.anomalyEnabled?` anomalyDetection: {
1232
+ actions: [${(Q.anomalyActions??[]).map((Y)=>`'${Y}'`).join(", ")}],
1233
+ },`:Q.anomalyEnabled?` anomalyDetection: {
1308
1234
  enabled: true,
1309
- ${typeof Z.anomalyMinimumSample==="number"?`minimumSample: ${Z.anomalyMinimumSample},`:""}
1235
+ ${typeof Q.anomalyMinimumSample==="number"?`minimumSample: ${Q.anomalyMinimumSample},`:""}
1310
1236
  },`:"";return` {
1311
- name: '${n(Z.name)}',
1312
- version: ${Z.version},
1237
+ name: '${n(Q.name)}',
1238
+ version: ${Q.version},
1313
1239
  semantics: {
1314
- what: '${n(Z.what)}',
1315
- ${Z.who?`who: '${n(Z.who)}',`:""}
1316
- ${Z.why?`why: '${n(Z.why)}',`:""}
1240
+ what: '${n(Q.what)}',
1241
+ ${Q.who?`who: '${n(Q.who)}',`:""}
1242
+ ${Q.why?`why: '${n(Q.why)}',`:""}
1317
1243
  },
1318
- privacy: '${Z.privacy}',
1244
+ privacy: '${Q.privacy}',
1319
1245
  properties: {
1320
- ${B}
1246
+ ${Z}
1321
1247
  },
1322
- ${typeof Z.retentionDays==="number"?`retention: { days: ${Z.retentionDays}, ${Z.retentionPolicy?`policy: '${Z.retentionPolicy}'`:""} },`:""}
1323
- ${typeof Z.samplingRate==="number"?`sampling: { rate: ${Z.samplingRate}${Z.samplingConditions?`, conditions: ['${n(Z.samplingConditions)}']`:""} },`:""}
1248
+ ${typeof Q.retentionDays==="number"?`retention: { days: ${Q.retentionDays}, ${Q.retentionPolicy?`policy: '${Q.retentionPolicy}'`:""} },`:""}
1249
+ ${typeof Q.samplingRate==="number"?`sampling: { rate: ${Q.samplingRate}${Q.samplingConditions?`, conditions: ['${n(Q.samplingConditions)}']`:""} },`:""}
1324
1250
  ${X}
1325
- ${Z.tags?.length?`tags: [${Z.tags.map((Y)=>`'${n(Y)}'`).join(", ")}],`:""}
1251
+ ${Q.tags?.length?`tags: [${Q.tags.map((Y)=>`'${n(Y)}'`).join(", ")}],`:""}
1326
1252
  }`}).join(`,
1327
1253
  `);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
1328
1254
 
@@ -1333,8 +1259,8 @@ export const ${W}: TelemetrySpec = {
1333
1259
  title: '${n($.name)} telemetry',
1334
1260
  description: '${n($.description||"Describe the purpose of this telemetry spec.")}',
1335
1261
  domain: '${n($.domain)}',
1336
- owners: [${$.owners.map((Z)=>`'${n(Z)}'`).join(", ")}],
1337
- tags: [${$.tags.map((Z)=>`'${n(Z)}'`).join(", ")}],
1262
+ owners: [${$.owners.map((Q)=>`'${n(Q)}'`).join(", ")}],
1263
+ tags: [${$.tags.map((Q)=>`'${n(Q)}'`).join(", ")}],
1338
1264
  stability: '${$.stability}',
1339
1265
  },
1340
1266
  config: {
@@ -1344,14 +1270,14 @@ export const ${W}: TelemetrySpec = {
1344
1270
  ${j}
1345
1271
  },
1346
1272
  events: [
1347
- ${Q}
1273
+ ${A}
1348
1274
  ],
1349
1275
  };
1350
- `}function dB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function n($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function nB($){let W=$.trim();if(!W)return"{}";if(W.startsWith("{")&&W.endsWith("}")||W.startsWith("[")&&W.endsWith("]"))return W;return`'${n(W)}'`}function m4($){let W=lB($.name.split(".").pop()??"Workflow")+"Workflow",j=$.steps.map((Z)=>cB(Z)).join(`,
1351
- `),Q=$.transitions.map((Z)=>` {
1352
- from: '${Z.from}',
1353
- to: '${Z.to}',
1354
- ${Z.condition?` condition: '${m$(Z.condition)}',`:""}
1276
+ `}function UZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function n($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function LZ($){let W=$.trim();if(!W)return"{}";if(W.startsWith("{")&&W.endsWith("}")||W.startsWith("[")&&W.endsWith("]"))return W;return`'${n(W)}'`}function Y8($){let W=SZ($.name.split(".").pop()??"Workflow")+"Workflow",j=$.steps.map((Q)=>OZ(Q)).join(`,
1277
+ `),A=$.transitions.map((Q)=>` {
1278
+ from: '${Q.from}',
1279
+ to: '${Q.to}',
1280
+ ${Q.condition?` condition: '${h$(Q.condition)}',`:""}
1355
1281
  }`).join(`,
1356
1282
  `);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
1357
1283
 
@@ -1367,12 +1293,12 @@ export const ${W}: WorkflowSpec = {
1367
1293
  meta: {
1368
1294
  key: '${$.name}',
1369
1295
  version: ${$.version},
1370
- title: '${m$($.title)}',
1371
- description: '${m$($.description)}',
1372
- domain: '${m$($.domain)}',
1296
+ title: '${h$($.title)}',
1297
+ description: '${h$($.description)}',
1298
+ domain: '${h$($.domain)}',
1373
1299
  stability: '${$.stability}',
1374
- owners: [${$.owners.map((Z)=>`'${Z}'`).join(", ")}],
1375
- tags: [${$.tags.map((Z)=>`'${Z}'`).join(", ")}],
1300
+ owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
1301
+ tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
1376
1302
  },
1377
1303
  definition: {
1378
1304
  ${$.entryStepId?` entryStepId: '${$.entryStepId}',
@@ -1380,21 +1306,73 @@ ${$.entryStepId?` entryStepId: '${$.entryStepId}',
1380
1306
  ${j}
1381
1307
  ],
1382
1308
  transitions: [
1383
- ${Q}
1309
+ ${A}
1384
1310
  ],
1385
1311
  },
1386
1312
  ${$.policyFlags.length>0?`policy: {
1387
- flags: [${$.policyFlags.map((Z)=>`'${Z}'`).join(", ")}],
1313
+ flags: [${$.policyFlags.map((Q)=>`'${Q}'`).join(", ")}],
1388
1314
  },`:"// policy: { flags: [] },"}
1389
1315
  };
1390
- `}function cB($){let W=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${m$($.label)}',`];if($.description)W.push(` description: '${m$($.description)}',`);let j=[];if($.operation)j.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)j.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(j.length)W.push(` action: { ${j.join(", ")} },`);return W.push(" }"),W.join(`
1391
- `)}function lB($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function m$($){return $.replace(/'/g,"\\'")}function k4({exportName:$,specImportPath:W,runnerName:j,workflowName:Q}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
1316
+ `}function OZ($){let W=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${h$($.label)}',`];if($.description)W.push(` description: '${h$($.description)}',`);let j=[];if($.operation)j.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)j.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(j.length)W.push(` action: { ${j.join(", ")} },`);return W.push(" }"),W.join(`
1317
+ `)}function SZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function h$($){return $.replace(/'/g,"\\'")}function a0({exportName:$,specImportPath:W,workflowFunctionName:j}){return`import { createHook, createWebhook, sleep } from 'workflow';
1318
+ import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
1319
+ import { ${$} } from '${W}';
1320
+
1321
+ export async function ${j}(input = {}, bridge = {}) {
1322
+ "use workflow";
1323
+
1324
+ // Keep the workflow function deterministic.
1325
+ // Any Node.js or side-effectful logic should live in "use step" helpers that
1326
+ // your bridge calls, not in this orchestrator itself.
1327
+ return runWorkflowSpecWithWorkflowDevkit({
1328
+ spec: ${$},
1329
+ initialData: input,
1330
+ bridge,
1331
+ primitives: {
1332
+ sleep,
1333
+ createHook,
1334
+ createWebhook,
1335
+ },
1336
+ });
1337
+ }
1338
+ `}function s0($,W){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
1339
+ import { ${W} } from '${$}';
1340
+
1341
+ export const POST = createWorkflowDevkitStartRoute({
1342
+ workflow: ${W},
1343
+ async buildArgs(body) {
1344
+ return [body];
1345
+ },
1346
+ });
1347
+ `}function e0(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
1348
+
1349
+ export const POST = createWorkflowDevkitFollowUpRoute({
1350
+ resolveToken({ runId }) {
1351
+ return \`workflow-session:\${runId}\`;
1352
+ },
1353
+ });
1354
+ `}function $W(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
1355
+
1356
+ export const GET = createWorkflowDevkitStreamRoute();
1357
+ `}function WW($,W){return`import { ${W} } from '${$}';
1358
+
1359
+ export const workflowDevkitBootstrap = {
1360
+ workflow: ${W},
1361
+ createBridge() {
1362
+ return {
1363
+ executeAutomationStep: async () => {
1364
+ throw new Error('Provide executeAutomationStep in your generic host bridge.');
1365
+ },
1366
+ };
1367
+ },
1368
+ };
1369
+ `}function jW({exportName:$,specImportPath:W,runnerName:j,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
1392
1370
  import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
1393
1371
  import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
1394
1372
  import { ${$} } from '${W}';
1395
1373
 
1396
1374
  /**
1397
- * Runner wiring for ${Q}.
1375
+ * Runner wiring for ${A}.
1398
1376
  *
1399
1377
  * TODO:
1400
1378
  * - Replace the in-memory state store with a persistent adapter if needed.
@@ -1428,37 +1406,298 @@ export const ${j} = new WorkflowRunner({
1428
1406
  // console.log(event, payload);
1429
1407
  },
1430
1408
  });
1431
- `}WW();class h4{ai;templates=o1;constructor($){this.ai=new $W($)}}function zU($){return new h4($)}import{scanSpecSource as rB}from"@contractspec/module.workspace";function f4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function IU($,W,j={}){let{fs:Q,logger:Z}=W,B=await Q.exists($);if(!B&&!j.force)return{specPath:$,specInfo:f4($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let X=f4($),Y;if(B)try{let A=await Q.readFile($);X=rB(A,$),Y=X.key}catch{}let q=[];if(j.clean&&Y)try{let A=await c0(Y,{fs:Q});for(let H of A)try{await Q.remove(H.filePath),q.push(H.filePath),Z.info(`Removed artifact: ${H.filePath}`)}catch{Z.warn(`Could not remove artifact: ${H.filePath}`)}}catch{Z.warn("Could not discover implementations for cleanup")}if(B)await Q.remove($),Z.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:X,deleted:!0,cleanedFiles:q,errors:[]}}import{computeSemanticDiff as oB}from"@contractspec/module.workspace";async function wU($,W,j,Q={}){let{fs:Z,git:B}=j;if(!await Z.exists($))throw Error(`Spec file not found: ${$}`);let Y=await Z.readFile($),q,A;if(Q.baseline)q=await B.showFile(Q.baseline,$),A=`${Q.baseline}:${$}`;else{if(!await Z.exists(W))throw Error(`Spec file not found: ${W}`);q=await Z.readFile(W),A=W}let H=oB(Y,$,q,A,{breakingOnly:Q.breakingOnly});return{spec1:$,spec2:A,differences:H}}B$();import{openApiForRegistry as pB}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as p1}from"@contractspec/lib.contracts-spec/operations";async function iB($,W){let{fs:j,logger:Q}=W,{registryPath:Z,outputPath:B="./openapi.json"}=$;Q.info("Loading registry...",{registryPath:Z});let X=await aB(Z,j);Q.info("Generating OpenAPI document...");let Y=pB(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),q=JSON.stringify(Y,null,2)+`
1432
- `,A=j.resolve(B);return await j.mkdir(j.dirname(A)),await j.writeFile(A,q),Q.info(`OpenAPI document written to ${A}`),{document:Y,outputPath:A,json:q}}async function aB($,W){let Q=await import(W.resolve($));if(Q instanceof p1)return Q;if(Q.registry instanceof p1)return Q.registry;let Z=typeof Q.createRegistry==="function"?Q.createRegistry:typeof Q.default==="function"?Q.default:void 0;if(Z){let B=await Z();if(B instanceof p1)return B}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as tB,parseOpenApi as sB}from"@contractspec/lib.contracts-transformers/openapi";import{basename as i1,dirname as u4,join as k$}from"path";function eB($,W,j){if(W.outputDir)return W.outputDir;let{outputDir:Q,conventions:Z}=j;switch($){case"operation":return k$(Q,Z.operations.split("|")[0]??"operations");case"event":return k$(Q,Z.events);case"model":return k$(Q,"models");default:return Q}}async function d4($,W,j){let{fs:Q,logger:Z}=j,{source:B,prefix:X,tags:Y,exclude:q,defaultStability:A,defaultOwners:H,defaultAuth:V,dryRun:G=!1}=W;Z.info(`Importing from OpenAPI: ${B}`);let z=await sB(B,{fetch:globalThis.fetch,readFile:(L)=>Q.readFile(L)});if(z.warnings.length>0)for(let L of z.warnings)Z.warn(`Parse warning: ${L}`);Z.info(`Parsed ${z.operations.length} operations from ${z.info.title} v${z.info.version}`);let J=tB(z,$,{prefix:X,tags:Y,exclude:q,defaultStability:A,defaultOwners:H,defaultAuth:V});Z.info(`Import result: ${J.summary.imported} imported, ${J.summary.skipped} skipped, ${J.summary.errors} errors`);let K=[],_=[],w=[],b=new Map;for(let L of J.operationSpecs){let I="operation",U=null;if(L.code.includes("defineEvent("))I="event",U=L.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((L.code.includes("defineSchemaModel(")||L.code.includes("new EnumType(")||L.code.includes("ScalarTypeEnum.")||L.code.includes("new ZodSchemaType(")||L.code.includes("z.enum(")||L.code.includes("new JsonSchemaType(")||L.code.includes("new GraphQLSchemaType("))&&!L.code.includes("defineCommand(")&&!L.code.includes("defineQuery("))I="model";else I="operation",U=L.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let O=eB(I,W,$),C=k$(O,L.fileName);if(!U&&I==="model"){if(L.code.includes("new ZodSchemaType("))U=L.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(L.code.includes("new JsonSchemaType("))U=L.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(L.code.includes("new GraphQLSchemaType("))U=L.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!U)U=L.code.match(/export const (\w+)\s*=/)}if(G)Z.info(`[DRY RUN] Would create: ${C}`);else{let S=u4(C);if(!await Q.exists(S))await Q.mkdir(S);await Q.writeFile(C,L.code),Z.info(`Created: ${C}`)}if(K.push({path:C,operationId:L.source.sourceId,specName:L.fileName.replace(".ts","")}),U){let S=u4(C),M=b.get(S)||[];M.push({file:i1(C),name:U[1],type:I}),b.set(S,M)}}if(!G&&K.length>0)for(let[L,I]of b.entries()){if(I.length===0)continue;let U=I.map((F)=>F.type),O=U.every((F)=>F==="operation"),C=U.every((F)=>F==="event"),S=U.every((F)=>F==="model"),M=`/**
1409
+ `}import{getAuthoringTargetDefinition as IZ}from"@contractspec/module.workspace";var q8={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function H8($,W){let j=MZ($,W.specPath),A=EZ($,W.target,j),Q=$.join(j,"package.json"),Z=$.join(j,"README.md"),X=$.join(j,"src"),Y=$.join(X,"index.ts"),B=z1($.relative(X,W.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(X);let q=[[Q,JSON.stringify({name:A,version:"0.1.0",description:q8[W.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
1410
+ `],[Z,`# ${A}
1411
+
1412
+ ${q8[W.target]}.
1413
+ `],[Y,`export * from "./${B.startsWith(".")?B:`./${B}`}";
1414
+ `],[W.specPath,W.specCode]],H={packageRoot:j,files:q.map(([V])=>V),created:[],skipped:[]};for(let[V,G]of q){if(await $.exists(V)&&!W.overwrite){H.skipped.push(V);continue}await $.writeFile(V,G),H.created.push(V)}return H}function V8($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
1415
+
1416
+ export const ${$.exportName} = defineModuleBundle({
1417
+ meta: {
1418
+ key: "${$.key}",
1419
+ version: "1.0.0",
1420
+ title: "${$.title}",
1421
+ description: "${$.description}",
1422
+ },
1423
+ routes: [
1424
+ {
1425
+ routeId: "default",
1426
+ path: "/",
1427
+ defaultSurface: "main",
1428
+ },
1429
+ ],
1430
+ surfaces: {
1431
+ main: {
1432
+ surfaceId: "main",
1433
+ kind: "workbench",
1434
+ title: "${$.title}",
1435
+ slots: [],
1436
+ layouts: [],
1437
+ data: [],
1438
+ verification: {
1439
+ level: "basic",
1440
+ },
1441
+ },
1442
+ },
1443
+ });
1444
+ `;case"builder-spec":return`import type { BuilderWorkspace } from "@contractspec/lib.builder-spec";
1445
+
1446
+ export const ${$.exportName}: BuilderWorkspace = {
1447
+ id: "${$.key}",
1448
+ tenantId: "default",
1449
+ name: "${$.title}",
1450
+ status: "draft",
1451
+ appClass: "custom",
1452
+ defaultRuntimeMode: "managed",
1453
+ mobileParityRequired: false,
1454
+ ownerIds: [],
1455
+ defaultLocale: "en",
1456
+ defaultChannelPolicy: {},
1457
+ createdAt: new Date().toISOString(),
1458
+ updatedAt: new Date().toISOString(),
1459
+ };
1460
+ `;case"provider-spec":return`import type { ProviderCapabilityProfile } from "@contractspec/lib.provider-spec";
1461
+
1462
+ export const ${$.exportName}: ProviderCapabilityProfile = {
1463
+ providerId: "${$.key}",
1464
+ supportsRepoScopedPatch: true,
1465
+ supportsStructuredDiff: true,
1466
+ supportsLongContext: true,
1467
+ supportsFunctionCalling: true,
1468
+ supportsSTT: false,
1469
+ supportsVision: false,
1470
+ supportsStreaming: true,
1471
+ supportsLocalExecution: false,
1472
+ supportedArtifactTypes: ["patch"],
1473
+ knownConstraints: [],
1474
+ };
1475
+ `}}function MZ($,W){let j=z1(W),A="/src/",Q=j.lastIndexOf("/src/");if(Q===-1)return $.dirname(W);return j.slice(0,Q)}function EZ($,W,j){let A=IZ(W),Q=z1($.basename(j));return`${A.defaultPackagePrefix??(W==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${Q}`}function z1($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function f$($,W,j,A={}){let{fs:Q,logger:Z,workspace:X}=W,Y=X?.scanSpecSource??xZ,B=X?.inferSpecTypeFromFilePath??FZ,q=X?.generateHandlerTemplate??CZ,H=X?.generateComponentTemplate??RZ,V=X?.generateTestTemplate??DZ,{targets:G=void 0,outputDir:J=j.outputDir,overwrite:b=!1,dryRun:w=!1,includeTests:L=!1,runtimeGeneration:z}=A,S=await Q.readFile($),U=Y(S,$),O=NZ(S,$),K=O==="unknown"?B($):O,_=G??L1(K,{includeTests:L});Z.info(`Building from spec: ${$}`,{targetId:K});let I=[],M={};for(let E of _)try{let C=await yZ(E,$,S,U,K,{fs:Q,logger:Z},J,b,w,z,M,{genHandler:q,genComponent:H,genTest:V});if(I.push(C),C.success&&C.generatedCode)M[E]=C.generatedCode}catch(C){I.push({target:E,outputPath:"",success:!1,error:C instanceof Error?C.message:String(C),skipped:!1})}return{specPath:$,specInfo:U,targetId:K,results:I}}async function yZ($,W,j,A,Q,Z,X,Y,B,q,H,V){let{fs:G,logger:J}=Z,{genHandler:b,genComponent:w,genTest:L}=V,z,S,U=[];switch($){case"handler":{if(Q!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${Q})`};let _=A.kind==="command"||A.kind==="query"?A.kind:"command",I=b(o(j,A,W),_);S=g$(W,X,"handlers",o(j,A,W),".handler.ts",Z.fs),z=await q?.generateArtifact?.({kind:"handler",specCode:j,outputPath:S,fallbackCode:I})??I;break}case"component":{if(Q!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${Q})`};let _=w(o(j,A,W),A.description??"");S=g$(W,X,"components",o(j,A,W),".tsx",Z.fs),z=await q?.generateArtifact?.({kind:"component",specCode:j,outputPath:S,fallbackCode:_})??_;break}case"test":{let _=Q==="operation"?"handler":"component",I=Q==="operation"?H.handler??"":Q==="presentation"?H.component??"":Q==="form"?H.form??"":"",M=L(o(j,A,W),_);S=g$(W,X,"__tests__",o(j,A,W),".test.ts",Z.fs),z=await q?.generateTest?.({kind:_,specCode:j,outputPath:S,existingCode:I,fallbackCode:M})??M;break}case"form":{if(Q!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${Q})`};let _=`import * as React from "react";
1476
+
1477
+ export interface ${q$(o(j,A,W))}Props {
1478
+ className?: string;
1479
+ }
1480
+
1481
+ export function ${q$(o(j,A,W))}Form({
1482
+ className,
1483
+ }: ${q$(o(j,A,W))}Props) {
1484
+ return <form className={className}>TODO: implement ${o(j,A,W)}</form>;
1485
+ }
1486
+ `;S=g$(W,X,"forms",o(j,A,W),".form.tsx",Z.fs),z=await q?.generateArtifact?.({kind:"form",specCode:j,outputPath:S,fallbackCode:_})??_;break}case"workflow-runner":{if(Q!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${Q})`};let _=o(j,A,W),I=kZ(j)??`${q$(_)}Workflow`,M=`${q$(_)}Runner`,E=O1(_);if(S=g$(W,X,"workflows",_,".runner.ts",Z.fs),z=jW({exportName:I,specImportPath:U1(Z.fs,S,W),runnerName:M,workflowName:_}),fZ(j)){let C=`${q$(_)}WorkflowDevkit`,R=W0(Z.fs,S,`${E}.workflow-devkit.ts`),v=W0(Z.fs,S,`${E}.workflow-devkit.start.route.ts`),x=W0(Z.fs,S,`${E}.workflow-devkit.follow-up.route.ts`),L$=W0(Z.fs,S,`${E}.workflow-devkit.stream.route.ts`),v0=W0(Z.fs,S,`${E}.workflow-devkit.generic.ts`);U=[{path:R,code:a0({exportName:I,specImportPath:U1(Z.fs,R,W),workflowFunctionName:C})},{path:v,code:s0(G8(Z.fs,v,R),C)},{path:x,code:e0()},{path:L$,code:$W()},{path:v0,code:WW(G8(Z.fs,v0,R),C)}]}break}case"data-view-renderer":{if(Q!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${Q})`};let _=o(j,A,W),I=hZ(j)??`${q$(_)}DataView`,M=`${q$(_)}Renderer`;S=g$(W,X,"data-views",_,".renderer.tsx",Z.fs),z=p0({exportName:I,specImportPath:U1(Z.fs,S,W),rendererName:M,viewKind:gZ(j)??"table"});break}case"package-scaffold":{if(Q!=="module-bundle"&&Q!=="builder-spec"&&Q!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${Q})`};if(B){let M=mZ(W);return J.info(`[dry-run] Would scaffold package: ${M}`),{target:$,outputPath:M,success:!0}}let _=j.trim().length>0?j:V8({target:Q,key:A.key??Z.fs.basename(W),title:A.key??Z.fs.basename(W),description:A.description??TZ(Q).title,exportName:q$(A.key??Z.fs.basename(W))});return S=(await H8(Z.fs,{target:Q,specPath:W,specCode:_,overwrite:Y})).packageRoot,J.info(`Generated package scaffold: ${S}`),{target:$,outputPath:S,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let O=[{path:S,code:z},...U],K=Y?void 0:await vZ(O,G);if(K)return{target:$,outputPath:K,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(B){for(let _ of O)J.info(`[dry-run] Would write: ${_.path}`);return{target:$,outputPath:S,success:!0,generatedCode:O[0]?.code}}for(let _ of O)await G.mkdir(G.dirname(_.path)),await G.writeFile(_.path,uZ(_.code)),J.info(`Generated: ${_.path}`);return{target:$,outputPath:S,success:!0}}function L1($,W){switch($){case"operation":return W.includeTests?["handler","test"]:["handler"];case"presentation":return W.includeTests?["component","test"]:["component"];case"form":return W.includeTests?["form","test"]:["form"];case"workflow":return["workflow-runner"];case"data-view":return["data-view-renderer"];case"module-bundle":case"builder-spec":case"provider-spec":return["package-scaffold"];default:return[]}}function g$($,W,j,A,Q,Z){let X=O1(A.split(".").pop()??"unknown"),Y;if(W.startsWith("."))Y=Z.resolve(Z.dirname($),"..",W,j);else Y=Z.resolve(W,j);return Z.join(Y,`${X}${Q}`)}async function vZ($,W){for(let j of $)if(await W.exists(j.path))return j.path;return}function O1($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function q$($){return O1($).split("-").filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function S1($){return $.replace(/\.[^.]+$/,"")}function mZ($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function U1($,W,j){let A=S1($.relative($.dirname(W),j));return A.startsWith(".")?A:`./${A}`}function G8($,W,j){let A=S1($.relative($.dirname(W),j));return A.startsWith(".")?A:`./${A}`}function W0($,W,j){return $.join($.dirname(W),j)}function o($,W,j){return PZ($,"name")??W.key??S1(dZ(j))}function PZ($,W){let j=new RegExp(`${W}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(j)?.[1]??null}function kZ($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function hZ($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function gZ($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function fZ($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function uZ($){return $.endsWith(`
1487
+ `)?$:`${$}
1488
+ `}function dZ($){return $.replaceAll("\\","/").split("/").pop()??$}i();import{scanAllSpecsFromSource as iZ,scanSpecSource as pZ}from"@contractspec/module.workspace";import tZ from"micromatch";var K8={};h(K8,{validators:()=>oZ,urlSchema:()=>lZ,isValidVersion:()=>cZ,isValidIdentifier:()=>b8,isValidDotName:()=>w8,isTestFile:()=>j0,isLibraryDefinitionFile:()=>A0,emailSchema:()=>rZ});import I1 from"micromatch";function j0($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return I1.isMatch($,j)}function A0($){let W=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(I1.isMatch($,W))return!1;let j=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return I1.isMatch($,j)}import*as H$ from"zod";function b8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function w8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function cZ($){return Number.isInteger($)&&$>0}var rZ=H$.string().email(),lZ=H$.string().url(),oZ={specName:H$.string().refine(w8,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:H$.number().int().positive(),identifier:H$.string().refine(b8,{message:"Must be a valid TypeScript identifier"}),owner:H$.string().startsWith("@"),tag:H$.string().min(1)};function Q0($){return($??"").split("|").map((W)=>W.trim().replace(/^\.?\//,"")).filter(Boolean)}function aZ($){let W=$?.packages&&$.packages.length>0?$.packages:["**"],j=[...Q0($?.conventions.models),...Q0($?.conventions.operations),...Q0($?.conventions.events),...Q0($?.conventions.presentations),...Q0($?.conventions.forms)];return[...new Set(W.flatMap((A)=>{let Q=A==="**"?"":`${A}/`,Z=Y$.map((Y)=>`${Q}${Y}`),X=j.map((Y)=>`${Q}${Y}/**/*.ts`);return[...Z,...X]}))]}function sZ($,W,j){if($.specType==="unknown")return!1;if(W.type&&!j.includes($.specType))return!1;return!0}function eZ($,W){let j=$.filePath.localeCompare(W.filePath);if(j!==0)return j;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(W.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(W.discoveryId??W.key??"")}async function N$($,W={}){if(W.paths&&W.paths.length>0)return[...new Set(W.paths)].sort((j,A)=>j.localeCompare(A));if(W.pattern)return $.glob({cwd:W.cwd,pattern:W.pattern});return $.glob({cwd:W.cwd,patterns:aZ(W.config)})}async function QW($,W={}){let j=await N$($.fs,W),A=W.type?Array.isArray(W.type)?W.type:[W.type]:[],Q=[];for(let Z of j){if(W.config?.excludePackages&&tZ.isMatch(Z,W.config.excludePackages,{contains:!0}))continue;if(Z.includes("node_modules")||Z.includes("/dist/")||j0(Z,W.config)||A0(Z))continue;try{let X=await $.fs.readFile(Z),Y=iZ(X,Z),B=Y.length>0?Y:[pZ(X,Z)];for(let q of B)if(sZ(q,W,A))Q.push(q)}catch{}}return Q.sort(eZ)}function J$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function ZW($){let W=JSON.parse($),j=new Map,A=0,Q=0,Z=0,X=0,Y=0,B=0,q=0,H=0;for(let[G,J]of Object.entries(W)){let b=$6(G,J);j.set(G,b),A+=b.statements.total,Q+=b.statements.covered,Z+=b.branches.total,X+=b.branches.covered,Y+=b.functions.total,B+=b.functions.covered,q+=b.lines.total,H+=b.lines.covered}let V={statements:{covered:Q,total:A,pct:J$(Q,A)},branches:{covered:X,total:Z,pct:J$(X,Z)},functions:{covered:B,total:Y,pct:J$(B,Y)},lines:{covered:H,total:q,pct:J$(H,q)}};return{files:j,total:V}}function $6($,W){let j=Object.keys(W.statementMap).length,A=Object.values(W.s).filter((H)=>H>0).length,Q=Object.keys(W.fnMap).length,Z=Object.values(W.f).filter((H)=>H>0).length,X=0,Y=0;for(let H of Object.values(W.b))X+=H.length,Y+=H.filter((V)=>V>0).length;let B=new Set,q=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(B.add(G),(W.s[H]??0)>0)q.add(G);return{path:$,statements:{covered:A,total:j,pct:J$(A,j)},branches:{covered:Y,total:X,pct:J$(Y,X)},functions:{covered:Z,total:Q,pct:J$(Z,Q)},lines:{covered:q.size,total:B.size,pct:J$(q.size,B.size)}}}function M1($){switch($){case"istanbul":return{parse:ZW};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function E1($,W){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&W?.includes("cobertura"))return"cobertura";return"istanbul"}function N1($,W,j,A){let Q=[];if(j.statements!==void 0&&A.statements.pct<j.statements)Q.push({metric:"statements",required:j.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&A.branches.pct<j.branches)Q.push({metric:"branches",required:j.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&A.functions.pct<j.functions)Q.push({metric:"functions",required:j.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&A.lines.pct<j.lines)Q.push({metric:"lines",required:j.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Q.push({metric:"mutations",required:j.mutations,actual:0,message:`Mutation coverage required (${j.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:W,requirement:j,actual:A,passed:Q.length===0,failures:Q}}async function R1($,W,j){let{fs:A,logger:Q}=$,Z=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],B,q;for(let J of Y)if(await A.exists(J)){B=await A.readFile(J),q=J;break}if(!B)return Q.info("No coverage report found, skipping coverage checks"),Z;let H=E1(q??"coverage.json"),G=M1(H).parse(B);for(let J of W){if(J.specType!=="test-spec"||!J.key||!J.version||!J.sourceBlock)continue;let b=J.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!b||!b[1])continue;let w=b[1],L={},z=w.match(/statements\s*:\s*(\d+)/);if(z&&z[1])L.statements=parseInt(z[1],10);let S=w.match(/branches\s*:\s*(\d+)/);if(S&&S[1])L.branches=parseInt(S[1],10);let U=w.match(/functions\s*:\s*(\d+)/);if(U&&U[1])L.functions=parseInt(U[1],10);let O=w.match(/lines\s*:\s*(\d+)/);if(O&&O[1])L.lines=parseInt(O[1],10);if(Object.keys(L).length===0)continue;let K=N1(J.key,J.version,L,G.total);for(let _ of K.failures)Z.push({ruleId:"coverage-below-threshold",severity:"error",message:_.message,category:"coverage",file:J.filePath,context:{specKey:J.key,specVersion:J.version,metric:_.metric,required:_.required,actual:_.actual}})}return Z}import{addContractNode as W6,buildReverseEdges as j6,createContractGraph as A6,detectCycles as Q6,findMissingDependencies as Z6,parseImportedSpecNames as X6,toDot as Y6}from"@contractspec/module.workspace";async function _8($,W={}){let{fs:j}=$,A=await N$(j,{config:W.config,pattern:W.pattern}),Q=A6();for(let Y of A){let B=await j.readFile(Y),q=j.relative(".",Y),H=j.basename(Y).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",V=X6(B,Y);W6(Q,H,q,V)}j6(Q);let Z=Q6(Q),X=Z6(Q);return{graph:Q,total:Q.size,cycles:Z,missing:X}}function pJ($,W){return $.get(W)}function tJ($){return Y6($)}function aJ($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),A=W.filter((X)=>X.dependencies.length===0),Q=W.filter((X)=>X.dependents.length>0),Z=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:A.length,used:Q.length,unused:Z.length}}i();async function C1($,W){let j=[],A=await m($.fs),Q=await _8($,{config:A,pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" \u2192 ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let X of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${X}`,category:"deps",context:{contract:Z.contract,missing:X}});return j}import{analyzePackageDocBlocks as B6}from"@contractspec/module.workspace";var q6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function H6($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:q6}),A=new Map;for(let X of j){let Y=$.dirname(X),B=$.join(Y,"src");if(!await $.exists(B))continue;try{let q=JSON.parse(await $.readFile(X));A.set(Y,{packageName:q.name??$.relative(W,Y),packageRoot:Y,srcRoot:B})}catch{continue}}let Q=$.join(W,"package.json"),Z=$.join(W,"src");if(await $.exists(Q)&&await $.exists(Z))try{let X=JSON.parse(await $.readFile(Q));A.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:Z})}catch{}return[...A.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function XW($,W){let j=[],A=await H6($,W);for(let Q of A){let Z=B6({packageName:Q.packageName,srcRoot:Q.srcRoot});for(let X of Z.diagnostics)j.push({...X,packageName:Q.packageName,packageRoot:Q.packageRoot,srcRoot:Q.srcRoot})}return j}async function D1($,W){let j=W.workspaceRoot??process.cwd();return(await XW($.fs,j)).map((Q)=>({ruleId:Q.ruleId,severity:Q.severity==="warning"?"warning":"error",message:Q.message,category:"docs",file:Q.file,line:Q.line,column:Q.column,context:{packageName:Q.packageName,packageRoot:Q.packageRoot,...Q.context}}))}async function T1($,W,j){let A=[],Q=await V6($,W);if(A.push(Q),Q.status==="pass")A.push(await G6($,W,j));return A}async function V6($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");try{if(!await $.exists(j))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let Q=await $.readFile(j),Z=JSON.parse(Q),X=Z.aiProvider??"claude",Y=Z.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${X}, Model: ${Y}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function G6($,W,j){let A=$.join(W.workspaceRoot,".contractsrc.json");try{let Q=await $.readFile(A),X=JSON.parse(Q).aiProvider??"claude",B={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!B)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[B])return{category:"ai",name:"API Key",status:"pass",message:`${B} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${B} not set`,details:`Set ${B} in your environment to use AI features`,fix:j?{description:`Set ${B} environment variable`,apply:async()=>{let H=await j.input(`Enter your ${X} API key:`,{password:!0});if(!H)return{success:!1,message:"No API key provided"};let V=$.join(W.workspaceRoot,".env");try{let G="";if(await $.exists(V)){if(G=await $.readFile(V),G.includes(`${B}=`))return{success:!1,message:`${B} already in .env, update manually`};G+=`
1489
+ `}return G+=`${B}=${H}
1490
+ `,await $.writeFile(V,G),{success:!0,message:`Added ${B} to .env (restart required)`}}catch(G){return{success:!1,message:`Failed: ${G instanceof Error?G.message:String(G)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as J6}from"child_process";import{promisify as b6}from"util";var YW=b6(J6);async function F1($,W){let j=[];return j.push(await w6(W)),j.push(await K6(W)),j.push(await _6($,W)),j}async function w6($){try{return await YW("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4}),{category:"cli",name:"CLI Accessible",status:"pass",message:"ContractSpec CLI is accessible"}}catch{return{category:"cli",name:"CLI Accessible",status:"fail",message:"ContractSpec CLI is not accessible",details:'Could not run "bunx contractspec --version"',fix:{description:"Install ContractSpec CLI globally",apply:async()=>{try{return await YW("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(W){return{success:!1,message:`Failed to install: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function K6($){try{let{stdout:W}=await YW("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${W.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function _6($,W){let j=$.join(W.workspaceRoot,"package.json");try{if(!await $.exists(j))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot){let Y=$.join(W.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(Y))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||Z.devDependencies?.["@contractspec/app.cli-contractspec"]!==void 0)return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is installed as a project dependency"};return{category:"cli",name:"Local Installation",status:"warn",message:"CLI is not installed as a project dependency",details:"Consider adding @contractspec/app.cli-contractspec to devDependencies",fix:{description:"Add CLI as a dev dependency",apply:async()=>{try{return await YW("npm install -D @contractspec/app.cli-contractspec",{cwd:W.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(Y){return{success:!1,message:`Failed to install: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}i();import{DEFAULT_CONTRACTSRC as x1}from"@contractspec/lib.contracts-spec/workspace-config";import{join as z6,relative as U6}from"path";var L6="contractspec",O6="contractsrc.schema.json";function S6($){let W=$.replaceAll("\\","/");return W.startsWith(".")?W:`./${W}`}function Z0($){return S6(U6($.configRoot,z6($.workspaceRoot,"node_modules",L6,O6)))}var X0=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md"],z8={"cli-config":"CLI Configuration (.contractsrc.json)","biome-config":"Biome Configuration (biome.jsonc + plugins)","vscode-settings":"VS Code Settings (.vscode/settings.json)","mcp-cursor":"MCP for Cursor (.cursor/mcp.json)","mcp-claude":"MCP for Claude Desktop","cursor-rules":"Cursor AI Rules (.cursor/rules/)","agents-md":"AI Agent Guide (AGENTS.md)"},U8=["core","connect","builder-managed","builder-local","builder-hybrid"],L8={core:"Core workspace setup",connect:"Connect-enabled setup","builder-managed":"Builder setup (managed runtime)","builder-local":"Builder setup (local runtime)","builder-hybrid":"Builder setup (hybrid runtime)"},O8={core:"Generic ContractSpec workspace files and editor wiring.",connect:"Core workspace setup plus Connect config, artifact storage, and adapter defaults.","builder-managed":"Core workspace setup plus Builder config for managed runtime and API-based next steps.","builder-local":"Core workspace setup plus Builder config for local runtime registration.","builder-hybrid":"Core workspace setup plus Builder config for hybrid runtime with API and local defaults."};var Y0={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function B0($){if($?.builder?.enabled)switch($.builder.runtimeMode){case"local":return"builder-local";case"hybrid":return"builder-hybrid";default:return"builder-managed"}if($?.connect?.enabled)return"connect";return"core"}function b$($){return $.preset??"core"}function S8($,W){if(W.length>0)return W;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return X0}}function I8($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function M8($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function bb($){return $.startsWith("builder-")}function wb($){return $==="connect"}function E8($){let W=b$($),j=I6($.projectName);switch(W){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return[`contractspec builder init --workspace-id ${j} --preset managed-mvp`,`contractspec builder status --workspace-id ${j}`];case"builder-local":return[`contractspec builder init --workspace-id ${j} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${j} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return[`contractspec builder init --workspace-id ${j} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${j} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function I6($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function N8($){let W=b$($),j=[Y0.verificationCache];if(W==="connect")j.unshift(Y0.connect);return j}function u$($){let W=$.isMonorepo&&$.scope==="package",j=W&&$.packageRoot?$.packageRoot:$.workspaceRoot,A=M6($),Q=E6($);return{$schema:Z0({configRoot:j,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...A?{connect:A}:{},...Q?{builder:Q}:{},...W&&$.packageName?{package:$.packageName}:{}}}function BW($){let W=b$($),j={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(W==="builder-managed"||W==="builder-hybrid")j["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return j}function q0(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function R8(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function C8($){let W=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
1491
+
1492
+ This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
1493
+
1494
+ ## Spec-First Principle
1495
+
1496
+ - **Always update contracts first** before changing implementation code.
1497
+ - Contracts are the source of truth for operations, events, and presentations.
1498
+ - Implementation code should be generated or derived from contracts.
1499
+ ${$.isMonorepo?`
1500
+ ## Monorepo Structure
1501
+
1502
+ This is a monorepo. Contracts may exist at:
1503
+ - Package level: \`packages/*/src/contracts/\`
1504
+ - Workspace level: \`src/contracts/\`
1505
+
1506
+ Check the appropriate level based on the feature scope.
1507
+ `:""}
1508
+ ## Contract Locations
1509
+
1510
+ Contracts are located in:
1511
+ - \`${A}/operations/\` - Command and query specs
1512
+ - \`${A}/events/\` - Event specs
1513
+ - \`${A}/presentations/\` - UI presentation specs
1514
+ - \`${A}/features/\` - Feature module specs
1515
+
1516
+ ## When Making Changes
1517
+
1518
+ 1. **Before coding**: Check if a contract exists for the feature.
1519
+ 2. **If contract exists**: Update the contract first, then regenerate code.
1520
+ 3. **If no contract**: Create a new contract using \`contractspec create\`.
1521
+ 4. **After changes**: Validate with \`contractspec validate\`.
1522
+
1523
+ ## Key Commands
1524
+
1525
+ - \`contractspec create\` - Scaffold new specs
1526
+ - \`contractspec validate\` - Validate specs
1527
+ - \`contractspec build\` - Generate implementation code
1528
+ - \`contractspec integrity\` - Check contract health
1529
+
1530
+ ## Contract Structure
1531
+
1532
+ Operations follow this pattern:
1533
+ \`\`\`typescript
1534
+ defineCommand({
1535
+ meta: { name: 'service.action', version: '1.0.0', ... },
1536
+ io: { input: InputSchema, output: OutputSchema },
1537
+ policy: { auth: 'user', ... },
1538
+ handler: async (args, ctx) => { ... }
1539
+ });
1540
+ \`\`\`
1541
+
1542
+ ## Rules for ${W}
1543
+
1544
+ - All API endpoints must have a corresponding operation contract.
1545
+ - Events must be declared in contracts before being emitted.
1546
+ - UI components should reference presentation contracts.
1547
+ - Feature flags should be defined in feature modules.
1548
+ `}function D8($){let W=$.projectName??"this project",j=$.isMonorepo&&$.scope==="package",A=b$($),Q=j&&$.packageName?`${$.packageName} package`:W,Z="src/contracts",X=$.isMonorepo?j?`
1549
+ ## Monorepo Scope
1550
+
1551
+ This guide is scoped to the current package.
1552
+ - Prefer package-local contracts under \`src/contracts/\`
1553
+ - Check workspace-level rules only when a change crosses package boundaries.
1554
+ `:`
1555
+ ## Monorepo Scope
1556
+
1557
+ This guide is scoped to the workspace root.
1558
+ - Shared contracts may live in multiple packages under \`packages/*/src/contracts/\`
1559
+ - Prefer the nearest package guide when working inside a specific package.
1560
+ `:"";return`# ContractSpec AI Guide
1561
+
1562
+ Scope: \`${Q}\`
1563
+
1564
+ This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
1565
+
1566
+ ## Core Rules
1567
+
1568
+ - Update contracts before implementation code.
1569
+ - Validate contracts after changes with \`contractspec validate\`.
1570
+ - Regenerate derived artifacts before considering the work complete.
1571
+ - Prefer existing package-local guides and READMEs when working in a nested package.
1572
+ ${X}
1573
+ ## Contract Locations
1574
+
1575
+ - \`src/contracts/operations/\` - command and query specs
1576
+ - \`src/contracts/events/\` - domain and integration events
1577
+ - \`src/contracts/presentations/\` - UI presentation contracts
1578
+ - \`src/contracts/features/\` - feature module contracts
1579
+
1580
+ ## Recommended Workflow
1581
+
1582
+ 1. Check whether a contract already exists for the change.
1583
+ 2. Update or create the contract first.
1584
+ 3. Run validation and generation commands.
1585
+ 4. Review downstream code and tests affected by the contract update.
1586
+
1587
+ ## Key Commands
1588
+
1589
+ - \`contractspec create\` - scaffold a new contract
1590
+ - \`contractspec validate\` - validate contract integrity
1591
+ - \`contractspec build\` - generate implementation artifacts
1592
+ - \`contractspec doctor\` - verify workspace configuration
1593
+
1594
+ ## Working Agreement
1595
+
1596
+ - Keep changes spec-first, deterministic, and reviewable.
1597
+ - Do not change generated outputs without updating their source contract.
1598
+ - When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
1599
+
1600
+ ## Initialization Preset
1601
+
1602
+ - This workspace was initialized with the \`${A}\` setup preset.
1603
+ `}function M6($){if(b$($)!=="connect")return;return{...x1.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin"},codex:{enabled:!0,mode:"wrapper"},"claude-code":{enabled:!0,mode:"rule"}},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:x1.connect?.studio}}function E6($){let W=I8(b$($)),j=M8(b$($));if(!W||!j)return;let A=W==="managed"||W==="hybrid",Q=W==="local"||W==="hybrid";return{...x1.builder,enabled:!0,runtimeMode:W,bootstrapPreset:j,api:A?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:Q?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function qW(){let $=process.platform,W=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${W}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??W}/Claude/claude_desktop_config.json`;default:return`${W}/.config/claude/claude_desktop_config.json`}}function p($,W){let j={...$};for(let A of Object.keys(W)){let Q=$[A],Z=W[A];if(Q===void 0)j[A]=Z;else if(HW(Q)&&HW(Z))j[A]=p(Q,Z)}return j}function y1($,W){let j={...$};for(let A of Object.keys(W)){let Q=$[A],Z=W[A];if(Z===void 0)continue;if(HW(Q)&&HW(Z))j[A]=y1(Q,Z);else j[A]=Z}return j}function HW($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function r($){try{return JSON.parse($)}catch{return null}}function F($){return JSON.stringify($,null,2)+`
1604
+ `}async function v1($,W){let j=[];return j.push(await N6($,W)),j.push(await R6($,W)),j.push(await C6($,W)),j.push(await D6($,W)),j.push(await T6($,W)),j.push(await F6($,W)),j.push(await x6($,W)),j}async function R$($,W){if(W.packageRoot&&W.packageRoot!==W.workspaceRoot&&await $.exists($.join(W.packageRoot,".contractsrc.json")))return W.packageRoot;return W.workspaceRoot}async function N6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(await $.exists(j))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let Q=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(Q)),{success:!0,message:"Created .contractsrc.json"}}catch(Q){return{success:!1,message:`Failed to create: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function R6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j);return JSON.parse(Q),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Q){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Q instanceof Error?Q.message:String(Q),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function C6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=[];if(!Z.outputDir)X.push("outputDir");if(!Z.conventions)X.push("conventions");if(X.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${X.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let Y=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let B of X)if(Y[B]!==void 0)Z[B]=Y[B];return await $.writeFile(j,F(Z)),{success:!0,message:"Added missing fields"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function D6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:Z.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return Z.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,F(Z)),{success:!0,message:"Added versioning configuration"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function T6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.hooks){let B=Z.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(B).length} git hook(s) configured`}}let X=$.join(W.workspaceRoot,".husky");if(await $.exists(X))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return Z.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,F(Z)),{success:!0,message:"Added hooks configuration"}}catch(B){return{success:!1,message:`Failed: ${B instanceof Error?B.message:String(B)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function F6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(Q==="connect"){let Y=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((H)=>H!==null),B=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(Y.length===0&&!B)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...Y,...B?["connect.studio.endpoint"]:[]].join(", ")}`}}let Z=[],X=A.builder?.api?.controlPlaneTokenEnvVar;if((Q==="builder-managed"||Q==="builder-hybrid")&&!A.builder?.api?.baseUrl)Z.push("builder.api.baseUrl");if((Q==="builder-managed"||Q==="builder-hybrid")&&!X)Z.push("builder.api.controlPlaneTokenEnvVar");if((Q==="builder-managed"||Q==="builder-hybrid")&&X&&!process.env[X])Z.push(`env:${X}`);if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)Z.push("builder.localRuntime.runtimeId");if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)Z.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:Z.length===0?"pass":"warn",message:Z.length===0?`Builder preset inferred (${Q}) and required config is present`:`Builder preset inferred (${Q}) but setup is missing ${Z.join(", ")}`}}async function x6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q!=="builder-managed"&&Q!=="builder-hybrid")return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder managed/hybrid preset is not enabled"};let Z=$.join(j,".vscode","settings.json"),X=A.builder?.api?.baseUrl;if(!X)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let Y=await $.readFile(Z).catch(()=>""),B=Y?r(Y):void 0;if(B?.["contractspec.api.baseUrl"]===X)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let H=$.join(j,".vscode");if(!await $.exists(H))await $.mkdir(H);let V={...B??{},...BW({workspaceRoot:W.workspaceRoot,packageRoot:W.packageRoot,isMonorepo:W.isMonorepo,packageName:W.packageName,interactive:!1,preset:Q,targets:[],builderApiBaseUrl:X})};return await $.writeFile(Z,F(V)),{success:!0,message:"Updated VS Code settings mirror"}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}}}import{exec as y6}from"child_process";import{promisify as v6}from"util";var C$=v6(y6);async function m1($,W){let j=[];return j.push(await m6(W)),j.push(await P6(W)),j.push(await k6($,W)),j.push(await h6($,W)),j.push(await g6($,W)),j}async function m6($){try{let{stdout:W}=await C$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${W.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function P6($){try{let{stdout:W}=await C$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${W.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function k6($,W){let j=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:Q,name:Z}of j){let X=$.join(W.workspaceRoot,Q);if(await $.exists(X)){A=Z;break}}if(!A){let Q=$.join(W.workspaceRoot,".."),Z=$.join(W.workspaceRoot,"../.."),X=[Q,Z];for(let Y of X){for(let{file:B,name:q}of j){let H=$.join(Y,B);if(await $.exists(H)){A=q;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await C$(`${A} --version`,{cwd:W.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function h6($,W){let j=$.join(W.workspaceRoot,"node_modules");if(await $.exists(j))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await C$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function g6($,W){let j=$.join(W.workspaceRoot,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A),Z={...Q.dependencies,...Q.devDependencies};if("@contractspec/lib.contracts-spec"in Z)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${Z["@contractspec/lib.contracts-spec"]})`};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await C$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function P1($,W){let j=await XW($,W.workspaceRoot);if(j.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return j.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(W.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as f6,isFeatureFile as u6,scanAllSpecsFromSource as d6,scanExampleSource as n6,scanFeatureSource as c6}from"@contractspec/module.workspace";function r6(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function VW($,W={}){let{fs:j,logger:A}=$,Q=r6(),Z=W.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let X=await j.glob({pattern:Z});for(let B of X){if(B.includes("node_modules")||B.includes("/dist/"))continue;try{let q=await j.readFile(B);if(u6(B)){let H=c6(q,B);Q.features.set(H.key,H);continue}if(f6(B)){let H=n6(q,B);Q.examples.set(H.key,H);continue}if(B.includes(".app-config.")||B.includes(".blueprint.")){let H=d6(q,B);for(let V of H)if(V.specType==="app-config"&&V.key)Q.appConfigs.set(V.key,V)}}catch{}}try{let B=await j.glob({pattern:"**/.contractsrc.json"});for(let q of B){if(q.includes("node_modules"))continue;try{let H=await j.readFile(q),V=JSON.parse(H);Q.workspaceConfigs.set(q,{file:q,config:V,valid:!0,errors:[]})}catch(H){Q.workspaceConfigs.set(q,{file:q,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Q.features.size,examples:Q.examples.size,appConfigs:Q.appConfigs.size,workspaceConfigs:Q.workspaceConfigs.size,total:Q.features.size+Q.examples.size+Q.appConfigs.size+Q.workspaceConfigs.size};return A.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Q,stats:Y}}function yb($){let W=[];for(let[j,A]of $.features)W.push({key:j,file:A.filePath,type:"feature"});for(let[j,A]of $.examples)W.push({key:j,version:A.version,file:A.filePath,type:"example"});for(let[j,A]of $.appConfigs)W.push({key:j,version:A.version,file:A.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function GW($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function k1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function JW($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let A=await $.readFile(j),Q=JSON.parse(A);return{version:typeof Q.version==="number"&&Number.isFinite(Q.version)?Q.version:1,criticalPackages:k1(Q.criticalPackages).map(GW),criticalFeatureKeys:k1(Q.criticalFeatureKeys),smokePackages:k1(Q.smokePackages)}}catch{return}}function T8($,W){let j=GW($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function F8($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function d$($){return GW(`${GW($)}/config/stability-policy.json`)}async function h1($,W){let j=[],A=await JW($,W.workspaceRoot),Q=await VW({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(l6(Q.stats.features)),j.push(o6(Q.stats.examples)),j.push(i6(Q.inventory.features,A,W)),j.push(p6(Q.inventory.examples)),j.push(t6(Q.inventory.workspaceConfigs)),j}function l6($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function o6($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function i6($,W,j){let A=[],Q=[];for(let[Z,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(F8(Z,W))Q.push(Z);else A.push(Z);if(Q.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Q.length>0?"fail":"warn",message:Q.length>0?`${Q.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:Q.length>0?`Critical features: ${Q.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:Q,missingFeatures:A}}}function p6($){let W=[];for(let[j,A]of $)if(!A.entrypoints.packageName)W.push(j);if(W.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${W.length} example(s) missing packageName`,details:`Examples: ${W.join(", ")}`}}function t6($){let W=[];for(let[,j]of $)if(!j.valid)W.push(j.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(W.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${W.length} workspace config(s) invalid`,details:`Files: ${W.join(", ")}`}}async function g1($,W){let j=[];return j.push(await a6($,W)),j.push(await s6($,W)),j.push(await e6($,W)),j}async function a6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(await $.exists(j))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let Q=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Q))await $.mkdir(Q);let Z=q0();return await $.writeFile(j,F(Z)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function s6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(!await $.exists(j))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let Y=q0(),B=p(Z,Y);return await $.writeFile(j,F(B)),{success:!0,message:"Registered MCP server"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function e6($,W){let j=qW();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Q=await $.readFile(j);if(JSON.parse(Q).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var $7=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],x8=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function W7($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,A])=>{if(typeof A==="string")W[j]=A;return W},{})}function j7($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function A7($,W,j){let A=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:x8}),Q=[];for(let Z of A){let X=$.dirname(Z),Y=$.relative(W,X);try{let B=JSON.parse(await $.readFile(Z)),q=W7(B.scripts),H=await $.glob({patterns:$7,cwd:X,ignore:x8});Q.push({packageName:B.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof q.build==="string",hasTypecheckScript:typeof q.typecheck==="string",hasLintScript:typeof q.lint==="string"||typeof q["lint:check"]==="string",hasTestScript:typeof q.test==="string",usesPassWithNoTests:j7(q),testFileCount:H.length,tier:T8(Y,j)})}catch{continue}}return Q}function Q7($){let W=[];if(!$.hasBuildScript)W.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)W.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)W.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)W.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)W.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)W.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return W}function Z7($){let W=[];if($.testFileCount>0&&!$.hasTestScript)W.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)W.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return W}async function y8($,W,j){let A=await A7($,W,j),Q=[];for(let X of A){if(X.tier==="critical")Q.push(...Q7(X));Q.push(...Z7(X))}let Z=A.filter((X)=>X.tier==="critical").map((X)=>({packageName:X.packageName,packagePath:X.packagePath,hasBuildScript:X.hasBuildScript,hasTypecheckScript:X.hasTypecheckScript,hasLintScript:X.hasLintScript,hasTestScript:X.hasTestScript,usesPassWithNoTests:X.usesPassWithNoTests,testFileCount:X.testFileCount}));return{findings:Q,criticalPackages:Z}}function m8($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function v8($,W,j,A){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let Q=W.filter((Z)=>{return Z.tier==="critical"||j.has(Z.code)});return{category:"workspace",name:$,status:Q.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:m8(W),context:{findings:W}}}async function P8($,W){let j=await JW($,W.workspaceRoot);if(!j)return[];let A=await y8($,W.workspaceRoot,j),Q=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),Z=A.findings.filter((B)=>Q.has(B.code)),X=A.findings.filter((B)=>B.code==="tests-without-test-script"),Y=A.findings.filter((B)=>B.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:Z.length>0?"fail":"pass",message:Z.length>0?`${Z.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:Z.length>0?m8(Z):W.verbose?`Policy: ${d$(W.workspaceRoot)}`:void 0,context:{policyPath:d$(W.workspaceRoot),criticalPackages:A.criticalPackages,findings:Z}},v8("Package Test Scripts",X,new Set,"All tested packages expose a test script"),v8("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var X7=["src/contracts","contracts","src/specs","specs"];async function f1($,W){let j=[];return j.push(Y7(W)),j.push(await B7($,W)),j.push(await q7($,W)),j.push(await H7($,W)),j.push(await G7($,W)),j.push(...await P8($,W)),j}function Y7($){if($.isMonorepo){let W=$.packageName?` in package "${$.packageName}"`:"",j=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${W}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${j}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function B7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let A of j){let Q=$.join(A,"package.json");if(await $.exists(Q))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function q7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],A=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of X7){let B=$.join(X,Y);if(await $.exists(B)){let q=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${q} level`:void 0}}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let Q=W.isMonorepo?"src/contracts":"src/contracts",Z=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Q}/${Z} to organize your specs`,fix:{description:`Create ${Q}/ directory${Z}`,apply:async()=>{try{let X=$.join(A,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Q}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function H7($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=W.isMonorepo?W.packageRoot:W.workspaceRoot,Q=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:A});if(Q.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Q.length} contract file(s)${X}`,details:W.verbose?Q.slice(0,5).join(", "):void 0}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:W.isMonorepo?`No contract files found in package "${W.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function V7($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let A=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:W.packageRoot,level:"package"}}let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{path:j,root:W.workspaceRoot,level:"workspace"};return null}async function G7($,W){try{let j=await V7($,W);if(!j)return{category:"workspace",name:"Output Directory",status:"skip",message:W.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(j.path),Q=JSON.parse(A),Z=Q.outputDir??"./src",X=$.join(j.root,Z),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${Z}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let q=Z==="./src"||Z==="src",H=Array.isArray(Q.packages)&&Q.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&q&&(H||j.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:W.verbose?`Resolved default output to packages via ${j.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${Z}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${Z} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${Z}`}}catch(V){return{success:!1,message:`Failed: ${V instanceof Error?V.message:String(V)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var k8=["cli","config","mcp","deps","docs","workspace","ai","layers"],h8={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var J7={checks:{runCliChecks:F1,runConfigChecks:v1,runMcpChecks:g1,runDepsChecks:m1,runDocChecks:P1,runWorkspaceChecks:f1,runAiChecks:T1,runLayerChecks:h1},workspace:{findWorkspaceRoot:D,findPackageRoot:f,isMonorepo:e$,getPackageName:I$}},b7={confirm:async()=>!1,input:async()=>""};async function g8($,W,j=b7,A=J7){let{fs:Q,logger:Z}=$,X=W.categories??k8,{checks:Y,workspace:B}=A,q=B.findWorkspaceRoot(W.workspaceRoot),H=B.findPackageRoot(W.workspaceRoot),V=B.isMonorepo(q),G=V?B.getPackageName(H):void 0,J={workspaceRoot:q,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let U=G?` (package: ${G})`:"";Z.info(`Detected monorepo${U}`)}let b=[];for(let U of X){if(W.skipAi&&U==="ai")continue;Z.info(`Checking ${h8[U]}...`);let O=await w7(U,Q,J,j,Y);for(let K of O){if(K.fix&&(K.status==="fail"||K.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${K.name}"? ${K.fix.description}`)){Z.info(`Applying fix: ${K.fix.description}`);let I=await K.fix.apply();if(I.success)Z.info(`\u2713 ${I.message}`),K.status="pass",K.message=`Fixed: ${I.message}`,K.fix=void 0;else Z.warn(`\u2717 ${I.message}`)}}b.push(K)}}let w=b.filter((U)=>U.status==="pass").length,L=b.filter((U)=>U.status==="warn").length,z=b.filter((U)=>U.status==="fail").length,S=b.filter((U)=>U.status==="skip").length;return{checks:b,passed:w,warnings:L,failures:z,skipped:S,healthy:z===0}}async function w7($,W,j,A,Q){switch($){case"cli":return Q.runCliChecks(W,j);case"config":return Q.runConfigChecks(W,j);case"mcp":return Q.runMcpChecks(W,j);case"deps":return Q.runDepsChecks(W,j);case"docs":return Q.runDocChecks(W,j);case"workspace":return Q.runWorkspaceChecks(W,j);case"ai":return Q.runAiChecks(W,j,A);case"layers":return Q.runLayerChecks(W,j);default:return[]}}function Bw($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("\u2713 All checks passed!");else W.push("\u2717 Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
1605
+ `)}function qw($){let j=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)j+=`
1606
+ ${$.details}`;if($.fix)j+=`
1607
+ Fix available: ${$.fix.description}`;return j}async function u1($,W){let j=[],A=W.workspaceRoot??process.cwd(),Q=await g8($,{workspaceRoot:A,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let Z of Q.checks)if(Z.status==="fail")j.push({ruleId:`doctor-${Z.category}-${Z.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${Z.name}: ${Z.message}`,category:"doctor",context:{details:Z.details,...Z.context??{}}});else if(Z.status==="warn")j.push({ruleId:`doctor-${Z.category}-${Z.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${Z.name}: ${Z.message}`,category:"doctor",context:{details:Z.details,...Z.context??{}}});return j}i();import{mkdtemp as F7,rm as x7}from"fs/promises";import{tmpdir as y7}from"os";import H0 from"path";import{DEFAULT_CONTRACTSRC as I7}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as M7}from"@contractspec/module.workspace";import E7 from"path";import{packageDocBlocks as K7}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as _7,convertSpecToDocBlock as z7,extractModuleDocData as U7,loadSpecFromSource as L7,scanAllSpecsFromSource as O7,scanSpecSource as S7}from"@contractspec/module.workspace";import n1 from"path";import{dirname as f8,sep as bW}from"path";class d1{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let W of $){let j;if(W.specType==="app-config")j="app-config";else if(W.specType==="example")j="example";else if(W.specType==="feature")j="feature";if(j&&W.key){let A=f8(W.filePath);this.modules.push({type:j,key:W.key,dirPath:A})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let W=f8($),j=this.modules.filter((A)=>{let Q=A.dirPath.endsWith(bW)?A.dirPath:A.dirPath+bW;return(W.endsWith(bW)?W:W+bW).startsWith(Q)||W===A.dirPath});if(j.length===0)return;return j.sort((A,Q)=>{let Z={"app-config":3,example:2,feature:1},X=Z[A.type],Y=Z[Q.type];if(X!==Y)return Y-X;return Q.dirPath.length-A.dirPath.length}),j[0]}}async function d8($,W,j){let{fs:A,logger:Q}=j,Z=[];if(Q.info(`Generating docs for ${$.length} files...`),W.outputDir)await A.mkdir(W.outputDir);let X=new d1(j),Y=[];for(let q of $)try{let H=await A.readFile(q),V=O7(H,q);if(V.length>0)Y.push(...V);else{let G=S7(H,q);if(G.specType!=="unknown")Y.push(G)}}catch(H){}X.initialize(Y);let B=await n8($,j);for(let q of B)if(Z.push(q.entry.block),Q.debug(`Loaded authored doc ${q.entry.id}`),W.outputDir)await u8(q.entry.block,q.filePath,W.outputDir,X,A);for(let q of $)try{let H=await L7(q);if(!H?.length){Q.warn(`Could not parse spec from ${q}`);continue}for(let V of H){let G=z7(V,{rootPath:W.rootPath});if(Z.push(G),Q.debug(`Generated doc for ${G.id}`),!W.outputDir)continue;await u8(G,q,W.outputDir,X,A)}}catch(H){Q.error(`Error processing ${q}: ${H instanceof Error?H.message:String(H)}`)}if(W.outputDir)Q.info(`Wrote ${Z.length} doc files to ${W.outputDir}`);return{blocks:Z,count:Z.length}}async function Uw($,W){return(await n8($,W)).map(({entry:A})=>A.block)}function Lw($,W){return K7(_7({packageName:$,srcRoot:W}))}async function n8($,W){let j=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z)),A=[];for(let Q of j){let Z=await W.fs.readFile(Q),X=Q.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),Y=U7(Z,Q,X);for(let B of Y.entries)A.push({entry:B,filePath:Q})}return A}async function u8($,W,j,A,Q){let Z=A.resolve(W),X=Z?n1.join(j,Z.key):n1.join(j,"_common");await Q.mkdir(X);let Y=n1.join(X,`${$.id}.md`),B=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
1608
+
1609
+ ${$.body}`;await Q.writeFile(Y,B)}async function c8($,W,j,A,Q={}){let Z=Q.config,X=await QW($,{cwd:Q.specSearchRoot,config:Z,pattern:Q.specPattern??R7(W,Q)});if(X.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let Y=E7.join(C7(j,Z),"docs"),B=await d8(X.map((H)=>H.filePath),{outputDir:Y,format:"markdown",rootPath:A},$),q=0;for(let H of X){let V=N7(H);if(!V||V.materialization==="none"||V.materialization==="docs")continue;let G=await f$(H.filePath,$,Z??I7,{targets:L1(H.specType,{includeTests:Boolean(Q.includeRuntimeTests)}),outputDir:Z?.outputDir??"./src",overwrite:!1});q+=G.results.filter((J)=>J.success).length}return{specsCount:X.length,docsCount:B.count,materializedCount:q}}function N7($){return M7($.specType)}function R7($,W){if(W.config&&!W.specPattern)return;if(W.scanAllSpecs)return W.specPattern;return $?`${c1($)}/**/*.ts`:void 0}function C7($,W){let j=(W?.connect?.policy?.generatedPaths??[]).map(T7).filter(Boolean);if(j.length>0)return j[0];if(W?.outputDir&&W.outputDir!=="./src")return c1(W.outputDir);return $}function D7($){return c1($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function T7($){let W=D7($);return W.endsWith("/docs")?W.replace(/\/docs$/,""):W}function c1($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function wW($,W,j,A={}){let Q=await F7(H0.join(y7(),"contractspec-drift-"));try{await c8($,W,Q,A.rootPath,A.generation);let Z=[],X=await import("fs/promises");async function Y(G){let J=await X.readdir(G,{withFileTypes:!0}),b=[];for(let w of J){let L=H0.resolve(G,w.name);if(w.isDirectory())b.push(...await Y(L));else b.push(L)}return b}let B=async(G)=>{if(!await X.stat(G).catch(()=>!1))return[];return(await Y(G)).map((b)=>H0.relative(G,b)).sort()},q=await B(Q),H=await B(j),V=new Set([...q,...H]);for(let G of V){if(!H.includes(G)){Z.push(G);continue}if(!q.includes(G)){Z.push(G);continue}let J=await X.readFile(H0.join(Q,G)),b=await X.readFile(H0.join(j,G));if(!J.equals(b))Z.push(G)}return{hasDrift:Z.length>0,files:Z}}finally{await x7(Q,{recursive:!0,force:!0})}}async function r1($,W){let{fs:j,logger:A}=$,Q=[],Z=await m(j);if(!Z.outputDir)return A.info("No outputDir configured, skipping drift checks"),Q;let X="./contracts",Y=Z.outputDir;if(!await j.exists(Y))return A.info("Generated directory does not exist, skipping drift checks"),Q;try{let B=await wW($,X,Y);if(B.hasDrift)for(let q of B.files)Q.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${q}`,category:"drift",file:`${Y}/${q}`,context:{file:q}})}catch(B){A.warn("Drift detection failed",{error:B instanceof Error?B.message:String(B)})}return Q}i();function v7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function m7($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}async function KW($,W,j,A={}){let{fs:Q}=W,Z=[],X=[],Y=$.key??Q.basename($.filePath).replace(/\.[jt]s$/,""),B=A.outputDir??j.outputDir??"./src",q=v7(Y),H={};if($.specType==="operation")H.handlerPath=Q.join(B,"handlers",`${q}.handler.ts`),H.handlerTestPath=Q.join(B,"handlers",`${q}.handler.test.ts`);if($.specType==="presentation")H.componentPath=Q.join(B,"components",`${q}.tsx`),H.componentTestPath=Q.join(B,"components",`${q}.test.tsx`);if($.specType==="form")H.formPath=Q.join(B,"forms",`${q}.form.tsx`),H.formTestPath=Q.join(B,"forms",`${q}.form.test.tsx`);if(A.checkHandlers&&H.handlerPath)if(!await Q.exists(H.handlerPath))Z.push(`Missing handler file: ${H.handlerPath}`);else{let G=await Q.readFile(H.handlerPath),J=`${m7(Y.split(".").pop()??Y)}Spec`,b=/ContractHandler<\s*typeof\s+\w+\s*>/.test(G),w=new RegExp(`typeof\\s+${J}\\b`).test(G);if(!b)X.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${H.handlerPath}`);else if(!w)X.push(`Handler ContractHandler typing does not reference expected spec var (${J}): ${H.handlerPath}`)}if(A.checkTests){let V=[H.handlerTestPath,H.componentTestPath,H.formTestPath].filter((G)=>typeof G==="string");for(let G of V)if(!await Q.exists(G))Z.push(`Missing test file: ${G}`)}return{valid:Z.length===0,errors:Z,warnings:X,expected:H}}async function l1($,W){let{fs:j}=$,A=[],Q=await m(j);for(let Z of W){if(Z.specType!=="operation")continue;let X=await KW(Z,{fs:j},Q,{checkHandlers:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"handler-missing",severity:"warning",message:Y,category:"handlers",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"handler-warning",severity:"warning",message:Y,category:"handlers",file:Z.filePath})}return A}i();import{createHash as u7}from"crypto";import d7 from"path";var V0={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},P7={".handler.ts":"handler",".handler.tsx":"handler",".service.ts":"service",".service.tsx":"service",".test.ts":"test",".test.tsx":"test",".spec.ts":"test",".spec.tsx":"test",".component.tsx":"component",".tsx":"component",".form.tsx":"form",".hook.ts":"hook",".hook.tsx":"hook"};function k7($){let W=$.toLowerCase();for(let[j,A]of Object.entries(P7))if(W.endsWith(j))return A;if(W.includes("/handlers/"))return"handler";if(W.includes("/services/"))return"service";if(W.includes("/components/"))return"component";if(W.includes("/forms/"))return"form";if(W.includes("/hooks/"))return"hook";if(W.includes("/__tests__/"))return"test";return"other"}function r8($,W){let j=[],A=new Set,Q=(G,J,b)=>{let w=`${G}:${J}`;if(A.has(w))return;A.add(w),j.push({filePath:W,specKey:G,referenceType:J,lineNumber:b,inferredType:k7(W)})},Z=(G)=>{return $.substring(0,G).split(`
1610
+ `).length},X,Y=new RegExp(V0.contractHandler);while((X=Y.exec($))!==null)if(X[1])Q(X[1],"handler",Z(X.index));let B=new RegExp(V0.typeofSpec);while((X=B.exec($))!==null)if(X[1])Q(X[1],"typeof",Z(X.index));let q=new RegExp(V0.namedImport);while((X=q.exec($))!==null){let J=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(J)for(let b of J)Q(b,"import",Z(X.index))}let H=new RegExp(V0.defaultImport);while((X=H.exec($))!==null)if(X[1])Q(X[1],"import",Z(X.index));let V=new RegExp(V0.specAssignment);while((X=V.exec($))!==null)if(X[1])Q(X[1],"unknown",Z(X.index));return j}var l8=["**/*.ts(x)"];async function _W($,W,j={}){let{fs:A}=W,Q=j.includePatterns??l8,Z=j.excludePatterns??[...new Set([...S$,...Y$])],X=[];for(let Y of Q){let B=await A.glob({pattern:Y,ignore:Z});for(let q of B)try{let H=await A.readFile(q),G=r8(H,q).filter((J)=>J.specKey===$);X.push(...G)}catch{}}return X}async function rw($,W={}){let{fs:j}=$,A=W.includePatterns??l8,Q=W.excludePatterns??[...new Set([...S$,...Y$])],Z=new Map;for(let X of A){let Y=await j.glob({pattern:X,ignore:Q});for(let B of Y)try{let q=await j.readFile(B),H=r8(q,B);for(let V of H){let G=Z.get(V.specKey)??[];G.push(V),Z.set(V.specKey,G)}}catch{}}return Z}function h7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o8($,W,j){let A=h7(W),Q=[];if($==="operation")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")Q.push({path:`${j}/components/${A}.tsx`,type:"component"}),Q.push({path:`${j}/components/${A}.test.tsx`,type:"test"});if($==="form")Q.push({path:`${j}/forms/${A}.form.tsx`,type:"form"}),Q.push({path:`${j}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});return Q}import{Node as c,Project as g7,SyntaxKind as f7}from"ts-morph";function i8($){let W=[],A=new g7({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Q=(B)=>{if(!c.isObjectLiteralExpression(B))return;let q=B.getProperty("implementations");if(q&&c.isPropertyAssignment(q)){let H=q.getInitializer();if(H&&c.isArrayLiteralExpression(H)){for(let V of H.getElements())if(c.isObjectLiteralExpression(V)){let G,J,b,w=V.getProperty("path");if(w&&c.isPropertyAssignment(w)){let S=w.getInitializer();if(c.isStringLiteral(S))G=S.getLiteralText()}let L=V.getProperty("type");if(L&&c.isPropertyAssignment(L)){let S=L.getInitializer();if(c.isStringLiteral(S))J=S.getLiteralText()}let z=V.getProperty("description");if(z&&c.isPropertyAssignment(z)){let S=z.getInitializer();if(c.isStringLiteral(S))b=S.getLiteralText()}if(G&&J)W.push({path:G,type:J,description:b})}}}},Z=A.getDescendantsOfKind(f7.CallExpression);for(let B of Z){let q=B.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(q)){let H=B.getArguments();if(H.length>0&&c.isObjectLiteralExpression(H[0]))return Q(H[0]),W}}let X=A.getVariableStatements();for(let B of X)if(B.isExported())for(let q of B.getDeclarations()){let H=q.getInitializer();if(H&&c.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Q(H),W}}let Y=A.getExportAssignment((B)=>!B.isExportEquals());if(Y){let B=Y.getExpression();if(c.isObjectLiteralExpression(B))Q(B);else if(c.isAsExpression(B)&&c.isObjectLiteralExpression(B.getExpression()))Q(B.getExpression())}return W}function p8($){if($.length===0)return"missing";let W=$.filter((Q)=>Q.exists),j=$.filter((Q)=>Q.type!=="test");if(W.filter((Q)=>Q.type!=="test").length===0)return"missing";if($.every((Q)=>Q.exists))return"implemented";return"partial"}function tw($){let W=$.filter((Q)=>Q.status==="implemented").length,j=$.filter((Q)=>Q.status==="partial").length,A=$.filter((Q)=>Q.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:A,coverage:$.length>0?Math.round(W/$.length*100):100}}var n7={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function t8($){return u7("sha256").update($).digest("hex")}async function c7($,W,j,A={},Q){let Z={...n7,...A},X=Z.computeHashes?t8($.sourceBlock||""):void 0,Y=$.key??d7.basename($.filePath).replace(/\.[jt]s$/,""),B=$.version??"1.0.0",{fs:q}=W,H=[],V=new Set,G=async(b,w,L,z)=>{if(V.has(b))return;V.add(b);let S=await q.exists(b),U=void 0,O=void 0;if(S&&Z.computeHashes)try{U=await q.readFile(b),O=t8(U)}catch{}H.push({path:b,type:w,source:L,exists:S,implementationSourceContent:U,implementationSourceHash:O,description:z})};if(Z.includeExplicit&&$.sourceBlock){if(Q)Q.suffixText="Discover explicit implementations";let b=i8($.sourceBlock);for(let w of b)await G(w.path,w.type,"explicit",w.description)}if(Z.includeDiscovered){if(Q)Q.suffixText="Discover implementations";let b=await _W(Y,W,Z);for(let w of b){if(w.filePath===$.filePath)continue;await G(w.filePath,w.inferredType,"discovered")}}if(Z.includeConvention){if(Q)Q.suffixText="Discover implementations based on conventions";let b=Z.outputDir??j.outputDir??"./src",w=o8($.specType,Y,b);for(let{path:L,type:z}of w)await G(L,z,"convention")}if(Q)Q.suffixText="Determine implementation status";let J=p8(H);return{specKey:Y,specVersion:B,specPath:$.filePath,specType:$.specType,implementations:H,status:J,specHash:X}}async function a8($,W,j,A={},Q){let Z=[];for(let X of $){if(Q)Q.text=`Resolving implementation... (${Z.length}/${$.length})`;try{let Y=await c7(X,W,j,A,Q);Z.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return Z}async function o1($,W,j){let{fs:A}=$,Q=[],Z=await m(A),X=j.implementation??{},Y=W.filter((q)=>q.specType==="operation"),B=await a8(Y,{fs:A},Z,{computeHashes:X.useCache??!0});for(let q of B){if(X.requireImplemented&&q.status==="missing")Q.push({ruleId:"impl-missing",severity:"error",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});else if(q.status==="missing")Q.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});if(!X.allowPartial&&q.status==="partial"){let V=q.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Q.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${q.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status,missingFiles:V}})}let H=q.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Q.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${q.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,missingTests:H.map((V)=>V.path)}})}return Q}import{isFeatureFile as o7,scanAllSpecsFromSource as i7,scanFeatureSource as p7}from"@contractspec/module.workspace";function r7($,W){return`${$}.v${W}`}function i1($,W,j,A,Q,Z={}){let{treatMissingAsError:X=!0}=Z;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],B=[],q=[];for(let H of A){let V=r7(H.key,H.version);if(Q.has(V))Y.push(H);else if(B.push(H),X)q.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:B.length===0,foundTests:Y,missingTests:B,errors:q,specFile:$}}function s8($,W){return`${$}.v${W}`}function e8($,W){let j=new Map,A=new Map,Q=[],Z=[];for(let X of $){if(!X.key||!X.version)continue;let Y=s8(X.key,X.version);if(!X.testTarget){Z.push(Y);continue}let{type:B,key:q,version:H}=X.testTarget,V=H??X.version,G=s8(q,V),J=l7(W,B);if(!J||!J.has(G)){Q.push(Y);continue}if(A.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:A,orphanedTests:Q,testsWithoutTarget:Z}}function l7($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function t($,W){return`${$}.v${W}`}function t7(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function p1($,W){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[W]}async function zW($,W={}){let{fs:j,logger:A}=$;A.info("Starting integrity analysis...",{options:W});let Q=await N$(j,{config:W.config,cwd:W.cwd,pattern:W.pattern}),Z=t7(),X=[],Y=[];for(let K of Q){if((await j.stat(K)).isDirectory)continue;let I=await j.readFile(K);if(o7(K)){let M=p7(I,K);X.push(M)}else{let M=i7(I,K);for(let E of M)if(E.specType!=="unknown"&&E.specType!=="feature"){let C=p1(Z,E.specType);if(C&&E.key&&E.version!==void 0){let R=t(E.key,E.version);C.set(R,{key:E.key,version:E.version,file:E.filePath,type:E.specType,stability:E.stability,testTarget:E.testTarget,testCoverage:E.testCoverage})}}}}let B=W.featureKey?X.filter((K)=>K.key===W.featureKey):X,q=new Set;for(let K of B){for(let _ of K.operations){let I=t(_.key,_.version);if(q.add(`operation:${I}`),!Z.operations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_})}for(let _ of K.events){let I=t(_.key,_.version);if(q.add(`event:${I}`),!Z.events.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"event",ref:_})}for(let _ of K.presentations){let I=t(_.key,_.version);if(q.add(`presentation:${I}`),!Z.presentations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_})}for(let _ of K.experiments){let I=t(_.key,_.version);if(q.add(`experiment:${I}`),!Z.experiments.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"experiment",ref:_})}for(let _ of K.capabilities.provides){let I=t(_.key,_.version);if(q.add(`capability:${I}`),!Z.capabilities.has(I))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"capability",ref:_})}for(let _ of K.capabilities.requires){let I=t(_.key,_.version);q.add(`capability:${I}`)}for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=t(_.pres.key,_.pres.version);if(!Z.operations.has(I))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${_.op.key}.v${_.op.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op});if(!Z.presentations.has(M))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${_.pres.key}.v${_.pres.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_.pres})}if(K.presentationsTargets)for(let _ of K.presentationsTargets){let I=t(_.key,_.version);if(!Z.presentations.has(I))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:{key:_.key,version:_.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let K of V){let _=p1(Z,K);if(!_)continue;for(let[I,M]of _)if(!q.has(`${K}:${I}`))H.push(M),Y.push({severity:"warning",type:"orphaned",message:`${K} ${M.key}.v${M.version} is not linked to any feature`,file:M.file,specKey:M.key,specType:M.type})}let G=[];for(let[,K]of Z.testSpecs)G.push({filePath:K.file,specType:"test-spec",key:K.key,version:K.version,testTarget:K.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let J=e8(G,Z);for(let K of B)for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=J.targetToTests.get(I),E=!1,C=!1;if(M)for(let R of M){let v=Z.testSpecs.get(R);if(v?.testCoverage){if(v.testCoverage.hasSuccess)E=!0;if(v.testCoverage.hasError)C=!0}}if(!M||!E||!C){let R=[];if(!E)R.push("success scenario");if(!C)R.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${_.op.key}.v${_.op.version} linked to presentation requires tests covering: ${R.join(", ")}`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op})}}let b={},w=0;for(let K of V){let _=p1(Z,K);if(!_)continue;let I=_.size,M=0,E=0,C=W.requireTestsFor?.includes(K);for(let[R,v]of _){if(q.has(`${K}:${R}`))M++;if(C){let x=t(v.key,v.version),L$=J.targetToTests.has(x),v0=`${v.key}.test`,zA=Z.testSpecs.has(t(v0,v.version));if(!L$&&!zA)E++,w++,Y.push({severity:"warning",type:"missing-test",message:`${K} ${v.key}.v${v.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:v.file,specKey:v.key,specType:v.type})}}b[K]={total:I,covered:M,orphaned:I-M,missingTest:C?E:0}}let L=Object.values(b).reduce((K,_)=>K+_.total,0),z=Object.values(b).reduce((K,_)=>K+_.covered,0),S={total:L,linkedToFeature:z,orphaned:L-z,missingTest:w,byType:b},O=!Y.some((K)=>K.severity==="error");return A.info("Integrity analysis complete",{features:X.length,totalSpecs:L,orphaned:H.length,issues:Y.length,healthy:O}),{inventory:Z,features:B,coverage:S,issues:Y,orphanedSpecs:H,healthy:O}}function _K($){let W=[];for(let j of Object.values($))for(let A of j.values())W.push(A);return W}function zK($,W){return $.filter((j)=>j.type===W)}function UK($,W){return $.filter((j)=>j.severity===W)}i();async function t1($,W){let j=[],A=await m($.fs),Q=await zW($,{config:A,pattern:W.pattern,all:!0});for(let Z of Q.issues)j.push({ruleId:`integrity-${Z.type}`,severity:Z.severity==="error"?"error":"warning",message:Z.message,category:"integrity",file:Z.file,context:{specKey:Z.specKey,specType:Z.specType,featureKey:Z.featureKey,ref:Z.ref}});return j}async function a1($,W){let j=[],A=await VW($,{});for(let[Q,Z]of A.inventory.features){if(!Z.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Q}' missing 'owners' field`,category:"layers",file:Z.filePath,context:{key:Q}});if(Z.operations.length===0&&Z.events.length===0&&Z.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Q}' has no operations, events, or presentations`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let[Q,Z]of A.inventory.examples){if(!Z.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Q}' missing 'packageName' in entrypoints`,category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.surfaces.templates&&!Z.surfaces.sandbox.enabled&&!Z.surfaces.studio.enabled&&!Z.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Q}' has no enabled surfaces`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let Q of A.inventory.workspaceConfigs.values())if(!Q.valid)for(let Z of Q.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${Z}`,category:"layers",file:Q.file});return j}i();import{ContractsrcSchema as s7,DEFAULT_CONTRACTSRC as UW}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as a7}from"@contractspec/module.workspace";async function $$($,W={}){let{fs:j,scan:A=a7}=$,Q=await N$(j,W),Z=[],X=Array.isArray(W.type)?W.type:[W.type];for(let Y of Q){if(j0(Y,W.config))continue;if(A0(Y))continue;try{let B=await j.readFile(Y),q=A(B,Y);if(q.specType==="unknown")continue;if(W.type&&!X.includes(q.specType))continue;Z.push(q)}catch{}}return Z}function DK($){let W=new Map;for(let j of $){let A=W.get(j.specType)??[];A.push(j),W.set(j.specType,A)}return W}var e7=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,$X=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,WX=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,jX=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,AX=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,QX=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,ZX=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function LW($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function XX($,W){let j=$.replaceAll("\\","/"),A=new Set(["contracts","features",...LW(W?.conventions?.operations),...LW(W?.conventions?.events),...LW(W?.conventions?.presentations),...LW(W?.conventions?.forms)]);return j.split("/").some((Q)=>A.has(Q))}function YX($,W,j){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||AX.test(A)||jX.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(W.has(A))return!1;if(XX(A,j))return!1;return e7.test(A)}function $4($){return $.replaceAll("\\","/").match(QX)?.[1]??null}function BX($){let W=$.split(`
1611
+ `).map((j)=>j.trim()).filter((j)=>j.length>0&&!j.startsWith("//")&&!j.startsWith("/*")&&!j.startsWith("*")&&!j.startsWith("*/"));return W.length>0&&W.every((j)=>j.startsWith("import ")||j.startsWith("export *")||j.startsWith("export {")||j.startsWith("export type {")||j==="'use client';"||j==='"use client";'||j==="'use server';"||j==='"use server";')}function qX($){if(!$)return UW;let W=s7.safeParse($),j=W.success?W.data:{};return{...UW,...j,conventions:{...UW.conventions,...j.conventions??{}},ci:{...UW.ci,...j.ci??{}}}}async function s1($,W){let{fs:j,logger:A}=$,Q=[],Z=W.config?qX(W.config):await m(j),X=await $$({fs:j},{config:Z}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),B=new Set(X.map((H)=>$4(H.filePath)).filter((H)=>Boolean(H))),q=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of q){if(!YX(H,Y,Z))continue;try{let V=await j.readFile(H);if(BX(V))continue;let G=$4(H);if(!(G!==null&&ZX.test(G)&&B.has(G))&&!WX.test(V))continue;if($X.test(V))continue;Q.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:H})}catch(V){A.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Q}import{validateSpecStructure as HX}from"@contractspec/module.workspace";async function e1($){let W=[];for(let j of $){let A=HX(j);for(let Q of A.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Q,category:"structure",file:j.filePath});for(let Q of A.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Q,category:"structure",file:j.filePath})}return W}async function $j($){let W=[],j=new Map,A=new Map;for(let Q of $){if(!Q.key||!Q.version)continue;if(Q.specType==="test-spec"){let Z=`${Q.key}.v${Q.version}`;j.set(Z,{key:Q.key,version:Q.version,file:Q.filePath,type:"test-spec"})}if(Q.testRefs&&Q.testRefs.length>0){if(!A.has(Q.filePath))A.set(Q.filePath,[]);A.get(Q.filePath)?.push({key:Q.key,version:Q.version,testRefs:Q.testRefs})}}for(let[Q,Z]of A)for(let X of Z){if(!X.testRefs)continue;let Y=i1(Q,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let B of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:B,category:"test-refs",file:Q,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}i();async function Wj($,W){let{fs:j}=$,A=[],Q=await m(j);for(let Z of W){if(Z.specType!=="operation")continue;let X=await KW(Z,{fs:j},Q,{checkTests:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:Z.filePath})}return A}function l($,W,j){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},Q=W.filter((Y)=>Y.severity==="error").length,Z=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:A[$],errors:Q,warnings:Z,notes:X,passed:Q===0,durationMs:j}}async function W4($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),A=j.match(/^ref: (.+)$/m);if(A){let Z=A[1]?.replace("refs/heads/",""),X=`.git/${A[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:Z};return{branch:Z}}return{commitSha:j.trim()}}catch{return{}}}function j4($){let W=$.config?.ci?.checks,j=W&&W.length>0?[...W]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)j.push("handlers");if($.checkTests)j.push("tests");if($.implementation)j.push("implementation");if($.checkDrift)j.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return j.filter((A)=>!$.skip?.includes(A));return j}async function Y_($,W={}){let j=Date.now(),{fs:A,logger:Q}=$,Z=[],X=[],Y=j4(W);Q.info("Starting CI checks...",{checks:Y});let B=await m(A),q=await QW($,{config:B,pattern:W.pattern});if(Y.includes("structure")){let L=Date.now(),z=await e1(q);Z.push(...z),X.push(l("structure",z,Date.now()-L))}if(Y.includes("integrity")){let L=Date.now(),z=await t1($,W);Z.push(...z),X.push(l("integrity",z,Date.now()-L))}if(Y.includes("deps")){let L=Date.now(),z=await C1($,W);Z.push(...z),X.push(l("deps",z,Date.now()-L))}if(Y.includes("doctor")){let L=Date.now(),z=await u1($,W);Z.push(...z),X.push(l("doctor",z,Date.now()-L))}if(Y.includes("docs")){let L=Date.now(),z=await D1($,W);Z.push(...z),X.push(l("docs",z,Date.now()-L))}if(Y.includes("policy")){let L=Date.now(),z=await s1($,W);Z.push(...z),X.push(l("policy",z,Date.now()-L))}if(Y.includes("handlers")||W.checkHandlers){let L=Date.now(),z=await l1($,q);Z.push(...z),X.push(l("handlers",z,Date.now()-L))}if(Y.includes("tests")||W.checkTests){let L=Date.now(),z=await Wj($,q);Z.push(...z),X.push(l("tests",z,Date.now()-L))}if(Y.includes("test-refs")){let L=Date.now(),z=await $j(q);Z.push(...z),X.push(l("test-refs",z,Date.now()-L))}if(Y.includes("coverage")){let L=Date.now(),z=await R1($,q,W);Z.push(...z),X.push(l("coverage",z,Date.now()-L))}if(Y.includes("implementation")){let L=Date.now(),z=await o1($,q,W);Z.push(...z),X.push(l("implementation",z,Date.now()-L))}if(Y.includes("layers")){let L=Date.now(),z=await a1($,W);Z.push(...z),X.push(l("layers",z,Date.now()-L))}if(Y.includes("drift")){let L=Date.now(),z=await r1($,W);Z.push(...z),X.push(l("drift",z,Date.now()-L))}let H=Z.filter((L)=>L.severity==="error").length,V=Z.filter((L)=>L.severity==="warning").length,G=Z.filter((L)=>L.severity==="note").length,J=W.failOnWarnings?H===0&&V===0:H===0,b=await W4(A),w={success:J,totalErrors:H,totalWarnings:V,totalNotes:G,issues:Z,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...b};return Q.info("CI checks complete",{success:J,errors:H,warnings:V,durationMs:w.durationMs}),w}var q_=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],H_={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function w_($,W={}){let{fs:j,logger:A}=$,Q=(W.outputDir??"./src").replace(/\\/g,"/"),Z=["generated/**","dist/**",".turbo/**"],X=[`${Q}/handlers/**/*.handler.ts`,`${Q}/handlers/**/*.handler.test.ts`,`${Q}/components/**/*.tsx`,`${Q}/components/**/*.test.tsx`,`${Q}/forms/**/*.form.tsx`,`${Q}/forms/**/*.form.test.tsx`,`${Q}/**/*.runner.ts`,`${Q}/**/*.renderer.tsx`],Y=W.generatedOnly?[...Z,...X]:[...Z,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],B=await j.glob({patterns:Y,ignore:["node_modules/**"]}),q=[],H=[];for(let V of B)try{let G=await j.stat(V),J=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&J<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)A.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),A.info("clean.removed",{path:V,size:G.size});q.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:q,skipped:H}}i();var C4={};h(C4,{writeReviewPacket:()=>_j,writeDecisionEnvelope:()=>z0,withBranch:()=>x$,verifyConnectMutation:()=>w2,resolveWorkspace:()=>d,resolveStoragePaths:()=>A$,replayConnectDecision:()=>pX,persistLatestArtifacts:()=>wj,persistDecisionArtifacts:()=>_0,normalizeEvalInput:()=>fX,matchConfiguredPath:()=>G0,loadStoredDecision:()=>U0,listStoredReviewPackets:()=>zj,listConnectReviewPackets:()=>tX,isReviewCommand:()=>jj,isDeniedCommand:()=>Aj,isAllowedCommand:()=>OW,initConnectWorkspace:()=>rX,inferSurfaces:()=>w0,evaluateConnectDecision:()=>hX,ensureStorage:()=>K0,defaultActor:()=>b0,decisionArtifactRefs:()=>r$,createConnectControlPlaneRuntime:()=>X2,connectVerdictToPolicy:()=>n$,configuredThreshold:()=>D$,compileConnectPlanPacket:()=>Uj,buildConnectContextPack:()=>bj,assessConnectPolicy:()=>J0,assertConnectEnabled:()=>a,artifactRef:()=>V$,appendAuditRecord:()=>Kj,analyzeConnectImpact:()=>y$,CONTROL_PLANE_TRACE_GET_REF:()=>SW,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>IW,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Yj,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Xj,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Zj,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>T$,AGENT_APPROVALS_REF:()=>MW,ACP_TERMINAL_EXEC_REF:()=>bX,ACP_FS_ACCESS_REF:()=>JX});import VX from"micromatch";function a($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function G0($,W,j){if(!j||j.length===0)return!1;let A=W.replaceAll("\\","/");return VX.isMatch(A,j,{contains:!0})}function D$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function OW($,W){return Qj($.config.connect?.commands?.allow,W)}function jj($,W){return Qj($.config.connect?.commands?.review,W)}function Aj($,W){return Qj($.config.connect?.commands?.deny,W)}function Qj($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function Q4($,W){if(W.length===0)return{state:"none"};for(let A of W)if(Aj($,A))return{commandMatch:A,state:"deny"};for(let A of W)if(jj($,A))return{commandMatch:A,state:"review"};if(W.every((A)=>OW($,A)))return{state:"allow"};let j=W.find(GX);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((A)=>!OW($,A)),state:"unknown"}}function GX($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return A4(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return A4(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function A4($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var Zj={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Xj={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Yj={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},SW={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},IW={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},T$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},JX={key:"acp.fs.access",version:"1.0.0",kind:"command"},bX={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},MW={key:"agent.approvals",version:"1.0.0",kind:"command"};function J0($,W){let j=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.immutablePaths)),A=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.protectedPaths)),Q=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:Z,state:X}=Q4($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,B=W.impactAnalysis.driftFiles.length>0,q=wX({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:B,generatedPath:Boolean(Q),immutable:Boolean(j),protectedPath:Boolean(A),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=KX({breakingChange:W.impactAnalysis.breakingChange,commandMatch:Z,commandState:X,contractDrift:B,protectedPath:A,unknownPaths:W.impactAnalysis.unknownPaths}),V=n$(q);return{commandMatch:Z,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Q,immutablePath:j,protectedPath:A,requiredApprovals:V.requiresApproval?[{capability:T$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:q}}function n$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function wX($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(D$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(D$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(D$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(D$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(D$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(_X)[0]??"permit"}function KX($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function _X($,W){return Z4($)-Z4(W)}function Z4($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as PX}from"crypto";var H4={};h(H4,{formatPrComment:()=>X4,formatMinimalComment:()=>Bj,formatJson:()=>B4,formatCheckRun:()=>Y4,detectImpact:()=>F$,ImpactDetectionOverviewDocBlock:()=>IX});function X4($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)j.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else j.push("\u2705 **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| \u2796 Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let A=$.deltas.filter((Z)=>Z.severity==="breaking"),Q=$.deltas.filter((Z)=>Z.severity==="non_breaking");if(A.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let Z of A)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}if(Q.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let Z of Q)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let A of $.addedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let A of $.removedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### \u26A0\uFE0F Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let A of W.drift.files)j.push(`- \`${A}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### \u2705 No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
1612
+ `)}function Bj($){if($.hasBreaking)return`\u274C **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`\u26A0\uFE0F **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"\u2705 **No contract impact**"}function Y4($,W,j={}){let A=j.key??"ContractSpec Impact",Q=j.failOnBreaking??!0,Z,X;if($.hasBreaking)Z=Q?"failure":"neutral",X=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)Z="success",X=`Non-breaking changes (${$.summary.nonBreaking})`;else Z="success",X="No contract impact";let Y=Bj($);return{name:A,headSha:W,conclusion:Z,title:X,summary:Y,annotations:$.deltas.filter((B)=>B.severity==="breaking").slice(0,50).map((B)=>({path:B.path,startLine:1,endLine:1,annotationLevel:"failure",message:B.description,title:`Breaking: ${B.rule}`}))}}function B4($){let W={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((j)=>({type:j.rule,path:j.specKey,summary:j.description,severity:j.severity==="breaking"?"breaking":j.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(W,null,2)}import{classifyImpact as zX,computeIoDiff as UX,generateSnapshot as q4}from"@contractspec/module.workspace";async function F$($,W={}){let{fs:j,git:A,logger:Q}=$,Z=W.workspaceRoot??process.cwd();Q.info("Starting impact detection...",{baseline:W.baseline});let Y=(await j.glob({pattern:W.pattern??"**/*.{operation,event}.ts",cwd:Z})).filter((J)=>!J.includes(".test.")&&!J.includes(".spec.")&&!J.includes("node_modules"));Q.debug(`Found ${Y.length} spec files`);let B=await LX(j,Y,Z),q=q4(B),H;if(W.baseline){let J=await OX(j,A,Y,W.baseline,Z);H=q4(J)}else H={version:"1.0.0",generatedAt:"",specs:[],hash:""};let V=SX(H.specs,q.specs),G=zX(H.specs,q.specs,V);return Q.info("Impact detection complete",{status:G.status,breaking:G.summary.breaking,nonBreaking:G.summary.nonBreaking}),{...G,workspaceRoot:Z,specsAnalyzed:Y.length,baseRef:W.baseline}}async function LX($,W,j){let A=[];for(let Q of W){let Z=await $.readFile(Q);A.push({path:Q,content:Z})}return A}async function OX($,W,j,A,Q){let Z=[];for(let X of j)try{let Y=await W.showFile(A,X);Z.push({path:X,content:Y})}catch{}return Z}function SX($,W){let j=[],A=new Map($.map((Z)=>[`${Z.key}@${Z.version}`,Z])),Q=new Map(W.map((Z)=>[`${Z.key}@${Z.version}`,Z]));for(let[Z,X]of Q){let Y=A.get(Z);if(Y&&X.type==="operation"&&Y.type==="operation"){let B=UX(Y.io,X.io);j.push(...B)}}return j}var IX={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
1613
+ # Contract Impact Detection
1614
+
1615
+ Automated detection and classification of breaking changes in ContractSpec APIs.
1616
+
1617
+ ## Features
1618
+
1619
+ - **Snapshot Generation**: Creates canonical, deterministic representations of contracts
1620
+ - **Deep Diff Engine**: Field-level comparison of input/output schemas
1621
+ - **Breaking Change Classification**: Automatic classification using 16 rules
1622
+ - **Multiple Output Formats**: JSON, Markdown, Text, GitHub Check Run
1623
+ - **GitHub Integration**: PR comments and check runs
1624
+ - **CLI Tool**: \`contractspec impact\` command
1625
+
1626
+ ## Quick Start
1627
+
1628
+ ### CLI Usage
1629
+
1630
+ \`\`\`bash
1631
+ # Basic usage
1632
+ contractspec impact
1633
+
1634
+ # Compare against specific baseline
1635
+ contractspec impact --baseline origin/main
1636
+
1637
+ # Get JSON output
1638
+ contractspec impact --format json
1639
+ \`\`\`
1640
+
1641
+ ### GitHub Action
1642
+
1643
+ \`\`\`yaml
1644
+ - uses: lssm-tech/contractspec-action@v1
1645
+ with:
1646
+ mode: impact
1647
+ pr-comment: true
1648
+ fail-on-breaking: true
1649
+ \`\`\`
1650
+
1651
+ ## Architecture
1652
+
1653
+ The system consists of three layers:
1654
+
1655
+ 1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
1656
+ 2. **Impact Service** (bundle package): Orchestration + Formatters
1657
+ 3. **Integrations**: CLI command + GitHub Action
1658
+ `,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as G4,readFileSync as J4}from"fs";import{basename as MX,join as qj,resolve as EX}from"path";import{ContractsrcSchema as NX,DEFAULT_CONTRACTSRC as RX}from"@contractspec/lib.contracts-spec/workspace-config";function d($={}){let W=EX($.cwd??process.cwd()),j=$.workspaceRoot??D(W),A=$.packageRoot??f(W),Q=$.config??CX(j,A),Z=DX(A,j);return{cwd:W,workspaceRoot:j,packageRoot:A,config:Q,repoId:Z,branch:"unknown"}}function x$($,W){return{...$,branch:W&&W.length>0?W:"unknown"}}function b0($,W){return W??{id:`cli:${$}`,type:"human"}}function w0($){let W=new Set;for(let j of $){if(j.includes("/cli-")||j.includes("/apps/cli-"))W.add("cli");if(j.includes("/contracts-spec/")||j.includes("/specs/"))W.add("contract");if(j.includes("/runtime/"))W.add("runtime");if(j.includes("/harness"))W.add("harness");if(j.includes("/ai-agent/"))W.add("agent");if(j.includes("/knowledge/"))W.add("knowledge");if(j.includes("/mcp/"))W.add("mcp")}if(W.size===0)W.add("runtime");return W.add("audit"),[...W].sort()}function CX($,W){let j={...RX};if($!==W)j=V4(j,qj($,".contractsrc.json"));return V4(j,qj(W,".contractsrc.json"))}function V4($,W){if(!G4(W))return $;try{let j=J4(W,"utf-8"),A=JSON.parse(j),Q=NX.safeParse(A);if(!Q.success)return $;return{...$,...Q.data}}catch{return $}}function DX($,W){let j=qj($,"package.json");if(G4(j))try{let A=JSON.parse(J4(j,"utf-8"));if(A.name)return A.name}catch{}return MX(W)}async function y$($,W){let j=await $$({fs:$.fs},{config:W.workspace.config}),A=new Map(j.filter((B)=>typeof B.key==="string").map((B)=>[B.key,B])),Q=W.touchedPaths.map((B)=>TX($.fs,W.workspace,B,j,A)),Z=W.baseline!=null?await F$({...$,logger:$.logger??w4},{baseline:W.baseline,workspaceRoot:W.workspace.workspaceRoot}):void 0,X=await FX($,W.workspace,W.touchedPaths),Y=Jj([...Q.flatMap((B)=>B.contracts),...(Z?.deltas??[]).map((B)=>({key:B.specKey,version:B.specVersion,kind:B.specType==="event"?"event":"command"}))]);return{breakingChange:Z?.hasBreaking===!0,driftFiles:X,impactResult:Z,impactedContracts:Y,pathImpacts:Q,unknownPaths:Q.filter((B)=>B.contracts.length===0).map((B)=>B.path)}}function TX($,W,j,A,Q){let Z=$.resolve(W.workspaceRoot,j),X=Gj(j),Y=A.map((b)=>{let w=s($.relative(W.workspaceRoot,b.filePath));return{score:vX(j,X,w,b.key),spec:b}}).filter((b)=>b.score>=45).sort((b,w)=>w.score-b.score).slice(0,3),B=A.find((b)=>b.filePath===Z),q=B?[{score:100,spec:B}]:Y,H=q.filter((b)=>typeof b.spec.key==="string").map((b)=>Vj(b.spec.key,b.spec.version,b.spec.kind)),V=q.flatMap((b)=>[...b.spec.emittedEvents??[],...b.spec.policyRefs??[],...b.spec.testRefs??[]].map((w)=>Q.get(w.key)).filter(Boolean).map((w)=>Vj(w.key,w.version,w.kind))),G=Jj([...H,...V]),J=Jj([{key:"connect.policy",version:"1.0.0",kind:"policy"},...q.flatMap((b)=>b.spec.policyRefs??[]).map((b)=>Vj(b.key,b.version,"policy"))]);return{confidence:q[0]?.score===100?"exact":(q[0]?.score??0)>=70?"high":q.length>0?"medium":"none",contracts:G,path:j,policies:J,reasons:q.map((b)=>`${b.spec.key??b.spec.filePath} matched with score ${b.score}`),surfaces:w0([j])}}async function FX($,W,j){let A=xX($.fs,W,j),Q=await Promise.all(A.map(async(Z)=>{let X=$.fs.resolve(W.packageRoot,Z.comparisonRoot),Y=await wW({...$,logger:$.logger??w4},W.workspaceRoot,X,{generation:{scanAllSpecs:!0,specSearchRoot:W.workspaceRoot},rootPath:W.workspaceRoot}),B=Z.filterPrefix&&Z.filterPrefix!==Z.comparisonRoot?s($.fs.relative(Z.comparisonRoot,Z.filterPrefix)):void 0;return Y.files.filter((q)=>B?s(q)===B||s(q).startsWith(`${B}/`):!0).map((q)=>s($.fs.join(Z.comparisonRoot,q)))}));return[...new Set(Q.flat())].sort()}function xX($,W,j){let A=(W.config.connect?.policy?.generatedPaths??[]).map(mX).filter(Boolean),Q=W.config.outputDir&&W.config.outputDir!=="./src"?s(W.config.outputDir):void 0,Z=new Map;for(let X of j){let Y=s(X);if(Q&&Y.startsWith(Q))Z.set(Q,{comparisonRoot:Q});for(let B of A)if(Y.startsWith(B)){let q=yX($,Q,B);Z.set(`${q}::${B}`,{comparisonRoot:q,filterPrefix:B})}}return[...Z.values()]}function yX($,W,j){if(W&&j.startsWith(W))return W;return $.basename(j)==="docs"?s($.dirname(j)):j}function vX($,W,j,A){if(s($)===s(j))return 100;let Q=Gj(j),Z=Gj(A??""),X=b4($)===b4(j)?40:0,Y=Hj($.split("/"),j.split("/"),5),B=Hj(W,Q,5),q=Hj(W,Z,4);return X+Y+B+q}function Hj($,W,j){let A=new Set(W);return $.filter((Q)=>A.has(Q)).length*j}function Gj($){return s($).split(/[\/._-]+/).filter(Boolean)}function b4($){return s($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function mX($){return s($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function s($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Vj($,W,j){return{key:$,version:String(W??"1.0.0"),kind:j==="query"||j==="event"||j==="policy"||j==="capability"?j:"command"}}function Jj($){return[...new Map($.map((W)=>[`${W.key}@${W.version}`,W])).values()]}var w4={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function bj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let A=b0(W.taskId,W.actor),Q=await kX($,j.workspaceRoot,W),Z=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),X=j.config.connect?.canonPacks??[];return{id:`connect.ctx_${PX()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:A,knowledge:X.map((Y)=>({spaceKey:Y.ref,category:"canonical",trustLevel:Y.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:Z.impactedContracts,affectedSurfaces:Z.pathImpacts.length>0?[...new Set(Z.pathImpacts.flatMap((Y)=>Y.surfaces))].sort():w0(Q),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...X.map((Y)=>({key:Y.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...X.map((Y)=>({kind:"canon-pack",ref:Y.ref}))],acceptanceChecks:j.config.connect?.policy?.smokeChecks??[]}}async function kX($,W,j){let A=j.paths??[];if(A.length>0)return A.map((Z)=>K4($.fs,W,Z));if(!j.baseline)return[];return(await $.git.diffFiles(j.baseline)).map((Z)=>K4($.fs,W,Z))}function K4($,W,j){let A=$.resolve(W,j);return $.relative(W,A).replaceAll("\\","/")}import{resolve as v$}from"path";function A$($){let W=$.config.connect?.storage,j=v$($.packageRoot,W?.root??".contractspec/connect");return{root:j,contextPack:v$($.packageRoot,W?.contextPack??".contractspec/connect/context-pack.json"),planPacket:v$($.packageRoot,W?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:v$($.packageRoot,W?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:v$($.packageRoot,W?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:v$($.packageRoot,W?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:v$(j,"decisions")}}async function K0($,W){await $.mkdir(W.root),await $.mkdir(W.reviewPacketsDir),await $.mkdir(W.decisionsDir)}async function wj($,W,j){if(j.contextPack)await j$($,W.contextPack,j.contextPack);if(j.planPacket)await j$($,W.planPacket,j.planPacket);if(j.patchVerdict)await j$($,W.patchVerdict,j.patchVerdict)}async function _0($,W,j,A){let Q=$.join(W.decisionsDir,j);if(await $.mkdir(Q),A.contextPack)await j$($,$.join(Q,"context-pack.json"),A.contextPack);if(A.planPacket)await j$($,$.join(Q,"plan-packet.json"),A.planPacket);if(A.patchVerdict)await j$($,$.join(Q,"patch-verdict.json"),A.patchVerdict);if(A.reviewPacket)await j$($,$.join(Q,"review-packet.json"),A.reviewPacket);if(A.evaluationResult!==void 0)await j$($,$.join(Q,"evaluation-result.json"),A.evaluationResult);if(A.replayBundle!==void 0)await j$($,$.join(Q,"replay-bundle.json"),A.replayBundle);return Q}async function z0($,W,j,A){let Q=$.join(W.decisionsDir,j,"decision-envelope.json");return await j$($,Q,A),Q}async function Kj($,W,j){let A=await _4($,W.auditFile)??"",Q=`${JSON.stringify(j)}
1659
+ `;await $.writeFile(W.auditFile,`${A}${Q}`)}async function _j($,W,j){let A=$.join(W.reviewPacketsDir,`${j.id}.json`);return await j$($,A,j),A}async function U0($,W,j){let A=$.join(W.decisionsDir,j);return{historyDir:A,contextPack:await c$($,$.join(A,"context-pack.json")),planPacket:await c$($,$.join(A,"plan-packet.json")),patchVerdict:await c$($,$.join(A,"patch-verdict.json")),reviewPacket:await c$($,$.join(A,"review-packet.json")),envelope:await c$($,$.join(A,"decision-envelope.json"))}}async function zj($,W){let j=await $.glob({pattern:"*.json",cwd:W.reviewPacketsDir,absolute:!0}),A=[];for(let Q of j){let Z=await c$($,Q);if(Z)A.push({filePath:Q,packet:Z})}return A.sort((Q,Z)=>Q.packet.id.localeCompare(Z.packet.id))}function V$($,W,j){return $.relative(W.packageRoot,$.resolve(j)).replaceAll("\\","/")}function r$($,W,j,A,Q){let Z=$.join(j.decisionsDir,A);return{contextPack:V$($,W,$.join(Z,"context-pack.json")),planPacket:V$($,W,$.join(Z,"plan-packet.json")),patchVerdict:V$($,W,$.join(Z,"patch-verdict.json")),reviewPacket:Q.reviewPacket?V$($,W,$.join(Z,"review-packet.json")):void 0,evaluationResult:Q.evaluationResult?V$($,W,$.join(Z,"evaluation-result.json")):void 0,replayBundle:Q.replayBundle?V$($,W,$.join(Z,"replay-bundle.json")):void 0}}async function j$($,W,j){await $.writeFile(W,`${JSON.stringify(j,null,2)}
1660
+ `)}async function c$($,W){let j=await _4($,W);if(!j)return;try{return JSON.parse(j)}catch{return}}async function _4($,W){if(!await $.exists(W))return;try{return await $.readFile(W)}catch{return}}async function hX($,W,j){let A=d(W);if(a(A),!W.scenarioKey&&!W.suiteKey||W.scenarioKey&&W.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X=gX(A,Z),Y=W.scenarioKey?await j.runScenarioEvaluation({scenarioKey:W.scenarioKey,version:W.version,context:X}):await j.runSuiteEvaluation({suiteKey:W.suiteKey??"",version:W.version,context:X}),B=await _0($.fs,Q,W.decisionId,{evaluationResult:Y}),q=await $.fs.exists($.fs.join(B,"replay-bundle.json")),H={artifacts:r$($.fs,A,Q,W.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:q,reviewPacket:Boolean(Z.reviewPacket)}),connectDecisionId:W.decisionId,createdAt:Z.envelope?.createdAt??new Date().toISOString(),runtimeLink:Z.envelope?.runtimeLink,taskId:Z.contextPack?.taskId??W.decisionId,verdict:Z.patchVerdict?.verdict??"permit"};return await z0($.fs,Q,W.decisionId,H),{historyDir:B,evaluation:Y,context:X}}function gX($,W){return{traceId:W.envelope?.runtimeLink?.traceId??W.patchVerdict?.controlPlane.traceId??W.contextPack?.actor.traceId,actorId:W.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:W.envelope?.runtimeLink?.decisionId,controlPlanePlanId:W.envelope?.runtimeLink?.planId??W.planPacket?.id,metadata:{approvalStatus:W.envelope?.runtimeLink?.approvalStatus,decisionId:W.patchVerdict?.decisionId,taskId:W.contextPack?.taskId,branch:W.contextPack?.branch??$.branch}}}function fX($){return $}import{DEFAULT_CONTRACTSRC as cX}from"@contractspec/lib.contracts-spec/workspace-config";async function EW($,W){let j=$.join(W.root,".gitignore"),A=W.behavior??"auto",Q=L4(W.patterns);if(Q.length===0||A==="skip")return{target:"gitignore",filePath:j,action:"skipped",message:A==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(A==="auto"&&W.interactive&&W.prompts&&!await W.prompts.confirm(`Add recommended ContractSpec ignore rules to ${j}?`,!0))return{target:"gitignore",filePath:j,action:"skipped",message:"User skipped ContractSpec gitignore update"};let Z=await $.exists(j),X=Z?await $.readFile(j):"",Y=uX(X,Q);if(U4(X)===U4(Y))return{target:"gitignore",filePath:j,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(j,Y),{target:"gitignore",filePath:j,action:Z?"merged":"created",message:Z?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(Z){return{target:"gitignore",filePath:j,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}function uX($,W){let j=dX(W),A=nX(),Q=$.replace(/\r\n/g,`
1661
+ `);if(A.test(Q))return Q.replace(A,j);if(Q.trim().length===0)return j;return`${Q.endsWith(`
1662
+ `)?Q:`${Q}
1663
+ `}
1664
+ ${j}`}function dX($){return`# contractspec:init:gitignore:start
1665
+ # Managed by \`contractspec init\` and \`contractspec connect init\`.
1666
+ ${L4($).join(`
1667
+ `)}
1668
+ # contractspec:init:gitignore:end
1669
+ `}function nX(){return new RegExp(`${z4("# contractspec:init:gitignore:start")}[\\s\\S]*?${z4("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function z4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U4($){return $.replace(/\r\n/g,`
1670
+ `).trimEnd()}function L4($){return[...new Set($.map((W)=>W.trim()).filter(Boolean))]}async function rX($,W={}){let j=d(W),A=W.scope==="package"?j.packageRoot:j.workspaceRoot,Q=$.join(A,".contractsrc.json"),Z={connect:{...cX.connect,enabled:!0}},X="created";if(await $.exists(Q)){let q=r(await $.readFile(Q)),H=p(q??{},Z);if(q?.connect&&typeof q.connect==="object")H.connect.enabled=!0;await $.writeFile(Q,F(H)),X="merged"}else await $.writeFile(Q,F(Z));let Y=A$(d({...W,workspaceRoot:A,packageRoot:A}));await K0($,Y);let B=await EW($,{behavior:W.gitignoreBehavior,interactive:W.interactive??!1,patterns:[Y0.connect,Y0.verificationCache],prompts:W.prompts,root:j.workspaceRoot});return{configPath:Q,targetRoot:A,action:X,gitignore:B}}import{randomUUID as NW}from"crypto";async function Uj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let{commands:A,touchedPaths:Q}=lX(W.candidate),Z=await bj($,{...W,paths:Q}),X=b0(W.taskId,W.actor),Y=oX(W.candidate.steps,W.candidate),B=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),q=J0(j,{commands:A,impactAnalysis:B,touchedPaths:Q}),H={id:`connect.plan_${NW()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:Z.impactedContracts,affectedSurfaces:Z.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:q.requiredApprovals,riskScore:iX(Q.length,A.length),verificationStatus:q.verificationStatus,controlPlane:{intentSubmit:Zj,planCompile:Xj,planVerify:Yj,traceId:X.traceId},acpActions:[...Q.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:Z,planPacket:H}}function lX($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let Q of A.paths??[])W.add(Q);for(let Q of A.commands??[])j.add(Q)}return{commands:[...j],touchedPaths:[...W]}}function oX($,W){if(!$||$.length===0)return[{id:`step_${NW()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${NW()}`,summary:j}:{id:`step_${NW()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function iX($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function pX($,W,j){let A=d(W);a(A);let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X={decisionId:Z.envelope?.runtimeLink?.decisionId,traceId:Z.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,B=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:Z.historyDir,contextPack:Z.contextPack,planPacket:Z.planPacket,patchVerdict:Z.patchVerdict,reviewPacket:Z.reviewPacket,trace:Y??void 0,replay:B??void 0,source:Y?"local+control-plane":"local"}}async function tX($,W={}){let j=d(W);return a(j),zj($.fs,A$(j))}import{buildChannelPlanTrace as aX,compileChannelPlan as sX,finalizeChannelPlan as eX,replayExecutionTrace as $2,resolveChannelExecutionActor as W2}from"@contractspec/integration.runtime/channel";import{createHash as j2}from"crypto";var L0="connect.local",A2="connect.runtime-link.v1",Q2="connect.adapter.v1",Z2="connect-control-plane-bridge";function X2($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:A,patchVerdict:Q,planPacket:Z,workspace:X})=>{let Y=new Date(j),B=JSON.stringify({connectDecisionId:W,objective:Z.objective,taskId:Z.taskId,tool:A.tool,verdict:Q.verdict}),q={workspaceId:X.repoId,providerKey:L0,externalEventId:W,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Q.controlPlane.traceId,thread:{externalThreadId:`connect:${Z.taskId}`,externalUserId:Z.actor.id},message:{text:H2(Z.objective,A)},metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`}),rawPayload:B},H=await $.store.claimEventReceipt({workspaceId:q.workspaceId,providerKey:q.providerKey,externalEventId:q.externalEventId,eventType:q.eventType,signatureValid:!0,payloadHash:V2(B),traceId:q.traceId});if(H.duplicate)return Y2($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:q.workspaceId,providerKey:q.providerKey,externalThreadId:q.thread.externalThreadId,externalUserId:q.thread.externalUserId,occurredAt:Y}),G=W2(q,{actorId:Z.actor.id,actorType:Z.actor.type,capabilityGrants:q2(Q.verdict),capabilitySource:"connect",sessionId:Z.actor.sessionId}),J=sX({event:q,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),b=eX({plan:J,decision:B2(Q),approvalTimeoutMs:900000,now:Y}),w=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:b.policy?.verdict??"blocked",riskTier:b.policy?.riskTier??"blocked",confidence:b.policy?.confidence??0.5,modelName:Z2,promptVersion:A2,policyVersion:Q2,toolTrace:aX(b),actionPlan:b,requiresApproval:b.approval.required,approvalStatus:b.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:b.approval.required?"pending":"processed",decisionId:w.id,receiptId:H.receiptId,traceId:b.traceId,workspaceId:X.repoId,providerKey:L0,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`,metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,tool:A.tool})}),{approvalStatus:w.approvalStatus,decisionId:w.id,planId:b.id,providerKey:L0,receiptId:H.receiptId,threadId:V.id,traceId:b.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>O4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await O4($.traceService,W);return j?$2(j):null}}}async function Y2($,W,j){let Q=(await $.listDecisions({externalEventId:j,limit:1,providerKey:L0,workspaceId:W}))[0];return Q?{approvalStatus:Q.approvalStatus,decisionId:Q.id,planId:Q.actionPlan.id,providerKey:L0,receiptId:Q.receiptId,threadId:Q.threadId,traceId:Q.actionPlan.traceId,workspaceId:W}:null}async function O4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function B2($){let W=n$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((j)=>`${j.status}:${j.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:W.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:W.controlPlaneVerdict}}function q2($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function H2($,W){return`${$} [${W.tool}]`}function V2($){return j2("sha256").update($).digest("hex")}function S4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as b2}from"crypto";function I4($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as G2}from"crypto";function M4($,W,j){let A=$?`Immutable path: ${$}`:W?`Protected path: ${W}`:j?`Generated path: ${j}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":W||j?"warn":"pass",detail:A}}function E4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:A}}function N4($,W,j){return{id:"impact-analysis",status:$?"fail":W||j?"warn":"pass",detail:$?"Breaking change detected.":W?"Generated-path drift detected.":j?"Impact could not be resolved.":"Impact resolved."}}function R4($,W,j,A,Q,Z){let X=Z.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${Z.runtimeLink.decisionId}`:Z.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${Z.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${G2()}`,sourceDecisionId:W,objective:A.objective,reason:Z.reason,summary:{paths:Q,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:Z.artifactRefs.contextPack},{type:"plan-packet",ref:Z.artifactRefs.planPacket},{type:"patch-verdict",ref:Z.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:T$.key,reason:Z.reason}],controlPlane:{traceQuery:SW,policyExplain:IW,approvalStatus:Z.runtimeLink?.approvalStatus,decisionId:Z.runtimeLink?.decisionId,traceId:Z.runtimeLink?.traceId??j.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Lj($,W,j,A,Q,Z,X,Y,B){let q=n$(X);return{decisionId:$,summary:A.objective,action:W.tool==="acp.fs.access"?{actionType:W.operation==="write"?"write_file":"edit_file",tool:W.tool,target:W.path}:{actionType:"run_command",tool:W.tool,cwd:W.cwd},impacted:Q,checks:Z,verdict:X,controlPlane:{verdict:q.controlPlaneVerdict,requiresApproval:q.requiresApproval,approvalStatus:B?.approvalStatus,decisionId:B?.decisionId,traceId:B?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${T$.key}@${T$.version}`,`${MW.key}@${MW.version}`]:void 0,remediation:J2(X),reviewPacketRef:Y,replay:{traceQuery:SW,policyExplain:IW}}}function J2($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function w2($,W,j={}){let A=d(W);a(A),A=x$(A,await $.git.currentBranch());let Q=`connect.dec_${b2()}`,Z=(j.now??(()=>new Date))().toISOString(),X=A$(A);await K0($.fs,X);let{contextPack:Y,planPacket:B}=await Uj($,{...W,candidate:K2(W)}),q=_2(W),H=await y$($,{baseline:W.baseline,touchedPaths:q,workspace:A}),V=await z2(j,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),G=V.some((M)=>M.id.startsWith("smoke:")&&M.status==="fail"),J=J0(A,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:q}),b=[M4(J.immutablePath,J.protectedPath,J.generatedPath),E4(J.commandState,J.commandMatch),N4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],w=r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0}),L=H.pathImpacts.length>0?H.pathImpacts.map((M)=>({file:M.path,contracts:M.contracts,policies:M.policies,surfaces:M.surfaces})):q.map((M)=>({file:M,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),z=Lj(Q,W,Y,B,L,b,J.verdict,void 0),S=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Q,createdAt:Z,input:W,patchVerdict:z,planPacket:B,workspace:A}):null,U=S?{...B,controlPlane:{...B.controlPlane,decisionId:S.decisionId,traceId:S.traceId??B.controlPlane.traceId}}:B,O=J.verdict==="require_review"?R4(A,Q,Y,U,q,{artifactRefs:w,reason:J.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:S}):void 0,K=Lj(Q,W,Y,U,L,b,J.verdict,O?V$($.fs,A,$.fs.join(X.reviewPacketsDir,`${O.id}.json`)):void 0,S);if(await wj($.fs,X,{contextPack:Y,planPacket:U,patchVerdict:K}),O)await _j($.fs,X,O);let _=await _0($.fs,X,Q,{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O}),I={artifacts:r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(O)}),connectDecisionId:Q,createdAt:Z,runtimeLink:S??void 0,taskId:W.taskId,verdict:J.verdict};return await z0($.fs,X,Q,I),await Kj($.fs,X,I4({contextPack:Y,createdAt:Z,envelope:I,reviewPacket:O,verifyInput:W,workspace:A})),{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O,historyDir:_}}function K2($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function _2($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function z2($,W,j){if(!$.runCommand)return[];let A=[];for(let Q of W){let Z=await $.runCommand(Q,{cwd:j});A.push({id:`smoke:${Q}`,status:Z.exitCode===0?"pass":"fail",detail:Z.exitCode===0?`Passed: ${Q}`:`Failed (${Z.exitCode}): ${Q}`})}return A}DW();var Ij={};h(Ij,{generateWorkflowSpec:()=>Y8,generateWorkflowRunnerTemplate:()=>jW,generateWorkflowDevkitWorkflowTemplate:()=>a0,generateWorkflowDevkitStreamRouteTemplate:()=>$W,generateWorkflowDevkitStartRouteTemplate:()=>s0,generateWorkflowDevkitGenericTemplate:()=>WW,generateWorkflowDevkitFollowUpRouteTemplate:()=>e0,generateTestTemplate:()=>s5,generateTelemetrySpec:()=>X8,generatePresentationSpec:()=>Z8,generateOperationSpec:()=>Q8,generateMigrationSpec:()=>A8,generateKnowledgeSpaceSpec:()=>W8,generateIntegrationSpec:()=>$8,generateHandlerTemplate:()=>t5,generateFormSpec:()=>p5,generateFeatureSpec:()=>i5,generateExperimentSpec:()=>o5,generateEventSpec:()=>l5,generateDataViewSpec:()=>r5,generateDataViewRendererTemplate:()=>p0,generateComponentTemplate:()=>a5,generateAppBlueprintSpec:()=>c5});DW();class T4{ai;templates=Ij;constructor($){this.ai=new CW($)}}function HU($){return new T4($)}import{scanSpecSource as C2}from"@contractspec/module.workspace";function F4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function KU($,W,j={}){let{fs:A,logger:Q}=W,Z=await A.exists($);if(!Z&&!j.force)return{specPath:$,specInfo:F4($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let X=F4($),Y;if(Z)try{let q=await A.readFile($);X=C2(q,$),Y=X.key}catch{}let B=[];if(j.clean&&Y)try{let q=await _W(Y,{fs:A});for(let H of q)try{await A.remove(H.filePath),B.push(H.filePath),Q.info(`Removed artifact: ${H.filePath}`)}catch{Q.warn(`Could not remove artifact: ${H.filePath}`)}}catch{Q.warn("Could not discover implementations for cleanup")}if(Z)await A.remove($),Q.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:X,deleted:!0,cleanedFiles:B,errors:[]}}import{computeSemanticDiff as D2}from"@contractspec/module.workspace";async function UU($,W,j,A={}){let{fs:Q,git:Z}=j;if(!await Q.exists($))throw Error(`Spec file not found: ${$}`);let Y=await Q.readFile($),B,q;if(A.baseline)B=await Z.showFile(A.baseline,$),q=`${A.baseline}:${$}`;else{if(!await Q.exists(W))throw Error(`Spec file not found: ${W}`);B=await Q.readFile(W),q=W}let H=D2(Y,$,B,q,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:q,differences:H}}i();import{openApiForRegistry as T2}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Mj}from"@contractspec/lib.contracts-spec/operations";async function F2($,W){let{fs:j,logger:A}=W,{registryPath:Q,outputPath:Z="./openapi.json"}=$;A.info("Loading registry...",{registryPath:Q});let X=await x2(Q,j);A.info("Generating OpenAPI document...");let Y=T2(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),B=JSON.stringify(Y,null,2)+`
1671
+ `,q=j.resolve(Z);return await j.mkdir(j.dirname(q)),await j.writeFile(q,B),A.info(`OpenAPI document written to ${q}`),{document:Y,outputPath:q,json:B}}async function x2($,W){let A=await import(W.resolve($));if(A instanceof Mj)return A;if(A.registry instanceof Mj)return A.registry;let Q=typeof A.createRegistry==="function"?A.createRegistry:typeof A.default==="function"?A.default:void 0;if(Q){let Z=await Q();if(Z instanceof Mj)return Z}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as y2,parseOpenApi as v2}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Ej,dirname as x4,join as l$}from"path";function m2($,W,j){if(W.outputDir)return W.outputDir;let{outputDir:A,conventions:Q}=j;switch($){case"operation":return l$(A,Q.operations.split("|")[0]??"operations");case"event":return l$(A,Q.events);case"model":return l$(A,"models");default:return A}}async function y4($,W,j){let{fs:A,logger:Q}=j,{source:Z,prefix:X,tags:Y,exclude:B,defaultStability:q,defaultOwners:H,defaultAuth:V,dryRun:G=!1}=W;Q.info(`Importing from OpenAPI: ${Z}`);let J=await v2(Z,{fetch:globalThis.fetch,readFile:(U)=>A.readFile(U)});if(J.warnings.length>0)for(let U of J.warnings)Q.warn(`Parse warning: ${U}`);Q.info(`Parsed ${J.operations.length} operations from ${J.info.title} v${J.info.version}`);let b=y2(J,$,{prefix:X,tags:Y,exclude:B,defaultStability:q,defaultOwners:H,defaultAuth:V});Q.info(`Import result: ${b.summary.imported} imported, ${b.summary.skipped} skipped, ${b.summary.errors} errors`);let w=[],L=[],z=[],S=new Map;for(let U of b.operationSpecs){let O="operation",K=null;if(U.code.includes("defineEvent("))O="event",K=U.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((U.code.includes("defineSchemaModel(")||U.code.includes("new EnumType(")||U.code.includes("ScalarTypeEnum.")||U.code.includes("new ZodSchemaType(")||U.code.includes("z.enum(")||U.code.includes("new JsonSchemaType(")||U.code.includes("new GraphQLSchemaType("))&&!U.code.includes("defineCommand(")&&!U.code.includes("defineQuery("))O="model";else O="operation",K=U.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let _=m2(O,W,$),I=l$(_,U.fileName);if(!K&&O==="model"){if(U.code.includes("new ZodSchemaType("))K=U.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(U.code.includes("new JsonSchemaType("))K=U.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(U.code.includes("new GraphQLSchemaType("))K=U.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!K)K=U.code.match(/export const (\w+)\s*=/)}if(G)Q.info(`[DRY RUN] Would create: ${I}`);else{let M=x4(I);if(!await A.exists(M))await A.mkdir(M);await A.writeFile(I,U.code),Q.info(`Created: ${I}`)}if(w.push({path:I,operationId:U.source.sourceId,specName:U.fileName.replace(".ts","")}),K){let M=x4(I),E=S.get(M)||[];E.push({file:Ej(I),name:K[1],type:O}),S.set(M,E)}}if(!G&&w.length>0)for(let[U,O]of S.entries()){if(O.length===0)continue;let K=O.map((x)=>x.type),_=K.every((x)=>x==="operation"),I=K.every((x)=>x==="event"),M=K.every((x)=>x==="model"),E=`/**
1433
1672
  * Auto-generated registry file.
1434
1673
  */
1435
- `;I.forEach((F)=>{let d$=`./${i1(F.file,".ts")}`;M+=`import { ${F.name} } from '${d$}';
1436
- `}),M+=`
1437
- `;let u=!1;if(O)M+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
1674
+ `;O.forEach((x)=>{let L$=`./${Ej(x.file,".ts")}`;E+=`import { ${x.name} } from '${L$}';
1675
+ `}),E+=`
1676
+ `;let C=!1;if(_)E+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
1438
1677
 
1439
- `,M+=`export const operationRegistry = new OperationSpecRegistry();
1440
- `,I.forEach((F)=>{M+=`operationRegistry.register(${F.name});
1441
- `}),u=!0;else if(C)M+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
1678
+ `,E+=`export const operationRegistry = new OperationSpecRegistry();
1679
+ `,O.forEach((x)=>{E+=`operationRegistry.register(${x.name});
1680
+ `}),C=!0;else if(I)E+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
1442
1681
 
1443
- `,M+=`export const eventRegistry = new EventRegistry();
1444
- `,I.forEach((F)=>{M+=`eventRegistry.register(${F.name});
1445
- `}),u=!0;else if(S)M+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
1682
+ `,E+=`export const eventRegistry = new EventRegistry();
1683
+ `,O.forEach((x)=>{E+=`eventRegistry.register(${x.name});
1684
+ `}),C=!0;else if(M)E+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
1446
1685
 
1447
- `,M+=`export const modelRegistry = new ModelRegistry();
1448
- `,I.forEach((F)=>{M+=`modelRegistry.register(${F.name});
1449
- `}),u=!0;if(u){let F=k$(L,"registry.ts");await Q.writeFile(F,M),Z.info(`Created/Updated registry: ${F}`)}let l=`/**
1686
+ `,E+=`export const modelRegistry = new ModelRegistry();
1687
+ `,O.forEach((x)=>{E+=`modelRegistry.register(${x.name});
1688
+ `}),C=!0;if(C){let x=l$(U,"registry.ts");await A.writeFile(x,E),Q.info(`Created/Updated registry: ${x}`)}let R=`/**
1450
1689
  * Auto-generated barrel file.
1451
1690
  */
1452
1691
 
1453
- `;if(I.forEach((F)=>{let d$=`./${i1(F.file,".ts")}`;l+=`export * from '${d$}';
1454
- `}),u)l+=`export * from './registry';
1455
- `;let y=k$(L,"index.ts");await Q.writeFile(y,l),Z.info(`Created/Updated index: ${y}`)}for(let L of J.skipped)_.push({operationId:L.sourceId,reason:L.reason}),Z.debug(`Skipped: ${L.sourceId} - ${L.reason}`);for(let L of J.errors)w.push({operationId:L.sourceId,error:L.error}),Z.error(`Error: ${L.sourceId} - ${L.error}`);return{imported:J.summary.imported,skipped:J.summary.skipped,errors:J.summary.errors,files:K,skippedOperations:_,errorMessages:w}}import{importFromOpenApi as $X,parseOpenApi as WX}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as jX,join as QX}from"path";async function PU($,W,j){let{fs:Q,logger:Z}=j,{sources:B,sourceName:X,interactive:Y,force:q,dryRun:A}=$,{outputDir:H}=W,V=B??W.openapi?.sources??[];if(X){if(V=V.filter((z)=>z.name===X),V.length===0)throw Error(`Source not found: ${X}`)}if(V.length===0)return Z.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let G={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let z of V){Z.info(`Syncing with source: ${z.name}`);let J=z.url??z.file;if(!J){Z.warn(`Source ${z.name} has no url or file configured`);continue}let K=await WX(J,{fetch:globalThis.fetch,readFile:(w)=>Q.readFile(w)});Z.info(`Parsed ${K.operations.length} operations from ${z.name}`);let _=$X(K,W,{prefix:z.prefix,tags:z.tags,exclude:z.exclude,defaultStability:z.defaultStability,defaultAuth:z.defaultAuth});for(let w of _.operationSpecs){let b=QX(H,w.fileName);if(!await Q.exists(b)){if(!A){let I=jX(b);await Q.mkdir(I),await Q.writeFile(b,w.code)}G.added++,G.changes.push({operationId:w.source.sourceId,action:"added",path:b}),Z.info(`Added: ${w.source.sourceId}`)}else if(await Q.readFile(b)===w.code)G.unchanged++,G.changes.push({operationId:w.source.sourceId,action:"unchanged",path:b});else if(q==="openapi"){if(!A)await Q.writeFile(b,w.code);G.updated++,G.changes.push({operationId:w.source.sourceId,action:"updated",path:b}),Z.info(`Updated: ${w.source.sourceId}`)}else if(q==="contractspec")G.unchanged++,G.changes.push({operationId:w.source.sourceId,action:"unchanged",path:b}),Z.info(`Kept: ${w.source.sourceId}`);else if(Y)G.conflicts++,G.changes.push({operationId:w.source.sourceId,action:"conflict",path:b}),Z.warn(`Conflict: ${w.source.sourceId} - needs resolution`);else G.conflicts++,G.changes.push({operationId:w.source.sourceId,action:"conflict",path:b}),Z.warn(`Conflict: ${w.source.sourceId}`)}}return Z.info(`Sync complete: ${G.added} added, ${G.updated} updated, ${G.unchanged} unchanged, ${G.conflicts} conflicts`),G}import{parseOpenApi as ZX}from"@contractspec/lib.contracts-transformers/openapi";async function gU($,W){let{fs:j,logger:Q}=W,{specPath:Z,openApiSource:B,ignoreDescriptions:X,ignoreTags:Y,ignoreTransport:q}=$;Q.info(`Validating specs against OpenAPI: ${B}`);let A=await ZX(B,{fetch:globalThis.fetch,readFile:(w)=>j.readFile(w)});Q.info(`Parsed ${A.operations.length} operations from ${A.info.title}`);let H=new Map;for(let w of A.operations)H.set(w.operationId,w);let V=[],G=0,z=0,J=await j.stat(Z),K=[];if(J.isDirectory){let w=await j.glob({pattern:"**/*.ts",cwd:Z,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});K.push(...w)}else K.push(Z);Q.info(`Found ${K.length} spec files to validate`);for(let w of K)try{let b=await j.readFile(w),L=b.match(/operationId:\s*['"]([^'"]+)['"]/)||b.match(/name:\s*['"]([^'"]+)['"]/)||b.match(/export\s+const\s+(\w+)Spec\s*=/);if(!L||!L[1]){Q.debug(`Could not extract operationId from ${w}`);continue}let I=L[1];G++;let U;if(U=H.get(I),!U){let S=I.replace(/([A-Z])/g,"_$1").toLowerCase();U=H.get(S)}if(!U){for(let[S,M]of H)if(S.toLowerCase().includes(I.toLowerCase())||I.toLowerCase().includes(S.toLowerCase())){U=M;break}}if(!U){V.push({specPath:w,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${I}`}]}),z++;continue}let O=[];if(U.deprecated&&!b.includes("deprecated"))O.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!q){let S=b.match(/path:\s*['"]([^'"]+)['"]/);if(S&&S[1]!==U.path)O.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${S[1]}", OpenAPI has "${U.path}"`})}if(!q){let S=b.match(/method:\s*['"]([^'"]+)['"]/);if(S?.[1]&&S[1].toLowerCase()!==U.method.toLowerCase())O.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${S[1]}", OpenAPI has "${U.method.toUpperCase()}"`})}let C=O.length===0;if(!C)z++;V.push({specPath:w,operationId:U.operationId,valid:C,diffs:O})}catch(b){Q.error(`Error validating ${w}: ${b}`),V.push({specPath:w,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${b instanceof Error?b.message:String(b)}`}]}),z++}let _=z===0;return Q.info(`Validation ${_?"passed":"failed"}: ${G} specs checked, ${z} with differences`),{valid:_,specsValidated:G,specsWithDiffs:z,results:V}}async function pU($,W,j){let{fs:Q,logger:Z}=$,{source:B,outputDir:X}=W,Y=Q.resolve(j??process.cwd(),B);if(!await Q.exists(Y))throw Error(`Source file not found: ${Y}`);let A={...await a(Q,j),outputDir:X};return Z.info(`Extracting contracts from ${Y} to ${X}`),d4(A,{source:Y,outputDir:X,dryRun:!1},$)}var c4={};P(c4,{validateFeatureRefs:()=>YX,getArrayNameForSpecType:()=>n4,detectFeatureContext:()=>BX,computeAddSpecEdit:()=>XX});function BX($,W){let j=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],Q=null;for(let{type:V,regex:G,specType:z}of j){let J;G.lastIndex=0;while((J=G.exec($))!==null)if(!Q||J.index>Q.index)Q={type:V,specType:z,index:J.index}}if(!Q)return null;let Z=$.slice(Q.index)+W,B=Q.type;new RegExp(`${B}\\s*:\\s*\\[`).exec(Z);let Y=$.slice(Q.index),q=0,A=!1,H="";for(let V=0;V<Y.length;V++){let G=Y[V],z=V>0?Y[V-1]:"";if((G==='"'||G==="'"||G==="`")&&z!=="\\"){if(!A)A=!0,H=G;else if(G===H)A=!1;continue}if(A)continue;if(G==="[")q++;else if(G==="]"){if(q--,q===0)return null}}if(q>0)return{type:Q.type,specType:Q.specType};return null}function XX($,W){let j=n4(W.type),Z=new RegExp(`${j}\\s*:\\s*\\[`,"g").exec($);if(Z){let B=Z.index+Z[0].length,X=typeof W.version==="string"?`'${W.version}'`:W.version,Y=`
1456
- { key: '${W.key}', version: ${X} },`;return{index:B,text:Y}}return null}function n4($){switch($){case"operation":case"command":case"query":return"operations";case"event":return"events";case"presentation":return"presentations";case"experiment":return"experiments";case"workflow":return"workflows";default:return"operations"}}function YX($,W){let j=[],Q=(Z,B,X)=>{for(let Y of Z){let q=`${Y.key}.v${Y.version}`;if(!B.has(q))j.push({key:Y.key,version:Y.version,type:X,message:`${X} ${Y.key}.v${Y.version} not found`})}};return Q($.operations,W.operations,"Operation"),Q($.events,W.events,"Event"),Q($.presentations,W.presentations,"Presentation"),Q($.experiments,W.experiments,"Experiment"),j}var p4={};P(p4,{removeReferenceStrategy:()=>YW,implementSkeletonStrategy:()=>XW,implementAiStrategy:()=>BW,generateFixLinks:()=>qX,FixService:()=>o4,FIX_STRATEGY_STABILITY:()=>H0,FIX_STRATEGY_LABELS:()=>JX,CiOutputSchema:()=>EX});function qX($,W){let j=[];if(!$.ref||!$.file)return j;if(W.includeCli)j.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(W.includeVscode){let Q=$.file.startsWith("/")?$.file:`/${$.file}`,Z=$.ref,B=Z.line||1,X=Z.column||1;j.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${Q}:${B}:${X}`})}if(W.includeGithubIssue&&W.repository){let Q=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),Z=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
1692
+ `;if(O.forEach((x)=>{let L$=`./${Ej(x.file,".ts")}`;R+=`export * from '${L$}';
1693
+ `}),C)R+=`export * from './registry';
1694
+ `;let v=l$(U,"index.ts");await A.writeFile(v,R),Q.info(`Created/Updated index: ${v}`)}for(let U of b.skipped)L.push({operationId:U.sourceId,reason:U.reason}),Q.debug(`Skipped: ${U.sourceId} - ${U.reason}`);for(let U of b.errors)z.push({operationId:U.sourceId,error:U.error}),Q.error(`Error: ${U.sourceId} - ${U.error}`);return{imported:b.summary.imported,skipped:b.summary.skipped,errors:b.summary.errors,files:w,skippedOperations:L,errorMessages:z}}import{importFromOpenApi as P2,parseOpenApi as k2}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as h2,join as g2}from"path";async function xU($,W,j){let{fs:A,logger:Q}=j,{sources:Z,sourceName:X,interactive:Y,force:B,dryRun:q}=$,{outputDir:H}=W,V=Z??W.openapi?.sources??[];if(X){if(V=V.filter((J)=>J.name===X),V.length===0)throw Error(`Source not found: ${X}`)}if(V.length===0)return Q.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let G={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let J of V){Q.info(`Syncing with source: ${J.name}`);let b=J.url??J.file;if(!b){Q.warn(`Source ${J.name} has no url or file configured`);continue}let w=await k2(b,{fetch:globalThis.fetch,readFile:(z)=>A.readFile(z)});Q.info(`Parsed ${w.operations.length} operations from ${J.name}`);let L=P2(w,W,{prefix:J.prefix,tags:J.tags,exclude:J.exclude,defaultStability:J.defaultStability,defaultAuth:J.defaultAuth});for(let z of L.operationSpecs){let S=g2(H,z.fileName);if(!await A.exists(S)){if(!q){let O=h2(S);await A.mkdir(O),await A.writeFile(S,z.code)}G.added++,G.changes.push({operationId:z.source.sourceId,action:"added",path:S}),Q.info(`Added: ${z.source.sourceId}`)}else if(await A.readFile(S)===z.code)G.unchanged++,G.changes.push({operationId:z.source.sourceId,action:"unchanged",path:S});else if(B==="openapi"){if(!q)await A.writeFile(S,z.code);G.updated++,G.changes.push({operationId:z.source.sourceId,action:"updated",path:S}),Q.info(`Updated: ${z.source.sourceId}`)}else if(B==="contractspec")G.unchanged++,G.changes.push({operationId:z.source.sourceId,action:"unchanged",path:S}),Q.info(`Kept: ${z.source.sourceId}`);else if(Y)G.conflicts++,G.changes.push({operationId:z.source.sourceId,action:"conflict",path:S}),Q.warn(`Conflict: ${z.source.sourceId} - needs resolution`);else G.conflicts++,G.changes.push({operationId:z.source.sourceId,action:"conflict",path:S}),Q.warn(`Conflict: ${z.source.sourceId}`)}}return Q.info(`Sync complete: ${G.added} added, ${G.updated} updated, ${G.unchanged} unchanged, ${G.conflicts} conflicts`),G}import{parseOpenApi as f2}from"@contractspec/lib.contracts-transformers/openapi";async function mU($,W){let{fs:j,logger:A}=W,{specPath:Q,openApiSource:Z,ignoreDescriptions:X,ignoreTags:Y,ignoreTransport:B}=$;A.info(`Validating specs against OpenAPI: ${Z}`);let q=await f2(Z,{fetch:globalThis.fetch,readFile:(z)=>j.readFile(z)});A.info(`Parsed ${q.operations.length} operations from ${q.info.title}`);let H=new Map;for(let z of q.operations)H.set(z.operationId,z);let V=[],G=0,J=0,b=await j.stat(Q),w=[];if(b.isDirectory){let z=await j.glob({pattern:"**/*.ts",cwd:Q,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});w.push(...z)}else w.push(Q);A.info(`Found ${w.length} spec files to validate`);for(let z of w)try{let S=await j.readFile(z),U=S.match(/operationId:\s*['"]([^'"]+)['"]/)||S.match(/name:\s*['"]([^'"]+)['"]/)||S.match(/export\s+const\s+(\w+)Spec\s*=/);if(!U||!U[1]){A.debug(`Could not extract operationId from ${z}`);continue}let O=U[1];G++;let K;if(K=H.get(O),!K){let M=O.replace(/([A-Z])/g,"_$1").toLowerCase();K=H.get(M)}if(!K){for(let[M,E]of H)if(M.toLowerCase().includes(O.toLowerCase())||O.toLowerCase().includes(M.toLowerCase())){K=E;break}}if(!K){V.push({specPath:z,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${O}`}]}),J++;continue}let _=[];if(K.deprecated&&!S.includes("deprecated"))_.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!B){let M=S.match(/path:\s*['"]([^'"]+)['"]/);if(M&&M[1]!==K.path)_.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${M[1]}", OpenAPI has "${K.path}"`})}if(!B){let M=S.match(/method:\s*['"]([^'"]+)['"]/);if(M?.[1]&&M[1].toLowerCase()!==K.method.toLowerCase())_.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${M[1]}", OpenAPI has "${K.method.toUpperCase()}"`})}let I=_.length===0;if(!I)J++;V.push({specPath:z,operationId:K.operationId,valid:I,diffs:_})}catch(S){A.error(`Error validating ${z}: ${S}`),V.push({specPath:z,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${S instanceof Error?S.message:String(S)}`}]}),J++}let L=J===0;return A.info(`Validation ${L?"passed":"failed"}: ${G} specs checked, ${J} with differences`),{valid:L,specsValidated:G,specsWithDiffs:J,results:V}}async function rU($,W,j){let{fs:A,logger:Q}=$,{source:Z,outputDir:X}=W,Y=A.resolve(j??process.cwd(),Z);if(!await A.exists(Y))throw Error(`Source file not found: ${Y}`);let q={...await m(A,j),outputDir:X};return Q.info(`Extracting contracts from ${Y} to ${X}`),y4(q,{source:Y,outputDir:X,dryRun:!1},$)}var m4={};h(m4,{validateFeatureRefs:()=>n2,getArrayNameForSpecType:()=>v4,detectFeatureContext:()=>u2,computeAddSpecEdit:()=>d2});function u2($,W){let j=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],A=null;for(let{type:V,regex:G,specType:J}of j){let b;G.lastIndex=0;while((b=G.exec($))!==null)if(!A||b.index>A.index)A={type:V,specType:J,index:b.index}}if(!A)return null;let Q=$.slice(A.index)+W,Z=A.type;new RegExp(`${Z}\\s*:\\s*\\[`).exec(Q);let Y=$.slice(A.index),B=0,q=!1,H="";for(let V=0;V<Y.length;V++){let G=Y[V],J=V>0?Y[V-1]:"";if((G==='"'||G==="'"||G==="`")&&J!=="\\"){if(!q)q=!0,H=G;else if(G===H)q=!1;continue}if(q)continue;if(G==="[")B++;else if(G==="]"){if(B--,B===0)return null}}if(B>0)return{type:A.type,specType:A.specType};return null}function d2($,W){let j=v4(W.type),Q=new RegExp(`${j}\\s*:\\s*\\[`,"g").exec($);if(Q){let Z=Q.index+Q[0].length,X=typeof W.version==="string"?`'${W.version}'`:W.version,Y=`
1695
+ { key: '${W.key}', version: ${X} },`;return{index:Z,text:Y}}return null}function v4($){switch($){case"operation":case"command":case"query":return"operations";case"event":return"events";case"presentation":return"presentations";case"experiment":return"experiments";case"workflow":return"workflows";default:return"operations"}}function n2($,W){let j=[],A=(Q,Z,X)=>{for(let Y of Q){let B=`${Y.key}.v${Y.version}`;if(!Z.has(B))j.push({key:Y.key,version:Y.version,type:X,message:`${X} ${Y.key}.v${Y.version} not found`})}};return A($.operations,W.operations,"Operation"),A($.events,W.events,"Event"),A($.presentations,W.presentations,"Presentation"),A($.experiments,W.experiments,"Experiment"),j}var g4={};h(g4,{removeReferenceStrategy:()=>yW,implementSkeletonStrategy:()=>xW,implementAiStrategy:()=>FW,generateFixLinks:()=>c2,FixService:()=>h4,FIX_STRATEGY_STABILITY:()=>N0,FIX_STRATEGY_LABELS:()=>t2,CiOutputSchema:()=>YY});function c2($,W){let j=[];if(!$.ref||!$.file)return j;if(W.includeCli)j.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(W.includeVscode){let A=$.file.startsWith("/")?$.file:`/${$.file}`,Q=$.ref,Z=Q.line||1,X=Q.column||1;j.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${A}:${Z}:${X}`})}if(W.includeGithubIssue&&W.repository){let A=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),Q=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
1457
1696
 
1458
1697
  > ${$.message}
1459
1698
 
1460
- Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${W.repository}/issues/new?title=${Q}&body=${Z}`})}return j}import KX from"path";function H$($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function V$($,W){let j=$.enrichment?.owners?.length?$.enrichment.owners.map((X)=>`'${X}'`).join(", "):"'@team'",Q=$.enrichment?.tags?.length?$.enrichment.tags.map((X)=>`'${X}'`).join(", "):"",Z=$.description||`TODO: Add description for ${$.key}`,B=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(W)Object.entries(W).forEach(([X,Y])=>{if(Y!==void 0)B.push(`${X}: ${Y}`)});return B.push(`owners: [${j}]`),B.push(`tags: [${Q}]`),B.push(`description: '${Z}'`),B.join(`,
1461
- `)}function X0($){let W=$.key.split(".").pop()||"Unknown",j=H$(W)+"Spec",Q=V$($,{kind:"'api'"});return`/**
1699
+ Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${W.repository}/issues/new?title=${A}&body=${Q}`})}return j}import a2 from"path";function w$($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function K$($,W){let j=$.enrichment?.owners?.length?$.enrichment.owners.map((X)=>`'${X}'`).join(", "):"'@team'",A=$.enrichment?.tags?.length?$.enrichment.tags.map((X)=>`'${X}'`).join(", "):"",Q=$.description||`TODO: Add description for ${$.key}`,Z=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(W)Object.entries(W).forEach(([X,Y])=>{if(Y!==void 0)Z.push(`${X}: ${Y}`)});return Z.push(`owners: [${j}]`),Z.push(`tags: [${A}]`),Z.push(`description: '${Q}'`),Z.join(`,
1700
+ `)}function S0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"Spec",A=K$($,{kind:"'api'"});return`/**
1462
1701
  * Capability: ${$.key}
1463
1702
  *
1464
1703
  * Skeleton spec generated by ContractSpec fix command.
@@ -1471,7 +1710,7 @@ import { defineCapability } from '@contractspec/lib.contracts-spec';
1471
1710
 
1472
1711
  export const ${j} = defineCapability({
1473
1712
  meta: {
1474
- ${Q}
1713
+ ${A}
1475
1714
  },
1476
1715
 
1477
1716
  provides: [
@@ -1495,7 +1734,7 @@ export const ${j} = defineCapability({
1495
1734
  // }
1496
1735
  ],
1497
1736
  });
1498
- `}function Y0($){let W=$.key.split(".").pop()||"Unknown",j=H$(W)+"EventSpec",Q=j.replace("Spec","Payload"),Z=V$($);return`/**
1737
+ `}function I0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"EventSpec",A=j.replace("Spec","Payload"),Q=K$($);return`/**
1499
1738
  * Event: ${$.key}
1500
1739
  *
1501
1740
  * Skeleton spec generated by ContractSpec fix command.
@@ -1508,8 +1747,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
1508
1747
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
1509
1748
 
1510
1749
  // TODO: Define event payload schema
1511
- export const ${Q} = new SchemaModel({
1512
- name: '${Q}',
1750
+ export const ${A} = new SchemaModel({
1751
+ name: '${A}',
1513
1752
  description: 'Payload for ${$.key} event',
1514
1753
  fields: {
1515
1754
  // Add your payload fields here
@@ -1521,10 +1760,10 @@ export const ${Q} = new SchemaModel({
1521
1760
 
1522
1761
  export const ${j} = defineEvent({
1523
1762
  meta: {
1524
- ${Z}
1763
+ ${Q}
1525
1764
  },
1526
1765
 
1527
- payload: ${Q},
1766
+ payload: ${A},
1528
1767
 
1529
1768
  // TODO: Specify PII fields if any
1530
1769
  // piiFields: ['user.email'],
@@ -1535,7 +1774,7 @@ export const ${j} = defineEvent({
1535
1774
  // policy: 'archive',
1536
1775
  // },
1537
1776
  });
1538
- `}function AX($){let W=$.toLowerCase(),j=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let Q of j)if(W.includes(Q))return"query";return"command"}function q0($){let W=$.key.split(".").pop()||"Unknown",j=H$(W)+"Spec",Q=j.replace("Spec","Input"),Z=j.replace("Spec","Output"),B=AX($.key),X=B==="query"?"defineQuery":"defineCommand",Y=$.enrichment?.goal||"TODO: Define the business goal",q=$.enrichment?.context||"TODO: Provide context",A=V$($,{goal:`'${Y}'`,context:`'${q}'`});return`/**
1777
+ `}function r2($){let W=$.toLowerCase(),j=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let A of j)if(W.includes(A))return"query";return"command"}function M0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"Spec",A=j.replace("Spec","Input"),Q=j.replace("Spec","Output"),Z=r2($.key),X=Z==="query"?"defineQuery":"defineCommand",Y=$.enrichment?.goal||"TODO: Define the business goal",B=$.enrichment?.context||"TODO: Provide context",q=K$($,{goal:`'${Y}'`,context:`'${B}'`});return`/**
1539
1778
  * Operation: ${$.key}
1540
1779
  *
1541
1780
  * Skeleton spec generated by ContractSpec fix command.
@@ -1548,8 +1787,8 @@ import { ${X} } from '@contractspec/lib.contracts-spec';
1548
1787
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
1549
1788
 
1550
1789
  // TODO: Define input schema
1551
- export const ${Q} = new SchemaModel({
1552
- name: '${Q}',
1790
+ export const ${A} = new SchemaModel({
1791
+ name: '${A}',
1553
1792
  description: 'Input for ${$.key}',
1554
1793
  fields: {
1555
1794
  // Add your input fields here
@@ -1558,8 +1797,8 @@ export const ${Q} = new SchemaModel({
1558
1797
  });
1559
1798
 
1560
1799
  // TODO: Define output schema
1561
- export const ${Z} = new SchemaModel({
1562
- name: '${Z}',
1800
+ export const ${Q} = new SchemaModel({
1801
+ name: '${Q}',
1563
1802
  description: 'Output for ${$.key}',
1564
1803
  fields: {
1565
1804
  // Add your output fields here
@@ -1569,12 +1808,12 @@ export const ${Z} = new SchemaModel({
1569
1808
 
1570
1809
  export const ${j} = ${X}({
1571
1810
  meta: {
1572
- ${A}
1811
+ ${q}
1573
1812
  },
1574
1813
 
1575
1814
  io: {
1576
- input: ${Q},
1577
- output: ${Z},
1815
+ input: ${A},
1816
+ output: ${Q},
1578
1817
  errors: {
1579
1818
  // TODO: Define possible errors
1580
1819
  // EXAMPLE_ERROR: {
@@ -1596,7 +1835,7 @@ export const ${j} = ${X}({
1596
1835
  },
1597
1836
 
1598
1837
  transport: {
1599
- rest: { method: '${B==="command"?"POST":"GET"}' },
1838
+ rest: { method: '${Z==="command"?"POST":"GET"}' },
1600
1839
  gql: { field: '${$.key.replace(/\./g,"_")}' },
1601
1840
  mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
1602
1841
  },
@@ -1613,7 +1852,7 @@ export const ${j} = ${X}({
1613
1852
  examples: [],
1614
1853
  },
1615
1854
  });
1616
- `}function HX($){let W=$.toLowerCase();if(W.includes("doc")||W.includes("guide")||W.includes("readme"))return"markdown";if(W.includes("data")||W.includes("api")||W.includes("export"))return"data";return"web_component"}function A0($){let W=$.key.split(".").pop()||"Unknown",j=H$(W)+"PresentationSpec",Q=HX($.key),Z=V$($);return`/**
1855
+ `}function l2($){let W=$.toLowerCase();if(W.includes("doc")||W.includes("guide")||W.includes("readme"))return"markdown";if(W.includes("data")||W.includes("api")||W.includes("export"))return"data";return"web_component"}function E0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"PresentationSpec",A=l2($.key),Q=K$($);return`/**
1617
1856
  * Presentation: ${$.key}
1618
1857
  *
1619
1858
  * Skeleton spec generated by ContractSpec fix command.
@@ -1626,10 +1865,10 @@ import { definePresentation } from '@contractspec/lib.contracts-spec';
1626
1865
 
1627
1866
  export const ${j} = definePresentation({
1628
1867
  meta: {
1629
- ${Z}
1868
+ ${Q}
1630
1869
  },
1631
1870
 
1632
- kind: '${Q}',
1871
+ kind: '${A}',
1633
1872
 
1634
1873
  // TODO: Define content structure
1635
1874
  content: {
@@ -1653,7 +1892,7 @@ export const ${j} = definePresentation({
1653
1892
  // focusable: true,
1654
1893
  // },
1655
1894
  });
1656
- `}import Q$ from"path";function ZW($,W){if(W.outputDir)return a1(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=VX($.featureFile);if(j)return a1(j,$.ref.key,$.specType)}return a1(Q$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function VX($){let W=Q$.dirname($),j=Q$.parse($).root,Q=0;while(W!==j&&Q<50){if(Q$.basename(W)==="src")return W;W=Q$.dirname(W),Q++}W=Q$.dirname($),Q=0;while(W!==j&&Q<50)W=Q$.dirname(W),Q++;let Z=$.lastIndexOf(`${Q$.sep}src${Q$.sep}`);if(Z!==-1)return $.substring(0,Z+5);return null}function a1($,W,j){let Q=W.replace(/\./g,"-").toLowerCase(),Z=GX(j),B=zX(j);return Q$.join($,B,`${Q}${Z}`)}function GX($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function zX($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var JX={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},H0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function BW($,W,j){let{fs:Q,logger:Z}=j,{ref:B,specType:X,featureKey:Y}=$;try{let q={key:B.key,version:B.version,specType:X,stability:H0["implement-ai"],featureKey:Y},A=q;if(W.aiConfig)try{A=await UX(q,W,Z)}catch(z){Z.warn("AI enrichment failed, falling back to skeleton",{error:z instanceof Error?z.message:String(z)})}else Z.info("No AI config provided, using skeleton with experimental stability");let H=IX(A);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=ZW($,W),G=[];if(!W.dryRun){let z=KX.dirname(V);await Q.mkdir(z),await Q.writeFile(V,H),G.push({path:V,action:"created"})}else G.push({path:V,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:G}}catch(q){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:q instanceof Error?q.message:String(q)}}}async function UX($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Z}=await Promise.resolve().then(() => (WW(),U4)),B=_X(W),X=new Z(B),Y=$.specType==="operation"?"command":$.specType,q=`${l4($.specType)} for ${$.key}`;if($.specType==="operation"){let A=await X.generateOperationSpec(q,Y);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:A.owners,tags:A.tags}}}if($.specType==="event"){let A=await X.generateEventSpec(q);return{...$,description:A.description,enrichment:{goal:`Emit ${$.key} event`,context:A.description,owners:["@team"],tags:A.tags}}}}catch(Z){j.warn("AIGenerator call failed, falling back to heuristics",{error:Z instanceof Error?Z.message:String(Z)})}let Q=LX($.key,$.specType);return{...$,description:Q.description,enrichment:{goal:Q.goal,context:Q.context,owners:["@team"],tags:Q.tags}}}function _X($){let W=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[W?.provider??"openai"]??"openai",aiModel:W?.model??"gpt-4-turbo",customApiKey:W?.apiKey??"",customEndpoint:W?.endpoint??""}}function LX($,W){let j=$.split("."),Q=j[0]||"unknown",Z=j.slice(1).join(" ").replace(/_/g," "),B=[Q],X=Z.toLowerCase().split(" "),q=["auth","user","admin","api","data","search","create","update","delete"].filter((A)=>X.some((H)=>H.includes(A)));return{description:`${l4(W)} for ${Q} ${Z}`,goal:`Enable ${Z} functionality in the ${Q} domain`,context:`Part of the ${Q} feature set. Generated by ContractSpec AI fix.`,tags:[...B,...q]}}function IX($){switch($.specType){case"operation":return q0($);case"event":return Y0($);case"presentation":return A0($);case"capability":return X0($);default:return}}function l4($){return $.charAt(0).toUpperCase()+$.slice(1)}import OX from"path";async function XW($,W,j){let{fs:Q}=j,{ref:Z,specType:B,featureKey:X}=$;try{let Y={key:Z.key,version:Z.version,specType:B,stability:H0["implement-skeleton"],description:`Skeleton spec for ${Z.key}`,featureKey:X},q=bX(Y);if(!q)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${B}`};let A=ZW($,W),H=[];if(!W.dryRun){let V=OX.dirname(A);await Q.mkdir(V),await Q.writeFile(A,q),H.push({path:A,action:"created"})}else H.push({path:A,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function bX($){switch($.specType){case"operation":return q0($);case"event":return Y0($);case"presentation":return A0($);case"capability":return X0($);default:return}}async function YW($,W,j){let{fs:Q}=j,{ref:Z,featureFile:B,specType:X}=$;try{let Y=await Q.readFile(B),q=Y,A=wX(Y,Z,X);if(A===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Z.key}.v${Z.version} in ${B}`};let H=[];if(!W.dryRun)await Q.writeFile(B,A),H.push({path:B,action:"modified",previousContent:q});else H.push({path:B,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function wX($,W,j){if(!CX(j))return $;let Z=r4(W.key),B=r4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Z}['"],\\s*version:\\s*['"]${B}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${B}['"],\\s*key:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let q of X)Y=Y.replace(q,"");return Y=SX(Y),Y}function CX($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function r4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function SX($){return $.replace(/,(\s*)\]/g,"$1]")}class o4{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(W,j)=>YW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(W,j)=>XW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(W,j)=>BW(W,j,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let W=[];if($.type==="unresolved-ref")W.push("remove-reference"),W.push("implement-skeleton"),W.push("implement-ai");else if($.type==="broken-link")W.push("remove-reference"),W.push("implement-skeleton");return W}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,W){let j=this.strategies.get(W.strategy);if(!j)return{success:!1,strategy:W.strategy,issue:$,filesChanged:[],error:`Strategy ${W.strategy} not found`};return this.adapters.logger.info(`Applying fix ${W.strategy} for ${$.ref.key}`,{dryRun:W.dryRun}),j.fix($,W)}async batchFix($){let W=[],j=0,Q=0;for(let Z of $.issues)try{let B=await this.fixIssue(Z,$.options);if(W.push(B),B.success)j++;else Q++}catch(B){Q++,W.push({success:!1,strategy:$.options.strategy,issue:Z,filesChanged:[],error:B instanceof Error?B.message:String(B)})}return{total:$.issues.length,succeeded:j,failed:Q,results:W}}async scanAndGetFixables($={}){return(await l0(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((j)=>this.getToFix(j)).filter((j)=>j!==null)}getToFix($){let W=this.getStrategiesForIssue($);if(W.length===0)return null;let j=this.parseFixableIssue($);if(!j)return null;return{...j,availableStrategies:W,strategies:[]}}resolveStrategy($,W){let{forceStrategy:j,preferAi:Q,select:Z}=W;if(j)return Promise.resolve(j);if(Q&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof Z==="function")return Z($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((W)=>{return this.getToFix(W)}).filter((W)=>W!==null)}}import{z as g$}from"zod";var EX=g$.union([g$.array(g$.unknown()),g$.object({issues:g$.array(g$.unknown())}).transform(($)=>$.issues)]);import{exec as MX}from"child_process";import{promisify as NX}from"util";var RX=NX(MX),i4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function o_($,W,j={}){if($.length===0)return;let Q=j.cwd??process.cwd(),Z=i4[j.type??"biome"]??i4.biome,B=50;for(let X=0;X<$.length;X+=B){let q=$.slice(X,X+B).map((A)=>`"${A}"`).join(" ");try{await RX(`${Z} ${q}`,{cwd:Q})}catch(A){}}}import G$ from"path";async function t_($,W){let j=G$.join(W,"contracts"),Q=G$.join(W,"generated"),Z=G$.join(Q,"docs"),B=await $.fs.exists(j),X=await $.fs.exists(Q);if(!B)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await h($,{pattern:"contracts/**/*.ts"}),q=[];if(X)for(let z of Y){let J=z.key||G$.basename(z.filePath,".ts"),K=G$.join(Z,`${J}.md`);if(!await $.fs.exists(K))q.push(J)}else if(Y.length>0)for(let z of Y){let J=z.key||G$.basename(z.filePath,".ts");q.push(J)}let A=G$.join(j,"index.ts"),H=G$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(A),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:q,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var e4={};P(e4,{runHook:()=>a4,getAvailableHooks:()=>t4});import{exec as DX}from"child_process";import{promisify as FX}from"util";var xX=FX(DX);async function a4($,W){let{fs:j,logger:Q}=$,{hookName:Z,dryRun:B=!1}=W,X=R(W.workspaceRoot);Q.info(`Running hook: ${Z}`,{workspaceRoot:X,dryRun:B});let Y=await s4(j,X);if(!Y)return{hookName:Z,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let q=Y[Z];if(!q||q.length===0)return{hookName:Z,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Z}`};Q.info(`Found ${q.length} command(s) for ${Z}`);let A=[],H=!0;for(let G of q){if(B){Q.info(`[DRY RUN] Would execute: ${G}`),A.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}Q.info(`Executing: ${G}`);try{let{stdout:z,stderr:J}=await xX(G,{cwd:X,timeout:300000});A.push({command:G,success:!0,exitCode:0,stdout:z,stderr:J}),Q.info(`\u2713 ${G}`)}catch(z){H=!1;let J=z;A.push({command:G,success:!1,exitCode:J.code??1,stdout:J.stdout??"",stderr:J.stderr??J.message??String(z)}),Q.error(`\u2717 ${G}`,{exitCode:J.code,stderr:J.stderr});break}}let V=A.filter((G)=>G.success).length;return{hookName:Z,success:H,commandResults:A,totalCommands:q.length,successfulCommands:V,summary:H?`\u2713 All ${q.length} command(s) passed`:`\u2717 ${V}/${q.length} command(s) passed`}}async function t4($,W){let j=await s4($.fs,W);return j?Object.keys(j):[]}async function s4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let Q=await $.readFile(j);return JSON.parse(Q).hooks??null}catch{return null}}import{detectFramework as TX,extractFromProject as vX}from"@contractspec/lib.source-extractors";import{generateOperations as yX,generateRegistry as PX,generateSchemas as mX}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as kX}from"@contractspec/lib.source-extractors/extractors";import{dirname as gX,join as t1}from"path";async function hX($,W,j,Q){let{fs:Z,logger:B}=j,X=Q??process.cwd();kX(),B.info(`Scanning source code in ${X}...`);let Y={readFile:(I)=>Z.readFile(I),glob:(I,U)=>Z.glob({pattern:I,cwd:U?.cwd}),exists:(I)=>Z.exists(I)},q=await TX(X,{readFile:(I)=>Z.readFile(I),glob:(I)=>Z.glob({pattern:I})});if(q.frameworks.length===0)return B.warn("No supported frameworks detected"),{success:!1,report:fX(),errors:["No supported frameworks detected in project"]};B.info(`Detected frameworks: ${q.frameworks.map((I)=>I.name).join(", ")}`);let{extractorRegistry:A}=await import("@contractspec/lib.source-extractors");for(let I of A.getAll())if("setFs"in I&&typeof I.setFs==="function")I.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await vX(q,H);if(!V.success||!V.ir)return{success:!1,report:uX(V.errors??[]),errors:V.errors?.map((I)=>I.message)};let G=V.ir;if(B.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:dX(G)};let z=W.outputDir??t1($.outputDir,"generated"),J={outputDir:z,defaultAuth:"user"},K=yX(G,J),_=mX(G,J),w=PX(K),b=[...K,..._,w];if(!W.dryRun)for(let I of b){let U=t1(z,I.path),O=gX(U);if(!await Z.exists(O))await Z.mkdir(O);await Z.writeFile(U,I.content),B.info(`Created: ${U}`)}else for(let I of b)B.info(`[DRY RUN] Would create: ${t1(z,I.path)}`);let L={files:b,operationsGenerated:K.length,schemasGenerated:_.length,warnings:[]};return{success:!0,ir:G,generation:L,report:nX(G,L,W)}}function fX(){return`# Import Report
1895
+ `}import X$ from"path";function TW($,W){if(W.outputDir)return Nj(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=o2($.featureFile);if(j)return Nj(j,$.ref.key,$.specType)}return Nj(X$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function o2($){let W=X$.dirname($),j=X$.parse($).root,A=0;while(W!==j&&A<50){if(X$.basename(W)==="src")return W;W=X$.dirname(W),A++}W=X$.dirname($),A=0;while(W!==j&&A<50)W=X$.dirname(W),A++;let Q=$.lastIndexOf(`${X$.sep}src${X$.sep}`);if(Q!==-1)return $.substring(0,Q+5);return null}function Nj($,W,j){let A=W.replace(/\./g,"-").toLowerCase(),Q=i2(j),Z=p2(j);return X$.join($,Z,`${A}${Q}`)}function i2($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function p2($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var t2={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},N0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function FW($,W,j){let{fs:A,logger:Q}=j,{ref:Z,specType:X,featureKey:Y}=$;try{let B={key:Z.key,version:Z.version,specType:X,stability:N0["implement-ai"],featureKey:Y},q=B;if(W.aiConfig)try{q=await s2(B,W,Q)}catch(J){Q.warn("AI enrichment failed, falling back to skeleton",{error:J instanceof Error?J.message:String(J)})}else Q.info("No AI config provided, using skeleton with experimental stability");let H=WY(q);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=TW($,W),G=[];if(!W.dryRun){let J=a2.dirname(V);await A.mkdir(J),await A.writeFile(V,H),G.push({path:V,action:"created"})}else G.push({path:V,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:G}}catch(B){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:B instanceof Error?B.message:String(B)}}}async function s2($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Q}=await Promise.resolve().then(() => (DW(),D4)),Z=e2(W),X=new Q(Z),Y=$.specType==="operation"?"command":$.specType,B=`${P4($.specType)} for ${$.key}`;if($.specType==="operation"){let q=await X.generateOperationSpec(B,Y);return{...$,description:q.description,enrichment:{goal:q.goal,context:q.context,owners:q.owners,tags:q.tags}}}if($.specType==="event"){let q=await X.generateEventSpec(B);return{...$,description:q.description,enrichment:{goal:`Emit ${$.key} event`,context:q.description,owners:["@team"],tags:q.tags}}}}catch(Q){j.warn("AIGenerator call failed, falling back to heuristics",{error:Q instanceof Error?Q.message:String(Q)})}let A=$Y($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function e2($){let W=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[W?.provider??"openai"]??"openai",aiModel:W?.model??"gpt-4-turbo",customApiKey:W?.apiKey??"",customEndpoint:W?.endpoint??""}}function $Y($,W){let j=$.split("."),A=j[0]||"unknown",Q=j.slice(1).join(" ").replace(/_/g," "),Z=[A],X=Q.toLowerCase().split(" "),B=["auth","user","admin","api","data","search","create","update","delete"].filter((q)=>X.some((H)=>H.includes(q)));return{description:`${P4(W)} for ${A} ${Q}`,goal:`Enable ${Q} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...Z,...B]}}function WY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}function P4($){return $.charAt(0).toUpperCase()+$.slice(1)}import jY from"path";async function xW($,W,j){let{fs:A}=j,{ref:Q,specType:Z,featureKey:X}=$;try{let Y={key:Q.key,version:Q.version,specType:Z,stability:N0["implement-skeleton"],description:`Skeleton spec for ${Q.key}`,featureKey:X},B=AY(Y);if(!B)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${Z}`};let q=TW($,W),H=[];if(!W.dryRun){let V=jY.dirname(q);await A.mkdir(V),await A.writeFile(q,B),H.push({path:q,action:"created"})}else H.push({path:q,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function AY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}async function yW($,W,j){let{fs:A}=j,{ref:Q,featureFile:Z,specType:X}=$;try{let Y=await A.readFile(Z),B=Y,q=QY(Y,Q,X);if(q===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Q.key}.v${Q.version} in ${Z}`};let H=[];if(!W.dryRun)await A.writeFile(Z,q),H.push({path:Z,action:"modified",previousContent:B});else H.push({path:Z,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function QY($,W,j){if(!ZY(j))return $;let Q=k4(W.key),Z=k4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Q}['"],\\s*version:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${Z}['"],\\s*key:\\s*['"]${Q}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let B of X)Y=Y.replace(B,"");return Y=XY(Y),Y}function ZY($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function k4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XY($){return $.replace(/,(\s*)\]/g,"$1]")}class h4{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(W,j)=>yW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(W,j)=>xW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(W,j)=>FW(W,j,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let W=[];if($.type==="unresolved-ref")W.push("remove-reference"),W.push("implement-skeleton"),W.push("implement-ai");else if($.type==="broken-link")W.push("remove-reference"),W.push("implement-skeleton");return W}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,W){let j=this.strategies.get(W.strategy);if(!j)return{success:!1,strategy:W.strategy,issue:$,filesChanged:[],error:`Strategy ${W.strategy} not found`};return this.adapters.logger.info(`Applying fix ${W.strategy} for ${$.ref.key}`,{dryRun:W.dryRun}),j.fix($,W)}async batchFix($){let W=[],j=0,A=0;for(let Q of $.issues)try{let Z=await this.fixIssue(Q,$.options);if(W.push(Z),Z.success)j++;else A++}catch(Z){A++,W.push({success:!1,strategy:$.options.strategy,issue:Q,filesChanged:[],error:Z instanceof Error?Z.message:String(Z)})}return{total:$.issues.length,succeeded:j,failed:A,results:W}}async scanAndGetFixables($={}){return(await zW(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((j)=>this.getToFix(j)).filter((j)=>j!==null)}getToFix($){let W=this.getStrategiesForIssue($);if(W.length===0)return null;let j=this.parseFixableIssue($);if(!j)return null;return{...j,availableStrategies:W,strategies:[]}}resolveStrategy($,W){let{forceStrategy:j,preferAi:A,select:Q}=W;if(j)return Promise.resolve(j);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof Q==="function")return Q($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((W)=>{return this.getToFix(W)}).filter((W)=>W!==null)}}import{z as o$}from"zod";var YY=o$.union([o$.array(o$.unknown()),o$.object({issues:o$.array(o$.unknown())}).transform(($)=>$.issues)]);import{exec as BY}from"child_process";import{promisify as qY}from"util";var HY=qY(BY),f4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function cL($,W,j={}){if($.length===0)return;let A=j.cwd??process.cwd(),Q=f4[j.type??"biome"]??f4.biome,Z=50;for(let X=0;X<$.length;X+=Z){let B=$.slice(X,X+Z).map((q)=>`"${q}"`).join(" ");try{await HY(`${Q} ${B}`,{cwd:A})}catch(q){}}}import _$ from"path";async function iL($,W){let j=_$.join(W,"contracts"),A=_$.join(W,"generated"),Q=_$.join(A,"docs"),Z=await $.fs.exists(j),X=await $.fs.exists(A);if(!Z)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await $$($,{pattern:"contracts/**/*.ts"}),B=[];if(X)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts"),w=_$.join(Q,`${b}.md`);if(!await $.fs.exists(w))B.push(b)}else if(Y.length>0)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts");B.push(b)}let q=_$.join(j,"index.ts"),H=_$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(q),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:B,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var c4={};h(c4,{runHook:()=>u4,getAvailableHooks:()=>d4});import{exec as VY}from"child_process";import{promisify as GY}from"util";var JY=GY(VY);async function u4($,W){let{fs:j,logger:A}=$,{hookName:Q,dryRun:Z=!1}=W,X=D(W.workspaceRoot);A.info(`Running hook: ${Q}`,{workspaceRoot:X,dryRun:Z});let Y=await n4(j,X);if(!Y)return{hookName:Q,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let B=Y[Q];if(!B||B.length===0)return{hookName:Q,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Q}`};A.info(`Found ${B.length} command(s) for ${Q}`);let q=[],H=!0;for(let G of B){if(Z){A.info(`[DRY RUN] Would execute: ${G}`),q.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${G}`);try{let{stdout:J,stderr:b}=await JY(G,{cwd:X,timeout:300000});q.push({command:G,success:!0,exitCode:0,stdout:J,stderr:b}),A.info(`\u2713 ${G}`)}catch(J){H=!1;let b=J;q.push({command:G,success:!1,exitCode:b.code??1,stdout:b.stdout??"",stderr:b.stderr??b.message??String(J)}),A.error(`\u2717 ${G}`,{exitCode:b.code,stderr:b.stderr});break}}let V=q.filter((G)=>G.success).length;return{hookName:Q,success:H,commandResults:q,totalCommands:B.length,successfulCommands:V,summary:H?`\u2713 All ${B.length} command(s) passed`:`\u2717 ${V}/${B.length} command(s) passed`}}async function d4($,W){let j=await n4($.fs,W);return j?Object.keys(j):[]}async function n4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let A=await $.readFile(j);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as bY,extractFromProject as wY}from"@contractspec/lib.source-extractors";import{generateOperations as KY,generateRegistry as _Y,generateSchemas as zY}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as UY}from"@contractspec/lib.source-extractors/extractors";import{dirname as LY,join as Rj}from"path";async function OY($,W,j,A){let{fs:Q,logger:Z}=j,X=A??process.cwd();UY(),Z.info(`Scanning source code in ${X}...`);let Y={readFile:(O)=>Q.readFile(O),glob:(O,K)=>Q.glob({pattern:O,cwd:K?.cwd}),exists:(O)=>Q.exists(O)},B=await bY(X,{readFile:(O)=>Q.readFile(O),glob:(O)=>Q.glob({pattern:O})});if(B.frameworks.length===0)return Z.warn("No supported frameworks detected"),{success:!1,report:SY(),errors:["No supported frameworks detected in project"]};Z.info(`Detected frameworks: ${B.frameworks.map((O)=>O.name).join(", ")}`);let{extractorRegistry:q}=await import("@contractspec/lib.source-extractors");for(let O of q.getAll())if("setFs"in O&&typeof O.setFs==="function")O.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await wY(B,H);if(!V.success||!V.ir)return{success:!1,report:IY(V.errors??[]),errors:V.errors?.map((O)=>O.message)};let G=V.ir;if(Z.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:MY(G)};let J=W.outputDir??Rj($.outputDir,"generated"),b={outputDir:J,defaultAuth:"user"},w=KY(G,b),L=zY(G,b),z=_Y(w),S=[...w,...L,z];if(!W.dryRun)for(let O of S){let K=Rj(J,O.path),_=LY(K);if(!await Q.exists(_))await Q.mkdir(_);await Q.writeFile(K,O.content),Z.info(`Created: ${K}`)}else for(let O of S)Z.info(`[DRY RUN] Would create: ${Rj(J,O.path)}`);let U={files:S,operationsGenerated:w.length,schemasGenerated:L.length,warnings:[]};return{success:!0,ir:G,generation:U,report:EY(G,U,W)}}function SY(){return`# Import Report
1657
1896
 
1658
1897
  ## \u274C No Supported Frameworks Detected
1659
1898
 
@@ -1670,13 +1909,13 @@ No supported frameworks were detected in the project.
1670
1909
  - Next.js API Routes
1671
1910
 
1672
1911
  Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
1673
- `}function uX($){return`# Import Report
1912
+ `}function IY($){return`# Import Report
1674
1913
 
1675
1914
  ## \u274C Extraction Failed
1676
1915
 
1677
1916
  ${$.map((W)=>`- ${W.message}`).join(`
1678
1917
  `)}
1679
- `}function dX($){return`# Import Analysis Report
1918
+ `}function MY($){return`# Import Analysis Report
1680
1919
 
1681
1920
  ## Summary
1682
1921
 
@@ -1708,7 +1947,7 @@ ${$.endpoints.map((W)=>`- \`${W.method} ${W.path}\` - ${W.confidence.level}`).jo
1708
1947
 
1709
1948
  ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
1710
1949
  `):"None"}
1711
- `}function nX($,W,j){return`# Import Report${j.dryRun?" (Dry Run)":""}
1950
+ `}function EY($,W,j){return`# Import Report${j.dryRun?" (Dry Run)":""}
1712
1951
 
1713
1952
  ## \u2705 Import Successful
1714
1953
 
@@ -1738,31 +1977,37 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
1738
1977
  2. Fill in TODO placeholders with business context
1739
1978
  3. Run \`contractspec validate\` to verify contracts
1740
1979
  4. Move stable contracts from \`generated/\` to \`curated/\`
1741
- `}function cX($,W,j={}){let Q=[];if(Q.push("# Import Report"),Q.push(""),Q.push(`**Generated**: ${new Date().toISOString()}`),Q.push(""),Q.push("## Summary"),Q.push(""),Q.push("| Metric | Count |"),Q.push("|--------|-------|"),Q.push(`| Files Scanned | ${$.stats.filesScanned} |`),Q.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),Q.push(`| Schemas Found | ${$.stats.schemasFound} |`),Q.push(`| Errors Found | ${$.stats.errorsFound} |`),Q.push(`| Events Found | ${$.stats.eventsFound} |`),Q.push(""),j.includeStats!==!1)Q.push("### Confidence"),Q.push(""),Q.push("| Level | Count |"),Q.push("|-------|-------|"),Q.push(`| High | ${$.stats.highConfidence} |`),Q.push(`| Medium | ${$.stats.mediumConfidence} |`),Q.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),Q.push("");Q.push("### Frameworks Detected"),Q.push("");for(let Z of $.project.frameworks)Q.push(`- **${Z.name}** (${Z.confidence})`);if(Q.push(""),j.includeEndpoints!==!1&&$.endpoints.length>0){Q.push("## Endpoints"),Q.push(""),Q.push("| Method | Path | Kind | Confidence |"),Q.push("|--------|------|------|------------|");for(let Z of $.endpoints)Q.push(`| ${Z.method} | \`${Z.path}\` | ${Z.kind} | ${Z.confidence.level} |`);Q.push("")}if(j.includeSchemas!==!1&&$.schemas.length>0){Q.push("## Schemas"),Q.push(""),Q.push("| Name | Type | Confidence |"),Q.push("|------|------|------------|");for(let Z of $.schemas)Q.push(`| ${Z.name} | ${Z.schemaType} | ${Z.confidence.level} |`);Q.push("")}if(W&&j.includeIssues!==!1){Q.push("## Verification"),Q.push(""),Q.push("| Status | Count |"),Q.push("|--------|-------|"),Q.push(`| Valid | ${W.summary.validEndpoints} |`),Q.push(`| Warnings | ${W.summary.warningEndpoints} |`),Q.push(`| Errors | ${W.summary.errorEndpoints} |`),Q.push("");let Z=W.endpointResults.filter((B)=>B.issues.length>0);if(Z.length>0){Q.push("### Issues"),Q.push("");for(let B of Z){Q.push(`#### ${B.endpoint.method} ${B.endpoint.path}`);for(let X of B.issues){let Y=X.severity==="error"?"\u274C":X.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(Q.push(`- ${Y} **${X.code}**: ${X.message}`),X.suggestion)Q.push(` - *Suggestion*: ${X.suggestion}`)}Q.push("")}}}if(j.includeAmbiguities!==!1&&$.ambiguities.length>0){Q.push("## Ambiguities (Require Review)"),Q.push("");for(let Z of $.ambiguities)if(Q.push(`- **${Z.type}** (${Z.itemId}): ${Z.description}`),Z.suggestion)Q.push(` - *Suggestion*: ${Z.suggestion}`);Q.push("")}return Q.push("## Next Steps"),Q.push(""),Q.push("1. Review generated contracts in the output directory"),Q.push("2. Fill in TODO placeholders with business context"),Q.push("3. Run `contractspec validate` to verify contracts"),Q.push("4. Move stable contracts from `generated/` to `curated/`"),Q.push(""),Q.join(`
1742
- `)}function lX($,W){let j=[];j.push(""),j.push("\uD83D\uDCCA Summary"),j.push(` Files scanned: ${$.stats.filesScanned}`),j.push(` Endpoints: ${$.stats.endpointsFound}`),j.push(` Schemas: ${$.stats.schemasFound}`),j.push(""),j.push("\uD83D\uDCC8 Confidence"),j.push(` High: ${$.stats.highConfidence}`),j.push(` Medium: ${$.stats.mediumConfidence}`),j.push(` Low: ${$.stats.lowConfidence}`),j.push(""),j.push("\uD83D\uDD27 Frameworks");for(let Q of $.project.frameworks)j.push(` \u2022 ${Q.name}`);if(j.push(""),W)j.push("\u2705 Verification"),j.push(` Valid: ${W.summary.validEndpoints}`),j.push(` Warnings: ${W.summary.warningEndpoints}`),j.push(` Errors: ${W.summary.errorEndpoints}`),j.push("");return j.join(`
1743
- `)}async function rX($,W,j){let{logger:Q}=j,Z=[],B=[...$.ambiguities];Q.info(`Verifying ${$.endpoints.length} endpoints...`);for(let Y of $.endpoints){let q=[];if(Y.confidence.level==="low"||Y.confidence.level==="ambiguous")q.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${Y.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!Y.input&&(Y.method==="POST"||Y.method==="PUT"||Y.method==="PATCH"))q.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!Y.output)q.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(W.checkDuplicates){if($.endpoints.filter((V)=>V.id!==Y.id&&V.path===Y.path&&V.method===Y.method).length>0)q.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${Y.method} ${Y.path} found`,severity:"error"})}if(W.checkConflicts){let H=oX(Y,$.endpoints);for(let V of H)q.push({code:"PATH_CONFLICT",message:`Path may conflict with ${V.method} ${V.path}`,severity:"warning"})}let A=q.some((H)=>H.severity==="error")?"error":q.some((H)=>H.severity==="warning")?"warning":"valid";Z.push({endpoint:Y,status:A,issues:q})}if(W.validateSchemas){for(let Y of $.schemas)if(!Y.fields||Y.fields.length===0)B.push({type:"schema",itemId:Y.id,description:`Schema ${Y.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:Y.source})}let X={totalEndpoints:Z.length,validEndpoints:Z.filter((Y)=>Y.status==="valid").length,warningEndpoints:Z.filter((Y)=>Y.status==="warning").length,errorEndpoints:Z.filter((Y)=>Y.status==="error").length,totalIssues:Z.reduce((Y,q)=>Y+q.issues.length,0)};return Q.info(`Verification complete: ${X.validEndpoints} valid, ${X.warningEndpoints} warnings, ${X.errorEndpoints} errors`),{valid:X.errorEndpoints===0,endpointResults:Z,ambiguities:B,summary:X}}function oX($,W){let j=[],Q=$.path.split("/").filter(Boolean);for(let Z of W){if(Z.id===$.id)continue;if(Z.method!==$.method)continue;let B=Z.path.split("/").filter(Boolean);if(B.length!==Q.length)continue;let X=!0;for(let Y=0;Y<Q.length;Y++){let q=Q[Y]??"",A=B[Y]??"",H=q.startsWith(":")||q.startsWith("{"),V=A.startsWith(":")||A.startsWith("{");if(!H&&!V&&q!==A){X=!1;break}}if(X&&$.path!==Z.path)j.push(Z)}return j}function OL($,W="feature-map",j={}){switch(W){case"feature-map":return $j($,j);case"orphans":return pX($,j);case"dependencies":return iX($,j);case"full":return aX($,j);default:return $j($,j)}}function $j($,W){let{direction:j="LR",showVersions:Q=!0,maxNodes:Z=50}=W,B=[`flowchart ${j}`],X=$.features;if(W.featureKeys&&W.featureKeys.length>0)X=X.filter((G)=>W.featureKeys?.includes(G.key));let Y=0,q=!1;if(X.length>0){B.push(" subgraph features [Features]");for(let G of X){if(Y>=Z)break;let z=x(`F_${G.key}`),J=G.title??G.key;B.push(` ${z}["${s(J)}"]`),Y++}B.push(" end")}let A=s1(X,"operations",$.inventory);if(A.length>0&&Y<Z){B.push(" subgraph ops [Operations]");for(let G of A){if(Y>=Z)break;let z=x(`O_${G.key}_v${G.version}`),J=Q?`${G.key}.v${G.version}`:G.key;B.push(` ${z}["${s(J)}"]`),Y++}B.push(" end")}let H=s1(X,"events",$.inventory);if(H.length>0&&Y<Z){B.push(" subgraph events [Events]");for(let G of H){if(Y>=Z)break;let z=x(`E_${G.key}_v${G.version}`),J=Q?`${G.key}.v${G.version}`:G.key;B.push(` ${z}["${s(J)}"]`),Y++}B.push(" end")}let V=s1(X,"presentations",$.inventory);if(V.length>0&&Y<Z){B.push(" subgraph presentations [Presentations]");for(let G of V){if(Y>=Z)break;let z=x(`P_${G.key}_v${G.version}`),J=Q?`${G.key}.v${G.version}`:G.key;B.push(` ${z}["${s(J)}"]`),Y++}B.push(" end")}for(let G of X){let z=x(`F_${G.key}`);for(let J of G.operations){let K=x(`O_${J.key}_v${J.version}`);B.push(` ${z} --> ${K}`)}for(let J of G.events){let K=x(`E_${J.key}_v${J.version}`);B.push(` ${z} -.-> ${K}`)}for(let J of G.presentations){let K=x(`P_${J.key}_v${J.version}`);B.push(` ${z} --> ${K}`)}}if(q)B.push(` note["... and more (truncated at ${Z} nodes)"]`);return B.join(`
1744
- `)}function pX($,W){let{direction:j="TB",showVersions:Q=!0,maxNodes:Z=50}=W,B=[`flowchart ${j}`],X=new Set,Y=new Set,q=new Set;for(let V of $.features){for(let G of V.operations)X.add(`${G.key}.v${G.version}`);for(let G of V.events)Y.add(`${G.key}.v${G.version}`);for(let G of V.presentations)q.add(`${G.key}.v${G.version}`)}let A=0;if($.features.length>0){B.push(" subgraph features [Features]");for(let V of $.features){if(A>=Z)break;let G=x(`F_${V.key}`);B.push(` ${G}["${s(V.title??V.key)}"]`),A++}B.push(" end")}if($.orphanedSpecs.length>0){B.push(" subgraph orphaned [Orphaned Specs]");for(let V of $.orphanedSpecs){if(A>=Z)break;let G=x(`orphan_${V.type}_${V.key}_v${V.version}`),z=Q?`${V.key}.v${V.version}`:V.key;B.push(` ${G}["${s(z)}"]`),A++}B.push(" end")}let H=[];for(let V of X){let[G,z]=e1(V);if(G&&z)H.push({type:"operation",key:G,version:z})}for(let V of Y){let[G,z]=e1(V);if(G&&z)H.push({type:"event",key:G,version:z})}for(let V of q){let[G,z]=e1(V);if(G&&z)H.push({type:"presentation",key:G,version:z})}if(H.length>0&&A<Z){B.push(" subgraph linked [Linked Specs]");for(let V of H){if(A>=Z)break;let G=x(`${V.type}_${V.key}_v${V.version}`),z=Q?`${V.key}.v${V.version}`:V.key;B.push(` ${G}["${s(z)}"]`),A++}B.push(" end")}for(let V of $.features){let G=x(`F_${V.key}`);for(let z of V.operations){let J=x(`operation_${z.key}_v${z.version}`);B.push(` ${G} --> ${J}`)}for(let z of V.events){let J=x(`event_${z.key}_v${z.version}`);B.push(` ${G} -.-> ${J}`)}for(let z of V.presentations){let J=x(`presentation_${z.key}_v${z.version}`);B.push(` ${G} --> ${J}`)}}return B.join(`
1745
- `)}function iX($,W){let{direction:j="TB",showVersions:Q=!0,maxNodes:Z=50}=W,B=[`flowchart ${j}`],X=0;for(let Y of $.features){if(X>=Z)break;let q=x(`F_${Y.key}`);B.push(` ${q}["${s(Y.title??Y.key)}"]`),X++;for(let A of Y.operations){if(X>=Z)break;let H=x(`O_${A.key}_v${A.version}`),V=Q?`${A.key}.v${A.version}`:A.key;B.push(` ${H}["${s(V)}"]`),B.push(` ${q} --> ${H}`),X++}for(let A of Y.events){if(X>=Z)break;let H=x(`E_${A.key}_v${A.version}`),V=Q?`${A.key}.v${A.version}`:A.key;B.push(` ${H}["${s(V)}"]`),B.push(` ${q} -.-> ${H}`),X++}for(let A of Y.presentations){if(X>=Z)break;let H=x(`P_${A.key}_v${A.version}`),V=Q?`${A.key}.v${A.version}`:A.key;B.push(` ${H}["${s(V)}"]`),B.push(` ${q} --> ${H}`),X++}for(let A of Y.opToPresentationLinks){let H=x(`O_${A.op.key}_v${A.op.version}`),V=x(`P_${A.pres.key}_v${A.pres.version}`);B.push(` ${H} --> ${V}`)}}return B.join(`
1746
- `)}function aX($,W){let j=$j($,W);if($.orphanedSpecs.length===0)return j;let Q=j.split(`
1747
- `);Q.push(" subgraph orphaned [Orphaned Specs]");for(let Z of $.orphanedSpecs.slice(0,20)){let B=x(`orphan_${Z.type}_${Z.key}_v${Z.version}`),X=`${Z.key}.v${Z.version}`;Q.push(` ${B}["${s(X)}"]:::orphan`)}return Q.push(" end"),Q.push(" classDef orphan stroke-dasharray: 5 5"),Q.join(`
1748
- `)}function s1($,W,j){let Q=new Set,Z=[];for(let B of $)for(let X of B[W]){let Y=`${X.key}.v${X.version}`;if(!Q.has(Y))Q.add(Y),Z.push(X)}return Z}function e1($){let W=$.match(/^(.+)\.v(\d+)$/);if(!W)return[void 0,void 0];return[W[1],W[2]]}function x($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function s($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as tX,specToMarkdown as z$}from"@contractspec/module.workspace";function wL($,W,j){let Q=[];if(j.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(W))Q.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!W.includes($.meta.key))Q.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(j.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(W))Q.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(W))Q.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(W))Q.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return Q}function CL($,W){let j=[];j.push(`# Verification Report: ${$.meta.key}`),j.push("");let Q=W.filter((X)=>X.severity==="error"),Z=W.filter((X)=>X.severity==="warning"),B=W.filter((X)=>X.severity==="info");if(j.push("## Summary"),j.push(""),j.push(`- Errors: ${Q.length}`),j.push(`- Warnings: ${Z.length}`),j.push(`- Info: ${B.length}`),j.push(""),Q.length>0){j.push("## Errors"),j.push("");for(let X of Q)j.push(`- \u274C **${X.category}**: ${X.message}`);j.push("")}if(Z.length>0){j.push("## Warnings"),j.push("");for(let X of Z)j.push(`- \u26A0\uFE0F **${X.category}**: ${X.message}`);j.push("")}if(B.length>0){j.push("## Info"),j.push("");for(let X of B)j.push(`- \u2139\uFE0F **${X.category}**: ${X.message}`);j.push("")}return j.join(`
1749
- `)}async function NL($,W){let j=[];j.push(z$($,"context"));let Q=await h(W),Z=async(B)=>{let X=Q.find((q)=>q.key===B.name&&q.version===B.version);if(!X)return null;return(await tX(X.filePath)).find((q)=>q.meta.key===B.name)??null};if($.operations?.length){j.push(`
1980
+ `}function NY($,W,j={}){let A=[];if(A.push("# Import Report"),A.push(""),A.push(`**Generated**: ${new Date().toISOString()}`),A.push(""),A.push("## Summary"),A.push(""),A.push("| Metric | Count |"),A.push("|--------|-------|"),A.push(`| Files Scanned | ${$.stats.filesScanned} |`),A.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),A.push(`| Schemas Found | ${$.stats.schemasFound} |`),A.push(`| Errors Found | ${$.stats.errorsFound} |`),A.push(`| Events Found | ${$.stats.eventsFound} |`),A.push(""),j.includeStats!==!1)A.push("### Confidence"),A.push(""),A.push("| Level | Count |"),A.push("|-------|-------|"),A.push(`| High | ${$.stats.highConfidence} |`),A.push(`| Medium | ${$.stats.mediumConfidence} |`),A.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),A.push("");A.push("### Frameworks Detected"),A.push("");for(let Q of $.project.frameworks)A.push(`- **${Q.name}** (${Q.confidence})`);if(A.push(""),j.includeEndpoints!==!1&&$.endpoints.length>0){A.push("## Endpoints"),A.push(""),A.push("| Method | Path | Kind | Confidence |"),A.push("|--------|------|------|------------|");for(let Q of $.endpoints)A.push(`| ${Q.method} | \`${Q.path}\` | ${Q.kind} | ${Q.confidence.level} |`);A.push("")}if(j.includeSchemas!==!1&&$.schemas.length>0){A.push("## Schemas"),A.push(""),A.push("| Name | Type | Confidence |"),A.push("|------|------|------------|");for(let Q of $.schemas)A.push(`| ${Q.name} | ${Q.schemaType} | ${Q.confidence.level} |`);A.push("")}if(W&&j.includeIssues!==!1){A.push("## Verification"),A.push(""),A.push("| Status | Count |"),A.push("|--------|-------|"),A.push(`| Valid | ${W.summary.validEndpoints} |`),A.push(`| Warnings | ${W.summary.warningEndpoints} |`),A.push(`| Errors | ${W.summary.errorEndpoints} |`),A.push("");let Q=W.endpointResults.filter((Z)=>Z.issues.length>0);if(Q.length>0){A.push("### Issues"),A.push("");for(let Z of Q){A.push(`#### ${Z.endpoint.method} ${Z.endpoint.path}`);for(let X of Z.issues){let Y=X.severity==="error"?"\u274C":X.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(A.push(`- ${Y} **${X.code}**: ${X.message}`),X.suggestion)A.push(` - *Suggestion*: ${X.suggestion}`)}A.push("")}}}if(j.includeAmbiguities!==!1&&$.ambiguities.length>0){A.push("## Ambiguities (Require Review)"),A.push("");for(let Q of $.ambiguities)if(A.push(`- **${Q.type}** (${Q.itemId}): ${Q.description}`),Q.suggestion)A.push(` - *Suggestion*: ${Q.suggestion}`);A.push("")}return A.push("## Next Steps"),A.push(""),A.push("1. Review generated contracts in the output directory"),A.push("2. Fill in TODO placeholders with business context"),A.push("3. Run `contractspec validate` to verify contracts"),A.push("4. Move stable contracts from `generated/` to `curated/`"),A.push(""),A.join(`
1981
+ `)}function RY($,W){let j=[];j.push(""),j.push("\uD83D\uDCCA Summary"),j.push(` Files scanned: ${$.stats.filesScanned}`),j.push(` Endpoints: ${$.stats.endpointsFound}`),j.push(` Schemas: ${$.stats.schemasFound}`),j.push(""),j.push("\uD83D\uDCC8 Confidence"),j.push(` High: ${$.stats.highConfidence}`),j.push(` Medium: ${$.stats.mediumConfidence}`),j.push(` Low: ${$.stats.lowConfidence}`),j.push(""),j.push("\uD83D\uDD27 Frameworks");for(let A of $.project.frameworks)j.push(` \u2022 ${A.name}`);if(j.push(""),W)j.push("\u2705 Verification"),j.push(` Valid: ${W.summary.validEndpoints}`),j.push(` Warnings: ${W.summary.warningEndpoints}`),j.push(` Errors: ${W.summary.errorEndpoints}`),j.push("");return j.join(`
1982
+ `)}async function CY($,W,j){let{logger:A}=j,Q=[],Z=[...$.ambiguities];A.info(`Verifying ${$.endpoints.length} endpoints...`);for(let Y of $.endpoints){let B=[];if(Y.confidence.level==="low"||Y.confidence.level==="ambiguous")B.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${Y.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!Y.input&&(Y.method==="POST"||Y.method==="PUT"||Y.method==="PATCH"))B.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!Y.output)B.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(W.checkDuplicates){if($.endpoints.filter((V)=>V.id!==Y.id&&V.path===Y.path&&V.method===Y.method).length>0)B.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${Y.method} ${Y.path} found`,severity:"error"})}if(W.checkConflicts){let H=DY(Y,$.endpoints);for(let V of H)B.push({code:"PATH_CONFLICT",message:`Path may conflict with ${V.method} ${V.path}`,severity:"warning"})}let q=B.some((H)=>H.severity==="error")?"error":B.some((H)=>H.severity==="warning")?"warning":"valid";Q.push({endpoint:Y,status:q,issues:B})}if(W.validateSchemas){for(let Y of $.schemas)if(!Y.fields||Y.fields.length===0)Z.push({type:"schema",itemId:Y.id,description:`Schema ${Y.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:Y.source})}let X={totalEndpoints:Q.length,validEndpoints:Q.filter((Y)=>Y.status==="valid").length,warningEndpoints:Q.filter((Y)=>Y.status==="warning").length,errorEndpoints:Q.filter((Y)=>Y.status==="error").length,totalIssues:Q.reduce((Y,B)=>Y+B.issues.length,0)};return A.info(`Verification complete: ${X.validEndpoints} valid, ${X.warningEndpoints} warnings, ${X.errorEndpoints} errors`),{valid:X.errorEndpoints===0,endpointResults:Q,ambiguities:Z,summary:X}}function DY($,W){let j=[],A=$.path.split("/").filter(Boolean);for(let Q of W){if(Q.id===$.id)continue;if(Q.method!==$.method)continue;let Z=Q.path.split("/").filter(Boolean);if(Z.length!==A.length)continue;let X=!0;for(let Y=0;Y<A.length;Y++){let B=A[Y]??"",q=Z[Y]??"",H=B.startsWith(":")||B.startsWith("{"),V=q.startsWith(":")||q.startsWith("{");if(!H&&!V&&B!==q){X=!1;break}}if(X&&$.path!==Q.path)j.push(Q)}return j}function _O($,W="feature-map",j={}){switch(W){case"feature-map":return Tj($,j);case"orphans":return TY($,j);case"dependencies":return FY($,j);case"full":return xY($,j);default:return Tj($,j)}}function Tj($,W){let{direction:j="LR",showVersions:A=!0,maxNodes:Q=50}=W,Z=[`flowchart ${j}`],X=$.features;if(W.featureKeys&&W.featureKeys.length>0)X=X.filter((G)=>W.featureKeys?.includes(G.key));let Y=0,B=!1;if(X.length>0){Z.push(" subgraph features [Features]");for(let G of X){if(Y>=Q)break;let J=y(`F_${G.key}`),b=G.title??G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}let q=Cj(X,"operations",$.inventory);if(q.length>0&&Y<Q){Z.push(" subgraph ops [Operations]");for(let G of q){if(Y>=Q)break;let J=y(`O_${G.key}_v${G.version}`),b=A?`${G.key}.v${G.version}`:G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}let H=Cj(X,"events",$.inventory);if(H.length>0&&Y<Q){Z.push(" subgraph events [Events]");for(let G of H){if(Y>=Q)break;let J=y(`E_${G.key}_v${G.version}`),b=A?`${G.key}.v${G.version}`:G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}let V=Cj(X,"presentations",$.inventory);if(V.length>0&&Y<Q){Z.push(" subgraph presentations [Presentations]");for(let G of V){if(Y>=Q)break;let J=y(`P_${G.key}_v${G.version}`),b=A?`${G.key}.v${G.version}`:G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}for(let G of X){let J=y(`F_${G.key}`);for(let b of G.operations){let w=y(`O_${b.key}_v${b.version}`);Z.push(` ${J} --> ${w}`)}for(let b of G.events){let w=y(`E_${b.key}_v${b.version}`);Z.push(` ${J} -.-> ${w}`)}for(let b of G.presentations){let w=y(`P_${b.key}_v${b.version}`);Z.push(` ${J} --> ${w}`)}}if(B)Z.push(` note["... and more (truncated at ${Q} nodes)"]`);return Z.join(`
1983
+ `)}function TY($,W){let{direction:j="TB",showVersions:A=!0,maxNodes:Q=50}=W,Z=[`flowchart ${j}`],X=new Set,Y=new Set,B=new Set;for(let V of $.features){for(let G of V.operations)X.add(`${G.key}.v${G.version}`);for(let G of V.events)Y.add(`${G.key}.v${G.version}`);for(let G of V.presentations)B.add(`${G.key}.v${G.version}`)}let q=0;if($.features.length>0){Z.push(" subgraph features [Features]");for(let V of $.features){if(q>=Q)break;let G=y(`F_${V.key}`);Z.push(` ${G}["${W$(V.title??V.key)}"]`),q++}Z.push(" end")}if($.orphanedSpecs.length>0){Z.push(" subgraph orphaned [Orphaned Specs]");for(let V of $.orphanedSpecs){if(q>=Q)break;let G=y(`orphan_${V.type}_${V.key}_v${V.version}`),J=A?`${V.key}.v${V.version}`:V.key;Z.push(` ${G}["${W$(J)}"]`),q++}Z.push(" end")}let H=[];for(let V of X){let[G,J]=Dj(V);if(G&&J)H.push({type:"operation",key:G,version:J})}for(let V of Y){let[G,J]=Dj(V);if(G&&J)H.push({type:"event",key:G,version:J})}for(let V of B){let[G,J]=Dj(V);if(G&&J)H.push({type:"presentation",key:G,version:J})}if(H.length>0&&q<Q){Z.push(" subgraph linked [Linked Specs]");for(let V of H){if(q>=Q)break;let G=y(`${V.type}_${V.key}_v${V.version}`),J=A?`${V.key}.v${V.version}`:V.key;Z.push(` ${G}["${W$(J)}"]`),q++}Z.push(" end")}for(let V of $.features){let G=y(`F_${V.key}`);for(let J of V.operations){let b=y(`operation_${J.key}_v${J.version}`);Z.push(` ${G} --> ${b}`)}for(let J of V.events){let b=y(`event_${J.key}_v${J.version}`);Z.push(` ${G} -.-> ${b}`)}for(let J of V.presentations){let b=y(`presentation_${J.key}_v${J.version}`);Z.push(` ${G} --> ${b}`)}}return Z.join(`
1984
+ `)}function FY($,W){let{direction:j="TB",showVersions:A=!0,maxNodes:Q=50}=W,Z=[`flowchart ${j}`],X=0;for(let Y of $.features){if(X>=Q)break;let B=y(`F_${Y.key}`);Z.push(` ${B}["${W$(Y.title??Y.key)}"]`),X++;for(let q of Y.operations){if(X>=Q)break;let H=y(`O_${q.key}_v${q.version}`),V=A?`${q.key}.v${q.version}`:q.key;Z.push(` ${H}["${W$(V)}"]`),Z.push(` ${B} --> ${H}`),X++}for(let q of Y.events){if(X>=Q)break;let H=y(`E_${q.key}_v${q.version}`),V=A?`${q.key}.v${q.version}`:q.key;Z.push(` ${H}["${W$(V)}"]`),Z.push(` ${B} -.-> ${H}`),X++}for(let q of Y.presentations){if(X>=Q)break;let H=y(`P_${q.key}_v${q.version}`),V=A?`${q.key}.v${q.version}`:q.key;Z.push(` ${H}["${W$(V)}"]`),Z.push(` ${B} --> ${H}`),X++}for(let q of Y.opToPresentationLinks){let H=y(`O_${q.op.key}_v${q.op.version}`),V=y(`P_${q.pres.key}_v${q.pres.version}`);Z.push(` ${H} --> ${V}`)}}return Z.join(`
1985
+ `)}function xY($,W){let j=Tj($,W);if($.orphanedSpecs.length===0)return j;let A=j.split(`
1986
+ `);A.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs.slice(0,20)){let Z=y(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=`${Q.key}.v${Q.version}`;A.push(` ${Z}["${W$(X)}"]:::orphan`)}return A.push(" end"),A.push(" classDef orphan stroke-dasharray: 5 5"),A.join(`
1987
+ `)}function Cj($,W,j){let A=new Set,Q=[];for(let Z of $)for(let X of Z[W]){let Y=`${X.key}.v${X.version}`;if(!A.has(Y))A.add(Y),Q.push(X)}return Q}function Dj($){let W=$.match(/^(.+)\.v(\d+)$/);if(!W)return[void 0,void 0];return[W[1],W[2]]}function y($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function W$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as yY,specToMarkdown as z$}from"@contractspec/module.workspace";function UO($,W,j){let A=[];if(j.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(W))A.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!W.includes($.meta.key))A.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(j.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(W))A.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(W))A.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(W))A.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return A}function LO($,W){let j=[];j.push(`# Verification Report: ${$.meta.key}`),j.push("");let A=W.filter((X)=>X.severity==="error"),Q=W.filter((X)=>X.severity==="warning"),Z=W.filter((X)=>X.severity==="info");if(j.push("## Summary"),j.push(""),j.push(`- Errors: ${A.length}`),j.push(`- Warnings: ${Q.length}`),j.push(`- Info: ${Z.length}`),j.push(""),A.length>0){j.push("## Errors"),j.push("");for(let X of A)j.push(`- \u274C **${X.category}**: ${X.message}`);j.push("")}if(Q.length>0){j.push("## Warnings"),j.push("");for(let X of Q)j.push(`- \u26A0\uFE0F **${X.category}**: ${X.message}`);j.push("")}if(Z.length>0){j.push("## Info"),j.push("");for(let X of Z)j.push(`- \u2139\uFE0F **${X.category}**: ${X.message}`);j.push("")}return j.join(`
1988
+ `)}async function MO($,W){let j=[];j.push(z$($,"context"));let A=await $$(W),Q=async(Z)=>{let X=A.find((B)=>B.key===Z.name&&B.version===Z.version);if(!X)return null;return(await yY(X.filePath)).find((B)=>B.meta.key===Z.name)??null};if($.operations?.length){j.push(`
1750
1989
  ## Operations (${$.operations.length})
1751
- `);for(let B of $.operations){let X=await Z(B);if(X)j.push(z$(X,"full"));else j.push(`### ${B.name} (v${B.version})
1990
+ `);for(let Z of $.operations){let X=await Q(Z);if(X)j.push(z$(X,"full"));else j.push(`### ${Z.name} (v${Z.version})
1752
1991
 
1753
1992
  *Spec not found*`);j.push("---")}}if($.events?.length){j.push(`
1754
1993
  ## Events (${$.events.length})
1755
- `);for(let B of $.events){let X=await Z(B);if(X)j.push(z$(X,"full"));else j.push(`### ${B.name} (v${B.version})
1994
+ `);for(let Z of $.events){let X=await Q(Z);if(X)j.push(z$(X,"full"));else j.push(`### ${Z.name} (v${Z.version})
1756
1995
 
1757
1996
  *Spec not found*`);j.push("---")}}if($.presentations?.length){j.push(`
1758
1997
  ## Presentations (${$.presentations.length})
1759
- `);for(let B of $.presentations){let X=await Z(B);if(X)j.push(z$(X,"full"));else j.push(`### ${B.name} (v${B.version})
1998
+ `);for(let Z of $.presentations){let X=await Q(Z);if(X)j.push(z$(X,"full"));else j.push(`### ${Z.name} (v${Z.version})
1760
1999
 
1761
2000
  *Spec not found*`);j.push("---")}}return j.join(`
1762
- `)}function sX($,W){let j=[];if(j.push(`# Implementation Guide: ${$.meta.key}`),j.push(""),j.push(`**Target Agent**: ${W}`),j.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),j.push(""),$.meta.description)j.push("## Overview"),j.push(""),j.push($.meta.description),j.push("");if($.meta.goal)j.push("## Goal"),j.push(""),j.push($.meta.goal),j.push("");if($.meta.context)j.push("## Context"),j.push(""),j.push($.meta.context),j.push("");if(j.push("## Implementation Steps"),j.push(""),$.specType==="operation"){if(j.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)j.push("2. Implement input validation according to the schema"),j.push("3. Implement the core business logic"),j.push("4. Return output matching the expected schema");if($.hasPolicy)j.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){j.push("6. Emit events on success:");for(let Q of $.emittedEvents)j.push(` - \`${Q.name}\` (v${Q.version})`)}j.push("7. Add error handling for expected failure cases"),j.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(j.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){j.push("2. Implement operations:");for(let Q of $.operations)j.push(` - \`${Q.name}\` (v${Q.version})`)}if($.presentations&&$.presentations.length>0){j.push("3. Implement presentations:");for(let Q of $.presentations)j.push(` - \`${Q.name}\` (v${Q.version})`)}j.push("4. Wire up feature exports"),j.push("5. Add integration tests")}else j.push("1. Review the spec requirements"),j.push("2. Implement the core logic"),j.push("3. Add tests"),j.push("4. Document the implementation");if(j.push(""),j.push("## Constraints"),j.push(""),j.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)j.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)j.push(`- Tags: ${$.meta.tags.join(", ")}`);if(j.push(""),W==="cursor-cli")j.push("## Cursor Notes"),j.push(""),j.push("- Use Composer mode for multi-file changes"),j.push("- Reference this guide in your cursor rules"),j.push("- Break implementation into small, focused commits");else if(W==="claude-code")j.push("## Claude Code Notes"),j.push(""),j.push("- Use extended thinking for complex logic"),j.push("- Ask for clarification on ambiguous requirements"),j.push("- Provide step-by-step reasoning");else if(W==="generic-mcp")j.push("## General Notes"),j.push(""),j.push("- Use inline comments to guide generation"),j.push("- Review generated code carefully");return j.push(""),j.push("## Spec Definition"),j.push(""),j.push(z$($,"full")),j.join(`
1763
- `)}function eX($){let W=[];if(W.push(`# ${$.meta.key}`),W.push(""),W.push(`Description: ${$.meta.description??"No description"}`),W.push(""),W.push("## Rules"),W.push(""),$.specType==="operation"){if(W.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)W.push("- Validate input and output against schemas");if($.hasPolicy)W.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)W.push("- Emit documented events")}else if($.specType==="feature")W.push("- Implement all operations and presentations"),W.push("- Follow modular architecture");else W.push(`- Follow ${$.specType} patterns`);return W.push("- Follow project code quality standards"),W.push("- Write tests for new functionality"),W.join(`
1764
- `)}function RL($,W,j="generic-mcp"){switch(W){case"guide":return sX($,j);case"rules":return eX($);case"prompt":return z$($,"prompt");case"context":return z$($,"context");case"full":default:return z$($,"full")}}var $Q=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],$Y=[...$Q,{name:"@contractspec/lib.schema",description:"Extended schema utilities and common types"},{name:"@contractspec/app.cli-contractspec",dev:!0,description:"ContractSpec CLI for validation, scaffolding, and code generation"},{name:"typescript",dev:!0,description:"TypeScript compiler for type checking"}];function Wj($){return $==="minimal"?$Q:$Y}function jj($){return $.filter((W)=>!W.dev)}function Qj($){return $.filter((W)=>W.dev)}import{exec as WY}from"child_process";import{promisify as jY}from"util";var QY=jY(WY),ZY={confirm:async()=>!0,select:async($,W)=>W[0]?.value??""};async function mL($,W,j=ZY){let Q=Wj(W.mode),Z=jj(Q),B=Qj(Q),X=[],Y=[],q=[],A=$.join(W.workspaceRoot,"package.json");if(!await $.exists(A))return{success:!1,installed:[],skipped:[],errors:[{name:"package.json",action:"error",message:"No package.json found. Run `npm init` first."}],summary:"No package.json found in workspace root."};let V=await $.readFile(A),G=JSON.parse(V),z=new Set([...Object.keys(G.dependencies??{}),...Object.keys(G.devDependencies??{})]),J=F$(W.workspaceRoot),K=Z.filter((L)=>{if(z.has(L.name)&&!W.force)return Y.push({name:L.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),_=B.filter((L)=>{if(z.has(L.name)&&!W.force)return Y.push({name:L.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(W.dryRun){let L=[...K,..._];return{success:!0,installed:L.map((I)=>({name:I.name,action:"installed",message:`Would install: ${I.description}`,dev:I.dev})),skipped:Y,errors:[],summary:`Dry run: would install ${L.length} package(s), skip ${Y.length}.`}}if(!W.skipPrompts&&(K.length>0||_.length>0)){let L=K.length+_.length;if(!await j.confirm(`Install ${L} package(s) using ${J}?`))return{success:!0,installed:[],skipped:[...Y,...K.map((U)=>({name:U.name,action:"skipped",message:"User cancelled"})),..._.map((U)=>({name:U.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(K.length>0){let L=await WQ(K,J,W.workspaceRoot,!1);for(let I of L)if(I.action==="installed")X.push(I);else q.push(I)}if(_.length>0){let L=await WQ(_,J,W.workspaceRoot,!0);for(let I of L)if(I.action==="installed")X.push(I);else q.push(I)}let w=q.length===0,b=w?`Successfully installed ${X.length} package(s), skipped ${Y.length}.`:`Installed ${X.length}, skipped ${Y.length}, failed ${q.length}.`;return{success:w,installed:X,skipped:Y,errors:q,summary:b}}async function WQ($,W,j,Q){let Z=[],B=$.map((X)=>X.version?`${X.name}@${X.version}`:X.name);try{let Y=`${aj(W,Q)} ${B.join(" ")}`;await QY(Y,{cwd:j,timeout:120000});for(let q of $)Z.push({name:q.name,action:"installed",message:q.description,dev:Q})}catch(X){let Y=X instanceof Error?X.message:String(X);for(let q of $)Z.push({name:q.name,action:"error",message:`Failed to install: ${Y}`,dev:Q})}return Z}async function kL($,W){let j=$.join(W,"package.json");try{let Q=await $.readFile(j),Z=JSON.parse(Q);return"@contractspec/lib.contracts-spec"in{...Z.dependencies,...Z.devDependencies}}catch{return!1}}function gL($){let W=Wj($),j=[];j.push(`ContractSpec ${$} installation:`),j.push("");let Q=jj(W);if(Q.length>0){j.push("Dependencies:");for(let B of Q)j.push(` \u2022 ${B.name} - ${B.description}`)}let Z=Qj(W);if(Z.length>0){j.push(""),j.push("Dev Dependencies:");for(let B of Z)j.push(` \u2022 ${B.name} - ${B.description}`)}return j.join(`
1765
- `)}import{RegeneratorService as BY}from"@contractspec/lib.contracts-spec/regenerator";function lL($){return new BY({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class qW{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let W=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,j;try{j=await fetch(W,{method:"GET",headers:{Accept:"application/json"}})}catch(Q){throw Error(`Registry request failed: ${W} (${Q instanceof Error?Q.message:String(Q)})`)}if(!j.ok){let Q=await j.text().catch(()=>"");throw Error(`Registry request failed: ${j.status} ${j.statusText} ${Q}`)}return await j.json()}}function Zj($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function oL($,W,j){let{logger:Q}=j,Z=Zj(W.registryUrl);Q.info(`Adding spec to registry: ${$}`,{registryUrl:Z}),await new qW({registryUrl:Z}).getJson(`/specs/add?path=${encodeURIComponent($)}`),Q.info("Spec added to registry successfully")}async function pL($,W){let{logger:j}=W,Q=Zj($.registryUrl);j.info("Listing specs from registry",{registryUrl:Q});let Z=new qW({registryUrl:Q}),B=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",X=await Z.getJson(`/specs${B}`);return j.info(`Found ${X.length} specs`),X}async function iL($,W,j){let{logger:Q}=j,Z=Zj(W.registryUrl);Q.info(`Searching registry: ${$}`,{registryUrl:Z});let X=await new qW({registryUrl:Z}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return Q.info(`Found ${X.length} results`),X}class XY{fs;logger;constructor($,W){this.fs=$;this.logger=W}async sync($){let{config:W,cwd:j}=$,Q=$.targets??W.targets??[];if(!W.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${Q.join(", ")}...`);try{let Z=this.fs.join(j,W.rulesDir??".rules");if(!await this.fs.exists(Z))return{success:!1,files:[],errors:[`Rules directory not found: ${Z}`]};let X=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${X}`);let Y=[];for(let q of Q){let A=this.getTargetFileName(q);if(A){let H=this.fs.join(j,A);Y.push(H)}}return{success:!0,files:Y,logs:[`Successfully synchronized rules to ${Y.length} targets.`]}}catch(Z){let B=Z instanceof Error?Z.message:String(Z);return this.logger.error(`Rule synchronization failed: ${B}`),{success:!1,files:[],errors:[B]}}}async generateConfig($){let{config:W}=$,j={rules:(W.rules??[]).map((Q)=>this.fs.join(W.rulesDir??".rules",Q)),targets:$.targets||W.targets};return JSON.stringify(j,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}async function Bj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,"AGENTS.md");try{let B=await $.exists(Z),X=L5(W);if(B)if(W.interactive){if(!await j.confirm(`${Z} exists. Overwrite with the latest ContractSpec guide?`))return{target:"agents-md",filePath:Z,action:"skipped",message:"User kept existing AGENTS guide"}}else return{target:"agents-md",filePath:Z,action:"skipped",message:"File already exists"};return await $.writeFile(Z,X),{target:"agents-md",filePath:Z,action:B?"merged":"created",message:B?"Updated AI agent guide":"Created AI agent guide"}}catch(B){return{target:"agents-md",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}import{generateArtifactsForAudience as YY,generateBiomePreset as qY}from"@contractspec/biome-config";async function Xj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,"biome.jsonc"),B=$.join(Q,".contractspec","biome"),X=$.join(B,"plugins"),Y=$.join(B,"ai"),q=YY("consumer");try{let A=await $.exists(Z);if(A&&W.interactive){if(!await j.confirm(`${Z} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Z,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Z,qY("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(q.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),q.aiRules),{target:"biome-config",filePath:Z,action:A?"merged":"created",message:A?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(A){return{target:"biome-config",filePath:Z,action:"error",message:A instanceof Error?A.message:"Unknown error"}}}async function Yj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,".contractsrc.json");try{let B=await $.exists(Z),X=x$(W);if(B){let Y=await $.readFile(Z),q=j$(Y);if(!q)return{target:"cli-config",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Z,action:"skipped",message:"User skipped merge"}}let A=r(q,X);return await $.writeFile(Z,D(A)),{target:"cli-config",filePath:Z,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Z,D(X)),{target:"cli-config",filePath:Z,action:"created",message:"Created CLI configuration"}}catch(B){return{target:"cli-config",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function qj($,W,j){let Q=$.join(W.workspaceRoot,".cursor","rules"),Z=$.join(Q,"contractspec.mdc");try{let B=$.join(W.workspaceRoot,".cursor");if(!await $.exists(B))await $.mkdir(B);if(!await $.exists(Q))await $.mkdir(Q);let X=await $.exists(Z),Y=_5(W);if(X)if(W.interactive){if(!await j.confirm(`${Z} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Z,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Z,action:"skipped",message:"File already exists"};return await $.writeFile(Z,Y),{target:"cursor-rules",filePath:Z,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(B){return{target:"cursor-rules",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function Aj($,W,j){let Q=P0();try{let Z=await $.exists(Q),B=U5();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${Q}?`))return{target:"mcp-claude",filePath:Q,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Z){let q=await $.readFile(Q),A=j$(q);if(!A)return{target:"mcp-claude",filePath:Q,action:"error",message:"Existing file is not valid JSON"};let H=r(A,B);return await $.writeFile(Q,D(H)),{target:"mcp-claude",filePath:Q,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=Q.substring(0,Q.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(Q,D(B)),{target:"mcp-claude",filePath:Q,action:"created",message:"Created Claude Desktop configuration"}}catch(Z){return{target:"mcp-claude",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function Hj($,W,j){let Q=$.join(W.workspaceRoot,".cursor"),Z=$.join(Q,"mcp.json");try{if(!await $.exists(Q))await $.mkdir(Q);let X=await $.exists(Z),Y=o$();if(X){let q=await $.readFile(Z),A=j$(q);if(!A)return{target:"mcp-cursor",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Z,action:"skipped",message:"User skipped merge"}}let H=r(A,Y);return await $.writeFile(Z,D(H)),{target:"mcp-cursor",filePath:Z,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Z,D(Y)),{target:"mcp-cursor",filePath:Z,action:"created",message:"Created Cursor MCP configuration"}}catch(B){return{target:"mcp-cursor",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function Vj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,".vscode"),B=$.join(Z,"settings.json");try{if(!await $.exists(Z))await $.mkdir(Z);let Y=await $.exists(B),q=K5();if(Y){let A=await $.readFile(B),H=j$(A);if(!H)return{target:"vscode-settings",filePath:B,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${B} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:B,action:"skipped",message:"User skipped merge"}}let V=r(H,q);return await $.writeFile(B,D(V)),{target:"vscode-settings",filePath:B,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(B,D(q)),{target:"vscode-settings",filePath:B,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:B,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var Gj=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md"],jQ={"cli-config":"CLI Configuration (.contractsrc.json)","biome-config":"Biome Configuration (biome.jsonc + plugins)","vscode-settings":"VS Code Settings (.vscode/settings.json)","mcp-cursor":"MCP for Cursor (.cursor/mcp.json)","mcp-claude":"MCP for Claude Desktop","cursor-rules":"Cursor AI Rules (.cursor/rules/)","agents-md":"AI Agent Guide (AGENTS.md)"};var AY={confirm:async()=>!0,multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function RI($,W,j=AY){let Q=[],Z=W.targets.length>0?W.targets:Gj,B=W.workspaceRoot,X=R(B),Y=W.packageRoot??k(B),q=W.isMonorepo??c$(X),A=W.packageName??(q?L$(Y):void 0),H=W.scope??"workspace",V=Y!==X;if(q&&W.interactive&&V)H=(await j.multiSelect("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${A??Y})`,selected:!0},{value:"workspace",label:`Workspace level (${X})`}]))[0]??"package";let G=Z;if(W.interactive)G=await j.multiSelect("Select components to configure:",Gj.map((b)=>({value:b,label:jQ[b],selected:Z.includes(b)})));let z=W.projectName;if(W.interactive&&!z){let b=H==="package"&&A?A:B.split("/").pop()??"my-project";z=await j.input("Project name:",b)}let J={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:q,scope:H,packageName:A,projectName:z,targets:G};for(let b of G){let L=await HY($,b,J,j);Q.push(L)}let K=Q.filter((b)=>b.action!=="error").length,_=Q.filter((b)=>b.action==="error").length,w=q?` (${H} level)`:"";return{success:_===0,files:Q,summary:`Setup complete${w}: ${K} configured, ${_} failed.`}}async function HY($,W,j,Q){switch(W){case"agents-md":return Bj($,j,Q);case"cli-config":return Yj($,j,Q);case"biome-config":return Xj($,j,Q);case"vscode-settings":return Vj($,j,Q);case"mcp-cursor":return Hj($,j,Q);case"mcp-claude":return Aj($,j,Q);case"cursor-rules":return qj($,j,Q);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}import{validateBlueprint as VY}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as GY}from"path";import{pathToFileURL as zY}from"url";async function gI($,W){let{fs:j}=W,Q=GY(process.cwd(),$);if(!await j.exists(Q))return{valid:!1,errors:[`Blueprint file not found: ${Q}`]};try{let Z=await JY(Q),B=KY(Z),X=VY(B);return{spec:B,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Z){return{valid:!1,errors:[Z instanceof Error?Z.message:String(Z)]}}}async function JY($){try{return await import(zY($).href)}catch(W){throw Error(`Failed to load module at ${$}: ${W}`)}}function KY($){let W=Object.values($).filter(UY);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function UY($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as _Y,dirname as zj,join as V0}from"path";async function dI($,W,j,Q,Z){let{fs:B}=Z,X=Q.implementationPath;if(!X){let H=zj($),V=_Y($,".ts"),G=[V0(H,V.replace(".contracts",".handler")+".ts"),V0(H,V.replace(".presentation","")+".tsx"),V0(H,V.replace(".form",".form")+".tsx"),V0(zj(H),"handlers",V.replace(".contracts",".handler")+".ts"),V0(zj(H),"components",V.replace(".presentation","")+".tsx")];for(let z of G)if(await B.exists(z)){X=z;break}}if(!X||!await B.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await B.readFile(X),A=await new w0(j).validate(W,Y);return{success:A.success,errors:A.errors||[],warnings:A.warnings||[],suggestions:A.suggestions||[],report:A.code}}import{validateSpecStructure as LY}from"@contractspec/module.workspace";async function R$($,W,j={}){let{fs:Q}=W;if(!await Q.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let B=await Q.readFile($),X=[],Y=[],q;if(!j.skipStructure){let A=await h(W,{pattern:$});for(let H of A)q=LY(H),X.push(...q.errors),Y.push(...q.warnings)}return{valid:X.length===0,structureResult:q,errors:X,warnings:Y,code:B}}async function rI($,W,j={}){let Q=new Map;for(let Z of $){let B=await R$(Z,W,j);Q.set(Z,B)}return Q}import{validateConfig as IY}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as Kj}from"fs/promises";import{resolve as AW}from"path";import{pathToFileURL as OY}from"url";async function sI($,W,j,Q){let{fs:Z}=Q,B=AW(process.cwd(),W);if(!await Z.exists(B))return{valid:!1,errors:[`Tenant config file not found: ${B}`]};try{let X=await bY(B),Y=await wY(j.connections,Z),q=await CY(j.translationCatalog,Z),A=await SY(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(q)H.translationCatalogs={blueprint:[q],platform:[]};if(A)H.integrationSpecs=A;let V=IY($,X,H);return{config:X,report:V,valid:V.valid,errors:V.errors.map((G)=>`[${G.code}] ${G.path}: ${G.message}`)}}catch(X){return{valid:!1,errors:[X instanceof Error?X.message:String(X)]}}}async function bY($){if($.endsWith(".json")){let Q=await Kj($,"utf-8"),Z=JSON.parse(Q);if(!QQ(Z))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Z}let W=await HW($),j=Object.values(W).filter(QQ);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function QQ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}async function HW($){try{return await import(OY($).href)}catch(W){throw Error(`Failed to load module at ${$}: ${W}`)}}function YQ($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function wY($,W){let j=YQ($);if(!j.length)return[];let Q=[];for(let Z of j){let B=AW(process.cwd(),Z);if(!await W.exists(B)){console.warn(`Warning: Connection file not found: ${B}`);continue}if(B.endsWith(".json")){let Y=await Kj(B,"utf-8"),q=JSON.parse(Y);Q.push(...Jj(q));continue}let X=await HW(B);Q.push(...Jj(X))}return Q}function Jj($){if(Array.isArray($)){let W=$.filter(ZQ);if(W.length)return W}if(ZQ($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((Q)=>Jj(Q));if(j.length)return j}return[]}function ZQ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function CY($,W){if(!$)return;let j=AW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let B=await Kj(j,"utf-8"),X=JSON.parse(B);if(BQ(X))return XQ(X);return}let Q=await HW(j),Z=Object.values(Q).filter(BQ);if(Z.length===0)return;return XQ(Z[0])}function BQ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function XQ($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function SY($){let W=YQ($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),Q=new j;for(let Z of W){let{modulePath:B,exportName:X}=EY(Z);if(!B)continue;let Y=AW(process.cwd(),B);try{let q=await HW(Y),A=MY(q,X);if(A)await A(Q)}catch(q){console.warn(`Failed to load registrar from ${Y}: ${q}`)}}return Q}function EY($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),Q=W?.trim()??null,Z=j?.trim();return{modulePath:Q,exportName:Z}}function MY($,W){if(W){let j=$[W];if(typeof j==="function")return j;return}if(typeof $.default==="function")return $.default;for(let j of Object.values($))if(typeof j==="function")return j;return}async function qO($,W,j={},Q){let{fs:Z,logger:B}=$,X=await Z.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],q=[],A=Q?.validate??((V)=>R$(V,{fs:Z,logger:B})),H=Q?.build??((V,G)=>x0(V,{fs:Z,logger:B},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let z={specPath:V,outputDir:G};if(j.validate)try{z.validation=await A(V)}catch(J){z.error={phase:"validate",message:J instanceof Error?J.message:String(J)},q.push(z);continue}if(!j.dryRun)try{z.build=await H(V,G)}catch(J){z.error={phase:"build",message:J instanceof Error?J.message:String(J)},q.push(z);continue}else B.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});q.push(z)}return{specs:X,runs:q}}import{generateText as NY}from"ai";var RY=`
2001
+ `)}function vY($,W){let j=[];if(j.push(`# Implementation Guide: ${$.meta.key}`),j.push(""),j.push(`**Target Agent**: ${W}`),j.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),j.push(""),$.meta.description)j.push("## Overview"),j.push(""),j.push($.meta.description),j.push("");if($.meta.goal)j.push("## Goal"),j.push(""),j.push($.meta.goal),j.push("");if($.meta.context)j.push("## Context"),j.push(""),j.push($.meta.context),j.push("");if(j.push("## Implementation Steps"),j.push(""),$.specType==="operation"){if(j.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)j.push("2. Implement input validation according to the schema"),j.push("3. Implement the core business logic"),j.push("4. Return output matching the expected schema");if($.hasPolicy)j.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){j.push("6. Emit events on success:");for(let A of $.emittedEvents)j.push(` - \`${A.name}\` (v${A.version})`)}j.push("7. Add error handling for expected failure cases"),j.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(j.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){j.push("2. Implement operations:");for(let A of $.operations)j.push(` - \`${A.name}\` (v${A.version})`)}if($.presentations&&$.presentations.length>0){j.push("3. Implement presentations:");for(let A of $.presentations)j.push(` - \`${A.name}\` (v${A.version})`)}j.push("4. Wire up feature exports"),j.push("5. Add integration tests")}else j.push("1. Review the spec requirements"),j.push("2. Implement the core logic"),j.push("3. Add tests"),j.push("4. Document the implementation");if(j.push(""),j.push("## Constraints"),j.push(""),j.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)j.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)j.push(`- Tags: ${$.meta.tags.join(", ")}`);if(j.push(""),W==="cursor-cli")j.push("## Cursor Notes"),j.push(""),j.push("- Use Composer mode for multi-file changes"),j.push("- Reference this guide in your cursor rules"),j.push("- Break implementation into small, focused commits");else if(W==="claude-code")j.push("## Claude Code Notes"),j.push(""),j.push("- Use extended thinking for complex logic"),j.push("- Ask for clarification on ambiguous requirements"),j.push("- Provide step-by-step reasoning");else if(W==="generic-mcp")j.push("## General Notes"),j.push(""),j.push("- Use inline comments to guide generation"),j.push("- Review generated code carefully");return j.push(""),j.push("## Spec Definition"),j.push(""),j.push(z$($,"full")),j.join(`
2002
+ `)}function mY($){let W=[];if(W.push(`# ${$.meta.key}`),W.push(""),W.push(`Description: ${$.meta.description??"No description"}`),W.push(""),W.push("## Rules"),W.push(""),$.specType==="operation"){if(W.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)W.push("- Validate input and output against schemas");if($.hasPolicy)W.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)W.push("- Emit documented events")}else if($.specType==="feature")W.push("- Implement all operations and presentations"),W.push("- Follow modular architecture");else W.push(`- Follow ${$.specType} patterns`);return W.push("- Follow project code quality standards"),W.push("- Write tests for new functionality"),W.join(`
2003
+ `)}function EO($,W,j="generic-mcp"){switch(W){case"guide":return vY($,j);case"rules":return mY($);case"prompt":return z$($,"prompt");case"context":return z$($,"context");case"full":default:return z$($,"full")}}import{readFile as PY}from"fs/promises";import{createRequire as kY}from"module";import{dirname as hY,resolve as l4}from"path";import{pathToFileURL as gY}from"url";import r4 from"vm";import Fj from"typescript";async function Q$($,W={}){let j=l4(process.cwd(),$),A=W.runtime??dY();try{let Q=A==="bun"?await fY(j):await uY(j);return{modulePath:j,exports:Q}}catch(Q){throw Error(i4(j,Q))}}async function vO($,W){let j=l4(process.cwd(),$);if(!await W.exists(j))return null;return Q$(j)}async function vW($,W={}){return(await Q$($,W)).exports}async function o4($,W){let j=await vW($);return p4(j,$,W)}function i4($,W){return`Failed to load authored module at ${$}: ${W instanceof Error?W.message:String(W)}`}async function p4($,W,j){if(j.isValue($))return $;for(let A of j.instanceKeys??[])if(j.isValue($[A]))return $[A];for(let A of j.factoryKeys??[]){let Q=$[A];if(typeof Q!=="function")continue;let Z=await Q();if(j.isValue(Z))return Z}throw Error(`${j.description} module ${W} must export a supported instance or factory.`)}async function fY($){return await import(gY($).href)}async function uY($){return await nY($)??{}}function dY(){return typeof globalThis.Bun<"u"?"bun":"node"}var mO={formatModuleLoadError:i4,resolveAuthoredModuleValue:p4};async function nY($){let W=await PY($,"utf-8"),j=Fj.transpileModule(W,{compilerOptions:{module:Fj.ModuleKind.CommonJS,target:Fj.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),A={},Q={exports:A},Z=kY($),X=r4.createContext({module:Q,exports:A,require:Z,__dirname:hY($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new r4.Script(j.outputText,{filename:$}).runInContext(X),Q.exports}var t4=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],cY=[...t4,{name:"@contractspec/lib.schema",description:"Extended schema utilities and common types"},{name:"@contractspec/app.cli-contractspec",dev:!0,description:"ContractSpec CLI for validation, scaffolding, and code generation"},{name:"typescript",dev:!0,description:"TypeScript compiler for type checking"}];function xj($){return $==="minimal"?t4:cY}function yj($){return $.filter((W)=>!W.dev)}function vj($){return $.filter((W)=>W.dev)}import{exec as rY}from"child_process";import{promisify as lY}from"util";var oY=lY(rY),iY={confirm:async()=>!0,select:async($,W)=>W[0]?.value??""};async function dO($,W,j=iY){let A=xj(W.mode),Q=yj(A),Z=vj(A),X=[],Y=[],B=[],q=$.join(W.workspaceRoot,"package.json");if(!await $.exists(q))return{success:!1,installed:[],skipped:[],errors:[{name:"package.json",action:"error",message:"No package.json found. Run `npm init` first."}],summary:"No package.json found in workspace root."};let V=await $.readFile(q),G=JSON.parse(V),J=new Set([...Object.keys(G.dependencies??{}),...Object.keys(G.devDependencies??{})]),b=k$(W.workspaceRoot),w=Q.filter((U)=>{if(J.has(U.name)&&!W.force)return Y.push({name:U.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),L=Z.filter((U)=>{if(J.has(U.name)&&!W.force)return Y.push({name:U.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(W.dryRun){let U=[...w,...L];return{success:!0,installed:U.map((O)=>({name:O.name,action:"installed",message:`Would install: ${O.description}`,dev:O.dev})),skipped:Y,errors:[],summary:`Dry run: would install ${U.length} package(s), skip ${Y.length}.`}}if(!W.skipPrompts&&(w.length>0||L.length>0)){let U=w.length+L.length;if(!await j.confirm(`Install ${U} package(s) using ${b}?`))return{success:!0,installed:[],skipped:[...Y,...w.map((K)=>({name:K.name,action:"skipped",message:"User cancelled"})),...L.map((K)=>({name:K.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(w.length>0){let U=await a4(w,b,W.workspaceRoot,!1);for(let O of U)if(O.action==="installed")X.push(O);else B.push(O)}if(L.length>0){let U=await a4(L,b,W.workspaceRoot,!0);for(let O of U)if(O.action==="installed")X.push(O);else B.push(O)}let z=B.length===0,S=z?`Successfully installed ${X.length} package(s), skipped ${Y.length}.`:`Installed ${X.length}, skipped ${Y.length}, failed ${B.length}.`;return{success:z,installed:X,skipped:Y,errors:B,summary:S}}async function a4($,W,j,A){let Q=[],Z=$.map((X)=>X.version?`${X.name}@${X.version}`:X.name);try{let Y=`${R5(W,A)} ${Z.join(" ")}`;await oY(Y,{cwd:j,timeout:120000});for(let B of $)Q.push({name:B.name,action:"installed",message:B.description,dev:A})}catch(X){let Y=X instanceof Error?X.message:String(X);for(let B of $)Q.push({name:B.name,action:"error",message:`Failed to install: ${Y}`,dev:A})}return Q}async function nO($,W){let j=$.join(W,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A);return"@contractspec/lib.contracts-spec"in{...Q.dependencies,...Q.devDependencies}}catch{return!1}}function cO($){let W=xj($),j=[];j.push(`ContractSpec ${$} installation:`),j.push("");let A=yj(W);if(A.length>0){j.push("Dependencies:");for(let Z of A)j.push(` \u2022 ${Z.name} - ${Z.description}`)}let Q=vj(W);if(Q.length>0){j.push(""),j.push("Dev Dependencies:");for(let Z of Q)j.push(` \u2022 ${Z.name} - ${Z.description}`)}return j.join(`
2004
+ `)}import{RegeneratorService as pY}from"@contractspec/lib.contracts-spec/regenerator";function aO($){return new pY({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class mW{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let W=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,j;try{j=await fetch(W,{method:"GET",headers:{Accept:"application/json"}})}catch(A){throw Error(`Registry request failed: ${W} (${A instanceof Error?A.message:String(A)})`)}if(!j.ok){let A=await j.text().catch(()=>"");throw Error(`Registry request failed: ${j.status} ${j.statusText} ${A}`)}return await j.json()}}function mj($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function eO($,W,j){let{logger:A}=j,Q=mj(W.registryUrl);A.info(`Adding spec to registry: ${$}`,{registryUrl:Q}),await new mW({registryUrl:Q}).getJson(`/specs/add?path=${encodeURIComponent($)}`),A.info("Spec added to registry successfully")}async function $S($,W){let{logger:j}=W,A=mj($.registryUrl);j.info("Listing specs from registry",{registryUrl:A});let Q=new mW({registryUrl:A}),Z=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",X=await Q.getJson(`/specs${Z}`);return j.info(`Found ${X.length} specs`),X}async function WS($,W,j){let{logger:A}=j,Q=mj(W.registryUrl);A.info(`Searching registry: ${$}`,{registryUrl:Q});let X=await new mW({registryUrl:Q}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return A.info(`Found ${X.length} results`),X}class tY{fs;logger;constructor($,W){this.fs=$;this.logger=W}async sync($){let{config:W,cwd:j}=$,A=$.targets??W.targets??[];if(!W.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${A.join(", ")}...`);try{let Q=this.fs.join(j,W.rulesDir??".rules");if(!await this.fs.exists(Q))return{success:!1,files:[],errors:[`Rules directory not found: ${Q}`]};let X=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${X}`);let Y=[];for(let B of A){let q=this.getTargetFileName(B);if(q){let H=this.fs.join(j,q);Y.push(H)}}return{success:!0,files:Y,logs:[`Successfully synchronized rules to ${Y.length} targets.`]}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return this.logger.error(`Rule synchronization failed: ${Z}`),{success:!1,files:[],errors:[Z]}}}async generateConfig($){let{config:W}=$,j={rules:(W.rules??[]).map((A)=>this.fs.join(W.rulesDir??".rules",A)),targets:$.targets||W.targets};return JSON.stringify(j,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}var $9="<!-- contractspec:init:agents:start -->",W9="<!-- contractspec:init:agents:end -->",aY="<!-- This section is managed by `contractspec init`. Content outside these markers is user-owned and preserved. -->";async function Pj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"AGENTS.md");try{let Z=await $.exists(Q),X=D8(W);if(Z){let Y=await $.readFile(Q);if(W.interactive){if(!await j.confirm(`${Q} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:Q,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(Q,sY(Y,X)),{target:"agents-md",filePath:Q,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(Q,j9(X)),{target:"agents-md",filePath:Q,action:"created",message:"Created AI agent guide"}}catch(Z){return{target:"agents-md",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}function sY($,W){let j=j9(W),A=eY();if(A.test($))return $.replace(A,j);if(s4($)===s4(W))return j;return`${j}${$}`}function j9($){let W=$.replace(/\r\n/g,`
2005
+ `).trimEnd();return`${$9}
2006
+ ${aY}
2007
+ ${W}
2008
+ ${W9}
2009
+ `}function s4($){return $.replace(/\r\n/g,`
2010
+ `).trimEnd()}function eY(){return new RegExp(`${e4($9)}[\\s\\S]*?${e4(W9)}(?:\\r?\\n)?`)}function e4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{generateArtifactsForAudience as $3,generateBiomePreset as W3}from"@contractspec/biome-config";async function kj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"biome.jsonc"),Z=$.join(A,".contractspec","biome"),X=$.join(Z,"plugins"),Y=$.join(Z,"ai"),B=$3("consumer");try{let q=await $.exists(Q);if(q&&W.interactive){if(!await j.confirm(`${Q} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Q,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Q,W3("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(B.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),B.aiRules),{target:"biome-config",filePath:Q,action:q?"merged":"created",message:q?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(q){return{target:"biome-config",filePath:Q,action:"error",message:q instanceof Error?q.message:"Unknown error"}}}async function hj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".contractsrc.json");try{let Z=await $.exists(Q),X=u$(W);if(Z){let Y=await $.readFile(Q),B=r(Y);if(!B)return{target:"cli-config",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Q,action:"skipped",message:"User skipped merge"}}let q=p(B,X);if((W.preset==="connect"||W.preset?.startsWith("builder-"))&&typeof X==="object"&&X!==null){let H={};if("connect"in X)H.connect=X.connect;if("builder"in X)H.builder=X.builder;await $.writeFile(Q,F(y1(q,H)))}else await $.writeFile(Q,F(q));return{target:"cli-config",filePath:Q,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Q,F(X)),{target:"cli-config",filePath:Q,action:"created",message:"Created CLI configuration"}}catch(Z){return{target:"cli-config",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function gj($,W,j){let A=$.join(W.workspaceRoot,".cursor","rules"),Q=$.join(A,"contractspec.mdc");try{let Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=C8(W);if(X)if(W.interactive){if(!await j.confirm(`${Q} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Q,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Q,action:"skipped",message:"File already exists"};return await $.writeFile(Q,Y),{target:"cursor-rules",filePath:Q,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(Z){return{target:"cursor-rules",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function fj($,W,j){let A=qW();try{let Q=await $.exists(A),Z=R8();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Q){let B=await $.readFile(A),q=r(B);if(!q)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let H=p(q,Z);return await $.writeFile(A,F(H)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(A,F(Z)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(Q){return{target:"mcp-claude",filePath:A,action:"error",message:Q instanceof Error?Q.message:"Unknown error"}}}async function uj($,W,j){let A=$.join(W.workspaceRoot,".cursor"),Q=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=q0();if(X){let B=await $.readFile(Q),q=r(B);if(!q)return{target:"mcp-cursor",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Q,action:"skipped",message:"User skipped merge"}}let H=p(q,Y);return await $.writeFile(Q,F(H)),{target:"mcp-cursor",filePath:Q,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Q,F(Y)),{target:"mcp-cursor",filePath:Q,action:"created",message:"Created Cursor MCP configuration"}}catch(Z){return{target:"mcp-cursor",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function dj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".vscode"),Z=$.join(Q,"settings.json");try{if(!await $.exists(Q))await $.mkdir(Q);let Y=await $.exists(Z),B=BW(W);if(Y){let q=await $.readFile(Z),H=r(q);if(!H)return{target:"vscode-settings",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:Z,action:"skipped",message:"User skipped merge"}}let V=p(H,B);if((W.preset==="builder-managed"||W.preset==="builder-hybrid")&&"contractspec.api.baseUrl"in B)V["contractspec.api.baseUrl"]=B["contractspec.api.baseUrl"];return await $.writeFile(Z,F(V)),{target:"vscode-settings",filePath:Z,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(Z,F(B)),{target:"vscode-settings",filePath:Z,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:Z,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var j3={confirm:async($,W)=>W??!0,select:async($,W)=>{return W.find((j)=>j.selected)?.value??W[0]?.value??""},multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function PS($,W,j=j3){let A=[],Q=W.targets.length>0?W.targets:X0,Z=W.workspaceRoot,X=D(Z),Y=W.packageRoot??f(Z),B=W.isMonorepo??e$(X),q=W.packageName??(B?I$(Y):void 0),H=await A9($,[Y,X]),V=W.preset??B0(H);if(W.interactive&&!W.preset)V=await j.select("Select initialization preset:",U8.map((R)=>({value:R,label:L8[R],description:O8[R],selected:R===V})));let G=W.scope??"workspace",J=Y!==X;if(B&&W.interactive&&J)G=await j.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${q??Y})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${X})`,description:"Create config files at the workspace root"}]);let b=B&&G==="package"?Y:X,w=await A9($,[b]),L={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:B,scope:G,packageName:q,preset:V,builderApiBaseUrl:W.builderApiBaseUrl??w?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:W.builderControlPlaneTokenEnvVar??w?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:W.builderLocalRuntimeId??w?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:W.builderLocalGrantedTo??w?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:W.builderLocalProviderIds??w?.builder?.localRuntime?.providerIds,connectStudioEndpoint:W.connectStudioEndpoint??w?.connect?.studio?.endpoint,connectStudioQueue:W.connectStudioQueue??w?.connect?.studio?.queue},z=S8(V,Q);if(W.interactive)z=await j.multiSelect("Select components to configure:",X0.map((R)=>({value:R,label:z8[R],selected:z.includes(R)})));let S=L.projectName;if(W.interactive&&!S){let R=G==="package"&&q?q:b.split("/").pop()??"my-project";S=await j.input("Project name:",R)}let U=L.builderApiBaseUrl;if(W.interactive&&(V==="builder-managed"||V==="builder-hybrid"))U=await j.input("Builder API base URL:",U??"https://api.contractspec.io");let{builderLocalRuntimeId:O,builderLocalGrantedTo:K}=L;if(W.interactive&&(V==="builder-local"||V==="builder-hybrid"))O=await j.input("Default local runtime target id:",O??"rt_local_daemon"),K=await j.input("Default local runtime grant target:",K??"local:operator");let _={...L,projectName:S,targets:z,builderApiBaseUrl:U,builderLocalRuntimeId:O,builderLocalGrantedTo:K};for(let R of z){let v=await A3($,R,_,j);A.push(v)}let I=await EW($,{behavior:_.gitignoreBehavior,interactive:_.interactive,patterns:N8({preset:V}),prompts:j,root:X});if(_.gitignoreBehavior!=="skip"||I.action!=="skipped")A.push(I);let M=A.filter((R)=>R.action!=="error").length,E=A.filter((R)=>R.action==="error").length,C=B?` (${G} level)`:"";return{success:E===0,preset:V,files:A,summary:`Setup complete${C}: ${M} configured, ${E} failed.`,nextSteps:E8(_)}}async function A3($,W,j,A){switch(W){case"agents-md":return Pj($,j,A);case"cli-config":return hj($,j,A);case"biome-config":return kj($,j,A);case"vscode-settings":return dj($,j,A);case"mcp-cursor":return uj($,j,A);case"mcp-claude":return fj($,j,A);case"cursor-rules":return gj($,j,A);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}async function A9($,W){for(let j of W){let A=$.join(j,".contractsrc.json");if(!await $.exists(A))continue;let Q=r(await $.readFile(A));if(Q)return Q}return null}import{validateBlueprint as Q3}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as Z3}from"path";async function iS($,W){let{fs:j}=W,A=Z3(process.cwd(),$);if(!await j.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let Q=await Q$(A),Z=X3(Q.exports),X=Q3(Z);return{spec:Z,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Q){return{valid:!1,errors:[Q instanceof Error?Q.message:String(Q)]}}}function X3($){let W=Object.values($).filter(Y3);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function Y3($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as B3,dirname as nj,join as R0}from"path";async function sS($,W,j,A,Q){let{fs:Z}=Q,X=A.implementationPath;if(!X){let H=nj($),V=B3($,".ts"),G=[R0(H,V.replace(".contracts",".handler")+".ts"),R0(H,V.replace(".presentation","")+".tsx"),R0(H,V.replace(".form",".form")+".tsx"),R0(nj(H),"handlers",V.replace(".contracts",".handler")+".ts"),R0(nj(H),"components",V.replace(".presentation","")+".tsx")];for(let J of G)if(await Z.exists(J)){X=J;break}}if(!X||!await Z.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await Z.readFile(X),q=await new g0(j).validate(W,Y);return{success:q.success,errors:q.errors||[],warnings:q.warnings||[],suggestions:q.suggestions||[],report:q.code}}import{validateBuilderBlueprint as q3,validateBuilderReadinessReport as H3,validateBuilderWorkspace as V3,validateBuilderWorkspaceSnapshot as G3}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as J3,validateExternalPatchProposal as b3,validateProviderRoutingPolicy as w3,validateRuntimeTarget as K3}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as _3,validateLayoutSlots as z3}from"@contractspec/lib.surface-runtime/spec";async function QI($,W){if(!I3($.specType))return{valid:!0,errors:[],warnings:[]};let j=y3($.filePath),A=[`${j}/package.json`,`${j}/README.md`,`${j}/src/index.ts`,$.filePath],Q=[];for(let Y of A)if(!await W.exists(Y))Q.push(`Missing package scaffold file: ${Y}`);if(Q.length>0)return{valid:!1,errors:Q,warnings:[]};let Z;try{Z=(await Q$($.filePath)).exports}catch(Y){return{valid:!1,errors:[Y instanceof Error?Y.message:String(Y)],warnings:[]}}let X=$.specType==="module-bundle"?U3(Z):$.specType==="builder-spec"?L3(Z):O3(Z);return{valid:Q.length===0&&X.errors.length===0,errors:[...Q,...X.errors],warnings:X.warnings.map((Y)=>`[${$.filePath}] ${Y}`)}}function U3($){let W=[],j=[],A=S3($,M3);if(A.length===0)return j.push(cj("module-bundle","bundle")),{errors:W,warnings:j};for(let Q of A){let Z=Object.values(Q.value.surfaces);for(let X of Z){try{z3(X)}catch(Y){W.push(`[${Q.exportName}] ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of _3(X).warnings)j.push(`[${Q.exportName}] ${Y}`)}}return{errors:W,warnings:j}}function L3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(E3(Z)){A+=1,W.push(...PW(Q,V3(Z)));continue}if(N3(Z)){A+=1,W.push(...PW(Q,q3(Z)));continue}if(R3(Z)){A+=1,W.push(...PW(Q,H3(Z)));continue}if(C3(Z))A+=1,W.push(...PW(Q,G3(Z)))}if(A===0)j.push(cj("builder-spec","builder"));return{errors:W,warnings:j}}function O3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(D3(Z)){A+=1,W.push(...kW(Q,K3(Z)));continue}if(T3(Z)){A+=1,W.push(...kW(Q,w3(Z)));continue}if(F3(Z)){A+=1,W.push(...kW(Q,J3(Z)));continue}if(x3(Z))A+=1,W.push(...kW(Q,b3(Z)))}if(A===0)j.push(cj("provider-spec","provider"));return{errors:W,warnings:j}}function S3($,W){return Object.entries($).filter(([j,A])=>j!=="__esModule"&&W(A)).map(([j,A])=>({exportName:j,value:A}))}function PW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function kW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function I3($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function M3($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function E3($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function N3($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function R3($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function C3($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function D3($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function T3($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function F3($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function x3($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function y3($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function cj($,W){return`No recognized ${W} exports were found for ${$} deep validation.`}import{validateSpecStructure as v3}from"@contractspec/module.workspace";function Q9($,W={}){let j=[],A=[],Q;if(!W.skipStructure)Q=v3($),j.push(...Q.errors),A.push(...Q.warnings);return{valid:j.length===0,structureResult:Q,errors:j,warnings:A,code:$.sourceBlock}}async function BI($,W={}){return $.map((j)=>({spec:j,...Q9(j,W)}))}async function m$($,W,j={}){let{fs:A}=W;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let Z=await A.readFile($),X=[],Y=[],B=void 0;if(!j.skipStructure){let q=await $$(W,{pattern:$});for(let H of q){let V=Q9(H,j);B=V.structureResult,X.push(...V.errors),Y.push(...V.warnings)}}return{valid:X.length===0,structureResult:B,errors:X,warnings:Y,code:Z}}async function qI($,W,j={}){let A=new Map;for(let Q of $){let Z=await m$(Q,W,j);A.set(Q,Z)}return A}import{validateConfig as m3}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as lj}from"fs/promises";import{resolve as hW}from"path";async function wI($,W,j,A){let{fs:Q}=A,Z=hW(process.cwd(),W);if(!await Q.exists(Z))return{valid:!1,errors:[`Tenant config file not found: ${Z}`]};try{let X=await P3(Z),Y=await k3(j.connections,Q),B=await h3(j.translationCatalog,Q),q=await g3(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(B)H.translationCatalogs={blueprint:[B],platform:[]};if(q)H.integrationSpecs=q;let V=m3($,X,H);return{config:X,report:V,valid:V.valid,errors:V.errors.map((G)=>`[${G.code}] ${G.path}: ${G.message}`)}}catch(X){return{valid:!1,errors:[X instanceof Error?X.message:String(X)]}}}async function P3($){if($.endsWith(".json")){let A=await lj($,"utf-8"),Q=JSON.parse(A);if(!Z9(Q))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Q}let W=await Q$($),j=Object.values(W.exports).filter(Z9);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function Z9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function q9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function k3($,W){let j=q9($);if(!j.length)return[];let A=[];for(let Q of j){let Z=hW(process.cwd(),Q);if(!await W.exists(Z)){console.warn(`Warning: Connection file not found: ${Z}`);continue}if(Z.endsWith(".json")){let Y=await lj(Z,"utf-8"),B=JSON.parse(Y);A.push(...rj(B));continue}let X=await Q$(Z);A.push(...rj(X.exports))}return A}function rj($){if(Array.isArray($)){let W=$.filter(X9);if(W.length)return W}if(X9($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((A)=>rj(A));if(j.length)return j}return[]}function X9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function h3($,W){if(!$)return;let j=hW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let Z=await lj(j,"utf-8"),X=JSON.parse(Z);if(Y9(X))return B9(X);return}let A=await Q$(j),Q=Object.values(A.exports).filter(Y9);if(Q.length===0)return;return B9(Q[0])}function Y9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function B9($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function g3($){let W=q9($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),A=new j;for(let Q of W){let{modulePath:Z,exportName:X}=f3(Q);if(!Z)continue;let Y=hW(process.cwd(),Z);try{let B=await Q$(Y),q=u3(B.exports,X);if(q)await q(A)}catch(B){console.warn(`Failed to load registrar from ${Y}: ${B}`)}}return A}function f3($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),A=W?.trim()??null,Q=j?.trim();return{modulePath:A,exportName:Q}}function u3($,W){if(W){let j=$[W];if(typeof j==="function")return j;return}if(typeof $.default==="function")return $.default;for(let j of Object.values($))if(typeof j==="function")return j;return}async function NI($,W,j={},A){let{fs:Q,logger:Z}=$,X=await Q.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],B=[],q=A?.validate??((V)=>m$(V,{fs:Q,logger:Z})),H=A?.build??((V,G)=>f$(V,{fs:Q,logger:Z},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let J={specPath:V,outputDir:G};if(j.validate)try{J.validation=await q(V)}catch(b){J.error={phase:"validate",message:b instanceof Error?b.message:String(b)},B.push(J);continue}if(!j.dryRun)try{J.build=await H(V,G)}catch(b){J.error={phase:"build",message:b instanceof Error?b.message:String(b)},B.push(J);continue}else Z.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});B.push(J)}return{specs:X,runs:B}}import{generateText as d3}from"ai";var n3=`
1766
2011
  You are an expert software test engineer specializing in ContractSpec.
1767
2012
  Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
1768
2013
 
@@ -1780,7 +2025,7 @@ Generate scenarios covering:
1780
2025
  - Happy path (valid input, successful execution)
1781
2026
  - Edge cases (boundary values, optional fields)
1782
2027
  - Error cases (invalid input, business rule violations)
1783
- `.trim();class DY{logger;defaultModel;constructor($,W){this.logger=$;this.defaultModel=W}async generateTests($,W={}){let j=W.model??this.defaultModel;if(!j)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let Q=`
2028
+ `.trim();class c3{logger;defaultModel;constructor($,W){this.logger=$;this.defaultModel=W}async generateTests($,W={}){let j=W.model??this.defaultModel;if(!j)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let A=`
1784
2029
  Generate a TestSpec for the following Operation:
1785
2030
 
1786
2031
  \`\`\`json
@@ -1789,23 +2034,23 @@ ${JSON.stringify($,null,2)}
1789
2034
 
1790
2035
  The output must be a valid JSON object conforming to the TestSpec interface.
1791
2036
  Do not include markdown formatting or explanations, just the JSON.
1792
- `.trim();try{let{text:Z,usage:B}=await NY({model:j,system:RY,prompt:Q});this.logUsage(B);let X=this.parseResponse(Z);return this.enrichSpec(X,$)}catch(Z){throw this.logger.error("Failed to generate tests",{error:Z}),Z}}parseResponse($){try{let W=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(W)}catch(W){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,W){let j={key:`${W.meta.key}.test`,version:W.meta.version??"0.0.1",owners:W.meta.owners??[]},Q={type:"operation",operation:{key:W.meta.key,version:W.meta.version}};return{meta:j,target:Q,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let W=$;this.logger.debug(`AI Usage: ${W.promptTokens} prompt + ${W.completionTokens} completion = ${W.totalTokens} total tokens`)}}import{OperationSpecRegistry as VW}from"@contractspec/lib.contracts-spec";import{TestRunner as qQ}from"@contractspec/lib.contracts-spec/tests";import{resolve as Uj}from"path";async function UO($,W){let j=new qQ({registry:W}),Q=[],Z=0,B=0;for(let X of $){let Y=await j.run(X);Q.push(Y),Z+=Y.passed,B+=Y.failed}return{results:Q,passed:Z,failed:B}}async function _O($,W,j){let{logger:Q}=j,Z;if(W.registry)Z=await xY(Uj(W.registry));else Z=new VW,Q.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let B=new qQ({registry:Z}),X=[],Y=!0;for(let q of $)try{let A=Uj(q),H=await r$(A),V=AQ(H);if(V.length===0){Q.warn(`No TestSpec exports found in ${q}`);continue}for(let G of V){Q.info(`Running ${G.meta.key}...`);let z=await B.run(G);if(X.push(z),z.failed>0)Y=!1,Q.error(`${G.meta.key} failed (${z.failed}/${z.scenarios.length})`);else Q.info(`${G.meta.key} passed (${z.passed}/${z.scenarios.length})`)}}catch(A){Q.error(`Failed to load/run spec ${q}: ${A instanceof Error?A.message:String(A)}`),Y=!1}return{results:X,passed:Y}}async function LO($,W){let j=[];for(let Q of $)try{let Z=Uj(Q),B=await r$(Z),X=AQ(B);j.push(...X)}catch(Z){W.logger.warn(`Failed to load tests from ${Q}: ${Z instanceof Error?Z.message:String(Z)}`)}return j}function AQ($){let W=[];for(let j of Object.values($))if(FY(j))W.push(j);return W}function FY($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function xY($){let W=await r$($);if(W instanceof VW)return W;if(W.registry instanceof VW)return W.registry;let j=typeof W.createRegistry==="function"?W.createRegistry:typeof W.default==="function"?W.default:void 0;if(j){let Q=await j();if(Q instanceof VW)return Q}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{scanSpecSource as G0}from"@contractspec/module.workspace";function TY($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function EO($,W,j={}){let{fs:Q,logger:Z}=W;if(!await Q.exists($))return{specPath:$,specInfo:TY($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let X=await Q.readFile($),Y;if(j.content!==void 0)Y=j.content;else if(j.fields?.length)Y=vY(X,j.fields);else return{specPath:$,specInfo:G0(X,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!j.skipValidation){await Q.writeFile($,Y);let q=await R$($,W);if(q.errors.length>0)return await Q.writeFile($,X),{specPath:$,specInfo:G0(Y,$),updated:!1,errors:q.errors,warnings:q.warnings};if(q.warnings.length>0&&!j.allowWarnings)return await Q.writeFile($,X),{specPath:$,specInfo:G0(Y,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:q.warnings};return Z.info(`Updated spec: ${$}`),{specPath:$,specInfo:G0(Y,$),updated:!0,errors:[],warnings:q.warnings}}return await Q.writeFile($,Y),Z.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:G0(Y,$),updated:!0,errors:[],warnings:[]}}function vY($,W){let j=$;for(let{key:Q,value:Z}of W){let B=Q.includes(".")?Q.split(".").pop():Q;if(!B)continue;let X=new RegExp(`(${yY(B)}\\s*:\\s*)(['"\`])([^'"\`]*?)\\2`,"g"),q=!/^(true|false|\d+(\.\d+)?)$/.test(Z)?`$1"${Z}"`:`$1${Z}`;j=j.replace(X,q)}return j}function yY($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var SQ={};P(SQ,{getPackageUpgradeCommand:()=>LQ,getDefaultVersioningConfig:()=>JW,getDefaultHooksConfig:()=>KW,applyGuidedUpgrade:()=>CQ,applyConfigUpgrades:()=>_Q,analyzeUpgrades:()=>zW,analyzeGuidedUpgrade:()=>Ij});import{GeneratedReleaseManifestSchema as bQ}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as cY,DEFAULT_CONTRACTSRC as lY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function HQ($){return $.packages.map((W)=>{let j=W.version?`@${W.version}`:"";return`- ${W.name}${j} (${W.releaseType})`})}function VQ($){return $.map((W)=>` - ${W}`)}function GQ($){let W=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...HQ($)];if($.deprecations.length>0)W.push("- Deprecations:"),W.push(...$.deprecations.map((j)=>` - ${j}`));return W.join(`
1793
- `)}function PY($){let W=[`### ${$.summary}`,...HQ($)];for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`);return W.join(`
1794
- `)}function zQ($){let W=[`### ${$.summary}`];if($.migrationInstructions.length===0)return W.push("- No manual migration steps recorded."),W.join(`
1795
- `);for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`),W.push(...VQ(j.steps));return W.join(`
1796
- `)}function _j($){return["# Patch Notes","",...$.releases.map(GQ)].join(`
2037
+ `.trim();try{let{text:Q,usage:Z}=await d3({model:j,system:n3,prompt:A});this.logUsage(Z);let X=this.parseResponse(Q);return this.enrichSpec(X,$)}catch(Q){throw this.logger.error("Failed to generate tests",{error:Q}),Q}}parseResponse($){try{let W=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(W)}catch(W){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,W){let j={key:`${W.meta.key}.test`,version:W.meta.version??"0.0.1",owners:W.meta.owners??[]},A={type:"operation",operation:{key:W.meta.key,version:W.meta.version}};return{meta:j,target:A,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let W=$;this.logger.debug(`AI Usage: ${W.promptTokens} prompt + ${W.completionTokens} completion = ${W.totalTokens} total tokens`)}}import{OperationSpecRegistry as H9}from"@contractspec/lib.contracts-spec";import{TestRunner as V9}from"@contractspec/lib.contracts-spec/tests";import{resolve as oj}from"path";async function vI($,W){let j=new V9({registry:W}),A=[],Q=0,Z=0;for(let X of $){let Y=await j.run(X);A.push(Y),Q+=Y.passed,Z+=Y.failed}return{results:A,passed:Q,failed:Z}}async function mI($,W,j){let{logger:A}=j,Q;if(W.registry)Q=await l3(oj(W.registry));else Q=new H9,A.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let Z=new V9({registry:Q}),X=[],Y=!0;for(let B of $)try{let q=oj(B),H=await vW(q),V=G9(H);if(V.length===0){A.warn(`No TestSpec exports found in ${B}`);continue}for(let G of V){A.info(`Running ${G.meta.key}...`);let J=await Z.run(G);if(X.push(J),J.failed>0)Y=!1,A.error(`${G.meta.key} failed (${J.failed}/${J.scenarios.length})`);else A.info(`${G.meta.key} passed (${J.passed}/${J.scenarios.length})`)}}catch(q){A.error(`Failed to load/run spec ${B}: ${q instanceof Error?q.message:String(q)}`),Y=!1}return{results:X,passed:Y}}async function PI($,W){let j=[];for(let A of $)try{let Q=oj(A),Z=await vW(Q),X=G9(Z);j.push(...X)}catch(Q){W.logger.warn(`Failed to load tests from ${A}: ${Q instanceof Error?Q.message:String(Q)}`)}return j}function G9($){let W=[];for(let j of Object.values($))if(r3(j))W.push(j);return W}function r3($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function l3($){return o4($,{description:"OperationSpecRegistry",isValue:(W)=>W instanceof H9,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as C0}from"@contractspec/module.workspace";import{IndentationText as o3,Node as i$,Project as i3,QuoteKind as p3,SyntaxKind as t3}from"ts-morph";function a3($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function cI($,W,j={}){let{fs:A,logger:Q}=W;if(!await A.exists($))return{specPath:$,specInfo:a3($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let X=await A.readFile($),Y;if(j.content!==void 0)Y=j.content;else if(j.fields?.length)Y=s3(X,j.fields);else return{specPath:$,specInfo:C0(X,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!j.skipValidation){await A.writeFile($,Y);let B=await m$($,W);if(B.errors.length>0)return await A.writeFile($,X),{specPath:$,specInfo:C0(Y,$),updated:!1,errors:B.errors,warnings:B.warnings};if(B.warnings.length>0&&!j.allowWarnings)return await A.writeFile($,X),{specPath:$,specInfo:C0(Y,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:B.warnings};return Q.info(`Updated spec: ${$}`),{specPath:$,specInfo:C0(Y,$),updated:!0,errors:[],warnings:B.warnings}}return await A.writeFile($,Y),Q.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:C0(Y,$),updated:!0,errors:[],warnings:[]}}function s3($,W){let A=new i3({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:o3.TwoSpaces,quoteKind:p3.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),Q=$B(A);if(!Q)return $;for(let Z of W)e3(Q,Z);return A.getFullText()}function e3($,W){let j=W.key.split(".").map((Y)=>Y.trim()).filter(Boolean);if(j.length===0)return;let A=$;for(let Y of j.slice(0,-1)){if(!A.getProperty(Y))A.addPropertyAssignment({name:Y,initializer:"{}"});let q=A.getPropertyOrThrow(Y);if(!i$.isPropertyAssignment(q))return;let H=q.getInitializer();if(!H||!i$.isObjectLiteralExpression(H))q.setInitializer("{}");let V=q.getInitializerIfKind(t3.ObjectLiteralExpression);if(!V)return;A=V}let Q=j[j.length-1];if(!Q)return;let Z=WB(W.value),X=A.getProperty(Q);if(X&&i$.isPropertyAssignment(X)){X.setInitializer(Z);return}A.addPropertyAssignment({name:Q,initializer:Z})}function $B($){for(let W of $.getVariableDeclarations()){let j=W.getInitializer();if(!j)continue;if(i$.isObjectLiteralExpression(j))return j;if(i$.isCallExpression(j)){let A=j.getArguments()[0];if(A&&i$.isObjectLiteralExpression(A))return A}}return}function WB($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var R9={};h(R9,{getPackageUpgradeCommand:()=>O9,getDefaultVersioningConfig:()=>fW,getDefaultHooksConfig:()=>uW,applyGuidedUpgrade:()=>N9,applyConfigUpgrades:()=>L9,analyzeUpgrades:()=>gW,analyzeGuidedUpgrade:()=>tj});import{GeneratedReleaseManifestSchema as M9}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as HB,DEFAULT_CONTRACTSRC as VB}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function J9($){return $.packages.map((W)=>{let j=W.version?`@${W.version}`:"";return`- ${W.name}${j} (${W.releaseType})`})}function b9($){return $.map((W)=>` - ${W}`)}function w9($){let W=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...J9($)];if($.deprecations.length>0)W.push("- Deprecations:"),W.push(...$.deprecations.map((j)=>` - ${j}`));return W.join(`
2038
+ `)}function jB($){let W=[`### ${$.summary}`,...J9($)];for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`);return W.join(`
2039
+ `)}function K9($){let W=[`### ${$.summary}`];if($.migrationInstructions.length===0)return W.push("- No manual migration steps recorded."),W.join(`
2040
+ `);for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`),W.push(...b9(j.steps));return W.join(`
2041
+ `)}function ij($){return["# Patch Notes","",...$.releases.map(w9)].join(`
1797
2042
 
1798
- `)}function Lj($){return["# Customer Upgrade Guide","",...$.releases.map(zQ)].join(`
2043
+ `)}function pj($){return["# Customer Upgrade Guide","",...$.releases.map(K9)].join(`
1799
2044
 
1800
- `)}function JQ($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((W)=>[`- [${W.level}] ${W.title}: ${W.summary}`,...VQ(W.instructions)].join(`
2045
+ `)}function _9($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((W)=>[`- [${W.level}] ${W.title}: ${W.summary}`,...b9(W.instructions)].join(`
1801
2046
  `)).join(`
1802
- `)}function h$($,W){let j=W.targetPackages.map((Q)=>`${Q.name}: ${Q.currentVersion??"unknown"} -> ${Q.targetVersion??"latest"}`).join(`
1803
- `);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",j||"- No package version targets were inferred.","","Required steps:",JQ(W)].join(`
1804
- `)}import{compareVersions as UQ,countUpgradePlanStepLevels as mY,createAgentPromptBundles as kY,dedupeUpgradePlanSteps as gY,sortReleaseManifest as KQ}from"@contractspec/lib.contracts-spec";function hY($,W){if(W.length===0)return KQ($);let j=new Map(W.map((Q)=>[Q.name,Q.currentVersion??"0.0.0"]));return KQ({...$,releases:$.releases.filter((Q)=>Q.packages.some((Z)=>{let B=j.get(Z.name);if(!B||!Z.version)return!1;return UQ(Z.version,B)===1}))})}function z0($,W,j,Q){let Z=hY($,W),B=fY(Z,W),X=gY(Z.flatMap((H)=>H.upgradeSteps)),Y=mY(X),q={generatedAt:new Date().toISOString(),targetPackages:B,releases:Z,steps:X,autofixCount:Y.auto,manualCount:Y.manual,assistedCount:Y.assisted,agentPrompts:[]},A=kY(q,j,Q);return{...q,agentPrompts:A}}function fY($,W){let j=new Map(W.map((Z)=>[Z.name,Z.currentVersion])),Q=new Map;for(let Z of $)for(let B of Z.packages){let X=j.get(B.name),Y=Q.get(B.name);if(!Y){Q.set(B.name,{name:B.name,currentVersion:X,targetVersion:B.version});continue}if(B.version&&Y.targetVersion&&UQ(B.version,Y.targetVersion)===1)Y.targetVersion=B.version}return Array.from(Q.values()).sort((Z,B)=>Z.name.localeCompare(B.name))}var uY=process.env.CONTRACTSPEC_API_HOST??"api.contractspec.io",GW=`https://${uY}/schemas/contractsrc.json`;async function zW($,W){let{fs:j,logger:Q}=$,Z=k(W.workspaceRoot),B=R(W.workspaceRoot),X=F$(B);Q.info("Analyzing available upgrades...",{workspaceRoot:B,packageRoot:Z,packageManager:X});let Y=await dY(j,Z),q=await nY(j,Z),A=Y.length>0||q.length>0;return{packageManager:X,packages:Y,configUpgrades:q,hasUpgrades:A}}async function dY($,W){let j=$.join(W,"package.json");if(!await $.exists(j))return[];try{let Q=await $.readFile(j),Z=JSON.parse(Q),B=Z.dependencies??{},X=Z.devDependencies??{},Y=[],q={...B,...X};for(let[A,H]of Object.entries(q))if(A.startsWith("@contractspec/")||A==="contractspec"||A.startsWith("@lssm/"))Y.push({name:A,currentVersion:H,isDevDependency:!!X[A]});return Y}catch{return[]}}async function nY($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return[];try{let Q=await $.readFile(j),Z=JSON.parse(Q),B=[],X=Z.$schema;if(!X||X!==GW)B.push({key:"$schema",currentValue:X,suggestedValue:GW,isNew:!X});if(!Z.versioning)B.push({key:"versioning",currentValue:void 0,suggestedValue:JW(),isNew:!0});else if(Z.versioning.integrateWithChangesets===void 0)B.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!Z.hooks)B.push({key:"hooks",currentValue:void 0,suggestedValue:KW(),isNew:!0});if(!Z.release)B.push({key:"release",currentValue:void 0,suggestedValue:IQ(),isNew:!0});if(!Z.upgrade)B.push({key:"upgrade",currentValue:void 0,suggestedValue:OQ(),isNew:!0});return B}catch{return[]}}async function _Q($,W){let{fs:j,logger:Q}=$,Z=k(W.workspaceRoot);if(W.dryRun)Q.info("Dry run - no changes will be made");let B=j.join(Z,".contractsrc.json");if(!await j.exists(B))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let X=await j.readFile(B),Y=JSON.parse(X),q=0,A=Y.$schema;if(!A||A!==GW)Y.$schema=GW,q++;if(!Y.versioning)Y.versioning=JW(),q++;else{let H=Y.versioning;if(H.integrateWithChangesets===void 0)H.integrateWithChangesets=!1,q++}if(!Y.hooks)Y.hooks=KW(),q++;if(!Y.release)Y.release=IQ(),q++;if(!Y.upgrade)Y.upgrade=OQ(),q++;if(q===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!W.dryRun)await j.writeFile(B,JSON.stringify(Y,null,2)+`
1805
- `),Q.info("Configuration upgraded",{sectionsUpgraded:q});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:q,summary:W.dryRun?`Would upgrade ${q} config section(s)`:`Upgraded ${q} config section(s)`}}catch(X){let Y=X instanceof Error?X.message:String(X);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:Y,summary:`Failed to upgrade config: ${Y}`}}}function LQ($,W,j){let Q=j?W.map((Z)=>`${Z.name}@latest`).join(" "):W.map((Z)=>Z.name).join(" ");switch($){case"bun":return`bun add ${Q}`;case"pnpm":return`pnpm add ${Q}`;case"yarn":return`yarn add ${Q}`;default:return`npm install ${Q}`}}function JW(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function KW(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function IQ(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function OQ(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var rY="**/*.{ts,tsx,js,jsx,mjs,cjs}",wQ=lY.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Ij($,W){let{fs:j}=$,Q=k(W.workspaceRoot),Z=R(W.workspaceRoot),B=await pY(j,Q,Z),X=await oY(j,Q,Z,W.manifestPaths??B.manifestPaths),Y=await zW($,{workspaceRoot:Q,dryRun:W.dryRun}),q=[W.agentTarget??B.defaultAgentTarget??"codex"],A=z0(X.manifest,Y.packages.map((V)=>({name:V.name,currentVersion:V.currentVersion})),q,h$),H=iY(A,Y.packages,Y.configUpgrades);return{packageManager:Y.packageManager,manifestPath:X.path,plan:H,humanChecklist:aY(H)}}async function CQ($,W){let{fs:j,logger:Q}=$,Z=k(W.workspaceRoot),B=await Ij($,W),X=[];if(!W.dryRun){for(let q of B.plan.steps){if(q.level!=="auto")continue;for(let A of q.autofixes??[])if(await tY(j,Z,A))X.push(A.id)}Q.info("Applied guided upgrade autofixes",{count:X.length,workspaceRoot:Z})}let Y=B.plan.steps.filter((q)=>q.level!=="auto");return{success:!0,packagesUpgraded:X.filter((q)=>q.startsWith("pkg:")).length,configSectionsUpgraded:X.filter((q)=>q.startsWith("config:")).length,summary:W.dryRun?`Would apply ${B.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${X.length} deterministic upgrade autofix(es)`,appliedAutofixes:X,remainingSteps:Y,humanChecklist:B.humanChecklist,promptBundle:B.plan.agentPrompts[0],plan:B.plan,manifestPath:B.manifestPath}}async function oY($,W,j,Q){let Z=Q??["generated/releases/upgrade-manifest.json"],B=Array.from(new Set([W,j]));for(let X of Z){let Y=X.startsWith("/")?[X]:B.map((q)=>$.join(q,X));for(let q of Y){if(!await $.exists(q))continue;let A=bQ.parse(JSON.parse(await $.readFile(q)));return{path:q,manifest:A}}}return{manifest:bQ.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function pY($,W,j){for(let Q of Array.from(new Set([$.join(W,".contractsrc.json"),$.join(j,".contractsrc.json")]))){if(!await $.exists(Q))continue;try{let Z=JSON.parse(await $.readFile(Q)),B=cY.safeParse(Z);if(B.success)return{...wQ,...B.data.upgrade}}catch{continue}}return wQ}function iY($,W,j){let Q=[];for(let H of W){let V=$.targetPackages.find((G)=>G.name===H.name);if(!V?.targetVersion||V.targetVersion===H.currentVersion)continue;Q.push({id:`pkg:${H.name}`,kind:"package-json",title:`Update ${H.name}`,summary:`Update ${H.name} to ${V.targetVersion}`,packageName:H.name,dependencyType:H.isDevDependency?"devDependencies":"dependencies",from:H.currentVersion,to:V.targetVersion})}let Z=j.map((H)=>({id:`config:${H.key}`,kind:"contractsrc",title:`Update ${H.key}`,summary:`Update .contractsrc.json at ${H.key}`,configPath:H.key,value:H.suggestedValue})),B=[];if(Q.length>0)B.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:Q.map((H)=>`${H.packageName}: ${H.from??"current"} -> ${H.to??"latest"}`),packages:Q.map((H)=>H.packageName??""),autofixes:Q});if(Z.length>0)B.push({id:"upgrade-contractsrc-config",title:"Refresh .contractsrc.json defaults",summary:"Bring workspace release and upgrade config in line with current defaults.",level:"auto",instructions:Z.map((H)=>`${H.configPath} -> updated`),autofixes:Z});let X=[...B,...$.steps],Y=X.filter((H)=>H.level==="auto").length,q=X.filter((H)=>H.level==="assisted").length,A=X.filter((H)=>H.level==="manual").length;return{...$,steps:X,autofixCount:Y,assistedCount:q,manualCount:A,agentPrompts:z0({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((H)=>({name:H.name,currentVersion:H.currentVersion})),$.agentPrompts.map((H)=>H.agent),h$).agentPrompts}}function aY($){return $.steps.map((W)=>`${W.title}: ${W.summary}`)}async function tY($,W,j){switch(j.kind){case"package-json":return sY($,W,j);case"contractsrc":return eY($,W,j);case"import-rewrite":return $2($,W,j);case"codemod":return!1}}async function sY($,W,j){let Q=$.join(W,"package.json");if(!await $.exists(Q))return!1;let Z=JSON.parse(await $.readFile(Q)),B=j.dependencyType??"dependencies",X=Z[B]??{};if(!j.packageName||!j.to||!X[j.packageName])return!1;return X[j.packageName]=j.to,Z[B]=X,await $.writeFile(Q,JSON.stringify(Z,null,2)+`
1806
- `),!0}async function eY($,W,j){let Q=$.join(W,".contractsrc.json"),Z=await $.exists(Q)?JSON.parse(await $.readFile(Q)):{};if(!j.configPath)return!1;return W2(Z,j.configPath,j.value),await $.writeFile(Q,JSON.stringify(Z,null,2)+`
1807
- `),!0}async function $2($,W,j){if(!j.from||!j.to)return!1;let Q=await $.glob({pattern:j.path??rY,cwd:W,absolute:!0}),Z=!1;for(let B of Q){let X=await $.readFile(B);if(!X.includes(j.from))continue;await $.writeFile(B,X.split(j.from).join(j.to)),Z=!0}return Z}function W2($,W,j){let Q=W.split("."),Z=$;for(let X of Q.slice(0,-1)){let Y=Z[X];if(!Y||typeof Y!=="object"||Array.isArray(Y))Z[X]={};Z=Z[X]}let B=Q.at(-1);if(B)Z[B]=j}import{existsSync as Oj,mkdirSync as j2,readFileSync as Q2,renameSync as Z2,statSync as B2,writeFileSync as X2}from"fs";import{dirname as Y2,join as q2}from"path";var A2=".contractspec/verification-cache.json",EQ=1;class MQ{filePath;cache;isDirty=!1;constructor($,W){let j=W??process.cwd();this.filePath=$??q2(j,A2),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Oj(this.filePath))return;let $=Q2(this.filePath,"utf-8"),W=JSON.parse($);if(W.version!==EQ)return;for(let[j,Q]of Object.entries(W.entries))this.cache.set(j,Q)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=Y2(this.filePath);if(!Oj($))j2($,{recursive:!0});let W={version:EQ,entries:Object.fromEntries(this.cache.entries())},j=`${this.filePath}.tmp`;X2(j,JSON.stringify(W,null,2),"utf-8"),Z2(j,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,W){this.cache.set($,W),this.isDirty=!0,this.saveSync()}async delete($){let W=this.cache.delete($);if(W)this.isDirty=!0,this.saveSync();return W}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(Oj(this.filePath))$=B2(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function cO($,W){return new MQ($,W)}class NQ{cache=new Map;async get($){return this.cache.get($)??null}async set($,W){this.cache.set($,W)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[W,j]of this.cache.entries())$+=W.length*2,$+=JSON.stringify(j).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function rO(){return new NQ}class RQ{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let W=this.getStorageKey($);return this.store.get(W)??null}async set($,W){let j=this.getStorageKey($);if(await this.store.update(j,W),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let W=this.getStorageKey($),j=this.keyIndex.has($);if(j)await this.store.update(W,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return j}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let W=this.getStorageKey($);await this.store.update(W,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function pO($){return new RQ($)}import{createHash as H2}from"crypto";var DQ={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function FQ($){return H2("sha256").update($).digest("hex")}function xQ($){let W=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)W.push(`model:${$.aiModelVersion}`);return W.join("|")}function V2($){try{let W=$.split("|"),j=new Map;for(let X of W){let[Y,q]=X.split(":");if(Y&&q)j.set(Y,q)}let Q=j.get("spec"),Z=j.get("impl"),B=j.get("tier");if(!Q||!Z||!B)return null;return{specHash:Q,implHash:Z,tier:B,aiModelVersion:j.get("model")}}catch{return null}}function G2($,W){switch($){case"structure":return W.structureTtlMs;case"behavior":return W.behaviorTtlMs;case"ai_review":return W.aiTtlMs;default:return W.defaultTtlMs}}class TQ{storage;config;stats;constructor($,W={}){this.storage=$,this.config={...DQ,...W},this.stats={hits:0,misses:0}}createKey($,W,j,Q){return{specHash:FQ($),implHash:FQ(W),tier:j,aiModelVersion:j==="ai_review"?Q:void 0}}async lookup($){let W=xQ($),j=await this.storage.get(W);if(!j)return this.stats.misses++,{hit:!1,reason:"not_found"};if(j.meta.expiresAt){let Q=new Date(j.meta.expiresAt).getTime();if(Date.now()>Q)return this.stats.misses++,await this.storage.delete(W),{hit:!1,reason:"expired"}}if(j.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(j.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&j.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:j}}async store($,W,j={}){let Q=xQ($),Z=G2($.tier,this.config),B={key:$,result:W,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Z).toISOString(),dependencies:j.dependencies??[],specName:j.specName,implPath:j.implPath}};await this.storage.set(Q,B),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let W=await this.storage.keys(),j=0;for(let Q of W){let Z=await this.storage.get(Q);if(!Z)continue;if(Z.meta.dependencies.includes($))await this.storage.delete(Q),j++;if(Z.meta.specName===$||Z.meta.implPath===$)await this.storage.delete(Q),j++}return j}async invalidateForSpec($){let W=await this.storage.keys(),j=0;for(let Q of W){let Z=V2(Q);if(Z&&Z.specHash.startsWith($.substring(0,16)))await this.storage.delete(Q),j++}return j}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let W=[];for(let Q of $){let Z=await this.storage.get(Q);if(Z)W.push({key:Q,createdAt:new Date(Z.meta.createdAt).getTime()})}W.sort((Q,Z)=>Q.createdAt-Z.createdAt);let j=W.length-this.config.maxEntries;for(let Q=0;Q<j;Q++){let Z=W[Q];if(Z)await this.storage.delete(Z.key)}}}function Qb($,W){return new TQ($,W)}import{generateVerificationPrompt as z2}from"@contractspec/lib.contracts-spec/llm";function J2($){let W=$.match(/```json\n?([\s\S]*?)\n?```/);if(W?.[1])try{let q=JSON.parse(W[1]);return{compliant:q.passed??!1,confidence:(q.score??0)/100,findings:(q.issues??[]).map((A)=>({category:String(A.category??"semantic"),severity:String(A.severity??"warning"),message:String(A.message??""),location:A.location?String(A.location):void 0,suggestion:A.suggestion?String(A.suggestion):void 0})),rawResponse:$}}catch{}let j=[],Q=$.split(`
1808
- `),Z="info";for(let q of Q){let A=q.toLowerCase();if(A.includes("error")||A.includes("critical"))Z="error";else if(A.includes("warning")||A.includes("should"))Z="warning";else if(A.includes("info")||A.includes("note"))Z="info";let H=q.match(/^[-*\u2022]\s*(.+)$/),V=q.match(/^\d+\.\s*(.+)$/);if(H||V){let G=H?.[1]??V?.[1]??"";if(G.length>10)j.push({category:"semantic",severity:Z,message:G})}}let B=j.some((q)=>q.severity==="error"),X=!B,Y=B?0.3:j.length===0?0.9:0.7;return{compliant:X,confidence:Y,findings:j,rawResponse:$}}async function vQ($,W){if(!W.aiApiKey)return`\`\`\`json
2047
+ `)}function p$($,W){let j=W.targetPackages.map((A)=>`${A.name}: ${A.currentVersion??"unknown"} -> ${A.targetVersion??"latest"}`).join(`
2048
+ `);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",j||"- No package version targets were inferred.","","Required steps:",_9(W)].join(`
2049
+ `)}import{compareVersions as U9,countUpgradePlanStepLevels as AB,createAgentPromptBundles as QB,dedupeUpgradePlanSteps as ZB,sortReleaseManifest as z9}from"@contractspec/lib.contracts-spec";function XB($,W){if(W.length===0)return z9($);let j=new Map(W.map((A)=>[A.name,A.currentVersion??"0.0.0"]));return z9({...$,releases:$.releases.filter((A)=>A.packages.some((Q)=>{let Z=j.get(Q.name);if(!Z||!Q.version)return!1;return U9(Q.version,Z)===1}))})}function D0($,W,j,A){let Q=XB($,W),Z=YB(Q,W),X=ZB(Q.flatMap((H)=>H.upgradeSteps)),Y=AB(X),B={generatedAt:new Date().toISOString(),targetPackages:Z,releases:Q,steps:X,autofixCount:Y.auto,manualCount:Y.manual,assistedCount:Y.assisted,agentPrompts:[]},q=QB(B,j,A);return{...B,agentPrompts:q}}function YB($,W){let j=new Map(W.map((Q)=>[Q.name,Q.currentVersion])),A=new Map;for(let Q of $)for(let Z of Q.packages){let X=j.get(Z.name),Y=A.get(Z.name);if(!Y){A.set(Z.name,{name:Z.name,currentVersion:X,targetVersion:Z.version});continue}if(Z.version&&Y.targetVersion&&U9(Z.version,Y.targetVersion)===1)Y.targetVersion=Z.version}return Array.from(A.values()).sort((Q,Z)=>Q.name.localeCompare(Z.name))}async function gW($,W){let{fs:j,logger:A}=$,Q=f(W.workspaceRoot),Z=D(W.workspaceRoot),X=k$(Z);A.info("Analyzing available upgrades...",{workspaceRoot:Z,packageRoot:Q,packageManager:X});let Y=await BB(j,Q),B=await qB(j,Q,Z),q=Y.length>0||B.length>0;return{packageManager:X,packages:Y,configUpgrades:B,hasUpgrades:q}}async function BB($,W){let j=$.join(W,"package.json");if(!await $.exists(j))return[];try{let A=await $.readFile(j),Q=JSON.parse(A),Z=Q.dependencies??{},X=Q.devDependencies??{},Y=[],B={...Z,...X};for(let[q,H]of Object.entries(B))if(q.startsWith("@contractspec/")||q==="contractspec"||q.startsWith("@lssm/"))Y.push({name:q,currentVersion:H,isDevDependency:!!X[q]});return Y}catch{return[]}}async function qB($,W,j){let A=$.join(W,".contractsrc.json"),Q=Z0({configRoot:W,workspaceRoot:j});if(!await $.exists(A))return[];try{let Z=await $.readFile(A),X=JSON.parse(Z),Y=[],B=X.$schema;if(!B||B!==Q)Y.push({key:"$schema",currentValue:B,suggestedValue:Q,isNew:!B});if(!X.versioning)Y.push({key:"versioning",currentValue:void 0,suggestedValue:fW(),isNew:!0});else if(X.versioning.integrateWithChangesets===void 0)Y.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!X.hooks)Y.push({key:"hooks",currentValue:void 0,suggestedValue:uW(),isNew:!0});if(!X.release)Y.push({key:"release",currentValue:void 0,suggestedValue:S9(),isNew:!0});if(!X.upgrade)Y.push({key:"upgrade",currentValue:void 0,suggestedValue:I9(),isNew:!0});return Y}catch{return[]}}async function L9($,W){let{fs:j,logger:A}=$,Q=f(W.workspaceRoot),Z=D(W.workspaceRoot),X=Z0({configRoot:Q,workspaceRoot:Z});if(W.dryRun)A.info("Dry run - no changes will be made");let Y=j.join(Q,".contractsrc.json");if(!await j.exists(Y))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let B=await j.readFile(Y),q=JSON.parse(B),H=0,V=q.$schema;if(!V||V!==X)q.$schema=X,H++;if(!q.versioning)q.versioning=fW(),H++;else{let G=q.versioning;if(G.integrateWithChangesets===void 0)G.integrateWithChangesets=!1,H++}if(!q.hooks)q.hooks=uW(),H++;if(!q.release)q.release=S9(),H++;if(!q.upgrade)q.upgrade=I9(),H++;if(H===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!W.dryRun)await j.writeFile(Y,JSON.stringify(q,null,2)+`
2050
+ `),A.info("Configuration upgraded",{sectionsUpgraded:H});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:H,summary:W.dryRun?`Would upgrade ${H} config section(s)`:`Upgraded ${H} config section(s)`}}catch(B){let q=B instanceof Error?B.message:String(B);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:q,summary:`Failed to upgrade config: ${q}`}}}function O9($,W,j){let A=j?W.map((Q)=>`${Q.name}@latest`).join(" "):W.map((Q)=>Q.name).join(" ");switch($){case"bun":return`bun add ${A}`;case"pnpm":return`pnpm add ${A}`;case"yarn":return`yarn add ${A}`;default:return`npm install ${A}`}}function fW(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function uW(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function S9(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function I9(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var GB="**/*.{ts,tsx,js,jsx,mjs,cjs}",E9=VB.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function tj($,W){let{fs:j}=$,A=f(W.workspaceRoot),Q=D(W.workspaceRoot),Z=await bB(j,A,Q),X=await JB(j,A,Q,W.manifestPaths??Z.manifestPaths),Y=await gW($,{workspaceRoot:A,dryRun:W.dryRun}),B=[W.agentTarget??Z.defaultAgentTarget??"codex"],q=D0(X.manifest,Y.packages.map((V)=>({name:V.name,currentVersion:V.currentVersion})),B,p$),H=wB(q,Y.packages,Y.configUpgrades);return{packageManager:Y.packageManager,manifestPath:X.path,plan:H,humanChecklist:KB(H)}}async function N9($,W){let{fs:j,logger:A}=$,Q=f(W.workspaceRoot),Z=await tj($,W),X=[];if(!W.dryRun){for(let B of Z.plan.steps){if(B.level!=="auto")continue;for(let q of B.autofixes??[])if(await _B(j,Q,q))X.push(q.id)}A.info("Applied guided upgrade autofixes",{count:X.length,workspaceRoot:Q})}let Y=Z.plan.steps.filter((B)=>B.level!=="auto");return{success:!0,packagesUpgraded:X.filter((B)=>B.startsWith("pkg:")).length,configSectionsUpgraded:X.filter((B)=>B.startsWith("config:")).length,summary:W.dryRun?`Would apply ${Z.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${X.length} deterministic upgrade autofix(es)`,appliedAutofixes:X,remainingSteps:Y,humanChecklist:Z.humanChecklist,promptBundle:Z.plan.agentPrompts[0],plan:Z.plan,manifestPath:Z.manifestPath}}async function JB($,W,j,A){let Q=A??["generated/releases/upgrade-manifest.json"],Z=Array.from(new Set([W,j]));for(let X of Q){let Y=X.startsWith("/")?[X]:Z.map((B)=>$.join(B,X));for(let B of Y){if(!await $.exists(B))continue;let q=M9.parse(JSON.parse(await $.readFile(B)));return{path:B,manifest:q}}}return{manifest:M9.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function bB($,W,j){for(let A of Array.from(new Set([$.join(W,".contractsrc.json"),$.join(j,".contractsrc.json")]))){if(!await $.exists(A))continue;try{let Q=JSON.parse(await $.readFile(A)),Z=HB.safeParse(Q);if(Z.success)return{...E9,...Z.data.upgrade}}catch{continue}}return E9}function wB($,W,j){let A=[];for(let H of W){let V=$.targetPackages.find((G)=>G.name===H.name);if(!V?.targetVersion||V.targetVersion===H.currentVersion)continue;A.push({id:`pkg:${H.name}`,kind:"package-json",title:`Update ${H.name}`,summary:`Update ${H.name} to ${V.targetVersion}`,packageName:H.name,dependencyType:H.isDevDependency?"devDependencies":"dependencies",from:H.currentVersion,to:V.targetVersion})}let Q=j.map((H)=>({id:`config:${H.key}`,kind:"contractsrc",title:`Update ${H.key}`,summary:`Update .contractsrc.json at ${H.key}`,configPath:H.key,value:H.suggestedValue})),Z=[];if(A.length>0)Z.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:A.map((H)=>`${H.packageName}: ${H.from??"current"} -> ${H.to??"latest"}`),packages:A.map((H)=>H.packageName??""),autofixes:A});if(Q.length>0)Z.push({id:"upgrade-contractsrc-config",title:"Refresh .contractsrc.json defaults",summary:"Bring workspace release and upgrade config in line with current defaults.",level:"auto",instructions:Q.map((H)=>`${H.configPath} -> updated`),autofixes:Q});let X=[...Z,...$.steps],Y=X.filter((H)=>H.level==="auto").length,B=X.filter((H)=>H.level==="assisted").length,q=X.filter((H)=>H.level==="manual").length;return{...$,steps:X,autofixCount:Y,assistedCount:B,manualCount:q,agentPrompts:D0({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((H)=>({name:H.name,currentVersion:H.currentVersion})),$.agentPrompts.map((H)=>H.agent),p$).agentPrompts}}function KB($){return $.steps.map((W)=>`${W.title}: ${W.summary}`)}async function _B($,W,j){switch(j.kind){case"package-json":return zB($,W,j);case"contractsrc":return UB($,W,j);case"import-rewrite":return LB($,W,j);case"codemod":return!1}}async function zB($,W,j){let A=$.join(W,"package.json");if(!await $.exists(A))return!1;let Q=JSON.parse(await $.readFile(A)),Z=j.dependencyType??"dependencies",X=Q[Z]??{};if(!j.packageName||!j.to||!X[j.packageName])return!1;return X[j.packageName]=j.to,Q[Z]=X,await $.writeFile(A,JSON.stringify(Q,null,2)+`
2051
+ `),!0}async function UB($,W,j){let A=$.join(W,".contractsrc.json"),Q=await $.exists(A)?JSON.parse(await $.readFile(A)):{};if(!j.configPath)return!1;return OB(Q,j.configPath,j.value),await $.writeFile(A,JSON.stringify(Q,null,2)+`
2052
+ `),!0}async function LB($,W,j){if(!j.from||!j.to)return!1;let A=await $.glob({pattern:j.path??GB,cwd:W,absolute:!0}),Q=!1;for(let Z of A){let X=await $.readFile(Z);if(!X.includes(j.from))continue;await $.writeFile(Z,X.split(j.from).join(j.to)),Q=!0}return Q}function OB($,W,j){let A=W.split("."),Q=$;for(let X of A.slice(0,-1)){let Y=Q[X];if(!Y||typeof Y!=="object"||Array.isArray(Y))Q[X]={};Q=Q[X]}let Z=A.at(-1);if(Z)Q[Z]=j}import{existsSync as aj,mkdirSync as SB,readFileSync as IB,renameSync as MB,statSync as EB,writeFileSync as NB}from"fs";import{dirname as RB,join as CB}from"path";var DB=".contractspec/verification-cache.json",C9=1;class D9{filePath;cache;isDirty=!1;constructor($,W){let j=W??process.cwd();this.filePath=$??CB(j,DB),this.cache=new Map,this.loadSync()}loadSync(){try{if(!aj(this.filePath))return;let $=IB(this.filePath,"utf-8"),W=JSON.parse($);if(W.version!==C9)return;for(let[j,A]of Object.entries(W.entries))this.cache.set(j,A)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=RB(this.filePath);if(!aj($))SB($,{recursive:!0});let W={version:C9,entries:Object.fromEntries(this.cache.entries())},j=`${this.filePath}.tmp`;NB(j,JSON.stringify(W,null,2),"utf-8"),MB(j,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,W){this.cache.set($,W),this.isDirty=!0,this.saveSync()}async delete($){let W=this.cache.delete($);if(W)this.isDirty=!0,this.saveSync();return W}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(aj(this.filePath))$=EB(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function HM($,W){return new D9($,W)}class T9{cache=new Map;async get($){return this.cache.get($)??null}async set($,W){this.cache.set($,W)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[W,j]of this.cache.entries())$+=W.length*2,$+=JSON.stringify(j).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function GM(){return new T9}class F9{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let W=this.getStorageKey($);return this.store.get(W)??null}async set($,W){let j=this.getStorageKey($);if(await this.store.update(j,W),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let W=this.getStorageKey($),j=this.keyIndex.has($);if(j)await this.store.update(W,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return j}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let W=this.getStorageKey($);await this.store.update(W,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function bM($){return new F9($)}import{createHash as TB}from"crypto";var x9={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function y9($){return TB("sha256").update($).digest("hex")}function v9($){let W=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)W.push(`model:${$.aiModelVersion}`);return W.join("|")}function FB($){try{let W=$.split("|"),j=new Map;for(let X of W){let[Y,B]=X.split(":");if(Y&&B)j.set(Y,B)}let A=j.get("spec"),Q=j.get("impl"),Z=j.get("tier");if(!A||!Q||!Z)return null;return{specHash:A,implHash:Q,tier:Z,aiModelVersion:j.get("model")}}catch{return null}}function xB($,W){switch($){case"structure":return W.structureTtlMs;case"behavior":return W.behaviorTtlMs;case"ai_review":return W.aiTtlMs;default:return W.defaultTtlMs}}class m9{storage;config;stats;constructor($,W={}){this.storage=$,this.config={...x9,...W},this.stats={hits:0,misses:0}}createKey($,W,j,A){return{specHash:y9($),implHash:y9(W),tier:j,aiModelVersion:j==="ai_review"?A:void 0}}async lookup($){let W=v9($),j=await this.storage.get(W);if(!j)return this.stats.misses++,{hit:!1,reason:"not_found"};if(j.meta.expiresAt){let A=new Date(j.meta.expiresAt).getTime();if(Date.now()>A)return this.stats.misses++,await this.storage.delete(W),{hit:!1,reason:"expired"}}if(j.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(j.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&j.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:j}}async store($,W,j={}){let A=v9($),Q=xB($.tier,this.config),Z={key:$,result:W,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Q).toISOString(),dependencies:j.dependencies??[],specName:j.specName,implPath:j.implPath}};await this.storage.set(A,Z),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let W=await this.storage.keys(),j=0;for(let A of W){let Q=await this.storage.get(A);if(!Q)continue;if(Q.meta.dependencies.includes($))await this.storage.delete(A),j++;if(Q.meta.specName===$||Q.meta.implPath===$)await this.storage.delete(A),j++}return j}async invalidateForSpec($){let W=await this.storage.keys(),j=0;for(let A of W){let Q=FB(A);if(Q&&Q.specHash.startsWith($.substring(0,16)))await this.storage.delete(A),j++}return j}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let W=[];for(let A of $){let Q=await this.storage.get(A);if(Q)W.push({key:A,createdAt:new Date(Q.meta.createdAt).getTime()})}W.sort((A,Q)=>A.createdAt-Q.createdAt);let j=W.length-this.config.maxEntries;for(let A=0;A<j;A++){let Q=W[A];if(Q)await this.storage.delete(Q.key)}}}function IM($,W){return new m9($,W)}import{generateVerificationPrompt as yB}from"@contractspec/lib.contracts-spec/llm";function vB($){let W=$.match(/```json\n?([\s\S]*?)\n?```/);if(W?.[1])try{let B=JSON.parse(W[1]);return{compliant:B.passed??!1,confidence:(B.score??0)/100,findings:(B.issues??[]).map((q)=>({category:String(q.category??"semantic"),severity:String(q.severity??"warning"),message:String(q.message??""),location:q.location?String(q.location):void 0,suggestion:q.suggestion?String(q.suggestion):void 0})),rawResponse:$}}catch{}let j=[],A=$.split(`
2053
+ `),Q="info";for(let B of A){let q=B.toLowerCase();if(q.includes("error")||q.includes("critical"))Q="error";else if(q.includes("warning")||q.includes("should"))Q="warning";else if(q.includes("info")||q.includes("note"))Q="info";let H=B.match(/^[-*\u2022]\s*(.+)$/),V=B.match(/^\d+\.\s*(.+)$/);if(H||V){let G=H?.[1]??V?.[1]??"";if(G.length>10)j.push({category:"semantic",severity:Q,message:G})}}let Z=j.some((B)=>B.severity==="error"),X=!Z,Y=Z?0.3:j.length===0?0.9:0.7;return{compliant:X,confidence:Y,findings:j,rawResponse:$}}async function P9($,W){if(!W.aiApiKey)return`\`\`\`json
1809
2054
  {
1810
2055
  "passed": true,
1811
2056
  "score": 50,
@@ -1822,7 +2067,7 @@ Do not include markdown formatting or explanations, just the JSON.
1822
2067
  ],
1823
2068
  "summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
1824
2069
  }
1825
- \`\`\``;try{let j=W.aiProvider??"anthropic";if(j==="anthropic"){let{anthropic:Q}=await import("@ai-sdk/anthropic"),{generateText:Z}=await import("ai");return(await Z({model:Q("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(j==="openai"){let{openai:Q}=await import("@ai-sdk/openai"),{generateText:Z}=await import("ai");return(await Z({model:Q("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${j}`)}catch(j){return`\`\`\`json
2070
+ \`\`\``;try{let j=W.aiProvider??"anthropic";if(j==="anthropic"){let{anthropic:A}=await import("@ai-sdk/anthropic"),{generateText:Q}=await import("ai");return(await Q({model:A("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(j==="openai"){let{openai:A}=await import("@ai-sdk/openai"),{generateText:Q}=await import("ai");return(await Q({model:A("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${j}`)}catch(j){return`\`\`\`json
1826
2071
  {
1827
2072
  "passed": false,
1828
2073
  "score": 0,
@@ -1831,7 +2076,7 @@ Do not include markdown formatting or explanations, just the JSON.
1831
2076
  ],
1832
2077
  "summary": "AI verification encountered an error"
1833
2078
  }
1834
- \`\`\``}}async function J0($,W={}){let{spec:j,implementationCode:Q,implementationPath:Z}=$,B=Date.now(),X=z2(j,Q),Y=await vQ(X.taskPrompt,W),q=J2(Y),A=q.findings.map((z)=>({severity:z.severity,category:"semantic",message:z.message,location:z.location?{file:z.location}:Z?{file:Z}:void 0,suggestion:z.suggestion})),H=Math.round(q.confidence*100),V=q.compliant,G=q.findings.filter((z)=>z.suggestion).map((z)=>z.suggestion);return{tier:"ai_review",passed:V,score:H,issues:A,suggestions:G,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:V?1:0}},meta:{specName:j.meta.key,specVersion:j.meta.version,implementationPath:Z??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-B}}}function UW($){let{spec:W,implementationCode:j,implementationPath:Q}=$,Z=Date.now(),B=[];if(j.includes("console.log"))B.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(j.includes("// TODO")||j.includes("// FIXME"))B.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(W.policy.auth!=="anonymous"&&!j.includes("auth"))B.push({severity:"warning",category:"semantic",message:`Spec requires ${W.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let X=B.filter((q)=>q.severity==="error").length===0?80:40,Y=B.filter((q)=>q.severity==="error").length===0;return{tier:"ai_review",passed:Y,score:X,issues:B,suggestions:B.filter((q)=>q.suggestion).map((q)=>q.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Y?1:0}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:Q??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Z}}}function K2($,W){return`You are analyzing a code implementation against its specification.
2079
+ \`\`\``}}async function T0($,W={}){let{spec:j,implementationCode:A,implementationPath:Q}=$,Z=Date.now(),X=yB(j,A),Y=await P9(X.taskPrompt,W),B=vB(Y),q=B.findings.map((J)=>({severity:J.severity,category:"semantic",message:J.message,location:J.location?{file:J.location}:Q?{file:Q}:void 0,suggestion:J.suggestion})),H=Math.round(B.confidence*100),V=B.compliant,G=B.findings.filter((J)=>J.suggestion).map((J)=>J.suggestion);return{tier:"ai_review",passed:V,score:H,issues:q,suggestions:G,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:V?1:0}},meta:{specName:j.meta.key,specVersion:j.meta.version,implementationPath:Q??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Z}}}function dW($){let{spec:W,implementationCode:j,implementationPath:A}=$,Q=Date.now(),Z=[];if(j.includes("console.log"))Z.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(j.includes("// TODO")||j.includes("// FIXME"))Z.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(W.policy.auth!=="anonymous"&&!j.includes("auth"))Z.push({severity:"warning",category:"semantic",message:`Spec requires ${W.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let X=Z.filter((B)=>B.severity==="error").length===0?80:40,Y=Z.filter((B)=>B.severity==="error").length===0;return{tier:"ai_review",passed:Y,score:X,issues:Z,suggestions:Z.filter((B)=>B.suggestion).map((B)=>B.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Y?1:0}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Q}}}function mB($,W){return`You are analyzing a code implementation against its specification.
1835
2080
 
1836
2081
  ## Spec Schema Fields
1837
2082
  ${$}
@@ -1878,42 +2123,42 @@ Match types:
1878
2123
  - "compatible": Semantically similar (e.g., "email" vs "emailAddress")
1879
2124
  - "mismatch": Different meaning despite similar naming
1880
2125
  - "missing": Spec field not found in implementation
1881
- `}function U2($){let W=[],j=(Q,Z)=>{try{let X=Q?._def?.shape;if(X&&typeof X==="function"){let Y=X();for(let[q,A]of Object.entries(Y)){let V=A?._def?.typeName??"unknown";W.push(`- ${q}: ${String(V).replace("Zod","").toLowerCase()} (${Z})`)}}}catch{W.push(`- [unable to extract ${Z} fields]`)}};if($.io.input)j($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))j($.io.output,"output");if(W.length===0)return"- [no schema fields could be extracted]";return W.join(`
1882
- `)}function _2($){let W=$.match(/```json\n?([\s\S]*?)\n?```/);if(W?.[1])try{let j=JSON.parse(W[1]);return{fieldMappings:(j.fieldMappings??[]).map((Q)=>({specField:String(Q.specField??""),specType:String(Q.specType??"unknown"),implementationField:Q.implementationField?String(Q.implementationField):void 0,implementationType:Q.implementationType?String(Q.implementationType):void 0,match:Q.match??"missing",aiConfidence:typeof Q.aiConfidence==="number"?Q.aiConfidence:0.5,suggestion:Q.suggestion?String(Q.suggestion):void 0})),intentAlignment:{score:typeof j.intentAlignment?.score==="number"?j.intentAlignment.score:50,issues:Array.isArray(j.intentAlignment?.issues)?j.intentAlignment.issues:[],suggestions:Array.isArray(j.intentAlignment?.suggestions)?j.intentAlignment.suggestions:[]},semanticIssues:(j.semanticIssues??[]).map((Q)=>({category:String(Q.category??"semantic"),severity:Q.severity??"warning",message:String(Q.message??""),suggestion:Q.suggestion?String(Q.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function yQ($,W={}){let{spec:j,implementationCode:Q}=$,Z=U2(j),B=K2(Z,Q),X=await vQ(B,W);return _2(X)}async function L2($,W={}){let{spec:j,implementationCode:Q,implementationPath:Z}=$,B=Date.now(),X=await J0($,W),Y;if(W.aiApiKey)try{Y=await yQ($,W)}catch{}if(Y){let q=[];for(let G of Y.fieldMappings)if(G.match==="missing")q.push({severity:"error",category:"semantic",message:`Missing field: '${G.specField}' (${G.specType}) not found in implementation`,suggestion:G.suggestion??`Add field '${G.specField}' to implementation`});else if(G.match==="mismatch")q.push({severity:"warning",category:"semantic",message:`Field mismatch: '${G.specField}' has incorrect implementation as '${G.implementationField}'`,suggestion:G.suggestion});else if(G.match==="compatible"&&G.aiConfidence<0.8)q.push({severity:"info",category:"semantic",message:`Field naming: '${G.specField}' implemented as '${G.implementationField}' (compatible but not exact)`,suggestion:G.suggestion});for(let G of Y.intentAlignment.issues)q.push({severity:"warning",category:"semantic",message:G});for(let G of Y.semanticIssues)q.push({severity:G.severity,category:"semantic",message:G.message,suggestion:G.suggestion});X.issues=[...X.issues,...q];let A=Y.fieldMappings.length,H=Y.fieldMappings.filter((G)=>G.match==="exact"||G.match==="compatible").length;if(A>0){let G=Math.round(H/A*100);X.score=Math.round((X.score+G)/2),X.coverage.fields={total:A,implemented:H}}if(q.some((G)=>G.severity==="error"))X.passed=!1;X.suggestions=[...X.suggestions,...Y.intentAlignment.suggestions]}return X.meta={...X.meta,duration:Date.now()-B},X}import{isEmitDeclRef as I2}from"@contractspec/lib.contracts-spec/operations";function O2($,W){let j=[...W.given,...W.when,...W.then].flatMap((A)=>A.toLowerCase().split(/\s+/).filter((H)=>H.length>3)),Q=$.toLowerCase(),Z=j.filter((A)=>Q.includes(A)),B=j.length>0?Z.length/j.length:0,X=W.key.toLowerCase().replace(/\s+/g,""),Y=Q.includes(X)||Q.includes(`test('${W.key.toLowerCase()}'`)||Q.includes(`it('${W.key.toLowerCase()}'`)||Q.includes(`describe('${W.key.toLowerCase()}'`),q=B>=0.3||Y;return{name:W.key,type:"scenario",passed:q,expected:`Given: ${W.given.join("; ")}; When: ${W.when.join("; ")}; Then: ${W.then.join("; ")}`,details:q?void 0:`Scenario keywords not found in implementation (${Math.round(B*100)}% coverage)`}}function b2($,W){let j=JSON.stringify(W.input),Q=JSON.stringify(W.output),Z=PQ(W.input),B=PQ(W.output),X=$.toLowerCase(),Y=Z.filter((z)=>X.includes(z.toLowerCase())),q=B.filter((z)=>X.includes(z.toLowerCase())),A=Z.length>0?Y.length/Z.length:1,H=B.length>0?q.length/B.length:1,V=(A+H)/2,G=V>=0.2;return{name:W.key,type:"example",passed:G,expected:`Input: ${j.slice(0,100)}...; Output: ${Q.slice(0,100)}...`,details:G?void 0:`Example values not found in implementation (${Math.round(V*100)}% coverage)`}}function PQ($){let W=[];function j(Q){if(typeof Q==="string"&&Q.length>2)W.push(Q);else if(Array.isArray(Q))Q.forEach(j);else if(Q&&typeof Q==="object")Object.values(Q).forEach(j)}return j($),W}function w2($,W,j){let Q=$.includes(W),Z=j.http?$.includes(String(j.http)):!0,B=j.when.toLowerCase().split(/\s+/).filter((H)=>H.length>3),X=$.toLowerCase(),Y=B.filter((H)=>X.includes(H)),q=B.length>0?Y.length/B.length:1,A=Q&&(Z||q>=0.3);return{name:`Error: ${W}`,type:"error",passed:A,expected:`When: ${j.when}; Return: ${W} (HTTP ${j.http??400})`,details:A?void 0:!Q?`Error code '${W}' not found in implementation`:"Error condition not properly implemented"}}function C2($,W){let j=W.sideEffects?.emits??[],Q=[];for(let Z of j){let B=I2(Z)?Z.ref.key:Z.key,X=Z.when,Y=X.toLowerCase().split(/\s+/).filter((G)=>G.length>3),q=$.toLowerCase(),A=q.includes(B.toLowerCase()),H=Y.filter((G)=>q.includes(G)),V=Y.length>0?H.length/Y.length:1;Q.push({name:`Event: ${B}`,type:"scenario",passed:A&&V>=0.3,expected:`Emit ${B} when: ${X}`,details:!A?`Event '${B}' not found`:V<0.3?"Event condition not properly implemented":void 0})}return Q}function S2($,W){if(W.policy.idempotent===void 0)return null;if(!W.policy.idempotent)return null;let j=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],Q=$.toLowerCase(),Z=j.some((B)=>Q.includes(B));return{name:"Idempotency",type:"scenario",passed:Z,expected:"Operation should be idempotent (safe to retry)",details:Z?void 0:"No idempotency pattern found for idempotent operation"}}function _W($){let{spec:W,implementationCode:j,implementationPath:Q}=$,Z=Date.now(),B=[];for(let J of W.acceptance?.scenarios??[])B.push(O2(j,J));for(let J of W.acceptance?.examples??[])B.push(b2(j,J));for(let[J,K]of Object.entries(W.io.errors??{}))B.push(w2(j,J,K));B.push(...C2(j,W));let X=S2(j,W);if(X)B.push(X);let Y=B.filter((J)=>!J.passed).map((J)=>({severity:J.type==="error"?"error":"warning",category:J.type==="scenario"?"scenario":J.type==="example"?"scenario":"error_handling",message:J.details??`${J.type} not covered: ${J.name}`,location:Q?{file:Q}:void 0,suggestion:J.expected?`Expected: ${J.expected}`:void 0})),q=B.filter((J)=>J.type==="scenario"),A=B.filter((J)=>J.type==="error"),H=B.filter((J)=>J.passed).length,V=B.length>0?Math.round(H/B.length*100):100,G=Y.filter((J)=>J.severity==="error").length===0,z=B.filter((J)=>!J.passed&&J.expected).map((J)=>`${J.name}: ${J.expected}`);return{tier:"behavior",passed:G,score:V,issues:Y,suggestions:z,coverage:{scenarios:{total:q.length,covered:q.filter((J)=>J.passed).length},errors:{total:A.length,handled:A.filter((J)=>J.passed).length},fields:{total:B.length,implemented:H}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:Q??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Z}}}import{isEmitDeclRef as E2}from"@contractspec/lib.contracts-spec/operations";function M2($){let W=/export\s+(async\s+)?function\s+\w+/.test($)||/export\s+const\s+\w+\s*=\s*(async\s*)?\(/.test($)||/export\s+default\s+(async\s+)?function/.test($)||/export\s+\{\s*\w+/.test($);return{name:"handler_export",passed:W,details:W?void 0:"No exported handler function found",suggestion:"Export a function that handles the operation: export async function handle(...) { }"}}function N2($){if(!$)return!1;let W=$.replace(/\\/g,"/");return W.includes("/packages/libs/contracts-spec/src/")||W.includes("/packages/libs/contracts-integrations/src/")||W.includes("/packages/libs/contracts-runtime-")}function R2($,W){if(N2(W))return{name:"contracts_import",passed:!0};let j=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:j,details:j?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function D2($,W){if(!(W.io.input!==null||W.io.output!==null))return{name:"schema_import",passed:!0};let Q=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:Q,details:Q?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function F2($){let W=/:\s*any\b|as\s+any\b|<any>/,j=$.split(`
1883
- `),Q=[];for(let Z=0;Z<j.length;Z++){let B=j[Z]??"";if(B.trim().startsWith("//")||B.trim().startsWith("*"))continue;if(W.test(B))Q.push(Z+1)}return{name:"no_any_type",passed:Q.length===0,details:Q.length>0?`Found 'any' type on lines: ${Q.slice(0,5).join(", ")}${Q.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function x2($,W){let j=W.io.errors;if(!j||Object.keys(j).length===0)return{name:"error_handling",passed:!0};let Q=Object.keys(j),Z=[];for(let B of Q)if(!$.includes(B))Z.push(B);return{name:"error_handling",passed:Z.length===0,details:Z.length>0?`Missing error handling for: ${Z.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function T2($,W){let j=W.sideEffects?.emits;if(!j||j.length===0)return{name:"event_emission",passed:!0};let Q=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),Z=j.map((X)=>{if(E2(X))return X.ref.key;return X.key}),B=Z.filter((X)=>$.includes(X));return{name:"event_emission",passed:Q&&B.length>0,details:!Q?"No event emission pattern found":B.length===0?`Events not referenced: ${Z.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function v2($,W){if(!W.io.input)return{name:"input_validation",passed:!0};let j=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:j,details:j?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function y2($,W){let j=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(W.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:j,details:j?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function K0($){let{spec:W,implementationCode:j,implementationPath:Q}=$,Z=Date.now(),B=[M2(j),R2(j,Q),D2(j,W),F2(j),x2(j,W),T2(j,W),v2(j,W),y2(j,W)],X=B.filter((z)=>!z.passed).map((z)=>({severity:z.name==="no_any_type"?"warning":"error",category:z.name.includes("import")?"import":z.name.includes("export")?"export":"type",message:z.details??`Check failed: ${z.name}`,location:Q?{file:Q}:void 0,suggestion:z.suggestion})),Y=B.filter((z)=>z.passed).length,q=Math.round(Y/B.length*100),A=X.filter((z)=>z.severity==="error").length===0,H=B.filter((z)=>!z.passed&&z.suggestion).map((z)=>z.suggestion),V=Object.keys(W.io.errors??{}).length,G=B.find((z)=>z.name==="error_handling")?.passed?V:0;return{tier:"structure",passed:A,score:q,issues:X,suggestions:H,coverage:{scenarios:{total:0,covered:0},errors:{total:V,handled:G},fields:{total:B.length,implemented:Y}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:Q??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Z}}}var P2={verbose:!1},m2=["structure","behavior","ai_review"];class LW{config;constructor($={}){this.config={...P2,...$}}async verify($,W,j={}){let Q=Date.now(),Z=new Map,B=[],X={spec:$,implementationCode:W},Y=j.tiers??["structure","behavior"];for(let G of m2){if(!Y.includes(G))continue;let z;switch(G){case"structure":z=K0(X);break;case"behavior":z=_W(X);break;case"ai_review":if(this.config.aiApiKey)z=await J0(X,this.config);else z=UW(X);break;default:continue}if(Z.set(G,z),B.push(...z.issues),j.failFast&&!z.passed)break}let q=Array.from(Z.values()),A=q.every((G)=>G.passed),H=q.length>0?Math.round(q.reduce((G,z)=>G+z.score,0)/q.length):100,V=this.generateSummary(q,B);return{passed:A,score:H,reports:Z,allIssues:B,summary:V,duration:Date.now()-Q}}verifyStructure($,W,j){return K0({spec:$,implementationCode:W,implementationPath:j})}verifyBehavior($,W,j){return _W({spec:$,implementationCode:W,implementationPath:j})}async verifyAI($,W,j){let Q={spec:$,implementationCode:W,implementationPath:j};if(this.config.aiApiKey)return J0(Q,this.config);return UW(Q)}quickVerify($,W){return K0({spec:$,implementationCode:W})}formatAsMarkdown($){let W=[];W.push("# Verification Report"),W.push(""),W.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),W.push(`**Score:** ${$.score}/100`),W.push(`**Duration:** ${$.duration}ms`),W.push("");for(let[Q,Z]of $.reports){if(W.push(`## ${this.formatTierName(Q)}`),W.push(""),W.push(`**Status:** ${Z.passed?"\u2713 Passed":"\u2717 Failed"}`),W.push(`**Score:** ${Z.score}/100`),W.push(""),Z.issues.length>0){W.push("### Issues"),W.push("");for(let B of Z.issues){let X=B.severity==="error"?"\u274C":B.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(W.push(`${X} **${B.category}**: ${B.message}`),B.suggestion)W.push(` - Suggestion: ${B.suggestion}`)}W.push("")}if(Z.coverage.scenarios.total>0)W.push(`**Scenarios:** ${Z.coverage.scenarios.covered}/${Z.coverage.scenarios.total}`);if(Z.coverage.errors.total>0)W.push(`**Errors handled:** ${Z.coverage.errors.handled}/${Z.coverage.errors.total}`);W.push("")}let j=Array.from($.reports.values()).flatMap((Q)=>Q.suggestions);if(j.length>0){W.push("## Suggestions"),W.push("");for(let Q of j.slice(0,10))W.push(`- ${Q}`);if(j.length>10)W.push(`- ... and ${j.length-10} more`);W.push("")}return W.join(`
1884
- `)}configure($){this.config={...this.config,...$}}generateSummary($,W){let j=[],Q=$.every((q)=>q.passed),Z=$.length>0?Math.round($.reduce((q,A)=>q+A.score,0)/$.length):100;j.push(Q?"\u2713 Verification passed":"\u2717 Verification failed"),j.push(`Score: ${Z}/100`),j.push("");for(let q of $){let A=q.passed?"\u2713":"\u2717";j.push(`${A} ${q.tier}: ${q.score}/100`)}j.push("");let B=W.filter((q)=>q.severity==="error"),X=W.filter((q)=>q.severity==="warning"),Y=W.filter((q)=>q.severity==="info");if(B.length>0)j.push(`Errors: ${B.length}`);if(X.length>0)j.push(`Warnings: ${X.length}`);if(Y.length>0)j.push(`Info: ${Y.length}`);return j.join(`
1885
- `)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function k2($){return new LW($)}var g2=new LW;var W6={};P(W6,{renderUpgradePrompt:()=>h$,renderUpgradeChecklist:()=>JQ,renderPatchNotes:()=>_j,renderMigrationGuide:()=>zQ,renderMaintainerSummary:()=>GQ,renderCustomerPatchNote:()=>PY,renderCustomerGuide:()=>Lj,parseConventionalCommit:()=>bW,isConventionalCommit:()=>l2,initReleaseArtifacts:()=>tQ,getHighestBumpType:()=>wj,getBumpTypeFromCommit:()=>bj,generateChangelogs:()=>iQ,formatKeepAChangelog:()=>U0,formatConventionalChangelog:()=>kQ,formatChangelogJson:()=>IW,filterCommitsByScope:()=>r2,filterBumpableCommits:()=>o2,commitsToChangeEntries:()=>Cj,commitToChangeEntry:()=>hQ,checkReleaseArtifacts:()=>eQ,buildReleaseArtifacts:()=>sQ,applyVersionBump:()=>pQ,analyzeVersionsFromCommits:()=>CW,analyzeVersions:()=>_0,DEFAULT_COMMIT_TYPE_MAP:()=>OW});import{basename as h2,dirname as f2}from"path";function U0($){let W=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],j=[...$].sort((Q,Z)=>gQ(Q.version,Z.version));for(let Q of j){W.push(`## [${Q.version}] - ${Q.date}`),W.push("");let Z=Q.changes.filter((V)=>V.type==="added"),B=Q.changes.filter((V)=>V.type==="changed"),X=Q.changes.filter((V)=>V.type==="deprecated"),Y=Q.changes.filter((V)=>V.type==="removed"),q=Q.changes.filter((V)=>V.type==="fixed"),A=Q.changes.filter((V)=>V.type==="security"),H=Q.breakingChanges??Q.changes.filter((V)=>V.type==="breaking");if(H.length>0)W.push("### \u26A0\uFE0F Breaking Changes"),H.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Z.length>0)W.push("### Added"),Z.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(B.length>0)W.push("### Changed"),B.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(X.length>0)W.push("### Deprecated"),X.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Y.length>0)W.push("### Removed"),Y.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(q.length>0)W.push("### Fixed"),q.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(A.length>0)W.push("### Security"),A.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("")}return W.join(`
1886
- `)}function kQ($){let W=["# Changelog",""],j=[...$].sort((Q,Z)=>gQ(Q.version,Z.version));for(let Q of j){let Z=Q.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":Q.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";W.push(`## ${Q.version} (${Q.date}) - ${Z}`),W.push("");let B={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let X of Q.changes){let Y=B[X.type]??"chore",q=X.path?`(${X.path})`:"",A=X.type==="breaking"?"!":"";W.push(`- **${Y}${q}${A}**: ${X.description}`)}W.push("")}return W.join(`
1887
- `)}function IW($,W){let j=$.analyses.filter((B)=>B.needsBump),Q=new Date().toISOString(),Z=Q.split("T")[0]??"";return{generatedAt:Q,baseline:W,specs:j.map((B)=>({key:B.specKey,version:B.suggestedVersion,path:B.specPath,entries:[{version:B.suggestedVersion,date:Z,bumpType:B.bumpType,changes:B.changes,breakingChanges:B.changes.filter((X)=>X.type==="breaking")}]})),libraries:d2(j,Z)}}function u2($){let W=$.split("/"),j=W.lastIndexOf("packages");if(j>=0&&j+2<W.length)return W.slice(0,j+3).join("/");return f2($)}var mQ={major:3,minor:2,patch:1};function d2($,W){let j=new Map;for(let Q of $){let Z=u2(Q.specPath),B=j.get(Z);if(B)B.push(Q);else j.set(Z,[Q])}return Array.from(j.entries()).flatMap(([Q,Z])=>{let B=Z[0];if(!B)return[];let X=Z.reduce((Y,q)=>{return(mQ[q.bumpType]??0)>(mQ[Y.bumpType]??0)?q:Y},B);return[{name:h2(Q),path:Q,version:X.suggestedVersion,entries:[{version:X.suggestedVersion,date:W,bumpType:X.bumpType,changes:Z.flatMap((Y)=>Y.changes),breakingChanges:Z.flatMap((Y)=>Y.changes).filter((Y)=>Y.type==="breaking")}]}]})}function gQ($,W){let j=(B)=>{return B.split(".").map((Y)=>parseInt(Y,10)||0)},Q=j($),Z=j(W);for(let B=0;B<3;B++){let X=Q[B]??0,Y=Z[B]??0;if(X!==Y)return Y-X}return 0}var OW={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},n2=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,c2=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function bW($){let W=$.split(`
1888
- `),j=W[0]?.trim();if(!j)return null;let Q=j.match(n2);if(!Q)return null;let[,Z,B,X,Y]=Q;if(!Z||!Y)return null;let q=W.slice(1).join(`
1889
- `).trim()||void 0,A=q?.match(c2),H=A?.[1];return{type:Z.toLowerCase(),scope:B?.toLowerCase(),breaking:!!X||!!A,description:Y.trim(),body:q,breakingDescription:H,raw:$}}function l2($){return bW($)!==null}function bj($,W=OW){if($.breaking)return"major";return W[$.type]??null}function wj($,W=OW){let j=["major","minor","patch"],Q=null;for(let Z of $){let B=bj(Z,W);if(!B)continue;if(!Q){Q=B;continue}let X=j.indexOf(Q);if(j.indexOf(B)<X)Q=B}return Q}function hQ($){if($.breaking)return{type:"breaking",description:$.breakingDescription??$.description,path:$.scope};switch($.type){case"feat":return{type:"added",description:$.description,path:$.scope};case"fix":return{type:"fixed",description:$.description,path:$.scope};case"deprecate":return{type:"deprecated",description:$.description,path:$.scope};case"remove":return{type:"removed",description:$.description,path:$.scope};case"security":return{type:"security",description:$.description,path:$.scope};default:return{type:"changed",description:$.description,path:$.scope}}}function Cj($){return $.map(hQ)}function r2($,W){return $.filter((j)=>j.scope?.toLowerCase()===W.toLowerCase())}function o2($,W=OW){return $.filter((j)=>bj(j,W)!==null)}import{GeneratedReleaseManifestSchema as V3}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as G3,DEFAULT_CONTRACTSRC as z3}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";import{ReleaseCapsuleSchema as fQ}from"@contractspec/lib.contracts-spec";import{dump as p2,load as i2}from"js-yaml";var a2=".changeset/*.md",t2=".changeset/*.release.yaml",s2=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,e2=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function $3($,W){return(await $.glob({pattern:a2,cwd:W,absolute:!0})).filter((Q)=>$.basename(Q)!=="README.md")}async function Sj($,W){let j=await $3($,W),Q=[];for(let Z of j){let B=await $.readFile(Z);Q.push(W3($.basename(Z),B))}return Q}async function Ej($,W,j){let Q=await $.glob({pattern:t2,cwd:W,absolute:!0}),Z=new Map(j.map((X)=>[X.slug,X.packages])),B=new Map;for(let X of Q){let Y=$.basename(X).replace(/\.release\.yaml$/,""),q=i2(await $.readFile(X)),A=j3(q,Y,Z.get(Y)??[]);B.set(Y,A)}return B}async function Mj($,W){let j=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:W,absolute:!0}),Q=[];for(let Z of j){let B=JSON.parse(await $.readFile(Z));if(!B.name||!B.version||B.private===!0)continue;let X=$.relative(W,$.dirname(Z))||".";Q.push({name:B.name,dir:X,version:B.version})}return Q.sort((Z,B)=>Z.dir.localeCompare(B.dir))}function uQ($,W){let j=new Set;for(let Q of $){let Z=W.find((B)=>B.dir==="."?!Q.startsWith("packages/"):Q===B.dir||Q.startsWith(`${B.dir}/`));if(Z)j.add(Z.name)}return Array.from(j).sort((Q,Z)=>Q.localeCompare(Z))}function dQ($,W){return`---
1890
- ${W.map((Q)=>`"${Q.name}": ${Q.releaseType}`).join(`
2126
+ `}function PB($){let W=[],j=(A,Q)=>{try{let X=A?._def?.shape;if(X&&typeof X==="function"){let Y=X();for(let[B,q]of Object.entries(Y)){let V=q?._def?.typeName??"unknown";W.push(`- ${B}: ${String(V).replace("Zod","").toLowerCase()} (${Q})`)}}}catch{W.push(`- [unable to extract ${Q} fields]`)}};if($.io.input)j($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))j($.io.output,"output");if(W.length===0)return"- [no schema fields could be extracted]";return W.join(`
2127
+ `)}function kB($){let W=$.match(/```json\n?([\s\S]*?)\n?```/);if(W?.[1])try{let j=JSON.parse(W[1]);return{fieldMappings:(j.fieldMappings??[]).map((A)=>({specField:String(A.specField??""),specType:String(A.specType??"unknown"),implementationField:A.implementationField?String(A.implementationField):void 0,implementationType:A.implementationType?String(A.implementationType):void 0,match:A.match??"missing",aiConfidence:typeof A.aiConfidence==="number"?A.aiConfidence:0.5,suggestion:A.suggestion?String(A.suggestion):void 0})),intentAlignment:{score:typeof j.intentAlignment?.score==="number"?j.intentAlignment.score:50,issues:Array.isArray(j.intentAlignment?.issues)?j.intentAlignment.issues:[],suggestions:Array.isArray(j.intentAlignment?.suggestions)?j.intentAlignment.suggestions:[]},semanticIssues:(j.semanticIssues??[]).map((A)=>({category:String(A.category??"semantic"),severity:A.severity??"warning",message:String(A.message??""),suggestion:A.suggestion?String(A.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function k9($,W={}){let{spec:j,implementationCode:A}=$,Q=PB(j),Z=mB(Q,A),X=await P9(Z,W);return kB(X)}async function hB($,W={}){let{spec:j,implementationCode:A,implementationPath:Q}=$,Z=Date.now(),X=await T0($,W),Y;if(W.aiApiKey)try{Y=await k9($,W)}catch{}if(Y){let B=[];for(let G of Y.fieldMappings)if(G.match==="missing")B.push({severity:"error",category:"semantic",message:`Missing field: '${G.specField}' (${G.specType}) not found in implementation`,suggestion:G.suggestion??`Add field '${G.specField}' to implementation`});else if(G.match==="mismatch")B.push({severity:"warning",category:"semantic",message:`Field mismatch: '${G.specField}' has incorrect implementation as '${G.implementationField}'`,suggestion:G.suggestion});else if(G.match==="compatible"&&G.aiConfidence<0.8)B.push({severity:"info",category:"semantic",message:`Field naming: '${G.specField}' implemented as '${G.implementationField}' (compatible but not exact)`,suggestion:G.suggestion});for(let G of Y.intentAlignment.issues)B.push({severity:"warning",category:"semantic",message:G});for(let G of Y.semanticIssues)B.push({severity:G.severity,category:"semantic",message:G.message,suggestion:G.suggestion});X.issues=[...X.issues,...B];let q=Y.fieldMappings.length,H=Y.fieldMappings.filter((G)=>G.match==="exact"||G.match==="compatible").length;if(q>0){let G=Math.round(H/q*100);X.score=Math.round((X.score+G)/2),X.coverage.fields={total:q,implemented:H}}if(B.some((G)=>G.severity==="error"))X.passed=!1;X.suggestions=[...X.suggestions,...Y.intentAlignment.suggestions]}return X.meta={...X.meta,duration:Date.now()-Z},X}import{isEmitDeclRef as gB}from"@contractspec/lib.contracts-spec/operations";function fB($,W){let j=[...W.given,...W.when,...W.then].flatMap((q)=>q.toLowerCase().split(/\s+/).filter((H)=>H.length>3)),A=$.toLowerCase(),Q=j.filter((q)=>A.includes(q)),Z=j.length>0?Q.length/j.length:0,X=W.key.toLowerCase().replace(/\s+/g,""),Y=A.includes(X)||A.includes(`test('${W.key.toLowerCase()}'`)||A.includes(`it('${W.key.toLowerCase()}'`)||A.includes(`describe('${W.key.toLowerCase()}'`),B=Z>=0.3||Y;return{name:W.key,type:"scenario",passed:B,expected:`Given: ${W.given.join("; ")}; When: ${W.when.join("; ")}; Then: ${W.then.join("; ")}`,details:B?void 0:`Scenario keywords not found in implementation (${Math.round(Z*100)}% coverage)`}}function uB($,W){let j=JSON.stringify(W.input),A=JSON.stringify(W.output),Q=h9(W.input),Z=h9(W.output),X=$.toLowerCase(),Y=Q.filter((J)=>X.includes(J.toLowerCase())),B=Z.filter((J)=>X.includes(J.toLowerCase())),q=Q.length>0?Y.length/Q.length:1,H=Z.length>0?B.length/Z.length:1,V=(q+H)/2,G=V>=0.2;return{name:W.key,type:"example",passed:G,expected:`Input: ${j.slice(0,100)}...; Output: ${A.slice(0,100)}...`,details:G?void 0:`Example values not found in implementation (${Math.round(V*100)}% coverage)`}}function h9($){let W=[];function j(A){if(typeof A==="string"&&A.length>2)W.push(A);else if(Array.isArray(A))A.forEach(j);else if(A&&typeof A==="object")Object.values(A).forEach(j)}return j($),W}function dB($,W,j){let A=$.includes(W),Q=j.http?$.includes(String(j.http)):!0,Z=j.when.toLowerCase().split(/\s+/).filter((H)=>H.length>3),X=$.toLowerCase(),Y=Z.filter((H)=>X.includes(H)),B=Z.length>0?Y.length/Z.length:1,q=A&&(Q||B>=0.3);return{name:`Error: ${W}`,type:"error",passed:q,expected:`When: ${j.when}; Return: ${W} (HTTP ${j.http??400})`,details:q?void 0:!A?`Error code '${W}' not found in implementation`:"Error condition not properly implemented"}}function nB($,W){let j=W.sideEffects?.emits??[],A=[];for(let Q of j){let Z=gB(Q)?Q.ref.key:Q.key,X=Q.when,Y=X.toLowerCase().split(/\s+/).filter((G)=>G.length>3),B=$.toLowerCase(),q=B.includes(Z.toLowerCase()),H=Y.filter((G)=>B.includes(G)),V=Y.length>0?H.length/Y.length:1;A.push({name:`Event: ${Z}`,type:"scenario",passed:q&&V>=0.3,expected:`Emit ${Z} when: ${X}`,details:!q?`Event '${Z}' not found`:V<0.3?"Event condition not properly implemented":void 0})}return A}function cB($,W){if(W.policy.idempotent===void 0)return null;if(!W.policy.idempotent)return null;let j=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],A=$.toLowerCase(),Q=j.some((Z)=>A.includes(Z));return{name:"Idempotency",type:"scenario",passed:Q,expected:"Operation should be idempotent (safe to retry)",details:Q?void 0:"No idempotency pattern found for idempotent operation"}}function nW($){let{spec:W,implementationCode:j,implementationPath:A}=$,Q=Date.now(),Z=[];for(let b of W.acceptance?.scenarios??[])Z.push(fB(j,b));for(let b of W.acceptance?.examples??[])Z.push(uB(j,b));for(let[b,w]of Object.entries(W.io.errors??{}))Z.push(dB(j,b,w));Z.push(...nB(j,W));let X=cB(j,W);if(X)Z.push(X);let Y=Z.filter((b)=>!b.passed).map((b)=>({severity:b.type==="error"?"error":"warning",category:b.type==="scenario"?"scenario":b.type==="example"?"scenario":"error_handling",message:b.details??`${b.type} not covered: ${b.name}`,location:A?{file:A}:void 0,suggestion:b.expected?`Expected: ${b.expected}`:void 0})),B=Z.filter((b)=>b.type==="scenario"),q=Z.filter((b)=>b.type==="error"),H=Z.filter((b)=>b.passed).length,V=Z.length>0?Math.round(H/Z.length*100):100,G=Y.filter((b)=>b.severity==="error").length===0,J=Z.filter((b)=>!b.passed&&b.expected).map((b)=>`${b.name}: ${b.expected}`);return{tier:"behavior",passed:G,score:V,issues:Y,suggestions:J,coverage:{scenarios:{total:B.length,covered:B.filter((b)=>b.passed).length},errors:{total:q.length,handled:q.filter((b)=>b.passed).length},fields:{total:Z.length,implemented:H}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Q}}}import{isEmitDeclRef as rB}from"@contractspec/lib.contracts-spec/operations";function lB($){let W=/export\s+(async\s+)?function\s+\w+/.test($)||/export\s+const\s+\w+\s*=\s*(async\s*)?\(/.test($)||/export\s+default\s+(async\s+)?function/.test($)||/export\s+\{\s*\w+/.test($);return{name:"handler_export",passed:W,details:W?void 0:"No exported handler function found",suggestion:"Export a function that handles the operation: export async function handle(...) { }"}}function oB($){if(!$)return!1;let W=$.replace(/\\/g,"/");return W.includes("/packages/libs/contracts-spec/src/")||W.includes("/packages/libs/contracts-integrations/src/")||W.includes("/packages/libs/contracts-runtime-")}function iB($,W){if(oB(W))return{name:"contracts_import",passed:!0};let j=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:j,details:j?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function pB($,W){if(!(W.io.input!==null||W.io.output!==null))return{name:"schema_import",passed:!0};let A=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function tB($){let W=/:\s*any\b|as\s+any\b|<any>/,j=$.split(`
2128
+ `),A=[];for(let Q=0;Q<j.length;Q++){let Z=j[Q]??"";if(Z.trim().startsWith("//")||Z.trim().startsWith("*"))continue;if(W.test(Z))A.push(Q+1)}return{name:"no_any_type",passed:A.length===0,details:A.length>0?`Found 'any' type on lines: ${A.slice(0,5).join(", ")}${A.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function aB($,W){let j=W.io.errors;if(!j||Object.keys(j).length===0)return{name:"error_handling",passed:!0};let A=Object.keys(j),Q=[];for(let Z of A)if(!$.includes(Z))Q.push(Z);return{name:"error_handling",passed:Q.length===0,details:Q.length>0?`Missing error handling for: ${Q.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function sB($,W){let j=W.sideEffects?.emits;if(!j||j.length===0)return{name:"event_emission",passed:!0};let A=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),Q=j.map((X)=>{if(rB(X))return X.ref.key;return X.key}),Z=Q.filter((X)=>$.includes(X));return{name:"event_emission",passed:A&&Z.length>0,details:!A?"No event emission pattern found":Z.length===0?`Events not referenced: ${Q.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function eB($,W){if(!W.io.input)return{name:"input_validation",passed:!0};let j=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:j,details:j?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function $q($,W){let j=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(W.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:j,details:j?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function F0($){let{spec:W,implementationCode:j,implementationPath:A}=$,Q=Date.now(),Z=[lB(j),iB(j,A),pB(j,W),tB(j),aB(j,W),sB(j,W),eB(j,W),$q(j,W)],X=Z.filter((J)=>!J.passed).map((J)=>({severity:J.name==="no_any_type"?"warning":"error",category:J.name.includes("import")?"import":J.name.includes("export")?"export":"type",message:J.details??`Check failed: ${J.name}`,location:A?{file:A}:void 0,suggestion:J.suggestion})),Y=Z.filter((J)=>J.passed).length,B=Math.round(Y/Z.length*100),q=X.filter((J)=>J.severity==="error").length===0,H=Z.filter((J)=>!J.passed&&J.suggestion).map((J)=>J.suggestion),V=Object.keys(W.io.errors??{}).length,G=Z.find((J)=>J.name==="error_handling")?.passed?V:0;return{tier:"structure",passed:q,score:B,issues:X,suggestions:H,coverage:{scenarios:{total:0,covered:0},errors:{total:V,handled:G},fields:{total:Z.length,implemented:Y}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Q}}}var Wq={verbose:!1},jq=["structure","behavior","ai_review"];class cW{config;constructor($={}){this.config={...Wq,...$}}async verify($,W,j={}){let A=Date.now(),Q=new Map,Z=[],X={spec:$,implementationCode:W},Y=j.tiers??["structure","behavior"];for(let G of jq){if(!Y.includes(G))continue;let J;switch(G){case"structure":J=F0(X);break;case"behavior":J=nW(X);break;case"ai_review":if(this.config.aiApiKey)J=await T0(X,this.config);else J=dW(X);break;default:continue}if(Q.set(G,J),Z.push(...J.issues),j.failFast&&!J.passed)break}let B=Array.from(Q.values()),q=B.every((G)=>G.passed),H=B.length>0?Math.round(B.reduce((G,J)=>G+J.score,0)/B.length):100,V=this.generateSummary(B,Z);return{passed:q,score:H,reports:Q,allIssues:Z,summary:V,duration:Date.now()-A}}verifyStructure($,W,j){return F0({spec:$,implementationCode:W,implementationPath:j})}verifyBehavior($,W,j){return nW({spec:$,implementationCode:W,implementationPath:j})}async verifyAI($,W,j){let A={spec:$,implementationCode:W,implementationPath:j};if(this.config.aiApiKey)return T0(A,this.config);return dW(A)}quickVerify($,W){return F0({spec:$,implementationCode:W})}formatAsMarkdown($){let W=[];W.push("# Verification Report"),W.push(""),W.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),W.push(`**Score:** ${$.score}/100`),W.push(`**Duration:** ${$.duration}ms`),W.push("");for(let[A,Q]of $.reports){if(W.push(`## ${this.formatTierName(A)}`),W.push(""),W.push(`**Status:** ${Q.passed?"\u2713 Passed":"\u2717 Failed"}`),W.push(`**Score:** ${Q.score}/100`),W.push(""),Q.issues.length>0){W.push("### Issues"),W.push("");for(let Z of Q.issues){let X=Z.severity==="error"?"\u274C":Z.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(W.push(`${X} **${Z.category}**: ${Z.message}`),Z.suggestion)W.push(` - Suggestion: ${Z.suggestion}`)}W.push("")}if(Q.coverage.scenarios.total>0)W.push(`**Scenarios:** ${Q.coverage.scenarios.covered}/${Q.coverage.scenarios.total}`);if(Q.coverage.errors.total>0)W.push(`**Errors handled:** ${Q.coverage.errors.handled}/${Q.coverage.errors.total}`);W.push("")}let j=Array.from($.reports.values()).flatMap((A)=>A.suggestions);if(j.length>0){W.push("## Suggestions"),W.push("");for(let A of j.slice(0,10))W.push(`- ${A}`);if(j.length>10)W.push(`- ... and ${j.length-10} more`);W.push("")}return W.join(`
2129
+ `)}configure($){this.config={...this.config,...$}}generateSummary($,W){let j=[],A=$.every((B)=>B.passed),Q=$.length>0?Math.round($.reduce((B,q)=>B+q.score,0)/$.length):100;j.push(A?"\u2713 Verification passed":"\u2717 Verification failed"),j.push(`Score: ${Q}/100`),j.push("");for(let B of $){let q=B.passed?"\u2713":"\u2717";j.push(`${q} ${B.tier}: ${B.score}/100`)}j.push("");let Z=W.filter((B)=>B.severity==="error"),X=W.filter((B)=>B.severity==="warning"),Y=W.filter((B)=>B.severity==="info");if(Z.length>0)j.push(`Errors: ${Z.length}`);if(X.length>0)j.push(`Warnings: ${X.length}`);if(Y.length>0)j.push(`Info: ${Y.length}`);return j.join(`
2130
+ `)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function Aq($){return new cW($)}var Qq=new cW;var QA={};h(QA,{renderUpgradePrompt:()=>p$,renderUpgradeChecklist:()=>_9,renderPatchNotes:()=>ij,renderMigrationGuide:()=>K9,renderMaintainerSummary:()=>w9,renderCustomerPatchNote:()=>jB,renderCustomerGuide:()=>pj,parseConventionalCommit:()=>oW,isConventionalCommit:()=>Vq,initReleaseArtifacts:()=>$A,getHighestBumpType:()=>ej,getBumpTypeFromCommit:()=>sj,generateChangelogs:()=>s9,formatKeepAChangelog:()=>x0,formatConventionalChangelog:()=>f9,formatChangelogJson:()=>rW,filterCommitsByScope:()=>Gq,filterBumpableCommits:()=>Jq,commitsToChangeEntries:()=>$5,commitToChangeEntry:()=>d9,checkReleaseArtifacts:()=>jA,buildReleaseArtifacts:()=>WA,applyVersionBump:()=>a9,analyzeVersionsFromCommits:()=>pW,analyzeVersions:()=>y0,DEFAULT_COMMIT_TYPE_MAP:()=>lW});import{basename as Zq,dirname as Xq}from"path";function x0($){let W=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],j=[...$].sort((A,Q)=>u9(A.version,Q.version));for(let A of j){W.push(`## [${A.version}] - ${A.date}`),W.push("");let Q=A.changes.filter((V)=>V.type==="added"),Z=A.changes.filter((V)=>V.type==="changed"),X=A.changes.filter((V)=>V.type==="deprecated"),Y=A.changes.filter((V)=>V.type==="removed"),B=A.changes.filter((V)=>V.type==="fixed"),q=A.changes.filter((V)=>V.type==="security"),H=A.breakingChanges??A.changes.filter((V)=>V.type==="breaking");if(H.length>0)W.push("### \u26A0\uFE0F Breaking Changes"),H.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Q.length>0)W.push("### Added"),Q.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Z.length>0)W.push("### Changed"),Z.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(X.length>0)W.push("### Deprecated"),X.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Y.length>0)W.push("### Removed"),Y.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(B.length>0)W.push("### Fixed"),B.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(q.length>0)W.push("### Security"),q.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("")}return W.join(`
2131
+ `)}function f9($){let W=["# Changelog",""],j=[...$].sort((A,Q)=>u9(A.version,Q.version));for(let A of j){let Q=A.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":A.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";W.push(`## ${A.version} (${A.date}) - ${Q}`),W.push("");let Z={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let X of A.changes){let Y=Z[X.type]??"chore",B=X.path?`(${X.path})`:"",q=X.type==="breaking"?"!":"";W.push(`- **${Y}${B}${q}**: ${X.description}`)}W.push("")}return W.join(`
2132
+ `)}function rW($,W){let j=$.analyses.filter((Z)=>Z.needsBump),A=new Date().toISOString(),Q=A.split("T")[0]??"";return{generatedAt:A,baseline:W,specs:j.map((Z)=>({key:Z.specKey,version:Z.suggestedVersion,path:Z.specPath,entries:[{version:Z.suggestedVersion,date:Q,bumpType:Z.bumpType,changes:Z.changes,breakingChanges:Z.changes.filter((X)=>X.type==="breaking")}]})),libraries:Bq(j,Q)}}function Yq($){let W=$.split("/"),j=W.lastIndexOf("packages");if(j>=0&&j+2<W.length)return W.slice(0,j+3).join("/");return Xq($)}var g9={major:3,minor:2,patch:1};function Bq($,W){let j=new Map;for(let A of $){let Q=Yq(A.specPath),Z=j.get(Q);if(Z)Z.push(A);else j.set(Q,[A])}return Array.from(j.entries()).flatMap(([A,Q])=>{let Z=Q[0];if(!Z)return[];let X=Q.reduce((Y,B)=>{return(g9[B.bumpType]??0)>(g9[Y.bumpType]??0)?B:Y},Z);return[{name:Zq(A),path:A,version:X.suggestedVersion,entries:[{version:X.suggestedVersion,date:W,bumpType:X.bumpType,changes:Q.flatMap((Y)=>Y.changes),breakingChanges:Q.flatMap((Y)=>Y.changes).filter((Y)=>Y.type==="breaking")}]}]})}function u9($,W){let j=(Z)=>{return Z.split(".").map((Y)=>parseInt(Y,10)||0)},A=j($),Q=j(W);for(let Z=0;Z<3;Z++){let X=A[Z]??0,Y=Q[Z]??0;if(X!==Y)return Y-X}return 0}var lW={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},qq=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,Hq=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function oW($){let W=$.split(`
2133
+ `),j=W[0]?.trim();if(!j)return null;let A=j.match(qq);if(!A)return null;let[,Q,Z,X,Y]=A;if(!Q||!Y)return null;let B=W.slice(1).join(`
2134
+ `).trim()||void 0,q=B?.match(Hq),H=q?.[1];return{type:Q.toLowerCase(),scope:Z?.toLowerCase(),breaking:!!X||!!q,description:Y.trim(),body:B,breakingDescription:H,raw:$}}function Vq($){return oW($)!==null}function sj($,W=lW){if($.breaking)return"major";return W[$.type]??null}function ej($,W=lW){let j=["major","minor","patch"],A=null;for(let Q of $){let Z=sj(Q,W);if(!Z)continue;if(!A){A=Z;continue}let X=j.indexOf(A);if(j.indexOf(Z)<X)A=Z}return A}function d9($){if($.breaking)return{type:"breaking",description:$.breakingDescription??$.description,path:$.scope};switch($.type){case"feat":return{type:"added",description:$.description,path:$.scope};case"fix":return{type:"fixed",description:$.description,path:$.scope};case"deprecate":return{type:"deprecated",description:$.description,path:$.scope};case"remove":return{type:"removed",description:$.description,path:$.scope};case"security":return{type:"security",description:$.description,path:$.scope};default:return{type:"changed",description:$.description,path:$.scope}}}function $5($){return $.map(d9)}function Gq($,W){return $.filter((j)=>j.scope?.toLowerCase()===W.toLowerCase())}function Jq($,W=lW){return $.filter((j)=>sj(j,W)!==null)}import{GeneratedReleaseManifestSchema as Fq}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as xq,DEFAULT_CONTRACTSRC as yq}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";import{ReleaseCapsuleSchema as n9}from"@contractspec/lib.contracts-spec";import{dump as bq,load as wq}from"js-yaml";var Kq=".changeset/*.md",_q=".changeset/*.release.yaml",zq=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,Uq=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function Lq($,W){return(await $.glob({pattern:Kq,cwd:W,absolute:!0})).filter((A)=>$.basename(A)!=="README.md")}async function W5($,W){let j=await Lq($,W),A=[];for(let Q of j){let Z=await $.readFile(Q);A.push(Oq($.basename(Q),Z))}return A}async function j5($,W,j){let A=await $.glob({pattern:_q,cwd:W,absolute:!0}),Q=new Map(j.map((X)=>[X.slug,X.packages])),Z=new Map;for(let X of A){let Y=$.basename(X).replace(/\.release\.yaml$/,""),B=wq(await $.readFile(X)),q=Sq(B,Y,Q.get(Y)??[]);Z.set(Y,q)}return Z}async function A5($,W){let j=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:W,absolute:!0}),A=[];for(let Q of j){let Z=JSON.parse(await $.readFile(Q));if(!Z.name||!Z.version||Z.private===!0)continue;let X=$.relative(W,$.dirname(Q))||".";A.push({name:Z.name,dir:X,version:Z.version})}return A.sort((Q,Z)=>Q.dir.localeCompare(Z.dir))}function c9($,W){let j=new Set;for(let A of $){let Q=W.find((Z)=>Z.dir==="."?!A.startsWith("packages/"):A===Z.dir||A.startsWith(`${Z.dir}/`));if(Q)j.add(Q.name)}return Array.from(j).sort((A,Q)=>A.localeCompare(Q))}function r9($,W){return`---
2135
+ ${W.map((A)=>`"${A.name}": ${A.releaseType}`).join(`
1891
2136
  `)}
1892
2137
  ---
1893
2138
 
1894
2139
  ${$}
1895
- `}function nQ($){return p2(fQ.parse($),{noRefs:!0,lineWidth:100})}function W3($,W){let j=$.replace(/\.md$/,""),Q=W.match(s2);if(!Q)return{slug:j,summary:W.trim(),packages:[]};let Z=Q[1]??"",B=(Q[2]??"").trim(),X=[];for(let Y of Z.split(`
1896
- `)){let q=Y.trim().match(e2);if(!q)continue;let A=q[1],H=q[2];if(!A||H==="none")continue;X.push({name:A,releaseType:H})}return{slug:j,summary:B,packages:X}}function j3($,W,j){let Q=typeof $==="object"&&$!==null?$:{},Z=Array.isArray(Q.packageNames)?Q.packageNames.filter((B)=>typeof B==="string").map((B)=>({name:B,releaseType:Q.releaseType??"patch"})):[];return fQ.parse({...Q,slug:W,packages:Array.isArray(Q.packages)&&Q.packages.length>0?Q.packages:Z.length>0?Z:j})}import{bumpVersion as oQ,determineBumpType as Q3}from"@contractspec/lib.contracts-spec";async function _0($,W={}){let{fs:j,git:Q,logger:Z}=$,B=W.workspaceRoot??process.cwd();Z.info("Starting version analysis...",{baseline:W.baseline});let X=W.pattern??"**/*.{operation,event,presentation}.ts",q=(await j.glob({pattern:X,cwd:B})).filter((z)=>!z.includes(".test.")&&!z.includes(".spec.")&&!z.includes("node_modules"));Z.debug(`Found ${q.length} spec files`);let A=[],H=0,V=0;for(let z of q)try{let J=await j.readFile(z),K=wW(J);if(!K)continue;let _=null;if(W.baseline)try{_=await Q.showFile(W.baseline,z)}catch{_=null}let w=Z3(J,_),b=w.some((C)=>C.type==="breaking"),L=w.length>0&&!b,I=w.length>0;if(b)H++;if(L)V++;let U=Q3(b,L),O=I?oQ(K.version,U):K.version;A.push({specPath:z,specKey:K.key,currentVersion:K.version,suggestedVersion:O,bumpType:U,changes:w,hasBreaking:b,needsBump:I})}catch(J){Z.warn(`Failed to analyze ${z}:`,{error:J instanceof Error?J.message:String(J)})}let G=A.filter((z)=>z.needsBump).length;return Z.info("Version analysis complete",{totalSpecs:A.length,specsNeedingBump:G,totalBreaking:H,totalNonBreaking:V}),{analyses:A,totalSpecs:A.length,specsNeedingBump:G,totalBreaking:H,totalNonBreaking:V,baseline:W.baseline}}async function CW($,W={}){let{git:j,logger:Q}=$,Z=W.baseline??"HEAD~10";Q.info("Analyzing commits for version bump...",{baseline:Z});try{let B=await j.log(Z),X=[],Y=[];for(let V of B){let G=bW(V.message);if(G)X.push({hash:V.hash,message:V.message,type:G.type,scope:G.scope,breaking:G.breaking}),Y.push(G)}let q=wj(Y),A=Cj(Y),H=X.filter((V)=>V.breaking).length;return Q.info("Commit analysis complete",{totalCommits:X.length,breakingCommits:H,suggestedBumpType:q}),{suggestedBumpType:q,commits:X,changes:A,totalCommits:X.length,breakingCommits:H}}catch(B){return Q.warn("Failed to analyze commits",{error:B instanceof Error?B.message:String(B)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function pQ($,W){let{fs:j,logger:Q}=$,{specPath:Z,dryRun:B=!1,config:X}=W;Q.info("Applying version bump...",{specPath:Z,bumpType:W.bumpType});try{let Y=await j.readFile(Z),q=wW(Y);if(!q)return{success:!1,specPath:Z,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:lQ(),error:"Could not extract spec metadata"};let A=W.bumpType??"patch",H=oQ(q.version,A),V=W.changes??[];if(W.changeDescription)V.push({type:A==="major"?"breaking":"changed",description:W.changeDescription});let G={version:H,date:new Date().toISOString().split("T")[0]??"",bumpType:A,changes:V,breakingChanges:V.filter((z)=>z.type==="breaking")};if(!B){let z=X3(Y,q.version,H);await j.writeFile(Z,z)}if(Q.info("Version bump applied",{specPath:Z,previousVersion:q.version,newVersion:H}),X?.integrateWithChangesets)await A3($,{specPath:Z,bumpType:A,summary:W.changeDescription??`Bump ${q.key} to ${H}`,dryRun:B});return{success:!0,specPath:Z,specKey:q.key,previousVersion:q.version,newVersion:H,bumpType:A,changelogEntry:G}}catch(Y){let q=Y instanceof Error?Y.message:String(Y);return Q.error("Version bump failed",{specPath:Z,error:q}),{success:!1,specPath:Z,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:W.bumpType??"patch",changelogEntry:lQ(),error:q}}}async function iQ($,W={}){let{logger:j}=$,Q=W.tiers??["spec","library","monorepo"],Z=W.format??"keep-a-changelog";j.info("Generating changelogs...",{tiers:Q,format:Z});let B=await _0($,{baseline:W.baseline,workspaceRoot:W.workspaceRoot}),X=[],Y=new Map,q="",A=0;if(Q.includes("spec"))for(let V of B.analyses.filter((G)=>G.needsBump)){let G={id:`changelog.${V.specKey}`,title:`Changelog for ${V.specKey}`,body:Y3(V),kind:"changelog",specKey:V.specKey,specVersion:V.suggestedVersion,entries:[{version:V.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:V.bumpType,changes:V.changes,breakingChanges:V.changes.filter((z)=>z.type==="breaking")}]};X.push(G),A++}if(Q.includes("library")){let V=q3(B.analyses);for(let[G,z]of V){let J=z.filter((K)=>K.needsBump);if(J.length>0)Y.set(G,U0(J.map(rQ))),A+=J.length}}if(Q.includes("monorepo")){let V=B.analyses.filter((G)=>G.needsBump).map(rQ);q=U0(V)}let H=IW(B,W.baseline);return j.info("Changelog generation complete",{totalEntries:A}),{specChangelogs:X,libraryMarkdown:Y,monorepoMarkdown:q,json:H,totalEntries:A}}function wW($){let W=$.match(/key:\s*['"`]([^'"`]+)['"`]/),j=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!W||!j)return null;let Q=W[1],Z=j[1];if(!Q||!Z)return null;return{key:Q,version:Z}}function Z3($,W){let j=[];if(!W)return j.push({type:"added",description:"New spec added"}),j;let Q=wW($),Z=wW(W);if(!Q||!Z)return j;if(Q.version!==Z.version)j.push({type:"changed",description:`Version updated from ${Z.version} to ${Q.version}`,path:"meta.version"});let B=B3($,W);if(B.breaking)j.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(B.nonBreaking)j.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return j}function B3($,W){let j=/io:\s*\{[\s\S]*?\}/,Q=$.match(j)?.[0]??"",Z=W.match(j)?.[0]??"";if(Q===Z)return{breaking:!1,nonBreaking:!1};let B=cQ(Q),X=cQ(Z),Y=X.filter((A)=>!B.includes(A)),q=B.filter((A)=>!X.includes(A));return{breaking:Y.length>0,nonBreaking:q.length>0&&Y.length===0}}function cQ($){let W=/(\w+):/g;return[...$.matchAll(W)].map((Q)=>Q[1]).filter((Q)=>!!Q)}function X3($,W,j){return $.replace(new RegExp(`version:\\s*['"\`]${W}['"\`]`),`version: '${j}'`)}function lQ(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function Y3($){let W=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],j=$.changes.filter((B)=>B.type==="breaking"),Q=$.changes.filter((B)=>B.type==="changed"),Z=$.changes.filter((B)=>B.type==="added");if(j.length>0)W.push("### Breaking Changes"),j.forEach((B)=>W.push(`- ${B.description}`)),W.push("");if(Z.length>0)W.push("### Added"),Z.forEach((B)=>W.push(`- ${B.description}`)),W.push("");if(Q.length>0)W.push("### Changed"),Q.forEach((B)=>W.push(`- ${B.description}`)),W.push("");return W.join(`
1897
- `)}function q3($){let W=new Map;for(let j of $){let B=j.specPath.match(/(.+?\/src\/)/)?.[1]??j.specPath,X=W.get(B)??[];X.push(j),W.set(B,X)}return W}function rQ($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((W)=>W.type==="breaking")}}async function A3($,W){let{fs:j,logger:Q}=$,{specPath:Z,bumpType:B,summary:X,dryRun:Y}=W;try{let q=k(Z),A=L$(q);if(!A){Q.warn("Could not determine package name for changeset",{specPath:Z});return}let H=q,V=null;while(!0){let K=j.join(H,".changeset");if(await j.exists(K)){V=K;break}let _=j.dirname(H);if(_===H)break;H=_}if(!V){Q.warn("No .changeset directory found, skipping changeset generation");return}let G=`${H3()}.md`,z=j.join(V,G),J=`---
1898
- "${A}": ${B}
2140
+ `}function l9($){return bq(n9.parse($),{noRefs:!0,lineWidth:100})}function Oq($,W){let j=$.replace(/\.md$/,""),A=W.match(zq);if(!A)return{slug:j,summary:W.trim(),packages:[]};let Q=A[1]??"",Z=(A[2]??"").trim(),X=[];for(let Y of Q.split(`
2141
+ `)){let B=Y.trim().match(Uq);if(!B)continue;let q=B[1],H=B[2];if(!q||H==="none")continue;X.push({name:q,releaseType:H})}return{slug:j,summary:Z,packages:X}}function Sq($,W,j){let A=typeof $==="object"&&$!==null?$:{},Q=Array.isArray(A.packageNames)?A.packageNames.filter((Z)=>typeof Z==="string").map((Z)=>({name:Z,releaseType:A.releaseType??"patch"})):[];return n9.parse({...A,slug:W,packages:Array.isArray(A.packages)&&A.packages.length>0?A.packages:Q.length>0?Q:j})}import{bumpVersion as t9,determineBumpType as Iq}from"@contractspec/lib.contracts-spec";async function y0($,W={}){let{fs:j,git:A,logger:Q}=$,Z=W.workspaceRoot??process.cwd();Q.info("Starting version analysis...",{baseline:W.baseline});let X=W.pattern??"**/*.{operation,event,presentation}.ts",B=(await j.glob({pattern:X,cwd:Z})).filter((J)=>!J.includes(".test.")&&!J.includes(".spec.")&&!J.includes("node_modules"));Q.debug(`Found ${B.length} spec files`);let q=[],H=0,V=0;for(let J of B)try{let b=await j.readFile(J),w=iW(b);if(!w)continue;let L=null;if(W.baseline)try{L=await A.showFile(W.baseline,J)}catch{L=null}let z=Mq(b,L),S=z.some((I)=>I.type==="breaking"),U=z.length>0&&!S,O=z.length>0;if(S)H++;if(U)V++;let K=Iq(S,U),_=O?t9(w.version,K):w.version;q.push({specPath:J,specKey:w.key,currentVersion:w.version,suggestedVersion:_,bumpType:K,changes:z,hasBreaking:S,needsBump:O})}catch(b){Q.warn(`Failed to analyze ${J}:`,{error:b instanceof Error?b.message:String(b)})}let G=q.filter((J)=>J.needsBump).length;return Q.info("Version analysis complete",{totalSpecs:q.length,specsNeedingBump:G,totalBreaking:H,totalNonBreaking:V}),{analyses:q,totalSpecs:q.length,specsNeedingBump:G,totalBreaking:H,totalNonBreaking:V,baseline:W.baseline}}async function pW($,W={}){let{git:j,logger:A}=$,Q=W.baseline??"HEAD~10";A.info("Analyzing commits for version bump...",{baseline:Q});try{let Z=await j.log(Q),X=[],Y=[];for(let V of Z){let G=oW(V.message);if(G)X.push({hash:V.hash,message:V.message,type:G.type,scope:G.scope,breaking:G.breaking}),Y.push(G)}let B=ej(Y),q=$5(Y),H=X.filter((V)=>V.breaking).length;return A.info("Commit analysis complete",{totalCommits:X.length,breakingCommits:H,suggestedBumpType:B}),{suggestedBumpType:B,commits:X,changes:q,totalCommits:X.length,breakingCommits:H}}catch(Z){return A.warn("Failed to analyze commits",{error:Z instanceof Error?Z.message:String(Z)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function a9($,W){let{fs:j,logger:A}=$,{specPath:Q,dryRun:Z=!1,config:X}=W;A.info("Applying version bump...",{specPath:Q,bumpType:W.bumpType});try{let Y=await j.readFile(Q),B=iW(Y);if(!B)return{success:!1,specPath:Q,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:i9(),error:"Could not extract spec metadata"};let q=W.bumpType??"patch",H=t9(B.version,q),V=W.changes??[];if(W.changeDescription)V.push({type:q==="major"?"breaking":"changed",description:W.changeDescription});let G={version:H,date:new Date().toISOString().split("T")[0]??"",bumpType:q,changes:V,breakingChanges:V.filter((J)=>J.type==="breaking")};if(!Z){let J=Nq(Y,B.version,H);await j.writeFile(Q,J)}if(A.info("Version bump applied",{specPath:Q,previousVersion:B.version,newVersion:H}),X?.integrateWithChangesets)await Dq($,{specPath:Q,bumpType:q,summary:W.changeDescription??`Bump ${B.key} to ${H}`,dryRun:Z});return{success:!0,specPath:Q,specKey:B.key,previousVersion:B.version,newVersion:H,bumpType:q,changelogEntry:G}}catch(Y){let B=Y instanceof Error?Y.message:String(Y);return A.error("Version bump failed",{specPath:Q,error:B}),{success:!1,specPath:Q,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:W.bumpType??"patch",changelogEntry:i9(),error:B}}}async function s9($,W={}){let{logger:j}=$,A=W.tiers??["spec","library","monorepo"],Q=W.format??"keep-a-changelog";j.info("Generating changelogs...",{tiers:A,format:Q});let Z=await y0($,{baseline:W.baseline,workspaceRoot:W.workspaceRoot}),X=[],Y=new Map,B="",q=0;if(A.includes("spec"))for(let V of Z.analyses.filter((G)=>G.needsBump)){let G={id:`changelog.${V.specKey}`,title:`Changelog for ${V.specKey}`,body:Rq(V),kind:"changelog",specKey:V.specKey,specVersion:V.suggestedVersion,entries:[{version:V.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:V.bumpType,changes:V.changes,breakingChanges:V.changes.filter((J)=>J.type==="breaking")}]};X.push(G),q++}if(A.includes("library")){let V=Cq(Z.analyses);for(let[G,J]of V){let b=J.filter((w)=>w.needsBump);if(b.length>0)Y.set(G,x0(b.map(p9))),q+=b.length}}if(A.includes("monorepo")){let V=Z.analyses.filter((G)=>G.needsBump).map(p9);B=x0(V)}let H=rW(Z,W.baseline);return j.info("Changelog generation complete",{totalEntries:q}),{specChangelogs:X,libraryMarkdown:Y,monorepoMarkdown:B,json:H,totalEntries:q}}function iW($){let W=$.match(/key:\s*['"`]([^'"`]+)['"`]/),j=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!W||!j)return null;let A=W[1],Q=j[1];if(!A||!Q)return null;return{key:A,version:Q}}function Mq($,W){let j=[];if(!W)return j.push({type:"added",description:"New spec added"}),j;let A=iW($),Q=iW(W);if(!A||!Q)return j;if(A.version!==Q.version)j.push({type:"changed",description:`Version updated from ${Q.version} to ${A.version}`,path:"meta.version"});let Z=Eq($,W);if(Z.breaking)j.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(Z.nonBreaking)j.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return j}function Eq($,W){let j=/io:\s*\{[\s\S]*?\}/,A=$.match(j)?.[0]??"",Q=W.match(j)?.[0]??"";if(A===Q)return{breaking:!1,nonBreaking:!1};let Z=o9(A),X=o9(Q),Y=X.filter((q)=>!Z.includes(q)),B=Z.filter((q)=>!X.includes(q));return{breaking:Y.length>0,nonBreaking:B.length>0&&Y.length===0}}function o9($){let W=/(\w+):/g;return[...$.matchAll(W)].map((A)=>A[1]).filter((A)=>!!A)}function Nq($,W,j){return $.replace(new RegExp(`version:\\s*['"\`]${W}['"\`]`),`version: '${j}'`)}function i9(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function Rq($){let W=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],j=$.changes.filter((Z)=>Z.type==="breaking"),A=$.changes.filter((Z)=>Z.type==="changed"),Q=$.changes.filter((Z)=>Z.type==="added");if(j.length>0)W.push("### Breaking Changes"),j.forEach((Z)=>W.push(`- ${Z.description}`)),W.push("");if(Q.length>0)W.push("### Added"),Q.forEach((Z)=>W.push(`- ${Z.description}`)),W.push("");if(A.length>0)W.push("### Changed"),A.forEach((Z)=>W.push(`- ${Z.description}`)),W.push("");return W.join(`
2142
+ `)}function Cq($){let W=new Map;for(let j of $){let Z=j.specPath.match(/(.+?\/src\/)/)?.[1]??j.specPath,X=W.get(Z)??[];X.push(j),W.set(Z,X)}return W}function p9($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((W)=>W.type==="breaking")}}async function Dq($,W){let{fs:j,logger:A}=$,{specPath:Q,bumpType:Z,summary:X,dryRun:Y}=W;try{let B=f(Q),q=I$(B);if(!q){A.warn("Could not determine package name for changeset",{specPath:Q});return}let H=B,V=null;while(!0){let w=j.join(H,".changeset");if(await j.exists(w)){V=w;break}let L=j.dirname(H);if(L===H)break;H=L}if(!V){A.warn("No .changeset directory found, skipping changeset generation");return}let G=`${Tq()}.md`,J=j.join(V,G),b=`---
2143
+ "${q}": ${Z}
1899
2144
  ---
1900
2145
 
1901
2146
  ${X}
1902
- `;if(!Y)await j.writeFile(z,J),Q.info("Generated changeset",{filePath:z});else Q.info("Would generate changeset",{filePath:z,content:J})}catch(q){Q.error("Failed to generate changeset",{error:q instanceof Error?q.message:String(q)})}}function H3(){let $=["neat","calm","wild","soft","bold","fair","cool"],W=["fox","cat","dog","bat","ant","elk","owl"],j=["run","fly","hop","eat","nap","cry","sing"],Q=$[Math.floor(Math.random()*$.length)],Z=W[Math.floor(Math.random()*W.length)],B=j[Math.floor(Math.random()*j.length)],X=Math.floor(Math.random()*1000);return`${Q}-${Z}-${B}-${X}`}var aQ="generated/releases",SW=z3.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function tQ($,W={}){let{fs:j,git:Q,logger:Z}=$,B=R(W.workspaceRoot),X=await Mj(j,B),Y=W.baseline?await Q.diffFiles(W.baseline):[],q=W.packages&&W.packages.length>0?W.packages:uQ(Y,X),A=W.baseline?await CW($,{baseline:W.baseline,workspaceRoot:B}):null,H=W.baseline?await C$($,{baseline:W.baseline,workspaceRoot:B}):null,V=(H?.summary.breaking??0)>0?"major":A?.suggestedBumpType??J3(q),G=W.releaseType??V,z=W.summary??`Describe the ${G} release for ${q[0]??"the workspace"}`,J=W.slug??U3(z),K=q.map((U)=>({name:U,releaseType:G,version:X.find((O)=>O.name===U)?.version})),_={schemaVersion:"1",slug:J,summary:z,isBreaking:G==="major"||(H?.summary.breaking??0)>0,packages:K,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:z},{kind:"customer",summary:z}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},w=j.join(B,".changeset",`${J}.md`),b=j.join(B,".changeset",`${J}.release.yaml`);if(!W.force){if(await j.exists(w))throw Error(`Changeset already exists: ${w}`);if(await j.exists(b))throw Error(`Release capsule already exists: ${b}`)}let L=dQ(z,K),I=nQ(_);if(!W.dryRun)await j.writeFile(w,L),await j.writeFile(b,I);return Z.info("Initialized release artifacts",{slug:J,workspaceRoot:B}),{slug:J,changesetPath:w,capsulePath:b,changesetContent:L,capsuleContent:I,packages:K,releaseType:G,isBreaking:_.isBreaking}}async function sQ($,W={}){let{fs:j,logger:Q}=$,Z=R(W.workspaceRoot),B=await $6(j,Z),X=j.join(Z,W.outputDir??aQ),Y=await Sj(j,Z),q=await Ej(j,Z,Y),A=await Mj(j,Z),H=await Promise.all(Array.from(q.entries()).map(async([L,I])=>{let U=j.join(Z,".changeset",`${L}.release.yaml`),O=await j.stat(U);return{slug:L,version:K3(I,A),summary:I.summary,date:O.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:I.isBreaking,packages:I.packages.map((C)=>({...C,version:A.find((S)=>S.name===C.name)?.version??C.version})),affectedRuntimes:[...I.affectedRuntimes],affectedFrameworks:[...I.affectedFrameworks],audiences:[...I.audiences],deprecations:[...I.deprecations],migrationInstructions:[...I.migrationInstructions],upgradeSteps:[...I.upgradeSteps],validation:I.validation}})),V=V3.parse({generatedAt:new Date().toISOString(),releases:H}),G=W.agentTargets??B.agentTargets??["codex"],z=z0(V,[],G,h$),J=j.join(X,"manifest.json"),K=j.join(X,"upgrade-manifest.json"),_=j.join(X,"patch-notes.md"),w=j.join(X,"customer-guide.md"),b=Object.fromEntries(z.agentPrompts.map((L)=>[L.agent,j.join(X,"prompts",`${L.agent}.md`)]));if(!W.dryRun){await j.writeFile(J,JSON.stringify(V,null,2)),await j.writeFile(K,JSON.stringify(V,null,2)),await j.writeFile(_,_j(V)),await j.writeFile(w,Lj(V));for(let L of z.agentPrompts)await j.writeFile(b[L.agent]??"",L.prompt)}return Q.info("Built release artifacts",{outputDir:X,releasesBuilt:V.releases.length}),{outputDir:X,manifestPath:J,upgradeManifestPath:K,patchNotesPath:_,customerGuidePath:w,promptPaths:b,manifest:V,upgradePlan:z,releasesBuilt:V.releases.length}}async function eQ($,W={}){let{fs:j}=$,Q=R(W.workspaceRoot),Z=await $6(j,Q),B=j.join(Q,W.outputDir??aQ),X=[],Y=[],q=[],A=await Sj(j,Q),H=await Ej(j,Q,A),V=A.length>0,G=!V&&H.size>0;f$(X,V||G,"changesets",V?`Found ${A.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let z of A)if(!H.has(z.slug)&&Z.requireReleaseCapsule)q.push(`Missing release capsule for changeset ${z.slug}.`);for(let[z,J]of H){if(J.isBreaking&&J.migrationInstructions.length===0)q.push(`Breaking release ${z} is missing migration instructions.`);if(J.validation.commands.length===0)q.push(`Release capsule ${z} is missing validation commands.`);if(J.validation.evidence.length===0)q.push(`Release capsule ${z} is missing validation evidence.`)}if(W.baseline){try{let z=await C$($,{baseline:W.baseline,workspaceRoot:Q});if(f$(X,!0,"impact",`Impact status: ${z.status}`),z.summary.breaking>0&&!Array.from(H.values()).some((J)=>J.isBreaking))q.push("Breaking impact detected without a breaking release capsule.")}catch(z){f$(X,!1,"impact",EW(z)),q.push(`Impact detection failed: ${EW(z)}`)}try{let z=await _0($,{baseline:W.baseline,workspaceRoot:Q});f$(X,!0,"versioning",`${z.specsNeedingBump} spec(s) need version review.`)}catch(z){f$(X,!1,"versioning",EW(z)),q.push(`Version analysis failed: ${EW(z)}`)}}if(W.strict)for(let z of Z.publishArtifacts??[]){let J=j.join(B,z);if(!await j.exists(J))q.push(`Missing generated release artifact: ${J}`)}if(f$(X,q.length===0,"capsules",q.length===0?"All release capsules are complete.":q[0]??""),!V&&!G)Y.push("No pending release changesets were found.");return{success:q.length===0,errors:q,warnings:Y,checks:X}}async function $6($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return SW;try{let Q=JSON.parse(await $.readFile(j)),Z=G3.safeParse(Q);return Z.success?{...SW,...Z.data.release}:SW}catch{return SW}}function J3($){return $.length>0?"minor":"patch"}function K3($,W){return $.packages.map((Q)=>W.find((Z)=>Z.name===Q.name)?.version??Q.version).find((Q)=>typeof Q==="string")??"0.0.0"}function U3($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function f$($,W,j,Q){$.push({name:j,ok:W,message:Q})}function EW($){return $ instanceof Error?$.message:String($)}var G6={};P(G6,{silentLogger:()=>Z6,runWorkflow:()=>B6,loadWorkflows:()=>Dj,loadVibeConfig:()=>NW,installPack:()=>V6,getWorkflow:()=>Y6,exportContext:()=>Q6,consoleLogger:()=>Rj,builtinWorkflows:()=>RW,DEFAULT_VIBE_CONFIG:()=>MW});import{existsSync as _3}from"fs";import{readFile as L3}from"fs/promises";import{join as Nj}from"path";import I3 from"js-yaml";var MW={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function NW($){let W=$??process.cwd(),j=R(W)??W,Q=[Nj(j,".contractspec","vibe","config.json"),Nj(j,".contractspec","vibe","config.yaml"),Nj(j,".contractspec","vibe","config.yml")],Z={};for(let B of Q)if(_3(B))try{let X=await L3(B,"utf-8");if(B.endsWith(".json"))Z=JSON.parse(X);else Z=I3.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${B}`,X)}return{...MW,...Z}}import{existsSync as O3}from"fs";import{copyFile as b3,mkdir as j6,readFile as w3,writeFile as C3}from"fs/promises";import{dirname as S3,join as u$}from"path";import{glob as E3}from"glob";var M3=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function Q6($){let W=$??process.cwd(),j=R(W)??W,Q=await NW(W),Z=u$(j,".contractspec","context"),B=u$(Z,"files"),X=[...M3],Y=u$(j,".gitignore");if(O3(Y)){let K=(await w3(Y,"utf-8")).split(`
1903
- `).map((_)=>_.trim()).filter((_)=>_&&!_.startsWith("#"));X=[...X,...K]}let q=Q.contextExportAllowlist.length>0?Q.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],A=[];for(let J of q){let K=await E3(J,{cwd:j,ignore:X,nodir:!0,dot:!0});A.push(...K)}let H=Array.from(new Set(A)).sort();if(H.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await j6(B,{recursive:!0});let V=[];for(let J of H){let K=u$(j,J),_=u$(B,J);await j6(S3(_),{recursive:!0}),await b3(K,_),V.push({path:J,size:0})}let G=u$(Z,"index.json"),z={generatedAt:new Date().toISOString(),files:V.map((J)=>J.path),config:{allowlist:Q.contextExportAllowlist,ignores:X.length}};return await C3(G,JSON.stringify(z,null,2)),{success:!0,files:H,indexPath:G}}var RW=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and apply.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
2147
+ `;if(!Y)await j.writeFile(J,b),A.info("Generated changeset",{filePath:J});else A.info("Would generate changeset",{filePath:J,content:b})}catch(B){A.error("Failed to generate changeset",{error:B instanceof Error?B.message:String(B)})}}function Tq(){let $=["neat","calm","wild","soft","bold","fair","cool"],W=["fox","cat","dog","bat","ant","elk","owl"],j=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],Q=W[Math.floor(Math.random()*W.length)],Z=j[Math.floor(Math.random()*j.length)],X=Math.floor(Math.random()*1000);return`${A}-${Q}-${Z}-${X}`}var e9="generated/releases",tW=yq.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function $A($,W={}){let{fs:j,git:A,logger:Q}=$,Z=D(W.workspaceRoot),X=await A5(j,Z),Y=W.baseline?await A.diffFiles(W.baseline):[],B=W.packages&&W.packages.length>0?W.packages:c9(Y,X),q=W.baseline?await pW($,{baseline:W.baseline,workspaceRoot:Z}):null,H=W.baseline?await F$($,{baseline:W.baseline,workspaceRoot:Z}):null,V=(H?.summary.breaking??0)>0?"major":q?.suggestedBumpType??vq(B),G=W.releaseType??V,J=W.summary??`Describe the ${G} release for ${B[0]??"the workspace"}`,b=W.slug??Pq(J),w=B.map((K)=>({name:K,releaseType:G,version:X.find((_)=>_.name===K)?.version})),L={schemaVersion:"1",slug:b,summary:J,isBreaking:G==="major"||(H?.summary.breaking??0)>0,packages:w,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:J},{kind:"customer",summary:J}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},z=j.join(Z,".changeset",`${b}.md`),S=j.join(Z,".changeset",`${b}.release.yaml`);if(!W.force){if(await j.exists(z))throw Error(`Changeset already exists: ${z}`);if(await j.exists(S))throw Error(`Release capsule already exists: ${S}`)}let U=r9(J,w),O=l9(L);if(!W.dryRun)await j.writeFile(z,U),await j.writeFile(S,O);return Q.info("Initialized release artifacts",{slug:b,workspaceRoot:Z}),{slug:b,changesetPath:z,capsulePath:S,changesetContent:U,capsuleContent:O,packages:w,releaseType:G,isBreaking:L.isBreaking}}async function WA($,W={}){let{fs:j,logger:A}=$,Q=D(W.workspaceRoot),Z=await AA(j,Q),X=j.join(Q,W.outputDir??e9),Y=await W5(j,Q),B=await j5(j,Q,Y),q=await A5(j,Q),H=await Promise.all(Array.from(B.entries()).map(async([U,O])=>{let K=j.join(Q,".changeset",`${U}.release.yaml`),_=await j.stat(K);return{slug:U,version:mq(O,q),summary:O.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:O.isBreaking,packages:O.packages.map((I)=>({...I,version:q.find((M)=>M.name===I.name)?.version??I.version})),affectedRuntimes:[...O.affectedRuntimes],affectedFrameworks:[...O.affectedFrameworks],audiences:[...O.audiences],deprecations:[...O.deprecations],migrationInstructions:[...O.migrationInstructions],upgradeSteps:[...O.upgradeSteps],validation:O.validation}})),V=Fq.parse({generatedAt:new Date().toISOString(),releases:H}),G=W.agentTargets??Z.agentTargets??["codex"],J=D0(V,[],G,p$),b=j.join(X,"manifest.json"),w=j.join(X,"upgrade-manifest.json"),L=j.join(X,"patch-notes.md"),z=j.join(X,"customer-guide.md"),S=Object.fromEntries(J.agentPrompts.map((U)=>[U.agent,j.join(X,"prompts",`${U.agent}.md`)]));if(!W.dryRun){await j.writeFile(b,JSON.stringify(V,null,2)),await j.writeFile(w,JSON.stringify(V,null,2)),await j.writeFile(L,ij(V)),await j.writeFile(z,pj(V));for(let U of J.agentPrompts)await j.writeFile(S[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:X,releasesBuilt:V.releases.length}),{outputDir:X,manifestPath:b,upgradeManifestPath:w,patchNotesPath:L,customerGuidePath:z,promptPaths:S,manifest:V,upgradePlan:J,releasesBuilt:V.releases.length}}async function jA($,W={}){let{fs:j}=$,A=D(W.workspaceRoot),Q=await AA(j,A),Z=j.join(A,W.outputDir??e9),X=[],Y=[],B=[],q=await W5(j,A),H=await j5(j,A,q),V=q.length>0,G=!V&&H.size>0;t$(X,V||G,"changesets",V?`Found ${q.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let J of q)if(!H.has(J.slug)&&Q.requireReleaseCapsule)B.push(`Missing release capsule for changeset ${J.slug}.`);for(let[J,b]of H){if(b.isBreaking&&b.migrationInstructions.length===0)B.push(`Breaking release ${J} is missing migration instructions.`);if(b.validation.commands.length===0)B.push(`Release capsule ${J} is missing validation commands.`);if(b.validation.evidence.length===0)B.push(`Release capsule ${J} is missing validation evidence.`)}if(W.baseline){try{let J=await F$($,{baseline:W.baseline,workspaceRoot:A});if(t$(X,!0,"impact",`Impact status: ${J.status}`),J.summary.breaking>0&&!Array.from(H.values()).some((b)=>b.isBreaking))B.push("Breaking impact detected without a breaking release capsule.")}catch(J){t$(X,!1,"impact",aW(J)),B.push(`Impact detection failed: ${aW(J)}`)}try{let J=await y0($,{baseline:W.baseline,workspaceRoot:A});t$(X,!0,"versioning",`${J.specsNeedingBump} spec(s) need version review.`)}catch(J){t$(X,!1,"versioning",aW(J)),B.push(`Version analysis failed: ${aW(J)}`)}}if(W.strict)for(let J of Q.publishArtifacts??[]){let b=j.join(Z,J);if(!await j.exists(b))B.push(`Missing generated release artifact: ${b}`)}if(t$(X,B.length===0,"capsules",B.length===0?"All release capsules are complete.":B[0]??""),!V&&!G)Y.push("No pending release changesets were found.");return{success:B.length===0,errors:B,warnings:Y,checks:X}}async function AA($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return tW;try{let A=JSON.parse(await $.readFile(j)),Q=xq.safeParse(A);return Q.success?{...tW,...Q.data.release}:tW}catch{return tW}}function vq($){return $.length>0?"minor":"patch"}function mq($,W){return $.packages.map((A)=>W.find((Q)=>Q.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function Pq($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function t$($,W,j,A){$.push({name:j,ok:W,message:A})}function aW($){return $ instanceof Error?$.message:String($)}var wA={};h(wA,{silentLogger:()=>YA,runWorkflow:()=>BA,loadWorkflows:()=>X5,loadVibeConfig:()=>eW,installPack:()=>bA,getWorkflow:()=>HA,exportContext:()=>XA,consoleLogger:()=>Z5,builtinWorkflows:()=>$1,DEFAULT_VIBE_CONFIG:()=>sW});import{existsSync as kq}from"fs";import{readFile as hq}from"fs/promises";import{join as Q5}from"path";import gq from"js-yaml";var sW={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function eW($){let W=$??process.cwd(),j=D(W)??W,A=[Q5(j,".contractspec","vibe","config.json"),Q5(j,".contractspec","vibe","config.yaml"),Q5(j,".contractspec","vibe","config.yml")],Q={};for(let Z of A)if(kq(Z))try{let X=await hq(Z,"utf-8");if(Z.endsWith(".json"))Q=JSON.parse(X);else Q=gq.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${Z}`,X)}return{...sW,...Q}}import{existsSync as fq}from"fs";import{copyFile as uq,mkdir as ZA,readFile as dq,writeFile as nq}from"fs/promises";import{dirname as cq,join as a$}from"path";import{glob as rq}from"glob";var lq=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function XA($){let W=$??process.cwd(),j=D(W)??W,A=await eW(W),Q=a$(j,".contractspec","context"),Z=a$(Q,"files"),X=[...lq],Y=a$(j,".gitignore");if(fq(Y)){let w=(await dq(Y,"utf-8")).split(`
2148
+ `).map((L)=>L.trim()).filter((L)=>L&&!L.startsWith("#"));X=[...X,...w]}let B=A.contextExportAllowlist.length>0?A.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],q=[];for(let b of B){let w=await rq(b,{cwd:j,ignore:X,nodir:!0,dot:!0});q.push(...w)}let H=Array.from(new Set(q)).sort();if(H.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await ZA(Z,{recursive:!0});let V=[];for(let b of H){let w=a$(j,b),L=a$(Z,b);await ZA(cq(L),{recursive:!0}),await uq(w,L),V.push({path:b,size:0})}let G=a$(Q,"index.json"),J={generatedAt:new Date().toISOString(),files:V.map((b)=>b.path),config:{allowlist:A.contextExportAllowlist,ignores:X.length}};return await nq(G,JSON.stringify(J,null,2)),{success:!0,files:H,indexPath:G}}var $1=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and generate artifacts.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
1904
2149
  Please review them and move selected files to contracts/ directory.
1905
- Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"apply",label:"Apply Changes (Generate)",command:"contractspec apply"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"apply",label:"Apply Changes",command:"contractspec apply"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"changelog",label:"Generate Changelog",command:"contractspec changelog"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"regenerate",label:"Regenerate Artifacts",command:"contractspec apply"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as N3}from"child_process";var Z6={log:()=>{},warn:()=>{},error:()=>{}},Rj={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function B6($,W,j){let Q=j?.logger??Rj,Z=j?.prompter;if(Q.log(`
1906
- Running Workflow: ${$.name}`),$.description)Q.log($.description);if(Q.log(`Track: ${W.track}`),W.dryRun)Q.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
1907
- `);let B={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let X of $.steps){let Y={id:X.id,name:X.label,status:"skip",command:X.command};if(X.tracks&&!X.tracks.includes(W.track)){B.steps.push(Y);continue}if(X.condition){if(!await X.condition(W)){B.steps.push(Y);continue}}if(Q.log(`
1908
- \uD83D\uDC49 Step: ${X.label}`),W.dryRun&&X.command)Q.log(` Command: ${X.command}`);if(X.manualCheckpoint){if(W.dryRun)Q.warn(" [Manual Checkpoint] Would pause here for user input.");else if(Z){if(X.manualMessage)Q.log(X.manualMessage);let q=await Z.select({message:"Checkpoint action:",choices:[{name:"Proceed",value:"proceed",description:"Run this step"},{name:"Skip Step",value:"skip",description:"Skip this step and continue"},{name:"Abort Workflow",value:"abort",description:"Exit workflow"}]});if(q==="abort")return Q.warn("Workflow aborted by user."),B.success=!1,B.steps.push({...Y,status:"skip",error:"Aborted by user"}),B;if(q==="skip"){Q.warn(" \u2192 Skipped by user."),B.steps.push(Y);continue}}}if(!W.dryRun)try{if(X.execute)await X.execute(W);else if(X.command)await R3(X.command,W.root);Y.status="pass",B.stepsExecuted.push(X.id),B.steps.push(Y),Q.log(" \u2713 Completed")}catch(q){let A=q instanceof Error?q.message:String(q);return Q.error(` \u274C Failed: ${A}`),B.success=!1,B.error=q instanceof Error?q:Error(String(q)),Y.status="fail",Y.error=A,B.stepsExecuted.push(X.id),B.steps.push(Y),B}else B.steps.push(Y)}return B}async function R3($,W){let j=$.split(" "),Q=j[0],Z=j.slice(1);if(!Q)throw Error("Invalid command");return new Promise((B,X)=>{let Y=N3(Q,Z,{cwd:W,stdio:"inherit",shell:!0});Y.on("error",X),Y.on("exit",(q)=>{if(q===0)B();else X(Error(`Command exited with code ${q}`))})})}import{existsSync as D3}from"fs";import{readdir as F3,readFile as x3}from"fs/promises";import{join as X6}from"path";import T3 from"js-yaml";async function Dj($){let W=[...RW],j=$??process.cwd(),Q=R(j)??j,Z=X6(Q,".contractspec","vibe","workflows");if(D3(Z))try{let B=await F3(Z);for(let X of B)if(X.endsWith(".json")||X.endsWith(".yaml")||X.endsWith(".yml")){let Y=await x3(X6(Z,X),"utf-8");try{let q;if(X.endsWith(".json"))q=JSON.parse(Y);else q=T3.load(Y);if(q.id&&q.steps)W.push(q)}catch(q){console.warn(`Failed to parse workflow ${X}:`,q)}}}catch(B){console.warn("Error loading user workflows:",B)}return W}async function Y6($,W){return(await Dj(W)).find((Q)=>Q.id===$)}import{existsSync as Fj}from"fs";import{copyFile as q6,mkdir as A6,readdir as H6,stat as v3}from"fs/promises";import{join as J$,resolve as y3}from"path";async function V6($,W){let j=W??process.cwd(),Q=R(j)??j;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let Z=y3(j,$);if(!Fj(Z))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${Z}`};let B=0,X=0,Y=J$(Z,"workflows");if(Fj(Y)){let A=J$(Q,".contractspec","vibe","workflows");await A6(A,{recursive:!0});let H=await H6(Y);for(let V of H)if(V.endsWith(".json")||V.endsWith(".yaml")||V.endsWith(".yml"))await q6(J$(Y,V),J$(A,V)),B++}let q=J$(Z,"templates");if(Fj(q)){let A=J$(Q,".contractspec","vibe","templates");await A6(A,{recursive:!0});let H=await H6(q);for(let V of H){let G=J$(q,V),z=J$(A,V);if((await v3(G)).isFile())await q6(G,z),X++}}return{success:!0,workflowsInstalled:B,templatesInstalled:X}}import{loadSpecFromSource as P3}from"@contractspec/module.workspace";var z6=["product","eng","qa"];function m3($){return z6.includes($)}async function mw($,W){if(!m3(W.audience))throw Error(`Invalid audience: ${W.audience}. Must be one of: ${z6.join(", ")}`);let j,Q,Z;if(W.specFiles&&W.specFiles.length>0)j=W.specFiles;else{let X=await k3($,{baseline:W.baseline});if(Q=X.totalSpecs,Z=X.changedFilesCount,W.baseline){if(X.changedFilesCount===0)return{views:[],totalSpecs:Q,changedFilesCount:0,status:"no_changes"};if(X.specFiles.length===0)return{views:[],totalSpecs:Q,changedFilesCount:Z,status:"no_changed_specs"}}j=X.specFiles}if(j.length===0)return{views:[],totalSpecs:Q,changedFilesCount:Z,status:"no_specs"};let B=[];for(let X of j){let Y=await g3(X,W.audience,$);B.push({filePath:X,content:Y})}return{views:B,totalSpecs:Q,changedFilesCount:Z,status:"success"}}async function k3($,W={}){let Q=(await h({fs:$.fs})).map((Y)=>Y.filePath),Z=Q.length;if(!W.baseline)return{specFiles:Q,totalSpecs:Z};let B=await $.git.diffFiles(W.baseline);if(B.length===0)return{specFiles:[],totalSpecs:Z,changedFilesCount:0,hasChanges:!1};let X=Q.filter((Y)=>B.some((q)=>Y.endsWith(q)||q.endsWith(Y)||Y.includes(q)||q.includes(Y)));return{specFiles:X,totalSpecs:Z,changedFilesCount:B.length,hasChanges:X.length>0}}async function g3($,W,j){if(!await j.fs.exists($))throw Error(`File not found: ${$}`);let Q=await P3($);if(Q.length===0)return`No specs found in ${$} (Parse result empty)`;return Q.map((Z)=>h3(Z,W)).join(`
2150
+ Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"changelog",label:"Generate Changelog",command:"contractspec changelog"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as oq}from"child_process";var YA={log:()=>{},warn:()=>{},error:()=>{}},Z5={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function BA($,W,j){let A=j?.logger??Z5,Q=j?.prompter;if(A.log(`
2151
+ Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${W.track}`),W.dryRun)A.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
2152
+ `);let Z={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let X of $.steps){let Y={id:X.id,name:X.label,status:"skip",command:X.command};if(X.tracks&&!X.tracks.includes(W.track)){Z.steps.push(Y);continue}if(X.condition){if(!await X.condition(W)){Z.steps.push(Y);continue}}if(A.log(`
2153
+ \uD83D\uDC49 Step: ${X.label}`),W.dryRun&&X.command)A.log(` Command: ${X.command}`);if(X.manualCheckpoint){if(W.dryRun)A.warn(" [Manual Checkpoint] Would pause here for user input.");else if(Q){if(X.manualMessage)A.log(X.manualMessage);let B=await Q.select({message:"Checkpoint action:",choices:[{name:"Proceed",value:"proceed",description:"Run this step"},{name:"Skip Step",value:"skip",description:"Skip this step and continue"},{name:"Abort Workflow",value:"abort",description:"Exit workflow"}]});if(B==="abort")return A.warn("Workflow aborted by user."),Z.success=!1,Z.steps.push({...Y,status:"skip",error:"Aborted by user"}),Z;if(B==="skip"){A.warn(" \u2192 Skipped by user."),Z.steps.push(Y);continue}}}if(!W.dryRun)try{if(X.execute)await X.execute(W);else if(X.command)await iq(X.command,W.root);Y.status="pass",Z.stepsExecuted.push(X.id),Z.steps.push(Y),A.log(" \u2713 Completed")}catch(B){let q=B instanceof Error?B.message:String(B);return A.error(` \u274C Failed: ${q}`),Z.success=!1,Z.error=B instanceof Error?B:Error(String(B)),Y.status="fail",Y.error=q,Z.stepsExecuted.push(X.id),Z.steps.push(Y),Z}else Z.steps.push(Y)}return Z}async function iq($,W){let j=$.split(" "),A=j[0],Q=j.slice(1);if(!A)throw Error("Invalid command");return new Promise((Z,X)=>{let Y=oq(A,Q,{cwd:W,stdio:"inherit",shell:!0});Y.on("error",X),Y.on("exit",(B)=>{if(B===0)Z();else X(Error(`Command exited with code ${B}`))})})}import{existsSync as pq}from"fs";import{readdir as tq,readFile as aq}from"fs/promises";import{join as qA}from"path";import sq from"js-yaml";async function X5($){let W=[...$1],j=$??process.cwd(),A=D(j)??j,Q=qA(A,".contractspec","vibe","workflows");if(pq(Q))try{let Z=await tq(Q);for(let X of Z)if(X.endsWith(".json")||X.endsWith(".yaml")||X.endsWith(".yml")){let Y=await aq(qA(Q,X),"utf-8");try{let B;if(X.endsWith(".json"))B=JSON.parse(Y);else B=sq.load(Y);if(B.id&&B.steps)W.push(B)}catch(B){console.warn(`Failed to parse workflow ${X}:`,B)}}}catch(Z){console.warn("Error loading user workflows:",Z)}return W}async function HA($,W){return(await X5(W)).find((A)=>A.id===$)}import{existsSync as Y5}from"fs";import{copyFile as VA,mkdir as GA,readdir as JA,stat as eq}from"fs/promises";import{join as U$,resolve as $H}from"path";async function bA($,W){let j=W??process.cwd(),A=D(j)??j;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let Q=$H(j,$);if(!Y5(Q))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${Q}`};let Z=0,X=0,Y=U$(Q,"workflows");if(Y5(Y)){let q=U$(A,".contractspec","vibe","workflows");await GA(q,{recursive:!0});let H=await JA(Y);for(let V of H)if(V.endsWith(".json")||V.endsWith(".yaml")||V.endsWith(".yml"))await VA(U$(Y,V),U$(q,V)),Z++}let B=U$(Q,"templates");if(Y5(B)){let q=U$(A,".contractspec","vibe","templates");await GA(q,{recursive:!0});let H=await JA(B);for(let V of H){let G=U$(B,V),J=U$(q,V);if((await eq(G)).isFile())await VA(G,J),X++}}return{success:!0,workflowsInstalled:Z,templatesInstalled:X}}import{loadSpecFromSource as WH}from"@contractspec/module.workspace";var KA=["product","eng","qa"];function jH($){return KA.includes($)}async function jN($,W){if(!jH(W.audience))throw Error(`Invalid audience: ${W.audience}. Must be one of: ${KA.join(", ")}`);let j,A,Q;if(W.specFiles&&W.specFiles.length>0)j=W.specFiles;else{let X=await AH($,{baseline:W.baseline});if(A=X.totalSpecs,Q=X.changedFilesCount,W.baseline){if(X.changedFilesCount===0)return{views:[],totalSpecs:A,changedFilesCount:0,status:"no_changes"};if(X.specFiles.length===0)return{views:[],totalSpecs:A,changedFilesCount:Q,status:"no_changed_specs"}}j=X.specFiles}if(j.length===0)return{views:[],totalSpecs:A,changedFilesCount:Q,status:"no_specs"};let Z=[];for(let X of j){let Y=await QH(X,W.audience,$);Z.push({filePath:X,content:Y})}return{views:Z,totalSpecs:A,changedFilesCount:Q,status:"success"}}async function AH($,W={}){let A=(await $$({fs:$.fs})).map((Y)=>Y.filePath),Q=A.length;if(!W.baseline)return{specFiles:A,totalSpecs:Q};let Z=await $.git.diffFiles(W.baseline);if(Z.length===0)return{specFiles:[],totalSpecs:Q,changedFilesCount:0,hasChanges:!1};let X=A.filter((Y)=>Z.some((B)=>Y.endsWith(B)||B.endsWith(Y)||Y.includes(B)||B.includes(Y)));return{specFiles:X,totalSpecs:Q,changedFilesCount:Z.length,hasChanges:X.length>0}}async function QH($,W,j){if(!await j.fs.exists($))throw Error(`File not found: ${$}`);let A=await WH($);if(A.length===0)return`No specs found in ${$} (Parse result empty)`;return A.map((Q)=>ZH(Q,W)).join(`
1909
2154
 
1910
2155
  ---
1911
2156
 
1912
- `)}function h3($,W){let j=[];switch(W){case"product":f3($,j);break;case"eng":u3($,j);break;case"qa":d3($,j);break}return j.join(`
1913
- `)}function f3($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: Product (User Flow & Capabilities)"),W.push(""),$.meta.goal)W.push(`### Goal
2157
+ `)}function ZH($,W){let j=[];switch(W){case"product":XH($,j);break;case"eng":YH($,j);break;case"qa":BH($,j);break}return j.join(`
2158
+ `)}function XH($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: Product (User Flow & Capabilities)"),W.push(""),$.meta.goal)W.push(`### Goal
1914
2159
  ${$.meta.goal}
1915
2160
  `);if($.meta.context)W.push(`### Context
1916
2161
  ${$.meta.context}
1917
- `);if($.specType==="feature"){if($.operations?.length)W.push("### Capabilities (Operations)"),$.operations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("");if($.presentations?.length)W.push("### User Interfaces (Presentations)"),$.presentations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("")}else if($.specType==="operation"){if(W.push("### Behavior"),$.hasPolicy)W.push("- \u2705 Enforces Business Policies");if($.hasIo)W.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)W.push("### Triggers"),$.emittedEvents.forEach((j)=>W.push(`- **${j.name}** (Event)`))}else W.push(`Type: ${$.specType}`)}function u3($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: Engineering (API, Schemas, Constraints)"),W.push(""),W.push(`- **Type**: \`${$.specType}\``),W.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)W.push(`- **Stability**: \`${$.meta.stability}\``);if(W.push(""),$.specType==="operation"){if(W.push("### Contract Details"),W.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),W.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),W.push(""),$.emittedEvents?.length)W.push("### Emitted Events"),$.emittedEvents.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("")}else if($.specType==="feature"){if($.operations?.length)W.push("### Operations"),$.operations.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("");if($.events?.length)W.push("### Events"),$.events.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("")}if($.sourceBlock)W.push("### Source Signature"),W.push("```typescript"),W.push($.sourceBlock),W.push("```")}function d3($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: QA (Scenarios, Test Coverage)"),W.push(""),$.meta.goal)W.push(`**Goal**: ${$.meta.goal}
1918
- `);if($.testRefs?.length)W.push("### Linked Scenarios"),$.testRefs.forEach((j)=>W.push(`- \uD83E\uDDEA \`${j.name}\``)),W.push("");else W.push("### Linked Scenarios"),W.push("_(No explicit test refs found)_"),W.push("");if(W.push("### Verification Checklist"),$.specType==="operation"){if(W.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)W.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((j)=>W.push(`- [ ] Verify event \`${j.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((j)=>W.push(`- [ ] Test Operation flow: \`${j.name}\``));if($.presentations?.length)$.presentations.forEach((j)=>W.push(`- [ ] Test UI Component: \`${j.name}\``))}}function fw($,W,j,Q){let{watcher:Z,fs:B,logger:X}=$,Y=Z.watch(j),q=Q?.validate??(async(H)=>{await R$(H,{fs:B,logger:X})}),A=Q?.build??(async(H)=>{await x0(H,{fs:B,logger:X},W)});return Y.on(async(H)=>{if(H.type!=="change")return;if(X.info("watchSpecs.changed",{path:H.path}),j.runValidate)await q(H.path);if(j.runBuild)if(j.dryRun)X.info("[dry-run] watchSpecs skipped build",{path:H.path});else await A(H.path)}),Y}async function nw($,W){let j=ij(W),Q=$.join(j.workspaceRoot,".contractsrc.json"),Z=$.join(j.packageRoot,".contractsrc.json"),B=await $.exists(Q),X=j.workspaceRoot!==j.packageRoot?await $.exists(Z):!1,Y;if(B)try{let q=await $.readFile(Q),A=JSON.parse(q);if(A.packages||A.excludePackages||A.recursive)Y={packages:A.packages,excludePackages:A.excludePackages,recursive:A.recursive}}catch{}return{...j,monorepoConfig:Y,workspaceConfigPath:B?Q:void 0,packageConfigPath:X?Z:void 0}}async function cw($,W){let j=[],Q=$.join(W,".contractsrc.json");if(await $.exists(Q))j.push(Q);let Z=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let B of Z)if(B!==Q)j.push(B);return j}async function lw($,W,j){let Q={};if(W&&await $.exists(W))try{let Z=await $.readFile(W);Q=JSON.parse(Z)}catch{}if(j&&await $.exists(j))try{let Z=await $.readFile(j),B=JSON.parse(Z);Q=J6(Q,B)}catch{}return Q}function J6($,W){let j={...$};for(let Q of Object.keys(W)){let Z=$[Q],B=W[Q];if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&typeof B==="object"&&B!==null&&!Array.isArray(B))j[Q]=J6(Z,B);else j[Q]=B}return j}function rw($){let W=[];if(W.push(`Package Manager: ${$.packageManager}`),W.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(W.push("Monorepo: Yes"),W.push(`Package Root: ${$.packageRoot}`),$.packageName)W.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)W.push(`Package Patterns: ${$.packages.join(", ")}`)}else W.push("Monorepo: No");if($.workspaceConfigPath)W.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)W.push(`Package Config: ${$.packageConfigPath}`);return W.join(`
1919
- `)}export{fw as watchSpecs,G6 as vibe,W6 as versioning,L2 as verifyWithAIEnhanced,J0 as verifyWithAI,K0 as verifyStructure,g2 as verifyService,yQ as verifySemanticFields,rX as verifyImportedContracts,wL as verifyImplementationAgainstParsedSpec,_W as verifyBehavior,sI as validateTenantConfig,rI as validateSpecs,R$ as validateSpec,dI as validateImplementationWithAgent,n0 as validateImplementationFiles,gI as validateBlueprint,m3 as validateAudience,gU as validateAgainstOpenApiService,z5 as utils,SQ as upgrade,EO as updateSpec,C9 as toKebabCase,g4 as templates,PU as syncWithOpenApiService,qO as syncSpecs,V2 as stringToCacheKey,iL as searchRegistry,j$ as safeParseJson,UO as runTests,_O as runTestSpecs,RI as runSetup,mL as runQuickstart,R5 as runDoctor,hz as runCIChecks,Zj as resolveRegistryUrl,D9 as resolveImplementations,u5 as resolveAllImplementations,B5 as prompts,oj as parseGitModules,g5 as parseExplicitImplementations,kA as operationRegistry,PC as module,lw as mergeMonorepoConfigs,a as loadWorkspaceConfig,AG as loadPackageAuthoredDocBlocks,qG as loadAuthoredDocBlocksFromSourceFiles,LO as listTests,k3 as listSpecsForView,h as listSpecs,pL as listFromRegistry,nW as listAgentTypes,c$ as isMonorepo,kL as isContractSpecInstalled,w9 as inferImplementationType,hX as importFromSourceService,d4 as importFromOpenApiService,$4 as impact,e4 as hooks,DH as groupSpecsByType,e6 as getWorkspacePackages,ij as getWorkspaceInfo,Mq as getRunCommand,jj as getProductionDependencies,L$ as getPackageName,W7 as getMetaRepoInfo,aj as getInstallCommand,mG as getImplementationSummary,tH as getGraphStats,nw as getExtendedWorkspaceInfo,Nq as getExecCommand,Qj as getDevDependencies,Wj as getDependencies,k5 as getConventionPaths,iH as getContractNode,P0 as getClaudeDesktopConfigPath,D5 as getApiKey,jz as getAllSpecs,OV as getAllLayerLocations,l$ as getAgentAdapter,hW as getAIProvider,D0 as genericMCPAdapter,m4 as generateWorkflowSpec,k4 as generateWorkflowRunnerTemplate,K5 as generateVscodeSettings,mw as generateViews,g3 as generateView,N4 as generateTestTemplate,P4 as generateTelemetrySpec,y4 as generatePresentationSpec,v4 as generateOperationSpec,T4 as generateMigrationSpec,OL as generateMermaidDiagram,cX as generateMarkdownReport,F4 as generateKnowledgeSpaceSpec,D4 as generateIntegrationSpec,E4 as generateHandlerTemplate,sX as generateGuideFromParsedSpec,S4 as generateFeatureSpec,NL as generateFeatureContextMarkdown,C4 as generateExperimentSpec,w4 as generateEventSpec,T5 as generateDocsFromSpecs,b4 as generateDataViewSpec,eX as generateCursorRulesFromParsedSpec,_5 as generateCursorRules,o$ as generateCursorMcpConfig,x$ as generateContractsrcConfig,M4 as generateComponentTemplate,lX as generateCliReport,U5 as generateClaudeMcpConfig,y5 as generateArtifacts,O4 as generateAppBlueprintSpec,L5 as generateAgentsGuide,q5 as formatters,rw as formatWorkspaceInfo,CL as formatVerificationReport,gL as formatQuickstartPreview,D as formatJson,o_ as formatFiles,iV as formatDoctorSummary,aV as formatCheckResult,p4 as fix,R as findWorkspaceRoot,k as findPackageRoot,pj as findMetaRepoRoot,cw as findAllConfigFiles,Qz as filterIssuesByType,Zz as filterIssuesBySeverity,c4 as features,P5 as extractSpecReferences,pU as extractContracts,RL as exportSpecForLLM,iB as exportOpenApi,aH as exportGraphAsDot,k0 as discoverLayers,c0 as discoverImplementationsForSpec,xG as discoverAllImplementations,h5 as determineStatus,j7 as detectRepositoryType,F$ as detectPackageManager,IU as deleteSpec,r as deepMergePreserve,L8 as deepMergeOverwrite,N0 as cursorCLIAdapter,pO as createWorkspaceStateCacheStorage,E7 as createWorkspaceRegistry,k2 as createVerifyService,Qb as createVerificationCacheService,zU as createSpecCreator,lL as createRegeneratorService,UW as createQuickAIReview,dj as createNoopLoggerAdapter,nj as createNodeWatcherAdapter,fj as createNodeGitAdapter,gj as createNodeFsAdapter,yj as createNodeAiAdapter,Kq as createNodeAdapters,rO as createInMemoryCacheStorage,cO as createFileSystemCacheStorage,m8 as createEmptyLayerInventory,uj as createConsoleLoggerAdapter,bq as createBunFsAdapter,P7 as createAgentGuideService,K4 as connect,FQ as computeContentHash,wU as compareSpecs,oz as cleanArtifacts,E0 as claudeCodeAdapter,xQ as cacheKeyToString,x0 as buildSpec,v0 as analyzeWorkspaceDocBlocks,l0 as analyzeIntegrity,t_ as analyzeGap,J5 as analyzeDeps,m7 as agentGuideService,dW as agentAdapters,oL as addToRegistry,RQ as WorkspaceStateCacheStorage,LW as VerifyService,TQ as VerificationCacheService,z6 as VALID_AUDIENCES,DY as TestGeneratorService,h4 as SpecCreatorService,b0 as SimpleAgent,jQ as SETUP_TARGET_LABELS,XY as RuleSyncService,qW as RegistryClient,R7 as PrActionService,O0 as OpenAICodexAgent,$Q as MINIMAL_DEPENDENCIES,NQ as InMemoryCacheStorage,R0 as GenericMCPAdapter,MQ as FileSystemCacheStorage,$Y as FULL_DEPENDENCIES,M7 as DriftActionService,U$ as DEFAULT_SPEC_PATTERNS,_$ as DEFAULT_FS_IGNORES,DQ as DEFAULT_CACHE_CONFIG,M0 as CursorCLIAdapter,I0 as CursorAgent,L0 as ClaudeCodeAgent,S0 as ClaudeCodeAdapter,dz as CI_CHECK_CATEGORY_LABELS,N5 as CHECK_CATEGORY_LABELS,w0 as AgentOrchestrator,F0 as AgentGuideService,Gj as ALL_SETUP_TARGETS,uz as ALL_CI_CHECK_CATEGORIES,M5 as ALL_CHECK_CATEGORIES,$W as AIGenerator};
2162
+ `);if($.specType==="feature"){if($.operations?.length)W.push("### Capabilities (Operations)"),$.operations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("");if($.presentations?.length)W.push("### User Interfaces (Presentations)"),$.presentations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("")}else if($.specType==="operation"){if(W.push("### Behavior"),$.hasPolicy)W.push("- \u2705 Enforces Business Policies");if($.hasIo)W.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)W.push("### Triggers"),$.emittedEvents.forEach((j)=>W.push(`- **${j.name}** (Event)`))}else W.push(`Type: ${$.specType}`)}function YH($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: Engineering (API, Schemas, Constraints)"),W.push(""),W.push(`- **Type**: \`${$.specType}\``),W.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)W.push(`- **Stability**: \`${$.meta.stability}\``);if(W.push(""),$.specType==="operation"){if(W.push("### Contract Details"),W.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),W.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),W.push(""),$.emittedEvents?.length)W.push("### Emitted Events"),$.emittedEvents.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("")}else if($.specType==="feature"){if($.operations?.length)W.push("### Operations"),$.operations.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("");if($.events?.length)W.push("### Events"),$.events.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("")}if($.sourceBlock)W.push("### Source Signature"),W.push("```typescript"),W.push($.sourceBlock),W.push("```")}function BH($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: QA (Scenarios, Test Coverage)"),W.push(""),$.meta.goal)W.push(`**Goal**: ${$.meta.goal}
2163
+ `);if($.testRefs?.length)W.push("### Linked Scenarios"),$.testRefs.forEach((j)=>W.push(`- \uD83E\uDDEA \`${j.name}\``)),W.push("");else W.push("### Linked Scenarios"),W.push("_(No explicit test refs found)_"),W.push("");if(W.push("### Verification Checklist"),$.specType==="operation"){if(W.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)W.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((j)=>W.push(`- [ ] Verify event \`${j.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((j)=>W.push(`- [ ] Test Operation flow: \`${j.name}\``));if($.presentations?.length)$.presentations.forEach((j)=>W.push(`- [ ] Test UI Component: \`${j.name}\``))}}function XN($,W,j,A){let{watcher:Q,fs:Z,logger:X}=$,Y=Q.watch(j),B=A?.validate??(async(H)=>{await m$(H,{fs:Z,logger:X})}),q=A?.build??(async(H)=>{await f$(H,{fs:Z,logger:X},W)});return Y.on(async(H)=>{if(H.type!=="change")return;if(X.info("watchSpecs.changed",{path:H.path}),j.runValidate)await B(H.path);if(j.runBuild)if(j.dryRun)X.info("[dry-run] watchSpecs skipped build",{path:H.path});else await q(H.path)}),Y}async function qN($,W){let j=N5(W),A=$.join(j.workspaceRoot,".contractsrc.json"),Q=$.join(j.packageRoot,".contractsrc.json"),Z=await $.exists(A),X=j.workspaceRoot!==j.packageRoot?await $.exists(Q):!1,Y;if(Z)try{let B=await $.readFile(A),q=JSON.parse(B);if(q.packages||q.excludePackages||q.recursive)Y={packages:q.packages,excludePackages:q.excludePackages,recursive:q.recursive}}catch{}return{...j,monorepoConfig:Y,workspaceConfigPath:Z?A:void 0,packageConfigPath:X?Q:void 0}}async function HN($,W){let j=[],A=$.join(W,".contractsrc.json");if(await $.exists(A))j.push(A);let Q=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let Z of Q)if(Z!==A)j.push(Z);return j}async function VN($,W,j){let A={};if(W&&await $.exists(W))try{let Q=await $.readFile(W);A=JSON.parse(Q)}catch{}if(j&&await $.exists(j))try{let Q=await $.readFile(j),Z=JSON.parse(Q);A=_A(A,Z)}catch{}return A}function _A($,W){let j={...$};for(let A of Object.keys(W)){let Q=$[A],Z=W[A];if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q)&&typeof Z==="object"&&Z!==null&&!Array.isArray(Z))j[A]=_A(Q,Z);else j[A]=Z}return j}function GN($){let W=[];if(W.push(`Package Manager: ${$.packageManager}`),W.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(W.push("Monorepo: Yes"),W.push(`Package Root: ${$.packageRoot}`),$.packageName)W.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)W.push(`Package Patterns: ${$.packages.join(", ")}`)}else W.push("Monorepo: No");if($.workspaceConfigPath)W.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)W.push(`Package Config: ${$.packageConfigPath}`);return W.join(`
2164
+ `)}export{XN as watchSpecs,wA as vibe,QA as versioning,hB as verifyWithAIEnhanced,T0 as verifyWithAI,F0 as verifyStructure,Qq as verifyService,k9 as verifySemanticFields,CY as verifyImportedContracts,UO as verifyImplementationAgainstParsedSpec,nW as verifyBehavior,wI as validateTenantConfig,qI as validateSpecs,m$ as validateSpec,Q9 as validateScannedSpec,QI as validatePackageScaffold,sS as validateImplementationWithAgent,KW as validateImplementationFiles,BI as validateDiscoveredSpecs,iS as validateBlueprint,jH as validateAudience,mU as validateAgainstOpenApiService,K8 as utils,R9 as upgrade,cI as updateSpec,h7 as toKebabCase,B8 as templates,xU as syncWithOpenApiService,NI as syncSpecs,FB as stringToCacheKey,EW as setupGitignore,WS as searchRegistry,r as safeParseJson,vI as runTests,mI as runTestSpecs,PS as runSetup,dO as runQuickstart,g8 as runDoctor,Y_ as runCIChecks,S8 as resolveSetupTargets,b$ as resolveSetupPreset,mj as resolveRegistryUrl,c7 as resolveImplementations,L1 as resolveDefaultBuildTargets,p4 as resolveAuthoredModuleValue,a8 as resolveAllImplementations,P5 as prompts,M5 as parseGitModules,i8 as parseExplicitImplementations,AG as operationRegistry,QR as module,VN as mergeMonorepoConfigs,uX as mergeGitignoreContent,m as loadWorkspaceConfig,Lw as loadPackageAuthoredDocBlocks,o4 as loadAuthoredModuleValue,vO as loadAuthoredModuleIfExists,vW as loadAuthoredModuleExports,Q$ as loadAuthoredModule,Uw as loadAuthoredDocBlocksFromSourceFiles,PI as listTests,AH as listSpecsForView,$$ as listSpecs,$S as listFromRegistry,w1 as listAgentTypes,e$ as isMonorepo,nO as isContractSpecInstalled,wb as isConnectPreset,bb as isBuilderPreset,B0 as inferSetupPresetFromConfig,k7 as inferImplementationType,OY as importFromSourceService,y4 as importFromOpenApiService,H4 as impact,c4 as hooks,DK as groupSpecsByType,WQ as getWorkspacePackages,N5 as getWorkspaceInfo,lH as getRunCommand,yj as getProductionDependencies,I$ as getPackageName,AQ as getMetaRepoInfo,R5 as getInstallCommand,tw as getImplementationSummary,aJ as getGraphStats,qN as getExtendedWorkspaceInfo,oH as getExecCommand,vj as getDevDependencies,xj as getDependencies,o8 as getConventionPaths,pJ as getContractNode,qW as getClaudeDesktopConfigPath,I8 as getBuilderRuntimeModeForPreset,M8 as getBuilderBootstrapPresetForSetupPreset,J8 as getApiKey,_K as getAllSpecs,yb as getAllLayerLocations,$0 as getAgentAdapter,V1 as getAIProvider,l0 as genericMCPAdapter,Y8 as generateWorkflowSpec,jW as generateWorkflowRunnerTemplate,a0 as generateWorkflowDevkitWorkflowTemplate,$W as generateWorkflowDevkitStreamRouteTemplate,s0 as generateWorkflowDevkitStartRouteTemplate,WW as generateWorkflowDevkitGenericTemplate,e0 as generateWorkflowDevkitFollowUpRouteTemplate,BW as generateVscodeSettings,jN as generateViews,QH as generateView,s5 as generateTestTemplate,X8 as generateTelemetrySpec,Z8 as generatePresentationSpec,Q8 as generateOperationSpec,A8 as generateMigrationSpec,_O as generateMermaidDiagram,NY as generateMarkdownReport,W8 as generateKnowledgeSpaceSpec,$8 as generateIntegrationSpec,t5 as generateHandlerTemplate,vY as generateGuideFromParsedSpec,p5 as generateFormSpec,i5 as generateFeatureSpec,MO as generateFeatureContextMarkdown,o5 as generateExperimentSpec,l5 as generateEventSpec,d8 as generateDocsFromSpecs,r5 as generateDataViewSpec,p0 as generateDataViewRendererTemplate,mY as generateCursorRulesFromParsedSpec,C8 as generateCursorRules,q0 as generateCursorMcpConfig,u$ as generateContractsrcConfig,a5 as generateComponentTemplate,RY as generateCliReport,R8 as generateClaudeMcpConfig,c8 as generateArtifacts,c5 as generateAppBlueprintSpec,D8 as generateAgentsGuide,g5 as formatters,GN as formatWorkspaceInfo,LO as formatVerificationReport,cO as formatQuickstartPreview,i4 as formatModuleLoadError,F as formatJson,cL as formatFiles,Bw as formatDoctorSummary,qw as formatCheckResult,g4 as fix,D as findWorkspaceRoot,f as findPackageRoot,E5 as findMetaRepoRoot,HN as findAllConfigFiles,zK as filterIssuesByType,UK as filterIssuesBySeverity,m4 as features,r8 as extractSpecReferences,rU as extractContracts,EO as exportSpecForLLM,F2 as exportOpenApi,tJ as exportGraphAsDot,H8 as ensurePackageScaffold,QW as discoverSpecs,N$ as discoverSpecFiles,VW as discoverLayers,_W as discoverImplementationsForSpec,rw as discoverAllImplementations,p8 as determineStatus,QQ as detectRepositoryType,k$ as detectPackageManager,KU as deleteSpec,p as deepMergePreserve,y1 as deepMergeOverwrite,c0 as cursorCLIAdapter,bM as createWorkspaceStateCacheStorage,RQ as createWorkspaceRegistry,Aq as createVerifyService,IM as createVerificationCacheService,HU as createSpecCreator,E8 as createSetupNextSteps,N8 as createSetupGitignorePatterns,aO as createRegeneratorService,dW as createQuickAIReview,V8 as createPackageTargetSpecSource,U5 as createNoopLoggerAdapter,L5 as createNodeWatcherAdapter,_5 as createNodeGitAdapter,w5 as createNodeFsAdapter,V5 as createNodeAiAdapter,mH as createNodeAdapters,GM as createInMemoryCacheStorage,HM as createFileSystemCacheStorage,r6 as createEmptyLayerInventory,z5 as createConsoleLoggerAdapter,uH as createBunFsAdapter,I6 as createBuilderWorkspaceId,kQ as createAgentGuideService,C4 as connect,y9 as computeContentHash,UU as compareSpecs,w_ as cleanArtifacts,d0 as claudeCodeAdapter,v9 as cacheKeyToString,f$ as buildSpec,XW as analyzeWorkspaceDocBlocks,zW as analyzeIntegrity,iL as analyzeGap,_8 as analyzeDeps,hQ as agentGuideService,b1 as agentAdapters,eO as addToRegistry,mO as __moduleLoaderInternals,F9 as WorkspaceStateCacheStorage,cW as VerifyService,m9 as VerificationCacheService,KA as VALID_AUDIENCES,c3 as TestGeneratorService,T4 as SpecCreatorService,h0 as SimpleAgent,z8 as SETUP_TARGET_LABELS,L8 as SETUP_PRESET_LABELS,O8 as SETUP_PRESET_DESCRIPTIONS,Y0 as SETUP_GITIGNORE_PATTERNS,tY as RuleSyncService,mW as RegistryClient,TQ as PrActionService,k0 as OpenAICodexAgent,t4 as MINIMAL_DEPENDENCIES,T9 as InMemoryCacheStorage,r0 as GenericMCPAdapter,D9 as FileSystemCacheStorage,cY as FULL_DEPENDENCIES,CQ as DriftActionService,Y$ as DEFAULT_SPEC_PATTERNS,S$ as DEFAULT_FS_IGNORES,x9 as DEFAULT_CACHE_CONFIG,n0 as CursorCLIAdapter,P0 as CursorAgent,m0 as ClaudeCodeAgent,u0 as ClaudeCodeAdapter,H_ as CI_CHECK_CATEGORY_LABELS,h8 as CHECK_CATEGORY_LABELS,g0 as AgentOrchestrator,o0 as AgentGuideService,X0 as ALL_SETUP_TARGETS,U8 as ALL_SETUP_PRESETS,q_ as ALL_CI_CHECK_CATEGORIES,k8 as ALL_CHECK_CATEGORIES,CW as AIGenerator};