@contractspec/bundle.workspace 4.4.0 → 4.5.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 (51) hide show
  1. package/dist/index.js +873 -552
  2. package/dist/node/index.js +873 -552
  3. package/dist/services/adoption/catalog-core.d.ts +2 -0
  4. package/dist/services/adoption/catalog-entry.d.ts +2 -0
  5. package/dist/services/adoption/catalog-runtime.d.ts +2 -0
  6. package/dist/services/adoption/catalog-shared.d.ts +2 -0
  7. package/dist/services/adoption/catalog-solutions.d.ts +2 -0
  8. package/dist/services/adoption/catalog-ui.d.ts +2 -0
  9. package/dist/services/adoption/catalog.d.ts +3 -0
  10. package/dist/services/adoption/index.d.ts +6 -0
  11. package/dist/services/adoption/resolve.d.ts +6 -0
  12. package/dist/services/adoption/resolve.test.d.ts +1 -0
  13. package/dist/services/adoption/tokens.d.ts +6 -0
  14. package/dist/services/adoption/types.d.ts +99 -0
  15. package/dist/services/adoption/workspace-scan.d.ts +8 -0
  16. package/dist/services/adoption/workspace.d.ts +3 -0
  17. package/dist/services/connect/adoption.d.ts +10 -0
  18. package/dist/services/connect/types.d.ts +1 -1
  19. package/dist/services/deps.d.ts +1 -1
  20. package/dist/services/doctor/checks/config.test.d.ts +1 -0
  21. package/dist/services/index.d.ts +3 -0
  22. package/dist/services/integrity.d.ts +1 -1
  23. package/dist/services/onboarding/catalog.d.ts +4 -0
  24. package/dist/services/onboarding/index.d.ts +4 -0
  25. package/dist/services/onboarding/journey.d.ts +11 -0
  26. package/dist/services/onboarding/render.d.ts +5 -0
  27. package/dist/services/onboarding/service.d.ts +5 -0
  28. package/dist/services/onboarding/service.test.d.ts +1 -0
  29. package/dist/services/onboarding/types.d.ts +71 -0
  30. package/dist/services/setup/config-generators.d.ts +4 -0
  31. package/dist/services/setup/index.d.ts +3 -0
  32. package/dist/services/setup/managed-markdown.d.ts +8 -0
  33. package/dist/services/setup/targets/agents-md.d.ts +2 -0
  34. package/dist/services/setup/targets/index.d.ts +1 -0
  35. package/dist/services/setup/targets/usage-md.d.ts +5 -0
  36. package/dist/services/setup/targets/usage-md.test.d.ts +1 -0
  37. package/dist/services/setup/types.d.ts +2 -2
  38. package/dist/services/validate/spec-validator.d.ts +1 -1
  39. package/dist/services/validate/spec-validator.test.d.ts +1 -0
  40. package/dist/services/versioning/index.d.ts +1 -0
  41. package/dist/services/versioning/release-authoring.d.ts +14 -0
  42. package/dist/services/versioning/release-authoring.test.d.ts +1 -0
  43. package/dist/services/versioning/release-files.d.ts +7 -0
  44. package/dist/services/versioning/release-service.types.d.ts +53 -1
  45. package/dist/templates/additional-contracts.template.d.ts +40 -0
  46. package/dist/templates/advanced-contracts.template.d.ts +39 -0
  47. package/dist/templates/index.d.ts +3 -0
  48. package/dist/templates/theme.template.d.ts +12 -0
  49. package/dist/templates/theme.template.test.d.ts +1 -0
  50. package/dist/types.d.ts +16 -11
  51. package/package.json +10 -9
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // @bun
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=`
2
+ var f1=Object.defineProperty;var h1=($)=>$;function c1($,b){this[$]=h1.bind(null,b)}var P=($,b)=>{for(var A in b)f1($,A,{get:b[A],enumerable:!0,configurable:!0,set:c1.bind(b,A)})};var $W=($,b)=>()=>($&&(b=$($=0)),b);var M$=import.meta.require;import{ContractsrcSchema as g8,DEFAULT_CONTRACTSRC as MA}from"@contractspec/lib.contracts-spec/workspace-config";async function g($,b){let A=$.join(b??".",".contractsrc.json");if(!await $.exists(A))return MA;try{let n=await $.readFile(A),W=JSON.parse(n),w=g8.safeParse(W);return{...MA,...w.data,conventions:{...MA.conventions,...w.data?.conventions||{}}}}catch{return MA}}function Rw($){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 s=()=>{};var dj={};P(dj,{AIGenerator:()=>A0});import{createProvider as q4}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as O4,buildEventSpecPrompt as V4,buildFormPrompt as J4,buildHandlerPrompt as K4,buildOperationSpecPrompt as _4,buildPresentationSpecPrompt as U4,buildTestPrompt as z4,getCodeGenSystemPrompt as Pb,getSystemPrompt as wn}from"@contractspec/module.workspace";import{generateObject as jn,generateText as b0,streamText as L4}from"ai";import*as R from"zod";class A0{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||Rw(this.config.aiProvider),A={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return q4(A).getModel()}async generateOperationSpec($,b){let A=this.getModel(),m=R.object({name:R.string().describe('Dot notation name like "domain.operation"'),version:R.number().int().positive().default(1),description:R.string().describe("Clear, concise summary"),goal:R.string().describe("Business purpose"),context:R.string().describe("Background and constraints"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).describe("Team/person owners with @ prefix"),tags:R.array(R.string()).describe("Categorization tags"),auth:R.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:R.string().describe("Description of input structure"),outputShape:R.string().describe("Description of output structure"),flags:R.array(R.string()).describe("Feature flags").default([]),possibleEvents:R.array(R.string()).describe("Events this may emit").default([]),analytics:R.array(R.string()).describe("Analytics events to track").default([])}),n=_4($,b);return(await jn({model:A,schema:m,prompt:n,system:wn()})).object}async generateEventSpec($){let b=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),m=V4($);return(await jn({model:b,schema:A,prompt:m,system:wn()})).object}async generatePresentationSpec($,b){let A=this.getModel(),m=R.object({name:R.string(),version:R.number().int().positive().default(1),description:R.string(),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),componentKey:R.string().optional(),propsShape:R.string().optional(),content:R.string().optional(),mimeType:R.string().optional(),dataShape:R.string().optional()}),n=U4($,b);return(await jn({model:A,schema:m,prompt:n,system:wn()})).object}async generateHandler($){let b=this.getModel();return(await b0({model:b,prompt:K4($),system:Pb()})).text}async generateComponent($){let b=this.getModel();return(await b0({model:b,prompt:O4($),system:Pb()})).text}async generateForm($){let b=this.getModel();return(await b0({model:b,prompt:J4($),system:Pb()})).text}async generateTests($,b,A){let m=this.getModel();return(await b0({model:m,prompt:z4($,b,A),system:Pb()})).text}async streamCodeGeneration($,b){let A=this.getModel(),m=await L4({model:A,prompt:$,system:Pb()}),n="";for await(let W of m.textStream)n+=W,b(W);return n}}var m0=$W(()=>{s()});import*as Sx from"@contractspec/module.workspace";import{anthropic as d1}from"@ai-sdk/anthropic";import{openai as bW}from"@ai-sdk/openai";import{DEFAULT_MODELS as AW}from"@contractspec/lib.ai-providers/models";import{generateObject as u1,generateText as o1,streamText as i1}from"ai";import{ollama as l1}from"ollama-ai-provider";function mW($){return{async validateProvider(b){try{let{aiProvider:A}=b;if(A==="ollama")return{success:!0};if(A==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(A==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(A){return{success:!1,error:A instanceof Error?A.message:String(A)}}},async generateText(b){let A=N0($);return{text:(await o1({model:A,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let m={model:N0($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await u1(m)).object}},async streamText(b,A){let m=N0($),n=await i1({model:m,prompt:b.prompt,system:b.systemPrompt}),W="";for await(let w of n.textStream)W+=w,A(w);return W}}}function N0($){let{aiProvider:b,aiModel:A,customEndpoint:m}=$;switch(b){case"claude":{let n=A??AW.anthropic;return d1(n)}case"openai":{let n=A??AW.openai;return bW(n)}case"ollama":return l1(A??"codellama");case"custom":{if(!m)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return bW(A??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as SB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as t1,stat as p1,mkdir as nW,readFile as a1,rm as e1,writeFile as s1}from"fs/promises";import{basename as $B,dirname as WW,isAbsolute as bB,join as AB,relative as mB,resolve as wW}from"path";import{glob as nB}from"glob";var X$=["**/*.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"],x$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function jW($){let b=$??process.cwd();return{async exists(m){try{return await t1(A(m)),!0}catch{return!1}},async readFile(m){return a1(A(m),"utf-8")},async writeFile(m,n){let W=A(m),w=WW(W);await nW(w,{recursive:!0}),await s1(W,n,"utf-8")},async remove(m){await e1(A(m),{recursive:!0,force:!0})},async stat(m){let n=await p1(A(m));return{size:n.size,isFile:n.isFile(),isDirectory:n.isDirectory(),mtime:n.mtime}},async mkdir(m){await nW(A(m),{recursive:!0})},async glob(m){let n=m.patterns??(m.pattern?[m.pattern]:X$),W=m.ignore??x$,w=m.cwd??b,j=m.absolute??!0;return(await nB(n,{cwd:w,ignore:W,absolute:j})).sort((B,S)=>B.localeCompare(S))},resolve(...m){let[n,...W]=m;if(!n)return b;return wW(b,n,...W)},dirname(m){return WW(m)},basename(m){return $B(m)},join(...m){return AB(...m)},relative(m,n){return mB(m,n)}};function A(m){return bB(m)?m:wW(b,m)}}import{execFileSync as Zb}from"child_process";import{access as WB}from"fs/promises";import{resolve as yW}from"path";function BW($){let b=$??process.cwd();return{async currentBranch(){try{let A=Zb("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();return A.length>0?A:void 0}catch{return}},async showFile(A,m){try{return Zb("git",["show",`${A}:${m}`],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}catch(n){throw Error(`Could not load ${m} at ref ${A}: ${n instanceof Error?n.message:String(n)}`)}},async clean(A){let m=[];if(A?.force)m.push("-f");if(A?.directories)m.push("-d");if(A?.ignored)m.push("-x");if(A?.dryRun)m.push("--dry-run");Zb("git",["clean",...m],{cwd:b,stdio:"inherit"})},async isGitRepo(A){let m=A?yW(b,A):b;try{return await WB(yW(m,".git")),!0}catch{return!1}},async log(A){let m=A??"HEAD~10",n="--format=%H|||%s|||%an|||%aI";try{let W=Zb("git",["log",`${m}..HEAD`,"--format=%H|||%s|||%an|||%aI"],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}),w=[];for(let j of W.trim().split(`
3
+ `)){if(!j)continue;let[y,B,S,Q]=j.split("|||");if(y&&B)w.push({hash:y,message:B,author:S,date:Q})}return w}catch{return[]}},async diffFiles(A,m){try{let n=m&&m.length>0?["--",...m]:[];return Zb("git",["diff","--name-only",`${A}...HEAD`,...n],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim().split(`
4
+ `).filter(Boolean)}catch{return[]}}}}function SW(){return{debug($,b){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,b??"")},info($,b){console.info(`[INFO] ${$}`,b??"")},warn($,b){console.warn(`[WARN] ${$}`,b??"")},error($,b){console.error(`[ERROR] ${$}`,b??"")},createProgress(){return wB()}}}function QW(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:jB}}function wB(){return{start($){console.warn(`\u23F3 ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`\u2705 ${$??"Done"}`)},fail($){console.error(`\u274C ${$??"Failed"}`)},warn($){console.warn(`\u26A0\uFE0F ${$??"Warning"}`)},stop(){}}}function jB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import yB from"chokidar";var BB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function ZW($){let b=$??process.cwd();return{watch(A){let m=[],n,W=yB.watch(A.pattern,{cwd:b,ignored:A.ignore??BB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),w=(j)=>{if(A.debounceMs&&A.debounceMs>0)clearTimeout(n),n=setTimeout(()=>{m.forEach((y)=>y(j))},A.debounceMs);else m.forEach((y)=>y(j))};return W.on("add",(j)=>{w({type:"add",path:j})}),W.on("change",(j)=>{w({type:"change",path:j})}),W.on("unlink",(j)=>{w({type:"unlink",path:j})}),{on(j){m.push(j)},async close(){clearTimeout(n),await W.close()}}}}}function XX($={}){let{cwd:b,config:A,silent:m}=$,n=A??SB;return{fs:jW(b),git:BW(b),watcher:ZW(b),ai:mW(n),logger:m?QW():SW()}}import{stat as QB,mkdir as ZB}from"fs/promises";import{basename as GB,dirname as XB,isAbsolute as YB,join as HB,relative as qB,resolve as GW}from"path";import{glob as OB}from"glob";function JX($){let b=$??process.cwd();return{async exists(m){let n=Bun.file(A(m));try{return await n.exists(),!0}catch{return!1}},async readFile(m){return Bun.file(A(m)).text()},async writeFile(m,n){let W=A(m);await Bun.write(W,n)},async remove(m){await Bun.file(A(m)).delete()},async stat(m){let n=await QB(A(m));return{size:n.size,isFile:n.isFile(),isDirectory:n.isDirectory(),mtime:n.mtime}},async mkdir(m){await ZB(A(m),{recursive:!0})},async glob(m){let n=m.patterns??(m.pattern?[m.pattern]:X$),W=m.ignore??x$,w=m.cwd??b,j=m.absolute??!0;return await OB(n,{cwd:w,ignore:W,absolute:j})},resolve(...m){let[n,...W]=m;if(!n)return b;return GW(b,n,...W)},dirname(m){return XB(m)},basename(m){return GB(m)},join(...m){return HB(...m)},relative(m,n){return qB(m,n)}};function A(m){return YB(m)?m:GW(b,m)}}import{existsSync as d,readFileSync as K$}from"fs";import{tmpdir as VB}from"os";import{dirname as F0,isAbsolute as JB,join as c,relative as KB,resolve as u$}from"path";var XW={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},YW=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function _B($,b){let A=KB(b,$);return A===""||!A.startsWith("..")&&!JB(A)}function v0($){let b=u$($),A=u$(VB());return _B(b,A)?A:void 0}function r($=process.cwd()){let b=u$($),A=v0($);while(!0){if(d(c(b,"package.json")))return b;let m=F0(b);if(m===b||b===A)break;b=m}return $}function M($=process.cwd()){let b=u$($),A=null,m=v0($);while(!0){for(let w of YW)if(d(c(b,w)))return b;let n=c(b,"package.json");if(d(n)){A=b;try{if(JSON.parse(K$(n,"utf-8")).workspaces)return b}catch{}}for(let w of Object.keys(XW))if(d(c(b,w)))return b;let W=F0(b);if(W===b||b===m)break;b=W}return A??$}function o$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let m of b){let n=Object.entries(XW).filter(([,W])=>W===m);for(let[W]of n)if(d(c($,W)))return m}let A=c($,"package.json");if(d(A))try{let m=JSON.parse(K$(A,"utf-8"));if(m.packageManager){let n=m.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(n)return n[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Gb($=process.cwd()){for(let A of YW)if(d(c($,A)))return!0;let b=c($,"package.json");if(d(b))try{if(JSON.parse(K$(b,"utf-8")).workspaces)return!0}catch{}return!1}function UB($){let b=c($,"pnpm-workspace.yaml");if(d(b))try{let n=K$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(n?.[1])return n[1].split(`
5
+ `).map((w)=>w.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let A=c($,"package.json");if(d(A))try{let m=JSON.parse(K$(A,"utf-8"));if(Array.isArray(m.workspaces))return m.workspaces;if(m.workspaces?.packages&&Array.isArray(m.workspaces.packages))return m.workspaces.packages}catch{}return}function T$($){let b=c($,"package.json");if(d(b))try{return JSON.parse(K$(b,"utf-8")).name}catch{}return}function HW($){let b=c($,".gitmodules");if(!d(b))return[];try{let A=K$(b,"utf-8"),m=[],n=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,W;while((W=n.exec(A))!==null){let[,w,j,y]=W;if(w&&j&&y){let B=c($,j),S=d(c(B,"package.json"))&&zB(B);m.push({name:w,path:j,url:y,absolutePath:B,hasWorkspaces:S})}}return m}catch{return[]}}function zB($){let b=c($,"package.json");if(d(b))try{let A=JSON.parse(K$(b,"utf-8"));return Boolean(A.workspaces)}catch{}return d(c($,"pnpm-workspace.yaml"))}function qW($){let b=u$($),A=v0($);while(!0){if(d(c(b,".gitmodules")))return b;let m=F0(b);if(m===b||b===A)break;b=m}return}function LB($){let b=qW($);if(!b)return;let A=HW(b);if(A.length===0)return;let m=u$($),n=A.find((W)=>m.startsWith(W.absolutePath));return{root:b,submodules:A,activeSubmodule:n}}function RB($,b){let A=qW($);if(A){if(HW(A).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function OW($=process.cwd()){let b=r($),A=M($),m=o$(A),n=Gb(A),W=n?UB(A):void 0,w=T$(b),j=RB($,n),y=j==="meta-repo"?LB($):void 0;return{packageManager:m,workspaceRoot:A,packageRoot:b,isMonorepo:n,packages:W,packageName:w,repositoryType:j,metaRepo:y}}function LX($,b){switch($){case"bun":return`bun run ${b}`;case"pnpm":return`pnpm run ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npm run ${b}`}}function RX($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function VW($,b=!1){let A=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${A}`.trim();case"pnpm":return`pnpm add ${A}`.trim();case"yarn":return`yarn add ${A}`.trim();case"npm":return`npm install ${A}`.trim()}}import{anthropic as JW}from"@ai-sdk/anthropic";import{generateText as KW}from"ai";class WA{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 b=JW("claude-3-7-sonnet-20250219"),A=this.buildSystemPrompt($),m=this.buildUserPrompt($),n=await KW({model:b,prompt:m,system:A,temperature:0.2});return{success:!0,code:this.extractCode(n.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:n.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let b=JW("claude-3-7-sonnet-20250219"),A=`
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
- `,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.
34
+ `,m=await KW({model:b,prompt:A,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),n=this.detectIssues(m.text);return{success:!n,code:m.text,errors:n?this.extractErrors(m.text):[],warnings:this.extractWarnings(m.text),suggestions:this.extractSuggestions(m.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}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
@@ -51,7 +51,7 @@ Your code is:
51
51
  - Following SOLID principles and best practices
52
52
  - Modular and testable
53
53
 
54
- Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let W={generate:`Generate a complete, production-ready implementation for this specification:
54
+ Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let b={generate:`Generate a complete, production-ready implementation for this specification:
55
55
 
56
56
  ${$.specCode}
57
57
 
@@ -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((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
77
+ ${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],A=$.toLowerCase();return b.some((m)=>A.includes(m))}extractErrors($){let b=[],A=$.split(`
78
+ `);for(let m of A){let n=m.toLowerCase();if(n.includes("error")||n.includes("bug")||n.includes("incorrect")||n.includes("missing"))b.push(m.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],A=$.split(`
79
+ `);for(let m of A){let n=m.toLowerCase();if(n.includes("warning")||n.includes("should")||n.includes("consider"))b.push(m.trim())}return b}extractSuggestions($){let b=[],A=$.split(`
80
+ `);for(let m of A){let n=m.toLowerCase();if(n.includes("suggest")||n.includes("recommend")||n.includes("could")||n.includes("improvement"))b.push(m.trim())}return b}}import{spawn as CB}from"child_process";import{existsSync as _W}from"fs";import{mkdir as UW,readFile as IB,rm as EB,writeFile as Z$}from"fs/promises";import{homedir as g0,tmpdir as zW}from"os";import{join as u}from"path";class wA{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 b=u(zW(),`cursor-agent-${Date.now()}`);await UW(b,{recursive:!0});let A=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=u(zW(),`cursor-validate-${Date.now()}`);await UW(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let A=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}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(g0(),".cursor","cursor"),u(g0(),"AppData","Local","Programs","cursor","Cursor.exe"),u(g0(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let b of $)if(b.includes("cursor")||b.includes("Cursor")||b.includes("windsurf")||b.includes("Windsurf"))try{if(_W(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let A=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let m of A)try{let n=await m.fn();if(n.success)return n}catch(n){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($,b){if(!this.cursorPath)throw Error("Cursor executable not found");let A=u(b,"spec.ts"),m=u(b,"output.ts"),n=u(b,"INSTRUCTIONS.md");if(await Z$(A,$.specCode),await Z$(n,this.buildDetailedPrompt($)),$.existingCode)await Z$(u(b,"existing.ts"),$.existingCode);return new Promise((W,w)=>{let j=["--wait","--new-window",b],y=CB(this.cursorPath,j,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";y.stdout?.on("data",(Q)=>{B+=Q.toString()}),y.stderr?.on("data",(Q)=>{S+=Q.toString()}),y.on("error",(Q)=>{w(Q)}),y.on("close",async(Q)=>{if(_W(m))try{let Z=await IB(m,"utf-8");W({success:!0,code:Z,metadata:{agentMode:"cursor",method:"cli",exitCode:Q}})}catch(Z){w(Error("Failed to read generated output"))}else w(Error(`Cursor CLI exited with code ${Q}. No output generated.`))}),setTimeout(()=>{y.kill(),w(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let A=u(b,"SPECIFICATION.ts"),m=u(b,"INSTRUCTIONS.md"),n=u(b,"template.ts");return await Z$(A,$.specCode),await Z$(m,this.buildDetailedPrompt($)),await Z$(n,this.generateTemplate($)),await Z$(u(b,"README.md"),`# Cursor Agent Workspace
81
81
 
82
82
  This workspace was prepared for Cursor AI code generation.
83
83
 
@@ -92,19 +92,19 @@ This workspace was prepared for Cursor AI code generation.
92
92
  3. Use Cursor AI to generate code based on the spec
93
93
  4. Save the result as output.ts
94
94
 
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 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
95
+ Workspace path: ${b}
96
+ `),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Z$(u(b,"specification.ts"),$.specCode),await Z$(u(b,"implementation.ts"),$.existingCode||"// No implementation"),await Z$(u(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let A=[{path:"spec.ts",content:$.specCode}];if($.existingCode)A.push({path:"existing.ts",content:$.existingCode});return A}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
97
97
 
98
98
  **Task Type:** ${$.type}
99
99
  **Generated:** ${new Date().toISOString()}
100
100
 
101
- `,j=`## Specification
101
+ `,A=`## Specification
102
102
 
103
103
  \`\`\`typescript
104
104
  ${$.specCode}
105
105
  \`\`\`
106
106
 
107
- `,A={generate:`## Task: Generate Implementation
107
+ `,m={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+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
200
+ Refactored code that maintains functionality while improving quality.`};return b+A+(m[$.type]||m.generate)}buildValidationPrompt($){return`# Implementation Validation Report
201
201
 
202
202
  ## Specification
203
203
  \`\`\`typescript
@@ -245,7 +245,7 @@ Provide detailed feedback for each failed item.
245
245
  Suggest specific improvements with code examples where applicable.`}generateTemplate($){return`// Auto-generated template for ${$.type} task
246
246
  // Specification:
247
247
  ${$.specCode.split(`
248
- `).map((W)=>`// ${W}`).join(`
248
+ `).map((b)=>`// ${b}`).join(`
249
249
  `)}
250
250
 
251
251
  // TODO: Implement according to specification
@@ -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 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=`
258
+ `}async cleanupWorkDir($){try{await EB($,{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 LW}from"@ai-sdk/openai";import{generateText as RW}from"ai";class jA{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 A=this.isComplexTask($)?"o1":"gpt-5.4",m=LW(A),n=this.buildSystemPrompt($),W=this.buildUserPrompt($),w=await RW({model:m,prompt:W,system:n,temperature:0.2});return{success:!0,code:this.extractCode(w.text),metadata:{model:A,agentMode:"openai-codex",usage:w.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=LW("gpt-5.4"),A=`
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
- `,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.
278
+ `,m=await RW({model:b,prompt:A,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),n=this.detectIssues(m.text);return{success:!n,code:m.text,errors:n?this.extractErrors(m.text):[],warnings:this.extractWarnings(m.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],A=($.specCode+($.existingCode||"")).toLowerCase();return b.some((m)=>A.includes(m))}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((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.
315
+ ${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],A=$.toLowerCase();return b.some((m)=>A.includes(m))}extractErrors($){let b=[],A=$.split(`
316
+ `);for(let m of A)if(m.toLowerCase().includes("error")||m.toLowerCase().includes("bug")||m.toLowerCase().includes("fails"))b.push(m.trim());return b}extractWarnings($){let b=[],A=$.split(`
317
+ `);for(let m of A)if(m.toLowerCase().includes("warning")||m.toLowerCase().includes("should")||m.toLowerCase().includes("consider"))b.push(m.trim());return b}}import D$ from"chalk";import TB from"ora";import{generateText as CW}from"ai";var c0={};P(c0,{getCodeGenSystemPrompt:()=>h0,buildTestPrompt:()=>f0,buildHandlerPrompt:()=>k0,buildFormPrompt:()=>r0,buildComponentPrompt:()=>P0});function k0($){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 X1($){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 P0($){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 Y1($){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 r0($){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 B1($,W,j){return`You are a senior developer writing comprehensive tests.
375
+ Return only the TypeScript/TSX code for the form component.`}function f0($,b,A){return`You are a senior developer writing comprehensive tests.
376
376
 
377
377
  Spec:
378
378
  \`\`\`typescript
@@ -381,11 +381,11 @@ ${$}
381
381
 
382
382
  Implementation:
383
383
  \`\`\`typescript
384
- ${W}
384
+ ${b}
385
385
  \`\`\`
386
386
 
387
387
  Generate complete test suite using Vitest that:
388
- ${j==="handler"?`
388
+ ${A==="handler"?`
389
389
  - Test all acceptance scenarios from the spec
390
390
  - Test error cases defined in spec.io.errors
391
391
  - Verify events are emitted correctly
@@ -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 q1(){return`You are an expert TypeScript developer with deep knowledge of:
402
+ Return only the TypeScript test code.`}function h0(){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 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=`
416
+ Always prioritize code quality, safety, and user experience.`}import{getAIProvider as MB}from"@contractspec/lib.ai-providers";function d0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return MB(b)}class yA{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=d0(this.config),A=this.buildPrompt($),m=await CW({model:b,prompt:A,system:h0()});return{success:!0,code:m.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:m.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=d0(this.config),A=`
417
417
  Review the following implementation against its specification.
418
418
 
419
419
  Specification:
@@ -427,17 +427,17 @@ 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
- `,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:
430
+ `,m=await CW({model:b,prompt:A,system:"You are a code review expert. Provide thorough, constructive feedback."}),n=m.text.toLowerCase().includes("error")||m.text.toLowerCase().includes("missing")||m.text.toLowerCase().includes("incorrect");return{success:!n,code:m.text,warnings:n?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return k0($.specCode);else if($.specCode.includes(".presentation."))return P0($.specCode);else if($.specCode.includes(".form."))return r0($.specCode);return`Generate implementation for:
431
+ ${$.specCode}`;case"test":return f0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
432
+ ${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as xB}from"@contractspec/lib.ai-agent/agent/unified-agent";class u0{name;agent;constructor($,b,A={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=xB(A,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),A=await this.agent.run(b);return{success:!0,code:A.text,metadata:{finishReason:A.finishReason,usage:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
433
433
  ${$.specCode}
434
434
 
435
- `;if($.existingCode)W+=`Existing Code:
435
+ `;if($.existingCode)b+=`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 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.
438
+ `;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class BA{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new yA($),A=new wA,m=new WA,n=new jA;this.agents.set("simple",b),this.agents.set("cursor",A),this.agents.set("claude-code",m),this.agents.set("openai-codex",n),this.defaultAgent=b,this.agents.set("opencode-sdk",new u0("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),A=this.agents.get(b);if(!A)return console.log(D$.yellow(`\u26A0\uFE0F Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!A.canHandle($))return console.log(D$.yellow(`\u26A0\uFE0F Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let m=TB(`Executing with ${b} agent...`).start();try{let n=$.type==="validate"?await A.validate($):await A.generate($);if(n.success)return m.succeed(D$.green(`${b} agent completed successfully`)),n;m.warn(D$.yellow(`${b} agent failed, trying fallback...`));let W=this.getFallbackMode(b);if(W&&W!==b){let w=this.agents.get(W);if(w&&w.canHandle($))return $.type==="validate"?await w.validate($):await w.generate($)}return m.info(D$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(n){return m.fail(D$.red("Agent execution failed")),console.log(D$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,A]of this.agents){let m={type:"generate",specCode:"test"},n=A.canHandle(m);$.push({mode:b,available:n,reason:n?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 IW={};P(IW,{specCreation:()=>o0,codeGeneration:()=>c0});var o0={};P(o0,{getSystemPrompt:()=>vB,buildPresentationSpecPrompt:()=>FB,buildOperationSpecPrompt:()=>DB,buildEventSpecPrompt:()=>NB,addExampleContext:()=>gB});function DB($,b){return`You are a senior software architect creating a contract specification for an operation.
439
439
 
440
- The operation is a ${W} (${W==="command"?"changes state, has side effects":"read-only, idempotent"}).
440
+ The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
441
441
 
442
442
  User description: ${$}
443
443
 
@@ -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 GQ($){return`You are a senior software architect creating an event specification.
456
+ Respond with a structured spec.`}function NB($){return`You are a senior software architect creating an event specification.
457
457
 
458
458
  User description: ${$}
459
459
 
@@ -467,9 +467,9 @@ 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 JQ($,W){return`You are a senior software architect creating a presentation specification.
470
+ Respond with a structured spec.`}function FB($,b){return`You are a senior software architect creating a presentation specification.
471
471
 
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]}.
472
+ This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
473
473
 
474
474
  User description: ${$}
475
475
 
@@ -479,13 +479,13 @@ Create a complete presentation specification following these guidelines:
479
479
  2. **Version**: Start at 1
480
480
  3. **Description**: What this presentation shows/provides
481
481
  4. **Kind-specific details**:
482
- ${W==="web_component"?`- Component key (symbolic, resolved by host app)
482
+ ${b==="web_component"?`- Component key (symbolic, resolved by host app)
483
483
  - Props structure
484
- - Analytics events to track`:W==="markdown"?`- Content or resource URI
484
+ - Analytics events to track`:b==="markdown"?`- Content or resource URI
485
485
  - Target audience`:`- MIME type (e.g., application/json)
486
486
  - Data structure description`}
487
487
 
488
- Respond with a structured spec.`}function bQ(){return`You are an expert software architect specializing in API design and contract-driven development.
488
+ Respond with a structured spec.`}function vB(){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,111 +495,359 @@ 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 wQ($,W){if(W.length===0)return $;return`${$}
498
+ Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function gB($,b){if(b.length===0)return $;return`${$}
499
499
 
500
500
  Here are some good examples for reference:
501
501
 
502
- ${W.join(`
502
+ ${b.join(`
503
503
 
504
504
  `)}
505
505
 
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)}
506
+ Follow this structure and quality level.`}var xW={};P(xW,{sarifToJson:()=>cB,formatAsTextLines:()=>MW,formatAsText:()=>dB,formatAsSarif:()=>rB,formatAsJson:()=>kB});function kB($,b={}){let{pretty:A=!0,driftResult:m}=b,n=$.issues.map((S)=>({name:S.ruleId,status:S.severity==="error"?"fail":S.severity==="warning"?"warn":"pass",category:S.category,message:S.message,file:S.file,line:S.line,details:S.context})),W=$.categories.filter((S)=>S.passed).length,w=$.totalErrors,j=$.totalWarnings,y=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:n,categories:$.categories.map((S)=>({category:S.category,label:S.label,passed:S.passed,errors:S.errors,warnings:S.warnings,notes:S.notes,durationMs:S.durationMs})),drift:{status:m?.hasDrift?"detected":"none",files:m?.files??[]},summary:{pass:W,fail:w,warn:j,note:y,total:W+w+j+y,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return A?JSON.stringify(B,null,2):JSON.stringify(B)}var PB={"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 rB($,b={}){let{toolName:A="ContractSpec",toolVersion:m="1.0.0",toolUri:n="https://contractspec.io",repositoryUri:W,workingDirectory:w}=b,j=new Map,y=new Map,B=$.issues.filter((G)=>G.file);for(let G of B)if(!j.has(G.ruleId)){let X=PB[G.ruleId]??{name:G.ruleId,description:`Rule: ${G.ruleId}`},Y={id:G.ruleId,name:X.name,shortDescription:{text:X.description},defaultConfiguration:{level:EW(G.severity)}};if(X.helpUri)Y.helpUri=X.helpUri;y.set(G.ruleId,j.size),j.set(G.ruleId,Y)}let S=B.map((G)=>{let X={ruleId:G.ruleId,ruleIndex:y.get(G.ruleId)??0,level:EW(G.severity),message:{text:G.message}},Y={physicalLocation:{artifactLocation:{uri:fB(G.file),uriBaseId:"%SRCROOT%"}}};if(G.line!==void 0)Y.physicalLocation.region={startLine:G.line,startColumn:G.column??1,endLine:G.endLine??G.line,endColumn:G.endColumn};return X.locations=[Y],X.partialFingerprints={primaryLocationLineHash:hB(G)},X}),Q=[];if(W)Q.push({repositoryUri:W,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:A,version:m,informationUri:n,rules:Array.from(j.values())}},results:S,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...w&&{workingDirectory:{uri:w}}}]};if(Q.length>0)Z.versionControlProvenance=Q;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[Z]}}function EW($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function fB($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function hB($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function cB($){return JSON.stringify($,null,2)}function MW($,b={}){let A=[],{verbose:m=!1,showTiming:n=!0,groupByFile:W=!1}=b;if(A.push({text:"",style:"normal"}),A.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),A.push({text:"",style:"normal"}),$.commitSha||$.branch){let j=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");A.push({text:`Git: ${j}`,style:"muted"})}A.push({text:"",style:"normal"}),A.push({text:"Check Results:",style:"bold"});for(let j of $.categories){let y=j.passed?"\u2713":"\u2717",B=j.passed?"success":"error",S=uB(j),Q=n?` (${j.durationMs}ms)`:"";A.push({text:` ${y} ${j.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(A.push({text:"",style:"normal"}),A.push({text:"Issues:",style:"bold"}),W){let j=oB($.issues);for(let[y,B]of j){A.push({text:"",style:"normal"}),A.push({text:` ${y||"(no file)"}`,style:"bold",indent:1});for(let S of B)A.push(...SA(S,m,2))}}else{let j=$.issues.filter((S)=>S.severity==="error"),y=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(j.length>0){A.push({text:"",style:"normal"}),A.push({text:" Errors:",style:"error",indent:1});for(let S of j)A.push(...SA(S,m,2))}if(y.length>0){A.push({text:"",style:"normal"}),A.push({text:" Warnings:",style:"warning",indent:1});for(let S of y)A.push(...SA(S,m,2))}if(B.length>0&&m){A.push({text:"",style:"normal"}),A.push({text:" Notes:",style:"muted",indent:1});for(let S of B)A.push(...SA(S,m,2))}}A.push({text:"",style:"normal"}),A.push({text:"\u2500".repeat(50),style:"muted"});let w=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&m?`${$.totalNotes} note(s)`:null].filter(Boolean);if(w.length>0)A.push({text:`Found: ${w.join(", ")}`,style:$.success?"warning":"error"});if(n)A.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(A.push({text:"",style:"normal"}),$.success)A.push({text:"\u2705 All CI checks passed!",style:"success"});else A.push({text:"\u274C CI checks failed",style:"error"});return A.push({text:"",style:"normal"}),A}function dB($,b={}){return MW($,b).map((m)=>" ".repeat(m.indent??0)+m.text).join(`
507
+ `)}function uB($){let b=[];if($.errors>0)b.push(`${$.errors} error(s)`);if($.warnings>0)b.push(`${$.warnings} warning(s)`);if(b.length===0)return"passed";return b.join(", ")}function SA($,b,A){let m=[],n=$.severity==="error"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",W=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",w=`${n} ${$.message}`;if($.file){let j=$.line?`:${$.line}`:"";w+=` (${$.file}${j})`}if(m.push({text:w,style:W,indent:A}),b&&$.context){let j=JSON.stringify($.context);if(j!=="{}")m.push({text:`Context: ${j}`,style:"muted",indent:A+1})}return m}function oB($){let b=new Map;for(let A of $){let m=A.file??"";if(!b.has(m))b.set(m,[]);let n=b.get(m);if(n)n.push(A)}return new Map([...b.entries()].sort(([A],[m])=>A.localeCompare(m)))}import{OperationSpecRegistry as iB}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as lB}from"@contractspec/lib.contracts-spec/operations/report";function tB(){let $=new iB;return lB($),$}var vY=tB();class pB{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let A=$.drift?.status==="fail",m=!1;if(A&&b==="fail")m=!0;return{driftDetected:A,shouldFail:m}}}function aB($){if(!$)return"\u2014";let b=new Date($),m=new Date().getTime()-b.getTime(),n=Math.floor(m/86400000);if(n<1)return"today";if(n===1)return"yesterday";return`${n} days ago`}class eB{collectChanges($,b,A){if($){let m=$.endsWith("/")?$:`${$}/`;return A.filter((n)=>n.startsWith(m))}if(b){let m=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return A.filter((n)=>m.test(n))}return A}detectDrift($){let b=$.map((A)=>A.slice(3)).filter((A)=>A&&A.trim().length>0).filter((A)=>A!==".contractspec-ci"&&!A.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},A=b.breaking||0,m=b.nonBreaking||0,n=b.total;if(n===void 0)n=A+m;let W=$?.breaking||!1,w="unknown";if($){if(W||A>0)w="breaking",W=!0;else if(m>0)w="non-breaking";else if(n===0)w="no-impact"}return{status:w,breaking:W,breakingCount:A,nonBreakingCount:m,total:n||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,A=this.deriveImpactStatus($.impactJson),m={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:A.status,breaking:A.breakingCount,nonBreaking:A.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(m.validation?.status==="fail")m.nextSteps?.push("Fix validation errors and rerun the workflow.");if(m.risk?.status==="breaking")m.nextSteps?.push("Review breaking changes and plan a migration.");if(m.risk?.status==="unknown")m.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(m.drift?.status==="fail")m.nextSteps?.push("Run the generate command locally and commit drift fixes.");let n=this.finalizeResults(m,$.failOn);if(n.shouldFail)m.nextSteps?.unshift(`CI failed: ${n.failReasons.join(", ")} (fail_on=${$.failOn}).`);return m}finalizeResults($,b){let A=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,m=$.drift?.status==="fail",n=$.validation?.status==="fail",W=$.risk?.status==="unknown",w=[],j=!1;if(b!=="never"){if(b==="breaking"){if(A)w.push("breaking changes detected");if(W)w.push("impact status unknown")}else if(b==="drift"){if(m)w.push("drift detected");if(W)w.push("impact status unknown")}else if(b==="any"){if(A)w.push("breaking changes detected");if(m)w.push("drift detected");if(n)w.push("validation failed");if(W)w.push("impact status unknown")}else w.push(`invalid fail_on value (${b})`);if(w.length>0)j=!0}return{driftDetected:m,breakingChangeDetected:A,validationFailed:n,shouldFail:j,failReasons:w}}generateReportMarkdown($,b){let A=(y,B=60000)=>{if(y.length<=B)return y;return`${y.slice(0,B)}
508
508
 
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(`
509
+ *(output truncated)*`},m=(y)=>{if(!y||y.length===0)return"- None";return y.slice(0,20).map((B)=>`- ${B}`).join(`
510
+ `)},n=A($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),W=A($.validation?.outputPath?b($.validation.outputPath):""),w=$.drift?.files??[],j=[];if(j.push("## ContractSpec Report"),j.push(""),$.contracts&&$.contracts.length>0){j.push("### Overall verification status"),j.push(""),j.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),j.push("| --- | --- | --- | --- | --- |");for(let y of $.contracts){let B=y.lastVerifiedSha??"\u2014",S=aB(y.lastVerifiedDate),Q=y.surfaces.join(", ");j.push(`| ${y.name} | ${S} | ${y.driftMismatches} | ${Q} | ${B} |`)}j.push("")}if(j.push("### 1) What changed"),$.whatChanged?.summary)j.push($.whatChanged.summary);else j.push("No contract changes detected.");if(n.trim().length>0)j.push(""),j.push("<details>"),j.push("<summary>Contract view (product)</summary>"),j.push(""),j.push(n),j.push(""),j.push("</details>");if(j.push(""),j.push("### 2) Risk classification"),$.risk?.status){let y=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);j.push(y.join(" | "))}else j.push("Impact analysis unavailable.");if(j.push(""),j.push("### 3) Validation results"),$.validation?.status){if(j.push(`Status: ${$.validation.status}`),W.trim().length>0)j.push(""),j.push("<details>"),j.push("<summary>Validation output</summary>"),j.push(""),j.push(W),j.push(""),j.push("</details>")}else j.push("Validation step not run.");if(j.push(""),j.push("### 4) Drift results"),$.drift?.status){if(j.push(`Status: ${$.drift.status}`),w.length>0)j.push(""),j.push("<details>"),j.push("<summary>Drifted files</summary>"),j.push(""),j.push(m(w)),j.push(""),j.push("</details>")}else j.push("Drift check not run.");if(j.push(""),j.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)j.push(m($.nextSteps));else j.push("- No action required.");return`${j.join(`
511
511
  `)}
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
- `)}}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=[],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
- `)}}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 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)}',
512
+ `}}var s0={};P(s0,{uniqueTokens:()=>N$,tokenize:()=>i$,syncAdoptionCatalog:()=>J5,scanWorkspaceAdoptionCandidates:()=>p0,resolveAdoptionWorkspace:()=>l$,resolveAdoption:()=>Xb,overlap:()=>ZA,normalizeText:()=>gW,inferFamilyFromPath:()=>e0,hasLocalShadcnRegistry:()=>a0,getContractSpecAdoptionCatalog:()=>QA,createAdoptionCatalogDocument:()=>i0,candidateTokens:()=>l0});function E($,b,A,m,n,W,w,j,y={}){return{id:$,source:"contractspec",packageRef:b,family:A,packageKind:m,title:y.title??b,description:j,capabilityTags:W,preferredUseCases:w,avoidWhen:y.avoidWhen,platforms:y.platforms,replacementImportHints:y.replacementImportHints,resolutionPriority:n,runtimes:y.runtimes}}var TW=[E("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),E("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),E("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),E("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),E("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var DW=[E("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),E("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),E("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),E("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),E("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),E("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),E("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),E("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var NW=[E("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),E("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),E("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),E("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),E("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),E("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),E("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),E("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),E("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var FW=[E("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),E("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),E("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),E("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),E("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),E("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var vW=[E("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),E("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),E("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var sB=[...vW,...TW,...DW,...NW,...FW];function QA(){return[...sB].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function i0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:QA()}}import{DEFAULT_CONTRACTSRC as y5}from"@contractspec/lib.contracts-spec/workspace-config";function gW($){return $.toLowerCase().trim()}function i$($){return gW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function N$($){return[...new Set($.flatMap((b)=>i$(b)))]}function l0($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return N$(b)}function ZA($,b){let A=new Set(b);return $.filter((m)=>A.has(m)).length}import{resolve as $5}from"path";import{ContractsrcSchema as b5,DEFAULT_CONTRACTSRC as t0}from"@contractspec/lib.contracts-spec/workspace-config";async function l$($,b={}){let A=$5(b.cwd??process.cwd()),m=b.workspaceRoot??M(A),n=b.packageRoot??r(A),W=b.config?PW(t0,b.config):await A5($,m,n);return{adoption:W.connect?.adoption??t0.connect.adoption,config:W,cwd:A,packageRoot:n,workspaceRoot:m}}async function A5($,b,A){let m=t0;if(b!==A)m=await kW($,m,$.join(b,".contractsrc.json"));return kW($,m,$.join(A,".contractsrc.json"))}async function kW($,b,A){if(!await $.exists(A))return b;try{let m=JSON.parse(await $.readFile(A)),n=b5.safeParse(m);if(!n.success)return b;return PW(b,n.data)}catch{return b}}function PW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var m5=["package.json","packages/*/package.json"];async function p0($,b){let[A,m]=await Promise.all([n5($,b),W5($,b)]);return{fileCandidates:m,packageCandidates:A}}async function a0($,b){let A=$.join(b.workspaceRoot,"components.json");if(await $.exists(A))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function n5($,b){let A=await $.glob({patterns:m5,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),m=[];for(let n of A)try{let W=JSON.parse(await $.readFile($.join(b.workspaceRoot,n))),w=e0(n);if(!w)continue;let j=W.name??$.dirname(n);m.push({id:`workspace.package.${j}`,source:"workspace",family:w,title:j,description:W.description??`Local reusable package at ${n}.`,packageKind:j5(n),packageRef:j,capabilityTags:N$([j,n]),preferredUseCases:[n],resolutionPriority:120})}catch{continue}return m}async function W5($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((m)=>{let n=e0(m);if(!n)return[];let W=m.split("/").pop()?.replace(/\.[^.]+$/,"")??m;return[{id:`workspace.file.${m}`,source:"workspace",family:n,title:W,description:`Local reusable source at ${m}.`,filePath:m,capabilityTags:i$(m),preferredUseCases:[m],resolutionPriority:w5(n,m)}]})}function e0($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function w5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function j5($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Xb($,b){let A=await l$($.fs,b),m=q5(b),n=N$([m,b.symbol??"",...b.paths??[]]),W=await p0($.fs,A),w=await O5($,A),j=await a0($.fs,A),y=B5(A,n,b,[...W.packageCandidates,...W.fileCandidates,...w,...V5(b.family,b.platform,j)]),B=y[0]??null,S=y.length>1&&B!=null&&B.candidate.source===y[1].candidate.source&&Math.abs(B.score-y[1].score)<=40,Q=X5(A,B,S,b.currentTarget);return{ambiguous:S,candidates:y,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:m,reason:H5(B,S),selected:B,verdict:Q}}function B5($,b,A,m){return m.filter((n)=>n.family===A.family&&Z5($,n.family)).filter((n)=>G5(n,A.platform)).map((n)=>S5(n,b,A.paths)).filter((n)=>n.score>40).sort((n,W)=>W.score-n.score).slice(0,8)}function S5($,b,A){let m=l0($),n=N$(A??[]),W=[],w=ZA(b,m)*25,j=ZA(n,m)*10;if(w>0)W.push("query overlap");if(j>0)W.push("path overlap");return{candidate:$,matchReasons:W,score:Q5($.source)+($.resolutionPriority??0)+w+j}}function Q5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function Z5($,b){return $.adoption.families?.[b]??!0}function G5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function X5($,b,A,m){let n=$.adoption.thresholds??y5.connect.adoption.thresholds;if(A)return n.ambiguous??"require_review";if(!b)return n.newImplementation??"require_review";if(b.candidate.source==="workspace")return Y5(b.candidate,m)?"permit":n.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return n.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return n.newImplementation??"require_review";return n.newExternalDependency??"require_review"}function Y5($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function H5($,b){if(b)return"Multiple similarly strong adoption candidates were found.";if(!$)return"No reusable workspace or ContractSpec candidate matched the request.";return`Selected ${$.candidate.source} candidate ${$.candidate.title}.`}function q5($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function O5($,b){let A=QA(),m=b.adoption.catalog?.overrideManifestPath;if(!m||!await $.fs.exists($.fs.join(b.workspaceRoot,m)))return A;try{let n=await $.fs.readFile($.fs.join(b.workspaceRoot,m)),W=JSON.parse(n);return[...A,...Array.isArray(W)?W:W.entries??[]]}catch{return A}}function V5($,b,A){if($==="ui"&&b==="web"&&A)return[t$("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[t$("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[t$("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[t$("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[t$("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[t$("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function t$($,b,A,m,n){return{id:$,source:"ecosystem",packageRef:A,family:b,packageKind:"primitive",title:m,description:m,capabilityTags:i$(m),preferredUseCases:[m],resolutionPriority:n}}async function J5($,b={}){let A=await l$($.fs,b),m=i0(),n=$.fs.join(A.workspaceRoot,A.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(n,`${JSON.stringify(m,null,2)}
513
+ `),{catalog:m,catalogPath:n}}import{AGENT_SYSTEM_PROMPTS as K5}from"@contractspec/lib.contracts-spec/llm";class GA{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let A of $.fileStructure){let m=A.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";b.push(`${m} \`${A.path}\``),b.push(` ${A.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let A of $.steps){b.push(`### ${A.order}. ${A.title}`),b.push(""),b.push(A.description),b.push(""),b.push("**Acceptance Criteria:**");for(let m of A.acceptanceCriteria)b.push(`- [ ] ${m}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let A of $.constraints.security)b.push(`- \u26A0\uFE0F ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:K5["claude-code"],taskPrompt:b.join(`
514
+ `)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
515
+ `)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let A=[],m=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let n of m){let W=$.matchAll(n);for(let w of W)if(w[1])A.push(w[1])}if(A.length>0)return{errors:A};return{code:$}}}var XA=new GA;import{AGENT_SYSTEM_PROMPTS as _5}from"@contractspec/lib.contracts-spec/llm";class YA{agentType="cursor-cli";formatPlan($){let b=[];if(b.push(`# ${$.target.key}.v${$.target.version}`),b.push(""),b.push(`> ${$.context.goal}`),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push("");for(let m of $.fileStructure)b.push(`- ${m.type}: \`${m.path}\` - ${m.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let m of $.steps)b.push(`${m.order}. **${m.title}**: ${m.description}`);b.push("");let A=[...$.constraints.policy,...$.constraints.security.map((m)=>`\u26A0\uFE0F ${m}`)];if(A.length>0){b.push("## Constraints"),b.push("");for(let m of A)b.push(`- ${m}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((m)=>`\`${m}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:_5["cursor-cli"],taskPrompt:b.join(`
516
+ `)}}generateConfig($){let b=$.meta,A=[];if(A.push("---"),A.push(`description: Implementation rules for ${b.key}.v${b.version}`),A.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),A.push("alwaysApply: false"),A.push("---"),A.push(""),A.push(`# ${b.key} Implementation Rules`),A.push(""),A.push(`This ${b.kind} operation must follow the ContractSpec specification.`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Requirements"),A.push(""),A.push("1. Input/output types MUST match the spec schema exactly"),A.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)A.push("3. Events MUST be emitted as specified");if(A.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)A.push(`5. Idempotency: ${$.policy.idempotent}`);if(A.push(""),$.io.errors&&Object.keys($.io.errors).length>0){A.push("## Error Cases"),A.push("");for(let[m,n]of Object.entries($.io.errors))A.push(`- \`${m}\` (HTTP ${n.http??400}): ${n.when}`);A.push("")}if($.sideEffects?.emits?.length){A.push("## Events to Emit"),A.push("");for(let m of $.sideEffects.emits)if("ref"in m)A.push(`- \`${m.ref.key}.v${m.ref.version}\`: ${m.when}`);else A.push(`- \`${m.key}.v${m.version}\`: ${m.when}`);A.push("")}if($.policy.pii?.length){A.push("## PII Handling"),A.push(""),A.push("These fields contain PII and must be handled with care:");for(let m of $.policy.pii)A.push(`- \`${m}\``);A.push("")}if($.acceptance?.scenarios?.length){A.push("## Acceptance Scenarios"),A.push("");for(let m of $.acceptance.scenarios)A.push(`### ${m.key}`),A.push(`- Given: ${m.given.join("; ")}`),A.push(`- When: ${m.when.join("; ")}`),A.push(`- Then: ${m.then.join("; ")}`),A.push("")}return A.join(`
517
+ `)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var HA=new YA;import{AGENT_SYSTEM_PROMPTS as U5}from"@contractspec/lib.contracts-spec/llm";class qA{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let A of $.fileStructure)b.push(`| \`${A.path}\` | ${A.type} | ${A.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let A of $.steps)if(b.push(`### Step ${A.order}: ${A.title}`),b.push(""),b.push(A.description),b.push(""),A.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let m of A.acceptanceCriteria)b.push(`- ${m}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let A of $.constraints.security)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),{agent:"generic-mcp",systemPrompt:U5["generic-mcp"],taskPrompt:b.join(`
518
+ `)}}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 b=$.meta,A=[];return A.push(`# ${b.key} v${b.version}`),A.push(""),A.push(`**Type:** ${b.kind}`),A.push(`**Stability:** ${b.stability}`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Description"),A.push(""),A.push(b.description),A.push(""),A.join(`
519
+ `)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let A=JSON.parse($);if(typeof A.code==="string")return{code:A.code};if(typeof A.errors==="object")return{errors:Array.isArray(A.errors)?A.errors:[String(A.errors)]}}catch{}return{code:$}}}var OA=new qA;var $m={"claude-code":XA,"cursor-cli":HA,"generic-mcp":OA};function Yb($){let b=$m[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function bm(){return Object.keys($m)}import{featureToMarkdown as Am,generateImplementationPlan as rW,operationSpecToAgentPrompt as z5,operationSpecToFullMarkdown as L5}from"@contractspec/lib.contracts-spec/llm";var R5={defaultAgent:"generic-mcp",verbose:!1};class VA{config;constructor($={}){this.config={...R5,...$}}generateGuide($,b={}){let A=b.agent??this.config.defaultAgent,m=Yb(A),n=rW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),W=m.formatPlan(n),w=L5($);return{plan:n,prompt:W,markdown:w}}generateFeatureGuide($,b,A={}){let m=A.agent??this.config.defaultAgent,n=Yb(m),W=$.operations?.[0],w=W?b.specs?.get(W.key,W.version):void 0,j;if(w)j=rW(w,{projectRoot:this.config.projectRoot}),j.target={type:"feature",key:$.meta.key,version:"1.0.0"},j.context.goal=$.meta.description??j.context.goal;else j={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:Am($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(j.specMarkdown=Am($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)j.steps=$.operations.map((S,Q)=>({order:Q+1,title:`Implement ${S.key}`,description:`Implement operation ${S.key}.v${S.version}`,acceptanceCriteria:[`Operation ${S.key} works as specified`]}));let y=n.formatPlan(j),B=Am($,b);return{plan:j,prompt:y,markdown:B}}generateAgentConfig($,b){return Yb(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,A="implement",m){return z5($,{taskType:A,existingCode:m})}listAgentTypes(){return bm()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function C5($){return new VA($)}var I5=new VA;import{detectAuthoringTarget as J8,generateComponentTemplate as K8,generateHandlerTemplate as _8,generateTestTemplate as U8,getAuthoringTargetDefinition as z8,inferSpecTypeFromFilePath as L8,scanSpecSource as R8}from"@contractspec/module.workspace";var Kw={};P(Kw,{generateWorkflowSpec:()=>Jw,generateWorkflowRunnerTemplate:()=>EA,generateWorkflowDevkitWorkflowTemplate:()=>zA,generateWorkflowDevkitStreamRouteTemplate:()=>CA,generateWorkflowDevkitStartRouteTemplate:()=>LA,generateWorkflowDevkitGenericTemplate:()=>IA,generateWorkflowDevkitFollowUpRouteTemplate:()=>RA,generateVisualizationSpec:()=>oW,generateTranslationSpec:()=>dW,generateThemeSpec:()=>Vw,generateTestTemplate:()=>Sw,generateTestSpec:()=>cW,generateTelemetrySpec:()=>Ow,generateProductIntentSpec:()=>tW,generatePresentationSpec:()=>qw,generatePolicySpec:()=>hW,generateOperationSpec:()=>Hw,generateMigrationSpec:()=>Yw,generateKnowledgeSpaceSpec:()=>Gw,generateJobSpec:()=>uW,generateIntegrationSpec:()=>Zw,generateHarnessSuiteSpec:()=>aW,generateHarnessScenarioSpec:()=>pW,generateHandlerTemplate:()=>yw,generateFormSpec:()=>jw,generateFeatureSpec:()=>ww,generateExperimentSpec:()=>Ww,generateExampleSpec:()=>iW,generateEventSpec:()=>nw,generateDataViewSpec:()=>mw,generateDataViewRendererTemplate:()=>_A,generateComponentTemplate:()=>Bw,generateCapabilitySpec:()=>fW,generateAppBlueprintSpec:()=>Aw,generateAgentSpec:()=>lW});function fW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
520
+
521
+ export const ${a$($.key)}Capability = defineCapability({
522
+ meta: {
523
+ key: '${$.key}',
524
+ version: '${$.version}',
525
+ kind: '${$.kind??"api"}',
526
+ title: '${k(p$($))}',
527
+ description: '${k($.description)}',
528
+ domain: '${k(F$($))}',
529
+ owners: [${W$($.owners)}],
530
+ tags: [${W$($.tags)}],
531
+ stability: '${$.stability}',
532
+ },
533
+ provides: [],
534
+ requires: [],
535
+ });
536
+ `}function hW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
537
+
538
+ export const ${a$($.key)}Policy = definePolicy({
539
+ meta: {
540
+ key: '${$.key}',
541
+ version: '${$.version}',
542
+ title: '${k(p$($))}',
543
+ description: '${k($.description)}',
544
+ domain: '${k(F$($))}',
545
+ owners: [${W$($.owners)}],
546
+ tags: [${W$($.tags)}],
547
+ stability: '${$.stability}',
548
+ scope: '${$.scope??"feature"}',
549
+ },
550
+ rules: [
551
+ {
552
+ effect: 'allow',
553
+ actions: ['read'],
554
+ resource: { type: '${k(F$($))}' },
555
+ reason: 'TODO: replace with real access rules',
556
+ },
557
+ ],
558
+ });
559
+ `}function cW($){let b=$.targetVersion??"1.0.0",A=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
560
+
561
+ export const ${a$($.key)}TestSpec = defineTestSpec({
562
+ meta: {
563
+ key: '${$.key}',
564
+ version: '${$.version}',
565
+ title: '${k(p$($))}',
566
+ description: '${k($.description)}',
567
+ domain: '${k(F$($))}',
568
+ owners: [${W$($.owners)}],
569
+ tags: [${W$($.tags)}],
570
+ stability: '${$.stability}',
571
+ },
572
+ target: {
573
+ type: '${$.targetType}',
574
+ ${$.targetType}: ${A},
575
+ },
576
+ scenarios: [
577
+ {
578
+ key: 'success',
579
+ when: { ${$.targetType}: { key: '${$.targetKey}' } },
580
+ then: [{ type: 'expectOutput', match: {} }],
581
+ },
582
+ ],
583
+ });
584
+ `}function dW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
585
+
586
+ export const ${a$(`${$.key}.${$.locale}`)}Translation = defineTranslation({
587
+ meta: {
588
+ key: '${$.key}',
589
+ version: '${$.version}',
590
+ domain: '${k(F$($))}',
591
+ description: '${k($.description)}',
592
+ owners: [${W$($.owners)}],
593
+ tags: [${W$($.tags)}],
594
+ stability: '${$.stability}',
595
+ },
596
+ locale: '${$.locale}',
597
+ fallback: '${$.fallback??$.locale}',
598
+ messages: {
599
+ '${$.key}.title': {
600
+ value: '${k(p$($))}',
601
+ description: 'TODO: replace with a real localized message',
602
+ },
603
+ },
604
+ });
605
+ `}function uW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
606
+
607
+ export const ${a$($.key)}Job = defineJob({
608
+ meta: {
609
+ key: '${$.key}',
610
+ version: '${$.version}',
611
+ title: '${k(p$($))}',
612
+ description: '${k($.description)}',
613
+ domain: '${k(F$($))}',
614
+ owners: [${W$($.owners)}],
615
+ tags: [${W$($.tags)}],
616
+ stability: '${$.stability}',
617
+ },
618
+ payload: { schema: {} },
619
+ schedule: { intervalMs: ${$.intervalMs??60000} },
620
+ });
621
+ `}function oW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
622
+
623
+ export const ${a$($.key)}Visualization = defineVisualization({
624
+ meta: {
625
+ key: '${$.key}',
626
+ version: '${$.version}',
627
+ title: '${k(p$($))}',
628
+ description: '${k($.description)}',
629
+ goal: 'TODO: describe the decision this visualization supports',
630
+ context: 'TODO: describe where this visualization appears',
631
+ domain: '${k(F$($))}',
632
+ owners: [${W$($.owners)}],
633
+ tags: [${W$($.tags)}],
634
+ stability: '${$.stability}',
635
+ },
636
+ source: {
637
+ primary: {
638
+ key: '${$.sourceOperationKey}',
639
+ version: '${$.sourceOperationVersion??"1.0.0"}',
640
+ },
641
+ resultPath: 'data',
642
+ },
643
+ visualization: {
644
+ kind: 'metric',
645
+ measures: [{ key: 'value', label: 'Value', dataPath: 'value', format: 'number' }],
646
+ measure: 'value',
647
+ },
648
+ });
649
+ `}function p$($){return $.title??E5($.key.split(".").at(-1)??$.key)}function F$($){return $.domain??$.key.split(".")[0]??"contractspec"}function W$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function a$($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function E5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function iW($){let b=$.packageName??`@contractspec/example.${x5($.key.split(".").at(-1)??$.key)}`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
650
+
651
+ export const ${Hb($.key)}Example = defineExample({
652
+ meta: {
653
+ key: '${$.key}',
654
+ version: '${$.version}',
655
+ title: '${i(JA($))}',
656
+ description: '${i($.description)}',
657
+ kind: 'template',
658
+ visibility: 'experimental',
659
+ stability: '${$.stability}',
660
+ owners: [${B$($.owners)}],
661
+ tags: [${B$($.tags)}],
662
+ },
663
+ surfaces: {
664
+ templates: true,
665
+ sandbox: { enabled: true, modes: ['playground', 'specs'] },
666
+ studio: { enabled: false, installable: false },
667
+ mcp: { enabled: false },
668
+ },
669
+ entrypoints: {
670
+ packageName: '${b}',
671
+ },
672
+ });
673
+ `}function lW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
674
+
675
+ export const ${Hb($.key)}Agent = defineAgent({
676
+ meta: {
677
+ key: '${$.key}',
678
+ version: '${$.version}',
679
+ description: '${i($.description)}',
680
+ owners: [${B$($.owners)}],
681
+ tags: [${B$($.tags)}],
682
+ stability: '${$.stability}',
683
+ },
684
+ instructions: '${i($.instructions)}',
685
+ tools: [{ name: 'todo' }],
686
+ });
687
+ `}function tW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
688
+
689
+ export const ${Hb($.key)}ProductIntent = defineProductIntentSpec({
690
+ id: '${$.id??`${$.key}-run`}',
691
+ meta: {
692
+ key: '${$.key}',
693
+ version: '${$.version}',
694
+ title: '${i(JA($))}',
695
+ description: '${i($.description)}',
696
+ goal: 'TODO: capture the desired product outcome',
697
+ context: 'TODO: capture the decision context',
698
+ stability: '${$.stability}',
699
+ owners: [${B$($.owners)}],
700
+ tags: [${B$($.tags)}],
701
+ },
702
+ question: '${i($.question)}',
703
+ insights: { insights: [] },
704
+ });
705
+ `}function pW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
706
+
707
+ export const ${Hb($.key)}HarnessScenario = defineHarnessScenario({
708
+ meta: {
709
+ key: '${$.key}',
710
+ version: '${$.version}',
711
+ title: '${i(JA($))}',
712
+ description: '${i($.description)}',
713
+ domain: '${i(eW($))}',
714
+ owners: [${B$($.owners)}],
715
+ tags: [${B$($.tags)}],
716
+ stability: '${$.stability}',
717
+ },
718
+ target: {
719
+ isolation: 'preview',
720
+ preferredTargets: ['preview'],
721
+ },
722
+ allowedModes: ['deterministic-browser'],
723
+ steps: [
724
+ {
725
+ key: 'open-home',
726
+ description: 'Open the target application',
727
+ actionClass: 'navigate',
728
+ intent: 'Navigate to the primary page under test.',
729
+ },
730
+ ],
731
+ assertions: [
732
+ {
733
+ key: 'step-completes',
734
+ type: 'step-status',
735
+ description: 'TODO: replace with a real scenario assertion',
736
+ match: 'completed',
737
+ },
738
+ ],
739
+ });
740
+ `}function aW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
741
+
742
+ export const ${Hb($.key)}HarnessSuite = defineHarnessSuite({
743
+ meta: {
744
+ key: '${$.key}',
745
+ version: '${$.version}',
746
+ title: '${i(JA($))}',
747
+ description: '${i($.description)}',
748
+ domain: '${i(eW($))}',
749
+ owners: [${B$($.owners)}],
750
+ tags: [${B$($.tags)}],
751
+ stability: '${$.stability}',
752
+ },
753
+ scenarios: [
754
+ {
755
+ scenario: {
756
+ key: '${$.scenarioKey}',
757
+ version: '${$.scenarioVersion??"1.0.0"}',
758
+ },
759
+ required: true,
760
+ weight: 1,
761
+ },
762
+ ],
763
+ summary: '${i($.description)}',
764
+ tags: [${B$($.tags)}],
765
+ });
766
+ `}function JA($){return $.title??M5($.key.split(".").at(-1)??$.key)}function eW($){return $.domain??$.key.split(".")[0]??"contractspec"}function B$($){return $.map((b)=>`'${i(b)}'`).join(", ")}function Hb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function M5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function x5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function i($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Aw($){let b=r5($.key.split(".").pop()??"App")+"AppConfig",A=T5($),m=D5($),n=sW("dataViews",$.dataViews),W=sW("workflows",$.workflows),w=N5($),j=F5($),y=v5($),B=g5($),S=k5($),Q=P5($),Z=$.notes?` notes: '${D($.notes)}',
519
767
  `:"";return`import type { AppBlueprintSpec } from '@contractspec/lib.contracts-spec/app-config';
520
768
 
521
- export const ${W}: AppBlueprintSpec = {
769
+ export const ${b}: AppBlueprintSpec = {
522
770
  meta: {
523
- key: '${T($.name)}',
524
- version: ${$.version},
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(", ")}],
771
+ key: '${D($.key)}',
772
+ version: '${$.version}',
773
+ title: '${D($.title)}',
774
+ description: '${D($.description)}',
775
+ domain: '${D($.domain)}',
776
+ owners: [${$.owners.map((G)=>`'${D(G)}'`).join(", ")}],
777
+ tags: [${$.tags.map((G)=>`'${D(G)}'`).join(", ")}],
530
778
  stability: '${$.stability}',
531
- appId: '${T($.appId)}',
779
+ appId: '${D($.appId)}',
532
780
  },
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(", ")}],
781
+ ${A}${m}${n}${W}${w}${j}${y}${B}${S}${Q}${Z}};
782
+ `}function T5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((m)=>$w(m)).join(", ")}],
783
+ `:"",A=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((m)=>$w(m)).join(", ")}],
536
784
  `:"";return` capabilities: {
537
- ${W}${j} },
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(", ")}],
785
+ ${b}${A} },
786
+ `}function D5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((m)=>`{ key: '${D(m)}' }`).join(", ")}],
787
+ `:"",A=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((m)=>`{ key: '${D(m)}' }`).join(", ")}],
540
788
  `:"";return` features: {
541
- ${W}${j} },
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}',`:""}
789
+ ${b}${A} },
790
+ `}function sW($,b){if(b.length===0)return"";let A=b.map((m)=>` ${m.slot}: {
791
+ key: '${D(m.key)}'${m.version?`,
792
+ version: '${m.version}'`:""}
545
793
  }`).join(`,
546
794
  `);return` ${$}: {
547
- ${j}
795
+ ${A}
548
796
  },
549
- `}function uQ($){if($.policyRefs.length===0)return"";return` policies: [
550
- ${$.policyRefs.map((j)=>` {
551
- name: '${T(j.name)}'${j.version!==void 0?`,
552
- version: '${j.version}'`:""}
797
+ `}function N5($){if($.policyRefs.length===0)return"";return` policies: [
798
+ ${$.policyRefs.map((A)=>` {
799
+ key: '${D(A.key)}'${A.version?`,
800
+ version: '${A.version}'`:""}
553
801
  }`).join(`,
554
802
  `)}
555
803
  ],
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(", ")}],
804
+ `}function F5($){if(!$.theme)return"";let b=` primary: { key: '${D($.theme.key)}', version: '${$.theme.version}' },
805
+ `,A=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((m)=>`{ key: '${D(m.key)}', version: '${m.version}' }`).join(", ")}],
558
806
  `:"";return` theme: {
559
- ${W}${j} },
560
- `}function nQ($){if(!$.telemetry)return"";return` telemetry: {
807
+ ${b}${A} },
808
+ `}function v5($){if(!$.telemetry)return"";return` telemetry: {
561
809
  spec: {
562
- name: '${T($.telemetry.name)}'${$.telemetry.version!==void 0?`
810
+ key: '${D($.telemetry.key)}'${$.telemetry.version?`,
563
811
  version: '${$.telemetry.version}'`:""}
564
812
  },
565
813
  },
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(", ")}],
814
+ `}function g5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((m)=>bw(m)).join(", ")}],
815
+ `:"",A=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((m)=>bw(m)).join(", ")}],
568
816
  `:"";return` experiments: {
569
- ${W}${j} },
570
- `}function rQ($){if($.featureFlags.length===0)return"";return` featureFlags: [
571
- ${$.featureFlags.map((j)=>` {
572
- key: '${T(j.key)}',
573
- enabled: ${j.enabled},
574
- ${j.variant?`variant: '${T(j.variant)}',`:""}
575
- ${j.description?`description: '${T(j.description)}',`:""}
817
+ ${b}${A} },
818
+ `}function k5($){if($.featureFlags.length===0)return"";return` featureFlags: [
819
+ ${$.featureFlags.map((A)=>` {
820
+ key: '${D(A.key)}',
821
+ enabled: ${A.enabled},
822
+ ${A.variant?`variant: '${D(A.variant)}',`:""}
823
+ ${A.description?`description: '${D(A.description)}',`:""}
576
824
  }`).join(`,
577
825
  `)}
578
826
  ],
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(`,
827
+ `}function P5($){if($.routes.length===0)return"";return` routes: [
828
+ ${$.routes.map((A)=>{return` { ${[`path: '${D(A.path)}'`,A.label?`label: '${D(A.label)}'`:null,A.dataView?`dataView: '${D(A.dataView)}'`:null,A.workflow?`workflow: '${D(A.workflow)}'`:null,A.guardKey?`guard: { key: '${D(A.guardKey)}'${A.guardVersion?`, version: '${A.guardVersion}'`:""} }`:null,A.featureFlag?`featureFlag: '${D(A.featureFlag)}'`:null,A.experimentKey?`experiment: { key: '${D(A.experimentKey)}'${A.experimentVersion?`, version: '${A.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
581
829
  `)}
582
830
  ],
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,":""}
831
+ `}function $w($){return`{ key: '${D($)}' }`}function bw($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${D($.key)}'${b} }`}function r5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function D($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function mw($){let b=f5($.name.split(".").pop()??"DataView")+"DataView",A=$.fields.map((W)=>` {
832
+ key: '${W.key}',
833
+ label: '${KA(W.label)}',
834
+ dataPath: '${W.dataPath}',
835
+ ${W.format?`format: '${W.format}',`:""}
836
+ ${W.sortable?"sortable: true,":""}
837
+ ${W.filterable?"filterable: true,":""}
590
838
  }`).join(`,
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';
839
+ `),m=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((W)=>`'${W}'`).join(", ")}],`:"",n=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
592
840
 
593
- export const ${W}: DataViewSpec = {
841
+ export const ${b}: DataViewSpec = {
594
842
  meta: {
595
843
  key: '${$.name}',
596
844
  version: ${$.version},
597
845
  entity: '${$.entity}',
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(", ")}],
846
+ title: '${KA($.title)}',
847
+ description: '${KA($.description||"Describe the purpose of this data view.")}',
848
+ domain: '${KA($.domain||$.entity)}',
849
+ owners: [${$.owners.map((W)=>`'${W}'`).join(", ")}],
850
+ tags: [${$.tags.map((W)=>`'${W}'`).join(", ")}],
603
851
  stability: '${$.stability}',
604
852
  },
605
853
  source: {
@@ -607,7 +855,7 @@ export const ${W}: DataViewSpec = {
607
855
  name: '${$.primaryOperation.name}',
608
856
  version: ${$.primaryOperation.version},
609
857
  },
610
- ${Q}
858
+ ${n}
611
859
  refreshEvents: [
612
860
  // { name: 'entity.updated', version: '1.0.0' },
613
861
  ],
@@ -615,10 +863,10 @@ export const ${W}: DataViewSpec = {
615
863
  view: {
616
864
  kind: '${$.kind}',
617
865
  fields: [
618
- ${j}
866
+ ${A}
619
867
  ],
620
868
  ${$.primaryField?`primaryField: '${$.primaryField}',`:""}
621
- ${A}
869
+ ${m}
622
870
  filters: [
623
871
  // Example filter:
624
872
  // { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
@@ -633,13 +881,13 @@ ${j}
633
881
  // error: { name: 'app.data.error', version: '1.0.0' },
634
882
  },
635
883
  };
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';
884
+ `}function f5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function KA($){return $.replace(/'/g,"\\'")}function _A({exportName:$,specImportPath:b,rendererName:A,viewKind:m}){return`'use client';
637
885
 
638
886
  import * as React from 'react';
639
887
  import { DataViewRenderer } from '@contractspec/lib.design-system';
640
- import { ${$} } from '${W}';
888
+ import { ${$} } from '${b}';
641
889
 
642
- export interface ${j}Props {
890
+ export interface ${A}Props {
643
891
  items?: Record<string, unknown>[];
644
892
  item?: Record<string, unknown> | null;
645
893
  className?: string;
@@ -649,17 +897,17 @@ export interface ${j}Props {
649
897
  }
650
898
 
651
899
  /**
652
- * Auto-generated renderer for the "${A}" data view.
900
+ * Auto-generated renderer for the "${m}" data view.
653
901
  * Customize as needed for app-specific behaviour.
654
902
  */
655
- export function ${j}({
903
+ export function ${A}({
656
904
  items = [],
657
905
  item = null,
658
906
  className,
659
907
  renderActions,
660
908
  onSelect,
661
909
  onRowClick,
662
- }: ${j}Props) {
910
+ }: ${A}Props) {
663
911
  return (
664
912
  <DataViewRenderer
665
913
  spec={${$}}
@@ -672,93 +920,93 @@ export function ${j}({
672
920
  />
673
921
  );
674
922
  }
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';
923
+ `}function nw($){let{name:b,version:A,description:m,stability:n,owners:W,tags:w,piiFields:j}=$,y=h5(b.replace(/\./g,"_"))+"V"+A,B=y+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
676
924
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
677
925
 
678
926
  // TODO: Define event payload schema
679
- export const ${q} = new SchemaModel({
680
- name: '${q}',
681
- description: 'Payload for ${W}',
927
+ export const ${B} = new SchemaModel({
928
+ name: '${B}',
929
+ description: 'Payload for ${b}',
682
930
  fields: {
683
931
  // Add your payload fields here
684
932
  // example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
685
933
  },
686
934
  });
687
935
 
688
- export const ${B} = defineEvent({
689
- name: '${W}',
690
- name: '${W}',
691
- version: '${j}',
692
- description: '${A}',
693
- description: '${A}',
694
- stability: '${Q}',
695
- owners: [${Z.map((H)=>`'${H}'`).join(", ")}],
696
- tags: [${X.map((H)=>`'${H}'`).join(", ")}],
697
- ${Y.length>0?`pii: [${Y.map((H)=>`'${H}'`).join(", ")}],`:"// pii: [],"}
698
- payload: ${q},
936
+ export const ${y} = defineEvent({
937
+ name: '${b}',
938
+ name: '${b}',
939
+ version: '${A}',
940
+ description: '${m}',
941
+ description: '${m}',
942
+ stability: '${n}',
943
+ owners: [${W.map((S)=>`'${S}'`).join(", ")}],
944
+ tags: [${w.map((S)=>`'${S}'`).join(", ")}],
945
+ ${j.length>0?`pii: [${j.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
946
+ payload: ${B},
699
947
  });
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)=>` {
702
- type: '${Y.type}',
703
- target: '${P(Y.target)}',
704
- ${typeof Y.version==="string"?`version: ${Y.version},`:""}
948
+ `}function h5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ww($){let b=d5($.name.split(".").pop()??"Experiment")+"Experiment",A=$.variants.map((W)=>{let w=W.overrides?.length?` overrides: [
949
+ ${W.overrides.map((j)=>` {
950
+ type: '${j.type}',
951
+ target: '${f(j.target)}',
952
+ ${typeof j.version==="string"?`version: ${j.version},`:""}
705
953
  }`).join(`,
706
954
  `)}
707
955
  ],`:"";return` {
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},`:""}
712
- ${X}
956
+ id: '${f(W.id)}',
957
+ name: '${f(W.name)}',
958
+ ${W.description?`description: '${f(W.description)}',`:""}
959
+ ${typeof W.weight==="number"?`weight: ${W.weight},`:""}
960
+ ${w}
713
961
  }`}).join(`,
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},`:""}
962
+ `),m=c5($.allocation),n=$.successMetrics?.length?` successMetrics: [
963
+ ${$.successMetrics.map((W)=>` {
964
+ name: '${f(W.name)}',
965
+ telemetryEvent: { name: '${f(W.eventName)}', version: ${typeof W.eventVersion==="string"?`'${W.eventVersion}'`:W.eventVersion} },
966
+ aggregation: '${W.aggregation}',
967
+ ${typeof W.target==="number"?`target: ${W.target},`:""}
720
968
  }`).join(`,
721
969
  `)}
722
970
  ],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
723
971
 
724
- export const ${W}: ExperimentSpec = {
972
+ export const ${b}: ExperimentSpec = {
725
973
  meta: {
726
- key: '${P($.name)}',
974
+ key: '${f($.name)}',
727
975
  version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
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(", ")}],
976
+ title: '${f($.name)} experiment',
977
+ description: '${f($.description||"Describe the experiment goal.")}',
978
+ domain: '${f($.domain)}',
979
+ owners: [${$.owners.map((W)=>`'${f(W)}'`).join(", ")}],
980
+ tags: [${$.tags.map((W)=>`'${f(W)}'`).join(", ")}],
733
981
  stability: '${$.stability}',
734
982
  },
735
- controlVariant: '${P($.controlVariant)}',
983
+ controlVariant: '${f($.controlVariant)}',
736
984
  variants: [
737
- ${j}
985
+ ${A}
738
986
  ],
739
- allocation: ${A},
740
- ${Q}
987
+ allocation: ${m},
988
+ ${n}
741
989
  };
742
- `}function tQ($){switch($.type){case"random":return`{
990
+ `}function c5($){switch($.type){case"random":return`{
743
991
  type: 'random',
744
- ${$.salt?`salt: '${P($.salt)}',`:""}
992
+ ${$.salt?`salt: '${f($.salt)}',`:""}
745
993
  }`;case"sticky":return`{
746
994
  type: 'sticky',
747
995
  attribute: '${$.attribute}',
748
- ${$.salt?`salt: '${P($.salt)}',`:""}
996
+ ${$.salt?`salt: '${f($.salt)}',`:""}
749
997
  }`;case"targeted":return`{
750
998
  type: 'targeted',
751
999
  rules: [
752
- ${$.rules.map((W)=>` {
753
- variantId: '${P(W.variantId)}',
754
- ${typeof W.percentage==="number"?`percentage: ${W.percentage},`:""}
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)}',`:""}
1000
+ ${$.rules.map((b)=>` {
1001
+ variantId: '${f(b.variantId)}',
1002
+ ${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
1003
+ ${b.policy?`policy: { name: '${f(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
1004
+ ${b.expression?`expression: '${f(b.expression)}',`:""}
757
1005
  }`).join(`,
758
1006
  `)}
759
1007
  ],
760
1008
  fallback: '${$.fallback??"control"}',
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(`
1009
+ }`;default:return u5($)}}function d5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function u5($){throw Error(`Unsupported allocation type ${$}`)}function o5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function ww($){let b=(A)=>A.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
762
1010
  `);return`/**
763
1011
  * ${$.title} Feature
764
1012
  *
@@ -767,35 +1015,35 @@ ${$.rules.map((W)=>` {
767
1015
 
768
1016
  import { defineFeature } from '@contractspec/lib.contracts-spec';
769
1017
 
770
- export const ${eQ($.key)}Feature = defineFeature({
1018
+ export const ${o5($.key)}Feature = defineFeature({
771
1019
  meta: {
772
1020
  key: '${$.key}',
773
1021
  version: '${$.version}',
774
1022
  title: '${$.title}',
775
1023
  description: '${$.description||"TODO: Add description"}',
776
1024
  domain: '${$.domain}',
777
- owners: [${$.owners.map((j)=>`'${j}'`).join(", ")}],
778
- tags: [${$.tags.map((j)=>`'${j}'`).join(", ")}],
1025
+ owners: [${$.owners.map((A)=>`'${A}'`).join(", ")}],
1026
+ tags: [${$.tags.map((A)=>`'${A}'`).join(", ")}],
779
1027
  stability: '${$.stability||"beta"}',
780
1028
  },
781
1029
 
782
1030
  operations: [
783
- ${W($.operations)||" // Add operations here"}
1031
+ ${b($.operations)||" // Add operations here"}
784
1032
  ],
785
1033
 
786
1034
  events: [
787
- ${W($.events)||" // Add events here"}
1035
+ ${b($.events)||" // Add events here"}
788
1036
  ],
789
1037
 
790
1038
  presentations: [
791
- ${W($.presentations)||" // Add presentations here"}
1039
+ ${b($.presentations)||" // Add presentations here"}
792
1040
  ],
793
1041
 
794
1042
  experiments: [
795
- ${W($.experiments)||" // Add experiments here"}
1043
+ ${b($.experiments)||" // Add experiments here"}
796
1044
  ],
797
1045
  });
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`/**
1046
+ `}function i5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function jw($){let b=i5($.key),A=`${b}FormModel`,m=`${b}Form`;return`/**
799
1047
  * ${$.title} Form
800
1048
  *
801
1049
  * Auto-generated form spec.
@@ -804,8 +1052,8 @@ ${W($.experiments)||" // Add experiments here"}
804
1052
  import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
805
1053
  import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
806
1054
 
807
- const ${j} = defineSchemaModel({
808
- name: '${j}',
1055
+ const ${A} = defineSchemaModel({
1056
+ name: '${A}',
809
1057
  description: '${$.description||"TODO: Add form model description"}',
810
1058
  fields: {
811
1059
  ${$.primaryFieldKey}: {
@@ -815,18 +1063,18 @@ const ${j} = defineSchemaModel({
815
1063
  },
816
1064
  });
817
1065
 
818
- export const ${A} = defineFormSpec({
1066
+ export const ${m} = defineFormSpec({
819
1067
  meta: {
820
1068
  key: '${$.key}',
821
1069
  version: '${$.version}',
822
1070
  title: '${$.title}',
823
1071
  description: '${$.description||"TODO: Add description"}',
824
1072
  domain: '${$.domain}',
825
- owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
826
- tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
1073
+ owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
1074
+ tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
827
1075
  stability: '${$.stability||"beta"}',
828
1076
  },
829
- model: ${j},
1077
+ model: ${A},
830
1078
  fields: [
831
1079
  {
832
1080
  kind: 'text',
@@ -851,17 +1099,17 @@ export const ${A} = defineFormSpec({
851
1099
  form: 'react-hook-form',
852
1100
  },
853
1101
  });
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';
1102
+ `}function yw($,b){let A=l5($.split(".").pop()||"unknown")+"Handler",m=UA($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
1103
+ import { ${m} } from '../contracts/${Qw($)}.contracts';
856
1104
 
857
1105
  /**
858
1106
  * Handler for ${$}
859
1107
  */
860
- export const ${j}: ContractHandler<typeof ${A}> = async (
1108
+ export const ${A}: ContractHandler<typeof ${m}> = async (
861
1109
  input,
862
1110
  context
863
1111
  ) => {
864
- // TODO: Implement ${W} logic
1112
+ // TODO: Implement ${b} logic
865
1113
 
866
1114
  try {
867
1115
  // 1. Validate prerequisites
@@ -877,28 +1125,28 @@ export const ${j}: ContractHandler<typeof ${A}> = async (
877
1125
  throw error;
878
1126
  }
879
1127
  };
880
- `}function a5($,W){let j=t0($);return`import React from 'react';
1128
+ `}function Bw($,b){let A=UA($);return`import React from 'react';
881
1129
 
882
- interface ${j}Props {
1130
+ interface ${A}Props {
883
1131
  // TODO: Define props based on presentation spec
884
1132
  }
885
1133
 
886
1134
  /**
887
- * ${W}
1135
+ * ${b}
888
1136
  */
889
- export const ${j}: React.FC<${j}Props> = (props) => {
1137
+ export const ${A}: React.FC<${A}Props> = (props) => {
890
1138
  return (
891
1139
  <div>
892
1140
  {/* TODO: Implement component UI */}
893
- <p>Component: ${j}</p>
1141
+ <p>Component: ${A}</p>
894
1142
  </div>
895
1143
  );
896
1144
  };
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($)}';
1145
+ `}function Sw($,b){let A=b==="handler"?"../handlers":"../components",m=UA($);return`import { describe, it, expect } from 'bun:test';
1146
+ import { ${m} } from '${A}/${Qw($)}';
899
1147
 
900
- describe('${A}', () => {
901
- it('should ${W==="handler"?"handle valid input":"render correctly"}', async () => {
1148
+ describe('${m}', () => {
1149
+ it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
902
1150
  // TODO: Implement test
903
1151
  expect(true).toBe(true);
904
1152
  });
@@ -907,170 +1155,170 @@ describe('${A}', () => {
907
1155
  // TODO: Test edge cases
908
1156
  });
909
1157
 
910
- ${W==="handler"?`it('should handle errors appropriately', async () => {
1158
+ ${b==="handler"?`it('should handle errors appropriately', async () => {
911
1159
  // TODO: Test error scenarios
912
1160
  });`:`it('should be accessible', async () => {
913
1161
  // TODO: Test accessibility
914
1162
  });`}
915
1163
  });
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(`,
917
- `),Y=$.capabilitiesRequired.length>0?` requires: [
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(`,
1164
+ `}function l5($){let b=UA($);return b.charAt(0).toLowerCase()+b.slice(1)}function UA($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Qw($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Zw($){let b=m8($.name.split(".").pop()??"Integration"),A=`${b}IntegrationSpec`,m=`register${b}Integration`,n=$.supportedModes.length?$.supportedModes:["managed"],W=n.map((Y)=>`'${Y}'`).join(", "),w=$.capabilitiesProvided.map((Y)=>` { key: '${Y.key}', version: '${Y.version}' }`).join(`,
1165
+ `),j=$.capabilitiesRequired.length>0?` requires: [
1166
+ ${$.capabilitiesRequired.map((Y)=>{let V=Y.version!==void 0?`, version: '${Y.version}'`:"",O=Y.optional?", optional: true":"",K=Y.reason?`, reason: '${w$(Y.reason)}'`:"";return` { key: '${Y.key}'${V}${O}${K} }`}).join(`,
919
1167
  `)}
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';
1168
+ ],`:"",y=t5($.configFields),B=a5($.configFields),S=p5($.secretFields),Q=e5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
1169
+ `:"",G=s5($.rateLimitRpm,$.rateLimitRph),X=$8(n,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
922
1170
  import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
923
1171
  import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
924
1172
 
925
- export const ${j}: IntegrationSpec = {
1173
+ export const ${A}: IntegrationSpec = {
926
1174
  meta: {
927
1175
  key: '${$.name}',
928
1176
  version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
929
1177
  category: '${$.category}',
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)},
937
- },
938
- supportedModes: [${Z}],
1178
+ displayName: '${w$($.displayName)}',
1179
+ title: '${w$($.title)}',
1180
+ description: '${w$($.description)}',
1181
+ domain: '${w$($.domain)}',
1182
+ owners: [${$.owners.map((Y)=>`'${w$(Y)}'`).join(", ")}],
1183
+ tags: [${$.tags.map((Y)=>`'${w$(Y)}'`).join(", ")}],
1184
+ stability: StabilityEnum.${A8($.stability)},
1185
+ },
1186
+ supportedModes: [${W}],
939
1187
  capabilities: {
940
1188
  provides: [
941
- ${X}
1189
+ ${w}
942
1190
  ],
943
- ${Y.length>0?`${Y}
1191
+ ${j.length>0?`${j}
944
1192
  `:""} },
945
1193
  configSchema: {
946
- ${B}
947
- example: ${q},
1194
+ ${y}
1195
+ example: ${B},
948
1196
  },
949
1197
  secretSchema: {
950
- ${H}
951
- example: ${V},
1198
+ ${S}
1199
+ example: ${Q},
952
1200
  },
953
- ${G}${J}${b} healthCheck: {
1201
+ ${Z}${G}${X} healthCheck: {
954
1202
  method: '${$.healthCheckMethod}',
955
1203
  timeoutMs: ${$.healthCheckTimeoutMs},
956
1204
  },
957
1205
  };
958
1206
 
959
- export function ${A}(
1207
+ export function ${m}(
960
1208
  registry: IntegrationSpecRegistry
961
1209
  ): IntegrationSpecRegistry {
962
- return registry.register(${j});
1210
+ return registry.register(${A});
963
1211
  }
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(`,
1212
+ `}function t5($){let b=$.filter((n)=>n.required),A=b.length>0?` required: [${b.map((n)=>`'${n.key}'`).join(", ")}],
1213
+ `:"",m=$.length?$.map((n)=>{let W=n.description?`, description: '${w$(n.description)}'`:"";return` ${n.key}: { type: '${b8(n.type)}'${W} }`}).join(`,
966
1214
  `):"";return` schema: {
967
1215
  type: 'object',
968
- ${j} properties: {
969
- ${A||" "}
1216
+ ${A} properties: {
1217
+ ${m||" "}
970
1218
  },
971
1219
  },
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(`,
1220
+ `}function p5($){let b=$.filter((n)=>n.required),A=b.length>0?` required: [${b.map((n)=>`'${n.key}'`).join(", ")}],
1221
+ `:"",m=$.length?$.map((n)=>{let W=n.description?`, description: '${w$(n.description)}'`:"";return` ${n.key}: { type: 'string'${W} }`}).join(`,
974
1222
  `):"";return` schema: {
975
1223
  type: 'object',
976
- ${j} properties: {
977
- ${A||" "}
1224
+ ${A} properties: {
1225
+ ${m||" "}
978
1226
  },
979
1227
  },
980
- `}function QZ($){if($.length===0)return"{}";return`{
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(`,
1228
+ `}function a5($){if($.length===0)return"{}";return`{
1229
+ ${$.map((A)=>{switch(A.type){case"number":return` ${A.key}: 0`;case"boolean":return` ${A.key}: true`;case"string":default:return` ${A.key}: '${A.key.toUpperCase()}_VALUE'`}}).join(`,
982
1230
  `)}
983
- }`}function ZZ($){if($.length===0)return"{}";return`{
984
- ${$.map((j)=>` ${j.key}: '${j.key.toUpperCase()}_SECRET'`).join(`,
1231
+ }`}function e5($){if($.length===0)return"{}";return`{
1232
+ ${$.map((A)=>` ${A.key}: '${A.key.toUpperCase()}_SECRET'`).join(`,
985
1233
  `)}
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: {
1234
+ }`}function s5($,b){if($==null&&b==null)return"";let A=[];if($!=null)A.push(` rpm: ${$}`);if(b!=null)A.push(` rph: ${b}`);return` constraints: {
987
1235
  rateLimit: {
988
- ${j.join(`,
1236
+ ${A.join(`,
989
1237
  `)}
990
1238
  },
991
1239
  },
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';
1240
+ `}function $8($,b,A){if(!$.includes("byok"))return"";let m=b?` setupInstructions: '${w$(b)}',
1241
+ `:"",n=A&&A.length?` requiredScopes: [${A.map((W)=>`'${w$(W)}'`).join(", ")}],
1242
+ `:"";if(!m&&!n)return"";return` byokSetup: {
1243
+ ${m}${n} },
1244
+ `}function b8($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function A8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function m8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function w$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Gw($){let b=y8($.name.split(".").pop()??"KnowledgeSpace"),A=`${b}KnowledgeSpace`,m=`register${b}KnowledgeSpace`,n=n8($),W=W8($),w=w8($),j=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
997
1245
  import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
998
1246
  import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
999
1247
 
1000
- export const ${j}: KnowledgeSpaceSpec = {
1248
+ export const ${A}: KnowledgeSpaceSpec = {
1001
1249
  meta: {
1002
1250
  key: '${$.name}',
1003
1251
  version: ${$.version},
1004
1252
  category: '${$.category}',
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)},
1012
- },
1013
- retention: ${Q},
1253
+ displayName: '${Y$($.displayName)}',
1254
+ title: '${Y$($.title)}',
1255
+ description: '${Y$($.description)}',
1256
+ domain: '${Y$($.domain)}',
1257
+ owners: [${$.owners.map((y)=>`'${Y$(y)}'`).join(", ")}],
1258
+ tags: [${$.tags.map((y)=>`'${Y$(y)}'`).join(", ")}],
1259
+ stability: StabilityEnum.${j8($.stability)},
1260
+ },
1261
+ retention: ${n},
1014
1262
  access: {
1015
- ${Z}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${Y}
1263
+ ${W}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${j}
1016
1264
  `:""} },
1017
- ${X} description: '${B$($.description||$.displayName)}',
1265
+ ${w} description: '${Y$($.description||$.displayName)}',
1018
1266
  };
1019
1267
 
1020
- export function ${A}(
1268
+ export function ${m}(
1021
1269
  registry: KnowledgeSpaceRegistry
1022
1270
  ): KnowledgeSpaceRegistry {
1023
- return registry.register(${j});
1271
+ return registry.register(${A});
1024
1272
  }
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}',
1026
- `,j=` automationWritable: ${$.automationWritable},
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: {
1028
- ${W.join(`,
1273
+ `}function n8($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",A=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${A} }`}function W8($){let b=` trustLevel: '${$.trustLevel}',
1274
+ `,A=` automationWritable: ${$.automationWritable},
1275
+ `;return`${b}${A}`}function w8($){let b=[];if($.embeddingModel)b.push(` embeddingModel: '${Y$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")b.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)b.push(` vectorDbIntegration: '${Y$($.vectorDbIntegration)}'`);if(b.length===0)return"";return` indexing: {
1276
+ ${b.join(`,
1029
1277
  `)}
1030
1278
  },
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';
1279
+ `}function j8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function y8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Y$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Yw($){let A=`${B8($.name.split(".").pop()??"Migration")}Migration`,m=$.dependencies.length>0?`dependencies: [${$.dependencies.map((n)=>`'${n}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
1032
1280
 
1033
- export const ${j}: MigrationSpec = {
1281
+ export const ${A}: MigrationSpec = {
1034
1282
  meta: {
1035
1283
  key: '${$.name}',
1036
1284
  version: ${$.version},
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(", ")}],
1285
+ title: '${v$($.title)}',
1286
+ description: '${v$($.description??"")}',
1287
+ domain: '${v$($.domain)}',
1288
+ owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
1289
+ tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
1042
1290
  stability: '${$.stability}',
1043
1291
  },
1044
1292
  plan: {
1045
1293
  up: [
1046
- ${j8($.up)}
1294
+ ${Xw($.up)}
1047
1295
  ],${$.down&&$.down.length?`
1048
1296
  down: [
1049
- ${j8($.down)}
1297
+ ${Xw($.down)}
1050
1298
  ],`:""}
1051
1299
  },
1052
- ${A}
1300
+ ${m}
1053
1301
  };
1054
- `}function j8($){return $.map((W)=>{let j=W.description?`description: '${E$(W.description)}',`:"";switch(W.kind){case"schema":return` {
1302
+ `}function Xw($){return $.map((b)=>{let A=b.description?`description: '${v$(b.description)}',`:"";switch(b.kind){case"schema":return` {
1055
1303
  kind: 'schema',
1056
- ${j}
1057
- sql: \`${E$(W.sql??"")}\`,
1304
+ ${A}
1305
+ sql: \`${v$(b.sql??"")}\`,
1058
1306
  }`;case"data":return` {
1059
1307
  kind: 'data',
1060
- ${j}
1061
- script: \`${E$(W.script??"")}\`,
1308
+ ${A}
1309
+ script: \`${v$(b.script??"")}\`,
1062
1310
  }`;case"validation":default:return` {
1063
1311
  kind: 'validation',
1064
- ${j}
1065
- assertion: \`${E$(W.assertion??"")}\`,
1312
+ ${A}
1313
+ assertion: \`${v$(b.assertion??"")}\`,
1066
1314
  }`}}).join(`,
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';
1315
+ `)}function B8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function v$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Hw($){let{name:b,version:A,kind:m,description:n,goal:W,context:w,stability:j,owners:y,tags:B,auth:S,flags:Q}=$,Z=S8(b.split(".").pop()||"Unknown")+"Spec",G=Z.replace("Spec","Input"),X=Z.replace("Spec","Output");return`import { define${mm(m)} } from '@contractspec/lib.contracts-spec';
1068
1316
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
1069
1317
 
1070
1318
  // TODO: Define input schema
1071
- export const ${J} = new SchemaModel({
1072
- name: '${J}',
1073
- description: 'Input for ${W}',
1319
+ export const ${G} = new SchemaModel({
1320
+ name: '${G}',
1321
+ description: 'Input for ${b}',
1074
1322
  fields: {
1075
1323
  // Add your fields here
1076
1324
  // example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
@@ -1078,32 +1326,32 @@ export const ${J} = new SchemaModel({
1078
1326
  });
1079
1327
 
1080
1328
  // TODO: Define output schema
1081
- export const ${b} = new SchemaModel({
1082
- name: '${b}',
1083
- description: 'Output for ${W}',
1329
+ export const ${X} = new SchemaModel({
1330
+ name: '${X}',
1331
+ description: 'Output for ${b}',
1084
1332
  fields: {
1085
1333
  // Add your fields here
1086
1334
  ok: { type: ScalarTypeEnum.Boolean(), isOptional: false },
1087
1335
  },
1088
1336
  });
1089
1337
 
1090
- export const ${G} = define${_1(A)}({
1338
+ export const ${Z} = define${mm(m)}({
1091
1339
  meta: {
1092
- key: '${W}',
1093
- key: '${W}',
1094
- version: '${j}',
1095
- stability: '${Y}',
1096
- stability: '${Y}',
1097
- owners: [${B.map((w)=>`'${w}'`).join(", ")}],
1098
- tags: [${q.map((w)=>`'${w}'`).join(", ")}],
1099
- description: '${Q}',
1100
- goal: '${Z}',
1101
- context: '${X}',
1340
+ key: '${b}',
1341
+ key: '${b}',
1342
+ version: '${A}',
1343
+ stability: '${j}',
1344
+ stability: '${j}',
1345
+ owners: [${y.map((Y)=>`'${Y}'`).join(", ")}],
1346
+ tags: [${B.map((Y)=>`'${Y}'`).join(", ")}],
1347
+ description: '${n}',
1348
+ goal: '${W}',
1349
+ context: '${w}',
1102
1350
  },
1103
1351
 
1104
1352
  io: {
1105
- input: ${J},
1106
- output: ${b},
1353
+ input: ${G},
1354
+ output: ${X},
1107
1355
  errors: {
1108
1356
  // Define possible errors
1109
1357
  // EXAMPLE_ERROR: {
@@ -1115,8 +1363,8 @@ export const ${G} = define${_1(A)}({
1115
1363
  },
1116
1364
 
1117
1365
  policy: {
1118
- auth: '${H}',
1119
- ${V.length>0?`flags: [${V.map((w)=>`'${w}'`).join(", ")}],`:"// flags: [],"}
1366
+ auth: '${S}',
1367
+ ${Q.length>0?`flags: [${Q.map((Y)=>`'${Y}'`).join(", ")}],`:"// flags: [],"}
1120
1368
  },
1121
1369
 
1122
1370
  sideEffects: {
@@ -1130,9 +1378,9 @@ export const ${G} = define${_1(A)}({
1130
1378
  },
1131
1379
 
1132
1380
  transport: {
1133
- rest: { method: '${A==="command"?"POST":"GET"}' },
1134
- gql: { field: '${W.replace(/\./g,"_")}' },
1135
- mcp: { toolName: '${W.replace(/\./g,"_")}-v${String(j).replace(/\./g,"_")}' },
1381
+ rest: { method: '${m==="command"?"POST":"GET"}' },
1382
+ gql: { field: '${b.replace(/\./g,"_")}' },
1383
+ mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(A).replace(/\./g,"_")}' },
1136
1384
  },
1137
1385
 
1138
1386
  acceptance: {
@@ -1153,13 +1401,13 @@ export const ${G} = define${_1(A)}({
1153
1401
  ],
1154
1402
  },
1155
1403
  });
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: {
1404
+ `}function mm($){return $.charAt(0).toUpperCase()+$.slice(1)}function S8($){return $.split(/[-_.]/).map(mm).join("")}function qw($){let{name:b,version:A,description:m,stability:n,owners:W,tags:w,presentationKind:j}=$,y=Q8(b.replace(/\./g,"_"))+"Presentation",B="";switch(j){case"web_component":B=` content: {
1157
1405
  kind: 'web_component',
1158
1406
  framework: 'react',
1159
- componentKey: '${W.replace(/\./g,"_")}',
1407
+ componentKey: '${b.replace(/\./g,"_")}',
1160
1408
  props: new SchemaModel({
1161
- name: '${B}Props',
1162
- description: 'Props for ${W}',
1409
+ name: '${y}Props',
1410
+ description: 'Props for ${b}',
1163
1411
  fields: {
1164
1412
  // TODO: Define component props
1165
1413
  },
@@ -1167,20 +1415,20 @@ export const ${G} = define${_1(A)}({
1167
1415
  analytics: [
1168
1416
  // TODO: Define analytics events
1169
1417
  ],
1170
- },`;break;case"markdown":q=` content: {
1418
+ },`;break;case"markdown":B=` content: {
1171
1419
  kind: 'markdown',
1172
1420
  content: \`
1173
- # ${A}
1421
+ # ${m}
1174
1422
 
1175
1423
  TODO: Add markdown content here
1176
1424
  \`,
1177
- // Or use resourceUri: 'feature://${W}/guide.md'
1178
- },`;break;case"data":q=` content: {
1425
+ // Or use resourceUri: 'feature://${b}/guide.md'
1426
+ },`;break;case"data":B=` content: {
1179
1427
  kind: 'data',
1180
1428
  mimeType: 'application/json',
1181
1429
  model: new SchemaModel({
1182
- name: '${B}Data',
1183
- description: 'Data structure for ${W}',
1430
+ name: '${y}Data',
1431
+ description: 'Data structure for ${b}',
1184
1432
  fields: {
1185
1433
  // TODO: Define data structure
1186
1434
  },
@@ -1188,14 +1436,14 @@ TODO: Add markdown content here
1188
1436
  },`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
1189
1437
  import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
1190
1438
 
1191
- export const ${B}: PresentationSpec = {
1439
+ export const ${y}: PresentationSpec = {
1192
1440
  meta: {
1193
- key: '${W}',
1194
- version: ${j},
1195
- stability: '${Q}',
1196
- owners: [${Z.map((H)=>`'${H}'`).join(", ")}],
1197
- tags: [${X.map((H)=>`'${H}'`).join(", ")}],
1198
- description: '${A}',
1441
+ key: '${b}',
1442
+ version: ${A},
1443
+ stability: '${n}',
1444
+ owners: [${W.map((S)=>`'${S}'`).join(", ")}],
1445
+ tags: [${w.map((S)=>`'${S}'`).join(", ")}],
1446
+ description: '${m}',
1199
1447
  },
1200
1448
 
1201
1449
  policy: {
@@ -1203,81 +1451,109 @@ export const ${B}: PresentationSpec = {
1203
1451
  // pii: [],
1204
1452
  },
1205
1453
 
1206
- ${q}
1454
+ ${B}
1207
1455
  };
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)},
1456
+ `}function Q8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ow($){let b=Z8($.name.split(".").pop()??"Telemetry")+"Telemetry",A=$.providers?.length?`providers: [
1457
+ ${$.providers.map((n)=>` {
1458
+ type: '${n.type}',
1459
+ config: ${G8(n.config)},
1212
1460
  }`).join(`,
1213
1461
  `)}
1214
- ],`:"",A=$.events.map((Q)=>{let Z=Q.properties.map((Y)=>` '${Y.name}': {
1215
- type: '${Y.type}',
1216
- ${Y.required?"required: true,":""}
1217
- ${Y.pii?"pii: true,":""}
1218
- ${Y.redact?"redact: true,":""}
1219
- ${Y.description?`description: '${n(Y.description)}',`:""}
1462
+ ],`:"",m=$.events.map((n)=>{let W=n.properties.map((j)=>` '${j.name}': {
1463
+ type: '${j.type}',
1464
+ ${j.required?"required: true,":""}
1465
+ ${j.pii?"pii: true,":""}
1466
+ ${j.redact?"redact: true,":""}
1467
+ ${j.description?`description: '${l(j.description)}',`:""}
1220
1468
  }`).join(`,
1221
- `),X=Q.anomalyRules?.length?` anomalyDetection: {
1469
+ `),w=n.anomalyRules?.length?` anomalyDetection: {
1222
1470
  enabled: true,
1223
- ${typeof Q.anomalyMinimumSample==="number"?`minimumSample: ${Q.anomalyMinimumSample},`:""}
1471
+ ${typeof n.anomalyMinimumSample==="number"?`minimumSample: ${n.anomalyMinimumSample},`:""}
1224
1472
  thresholds: [
1225
- ${Q.anomalyRules.map((Y)=>` {
1226
- metric: '${n(Y.metric)}',
1227
- ${typeof Y.min==="number"?`min: ${Y.min},`:""}
1228
- ${typeof Y.max==="number"?`max: ${Y.max},`:""}
1473
+ ${n.anomalyRules.map((j)=>` {
1474
+ metric: '${l(j.metric)}',
1475
+ ${typeof j.min==="number"?`min: ${j.min},`:""}
1476
+ ${typeof j.max==="number"?`max: ${j.max},`:""}
1229
1477
  }`).join(`,
1230
1478
  `)}
1231
1479
  ],
1232
- actions: [${(Q.anomalyActions??[]).map((Y)=>`'${Y}'`).join(", ")}],
1233
- },`:Q.anomalyEnabled?` anomalyDetection: {
1480
+ actions: [${(n.anomalyActions??[]).map((j)=>`'${j}'`).join(", ")}],
1481
+ },`:n.anomalyEnabled?` anomalyDetection: {
1234
1482
  enabled: true,
1235
- ${typeof Q.anomalyMinimumSample==="number"?`minimumSample: ${Q.anomalyMinimumSample},`:""}
1483
+ ${typeof n.anomalyMinimumSample==="number"?`minimumSample: ${n.anomalyMinimumSample},`:""}
1236
1484
  },`:"";return` {
1237
- name: '${n(Q.name)}',
1238
- version: ${Q.version},
1485
+ name: '${l(n.name)}',
1486
+ version: ${n.version},
1239
1487
  semantics: {
1240
- what: '${n(Q.what)}',
1241
- ${Q.who?`who: '${n(Q.who)}',`:""}
1242
- ${Q.why?`why: '${n(Q.why)}',`:""}
1488
+ what: '${l(n.what)}',
1489
+ ${n.who?`who: '${l(n.who)}',`:""}
1490
+ ${n.why?`why: '${l(n.why)}',`:""}
1243
1491
  },
1244
- privacy: '${Q.privacy}',
1492
+ privacy: '${n.privacy}',
1245
1493
  properties: {
1246
- ${Z}
1494
+ ${W}
1247
1495
  },
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)}']`:""} },`:""}
1250
- ${X}
1251
- ${Q.tags?.length?`tags: [${Q.tags.map((Y)=>`'${n(Y)}'`).join(", ")}],`:""}
1496
+ ${typeof n.retentionDays==="number"?`retention: { days: ${n.retentionDays}, ${n.retentionPolicy?`policy: '${n.retentionPolicy}'`:""} },`:""}
1497
+ ${typeof n.samplingRate==="number"?`sampling: { rate: ${n.samplingRate}${n.samplingConditions?`, conditions: ['${l(n.samplingConditions)}']`:""} },`:""}
1498
+ ${w}
1499
+ ${n.tags?.length?`tags: [${n.tags.map((j)=>`'${l(j)}'`).join(", ")}],`:""}
1252
1500
  }`}).join(`,
1253
1501
  `);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
1254
1502
 
1255
- export const ${W}: TelemetrySpec = {
1503
+ export const ${b}: TelemetrySpec = {
1256
1504
  meta: {
1257
- key: '${n($.name)}',
1505
+ key: '${l($.name)}',
1258
1506
  version: ${$.version},
1259
- title: '${n($.name)} telemetry',
1260
- description: '${n($.description||"Describe the purpose of this telemetry spec.")}',
1261
- domain: '${n($.domain)}',
1262
- owners: [${$.owners.map((Q)=>`'${n(Q)}'`).join(", ")}],
1263
- tags: [${$.tags.map((Q)=>`'${n(Q)}'`).join(", ")}],
1507
+ title: '${l($.name)} telemetry',
1508
+ description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
1509
+ domain: '${l($.domain)}',
1510
+ owners: [${$.owners.map((n)=>`'${l(n)}'`).join(", ")}],
1511
+ tags: [${$.tags.map((n)=>`'${l(n)}'`).join(", ")}],
1264
1512
  stability: '${$.stability}',
1265
1513
  },
1266
1514
  config: {
1267
1515
  ${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
1268
1516
  ${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
1269
1517
  ${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
1270
- ${j}
1518
+ ${A}
1271
1519
  },
1272
1520
  events: [
1273
- ${A}
1521
+ ${m}
1274
1522
  ],
1275
1523
  };
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)}',`:""}
1524
+ `}function Z8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function G8($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function X8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Vw($){return`/**
1525
+ * ${$.title} Theme
1526
+ *
1527
+ * Auto-generated theme spec.
1528
+ */
1529
+
1530
+ import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
1531
+
1532
+ export const ${X8($.key)}Theme = defineTheme({
1533
+ meta: {
1534
+ key: '${$.key}',
1535
+ version: '${$.version}',
1536
+ title: '${$.title}',
1537
+ description: '${$.description}',
1538
+ domain: '${$.domain}',
1539
+ owners: [${$.owners.map((b)=>`'${b}'`).join(", ")}],
1540
+ tags: [${$.tags.map((b)=>`'${b}'`).join(", ")}],
1541
+ stability: '${$.stability}',
1542
+ scopes: [${$.scopes.map((b)=>`'${b}'`).join(", ")}],
1543
+ },
1544
+ tokens: {
1545
+ colors: {
1546
+ primary: { value: '#2563eb' },
1547
+ background: { value: '#ffffff' },
1548
+ foreground: { value: '#111827' },
1549
+ },
1550
+ },
1551
+ });
1552
+ `}function Jw($){let b=H8($.name.split(".").pop()??"Workflow")+"Workflow",A=$.steps.map((n)=>Y8(n)).join(`,
1553
+ `),m=$.transitions.map((n)=>` {
1554
+ from: '${n.from}',
1555
+ to: '${n.to}',
1556
+ ${n.condition?` condition: '${e$(n.condition)}',`:""}
1281
1557
  }`).join(`,
1282
1558
  `);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
1283
1559
 
@@ -1289,36 +1565,36 @@ ${Q.condition?` condition: '${h$(Q.condition)}',`:""}
1289
1565
  * - Provide form renderers for human steps.
1290
1566
  * - Add guards/conditions as needed.
1291
1567
  */
1292
- export const ${W}: WorkflowSpec = {
1568
+ export const ${b}: WorkflowSpec = {
1293
1569
  meta: {
1294
1570
  key: '${$.name}',
1295
1571
  version: ${$.version},
1296
- title: '${h$($.title)}',
1297
- description: '${h$($.description)}',
1298
- domain: '${h$($.domain)}',
1572
+ title: '${e$($.title)}',
1573
+ description: '${e$($.description)}',
1574
+ domain: '${e$($.domain)}',
1299
1575
  stability: '${$.stability}',
1300
- owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
1301
- tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
1576
+ owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
1577
+ tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
1302
1578
  },
1303
1579
  definition: {
1304
1580
  ${$.entryStepId?` entryStepId: '${$.entryStepId}',
1305
1581
  `:""} steps: [
1306
- ${j}
1582
+ ${A}
1307
1583
  ],
1308
1584
  transitions: [
1309
- ${A}
1585
+ ${m}
1310
1586
  ],
1311
1587
  },
1312
1588
  ${$.policyFlags.length>0?`policy: {
1313
- flags: [${$.policyFlags.map((Q)=>`'${Q}'`).join(", ")}],
1589
+ flags: [${$.policyFlags.map((n)=>`'${n}'`).join(", ")}],
1314
1590
  },`:"// policy: { flags: [] },"}
1315
1591
  };
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';
1592
+ `}function Y8($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${e$($.label)}',`];if($.description)b.push(` description: '${e$($.description)}',`);let A=[];if($.operation)A.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)A.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(A.length)b.push(` action: { ${A.join(", ")} },`);return b.push(" }"),b.join(`
1593
+ `)}function H8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function e$($){return $.replace(/'/g,"\\'")}function zA({exportName:$,specImportPath:b,workflowFunctionName:A}){return`import { createHook, createWebhook, sleep } from 'workflow';
1318
1594
  import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
1319
- import { ${$} } from '${W}';
1595
+ import { ${$} } from '${b}';
1320
1596
 
1321
- export async function ${j}(input = {}, bridge = {}) {
1597
+ export async function ${A}(input = {}, bridge = {}) {
1322
1598
  "use workflow";
1323
1599
 
1324
1600
  // Keep the workflow function deterministic.
@@ -1335,29 +1611,29 @@ export async function ${j}(input = {}, bridge = {}) {
1335
1611
  },
1336
1612
  });
1337
1613
  }
1338
- `}function s0($,W){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
1339
- import { ${W} } from '${$}';
1614
+ `}function LA($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
1615
+ import { ${b} } from '${$}';
1340
1616
 
1341
1617
  export const POST = createWorkflowDevkitStartRoute({
1342
- workflow: ${W},
1618
+ workflow: ${b},
1343
1619
  async buildArgs(body) {
1344
1620
  return [body];
1345
1621
  },
1346
1622
  });
1347
- `}function e0(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
1623
+ `}function RA(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
1348
1624
 
1349
1625
  export const POST = createWorkflowDevkitFollowUpRoute({
1350
1626
  resolveToken({ runId }) {
1351
1627
  return \`workflow-session:\${runId}\`;
1352
1628
  },
1353
1629
  });
1354
- `}function $W(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
1630
+ `}function CA(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
1355
1631
 
1356
1632
  export const GET = createWorkflowDevkitStreamRoute();
1357
- `}function WW($,W){return`import { ${W} } from '${$}';
1633
+ `}function IA($,b){return`import { ${b} } from '${$}';
1358
1634
 
1359
1635
  export const workflowDevkitBootstrap = {
1360
- workflow: ${W},
1636
+ workflow: ${b},
1361
1637
  createBridge() {
1362
1638
  return {
1363
1639
  executeAutomationStep: async () => {
@@ -1366,13 +1642,13 @@ export const workflowDevkitBootstrap = {
1366
1642
  };
1367
1643
  },
1368
1644
  };
1369
- `}function jW({exportName:$,specImportPath:W,runnerName:j,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
1645
+ `}function EA({exportName:$,specImportPath:b,runnerName:A,workflowName:m}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
1370
1646
  import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
1371
1647
  import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
1372
- import { ${$} } from '${W}';
1648
+ import { ${$} } from '${b}';
1373
1649
 
1374
1650
  /**
1375
- * Runner wiring for ${A}.
1651
+ * Runner wiring for ${m}.
1376
1652
  *
1377
1653
  * TODO:
1378
1654
  * - Replace the in-memory state store with a persistent adapter if needed.
@@ -1384,7 +1660,7 @@ registry.register(${$});
1384
1660
 
1385
1661
  const stateStore = new InMemoryStateStore();
1386
1662
 
1387
- export const ${j} = new WorkflowRunner({
1663
+ export const ${A} = new WorkflowRunner({
1388
1664
  registry,
1389
1665
  stateStore,
1390
1666
  opExecutor: async (operation, input, ctx) => {
@@ -1406,12 +1682,12 @@ export const ${j} = new WorkflowRunner({
1406
1682
  // console.log(event, payload);
1407
1683
  },
1408
1684
  });
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}
1685
+ `}import{getAuthoringTargetDefinition as q8}from"@contractspec/module.workspace";var _w={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function Uw($,b){let A=O8($,b.specPath),m=V8($,b.target,A),n=$.join(A,"package.json"),W=$.join(A,"README.md"),w=$.join(A,"src"),j=$.join(w,"index.ts"),y=nm($.relative(w,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(w);let B=[[n,JSON.stringify({name:m,version:"0.1.0",description:_w[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
1686
+ `],[W,`# ${m}
1411
1687
 
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";
1688
+ ${_w[b.target]}.
1689
+ `],[j,`export * from "./${y.startsWith(".")?y:`./${y}`}";
1690
+ `],[b.specPath,b.specCode]],S={packageRoot:A,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function zw($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
1415
1691
 
1416
1692
  export const ${$.exportName} = defineModuleBundle({
1417
1693
  meta: {
@@ -1472,22 +1748,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
1472
1748
  supportedArtifactTypes: ["patch"],
1473
1749
  knownConstraints: [],
1474
1750
  };
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";
1751
+ `}}function O8($,b){let A=nm(b),m="/src/",n=A.lastIndexOf("/src/");if(n===-1)return $.dirname(b);return A.slice(0,n)}function V8($,b,A){let m=q8(b),n=nm($.basename(A));return`${m.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${n}`}function nm($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function $b($,b,A,m={}){let{fs:n,logger:W,workspace:w}=b,j=w?.scanSpecSource??R8,y=w?.inferSpecTypeFromFilePath??L8,B=w?.generateHandlerTemplate??_8,S=w?.generateComponentTemplate??K8,Q=w?.generateTestTemplate??U8,{targets:Z=void 0,outputDir:G=A.outputDir,overwrite:X=!1,dryRun:Y=!1,includeTests:V=!1,runtimeGeneration:O}=m,K=await n.readFile($),J=j(K,$),_=J8(K,$),H=_==="unknown"?y($):_,q=Z??wm(H,{includeTests:V});W.info(`Building from spec: ${$}`,{targetId:H});let U=[],z={};for(let L of q)try{let I=await C8(L,$,K,J,H,{fs:n,logger:W},G,X,Y,O,z,{genHandler:B,genComponent:S,genTest:Q});if(U.push(I),I.success&&I.generatedCode)z[L]=I.generatedCode}catch(I){U.push({target:L,outputPath:"",success:!1,error:I instanceof Error?I.message:String(I),skipped:!1})}return{specPath:$,specInfo:J,targetId:H,results:U}}async function C8($,b,A,m,n,W,w,j,y,B,S,Q){let{fs:Z,logger:G}=W,{genHandler:X,genComponent:Y,genTest:V}=Q,O,K,J=[];switch($){case"handler":{if(n!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${n})`};let q=m.kind==="command"||m.kind==="query"?m.kind:"command",U=X(e(A,m,b),q);K=s$(b,w,"handlers",e(A,m,b),".handler.ts",W.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:A,outputPath:K,fallbackCode:U})??U;break}case"component":{if(n!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${n})`};let q=Y(e(A,m,b),m.description??"");K=s$(b,w,"components",e(A,m,b),".tsx",W.fs),O=await B?.generateArtifact?.({kind:"component",specCode:A,outputPath:K,fallbackCode:q})??q;break}case"test":{let q=n==="operation"?"handler":"component",U=n==="operation"?S.handler??"":n==="presentation"?S.component??"":n==="form"?S.form??"":"",z=V(e(A,m,b),q);K=s$(b,w,"__tests__",e(A,m,b),".test.ts",W.fs),O=await B?.generateTest?.({kind:q,specCode:A,outputPath:K,existingCode:U,fallbackCode:z})??z;break}case"form":{if(n!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${n})`};let q=`import * as React from "react";
1476
1752
 
1477
- export interface ${q$(o(j,A,W))}Props {
1753
+ export interface ${H$(e(A,m,b))}Props {
1478
1754
  className?: string;
1479
1755
  }
1480
1756
 
1481
- export function ${q$(o(j,A,W))}Form({
1757
+ export function ${H$(e(A,m,b))}Form({
1482
1758
  className,
1483
- }: ${q$(o(j,A,W))}Props) {
1484
- return <form className={className}>TODO: implement ${o(j,A,W)}</form>;
1759
+ }: ${H$(e(A,m,b))}Props) {
1760
+ return <form className={className}>TODO: implement ${e(A,m,b)}</form>;
1485
1761
  }
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(`
1762
+ `;K=s$(b,w,"forms",e(A,m,b),".form.tsx",W.fs),O=await B?.generateArtifact?.({kind:"form",specCode:A,outputPath:K,fallbackCode:q})??q;break}case"workflow-runner":{if(n!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${n})`};let q=e(A,m,b),U=x8(A)??`${H$(q)}Workflow`,z=`${H$(q)}Runner`,L=jm(q);if(K=s$(b,w,"workflows",q,".runner.ts",W.fs),O=EA({exportName:U,specImportPath:Wm(W.fs,K,b),runnerName:z,workflowName:q}),N8(A)){let I=`${H$(q)}WorkflowDevkit`,C=qb(W.fs,K,`${L}.workflow-devkit.ts`),F=qb(W.fs,K,`${L}.workflow-devkit.start.route.ts`),x=qb(W.fs,K,`${L}.workflow-devkit.follow-up.route.ts`),h=qb(W.fs,K,`${L}.workflow-devkit.stream.route.ts`),nA=qb(W.fs,K,`${L}.workflow-devkit.generic.ts`);J=[{path:C,code:zA({exportName:U,specImportPath:Wm(W.fs,C,b),workflowFunctionName:I})},{path:F,code:LA(Lw(W.fs,F,C),I)},{path:x,code:RA()},{path:h,code:CA()},{path:nA,code:IA(Lw(W.fs,nA,C),I)}]}break}case"data-view-renderer":{if(n!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${n})`};let q=e(A,m,b),U=T8(A)??`${H$(q)}DataView`,z=`${H$(q)}Renderer`;K=s$(b,w,"data-views",q,".renderer.tsx",W.fs),O=_A({exportName:U,specImportPath:Wm(W.fs,K,b),rendererName:z,viewKind:D8(A)??"table"});break}case"package-scaffold":{if(n!=="module-bundle"&&n!=="builder-spec"&&n!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${n})`};if(y){let z=E8(b);return G.info(`[dry-run] Would scaffold package: ${z}`),{target:$,outputPath:z,success:!0}}let q=A.trim().length>0?A:zw({target:n,key:m.key??W.fs.basename(b),title:m.key??W.fs.basename(b),description:m.description??z8(n).title,exportName:H$(m.key??W.fs.basename(b))});return K=(await Uw(W.fs,{target:n,specPath:b,specCode:q,overwrite:j})).packageRoot,G.info(`Generated package scaffold: ${K}`),{target:$,outputPath:K,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let _=[{path:K,code:O},...J],H=j?void 0:await I8(_,Z);if(H)return{target:$,outputPath:H,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(y){for(let q of _)G.info(`[dry-run] Would write: ${q.path}`);return{target:$,outputPath:K,success:!0,generatedCode:_[0]?.code}}for(let q of _)await Z.mkdir(Z.dirname(q.path)),await Z.writeFile(q.path,F8(q.code)),G.info(`Generated: ${q.path}`);return{target:$,outputPath:K,success:!0}}function wm($,b){switch($){case"operation":return b.includeTests?["handler","test"]:["handler"];case"presentation":return b.includeTests?["component","test"]:["component"];case"form":return b.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 s$($,b,A,m,n,W){let w=jm(m.split(".").pop()??"unknown"),j;if(b.startsWith("."))j=W.resolve(W.dirname($),"..",b,A);else j=W.resolve(b,A);return W.join(j,`${w}${n}`)}async function I8($,b){for(let A of $)if(await b.exists(A.path))return A.path;return}function jm($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function H$($){return jm($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function ym($){return $.replace(/\.[^.]+$/,"")}function E8($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Wm($,b,A){let m=ym($.relative($.dirname(b),A));return m.startsWith(".")?m:`./${m}`}function Lw($,b,A){let m=ym($.relative($.dirname(b),A));return m.startsWith(".")?m:`./${m}`}function qb($,b,A){return $.join($.dirname(b),A)}function e($,b,A){return M8($,"name")??b.key??ym(v8(A))}function M8($,b){let A=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(A)?.[1]??null}function x8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function T8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function D8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function N8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function F8($){return $.endsWith(`
1487
1763
  `)?$:`${$}
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
1764
+ `}function v8($){return $.replaceAll("\\","/").split("/").pop()??$}s();import{scanAllSpecsFromSource as h8,scanSpecSource as c8}from"@contractspec/module.workspace";import d8 from"micromatch";var Ew={};P(Ew,{validators:()=>f8,urlSchema:()=>r8,isValidVersion:()=>k8,isValidIdentifier:()=>Cw,isValidDotName:()=>Iw,isTestFile:()=>Ob,isLibraryDefinitionFile:()=>Vb,emailSchema:()=>P8});import Bm from"micromatch";function Ob($,b){let A=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return Bm.isMatch($,A)}function Vb($){let b=["**/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(Bm.isMatch($,b))return!1;let A=["**/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 Bm.isMatch($,A)}import*as q$ from"zod";function Cw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function Iw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function k8($){return Number.isInteger($)&&$>0}var P8=q$.string().email(),r8=q$.string().url(),f8={specName:q$.string().refine(Iw,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:q$.number().int().positive(),identifier:q$.string().refine(Cw,{message:"Must be a valid TypeScript identifier"}),owner:q$.string().startsWith("@"),tag:q$.string().min(1)};function Jb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function u8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],A=[...Jb($?.conventions.models),...Jb($?.conventions.operations),...Jb($?.conventions.events),...Jb($?.conventions.presentations),...Jb($?.conventions.forms)];return[...new Set(b.flatMap((m)=>{let n=m==="**"?"":`${m}/`,W=X$.map((j)=>`${n}${j}`),w=A.map((j)=>`${n}${j}/**/*.ts`);return[...W,...w]}))]}function o8($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function i8($,b){let A=$.filePath.localeCompare(b.filePath);if(A!==0)return A;let m=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(m!==0)return m;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function g$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((A,m)=>A.localeCompare(m));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:u8(b.config)})}async function xA($,b={}){let A=await g$($.fs,b),m=b.type?Array.isArray(b.type)?b.type:[b.type]:[],n=[];for(let W of A){if(b.config?.excludePackages&&d8.isMatch(W,b.config.excludePackages,{contains:!0}))continue;if(W.includes("node_modules")||W.includes("/dist/")||Ob(W,b.config)||Vb(W))continue;try{let w=await $.fs.readFile(W),j=h8(w,W),y=j.length>0?j:[c8(w,W)];for(let B of y)if(o8(B,b,m))n.push(B)}catch{}}return n.sort(i8)}function _$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function TA($){let b=JSON.parse($),A=new Map,m=0,n=0,W=0,w=0,j=0,y=0,B=0,S=0;for(let[Z,G]of Object.entries(b)){let X=l8(Z,G);A.set(Z,X),m+=X.statements.total,n+=X.statements.covered,W+=X.branches.total,w+=X.branches.covered,j+=X.functions.total,y+=X.functions.covered,B+=X.lines.total,S+=X.lines.covered}let Q={statements:{covered:n,total:m,pct:_$(n,m)},branches:{covered:w,total:W,pct:_$(w,W)},functions:{covered:y,total:j,pct:_$(y,j)},lines:{covered:S,total:B,pct:_$(S,B)}};return{files:A,total:Q}}function l8($,b){let A=Object.keys(b.statementMap).length,m=Object.values(b.s).filter((S)=>S>0).length,n=Object.keys(b.fnMap).length,W=Object.values(b.f).filter((S)=>S>0).length,w=0,j=0;for(let S of Object.values(b.b))w+=S.length,j+=S.filter((Q)=>Q>0).length;let y=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(y.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:m,total:A,pct:_$(m,A)},branches:{covered:j,total:w,pct:_$(j,w)},functions:{covered:W,total:n,pct:_$(W,n)},lines:{covered:B.size,total:y.size,pct:_$(B.size,y.size)}}}function Sm($){switch($){case"istanbul":return{parse:TA};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 Qm($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function Zm($,b,A,m){let n=[];if(A.statements!==void 0&&m.statements.pct<A.statements)n.push({metric:"statements",required:A.statements,actual:m.statements.pct,message:`Statement coverage ${m.statements.pct}% is below required ${A.statements}%`});if(A.branches!==void 0&&m.branches.pct<A.branches)n.push({metric:"branches",required:A.branches,actual:m.branches.pct,message:`Branch coverage ${m.branches.pct}% is below required ${A.branches}%`});if(A.functions!==void 0&&m.functions.pct<A.functions)n.push({metric:"functions",required:A.functions,actual:m.functions.pct,message:`Function coverage ${m.functions.pct}% is below required ${A.functions}%`});if(A.lines!==void 0&&m.lines.pct<A.lines)n.push({metric:"lines",required:A.lines,actual:m.lines.pct,message:`Line coverage ${m.lines.pct}% is below required ${A.lines}%`});if(A.mutations!==void 0)n.push({metric:"mutations",required:A.mutations,actual:0,message:`Mutation coverage required (${A.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:A,actual:m,passed:n.length===0,failures:n}}async function Gm($,b,A){let{fs:m,logger:n}=$,W=[],w=A.workspaceRoot?`${A.workspaceRoot}/coverage`:"./coverage",j=[`${w}/coverage-final.json`,`${w}/coverage.json`,`${w}/coverage-summary.json`],y,B;for(let G of j)if(await m.exists(G)){y=await m.readFile(G),B=G;break}if(!y)return n.info("No coverage report found, skipping coverage checks"),W;let S=Qm(B??"coverage.json"),Z=Sm(S).parse(y);for(let G of b){if(G.specType!=="test-spec"||!G.key||!G.version||!G.sourceBlock)continue;let X=G.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!X||!X[1])continue;let Y=X[1],V={},O=Y.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=Y.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=Y.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let _=Y.match(/lines\s*:\s*(\d+)/);if(_&&_[1])V.lines=parseInt(_[1],10);if(Object.keys(V).length===0)continue;let H=Zm(G.key,G.version,V,Z.total);for(let q of H.failures)W.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:G.filePath,context:{specKey:G.key,specVersion:G.version,metric:q.metric,required:q.required,actual:q.actual}})}return W}s();import{addContractNode as t8,buildReverseEdges as p8,createContractGraph as a8,detectCycles as e8,findMissingDependencies as s8,parseImportedSpecNames as $9,toDot as b9}from"@contractspec/module.workspace";async function Mw($,b={}){let{fs:A}=$,m=await g$(A,{config:b.config,pattern:b.pattern}),n=a8();for(let j of m){let y=await A.readFile(j),B=A.relative(".",j),S=A.basename(j).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=$9(y,j);t8(n,S,B,Q)}p8(n);let W=e8(n),w=s8(n);return{graph:n,total:n.size,cycles:W,missing:w}}function Hq($,b){return $.get(b)}function qq($){return b9($)}function Oq($){let b=Array.from($.values()),A=b.filter((w)=>w.dependencies.length>0),m=b.filter((w)=>w.dependencies.length===0),n=b.filter((w)=>w.dependents.length>0),W=b.filter((w)=>w.dependents.length===0);return{total:$.size,withDeps:A.length,withoutDeps:m.length,used:n.length,unused:W.length}}async function Xm($,b){let A=[],m=await g($.fs),n=await Mw($,{config:m,pattern:b.pattern});for(let W of n.cycles)A.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${W.join(" \u2192 ")}`,category:"deps",context:{cycle:W}});for(let W of n.missing)for(let w of W.missing)A.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${W.contract} requires ${w}`,category:"deps",context:{contract:W.contract,missing:w}});return A}import{analyzePackageDocBlocks as A9}from"@contractspec/module.workspace";var m9=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function n9($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:m9}),m=new Map;for(let w of A){let j=$.dirname(w),y=$.join(j,"src");if(!await $.exists(y))continue;try{let B=JSON.parse(await $.readFile(w));m.set(j,{packageName:B.name??$.relative(b,j),packageRoot:j,srcRoot:y})}catch{continue}}let n=$.join(b,"package.json"),W=$.join(b,"src");if(await $.exists(n)&&await $.exists(W))try{let w=JSON.parse(await $.readFile(n));m.set(b,{packageName:w.name??b,packageRoot:b,srcRoot:W})}catch{}return[...m.values()].sort((w,j)=>w.packageRoot.localeCompare(j.packageRoot))}async function DA($,b){let A=[],m=await n9($,b);for(let n of m){let W=A9({packageName:n.packageName,srcRoot:n.srcRoot});for(let w of W.diagnostics)A.push({...w,packageName:n.packageName,packageRoot:n.packageRoot,srcRoot:n.srcRoot})}return A}async function Ym($,b){let A=b.workspaceRoot??process.cwd();return(await DA($.fs,A)).map((n)=>({ruleId:n.ruleId,severity:n.severity==="warning"?"warning":"error",message:n.message,category:"docs",file:n.file,line:n.line,column:n.column,context:{packageName:n.packageName,packageRoot:n.packageRoot,...n.context}}))}async function Hm($,b,A){let m=[],n=await W9($,b);if(m.push(n),n.status==="pass")m.push(await w9($,b,A));return m}async function W9($,b){let A=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(A))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let n=await $.readFile(A),W=JSON.parse(n),w=W.aiProvider??"claude",j=W.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${w}, Model: ${j}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function w9($,b,A){let m=$.join(b.workspaceRoot,".contractsrc.json");try{let n=await $.readFile(m),w=JSON.parse(n).aiProvider??"claude",y={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[w];if(!y)return{category:"ai",name:"API Key",status:"pass",message:`${w} does not require an API key`};if(!!process.env[y])return{category:"ai",name:"API Key",status:"pass",message:`${y} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${y} not set`,details:`Set ${y} in your environment to use AI features`,fix:A?{description:`Set ${y} environment variable`,apply:async()=>{let S=await A.input(`Enter your ${w} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${y}=`))return{success:!1,message:`${y} already in .env, update manually`};Z+=`
1765
+ `}return Z+=`${y}=${S}
1766
+ `,await $.writeFile(Q,Z),{success:!0,message:`Added ${y} to .env (restart required)`}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as j9}from"child_process";import{promisify as y9}from"util";var NA=y9(j9);async function qm($,b){let A=[];return A.push(await B9(b)),A.push(await S9(b)),A.push(await Q9($,b)),A}async function B9($){try{return await NA("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 NA("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(b){return{success:!1,message:`Failed to install: ${b instanceof Error?b.message:String(b)}`}}}}}}}async function S9($){try{let{stdout:b}=await NA("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${b.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function Q9($,b){let A=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(A))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let j=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(j))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let n=await $.readFile(A),W=JSON.parse(n);if(W.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||W.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 NA("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(j){return{success:!1,message:`Failed to install: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}s();import{DEFAULT_CONTRACTSRC as FA}from"@contractspec/lib.contracts-spec/workspace-config";import{join as Z9,relative as G9}from"path";var X9="contractspec",Y9="contractsrc.schema.json";function H9($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Kb($){return H9(G9($.configRoot,Z9($.workspaceRoot,"node_modules",X9,Y9)))}var _b=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],xw={"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)","usage-md":"Usage Guide (USAGE.md)"},Tw=["core","connect","builder-managed","builder-local","builder-hybrid"],Dw={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)"},Nw={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 and control-plane-backed next steps.","builder-hybrid":"Core workspace setup plus Builder config for hybrid runtime with API and local defaults."};var Ub={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function zb($){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 U$($){return $.preset??"core"}function Fw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return _b}}function Om($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function vw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function Fq($){return $.startsWith("builder-")}function vq($){return $==="connect"}function gw($){let b=U$($),A=q9($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset managed-mvp`,`contractspec builder status --workspace-id ${A}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function q9($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function kw($){let b=U$($),A=[Ub.verificationCache];if(b==="connect")A.unshift(Ub.connect);return A}function bb($){let b=$.isMonorepo&&$.scope==="package",A=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,m=O9($),n=V9($);return{$schema:Kb({configRoot:A,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"]},...m?{connect:m}:{},...n?{builder:n}:{},...b&&$.packageName?{package:$.packageName}:{}}}function vA($){let b=U$($),A={"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(Om(b))A["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return A}function Lb(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function Pw(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function rw($){let b=$.projectName??"this project",m=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
1491
1767
 
1492
1768
  This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
1493
1769
 
@@ -1508,10 +1784,10 @@ Check the appropriate level based on the feature scope.
1508
1784
  ## Contract Locations
1509
1785
 
1510
1786
  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
1787
+ - \`${m}/operations/\` - Command and query specs
1788
+ - \`${m}/events/\` - Event specs
1789
+ - \`${m}/presentations/\` - UI presentation specs
1790
+ - \`${m}/features/\` - Feature module specs
1515
1791
 
1516
1792
  ## When Making Changes
1517
1793
 
@@ -1520,6 +1796,14 @@ Contracts are located in:
1520
1796
  3. **If no contract**: Create a new contract using \`contractspec create\`.
1521
1797
  4. **After changes**: Validate with \`contractspec validate\`.
1522
1798
 
1799
+ ## Adoption Engine
1800
+
1801
+ - Reuse existing workspace code before inventing a new local surface.
1802
+ - Prefer ContractSpec OSS packages before reaching for raw framework or vendor primitives.
1803
+ - Use \`contractspec connect adoption sync\` to mirror the local catalog.
1804
+ - Use \`contractspec connect adoption resolve --family <family> --stdin\` to resolve the recommended reuse target.
1805
+ - If Connect says \`rewrite\`, reuse the existing workspace or ContractSpec candidate instead of creating a duplicate.
1806
+
1523
1807
  ## Key Commands
1524
1808
 
1525
1809
  - \`contractspec create\` - Scaffold new specs
@@ -1539,13 +1823,13 @@ defineCommand({
1539
1823
  });
1540
1824
  \`\`\`
1541
1825
 
1542
- ## Rules for ${W}
1826
+ ## Rules for ${b}
1543
1827
 
1544
1828
  - All API endpoints must have a corresponding operation contract.
1545
1829
  - Events must be declared in contracts before being emitted.
1546
1830
  - UI components should reference presentation contracts.
1547
1831
  - 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?`
1832
+ `}function fw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package",m=U$($),n=A&&$.packageName?`${$.packageName} package`:b,W="src/contracts",w=$.isMonorepo?A?`
1549
1833
  ## Monorepo Scope
1550
1834
 
1551
1835
  This guide is scoped to the current package.
@@ -1559,7 +1843,7 @@ This guide is scoped to the workspace root.
1559
1843
  - Prefer the nearest package guide when working inside a specific package.
1560
1844
  `:"";return`# ContractSpec AI Guide
1561
1845
 
1562
- Scope: \`${Q}\`
1846
+ Scope: \`${n}\`
1563
1847
 
1564
1848
  This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
1565
1849
 
@@ -1569,7 +1853,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
1569
1853
  - Validate contracts after changes with \`contractspec validate\`.
1570
1854
  - Regenerate derived artifacts before considering the work complete.
1571
1855
  - Prefer existing package-local guides and READMEs when working in a nested package.
1572
- ${X}
1856
+ ${w}
1573
1857
  ## Contract Locations
1574
1858
 
1575
1859
  - \`src/contracts/operations/\` - command and query specs
@@ -1596,20 +1880,55 @@ ${X}
1596
1880
  - Keep changes spec-first, deterministic, and reviewable.
1597
1881
  - Do not change generated outputs without updating their source contract.
1598
1882
  - When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
1883
+ - Reuse existing workspace code before creating new files, packages, or dependencies.
1884
+ - Prefer ContractSpec OSS packages by family:
1885
+ - UI: local reusable UI -> \`@contractspec/lib.design-system\` -> platform ui-kit -> shadcn/web fallback
1886
+ - Contracts: existing local spec -> \`@contractspec/lib.contracts-spec\` / \`@contractspec/lib.schema\`
1887
+ - Integrations/runtime/shared libs: existing workspace surface -> ContractSpec OSS catalog -> reviewed fallback
1888
+ - Use \`contractspec connect adoption sync\` and \`contractspec connect adoption resolve --family <family>\` when the right reusable surface is unclear.
1599
1889
 
1600
1890
  ## Initialization Preset
1601
1891
 
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:`
1892
+ - This workspace was initialized with the \`${m}\` setup preset.
1893
+ `}function hw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
1894
+
1895
+ Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
1896
+
1897
+ This workspace uses ContractSpec to keep contracts, generated artifacts, and AI guidance aligned.
1898
+
1899
+ ## Start Here
1900
+
1901
+ 1. Run \`contractspec onboard\` to generate a track-aware onboarding guide for this repo.
1902
+ 2. Run \`contractspec validate\` after changing contracts or generated outputs.
1903
+ 3. Run \`contractspec doctor\` if local setup or tooling looks unhealthy.
1904
+
1905
+ ## Recommended Commands
1906
+
1907
+ - \`contractspec onboard\` - generate repo-local onboarding guidance and next steps
1908
+ - \`contractspec create\` - scaffold a new contract or package target
1909
+ - \`contractspec generate\` - refresh derived docs and artifacts
1910
+ - \`contractspec validate\` - validate contracts, package scaffolds, and integrity
1911
+ - \`contractspec connect adoption resolve --family <family> --stdin\` - reuse existing ContractSpec or workspace surfaces before building new ones
1912
+
1913
+ ## Builder / Connect
1914
+
1915
+ - Use \`contractspec init --preset connect\` when you want local Connect artifacts and reuse guidance in the repo.
1916
+ - Use \`contractspec init --preset builder-managed\`, \`builder-local\`, or \`builder-hybrid\` when you want Builder control-plane defaults.
1917
+
1918
+ ## Notes
1919
+
1920
+ - \`AGENTS.md\` is for AI-agent operating guidance.
1921
+ - \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
1922
+ `}function O9($){if(U$($)!=="connect")return;return{...FA.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin",packageRef:"contractspec-adoption"},codex:{enabled:!0,mode:"wrapper",packageRef:"contractspec-adoption"},"claude-code":{enabled:!0,mode:"rule",packageRef:"contractspec-adoption"}},adoption:{...FA.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:FA.connect?.studio}}function V9($){let b=Om(U$($)),A=vw(U$($));if(!b||!A)return;let m=!0,n=b==="local"||b==="hybrid";return{...FA.builder,enabled:!0,runtimeMode:b,bootstrapPreset:A,api:m?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:n?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function gA(){let $=process.platform,b=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${b}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??b}/Claude/claude_desktop_config.json`;default:return`${b}/.config/claude/claude_desktop_config.json`}}function $$($,b){let A={...$};for(let m of Object.keys(b)){let n=$[m],W=b[m];if(n===void 0)A[m]=W;else if(kA(n)&&kA(W))A[m]=$$(n,W)}return A}function Vm($,b){let A={...$};for(let m of Object.keys(b)){let n=$[m],W=b[m];if(W===void 0)continue;if(kA(n)&&kA(W))A[m]=Vm(n,W);else A[m]=W}return A}function kA($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function p($){try{return JSON.parse($)}catch{return null}}function N($){return JSON.stringify($,null,2)+`
1923
+ `}async function Jm($,b){let A=[];return A.push(await J9($,b)),A.push(await K9($,b)),A.push(await _9($,b)),A.push(await U9($,b)),A.push(await z9($,b)),A.push(await L9($,b)),A.push(await R9($,b)),A}async function k$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function J9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(await $.exists(A))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 n=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,N(n)),{success:!0,message:"Created .contractsrc.json"}}catch(n){return{success:!1,message:`Failed to create: ${n instanceof Error?n.message:String(n)}`}}}}}}async function K9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A);return JSON.parse(n),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(n){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:n instanceof Error?n.message:String(n),fix:{description:"Replace with valid default config",apply:async()=>{try{let w=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,N(w)),{success:!0,message:"Replaced with valid config"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}}async function _9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n),w=[];if(!W.outputDir)w.push("outputDir");if(!W.conventions)w.push("conventions");if(w.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: ${w.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let j=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let y of w)if(j[y]!==void 0)W[y]=j[y];return await $.writeFile(A,N(W)),{success:!0,message:"Added missing fields"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function U9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:W.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 W.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(A,N(W)),{success:!0,message:"Added versioning configuration"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function z9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.hooks){let y=W.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(y).length} git hook(s) configured`}}let w=$.join(b.workspaceRoot,".husky");if(await $.exists(w))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 W.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(A,N(W)),{success:!0,message:"Added hooks configuration"}}catch(y){return{success:!1,message:`Failed: ${y instanceof Error?y.message:String(y)}`}}}}};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 L9($,b){let A=await k$($,b),m=await g($,A),n=zb(m);if(n==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(n==="connect"){let j=[m.connect?.storage?.root?null:"storage.root",m.connect?.storage?.contextPack?null:"storage.contextPack",m.connect?.storage?.planPacket?null:"storage.planPacket",m.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),y=m.connect?.studio?.enabled&&m.connect?.studio?.mode==="review-bridge"&&!m.connect?.studio?.endpoint;if(j.length===0&&!y)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: ${[...j,...y?["connect.studio.endpoint"]:[]].join(", ")}`}}let W=[],w=m.builder?.api?.controlPlaneTokenEnvVar;if(n.startsWith("builder-")&&!m.builder?.api?.baseUrl)W.push("builder.api.baseUrl");if(n.startsWith("builder-")&&!w)W.push("builder.api.controlPlaneTokenEnvVar");if(n.startsWith("builder-")&&w&&!process.env[w])W.push(`env:${w}`);if((n==="builder-local"||n==="builder-hybrid")&&!m.builder?.localRuntime?.runtimeId)W.push("builder.localRuntime.runtimeId");if((n==="builder-local"||n==="builder-hybrid")&&!m.builder?.localRuntime?.grantedTo)W.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:W.length===0?"pass":"warn",message:W.length===0?`Builder preset inferred (${n}) and required config is present`:`Builder preset inferred (${n}) but setup is missing ${W.join(", ")}`}}async function R9($,b){let A=await k$($,b),m=await g($,A),n=zb(m);if(!n.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let W=$.join(A,".vscode","settings.json"),w=m.builder?.api?.baseUrl;if(!w)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let j=await $.readFile(W).catch(()=>""),y=j?p(j):void 0;if(y?.["contractspec.api.baseUrl"]===w)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 S=$.join(A,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...y??{},...vA({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:n,targets:[],builderApiBaseUrl:w})};return await $.writeFile(W,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as C9}from"child_process";import{promisify as I9}from"util";var P$=I9(C9);async function Km($,b){let A=[];return A.push(await E9(b)),A.push(await M9(b)),A.push(await x9($,b)),A.push(await T9($,b)),A.push(await D9($,b)),A}async function E9($){try{let{stdout:b}=await P$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.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 M9($){try{let{stdout:b}=await P$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.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 x9($,b){let A=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],m=null;for(let{file:n,name:W}of A){let w=$.join(b.workspaceRoot,n);if(await $.exists(w)){m=W;break}}if(!m){let n=$.join(b.workspaceRoot,".."),W=$.join(b.workspaceRoot,"../.."),w=[n,W];for(let j of w){for(let{file:y,name:B}of A){let S=$.join(j,y);if(await $.exists(S)){m=B;break}}if(m)break}}if(!m)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 P$(`${m} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${m}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${m} detected but not available`,details:`Install ${m} or use a different package manager`}}}async function T9($,b){let A=$.join(b.workspaceRoot,"node_modules");if(await $.exists(A))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 P$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await P$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(n){return{success:!1,message:`Failed: ${n instanceof Error?n.message:String(n)}`}}}}}}async function D9($,b){let A=$.join(b.workspaceRoot,"package.json");try{let m=await $.readFile(A),n=JSON.parse(m),W={...n.dependencies,...n.devDependencies};if("@contractspec/lib.contracts-spec"in W)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${W["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.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 P$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await P$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function _m($,b){let A=await DA($,b.workspaceRoot);if(A.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return A.map((m)=>({category:"docs",name:`Same-File DocBlocks (${m.packageName})`,status:m.severity==="warning"?"warn":"fail",message:m.message,details:$.relative(b.workspaceRoot,m.file),context:{ruleId:m.ruleId,file:m.file,line:m.line,column:m.column,packageName:m.packageName}}))}import{isExampleFile as N9,isFeatureFile as F9,scanAllSpecsFromSource as v9,scanExampleSource as g9,scanFeatureSource as k9}from"@contractspec/module.workspace";function P9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function PA($,b={}){let{fs:A,logger:m}=$,n=P9(),W=b.pattern??"**/*.{ts,tsx}";m.info("Scanning for contract layer files...");let w=await A.glob({pattern:W});for(let y of w){if(y.includes("node_modules")||y.includes("/dist/"))continue;try{let B=await A.readFile(y);if(F9(y)){let S=k9(B,y);n.features.set(S.key,S);continue}if(N9(y)){let S=g9(B,y);n.examples.set(S.key,S);continue}if(y.includes(".app-config.")||y.includes(".blueprint.")){let S=v9(B,y);for(let Q of S)if(Q.specType==="app-config"&&Q.key)n.appConfigs.set(Q.key,Q)}}catch{}}try{let y=await A.glob({pattern:"**/.contractsrc.json"});for(let B of y){if(B.includes("node_modules"))continue;try{let S=await A.readFile(B),Q=JSON.parse(S);n.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){n.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let j={features:n.features.size,examples:n.examples.size,appConfigs:n.appConfigs.size,workspaceConfigs:n.workspaceConfigs.size,total:n.features.size+n.examples.size+n.appConfigs.size+n.workspaceConfigs.size};return m.info(`Discovered ${j.features} features, ${j.examples} examples, ${j.appConfigs} app configs, ${j.workspaceConfigs} workspace configs`),{inventory:n,stats:j}}function $O($){let b=[];for(let[A,m]of $.features)b.push({key:A,file:m.filePath,type:"feature"});for(let[A,m]of $.examples)b.push({key:A,version:m.version,file:m.filePath,type:"example"});for(let[A,m]of $.appConfigs)b.push({key:A,version:m.version,file:m.filePath,type:"app-config"});for(let[,A]of $.workspaceConfigs)b.push({key:A.file,file:A.file,type:"workspace-config"});return b}function rA($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function Um($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function fA($,b){let A=$.join(b,"config/stability-policy.json");if(!await $.exists(A))return;try{let m=await $.readFile(A),n=JSON.parse(m);return{version:typeof n.version==="number"&&Number.isFinite(n.version)?n.version:1,criticalPackages:Um(n.criticalPackages).map(rA),criticalFeatureKeys:Um(n.criticalFeatureKeys),smokePackages:Um(n.smokePackages)}}catch{return}}function cw($,b){let A=rA($);if(b?.criticalPackages.includes(A))return"critical";return"non-critical"}function dw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function Ab($){return rA(`${rA($)}/config/stability-policy.json`)}async function zm($,b){let A=[],m=await fA($,b.workspaceRoot),n=await PA({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return A.push(r9(n.stats.features)),A.push(f9(n.stats.examples)),A.push(h9(n.inventory.features,m,b)),A.push(c9(n.inventory.examples)),A.push(d9(n.inventory.workspaceConfigs)),A}function r9($){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 f9($){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 h9($,b,A){let m=[],n=[];for(let[W,w]of $)if(!(Boolean(w.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(w.sourceBlock??"")))if(dw(W,b))n.push(W);else m.push(W);if(n.length===0&&m.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:b?Ab(A.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:n.length>0?"fail":"warn",message:n.length>0?`${n.length} critical feature(s) missing owners`:`${m.length} feature(s) missing owners`,details:n.length>0?`Critical features: ${n.join(", ")}`:`Features: ${m.slice(0,3).join(", ")}${m.length>3?"...":""}`,context:{policyPath:b?Ab(A.workspaceRoot):void 0,criticalMissingFeatures:n,missingFeatures:m}}}function c9($){let b=[];for(let[A,m]of $)if(!m.entrypoints.packageName)b.push(A);if(b.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:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function d9($){let b=[];for(let[,A]of $)if(!A.valid)b.push(A.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.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:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function Lm($,b){let A=[];return A.push(await u9($,b)),A.push(await o9($,b)),A.push(await i9($,b)),A}async function u9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(A))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 n=$.join(b.workspaceRoot,".cursor");if(!await $.exists(n))await $.mkdir(n);let W=Lb();return await $.writeFile(A,N(W)),{success:!0,message:"Created .cursor/mcp.json"}}catch(n){return{success:!1,message:`Failed: ${n instanceof Error?n.message:String(n)}`}}}}}}async function o9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(A))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.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 j=Lb(),y=$$(W,j);return await $.writeFile(A,N(y)),{success:!0,message:"Registered MCP server"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function i9($,b){let A=gA();try{if(!await $.exists(A))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let n=await $.readFile(A);if(JSON.parse(n).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 l9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],uw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function t9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,m])=>{if(typeof m==="string")b[A]=m;return b},{})}function p9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function a9($,b,A){let m=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:uw}),n=[];for(let W of m){let w=$.dirname(W),j=$.relative(b,w);try{let y=JSON.parse(await $.readFile(W)),B=t9(y.scripts),S=await $.glob({patterns:l9,cwd:w,ignore:uw});n.push({packageName:y.name??j,packagePath:j.replace(/\\/g,"/"),hasBuildScript:typeof B.build==="string",hasTypecheckScript:typeof B.typecheck==="string",hasLintScript:typeof B.lint==="string"||typeof B["lint:check"]==="string",hasTestScript:typeof B.test==="string",usesPassWithNoTests:p9(B),testFileCount:S.length,tier:cw(j,A)})}catch{continue}}return n}function e9($){let b=[];if(!$.hasBuildScript)b.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)b.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)b.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)b.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)b.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)b.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return b}function s9($){let b=[];if($.testFileCount>0&&!$.hasTestScript)b.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)b.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return b}async function ow($,b,A){let m=await a9($,b,A),n=[];for(let w of m){if(w.tier==="critical")n.push(...e9(w));n.push(...s9(w))}let W=m.filter((w)=>w.tier==="critical").map((w)=>({packageName:w.packageName,packagePath:w.packagePath,hasBuildScript:w.hasBuildScript,hasTypecheckScript:w.hasTypecheckScript,hasLintScript:w.hasLintScript,hasTestScript:w.hasTestScript,usesPassWithNoTests:w.usesPassWithNoTests,testFileCount:w.testFileCount}));return{findings:n,criticalPackages:W}}function lw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function iw($,b,A,m){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:m,context:{findings:[]}};let n=b.filter((W)=>{return W.tier==="critical"||A.has(W.code)});return{category:"workspace",name:$,status:n.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:lw(b),context:{findings:b}}}async function tw($,b){let A=await fA($,b.workspaceRoot);if(!A)return[];let m=await ow($,b.workspaceRoot,A),n=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"]),W=m.findings.filter((y)=>n.has(y.code)),w=m.findings.filter((y)=>y.code==="tests-without-test-script"),j=m.findings.filter((y)=>y.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:W.length>0?"fail":"pass",message:W.length>0?`${W.length} critical package gate failure(s)`:`All ${m.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:W.length>0?lw(W):b.verbose?`Policy: ${Ab(b.workspaceRoot)}`:void 0,context:{policyPath:Ab(b.workspaceRoot),criticalPackages:m.criticalPackages,findings:W}},iw("Package Test Scripts",w,new Set,"All tested packages expose a test script"),iw("Buildable Packages Without Tests",j,new Set,"All buildable packages have tests or explicit test scripts")]}var $S=["src/contracts","contracts","src/specs","specs"];async function Rm($,b){let A=[];return A.push(bS(b)),A.push(await AS($,b)),A.push(await mS($,b)),A.push(await nS($,b)),A.push(await wS($,b)),A.push(...await tw($,b)),A}function bS($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",A=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${A}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function AS($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let m of A){let n=$.join(m,"package.json");if(await $.exists(n))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${m}`: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 mS($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],m=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let w of A)for(let j of $S){let y=$.join(w,j);if(await $.exists(y)){let B=w===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${j}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let n=b.isMonorepo?"src/contracts":"src/contracts",W=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${n}/${W} to organize your specs`,fix:{description:`Create ${n}/ directory${W}`,apply:async()=>{try{let w=$.join(m,"src","contracts");return await $.mkdir(w),{success:!0,message:`Created ${n}/`}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}async function nS($,b){try{let A=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],m=b.isMonorepo?b.packageRoot:b.workspaceRoot,n=await $.glob({patterns:A,ignore:["node_modules/**","dist/**"],cwd:m});if(n.length>0){let w=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${n.length} contract file(s)${w}`,details:b.verbose?n.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.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:b.isMonorepo?`No contract files found in package "${b.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 WS($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let m=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(m))return{path:m,root:b.packageRoot,level:"package"}}let A=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.workspaceRoot,level:"workspace"};return null}async function wS($,b){try{let A=await WS($,b);if(!A)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let m=await $.readFile(A.path),n=JSON.parse(m),W=n.outputDir??"./src",w=$.join(A.root,W),j=b.isMonorepo?` (${A.level} level)`:"";if(await $.exists(w))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${W}${j}`,details:b.verbose?`Resolved to: ${w}`:void 0};let B=W==="./src"||W==="src",S=Array.isArray(n.packages)&&n.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||A.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${A.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${W}${j}`,details:b.verbose?`Expected at: ${w}`:void 0,fix:{description:`Create ${W} directory`,apply:async()=>{try{return await $.mkdir(w),{success:!0,message:`Created ${W}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var pw=["cli","config","mcp","deps","docs","workspace","ai","layers"],aw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var jS={checks:{runCliChecks:qm,runConfigChecks:Jm,runMcpChecks:Lm,runDepsChecks:Km,runDocChecks:_m,runWorkspaceChecks:Rm,runAiChecks:Hm,runLayerChecks:zm},workspace:{findWorkspaceRoot:M,findPackageRoot:r,isMonorepo:Gb,getPackageName:T$}},yS={confirm:async()=>!1,input:async()=>""};async function ew($,b,A=yS,m=jS){let{fs:n,logger:W}=$,w=b.categories??pw,{checks:j,workspace:y}=m,B=y.findWorkspaceRoot(b.workspaceRoot),S=y.findPackageRoot(b.workspaceRoot),Q=y.isMonorepo(B),Z=Q?y.getPackageName(S):void 0,G={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";W.info(`Detected monorepo${J}`)}let X=[];for(let J of w){if(b.skipAi&&J==="ai")continue;W.info(`Checking ${aw[J]}...`);let _=await BS(J,n,G,A,j);for(let H of _){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await A.confirm(`Fix "${H.name}"? ${H.fix.description}`)){W.info(`Applying fix: ${H.fix.description}`);let U=await H.fix.apply();if(U.success)W.info(`\u2713 ${U.message}`),H.status="pass",H.message=`Fixed: ${U.message}`,H.fix=void 0;else W.warn(`\u2717 ${U.message}`)}}X.push(H)}}let Y=X.filter((J)=>J.status==="pass").length,V=X.filter((J)=>J.status==="warn").length,O=X.filter((J)=>J.status==="fail").length,K=X.filter((J)=>J.status==="skip").length;return{checks:X,passed:Y,warnings:V,failures:O,skipped:K,healthy:O===0}}async function BS($,b,A,m,n){switch($){case"cli":return n.runCliChecks(b,A);case"config":return n.runConfigChecks(b,A);case"mcp":return n.runMcpChecks(b,A);case"deps":return n.runDepsChecks(b,A);case"docs":return n.runDocChecks(b,A);case"workspace":return n.runWorkspaceChecks(b,A);case"ai":return n.runAiChecks(b,A,m);case"layers":return n.runLayerChecks(b,A);default:return[]}}function EO($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
1924
+ `)}function MO($){let A=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)A+=`
1925
+ ${$.details}`;if($.fix)A+=`
1926
+ Fix available: ${$.fix.description}`;return A}async function Cm($,b){let A=[],m=b.workspaceRoot??process.cwd(),n=await ew($,{workspaceRoot:m,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let W of n.checks)if(W.status==="fail")A.push({ruleId:`doctor-${W.category}-${W.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${W.name}: ${W.message}`,category:"doctor",context:{details:W.details,...W.context??{}}});else if(W.status==="warn")A.push({ruleId:`doctor-${W.category}-${W.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${W.name}: ${W.message}`,category:"doctor",context:{details:W.details,...W.context??{}}});return A}s();import{mkdtemp as LS,rm as RS}from"fs/promises";import{tmpdir as CS}from"os";import Rb from"path";import{DEFAULT_CONTRACTSRC as qS}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as OS}from"@contractspec/module.workspace";import VS from"path";import{packageDocBlocks as SS}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as QS,convertSpecToDocBlock as ZS,extractModuleDocData as GS,loadSpecFromSource as XS,scanAllSpecsFromSource as YS,scanSpecSource as HS}from"@contractspec/module.workspace";import Em from"path";import{dirname as sw,sep as hA}from"path";class Im{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let A;if(b.specType==="app-config")A="app-config";else if(b.specType==="example")A="example";else if(b.specType==="feature")A="feature";if(A&&b.key){let m=sw(b.filePath);this.modules.push({type:A,key:b.key,dirPath:m})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=sw($),A=this.modules.filter((m)=>{let n=m.dirPath.endsWith(hA)?m.dirPath:m.dirPath+hA;return(b.endsWith(hA)?b:b+hA).startsWith(n)||b===m.dirPath});if(A.length===0)return;return A.sort((m,n)=>{let W={"app-config":3,example:2,feature:1},w=W[m.type],j=W[n.type];if(w!==j)return j-w;return n.dirPath.length-m.dirPath.length}),A[0]}}async function bj($,b,A){let{fs:m,logger:n}=A,W=[];if(n.info(`Generating docs for ${$.length} files...`),b.outputDir)await m.mkdir(b.outputDir);let w=new Im(A),j=[];for(let B of $)try{let S=await m.readFile(B),Q=YS(S,B);if(Q.length>0)j.push(...Q);else{let Z=HS(S,B);if(Z.specType!=="unknown")j.push(Z)}}catch(S){}w.initialize(j);let y=await Aj($,A);for(let B of y)if(W.push(B.entry.block),n.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await $j(B.entry.block,B.filePath,b.outputDir,w,m);for(let B of $)try{let S=await XS(B);if(!S?.length){n.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=ZS(Q,{rootPath:b.rootPath});if(W.push(Z),n.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await $j(Z,B,b.outputDir,w,m)}}catch(S){n.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)n.info(`Wrote ${W.length} doc files to ${b.outputDir}`);return{blocks:W,count:W.length}}async function rO($,b){return(await Aj($,b)).map(({entry:m})=>m.block)}function fO($,b){return SS(QS({packageName:$,srcRoot:b}))}async function Aj($,b){let A=[...new Set($)].sort((n,W)=>n.localeCompare(W)),m=[];for(let n of A){let W=await b.fs.readFile(n),w=n.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),j=GS(W,n,w);for(let y of j.entries)m.push({entry:y,filePath:n})}return m}async function $j($,b,A,m,n){let W=m.resolve(b),w=W?Em.join(A,W.key):Em.join(A,"_common");await n.mkdir(w);let j=Em.join(w,`${$.id}.md`),y=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
1927
+
1928
+ ${$.body}`;await n.writeFile(j,y)}async function mj($,b,A,m,n={}){let W=n.config,w=await xA($,{cwd:n.specSearchRoot,config:W,pattern:n.specPattern??KS(b,n)});if(w.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let j=VS.join(_S(A,W),"docs"),y=await bj(w.map((S)=>S.filePath),{outputDir:j,format:"markdown",rootPath:m},$),B=0;for(let S of w){let Q=JS(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await $b(S.filePath,$,W??qS,{targets:wm(S.specType,{includeTests:Boolean(n.includeRuntimeTests)}),outputDir:W?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((G)=>G.success).length}return{specsCount:w.length,docsCount:y.count,materializedCount:B}}function JS($){return OS($.specType)}function KS($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${Mm($)}/**/*.ts`:void 0}function _S($,b){let A=(b?.connect?.policy?.generatedPaths??[]).map(zS).filter(Boolean);if(A.length>0)return A[0];if(b?.outputDir&&b.outputDir!=="./src")return Mm(b.outputDir);return $}function US($){return Mm($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function zS($){let b=US($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function Mm($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function cA($,b,A,m={}){let n=await LS(Rb.join(CS(),"contractspec-drift-"));try{await mj($,b,n,m.rootPath,m.generation);let W=[],w=await import("fs/promises");async function j(Z){let G=await w.readdir(Z,{withFileTypes:!0}),X=[];for(let Y of G){let V=Rb.resolve(Z,Y.name);if(Y.isDirectory())X.push(...await j(V));else X.push(V)}return X}let y=async(Z)=>{if(!await w.stat(Z).catch(()=>!1))return[];return(await j(Z)).map((X)=>Rb.relative(Z,X)).sort()},B=await y(n),S=await y(A),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){W.push(Z);continue}if(!B.includes(Z)){W.push(Z);continue}let G=await w.readFile(Rb.join(n,Z)),X=await w.readFile(Rb.join(A,Z));if(!G.equals(X))W.push(Z)}return{hasDrift:W.length>0,files:W}}finally{await RS(n,{recursive:!0,force:!0})}}async function xm($,b){let{fs:A,logger:m}=$,n=[],W=await g(A);if(!W.outputDir)return m.info("No outputDir configured, skipping drift checks"),n;let w="./contracts",j=W.outputDir;if(!await A.exists(j))return m.info("Generated directory does not exist, skipping drift checks"),n;try{let y=await cA($,w,j);if(y.hasDrift)for(let B of y.files)n.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${j}/${B}`,context:{file:B}})}catch(y){m.warn("Drift detection failed",{error:y instanceof Error?y.message:String(y)})}return n}s();function IS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function ES($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function dA($,b,A,m={}){let{fs:n}=b,W=[],w=[],j=$.key??n.basename($.filePath).replace(/\.[jt]s$/,""),y=m.outputDir??A.outputDir??"./src",B=IS(j),S={};if($.specType==="operation")S.handlerPath=n.join(y,"handlers",`${B}.handler.ts`),S.handlerTestPath=n.join(y,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=n.join(y,"components",`${B}.tsx`),S.componentTestPath=n.join(y,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=n.join(y,"forms",`${B}.form.tsx`),S.formTestPath=n.join(y,"forms",`${B}.form.test.tsx`);if(m.checkHandlers&&S.handlerPath)if(!await n.exists(S.handlerPath))W.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await n.readFile(S.handlerPath),G=`${ES(j.split(".").pop()??j)}Spec`,X=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),Y=new RegExp(`typeof\\s+${G}\\b`).test(Z);if(!X)w.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!Y)w.push(`Handler ContractHandler typing does not reference expected spec var (${G}): ${S.handlerPath}`)}if(m.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await n.exists(Z))W.push(`Missing test file: ${Z}`)}return{valid:W.length===0,errors:W,warnings:w,expected:S}}async function Tm($,b){let{fs:A}=$,m=[],n=await g(A);for(let W of b){if(W.specType!=="operation")continue;let w=await dA(W,{fs:A},n,{checkHandlers:!0,outputDir:n.outputDir});for(let j of w.errors)m.push({ruleId:"handler-missing",severity:"warning",message:j,category:"handlers",file:W.filePath});for(let j of w.warnings)m.push({ruleId:"handler-warning",severity:"warning",message:j,category:"handlers",file:W.filePath})}return m}s();import{createHash as FS}from"crypto";import vS from"path";var Cb={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},MS={".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 xS($){let b=$.toLowerCase();for(let[A,m]of Object.entries(MS))if(b.endsWith(A))return m;if(b.includes("/handlers/"))return"handler";if(b.includes("/services/"))return"service";if(b.includes("/components/"))return"component";if(b.includes("/forms/"))return"form";if(b.includes("/hooks/"))return"hook";if(b.includes("/__tests__/"))return"test";return"other"}function nj($,b){let A=[],m=new Set,n=(Z,G,X)=>{let Y=`${Z}:${G}`;if(m.has(Y))return;m.add(Y),A.push({filePath:b,specKey:Z,referenceType:G,lineNumber:X,inferredType:xS(b)})},W=(Z)=>{return $.substring(0,Z).split(`
1929
+ `).length},w,j=new RegExp(Cb.contractHandler);while((w=j.exec($))!==null)if(w[1])n(w[1],"handler",W(w.index));let y=new RegExp(Cb.typeofSpec);while((w=y.exec($))!==null)if(w[1])n(w[1],"typeof",W(w.index));let B=new RegExp(Cb.namedImport);while((w=B.exec($))!==null){let G=w[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(G)for(let X of G)n(X,"import",W(w.index))}let S=new RegExp(Cb.defaultImport);while((w=S.exec($))!==null)if(w[1])n(w[1],"import",W(w.index));let Q=new RegExp(Cb.specAssignment);while((w=Q.exec($))!==null)if(w[1])n(w[1],"unknown",W(w.index));return A}var Wj=["**/*.ts(x)"];async function uA($,b,A={}){let{fs:m}=b,n=A.includePatterns??Wj,W=A.excludePatterns??[...new Set([...x$,...X$])],w=[];for(let j of n){let y=await m.glob({pattern:j,ignore:W});for(let B of y)try{let S=await m.readFile(B),Z=nj(S,B).filter((G)=>G.specKey===$);w.push(...Z)}catch{}}return w}async function ZV($,b={}){let{fs:A}=$,m=b.includePatterns??Wj,n=b.excludePatterns??[...new Set([...x$,...X$])],W=new Map;for(let w of m){let j=await A.glob({pattern:w,ignore:n});for(let y of j)try{let B=await A.readFile(y),S=nj(B,y);for(let Q of S){let Z=W.get(Q.specKey)??[];Z.push(Q),W.set(Q.specKey,Z)}}catch{}}return W}function TS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function wj($,b,A){let m=TS(b),n=[];if($==="operation")n.push({path:`${A}/handlers/${m}.handler.ts`,type:"handler"}),n.push({path:`${A}/handlers/${m}.handler.test.ts`,type:"test"});if($==="presentation")n.push({path:`${A}/components/${m}.tsx`,type:"component"}),n.push({path:`${A}/components/${m}.test.tsx`,type:"test"});if($==="form")n.push({path:`${A}/forms/${m}.form.tsx`,type:"form"}),n.push({path:`${A}/forms/${m}.form.test.tsx`,type:"test"});if($==="event")n.push({path:`${A}/handlers/${m}.handler.ts`,type:"handler"}),n.push({path:`${A}/handlers/${m}.handler.test.ts`,type:"test"});return n}import{Node as t,Project as DS,SyntaxKind as NS}from"ts-morph";function jj($){let b=[],m=new DS({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),n=(y)=>{if(!t.isObjectLiteralExpression(y))return;let B=y.getProperty("implementations");if(B&&t.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&t.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(t.isObjectLiteralExpression(Q)){let Z,G,X,Y=Q.getProperty("path");if(Y&&t.isPropertyAssignment(Y)){let K=Y.getInitializer();if(t.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&t.isPropertyAssignment(V)){let K=V.getInitializer();if(t.isStringLiteral(K))G=K.getLiteralText()}let O=Q.getProperty("description");if(O&&t.isPropertyAssignment(O)){let K=O.getInitializer();if(t.isStringLiteral(K))X=K.getLiteralText()}if(Z&&G)b.push({path:Z,type:G,description:X})}}}},W=m.getDescendantsOfKind(NS.CallExpression);for(let y of W){let B=y.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=y.getArguments();if(S.length>0&&t.isObjectLiteralExpression(S[0]))return n(S[0]),b}}let w=m.getVariableStatements();for(let y of w)if(y.isExported())for(let B of y.getDeclarations()){let S=B.getInitializer();if(S&&t.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return n(S),b}}let j=m.getExportAssignment((y)=>!y.isExportEquals());if(j){let y=j.getExpression();if(t.isObjectLiteralExpression(y))n(y);else if(t.isAsExpression(y)&&t.isObjectLiteralExpression(y.getExpression()))n(y.getExpression())}return b}function yj($){if($.length===0)return"missing";let b=$.filter((n)=>n.exists),A=$.filter((n)=>n.type!=="test");if(b.filter((n)=>n.type!=="test").length===0)return"missing";if($.every((n)=>n.exists))return"implemented";return"partial"}function qV($){let b=$.filter((n)=>n.status==="implemented").length,A=$.filter((n)=>n.status==="partial").length,m=$.filter((n)=>n.status==="missing").length;return{total:$.length,implemented:b,partial:A,missing:m,coverage:$.length>0?Math.round(b/$.length*100):100}}var gS={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Bj($){return FS("sha256").update($).digest("hex")}async function kS($,b,A,m={},n){let W={...gS,...m},w=W.computeHashes?Bj($.sourceBlock||""):void 0,j=$.key??vS.basename($.filePath).replace(/\.[jt]s$/,""),y=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(X,Y,V,O)=>{if(Q.has(X))return;Q.add(X);let K=await B.exists(X),J=void 0,_=void 0;if(K&&W.computeHashes)try{J=await B.readFile(X),_=Bj(J)}catch{}S.push({path:X,type:Y,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:_,description:O})};if(W.includeExplicit&&$.sourceBlock){if(n)n.suffixText="Discover explicit implementations";let X=jj($.sourceBlock);for(let Y of X)await Z(Y.path,Y.type,"explicit",Y.description)}if(W.includeDiscovered){if(n)n.suffixText="Discover implementations";let X=await uA(j,b,W);for(let Y of X){if(Y.filePath===$.filePath)continue;await Z(Y.filePath,Y.inferredType,"discovered")}}if(W.includeConvention){if(n)n.suffixText="Discover implementations based on conventions";let X=W.outputDir??A.outputDir??"./src",Y=wj($.specType,j,X);for(let{path:V,type:O}of Y)await Z(V,O,"convention")}if(n)n.suffixText="Determine implementation status";let G=yj(S);return{specKey:j,specVersion:y,specPath:$.filePath,specType:$.specType,implementations:S,status:G,specHash:w}}async function Sj($,b,A,m={},n){let W=[];for(let w of $){if(n)n.text=`Resolving implementation... (${W.length}/${$.length})`;try{let j=await kS(w,b,A,m,n);W.push(j)}catch(j){console.error(`Failed to resolve implementations for ${w}:`,j)}}return W}async function Dm($,b,A){let{fs:m}=$,n=[],W=await g(m),w=A.implementation??{},j=b.filter((B)=>B.specType==="operation"),y=await Sj(j,{fs:m},W,{computeHashes:w.useCache??!0});for(let B of y){if(w.requireImplemented&&B.status==="missing")n.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")n.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!w.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);n.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)n.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return n}s();import{isFeatureFile as fS,scanAllSpecsFromSource as hS,scanFeatureSource as cS}from"@contractspec/module.workspace";function PS($,b){return`${$}.v${b}`}function Nm($,b,A,m,n,W={}){let{treatMissingAsError:w=!0}=W;if(!m||m.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let j=[],y=[],B=[];for(let S of m){let Q=PS(S.key,S.version);if(n.has(Q))j.push(S);else if(y.push(S),w)B.push(`Spec ${b}.v${A} references test ${S.key}.v${S.version} which does not exist`)}return{valid:y.length===0,foundTests:j,missingTests:y,errors:B,specFile:$}}function Qj($,b){return`${$}.v${b}`}function Zj($,b){let A=new Map,m=new Map,n=[],W=[];for(let w of $){if(!w.key||!w.version)continue;let j=Qj(w.key,w.version);if(!w.testTarget){W.push(j);continue}let{type:y,key:B,version:S}=w.testTarget,Q=S??w.version,Z=Qj(B,Q),G=rS(b,y);if(!G||!G.has(Z)){n.push(j);continue}if(m.set(j,Z),!A.has(Z))A.set(Z,new Set);A.get(Z)?.add(j)}return{targetToTests:A,testToTarget:m,orphanedTests:n,testsWithoutTarget:W}}function rS($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function b$($,b){return`${$}.v${b}`}function dS(){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 Fm($,b){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}[b]}async function oA($,b={}){let{fs:A,logger:m}=$;m.info("Starting integrity analysis...",{options:b});let n=await g$(A,{config:b.config,cwd:b.cwd,pattern:b.pattern}),W=dS(),w=[],j=[];for(let H of n){if((await A.stat(H)).isDirectory)continue;let U=await A.readFile(H);if(fS(H)){let z=cS(U,H);w.push(z)}else{let z=hS(U,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let I=Fm(W,L.specType);if(I&&L.key&&L.version!==void 0){let C=b$(L.key,L.version);I.set(C,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let y=b.featureKey?w.filter((H)=>H.key===b.featureKey):w,B=new Set;for(let H of y){for(let q of H.operations){let U=b$(q.key,q.version);if(B.add(`operation:${U}`),!W.operations.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let U=b$(q.key,q.version);if(B.add(`event:${U}`),!W.events.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let U=b$(q.key,q.version);if(B.add(`presentation:${U}`),!W.presentations.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let U=b$(q.key,q.version);if(B.add(`experiment:${U}`),!W.experiments.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let U=b$(q.key,q.version);if(B.add(`capability:${U}`),!W.capabilities.has(U))j.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let U=b$(q.key,q.version);B.add(`capability:${U}`)}for(let q of H.opToPresentationLinks){let U=b$(q.op.key,q.op.version),z=b$(q.pres.key,q.pres.version);if(!W.operations.has(U))j.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!W.presentations.has(z))j.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let U=b$(q.key,q.version);if(!W.presentations.has(U))j.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=Fm(W,H);if(!q)continue;for(let[U,z]of q)if(!B.has(`${H}:${U}`))S.push(z),j.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of W.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let G=Zj(Z,W);for(let H of y)for(let q of H.opToPresentationLinks){let U=b$(q.op.key,q.op.version),z=G.targetToTests.get(U),L=!1,I=!1;if(z)for(let C of z){let F=W.testSpecs.get(C);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)I=!0}}if(!z||!L||!I){let C=[];if(!L)C.push("success scenario");if(!I)C.push("error scenario");j.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${C.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let X={},Y=0;for(let H of Q){let q=Fm(W,H);if(!q)continue;let U=q.size,z=0,L=0,I=b.requireTestsFor?.includes(H);for(let[C,F]of q){if(B.has(`${H}:${C}`))z++;if(I){let x=b$(F.key,F.version),h=G.targetToTests.has(x),nA=`${F.key}.test`,r1=W.testSpecs.has(b$(nA,F.version));if(!h&&!r1)L++,Y++,j.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}X[H]={total:U,covered:z,orphaned:U-z,missingTest:I?L:0}}let V=Object.values(X).reduce((H,q)=>H+q.total,0),O=Object.values(X).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:Y,byType:X},_=!j.some((H)=>H.severity==="error");return m.info("Integrity analysis complete",{features:w.length,totalSpecs:V,orphaned:S.length,issues:j.length,healthy:_}),{inventory:W,features:y,coverage:K,issues:j,orphanedSpecs:S,healthy:_}}function kV($){let b=[];for(let A of Object.values($))for(let m of A.values())b.push(m);return b}function PV($,b){return $.filter((A)=>A.type===b)}function rV($,b){return $.filter((A)=>A.severity===b)}async function vm($,b){let A=[],m=await g($.fs),n=await oA($,{config:m,pattern:b.pattern,all:!0});for(let W of n.issues)A.push({ruleId:`integrity-${W.type}`,severity:W.severity==="error"?"error":"warning",message:W.message,category:"integrity",file:W.file,context:{specKey:W.specKey,specType:W.specType,featureKey:W.featureKey,ref:W.ref}});return A}async function gm($,b){let A=[],m=await PA($,{});for(let[n,W]of m.inventory.features){if(!W.key)A.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:W.filePath,context:{key:n}});if(!W.owners?.length)A.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${n}' missing 'owners' field`,category:"layers",file:W.filePath,context:{key:n}});if(W.operations.length===0&&W.events.length===0&&W.presentations.length===0)A.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${n}' has no operations, events, or presentations`,category:"layers",file:W.filePath,context:{key:n}})}for(let[n,W]of m.inventory.examples){if(!W.entrypoints.packageName)A.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${n}' missing 'packageName' in entrypoints`,category:"layers",file:W.filePath,context:{key:n}});if(!W.surfaces.templates&&!W.surfaces.sandbox.enabled&&!W.surfaces.studio.enabled&&!W.surfaces.mcp.enabled)A.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${n}' has no enabled surfaces`,category:"layers",file:W.filePath,context:{key:n}})}for(let n of m.inventory.workspaceConfigs.values())if(!n.valid)for(let W of n.errors)A.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${W}`,category:"layers",file:n.file});return A}s();import{ContractsrcSchema as oS,DEFAULT_CONTRACTSRC as iA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as uS}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:A,scan:m=uS}=$,n=await g$(A,b),W=[],w=Array.isArray(b.type)?b.type:[b.type];for(let j of n){if(Ob(j,b.config))continue;if(Vb(j))continue;try{let y=await A.readFile(j),B=m(y,j);if(B.specType==="unknown")continue;if(b.type&&!w.includes(B.specType))continue;W.push(B)}catch{}}return W}function pV($){let b=new Map;for(let A of $){let m=b.get(A.specType)??[];m.push(A),b.set(A.specType,m)}return b}var iS=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,lS=/@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?)?['"]/,tS=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,pS=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,aS=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,eS=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,sS=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function lA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function $Q($,b){let A=$.replaceAll("\\","/"),m=new Set(["contracts","features",...lA(b?.conventions?.operations),...lA(b?.conventions?.events),...lA(b?.conventions?.presentations),...lA(b?.conventions?.forms)]);return A.split("/").some((n)=>m.has(n))}function bQ($,b,A){let m=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(m))return!1;if(m.includes("/node_modules/")||m.includes("/dist/")||aS.test(m)||pS.test(m)||m.endsWith(".d.ts")||m.endsWith(".test.ts")||m.endsWith(".spec.ts"))return!1;if(b.has(m))return!1;if($Q(m,A))return!1;return iS.test(m)}function Gj($){return $.replaceAll("\\","/").match(eS)?.[1]??null}function AQ($){let b=$.split(`
1930
+ `).map((A)=>A.trim()).filter((A)=>A.length>0&&!A.startsWith("//")&&!A.startsWith("/*")&&!A.startsWith("*")&&!A.startsWith("*/"));return b.length>0&&b.every((A)=>A.startsWith("import ")||A.startsWith("export *")||A.startsWith("export {")||A.startsWith("export type {")||A==="'use client';"||A==='"use client";'||A==="'use server';"||A==='"use server";')}function mQ($){if(!$)return iA;let b=oS.safeParse($),A=b.success?b.data:{};return{...iA,...A,conventions:{...iA.conventions,...A.conventions??{}},ci:{...iA.ci,...A.ci??{}}}}async function km($,b){let{fs:A,logger:m}=$,n=[],W=b.config?mQ(b.config):await g(A),w=await j$({fs:A},{config:W}),j=new Set(w.map((S)=>S.filePath.replaceAll("\\","/"))),y=new Set(w.map((S)=>Gj(S.filePath)).filter((S)=>Boolean(S))),B=await A.glob({pattern:"**/*.{ts,tsx}"});for(let S of B){if(!bQ(S,j,W))continue;try{let Q=await A.readFile(S);if(AQ(Q))continue;let Z=Gj(S);if(!(Z!==null&&sS.test(Z)&&y.has(Z))&&!tS.test(Q))continue;if(lS.test(Q))continue;n.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:S})}catch(Q){m.warn("Policy scan failed for file",{file:S,error:Q instanceof Error?Q.message:String(Q)})}}return n}import{validateSpecStructure as nQ}from"@contractspec/module.workspace";async function Pm($){let b=[];for(let A of $){let m=nQ(A);for(let n of m.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:n,category:"structure",file:A.filePath});for(let n of m.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:n,category:"structure",file:A.filePath})}return b}async function rm($){let b=[],A=new Map,m=new Map;for(let n of $){if(!n.key||!n.version)continue;if(n.specType==="test-spec"){let W=`${n.key}.v${n.version}`;A.set(W,{key:n.key,version:n.version,file:n.filePath,type:"test-spec"})}if(n.testRefs&&n.testRefs.length>0){if(!m.has(n.filePath))m.set(n.filePath,[]);m.get(n.filePath)?.push({key:n.key,version:n.version,testRefs:n.testRefs})}}for(let[n,W]of m)for(let w of W){if(!w.testRefs)continue;let j=Nm(n,w.key,w.version,w.testRefs,A,{treatMissingAsError:!0});for(let y of j.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:y,category:"test-refs",file:n,context:{specKey:w.key,specVersion:w.version,missingTests:j.missingTests}})}return b}s();async function fm($,b){let{fs:A}=$,m=[],n=await g(A);for(let W of b){if(W.specType!=="operation")continue;let w=await dA(W,{fs:A},n,{checkTests:!0,outputDir:n.outputDir});for(let j of w.errors)m.push({ruleId:"test-missing",severity:"warning",message:j,category:"tests",file:W.filePath});for(let j of w.warnings)m.push({ruleId:"test-warning",severity:"warning",message:j,category:"tests",file:W.filePath})}return m}function a($,b,A){let m={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"},n=b.filter((j)=>j.severity==="error").length,W=b.filter((j)=>j.severity==="warning").length,w=b.filter((j)=>j.severity==="note").length;return{category:$,label:m[$],errors:n,warnings:W,notes:w,passed:n===0,durationMs:A}}async function Xj($){try{if(!await $.exists(".git/HEAD"))return{};let A=await $.readFile(".git/HEAD"),m=A.match(/^ref: (.+)$/m);if(m){let W=m[1]?.replace("refs/heads/",""),w=`.git/${m[1]}`;if(await $.exists(w))return{commitSha:(await $.readFile(w)).trim(),branch:W};return{branch:W}}return{commitSha:A.trim()}}catch{return{}}}function Yj($){let b=$.config?.ci?.checks,A=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)A.push("handlers");if($.checkTests)A.push("tests");if($.implementation)A.push("implementation");if($.checkDrift)A.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return A.filter((m)=>!$.skip?.includes(m));return A}async function IJ($,b={}){let A=Date.now(),{fs:m,logger:n}=$,W=[],w=[],j=Yj(b);n.info("Starting CI checks...",{checks:j});let y=await g(m),B=await xA($,{config:y,pattern:b.pattern});if(j.includes("structure")){let V=Date.now(),O=await Pm(B);W.push(...O),w.push(a("structure",O,Date.now()-V))}if(j.includes("integrity")){let V=Date.now(),O=await vm($,b);W.push(...O),w.push(a("integrity",O,Date.now()-V))}if(j.includes("deps")){let V=Date.now(),O=await Xm($,b);W.push(...O),w.push(a("deps",O,Date.now()-V))}if(j.includes("doctor")){let V=Date.now(),O=await Cm($,b);W.push(...O),w.push(a("doctor",O,Date.now()-V))}if(j.includes("docs")){let V=Date.now(),O=await Ym($,b);W.push(...O),w.push(a("docs",O,Date.now()-V))}if(j.includes("policy")){let V=Date.now(),O=await km($,b);W.push(...O),w.push(a("policy",O,Date.now()-V))}if(j.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await Tm($,B);W.push(...O),w.push(a("handlers",O,Date.now()-V))}if(j.includes("tests")||b.checkTests){let V=Date.now(),O=await fm($,B);W.push(...O),w.push(a("tests",O,Date.now()-V))}if(j.includes("test-refs")){let V=Date.now(),O=await rm(B);W.push(...O),w.push(a("test-refs",O,Date.now()-V))}if(j.includes("coverage")){let V=Date.now(),O=await Gm($,B,b);W.push(...O),w.push(a("coverage",O,Date.now()-V))}if(j.includes("implementation")){let V=Date.now(),O=await Dm($,B,b);W.push(...O),w.push(a("implementation",O,Date.now()-V))}if(j.includes("layers")){let V=Date.now(),O=await gm($,b);W.push(...O),w.push(a("layers",O,Date.now()-V))}if(j.includes("drift")){let V=Date.now(),O=await xm($,b);W.push(...O),w.push(a("drift",O,Date.now()-V))}let S=W.filter((V)=>V.severity==="error").length,Q=W.filter((V)=>V.severity==="warning").length,Z=W.filter((V)=>V.severity==="note").length,G=b.failOnWarnings?S===0&&Q===0:S===0,X=await Xj(m),Y={success:G,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:W,categories:w,durationMs:Date.now()-A,timestamp:new Date().toISOString(),...X};return n.info("CI checks complete",{success:G,errors:S,warnings:Q,durationMs:Y.durationMs}),Y}var MJ=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],xJ={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 vJ($,b={}){let{fs:A,logger:m}=$,n=(b.outputDir??"./src").replace(/\\/g,"/"),W=["generated/**","dist/**",".turbo/**"],w=[`${n}/handlers/**/*.handler.ts`,`${n}/handlers/**/*.handler.test.ts`,`${n}/components/**/*.tsx`,`${n}/components/**/*.test.tsx`,`${n}/forms/**/*.form.tsx`,`${n}/forms/**/*.form.test.tsx`,`${n}/**/*.runner.ts`,`${n}/**/*.renderer.tsx`],j=b.generatedOnly?[...W,...w]:[...W,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...w],y=await A.glob({patterns:j,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of y)try{let Z=await A.stat(Q),G=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&G<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)m.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await A.remove(Q),m.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}s();var cj={};P(cj,{writeReviewPacket:()=>An,writeDecisionEnvelope:()=>Fb,withBranch:()=>f$,verifyConnectMutation:()=>Q4,resolveWorkspace:()=>o,resolveStoragePaths:()=>Q$,replayConnectDecision:()=>cQ,persistLatestArtifacts:()=>$n,persistDecisionArtifacts:()=>Nb,normalizeEvalInput:()=>NQ,matchConfiguredPath:()=>Ib,loadStoredDecision:()=>vb,listStoredReviewPackets:()=>mn,listConnectReviewPackets:()=>dQ,isReviewCommand:()=>hm,isDeniedCommand:()=>cm,isAllowedCommand:()=>tA,initConnectWorkspace:()=>PQ,inferSurfaces:()=>xb,evaluateConnectDecision:()=>TQ,ensureStorage:()=>Db,defaultActor:()=>Mb,decisionArtifactRefs:()=>nb,createConnectControlPlaneRuntime:()=>$4,connectVerdictToPolicy:()=>z$,configuredThreshold:()=>r$,compileConnectPlanPacket:()=>gb,buildConnectContextPack:()=>Tb,assessConnectPolicy:()=>Eb,assertConnectEnabled:()=>A$,artifactRef:()=>J$,appendAuditRecord:()=>bn,analyzeConnectImpact:()=>h$,CONTROL_PLANE_TRACE_GET_REF:()=>pA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>aA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>im,CONTROL_PLANE_PLAN_COMPILE_REF:()=>om,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>um,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>O$,AGENT_APPROVALS_REF:()=>eA,ACP_TERMINAL_EXEC_REF:()=>yQ,ACP_FS_ACCESS_REF:()=>jQ});import WQ from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function Ib($,b,A){if(!A||A.length===0)return!1;let m=b.replaceAll("\\","/");return WQ.isMatch(m,A,{contains:!0})}function r$($,b,A){return $.config.connect?.policy?.reviewThresholds?.[b]??A}function tA($,b){return dm($.config.connect?.commands?.allow,b)}function hm($,b){return dm($.config.connect?.commands?.review,b)}function cm($,b){return dm($.config.connect?.commands?.deny,b)}function dm($,b){if(!$||$.length===0)return!1;return $.some((A)=>b===A||b.startsWith(`${A} `))}function qj($,b){if(b.length===0)return{state:"none"};for(let m of b)if(cm($,m))return{commandMatch:m,state:"deny"};for(let m of b)if(hm($,m))return{commandMatch:m,state:"review"};if(b.every((m)=>tA($,m)))return{state:"allow"};let A=b.find(wQ);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((m)=>!tA($,m)),state:"unknown"}}function wQ($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return Hj(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return Hj(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function Hj($,b){return b.every((A)=>$.includes(A)||$.includes(A.replace("-","")))}var um={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},om={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},im={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},pA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},aA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},O$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},jQ={key:"acp.fs.access",version:"1.0.0",kind:"command"},yQ={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},eA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Eb($,b){let A=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.immutablePaths)),m=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.protectedPaths)),n=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:W,state:w}=qj($,b.commands??[]),j=b.impactAnalysis.unknownPaths.length>0,y=b.impactAnalysis.driftFiles.length>0,B=BQ({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:w==="destructive",commandState:w,contractDrift:y,generatedPath:Boolean(n),immutable:Boolean(A),protectedPath:Boolean(m),smokeFailed:b.smokeFailed===!0,unknownImpact:j,workspace:$}),S=SQ({breakingChange:b.impactAnalysis.breakingChange,commandMatch:W,commandState:w,contractDrift:y,protectedPath:m,unknownPaths:b.impactAnalysis.unknownPaths}),Q=z$(B);return{commandMatch:W,commandState:w,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:n,immutablePath:A,protectedPath:m,requiredApprovals:Q.requiresApproval?[{capability:O$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function z$($){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 BQ($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(r$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(r$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(r$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(r$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(r$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(QQ)[0]??"permit"}function SQ($){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 QQ($,b){return Oj($)-Oj(b)}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as MQ}from"crypto";var Uj={};P(Uj,{formatPrComment:()=>Vj,formatMinimalComment:()=>lm,formatJson:()=>Kj,formatCheckRun:()=>Jj,detectImpact:()=>V$,ImpactDetectionOverviewDocBlock:()=>qQ});function Vj($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)A.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else A.push("\u2705 **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| \u2796 Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let m=$.deltas.filter((W)=>W.severity==="breaking"),n=$.deltas.filter((W)=>W.severity==="non_breaking");if(m.length>0){A.push("#### \uD83D\uDD34 Breaking Changes"),A.push("");for(let W of m)A.push(`- **${W.specKey}**: ${W.description}`);A.push("")}if(n.length>0){A.push("#### \uD83D\uDFE1 Non-breaking Changes"),A.push("");for(let W of n)A.push(`- **${W.specKey}**: ${W.description}`);A.push("")}}if($.addedSpecs.length>0){A.push("### Added Specs"),A.push("");for(let m of $.addedSpecs)A.push(`- \`${m.key}\` v${m.version} (${m.type})`);A.push("")}if($.removedSpecs.length>0){A.push("### Removed Specs"),A.push("");for(let m of $.removedSpecs)A.push(`- \`${m.key}\` v${m.version} (${m.type})`);A.push("")}if(b.drift)if(b.drift.hasDrift){A.push("### \u26A0\uFE0F Drift Detected"),A.push(""),A.push("The following generated files are out of sync with their specs:"),A.push("");for(let m of b.drift.files)A.push(`- \`${m}\``);A.push(""),A.push("Run `contractspec generate` to regenerate artifacts."),A.push("")}else A.push("### \u2705 No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
1931
+ `)}function lm($){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 Jj($,b,A={}){let m=A.key??"ContractSpec Impact",n=A.failOnBreaking??!0,W,w;if($.hasBreaking)W=n?"failure":"neutral",w=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)W="success",w=`Non-breaking changes (${$.summary.nonBreaking})`;else W="success",w="No contract impact";let j=lm($);return{name:m,headSha:b,conclusion:W,title:w,summary:j,annotations:$.deltas.filter((y)=>y.severity==="breaking").slice(0,50).map((y)=>({path:y.path,startLine:1,endLine:1,annotationLevel:"failure",message:y.description,title:`Breaking: ${y.rule}`}))}}function Kj($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((A)=>({type:A.rule,path:A.specKey,summary:A.description,severity:A.severity==="breaking"?"breaking":A.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as ZQ,computeIoDiff as GQ,generateSnapshot as _j}from"@contractspec/module.workspace";async function V$($,b={}){let{fs:A,git:m,logger:n}=$,W=b.workspaceRoot??process.cwd();n.info("Starting impact detection...",{baseline:b.baseline});let j=(await A.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:W})).filter((G)=>!G.includes(".test.")&&!G.includes(".spec.")&&!G.includes("node_modules"));n.debug(`Found ${j.length} spec files`);let y=await XQ(A,j,W),B=_j(y),S;if(b.baseline){let G=await YQ(A,m,j,b.baseline,W);S=_j(G)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=HQ(S.specs,B.specs),Z=ZQ(S.specs,B.specs,Q);return n.info("Impact detection complete",{status:Z.status,breaking:Z.summary.breaking,nonBreaking:Z.summary.nonBreaking}),{...Z,workspaceRoot:W,specsAnalyzed:j.length,baseRef:b.baseline}}async function XQ($,b,A){let m=[];for(let n of b){let W=await $.readFile(n);m.push({path:n,content:W})}return m}async function YQ($,b,A,m,n){let W=[];for(let w of A)try{let j=await b.showFile(m,w);W.push({path:w,content:j})}catch{}return W}function HQ($,b){let A=[],m=new Map($.map((W)=>[`${W.key}@${W.version}`,W])),n=new Map(b.map((W)=>[`${W.key}@${W.version}`,W]));for(let[W,w]of n){let j=m.get(W);if(j&&w.type==="operation"&&j.type==="operation"){let y=GQ(j.io,w.io);A.push(...y)}}return A}var qQ={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
1613
1932
  # Contract Impact Detection
1614
1933
 
1615
1934
  Automated detection and classification of breaking changes in ContractSpec APIs.
@@ -1655,49 +1974,49 @@ The system consists of three layers:
1655
1974
  1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
1656
1975
  2. **Impact Service** (bundle package): Orchestration + Formatters
1657
1976
  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}
1977
+ `,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as Lj,readFileSync as Rj}from"fs";import{basename as OQ,join as tm,resolve as VQ}from"path";import{ContractsrcSchema as JQ,DEFAULT_CONTRACTSRC as KQ}from"@contractspec/lib.contracts-spec/workspace-config";function o($={}){let b=VQ($.cwd??process.cwd()),A=$.workspaceRoot??M(b),m=$.packageRoot??r(b),n=$.config??_Q(A,m),W=UQ(m,A);return{cwd:b,workspaceRoot:A,packageRoot:m,config:n,repoId:W,branch:"unknown"}}function f$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function Mb($,b){return b??{id:`cli:${$}`,type:"human"}}function xb($){let b=new Set;for(let A of $){if(A.includes("/cli-")||A.includes("/apps/cli-"))b.add("cli");if(A.includes("/contracts-spec/")||A.includes("/specs/"))b.add("contract");if(A.includes("/components/")||A.includes("/ui/")||A.endsWith(".tsx")||A.endsWith(".jsx"))b.add("ui");if(A.includes("/integrations/")||A.includes("/provider"))b.add("integration");if(A.includes("/libs/")||A.includes("/shared/")||A.includes("/utils/"))b.add("library");if(A.includes("/modules/")||A.includes("/bundles/")||A.includes("/examples/"))b.add("solution");if(A.includes("/runtime/"))b.add("runtime");if(A.includes("/harness"))b.add("harness");if(A.includes("/ai-agent/"))b.add("agent");if(A.includes("/knowledge/"))b.add("knowledge");if(A.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function _Q($,b){let A={...KQ};if($!==b)A=zj(A,tm($,".contractsrc.json"));return zj(A,tm(b,".contractsrc.json"))}function zj($,b){if(!Lj(b))return $;try{let A=Rj(b,"utf-8"),m=JSON.parse(A),n=JQ.safeParse(m);if(!n.success)return $;return{...$,...n.data}}catch{return $}}function UQ($,b){let A=tm($,"package.json");if(Lj(A))try{let m=JSON.parse(Rj(A,"utf-8"));if(m.name)return m.name}catch{}return OQ(b)}async function h$($,b){let A=await j$({fs:$.fs},{config:b.workspace.config}),m=new Map(A.filter((y)=>typeof y.key==="string").map((y)=>[y.key,y])),n=b.touchedPaths.map((y)=>zQ($.fs,b.workspace,y,A,m)),W=b.baseline!=null?await V$({...$,logger:$.logger??Ij},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,w=await LQ($,b.workspace,b.touchedPaths),j=sm([...n.flatMap((y)=>y.contracts),...(W?.deltas??[]).map((y)=>({key:y.specKey,version:y.specVersion,kind:y.specType==="event"?"event":"command"}))]);return{breakingChange:W?.hasBreaking===!0,driftFiles:w,impactResult:W,impactedContracts:j,pathImpacts:n,unknownPaths:n.filter((y)=>y.contracts.length===0).map((y)=>y.path)}}function zQ($,b,A,m,n){let W=$.resolve(b.workspaceRoot,A),w=em(A),j=m.map((X)=>{let Y=m$($.relative(b.workspaceRoot,X.filePath));return{score:IQ(A,w,Y,X.key),spec:X}}).filter((X)=>X.score>=45).sort((X,Y)=>Y.score-X.score).slice(0,3),y=m.find((X)=>X.filePath===W),B=y?[{score:100,spec:y}]:j,S=B.filter((X)=>typeof X.spec.key==="string").map((X)=>am(X.spec.key,X.spec.version,X.spec.kind)),Q=B.flatMap((X)=>[...X.spec.emittedEvents??[],...X.spec.policyRefs??[],...X.spec.testRefs??[]].map((Y)=>n.get(Y.key)).filter(Boolean).map((Y)=>am(Y.key,Y.version,Y.kind))),Z=sm([...S,...Q]),G=sm([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((X)=>X.spec.policyRefs??[]).map((X)=>am(X.key,X.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:A,policies:G,reasons:B.map((X)=>`${X.spec.key??X.spec.filePath} matched with score ${X.score}`),surfaces:xb([A])}}async function LQ($,b,A){let m=RQ($.fs,b,A),n=await Promise.all(m.map(async(W)=>{let w=$.fs.resolve(b.packageRoot,W.comparisonRoot),j=await cA({...$,logger:$.logger??Ij},b.workspaceRoot,w,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),y=W.filterPrefix&&W.filterPrefix!==W.comparisonRoot?m$($.fs.relative(W.comparisonRoot,W.filterPrefix)):void 0;return j.files.filter((B)=>y?m$(B)===y||m$(B).startsWith(`${y}/`):!0).map((B)=>m$($.fs.join(W.comparisonRoot,B)))}));return[...new Set(n.flat())].sort()}function RQ($,b,A){let m=(b.config.connect?.policy?.generatedPaths??[]).map(EQ).filter(Boolean),n=b.config.outputDir&&b.config.outputDir!=="./src"?m$(b.config.outputDir):void 0,W=new Map;for(let w of A){let j=m$(w);if(n&&j.startsWith(n))W.set(n,{comparisonRoot:n});for(let y of m)if(j.startsWith(y)){let B=CQ($,n,y);W.set(`${B}::${y}`,{comparisonRoot:B,filterPrefix:y})}}return[...W.values()]}function CQ($,b,A){if(b&&A.startsWith(b))return b;return $.basename(A)==="docs"?m$($.dirname(A)):A}function IQ($,b,A,m){if(m$($)===m$(A))return 100;let n=em(A),W=em(m??""),w=Cj($)===Cj(A)?40:0,j=pm($.split("/"),A.split("/"),5),y=pm(b,n,5),B=pm(b,W,4);return w+j+y+B}function pm($,b,A){let m=new Set(b);return $.filter((n)=>m.has(n)).length*A}function em($){return m$($).split(/[\/._-]+/).filter(Boolean)}function Cj($){return m$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function EQ($){return m$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function m$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function am($,b,A){return{key:$,version:String(b??"1.0.0"),kind:A==="query"||A==="event"||A==="policy"||A==="capability"?A:"command"}}function sm($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var Ij={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function Tb($,b){let A=o(b);A$(A),A=f$(A,await $.git.currentBranch());let m=Mb(b.taskId,b.actor),n=await xQ($,A.workspaceRoot,b),W=await h$($,{baseline:b.baseline,touchedPaths:n,workspace:A}),w=A.config.connect?.canonPacks??[];return{id:`connect.ctx_${MQ()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:m,knowledge:w.map((j)=>({spaceKey:j.ref,category:"canonical",trustLevel:j.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:W.impactedContracts,affectedSurfaces:W.pathImpacts.length>0?[...new Set(W.pathImpacts.flatMap((j)=>j.surfaces))].sort():xb(n),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...w.map((j)=>({key:j.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...w.map((j)=>({kind:"canon-pack",ref:j.ref}))],acceptanceChecks:A.config.connect?.policy?.smokeChecks??[]}}async function xQ($,b,A){let m=A.paths??[];if(m.length>0)return m.map((W)=>Ej($.fs,b,W));if(!A.baseline)return[];return(await $.git.diffFiles(A.baseline)).map((W)=>Ej($.fs,b,W))}function Ej($,b,A){let m=$.resolve(b,A);return $.relative(b,m).replaceAll("\\","/")}import{resolve as c$}from"path";function Q$($){let b=$.config.connect?.storage,A=c$($.packageRoot,b?.root??".contractspec/connect");return{root:A,contextPack:c$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:c$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:c$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:c$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:c$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:c$(A,"decisions")}}async function Db($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function $n($,b,A){if(A.contextPack)await S$($,b.contextPack,A.contextPack);if(A.planPacket)await S$($,b.planPacket,A.planPacket);if(A.patchVerdict)await S$($,b.patchVerdict,A.patchVerdict)}async function Nb($,b,A,m){let n=$.join(b.decisionsDir,A);if(await $.mkdir(n),m.contextPack)await S$($,$.join(n,"context-pack.json"),m.contextPack);if(m.planPacket)await S$($,$.join(n,"plan-packet.json"),m.planPacket);if(m.patchVerdict)await S$($,$.join(n,"patch-verdict.json"),m.patchVerdict);if(m.reviewPacket)await S$($,$.join(n,"review-packet.json"),m.reviewPacket);if(m.evaluationResult!==void 0)await S$($,$.join(n,"evaluation-result.json"),m.evaluationResult);if(m.replayBundle!==void 0)await S$($,$.join(n,"replay-bundle.json"),m.replayBundle);return n}async function Fb($,b,A,m){let n=$.join(b.decisionsDir,A,"decision-envelope.json");return await S$($,n,m),n}async function bn($,b,A){let m=await Mj($,b.auditFile)??"",n=`${JSON.stringify(A)}
1978
+ `;await $.writeFile(b.auditFile,`${m}${n}`)}async function An($,b,A){let m=$.join(b.reviewPacketsDir,`${A.id}.json`);return await S$($,m,A),m}async function vb($,b,A){let m=$.join(b.decisionsDir,A);return{historyDir:m,contextPack:await mb($,$.join(m,"context-pack.json")),planPacket:await mb($,$.join(m,"plan-packet.json")),patchVerdict:await mb($,$.join(m,"patch-verdict.json")),reviewPacket:await mb($,$.join(m,"review-packet.json")),envelope:await mb($,$.join(m,"decision-envelope.json"))}}async function mn($,b){let A=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),m=[];for(let n of A){let W=await mb($,n);if(W)m.push({filePath:n,packet:W})}return m.sort((n,W)=>n.packet.id.localeCompare(W.packet.id))}function J$($,b,A){return $.relative(b.packageRoot,$.resolve(A)).replaceAll("\\","/")}function nb($,b,A,m,n){let W=$.join(A.decisionsDir,m);return{contextPack:J$($,b,$.join(W,"context-pack.json")),planPacket:J$($,b,$.join(W,"plan-packet.json")),patchVerdict:J$($,b,$.join(W,"patch-verdict.json")),reviewPacket:n.reviewPacket?J$($,b,$.join(W,"review-packet.json")):void 0,evaluationResult:n.evaluationResult?J$($,b,$.join(W,"evaluation-result.json")):void 0,replayBundle:n.replayBundle?J$($,b,$.join(W,"replay-bundle.json")):void 0}}async function S$($,b,A){await $.writeFile(b,`${JSON.stringify(A,null,2)}
1979
+ `)}async function mb($,b){let A=await Mj($,b);if(!A)return;try{return JSON.parse(A)}catch{return}}async function Mj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function TQ($,b,A){let m=o(b);if(A$(m),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let n=Q$(m),W=await vb($.fs,n,b.decisionId),w=DQ(m,W),j=b.scenarioKey?await A.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:w}):await A.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:w}),y=await Nb($.fs,n,b.decisionId,{evaluationResult:j}),B=await $.fs.exists($.fs.join(y,"replay-bundle.json")),S={artifacts:nb($.fs,m,n,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(W.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:W.envelope?.createdAt??new Date().toISOString(),runtimeLink:W.envelope?.runtimeLink,taskId:W.contextPack?.taskId??b.decisionId,verdict:W.patchVerdict?.verdict??"permit"};return await Fb($.fs,n,b.decisionId,S),{historyDir:y,evaluation:j,context:w}}function DQ($,b){return{traceId:b.envelope?.runtimeLink?.traceId??b.patchVerdict?.controlPlane.traceId??b.contextPack?.actor.traceId,actorId:b.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:b.envelope?.runtimeLink?.decisionId,controlPlanePlanId:b.envelope?.runtimeLink?.planId??b.planPacket?.id,metadata:{approvalStatus:b.envelope?.runtimeLink?.approvalStatus,decisionId:b.patchVerdict?.decisionId,taskId:b.contextPack?.taskId,branch:b.contextPack?.branch??$.branch}}}function NQ($){return $}import{DEFAULT_CONTRACTSRC as kQ}from"@contractspec/lib.contracts-spec/workspace-config";async function sA($,b){let A=$.join(b.root,".gitignore"),m=b.behavior??"auto",n=Dj(b.patterns);if(n.length===0||m==="skip")return{target:"gitignore",filePath:A,action:"skipped",message:m==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(m==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${A}?`,!0))return{target:"gitignore",filePath:A,action:"skipped",message:"User skipped ContractSpec gitignore update"};let W=await $.exists(A),w=W?await $.readFile(A):"",j=FQ(w,n);if(Tj(w)===Tj(j))return{target:"gitignore",filePath:A,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(A,j),{target:"gitignore",filePath:A,action:W?"merged":"created",message:W?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(W){return{target:"gitignore",filePath:A,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}function FQ($,b){let A=vQ(b),m=gQ(),n=$.replace(/\r\n/g,`
1980
+ `);if(m.test(n))return n.replace(m,A);if(n.trim().length===0)return A;return`${n.endsWith(`
1981
+ `)?n:`${n}
1663
1982
  `}
1664
- ${j}`}function dX($){return`# contractspec:init:gitignore:start
1983
+ ${A}`}function vQ($){return`# contractspec:init:gitignore:start
1665
1984
  # Managed by \`contractspec init\` and \`contractspec connect init\`.
1666
- ${L4($).join(`
1985
+ ${Dj($).join(`
1667
1986
  `)}
1668
1987
  # 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=`/**
1988
+ `}function gQ(){return new RegExp(`${xj("# contractspec:init:gitignore:start")}[\\s\\S]*?${xj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tj($){return $.replace(/\r\n/g,`
1989
+ `).trimEnd()}function Dj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function PQ($,b={}){let A=o(b),m=b.scope==="package"?A.packageRoot:A.workspaceRoot,n=$.join(m,".contractsrc.json"),W={connect:{...kQ.connect,enabled:!0}},w="created";if(await $.exists(n)){let B=p(await $.readFile(n)),S=$$(B??{},W);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(n,N(S)),w="merged"}else await $.writeFile(n,N(W));let j=Q$(o({...b,workspaceRoot:m,packageRoot:m}));await Db($,j);let y=await sA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ub.connect,Ub.verificationCache],prompts:b.prompts,root:A.workspaceRoot});return{configPath:n,targetRoot:m,action:w,gitignore:y}}import{randomUUID as $0}from"crypto";async function gb($,b){let A=o(b);A$(A),A=f$(A,await $.git.currentBranch());let{commands:m,touchedPaths:n}=rQ(b.candidate),W=await Tb($,{...b,paths:n}),w=Mb(b.taskId,b.actor),j=fQ(b.candidate.steps,b.candidate),y=await h$($,{baseline:b.baseline,touchedPaths:n,workspace:A}),B=Eb(A,{commands:m,impactAnalysis:y,touchedPaths:n}),S={id:`connect.plan_${$0()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:w,objective:b.candidate.objective,steps:j,impactedContracts:W.impactedContracts,affectedSurfaces:W.affectedSurfaces,requiredChecks:A.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:hQ(n.length,m.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:um,planCompile:om,planVerify:im,traceId:w.traceId},acpActions:[...n.length>0?["acp.fs.access"]:[],...m.length>0?["acp.terminal.exec"]:[]]};return{contextPack:W,planPacket:S}}function rQ($){let b=new Set($.touchedPaths??[]),A=new Set($.commands??[]);for(let m of $.steps??[]){if(typeof m==="string")continue;for(let n of m.paths??[])b.add(n);for(let n of m.commands??[])A.add(n)}return{commands:[...A],touchedPaths:[...b]}}function fQ($,b){if(!$||$.length===0)return[{id:`step_${$0()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((A)=>typeof A==="string"?{id:`step_${$0()}`,summary:A}:{id:`step_${$0()}`,summary:A.summary,paths:A.paths,commands:A.commands,contractRefs:A.contractRefs})}function hQ($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function cQ($,b,A){let m=o(b);A$(m);let n=Q$(m),W=await vb($.fs,n,b.decisionId),w={decisionId:W.envelope?.runtimeLink?.decisionId,traceId:W.envelope?.runtimeLink?.traceId},j=A&&(w.decisionId||w.traceId)?await A.getExecutionTrace(w):null,y=A&&j?await A.replayExecutionTrace(w):null;return{decisionId:b.decisionId,historyDir:W.historyDir,contextPack:W.contextPack,planPacket:W.planPacket,patchVerdict:W.patchVerdict,reviewPacket:W.reviewPacket,trace:j??void 0,replay:y??void 0,source:j?"local+control-plane":"local"}}async function dQ($,b={}){let A=o(b);return A$(A),mn($.fs,Q$(A))}import{buildChannelPlanTrace as uQ,compileChannelPlan as oQ,finalizeChannelPlan as iQ,replayExecutionTrace as lQ,resolveChannelExecutionActor as tQ}from"@contractspec/integration.runtime/channel";import{createHash as pQ}from"crypto";var kb="connect.local",aQ="connect.runtime-link.v1",eQ="connect.adapter.v1",sQ="connect-control-plane-bridge";function $4($){return{linkDecision:async({connectDecisionId:b,createdAt:A,input:m,patchVerdict:n,planPacket:W,workspace:w})=>{let j=new Date(A),y=JSON.stringify({connectDecisionId:b,objective:W.objective,taskId:W.taskId,tool:m.tool,verdict:n.verdict}),B={workspaceId:w.repoId,providerKey:kb,externalEventId:b,eventType:m.tool==="acp.fs.access"?`connect.fs.${m.operation}`:"connect.terminal.exec",occurredAt:j,signatureValid:!0,traceId:n.controlPlane.traceId,thread:{externalThreadId:`connect:${W.taskId}`,externalUserId:W.actor.id},message:{text:n4(W.objective,m)},metadata:Fj({connectDecisionId:b,connectVerdict:n.verdict,sessionId:W.actor.sessionId,workflowId:`connect:${W.taskId}`}),rawPayload:y},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:W4(y),traceId:B.traceId});if(S.duplicate)return b4($.store,w.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:j}),Z=tQ(B,{actorId:W.actor.id,actorType:W.actor.type,capabilityGrants:m4(n.verdict),capabilitySource:"connect",sessionId:W.actor.sessionId}),G=oQ({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:j}),X=iQ({plan:G,decision:A4(n),approvalTimeoutMs:900000,now:j}),Y=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:X.policy?.verdict??"blocked",riskTier:X.policy?.riskTier??"blocked",confidence:X.policy?.confidence??0.5,modelName:sQ,promptVersion:aQ,policyVersion:eQ,toolTrace:uQ(X),actionPlan:X,requiresApproval:X.approval.required,approvalStatus:X.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:X.approval.required?"pending":"processed",decisionId:Y.id,receiptId:S.receiptId,traceId:X.traceId,workspaceId:w.repoId,providerKey:kb,sessionId:W.actor.sessionId,workflowId:`connect:${W.taskId}`,metadata:Fj({connectDecisionId:b,connectVerdict:n.verdict,tool:m.tool})}),{approvalStatus:Y.approvalStatus,decisionId:Y.id,planId:X.id,providerKey:kb,receiptId:S.receiptId,threadId:Q.id,traceId:X.traceId,workspaceId:w.repoId}},getExecutionTrace:(b)=>Nj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let A=await Nj($.traceService,b);return A?lQ(A):null}}}async function b4($,b,A){let n=(await $.listDecisions({externalEventId:A,limit:1,providerKey:kb,workspaceId:b}))[0];return n?{approvalStatus:n.approvalStatus,decisionId:n.id,planId:n.actionPlan.id,providerKey:kb,receiptId:n.receiptId,threadId:n.threadId,traceId:n.actionPlan.traceId,workspaceId:b}:null}async function Nj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function A4($){let b=z$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((A)=>`${A.status}:${A.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function m4($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function n4($,b){return`${$} [${b.tool}]`}function W4($){return pQ("sha256").update($).digest("hex")}function Fj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as S4}from"crypto";async function vj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=w4(b);if(!A)return{};let m=await Xb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:A,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:A==="ui"?j4(b):void 0,query:nn(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:m.verdict==="permit"?"pass":m.verdict==="rewrite"?"warn":"fail",detail:m.reason},reason:m.reason,remediation:m.selected!=null?[`Prefer ${m.selected.candidate.source} candidate ${m.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:m,verdict:m.verdict}}function w4($){let b=nn($).toLowerCase();if(/\b(contract|operation|event|spec|presentation|form)\b/.test(b))return"contracts";if(/\b(integration|provider|sdk|adapter|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render)\b/.test(b))return"runtime";if(/\b(component|ui|screen|view|page|tsx|jsx)\b/.test(b))return"ui";if(/\b(module|bundle|example|template)\b/.test(b))return"solutions";if(/\b(logger|schema|testing|observability|identity|utility|shared|lib)\b/.test(b))return"sharedLibs";return null}function nn($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function j4($){let b=nn($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function gj($){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 y4}from"crypto";function kj($,b,A){let m=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:A?`Generated path: ${A}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||A?"warn":"pass",detail:m}}function Pj($,b){let A=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",m=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:A,detail:m}}function rj($,b,A){return{id:"impact-analysis",status:$?"fail":b||A?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":A?"Impact could not be resolved.":"Impact resolved."}}function fj($,b,A,m,n,W){let w=W.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${W.runtimeLink.decisionId}`:W.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${W.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${y4()}`,sourceDecisionId:b,objective:m.objective,reason:W.reason,summary:{paths:n,impactedContracts:A.impactedContracts,affectedSurfaces:A.affectedSurfaces,requiredChecks:m.requiredChecks},evidence:[{type:"context-pack",ref:W.artifactRefs.contextPack},{type:"plan-packet",ref:W.artifactRefs.planPacket},{type:"patch-verdict",ref:W.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:w}],requiredApprovals:[{capability:O$.key,reason:W.reason}],controlPlane:{traceQuery:pA,policyExplain:aA,approvalStatus:W.runtimeLink?.approvalStatus,decisionId:W.runtimeLink?.decisionId,traceId:W.runtimeLink?.traceId??A.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Wn($,b,A,m,n,W,w,j,y){let B=z$(w);return{decisionId:$,summary:m.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:n,checks:W,verdict:w,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:y?.approvalStatus,decisionId:y?.decisionId,traceId:y?.traceId??A.actor.traceId},approvalOperationRefs:w==="require_review"?[`${O$.key}@${O$.version}`,`${eA.key}@${eA.version}`]:void 0,remediation:B4(w),reviewPacketRef:j,replay:{traceQuery:pA,policyExplain:aA}}}function B4($){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 Q4($,b,A={}){let m=o(b);A$(m),m=f$(m,await $.git.currentBranch());let n=`connect.dec_${S4()}`,W=(A.now??(()=>new Date))().toISOString(),w=Q$(m);await Db($.fs,w);let{contextPack:j,planPacket:y}=await gb($,{...b,candidate:X4(b)}),B=Y4(b),S=await h$($,{baseline:b.baseline,touchedPaths:B,workspace:m}),Q=await H4(A,m.config.connect?.policy?.smokeChecks??[],m.workspaceRoot),Z=Q.some((h)=>h.id.startsWith("smoke:")&&h.status==="fail"),G=Eb(m,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),X=await vj($,b),Y=[kj(G.immutablePath,G.protectedPath,G.generatedPath),Pj(G.commandState,G.commandMatch),rj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...X.check?[X.check]:[],...Q],V=Z4(G,X.verdict),O=z$(V),K=X.reason??G.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?G.requiredApprovals.length>0?G.requiredApprovals:[{capability:O$.key,reason:K}]:[],_={...y,requiredApprovals:J,verificationStatus:O.verificationStatus},H=nb($.fs,m,w,n,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((h)=>({file:h.path,contracts:h.contracts,policies:h.policies,surfaces:h.surfaces})):B.map((h)=>({file:h,contracts:j.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:j.affectedSurfaces})),U=Wn(n,b,j,_,q,Y,V,void 0),z=A.controlPlane?await A.controlPlane.linkDecision({connectDecisionId:n,createdAt:W,input:b,patchVerdict:U,planPacket:_,workspace:m}):null,L=z?{...y,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...y.controlPlane,decisionId:z.decisionId,traceId:z.traceId??y.controlPlane.traceId}}:_,I=V==="require_review"?fj(m,n,j,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,C=Wn(n,b,j,L,q,Y,V,I?J$($.fs,m,$.fs.join(w.reviewPacketsDir,`${I.id}.json`)):void 0,z);if(X.remediation?.length)C.remediation=X.remediation;if(await $n($.fs,w,{contextPack:j,planPacket:L,patchVerdict:C}),I)await An($.fs,w,I);let F=await Nb($.fs,w,n,{contextPack:j,planPacket:L,patchVerdict:C,reviewPacket:I}),x={artifacts:nb($.fs,m,w,n,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:n,createdAt:W,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await Fb($.fs,w,n,x),await bn($.fs,w,gj({contextPack:j,createdAt:W,envelope:x,reviewPacket:I,verifyInput:b,workspace:m})),{contextPack:j,planPacket:L,patchVerdict:C,reviewPacket:I,historyDir:F}}function Z4($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return G4($.verdict,b)}function G4($,b){if(!b)return $;return hj($)<=hj(b)?$:b}function hj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function X4($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function Y4($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function H4($,b,A){if(!$.runCommand)return[];let m=[];for(let n of b){let W=await $.runCommand(n,{cwd:A});m.push({id:`smoke:${n}`,status:W.exitCode===0?"pass":"fail",detail:W.exitCode===0?`Passed: ${n}`:`Failed (${W.exitCode}): ${n}`})}return m}m0();var yn={};P(yn,{generateWorkflowSpec:()=>Jw,generateWorkflowRunnerTemplate:()=>EA,generateWorkflowDevkitWorkflowTemplate:()=>zA,generateWorkflowDevkitStreamRouteTemplate:()=>CA,generateWorkflowDevkitStartRouteTemplate:()=>LA,generateWorkflowDevkitGenericTemplate:()=>IA,generateWorkflowDevkitFollowUpRouteTemplate:()=>RA,generateVisualizationSpec:()=>oW,generateTranslationSpec:()=>dW,generateThemeSpec:()=>Vw,generateTestTemplate:()=>Sw,generateTestSpec:()=>cW,generateTelemetrySpec:()=>Ow,generateProductIntentSpec:()=>tW,generatePresentationSpec:()=>qw,generatePolicySpec:()=>hW,generateOperationSpec:()=>Hw,generateMigrationSpec:()=>Yw,generateKnowledgeSpaceSpec:()=>Gw,generateJobSpec:()=>uW,generateIntegrationSpec:()=>Zw,generateHarnessSuiteSpec:()=>aW,generateHarnessScenarioSpec:()=>pW,generateHandlerTemplate:()=>yw,generateFormSpec:()=>jw,generateFeatureSpec:()=>ww,generateExperimentSpec:()=>Ww,generateExampleSpec:()=>iW,generateEventSpec:()=>nw,generateDataViewSpec:()=>mw,generateDataViewRendererTemplate:()=>_A,generateComponentTemplate:()=>Bw,generateCapabilitySpec:()=>fW,generateAppBlueprintSpec:()=>Aw,generateAgentSpec:()=>lW});m0();class uj{ai;templates=yn;constructor($){this.ai=new A0($)}}function N_($){return new uj($)}import{scanSpecSource as R4}from"@contractspec/module.workspace";function oj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function r_($,b,A={}){let{fs:m,logger:n}=b,W=await m.exists($);if(!W&&!A.force)return{specPath:$,specInfo:oj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let w=oj($),j;if(W)try{let B=await m.readFile($);w=R4(B,$),j=w.key}catch{}let y=[];if(A.clean&&j)try{let B=await uA(j,{fs:m});for(let S of B)try{await m.remove(S.filePath),y.push(S.filePath),n.info(`Removed artifact: ${S.filePath}`)}catch{n.warn(`Could not remove artifact: ${S.filePath}`)}}catch{n.warn("Could not discover implementations for cleanup")}if(W)await m.remove($),n.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:w,deleted:!0,cleanedFiles:y,errors:[]}}import{computeSemanticDiff as C4}from"@contractspec/module.workspace";async function c_($,b,A,m={}){let{fs:n,git:W}=A;if(!await n.exists($))throw Error(`Spec file not found: ${$}`);let j=await n.readFile($),y,B;if(m.baseline)y=await W.showFile(m.baseline,$),B=`${m.baseline}:${$}`;else{if(!await n.exists(b))throw Error(`Spec file not found: ${b}`);y=await n.readFile(b),B=b}let S=C4(j,$,y,B,{breakingOnly:m.breakingOnly});return{spec1:$,spec2:B,differences:S}}s();import{openApiForRegistry as I4}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Bn}from"@contractspec/lib.contracts-spec/operations";async function E4($,b){let{fs:A,logger:m}=b,{registryPath:n,outputPath:W="./openapi.json"}=$;m.info("Loading registry...",{registryPath:n});let w=await M4(n,A);m.info("Generating OpenAPI document...");let j=I4(w,{title:$.title,version:$.version,description:$.description,servers:$.servers}),y=JSON.stringify(j,null,2)+`
1990
+ `,B=A.resolve(W);return await A.mkdir(A.dirname(B)),await A.writeFile(B,y),m.info(`OpenAPI document written to ${B}`),{document:j,outputPath:B,json:y}}async function M4($,b){let m=await import(b.resolve($));if(m instanceof Bn)return m;if(m.registry instanceof Bn)return m.registry;let n=typeof m.createRegistry==="function"?m.createRegistry:typeof m.default==="function"?m.default:void 0;if(n){let W=await n();if(W instanceof Bn)return W}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as x4,parseOpenApi as T4}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Sn,dirname as ij,join as Wb}from"path";function D4($,b,A){if(b.outputDir)return b.outputDir;let{outputDir:m,conventions:n}=A;switch($){case"operation":return Wb(m,n.operations.split("|")[0]??"operations");case"event":return Wb(m,n.events);case"model":return Wb(m,"models");default:return m}}async function lj($,b,A){let{fs:m,logger:n}=A,{source:W,prefix:w,tags:j,exclude:y,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;n.info(`Importing from OpenAPI: ${W}`);let G=await T4(W,{fetch:globalThis.fetch,readFile:(J)=>m.readFile(J)});if(G.warnings.length>0)for(let J of G.warnings)n.warn(`Parse warning: ${J}`);n.info(`Parsed ${G.operations.length} operations from ${G.info.title} v${G.info.version}`);let X=x4(G,$,{prefix:w,tags:j,exclude:y,defaultStability:B,defaultOwners:S,defaultAuth:Q});n.info(`Import result: ${X.summary.imported} imported, ${X.summary.skipped} skipped, ${X.summary.errors} errors`);let Y=[],V=[],O=[],K=new Map;for(let J of X.operationSpecs){let _="operation",H=null;if(J.code.includes("defineEvent("))_="event",H=J.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((J.code.includes("defineSchemaModel(")||J.code.includes("new EnumType(")||J.code.includes("ScalarTypeEnum.")||J.code.includes("new ZodSchemaType(")||J.code.includes("z.enum(")||J.code.includes("new JsonSchemaType(")||J.code.includes("new GraphQLSchemaType("))&&!J.code.includes("defineCommand(")&&!J.code.includes("defineQuery("))_="model";else _="operation",H=J.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let q=D4(_,b,$),U=Wb(q,J.fileName);if(!H&&_==="model"){if(J.code.includes("new ZodSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(J.code.includes("new JsonSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(J.code.includes("new GraphQLSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!H)H=J.code.match(/export const (\w+)\s*=/)}if(Z)n.info(`[DRY RUN] Would create: ${U}`);else{let z=ij(U);if(!await m.exists(z))await m.mkdir(z);await m.writeFile(U,J.code),n.info(`Created: ${U}`)}if(Y.push({path:U,operationId:J.source.sourceId,specName:J.fileName.replace(".ts","")}),H){let z=ij(U),L=K.get(z)||[];L.push({file:Sn(U),name:H[1],type:_}),K.set(z,L)}}if(!Z&&Y.length>0)for(let[J,_]of K.entries()){if(_.length===0)continue;let H=_.map((x)=>x.type),q=H.every((x)=>x==="operation"),U=H.every((x)=>x==="event"),z=H.every((x)=>x==="model"),L=`/**
1672
1991
  * Auto-generated registry file.
1673
1992
  */
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';
1993
+ `;_.forEach((x)=>{let h=`./${Sn(x.file,".ts")}`;L+=`import { ${x.name} } from '${h}';
1994
+ `}),L+=`
1995
+ `;let I=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
1677
1996
 
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';
1997
+ `,L+=`export const operationRegistry = new OperationSpecRegistry();
1998
+ `,_.forEach((x)=>{L+=`operationRegistry.register(${x.name});
1999
+ `}),I=!0;else if(U)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
1681
2000
 
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';
2001
+ `,L+=`export const eventRegistry = new EventRegistry();
2002
+ `,_.forEach((x)=>{L+=`eventRegistry.register(${x.name});
2003
+ `}),I=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
1685
2004
 
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=`/**
2005
+ `,L+=`export const modelRegistry = new ModelRegistry();
2006
+ `,_.forEach((x)=>{L+=`modelRegistry.register(${x.name});
2007
+ `}),I=!0;if(I){let x=Wb(J,"registry.ts");await m.writeFile(x,L),n.info(`Created/Updated registry: ${x}`)}let C=`/**
1689
2008
  * Auto-generated barrel file.
1690
2009
  */
1691
2010
 
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}\`:
2011
+ `;if(_.forEach((x)=>{let h=`./${Sn(x.file,".ts")}`;C+=`export * from '${h}';
2012
+ `}),I)C+=`export * from './registry';
2013
+ `;let F=Wb(J,"index.ts");await m.writeFile(F,C),n.info(`Created/Updated index: ${F}`)}for(let J of X.skipped)V.push({operationId:J.sourceId,reason:J.reason}),n.debug(`Skipped: ${J.sourceId} - ${J.reason}`);for(let J of X.errors)O.push({operationId:J.sourceId,error:J.error}),n.error(`Error: ${J.sourceId} - ${J.error}`);return{imported:X.summary.imported,skipped:X.summary.skipped,errors:X.summary.errors,files:Y,skippedOperations:V,errorMessages:O}}import{importFromOpenApi as N4,parseOpenApi as F4}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as v4,join as g4}from"path";async function AU($,b,A){let{fs:m,logger:n}=A,{sources:W,sourceName:w,interactive:j,force:y,dryRun:B}=$,{outputDir:S}=b,Q=W??b.openapi?.sources??[];if(w){if(Q=Q.filter((G)=>G.name===w),Q.length===0)throw Error(`Source not found: ${w}`)}if(Q.length===0)return n.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let Z={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let G of Q){n.info(`Syncing with source: ${G.name}`);let X=G.url??G.file;if(!X){n.warn(`Source ${G.name} has no url or file configured`);continue}let Y=await F4(X,{fetch:globalThis.fetch,readFile:(O)=>m.readFile(O)});n.info(`Parsed ${Y.operations.length} operations from ${G.name}`);let V=N4(Y,b,{prefix:G.prefix,tags:G.tags,exclude:G.exclude,defaultStability:G.defaultStability,defaultAuth:G.defaultAuth});for(let O of V.operationSpecs){let K=g4(S,O.fileName);if(!await m.exists(K)){if(!B){let _=v4(K);await m.mkdir(_),await m.writeFile(K,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:K}),n.info(`Added: ${O.source.sourceId}`)}else if(await m.readFile(K)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K});else if(y==="openapi"){if(!B)await m.writeFile(K,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:K}),n.info(`Updated: ${O.source.sourceId}`)}else if(y==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K}),n.info(`Kept: ${O.source.sourceId}`);else if(j)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),n.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),n.warn(`Conflict: ${O.source.sourceId}`)}}return n.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as k4}from"@contractspec/lib.contracts-transformers/openapi";async function WU($,b){let{fs:A,logger:m}=b,{specPath:n,openApiSource:W,ignoreDescriptions:w,ignoreTags:j,ignoreTransport:y}=$;m.info(`Validating specs against OpenAPI: ${W}`);let B=await k4(W,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});m.info(`Parsed ${B.operations.length} operations from ${B.info.title}`);let S=new Map;for(let O of B.operations)S.set(O.operationId,O);let Q=[],Z=0,G=0,X=await A.stat(n),Y=[];if(X.isDirectory){let O=await A.glob({pattern:"**/*.ts",cwd:n,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});Y.push(...O)}else Y.push(n);m.info(`Found ${Y.length} spec files to validate`);for(let O of Y)try{let K=await A.readFile(O),J=K.match(/operationId:\s*['"]([^'"]+)['"]/)||K.match(/name:\s*['"]([^'"]+)['"]/)||K.match(/export\s+const\s+(\w+)Spec\s*=/);if(!J||!J[1]){m.debug(`Could not extract operationId from ${O}`);continue}let _=J[1];Z++;let H;if(H=S.get(_),!H){let z=_.replace(/([A-Z])/g,"_$1").toLowerCase();H=S.get(z)}if(!H){for(let[z,L]of S)if(z.toLowerCase().includes(_.toLowerCase())||_.toLowerCase().includes(z.toLowerCase())){H=L;break}}if(!H){Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${_}`}]}),G++;continue}let q=[];if(H.deprecated&&!K.includes("deprecated"))q.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!y){let z=K.match(/path:\s*['"]([^'"]+)['"]/);if(z&&z[1]!==H.path)q.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${z[1]}", OpenAPI has "${H.path}"`})}if(!y){let z=K.match(/method:\s*['"]([^'"]+)['"]/);if(z?.[1]&&z[1].toLowerCase()!==H.method.toLowerCase())q.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${z[1]}", OpenAPI has "${H.method.toUpperCase()}"`})}let U=q.length===0;if(!U)G++;Q.push({specPath:O,operationId:H.operationId,valid:U,diffs:q})}catch(K){m.error(`Error validating ${O}: ${K}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${K instanceof Error?K.message:String(K)}`}]}),G++}let V=G===0;return m.info(`Validation ${V?"passed":"failed"}: ${Z} specs checked, ${G} with differences`),{valid:V,specsValidated:Z,specsWithDiffs:G,results:Q}}async function YU($,b,A){let{fs:m,logger:n}=$,{source:W,outputDir:w}=b,j=m.resolve(A??process.cwd(),W);if(!await m.exists(j))throw Error(`Source file not found: ${j}`);let B={...await g(m,A),outputDir:w};return n.info(`Extracting contracts from ${j} to ${w}`),lj(B,{source:j,outputDir:w,dryRun:!1},$)}var pj={};P(pj,{validateFeatureRefs:()=>f4,getArrayNameForSpecType:()=>tj,detectFeatureContext:()=>P4,computeAddSpecEdit:()=>r4});function P4($,b){let A=[{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"}],m=null;for(let{type:Q,regex:Z,specType:G}of A){let X;Z.lastIndex=0;while((X=Z.exec($))!==null)if(!m||X.index>m.index)m={type:Q,specType:G,index:X.index}}if(!m)return null;let n=$.slice(m.index)+b,W=m.type;new RegExp(`${W}\\s*:\\s*\\[`).exec(n);let j=$.slice(m.index),y=0,B=!1,S="";for(let Q=0;Q<j.length;Q++){let Z=j[Q],G=Q>0?j[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&G!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")y++;else if(Z==="]"){if(y--,y===0)return null}}if(y>0)return{type:m.type,specType:m.specType};return null}function r4($,b){let A=tj(b.type),n=new RegExp(`${A}\\s*:\\s*\\[`,"g").exec($);if(n){let W=n.index+n[0].length,w=typeof b.version==="string"?`'${b.version}'`:b.version,j=`
2014
+ { key: '${b.key}', version: ${w} },`;return{index:W,text:j}}return null}function tj($){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 f4($,b){let A=[],m=(n,W,w)=>{for(let j of n){let y=`${j.key}.v${j.version}`;if(!W.has(y))A.push({key:j.key,version:j.version,type:w,message:`${w} ${j.key}.v${j.version} not found`})}};return m($.operations,b.operations,"Operation"),m($.events,b.events,"Event"),m($.presentations,b.presentations,"Presentation"),m($.experiments,b.experiments,"Experiment"),A}var $y={};P($y,{removeReferenceStrategy:()=>j0,implementSkeletonStrategy:()=>w0,implementAiStrategy:()=>W0,generateFixLinks:()=>h4,FixService:()=>sj,FIX_STRATEGY_STABILITY:()=>db,FIX_STRATEGY_LABELS:()=>l4,CiOutputSchema:()=>W6});function h4($,b){let A=[];if(!$.ref||!$.file)return A;if(b.includeCli)A.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let m=$.file.startsWith("/")?$.file:`/${$.file}`,n=$.ref,W=n.line||1,w=n.column||1;A.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${m}:${W}:${w}`})}if(b.includeGithubIssue&&b.repository){let m=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),n=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
1696
2015
 
1697
2016
  > ${$.message}
1698
2017
 
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`/**
2018
+ Reference: \`${$.ref.key}.v${$.ref.version}\``);A.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${m}&body=${n}`})}return A}import t4 from"path";function L$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function R$($,b){let A=$.enrichment?.owners?.length?$.enrichment.owners.map((w)=>`'${w}'`).join(", "):"'@team'",m=$.enrichment?.tags?.length?$.enrichment.tags.map((w)=>`'${w}'`).join(", "):"",n=$.description||`TODO: Add description for ${$.key}`,W=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([w,j])=>{if(j!==void 0)W.push(`${w}: ${j}`)});return W.push(`owners: [${A}]`),W.push(`tags: [${m}]`),W.push(`description: '${n}'`),W.join(`,
2019
+ `)}function rb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"Spec",m=R$($,{kind:"'api'"});return`/**
1701
2020
  * Capability: ${$.key}
1702
2021
  *
1703
2022
  * Skeleton spec generated by ContractSpec fix command.
@@ -1708,9 +2027,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",labe
1708
2027
 
1709
2028
  import { defineCapability } from '@contractspec/lib.contracts-spec';
1710
2029
 
1711
- export const ${j} = defineCapability({
2030
+ export const ${A} = defineCapability({
1712
2031
  meta: {
1713
- ${A}
2032
+ ${m}
1714
2033
  },
1715
2034
 
1716
2035
  provides: [
@@ -1734,7 +2053,7 @@ export const ${j} = defineCapability({
1734
2053
  // }
1735
2054
  ],
1736
2055
  });
1737
- `}function I0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"EventSpec",A=j.replace("Spec","Payload"),Q=K$($);return`/**
2056
+ `}function fb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"EventSpec",m=A.replace("Spec","Payload"),n=R$($);return`/**
1738
2057
  * Event: ${$.key}
1739
2058
  *
1740
2059
  * Skeleton spec generated by ContractSpec fix command.
@@ -1747,8 +2066,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
1747
2066
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
1748
2067
 
1749
2068
  // TODO: Define event payload schema
1750
- export const ${A} = new SchemaModel({
1751
- name: '${A}',
2069
+ export const ${m} = new SchemaModel({
2070
+ name: '${m}',
1752
2071
  description: 'Payload for ${$.key} event',
1753
2072
  fields: {
1754
2073
  // Add your payload fields here
@@ -1758,12 +2077,12 @@ export const ${A} = new SchemaModel({
1758
2077
  },
1759
2078
  });
1760
2079
 
1761
- export const ${j} = defineEvent({
2080
+ export const ${A} = defineEvent({
1762
2081
  meta: {
1763
- ${Q}
2082
+ ${n}
1764
2083
  },
1765
2084
 
1766
- payload: ${A},
2085
+ payload: ${m},
1767
2086
 
1768
2087
  // TODO: Specify PII fields if any
1769
2088
  // piiFields: ['user.email'],
@@ -1774,7 +2093,7 @@ export const ${j} = defineEvent({
1774
2093
  // policy: 'archive',
1775
2094
  // },
1776
2095
  });
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`/**
2096
+ `}function c4($){let b=$.toLowerCase(),A=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let m of A)if(b.includes(m))return"query";return"command"}function hb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"Spec",m=A.replace("Spec","Input"),n=A.replace("Spec","Output"),W=c4($.key),w=W==="query"?"defineQuery":"defineCommand",j=$.enrichment?.goal||"TODO: Define the business goal",y=$.enrichment?.context||"TODO: Provide context",B=R$($,{goal:`'${j}'`,context:`'${y}'`});return`/**
1778
2097
  * Operation: ${$.key}
1779
2098
  *
1780
2099
  * Skeleton spec generated by ContractSpec fix command.
@@ -1783,12 +2102,12 @@ export const ${j} = defineEvent({
1783
2102
  * Referenced by feature: ${$.featureKey||"unknown"}
1784
2103
  */
1785
2104
 
1786
- import { ${X} } from '@contractspec/lib.contracts-spec';
2105
+ import { ${w} } from '@contractspec/lib.contracts-spec';
1787
2106
  import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
1788
2107
 
1789
2108
  // TODO: Define input schema
1790
- export const ${A} = new SchemaModel({
1791
- name: '${A}',
2109
+ export const ${m} = new SchemaModel({
2110
+ name: '${m}',
1792
2111
  description: 'Input for ${$.key}',
1793
2112
  fields: {
1794
2113
  // Add your input fields here
@@ -1797,8 +2116,8 @@ export const ${A} = new SchemaModel({
1797
2116
  });
1798
2117
 
1799
2118
  // TODO: Define output schema
1800
- export const ${Q} = new SchemaModel({
1801
- name: '${Q}',
2119
+ export const ${n} = new SchemaModel({
2120
+ name: '${n}',
1802
2121
  description: 'Output for ${$.key}',
1803
2122
  fields: {
1804
2123
  // Add your output fields here
@@ -1806,14 +2125,14 @@ export const ${Q} = new SchemaModel({
1806
2125
  },
1807
2126
  });
1808
2127
 
1809
- export const ${j} = ${X}({
2128
+ export const ${A} = ${w}({
1810
2129
  meta: {
1811
- ${q}
2130
+ ${B}
1812
2131
  },
1813
2132
 
1814
2133
  io: {
1815
- input: ${A},
1816
- output: ${Q},
2134
+ input: ${m},
2135
+ output: ${n},
1817
2136
  errors: {
1818
2137
  // TODO: Define possible errors
1819
2138
  // EXAMPLE_ERROR: {
@@ -1835,7 +2154,7 @@ export const ${j} = ${X}({
1835
2154
  },
1836
2155
 
1837
2156
  transport: {
1838
- rest: { method: '${Z==="command"?"POST":"GET"}' },
2157
+ rest: { method: '${W==="command"?"POST":"GET"}' },
1839
2158
  gql: { field: '${$.key.replace(/\./g,"_")}' },
1840
2159
  mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
1841
2160
  },
@@ -1852,7 +2171,7 @@ export const ${j} = ${X}({
1852
2171
  examples: [],
1853
2172
  },
1854
2173
  });
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`/**
2174
+ `}function d4($){let b=$.toLowerCase();if(b.includes("doc")||b.includes("guide")||b.includes("readme"))return"markdown";if(b.includes("data")||b.includes("api")||b.includes("export"))return"data";return"web_component"}function cb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"PresentationSpec",m=d4($.key),n=R$($);return`/**
1856
2175
  * Presentation: ${$.key}
1857
2176
  *
1858
2177
  * Skeleton spec generated by ContractSpec fix command.
@@ -1863,12 +2182,12 @@ export const ${j} = ${X}({
1863
2182
 
1864
2183
  import { definePresentation } from '@contractspec/lib.contracts-spec';
1865
2184
 
1866
- export const ${j} = definePresentation({
2185
+ export const ${A} = definePresentation({
1867
2186
  meta: {
1868
- ${Q}
2187
+ ${n}
1869
2188
  },
1870
2189
 
1871
- kind: '${A}',
2190
+ kind: '${m}',
1872
2191
 
1873
2192
  // TODO: Define content structure
1874
2193
  content: {
@@ -1892,7 +2211,7 @@ export const ${j} = definePresentation({
1892
2211
  // focusable: true,
1893
2212
  // },
1894
2213
  });
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
2214
+ `}import G$ from"path";function n0($,b){if(b.outputDir)return Qn(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=u4($.featureFile);if(A)return Qn(A,$.ref.key,$.specType)}return Qn(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function u4($){let b=G$.dirname($),A=G$.parse($).root,m=0;while(b!==A&&m<50){if(G$.basename(b)==="src")return b;b=G$.dirname(b),m++}b=G$.dirname($),m=0;while(b!==A&&m<50)b=G$.dirname(b),m++;let n=$.lastIndexOf(`${G$.sep}src${G$.sep}`);if(n!==-1)return $.substring(0,n+5);return null}function Qn($,b,A){let m=b.replace(/\./g,"-").toLowerCase(),n=o4(A),W=i4(A);return G$.join($,W,`${m}${n}`)}function o4($){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 i4($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var l4={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},db={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function W0($,b,A){let{fs:m,logger:n}=A,{ref:W,specType:w,featureKey:j}=$;try{let y={key:W.key,version:W.version,specType:w,stability:db["implement-ai"],featureKey:j},B=y;if(b.aiConfig)try{B=await p4(y,b,n)}catch(G){n.warn("AI enrichment failed, falling back to skeleton",{error:G instanceof Error?G.message:String(G)})}else n.info("No AI config provided, using skeleton with experimental stability");let S=s4(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${w}`};let Q=n0($,b),Z=[];if(!b.dryRun){let G=t4.dirname(Q);await m.mkdir(G),await m.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(y){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:y instanceof Error?y.message:String(y)}}}async function p4($,b,A){if(A.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:n}=await Promise.resolve().then(() => (m0(),dj)),W=a4(b),w=new n(W),j=$.specType==="operation"?"command":$.specType,y=`${aj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await w.generateOperationSpec(y,j);return{...$,description:B.description,enrichment:{goal:B.goal,context:B.context,owners:B.owners,tags:B.tags}}}if($.specType==="event"){let B=await w.generateEventSpec(y);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(n){A.warn("AIGenerator call failed, falling back to heuristics",{error:n instanceof Error?n.message:String(n)})}let m=e4($.key,$.specType);return{...$,description:m.description,enrichment:{goal:m.goal,context:m.context,owners:["@team"],tags:m.tags}}}function a4($){let b=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[b?.provider??"openai"]??"openai",aiModel:b?.model??"gpt-4-turbo",customApiKey:b?.apiKey??"",customEndpoint:b?.endpoint??""}}function e4($,b){let A=$.split("."),m=A[0]||"unknown",n=A.slice(1).join(" ").replace(/_/g," "),W=[m],w=n.toLowerCase().split(" "),y=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>w.some((S)=>S.includes(B)));return{description:`${aj(b)} for ${m} ${n}`,goal:`Enable ${n} functionality in the ${m} domain`,context:`Part of the ${m} feature set. Generated by ContractSpec AI fix.`,tags:[...W,...y]}}function s4($){switch($.specType){case"operation":return hb($);case"event":return fb($);case"presentation":return cb($);case"capability":return rb($);default:return}}function aj($){return $.charAt(0).toUpperCase()+$.slice(1)}import $6 from"path";async function w0($,b,A){let{fs:m}=A,{ref:n,specType:W,featureKey:w}=$;try{let j={key:n.key,version:n.version,specType:W,stability:db["implement-skeleton"],description:`Skeleton spec for ${n.key}`,featureKey:w},y=b6(j);if(!y)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let B=n0($,b),S=[];if(!b.dryRun){let Q=$6.dirname(B);await m.mkdir(Q),await m.writeFile(B,y),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(j){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}function b6($){switch($.specType){case"operation":return hb($);case"event":return fb($);case"presentation":return cb($);case"capability":return rb($);default:return}}async function j0($,b,A){let{fs:m}=A,{ref:n,featureFile:W,specType:w}=$;try{let j=await m.readFile(W),y=j,B=A6(j,n,w);if(B===j)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${n.key}.v${n.version} in ${W}`};let S=[];if(!b.dryRun)await m.writeFile(W,B),S.push({path:W,action:"modified",previousContent:y});else S.push({path:W,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(j){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}function A6($,b,A){if(!m6(A))return $;let n=ej(b.key),W=ej(b.version),w=[new RegExp(`\\{\\s*key:\\s*['"]${n}['"],\\s*version:\\s*['"]${W}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${W}['"],\\s*key:\\s*['"]${n}['"]\\s*\\},?\\s*`,"g")],j=$;for(let y of w)j=j.replace(y,"");return j=n6(j),j}function m6($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function ej($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n6($){return $.replace(/,(\s*)\]/g,"$1]")}class sj{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,A)=>j0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,A)=>w0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,A)=>W0(b,A,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let A=this.strategies.get(b.strategy);if(!A)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),A.fix($,b)}async batchFix($){let b=[],A=0,m=0;for(let n of $.issues)try{let W=await this.fixIssue(n,$.options);if(b.push(W),W.success)A++;else m++}catch(W){m++,b.push({success:!1,strategy:$.options.strategy,issue:n,filesChanged:[],error:W instanceof Error?W.message:String(W)})}return{total:$.issues.length,succeeded:A,failed:m,results:b}}async scanAndGetFixables($={}){return(await oA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((A)=>this.getToFix(A)).filter((A)=>A!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let A=this.parseFixableIssue($);if(!A)return null;return{...A,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:A,preferAi:m,select:n}=b;if(A)return Promise.resolve(A);if(m&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof n==="function")return n($,$.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((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as wb}from"zod";var W6=wb.union([wb.array(wb.unknown()),wb.object({issues:wb.array(wb.unknown())}).transform(($)=>$.issues)]);import{exec as w6}from"child_process";import{promisify as j6}from"util";var y6=j6(w6),by={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function Xz($,b,A={}){if($.length===0)return;let m=A.cwd??process.cwd(),n=by[A.type??"biome"]??by.biome,W=50;for(let w=0;w<$.length;w+=W){let y=$.slice(w,w+W).map((B)=>`"${B}"`).join(" ");try{await y6(`${n} ${y}`,{cwd:m})}catch(B){}}}import C$ from"path";async function Oz($,b){let A=C$.join(b,"contracts"),m=C$.join(b,"generated"),n=C$.join(m,"docs"),W=await $.fs.exists(A),w=await $.fs.exists(m);if(!W)return{hasContracts:!1,hasGenerated:w,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let j=await j$($,{pattern:"contracts/**/*.ts"}),y=[];if(w)for(let G of j){let X=G.key||C$.basename(G.filePath,".ts"),Y=C$.join(n,`${X}.md`);if(!await $.fs.exists(Y))y.push(X)}else if(j.length>0)for(let G of j){let X=G.key||C$.basename(G.filePath,".ts");y.push(X)}let B=C$.join(A,"index.ts"),S=C$.join(A,"registry.ts"),Q=j.length>0&&!await $.fs.exists(B),Z=j.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:w,missingDocs:y,missingIndex:Q,missingRegistry:Z,totalSpecs:j.length}}var Wy={};P(Wy,{runHook:()=>Ay,getAvailableHooks:()=>my});import{exec as B6}from"child_process";import{promisify as S6}from"util";var Q6=S6(B6);async function Ay($,b){let{fs:A,logger:m}=$,{hookName:n,dryRun:W=!1}=b,w=M(b.workspaceRoot);m.info(`Running hook: ${n}`,{workspaceRoot:w,dryRun:W});let j=await ny(A,w);if(!j)return{hookName:n,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let y=j[n];if(!y||y.length===0)return{hookName:n,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${n}`};m.info(`Found ${y.length} command(s) for ${n}`);let B=[],S=!0;for(let Z of y){if(W){m.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}m.info(`Executing: ${Z}`);try{let{stdout:G,stderr:X}=await Q6(Z,{cwd:w,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:G,stderr:X}),m.info(`\u2713 ${Z}`)}catch(G){S=!1;let X=G;B.push({command:Z,success:!1,exitCode:X.code??1,stdout:X.stdout??"",stderr:X.stderr??X.message??String(G)}),m.error(`\u2717 ${Z}`,{exitCode:X.code,stderr:X.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:n,success:S,commandResults:B,totalCommands:y.length,successfulCommands:Q,summary:S?`\u2713 All ${y.length} command(s) passed`:`\u2717 ${Q}/${y.length} command(s) passed`}}async function my($,b){let A=await ny($.fs,b);return A?Object.keys(A):[]}async function ny($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return null;try{let m=await $.readFile(A);return JSON.parse(m).hooks??null}catch{return null}}import{detectFramework as Z6,extractFromProject as G6}from"@contractspec/lib.source-extractors";import{generateOperations as X6,generateRegistry as Y6,generateSchemas as H6}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as q6}from"@contractspec/lib.source-extractors/extractors";import{dirname as O6,join as Zn}from"path";async function V6($,b,A,m){let{fs:n,logger:W}=A,w=m??process.cwd();q6(),W.info(`Scanning source code in ${w}...`);let j={readFile:(_)=>n.readFile(_),glob:(_,H)=>n.glob({pattern:_,cwd:H?.cwd}),exists:(_)=>n.exists(_)},y=await Z6(w,{readFile:(_)=>n.readFile(_),glob:(_)=>n.glob({pattern:_})});if(y.frameworks.length===0)return W.warn("No supported frameworks detected"),{success:!1,report:J6(),errors:["No supported frameworks detected in project"]};W.info(`Detected frameworks: ${y.frameworks.map((_)=>_.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let _ of B.getAll())if("setFs"in _&&typeof _.setFs==="function")_.setFs(j);let S={scope:b.scope,framework:b.framework},Q=await G6(y,S);if(!Q.success||!Q.ir)return{success:!1,report:K6(Q.errors??[]),errors:Q.errors?.map((_)=>_.message)};let Z=Q.ir;if(W.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:_6(Z)};let G=b.outputDir??Zn($.outputDir,"generated"),X={outputDir:G,defaultAuth:"user"},Y=X6(Z,X),V=H6(Z,X),O=Y6(Y),K=[...Y,...V,O];if(!b.dryRun)for(let _ of K){let H=Zn(G,_.path),q=O6(H);if(!await n.exists(q))await n.mkdir(q);await n.writeFile(H,_.content),W.info(`Created: ${H}`)}else for(let _ of K)W.info(`[DRY RUN] Would create: ${Zn(G,_.path)}`);let J={files:K,operationsGenerated:Y.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:U6(Z,J,b)}}function J6(){return`# Import Report
1896
2215
 
1897
2216
  ## \u274C No Supported Frameworks Detected
1898
2217
 
@@ -1909,13 +2228,13 @@ No supported frameworks were detected in the project.
1909
2228
  - Next.js API Routes
1910
2229
 
1911
2230
  Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
1912
- `}function IY($){return`# Import Report
2231
+ `}function K6($){return`# Import Report
1913
2232
 
1914
2233
  ## \u274C Extraction Failed
1915
2234
 
1916
- ${$.map((W)=>`- ${W.message}`).join(`
2235
+ ${$.map((b)=>`- ${b.message}`).join(`
1917
2236
  `)}
1918
- `}function MY($){return`# Import Analysis Report
2237
+ `}function _6($){return`# Import Analysis Report
1919
2238
 
1920
2239
  ## Summary
1921
2240
 
@@ -1935,19 +2254,19 @@ ${$.map((W)=>`- ${W.message}`).join(`
1935
2254
 
1936
2255
  ## Detected Frameworks
1937
2256
 
1938
- ${$.project.frameworks.map((W)=>`- ${W.name} (${W.confidence})`).join(`
2257
+ ${$.project.frameworks.map((b)=>`- ${b.name} (${b.confidence})`).join(`
1939
2258
  `)}
1940
2259
 
1941
2260
  ## Endpoints
1942
2261
 
1943
- ${$.endpoints.map((W)=>`- \`${W.method} ${W.path}\` - ${W.confidence.level}`).join(`
2262
+ ${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).join(`
1944
2263
  `)}
1945
2264
 
1946
2265
  ## Ambiguities (Require Review)
1947
2266
 
1948
- ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
2267
+ ${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
1949
2268
  `):"None"}
1950
- `}function EY($,W,j){return`# Import Report${j.dryRun?" (Dry Run)":""}
2269
+ `}function U6($,b,A){return`# Import Report${A.dryRun?" (Dry Run)":""}
1951
2270
 
1952
2271
  ## \u2705 Import Successful
1953
2272
 
@@ -1959,9 +2278,9 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
1959
2278
 
1960
2279
  ### Generation Summary
1961
2280
 
1962
- - **Operations Generated**: ${W.operationsGenerated}
1963
- - **Schemas Generated**: ${W.schemasGenerated}
1964
- - **Total Files**: ${W.files.length}
2281
+ - **Operations Generated**: ${b.operationsGenerated}
2282
+ - **Schemas Generated**: ${b.schemasGenerated}
2283
+ - **Total Files**: ${b.files.length}
1965
2284
 
1966
2285
  ### Confidence Breakdown
1967
2286
 
@@ -1973,41 +2292,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
1973
2292
 
1974
2293
  ### Next Steps
1975
2294
 
1976
- 1. Review generated contracts in \`${j.outputDir??"generated/"}\`
2295
+ 1. Review generated contracts in \`${A.outputDir??"generated/"}\`
1977
2296
  2. Fill in TODO placeholders with business context
1978
2297
  3. Run \`contractspec validate\` to verify contracts
1979
2298
  4. Move stable contracts from \`generated/\` to \`curated/\`
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(`
2299
+ `}function z6($,b,A={}){let m=[];if(m.push("# Import Report"),m.push(""),m.push(`**Generated**: ${new Date().toISOString()}`),m.push(""),m.push("## Summary"),m.push(""),m.push("| Metric | Count |"),m.push("|--------|-------|"),m.push(`| Files Scanned | ${$.stats.filesScanned} |`),m.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),m.push(`| Schemas Found | ${$.stats.schemasFound} |`),m.push(`| Errors Found | ${$.stats.errorsFound} |`),m.push(`| Events Found | ${$.stats.eventsFound} |`),m.push(""),A.includeStats!==!1)m.push("### Confidence"),m.push(""),m.push("| Level | Count |"),m.push("|-------|-------|"),m.push(`| High | ${$.stats.highConfidence} |`),m.push(`| Medium | ${$.stats.mediumConfidence} |`),m.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),m.push("");m.push("### Frameworks Detected"),m.push("");for(let n of $.project.frameworks)m.push(`- **${n.name}** (${n.confidence})`);if(m.push(""),A.includeEndpoints!==!1&&$.endpoints.length>0){m.push("## Endpoints"),m.push(""),m.push("| Method | Path | Kind | Confidence |"),m.push("|--------|------|------|------------|");for(let n of $.endpoints)m.push(`| ${n.method} | \`${n.path}\` | ${n.kind} | ${n.confidence.level} |`);m.push("")}if(A.includeSchemas!==!1&&$.schemas.length>0){m.push("## Schemas"),m.push(""),m.push("| Name | Type | Confidence |"),m.push("|------|------|------------|");for(let n of $.schemas)m.push(`| ${n.name} | ${n.schemaType} | ${n.confidence.level} |`);m.push("")}if(b&&A.includeIssues!==!1){m.push("## Verification"),m.push(""),m.push("| Status | Count |"),m.push("|--------|-------|"),m.push(`| Valid | ${b.summary.validEndpoints} |`),m.push(`| Warnings | ${b.summary.warningEndpoints} |`),m.push(`| Errors | ${b.summary.errorEndpoints} |`),m.push("");let n=b.endpointResults.filter((W)=>W.issues.length>0);if(n.length>0){m.push("### Issues"),m.push("");for(let W of n){m.push(`#### ${W.endpoint.method} ${W.endpoint.path}`);for(let w of W.issues){let j=w.severity==="error"?"\u274C":w.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(m.push(`- ${j} **${w.code}**: ${w.message}`),w.suggestion)m.push(` - *Suggestion*: ${w.suggestion}`)}m.push("")}}}if(A.includeAmbiguities!==!1&&$.ambiguities.length>0){m.push("## Ambiguities (Require Review)"),m.push("");for(let n of $.ambiguities)if(m.push(`- **${n.type}** (${n.itemId}): ${n.description}`),n.suggestion)m.push(` - *Suggestion*: ${n.suggestion}`);m.push("")}return m.push("## Next Steps"),m.push(""),m.push("1. Review generated contracts in the output directory"),m.push("2. Fill in TODO placeholders with business context"),m.push("3. Run `contractspec validate` to verify contracts"),m.push("4. Move stable contracts from `generated/` to `curated/`"),m.push(""),m.join(`
2300
+ `)}function L6($,b){let A=[];A.push(""),A.push("\uD83D\uDCCA Summary"),A.push(` Files scanned: ${$.stats.filesScanned}`),A.push(` Endpoints: ${$.stats.endpointsFound}`),A.push(` Schemas: ${$.stats.schemasFound}`),A.push(""),A.push("\uD83D\uDCC8 Confidence"),A.push(` High: ${$.stats.highConfidence}`),A.push(` Medium: ${$.stats.mediumConfidence}`),A.push(` Low: ${$.stats.lowConfidence}`),A.push(""),A.push("\uD83D\uDD27 Frameworks");for(let m of $.project.frameworks)A.push(` \u2022 ${m.name}`);if(A.push(""),b)A.push("\u2705 Verification"),A.push(` Valid: ${b.summary.validEndpoints}`),A.push(` Warnings: ${b.summary.warningEndpoints}`),A.push(` Errors: ${b.summary.errorEndpoints}`),A.push("");return A.join(`
2301
+ `)}async function R6($,b,A){let{logger:m}=A,n=[],W=[...$.ambiguities];m.info(`Verifying ${$.endpoints.length} endpoints...`);for(let j of $.endpoints){let y=[];if(j.confidence.level==="low"||j.confidence.level==="ambiguous")y.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${j.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!j.input&&(j.method==="POST"||j.method==="PUT"||j.method==="PATCH"))y.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!j.output)y.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(b.checkDuplicates){if($.endpoints.filter((Q)=>Q.id!==j.id&&Q.path===j.path&&Q.method===j.method).length>0)y.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${j.method} ${j.path} found`,severity:"error"})}if(b.checkConflicts){let S=C6(j,$.endpoints);for(let Q of S)y.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=y.some((S)=>S.severity==="error")?"error":y.some((S)=>S.severity==="warning")?"warning":"valid";n.push({endpoint:j,status:B,issues:y})}if(b.validateSchemas){for(let j of $.schemas)if(!j.fields||j.fields.length===0)W.push({type:"schema",itemId:j.id,description:`Schema ${j.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:j.source})}let w={totalEndpoints:n.length,validEndpoints:n.filter((j)=>j.status==="valid").length,warningEndpoints:n.filter((j)=>j.status==="warning").length,errorEndpoints:n.filter((j)=>j.status==="error").length,totalIssues:n.reduce((j,y)=>j+y.issues.length,0)};return m.info(`Verification complete: ${w.validEndpoints} valid, ${w.warningEndpoints} warnings, ${w.errorEndpoints} errors`),{valid:w.errorEndpoints===0,endpointResults:n,ambiguities:W,summary:w}}function C6($,b){let A=[],m=$.path.split("/").filter(Boolean);for(let n of b){if(n.id===$.id)continue;if(n.method!==$.method)continue;let W=n.path.split("/").filter(Boolean);if(W.length!==m.length)continue;let w=!0;for(let j=0;j<m.length;j++){let y=m[j]??"",B=W[j]??"",S=y.startsWith(":")||y.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&y!==B){w=!1;break}}if(w&&$.path!==n.path)A.push(n)}return A}function fz($,b="feature-map",A={}){switch(b){case"feature-map":return Yn($,A);case"orphans":return I6($,A);case"dependencies":return E6($,A);case"full":return M6($,A);default:return Yn($,A)}}function Yn($,b){let{direction:A="LR",showVersions:m=!0,maxNodes:n=50}=b,W=[`flowchart ${A}`],w=$.features;if(b.featureKeys&&b.featureKeys.length>0)w=w.filter((Z)=>b.featureKeys?.includes(Z.key));let j=0,y=!1;if(w.length>0){W.push(" subgraph features [Features]");for(let Z of w){if(j>=n)break;let G=v(`F_${Z.key}`),X=Z.title??Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}let B=Gn(w,"operations",$.inventory);if(B.length>0&&j<n){W.push(" subgraph ops [Operations]");for(let Z of B){if(j>=n)break;let G=v(`O_${Z.key}_v${Z.version}`),X=m?`${Z.key}.v${Z.version}`:Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}let S=Gn(w,"events",$.inventory);if(S.length>0&&j<n){W.push(" subgraph events [Events]");for(let Z of S){if(j>=n)break;let G=v(`E_${Z.key}_v${Z.version}`),X=m?`${Z.key}.v${Z.version}`:Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}let Q=Gn(w,"presentations",$.inventory);if(Q.length>0&&j<n){W.push(" subgraph presentations [Presentations]");for(let Z of Q){if(j>=n)break;let G=v(`P_${Z.key}_v${Z.version}`),X=m?`${Z.key}.v${Z.version}`:Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}for(let Z of w){let G=v(`F_${Z.key}`);for(let X of Z.operations){let Y=v(`O_${X.key}_v${X.version}`);W.push(` ${G} --> ${Y}`)}for(let X of Z.events){let Y=v(`E_${X.key}_v${X.version}`);W.push(` ${G} -.-> ${Y}`)}for(let X of Z.presentations){let Y=v(`P_${X.key}_v${X.version}`);W.push(` ${G} --> ${Y}`)}}if(y)W.push(` note["... and more (truncated at ${n} nodes)"]`);return W.join(`
2302
+ `)}function I6($,b){let{direction:A="TB",showVersions:m=!0,maxNodes:n=50}=b,W=[`flowchart ${A}`],w=new Set,j=new Set,y=new Set;for(let Q of $.features){for(let Z of Q.operations)w.add(`${Z.key}.v${Z.version}`);for(let Z of Q.events)j.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)y.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){W.push(" subgraph features [Features]");for(let Q of $.features){if(B>=n)break;let Z=v(`F_${Q.key}`);W.push(` ${Z}["${y$(Q.title??Q.key)}"]`),B++}W.push(" end")}if($.orphanedSpecs.length>0){W.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=n)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),G=m?`${Q.key}.v${Q.version}`:Q.key;W.push(` ${Z}["${y$(G)}"]`),B++}W.push(" end")}let S=[];for(let Q of w){let[Z,G]=Xn(Q);if(Z&&G)S.push({type:"operation",key:Z,version:G})}for(let Q of j){let[Z,G]=Xn(Q);if(Z&&G)S.push({type:"event",key:Z,version:G})}for(let Q of y){let[Z,G]=Xn(Q);if(Z&&G)S.push({type:"presentation",key:Z,version:G})}if(S.length>0&&B<n){W.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=n)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),G=m?`${Q.key}.v${Q.version}`:Q.key;W.push(` ${Z}["${y$(G)}"]`),B++}W.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let G of Q.operations){let X=v(`operation_${G.key}_v${G.version}`);W.push(` ${Z} --> ${X}`)}for(let G of Q.events){let X=v(`event_${G.key}_v${G.version}`);W.push(` ${Z} -.-> ${X}`)}for(let G of Q.presentations){let X=v(`presentation_${G.key}_v${G.version}`);W.push(` ${Z} --> ${X}`)}}return W.join(`
2303
+ `)}function E6($,b){let{direction:A="TB",showVersions:m=!0,maxNodes:n=50}=b,W=[`flowchart ${A}`],w=0;for(let j of $.features){if(w>=n)break;let y=v(`F_${j.key}`);W.push(` ${y}["${y$(j.title??j.key)}"]`),w++;for(let B of j.operations){if(w>=n)break;let S=v(`O_${B.key}_v${B.version}`),Q=m?`${B.key}.v${B.version}`:B.key;W.push(` ${S}["${y$(Q)}"]`),W.push(` ${y} --> ${S}`),w++}for(let B of j.events){if(w>=n)break;let S=v(`E_${B.key}_v${B.version}`),Q=m?`${B.key}.v${B.version}`:B.key;W.push(` ${S}["${y$(Q)}"]`),W.push(` ${y} -.-> ${S}`),w++}for(let B of j.presentations){if(w>=n)break;let S=v(`P_${B.key}_v${B.version}`),Q=m?`${B.key}.v${B.version}`:B.key;W.push(` ${S}["${y$(Q)}"]`),W.push(` ${y} --> ${S}`),w++}for(let B of j.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);W.push(` ${S} --> ${Q}`)}}return W.join(`
2304
+ `)}function M6($,b){let A=Yn($,b);if($.orphanedSpecs.length===0)return A;let m=A.split(`
2305
+ `);m.push(" subgraph orphaned [Orphaned Specs]");for(let n of $.orphanedSpecs.slice(0,20)){let W=v(`orphan_${n.type}_${n.key}_v${n.version}`),w=`${n.key}.v${n.version}`;m.push(` ${W}["${y$(w)}"]:::orphan`)}return m.push(" end"),m.push(" classDef orphan stroke-dasharray: 5 5"),m.join(`
2306
+ `)}function Gn($,b,A){let m=new Set,n=[];for(let W of $)for(let w of W[b]){let j=`${w.key}.v${w.version}`;if(!m.has(j))m.add(j),n.push(w)}return n}function Xn($){let b=$.match(/^(.+)\.v(\d+)$/);if(!b)return[void 0,void 0];return[b[1],b[2]]}function v($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function y$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as x6,specToMarkdown as I$}from"@contractspec/module.workspace";function cz($,b,A){let m=[];if(A.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))m.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))m.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(A.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))m.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))m.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(b))m.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return m}function dz($,b){let A=[];A.push(`# Verification Report: ${$.meta.key}`),A.push("");let m=b.filter((w)=>w.severity==="error"),n=b.filter((w)=>w.severity==="warning"),W=b.filter((w)=>w.severity==="info");if(A.push("## Summary"),A.push(""),A.push(`- Errors: ${m.length}`),A.push(`- Warnings: ${n.length}`),A.push(`- Info: ${W.length}`),A.push(""),m.length>0){A.push("## Errors"),A.push("");for(let w of m)A.push(`- \u274C **${w.category}**: ${w.message}`);A.push("")}if(n.length>0){A.push("## Warnings"),A.push("");for(let w of n)A.push(`- \u26A0\uFE0F **${w.category}**: ${w.message}`);A.push("")}if(W.length>0){A.push("## Info"),A.push("");for(let w of W)A.push(`- \u2139\uFE0F **${w.category}**: ${w.message}`);A.push("")}return A.join(`
2307
+ `)}async function lz($,b){let A=[];A.push(I$($,"context"));let m=await j$(b),n=async(W)=>{let w=m.find((y)=>y.key===W.name&&y.version===W.version);if(!w)return null;return(await x6(w.filePath)).find((y)=>y.meta.key===W.name)??null};if($.operations?.length){A.push(`
1989
2308
  ## Operations (${$.operations.length})
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})
2309
+ `);for(let W of $.operations){let w=await n(W);if(w)A.push(I$(w,"full"));else A.push(`### ${W.name} (v${W.version})
1991
2310
 
1992
- *Spec not found*`);j.push("---")}}if($.events?.length){j.push(`
2311
+ *Spec not found*`);A.push("---")}}if($.events?.length){A.push(`
1993
2312
  ## Events (${$.events.length})
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})
2313
+ `);for(let W of $.events){let w=await n(W);if(w)A.push(I$(w,"full"));else A.push(`### ${W.name} (v${W.version})
1995
2314
 
1996
- *Spec not found*`);j.push("---")}}if($.presentations?.length){j.push(`
2315
+ *Spec not found*`);A.push("---")}}if($.presentations?.length){A.push(`
1997
2316
  ## Presentations (${$.presentations.length})
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})
1999
-
2000
- *Spec not found*`);j.push("---")}}return j.join(`
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=`
2317
+ `);for(let W of $.presentations){let w=await n(W);if(w)A.push(I$(w,"full"));else A.push(`### ${W.name} (v${W.version})
2318
+
2319
+ *Spec not found*`);A.push("---")}}return A.join(`
2320
+ `)}function T6($,b){let A=[];if(A.push(`# Implementation Guide: ${$.meta.key}`),A.push(""),A.push(`**Target Agent**: ${b}`),A.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),A.push(""),$.meta.description)A.push("## Overview"),A.push(""),A.push($.meta.description),A.push("");if($.meta.goal)A.push("## Goal"),A.push(""),A.push($.meta.goal),A.push("");if($.meta.context)A.push("## Context"),A.push(""),A.push($.meta.context),A.push("");if(A.push("## Implementation Steps"),A.push(""),$.specType==="operation"){if(A.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)A.push("2. Implement input validation according to the schema"),A.push("3. Implement the core business logic"),A.push("4. Return output matching the expected schema");if($.hasPolicy)A.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){A.push("6. Emit events on success:");for(let m of $.emittedEvents)A.push(` - \`${m.name}\` (v${m.version})`)}A.push("7. Add error handling for expected failure cases"),A.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(A.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){A.push("2. Implement operations:");for(let m of $.operations)A.push(` - \`${m.name}\` (v${m.version})`)}if($.presentations&&$.presentations.length>0){A.push("3. Implement presentations:");for(let m of $.presentations)A.push(` - \`${m.name}\` (v${m.version})`)}A.push("4. Wire up feature exports"),A.push("5. Add integration tests")}else A.push("1. Review the spec requirements"),A.push("2. Implement the core logic"),A.push("3. Add tests"),A.push("4. Document the implementation");if(A.push(""),A.push("## Constraints"),A.push(""),A.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)A.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)A.push(`- Tags: ${$.meta.tags.join(", ")}`);if(A.push(""),b==="cursor-cli")A.push("## Cursor Notes"),A.push(""),A.push("- Use Composer mode for multi-file changes"),A.push("- Reference this guide in your cursor rules"),A.push("- Break implementation into small, focused commits");else if(b==="claude-code")A.push("## Claude Code Notes"),A.push(""),A.push("- Use extended thinking for complex logic"),A.push("- Ask for clarification on ambiguous requirements"),A.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")A.push("## General Notes"),A.push(""),A.push("- Use inline comments to guide generation"),A.push("- Review generated code carefully");return A.push(""),A.push("## Spec Definition"),A.push(""),A.push(I$($,"full")),A.join(`
2321
+ `)}function D6($){let b=[];if(b.push(`# ${$.meta.key}`),b.push(""),b.push(`Description: ${$.meta.description??"No description"}`),b.push(""),b.push("## Rules"),b.push(""),$.specType==="operation"){if(b.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)b.push("- Validate input and output against schemas");if($.hasPolicy)b.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)b.push("- Emit documented events")}else if($.specType==="feature")b.push("- Implement all operations and presentations"),b.push("- Follow modular architecture");else b.push(`- Follow ${$.specType} patterns`);return b.push("- Follow project code quality standards"),b.push("- Write tests for new functionality"),b.join(`
2322
+ `)}function tz($,b,A="generic-mcp"){switch(b){case"guide":return T6($,A);case"rules":return D6($);case"prompt":return I$($,"prompt");case"context":return I$($,"context");case"full":default:return I$($,"full")}}import{readFile as N6}from"fs/promises";import{createRequire as F6}from"module";import{dirname as v6,resolve as jy}from"path";import{pathToFileURL as g6}from"url";import wy from"vm";import Hn from"typescript";async function n$($,b={}){let A=jy(process.cwd(),$),m=b.runtime??r6();try{let n=m==="bun"?await k6(A):await P6(A);return{modulePath:A,exports:n}}catch(n){throw Error(By(A,n))}}async function nL($,b){let A=jy(process.cwd(),$);if(!await b.exists(A))return null;return n$(A)}async function y0($,b={}){return(await n$($,b)).exports}async function yy($,b){let A=await y0($);return Sy(A,$,b)}function By($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function Sy($,b,A){if(A.isValue($))return $;for(let m of A.instanceKeys??[])if(A.isValue($[m]))return $[m];for(let m of A.factoryKeys??[]){let n=$[m];if(typeof n!=="function")continue;let W=await n();if(A.isValue(W))return W}throw Error(`${A.description} module ${b} must export a supported instance or factory.`)}async function k6($){return await import(g6($).href)}async function P6($){return await f6($)??{}}function r6(){return typeof globalThis.Bun<"u"?"bun":"node"}var WL={formatModuleLoadError:By,resolveAuthoredModuleValue:Sy};async function f6($){let b=await N6($,"utf-8"),A=Hn.transpileModule(b,{compilerOptions:{module:Hn.ModuleKind.CommonJS,target:Hn.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),m={},n={exports:m},W=F6($),w=wy.createContext({module:n,exports:m,require:W,__dirname:v6($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new wy.Script(A.outputText,{filename:$}).runInContext(w),n.exports}var Hy={};P(Hy,{renderOnboardingGuides:()=>Vn,listOnboardingTracks:()=>B0,getOnboardingTrack:()=>On,createOnboardingConnectArtifacts:()=>e6,buildOnboardingPlan:()=>a6,ONBOARDING_TRACKS:()=>qn});var qn=[{id:"contracts",title:"Contracts",summary:"Author and validate spec-first contracts before implementation.",description:"Use ContractSpec contracts as the durable source of truth for operations, events, presentations, and validation.",reuseFamily:"contracts",adoptionQuery:"contract operation event policy presentation spec-first contracts",primaryDocsRoute:"/docs/getting-started/start-here",secondaryDocsRoutes:["/docs/guides/spec-validation-and-typing","/docs/guides/generate-docs-clients-schemas"],packages:["@contractspec/lib.contracts-spec","@contractspec/lib.schema"],recommendedCommands:["contractspec create --type operation","contractspec generate","contractspec validate","contractspec ci"],starterExample:{key:"minimal",packageRef:"@contractspec/example.minimal",title:"Minimal",summary:"Smallest reference implementation for baseline ContractSpec usage."},connectSurfaces:["cli","contract","runtime"]},{id:"ui-design",title:"UI Design",summary:"Adopt the design system and contract-backed theming flow.",description:"Use ThemeSpec, the design system, and composed UI surfaces instead of ad-hoc theme files or raw primitives.",reuseFamily:"ui",adoptionQuery:"ui design system theme tokens composed controls themes",adoptionPlatform:"web",primaryDocsRoute:"/docs/tech/contracts/themes",secondaryDocsRoutes:["/docs/guides/first-module-bundle","/docs/getting-started/installation"],packages:["@contractspec/lib.design-system","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec create --type theme","contractspec generate","contractspec validate"],starterExample:{key:"data-grid-showcase",packageRef:"@contractspec/example.data-grid-showcase",title:"Data Grid Showcase",summary:"Reference app for composed design-system tables and contract-backed UI rendering."},connectSurfaces:["cli","runtime","ui"]},{id:"knowledge",title:"Knowledge",summary:"Model trusted knowledge spaces, sources, and retrieval flows.",description:"Use knowledge spaces, bindings, and governed retrieval instead of prompt-only context injection.",reuseFamily:"sharedLibs",adoptionQuery:"knowledge spaces sources bindings retrieval canon ingestion assistant",primaryDocsRoute:"/docs/knowledge",secondaryDocsRoutes:["/docs/knowledge/spaces","/docs/knowledge/examples"],packages:["@contractspec/lib.knowledge","@contractspec/lib.ai-agent"],recommendedCommands:["contractspec create --type knowledge","contractspec validate","contractspec connect adoption resolve --family sharedLibs --stdin"],starterExample:{key:"knowledge-canon",packageRef:"@contractspec/example.knowledge-canon",title:"Knowledge Canon",summary:"Minimal contract-first knowledge space example with bindings and source samples."},advancedExample:{key:"policy-safe-knowledge-assistant",packageRef:"@contractspec/example.policy-safe-knowledge-assistant",title:"Policy-Safe Knowledge Assistant",summary:"End-to-end governed knowledge assistant with policy, locale, and learning flows."},connectSurfaces:["cli","knowledge","mcp","runtime"]},{id:"ai-agents",title:"AI Agents",summary:"Define agents, tools, approvals, and MCP-aware execution.",description:"Use the ContractSpec agent runtime and agent specs instead of ad-hoc prompt wrappers.",reuseFamily:"sharedLibs",adoptionQuery:"ai agent tools approvals mcp orchestration unified agent runtime",primaryDocsRoute:"/docs/libraries/ai-agent",secondaryDocsRoutes:["/docs/advanced/mcp","/docs/getting-started/cli"],packages:["@contractspec/lib.ai-agent","@contractspec/lib.contracts-spec"],recommendedCommands:["contractspec create --type agent","contractspec agent export --spec <path> --format opencode","contractspec validate"],starterExample:{key:"agent-console",packageRef:"@contractspec/example.agent-console",title:"Agent Console",summary:"Reference autonomous-agent workspace with runs, tools, metrics, and replay."},connectSurfaces:["agent","cli","mcp","runtime"]},{id:"learning-journey",title:"Learning Journey",summary:"Guide users through milestones, progression, and adaptive journeys.",description:"Use the learning-journey module and example family for structured onboarding and progression flows.",reuseFamily:"solutions",adoptionQuery:"learning journey onboarding progression coaching drills guided wizard",primaryDocsRoute:"/docs/guides/first-module-bundle",secondaryDocsRoutes:["/docs/getting-started/start-here"],packages:["@contractspec/module.learning-journey","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec examples list --query learning-journey","contractspec validate","contractspec doctor"],starterExample:{key:"learning-journey-ui-onboarding",packageRef:"@contractspec/example.learning-journey-ui-onboarding",title:"Learning Journey UI Onboarding",summary:"Checklist- and journey-map-based onboarding mini app."},advancedExample:{key:"learning-journey-registry",packageRef:"@contractspec/example.learning-journey-registry",title:"Learning Journey Registry",summary:"Registry and template aggregation surface for broader learning-journey compositions."},connectSurfaces:["cli","runtime","solution"]}];function B0(){return qn}function On($){return qn.find((b)=>b.id===$)}function Vn($){return{agentGuide:h6($),humanGuide:d6($)}}function h6($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let A of $.recommendations)b.push(...c6(A.track,A.reason));return b.join(`
2323
+ `)}function c6($,b){let A=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let m of $.recommendedCommands)A.push(`- \`${m}\``);return[...A,""]}function d6($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((A,m)=>`${m+1}. \`${A}\``),"","## Track Guide",""];for(let A of $.recommendations)b.push(...u6(A.track,A.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let A of $.builderNextSteps)b.push(`- \`${A}\``);b.push("")}return b.join(`
2324
+ `)}function u6($,b){let A=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)A.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(A.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)A.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);A.push("","Commands:");for(let m of $.recommendedCommands)A.push(`- \`${m}\``);return A.push("",`Packages: ${$.packages.map((m)=>`\`${m}\``).join(", ")}`,""),A}import{buildContext as o6}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as i6}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as l6}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function Qy($,b,A,m){let n=o6({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:A,workspaceId:m}),W=await i6(l6(t6(b)),n);return{journeyContext:n,journeyPlan:W}}function Zy($){if(!$||$.length===0)return[...B0()];return $.map((b)=>{let A=On(b);if(!A)throw Error(`Unknown onboarding track: ${b}`);return A})}function Gy($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function Xy($){switch($){case"managed":return["contractspec builder status"];case"local":case"hybrid":return["contractspec builder status","contractspec builder local status"];case"none":default:return["contractspec init --preset builder-managed","contractspec init --preset builder-local","contractspec init --preset builder-hybrid"]}}function Yy($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let A of B0()){if(A.starterExample.key===b)return A.starterExample;if(A.advancedExample?.key===b)return A.advancedExample}return}function Jn($,b){return p6($,b.flatMap((A)=>A.track.connectSurfaces))}function t6($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((A)=>({defaultSurface:A.id,path:`/onboard/${A.id}`,routeId:`onboard-${A.id}`})),surfaces:Object.fromEntries($.map((A)=>[A.id,{commands:A.recommendedCommands.map((m,n)=>({commandId:`${A.id}-${n}`,intent:`Run ${m}`,title:m})),data:[{hydrateInto:"track",recipeId:`track-${A.id}`,source:{entityType:`onboarding.${A.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${A.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:A.id,title:A.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function p6($,b){return[...new Set([...$,...b])].sort()}async function a6($,b={}){let A=await l$($.fs,b),m=Zy(b.selectedTracks),n=Gy(A.config),w=[...await Promise.all(m.map(async(X)=>{let Y=await Xb($,{config:A.config,cwd:A.cwd,family:X.reuseFamily,packageRoot:A.packageRoot,platform:X.adoptionPlatform,query:X.adoptionQuery,workspaceRoot:A.workspaceRoot});return{reason:Y.reason,resolution:Y,score:Y.selected?.score??0,selected:!1,track:X}}))].sort((X,Y)=>Y.score-X.score).map((X,Y)=>({...X,selected:Y===0})),j=w[0]?.track;if(!j)throw Error("No onboarding tracks are available.");let{journeyContext:y,journeyPlan:B}=await Qy(j,m,A.workspaceRoot,A.packageRoot),S=Yy(j,b.forcedExampleKey)??j.starterExample,Q=s6(["contractspec onboard",...j.recommendedCommands,"contractspec doctor"]),Z=Xy(n),G={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:n,builderNextSteps:Z,config:A.config,cwd:A.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:y,journeyPlan:B,nextCommands:Q,packageRoot:A.packageRoot,primaryTrack:j,recommendations:w,selectedExample:S,workspaceRoot:A.workspaceRoot};return{...G,guides:Vn(G)}}async function e6($,b){if(!b.config.connect?.enabled)return;let A=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,m=[b.agentGuidePath,b.humanGuidePath],n=await Tb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:m,taskId:A,workspaceRoot:b.workspaceRoot}),W=await gb($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((w)=>w.track.id).join(", ")}`,steps:b.recommendations.map((w)=>({commands:w.track.recommendedCommands,paths:m,summary:`Adopt ${w.track.title}`})),touchedPaths:m},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:m,taskId:A,workspaceRoot:b.workspaceRoot});return{contextPack:{...n,affectedSurfaces:Jn(n.affectedSurfaces,b.recommendations)},planPacket:{...W.planPacket,affectedSurfaces:Jn(W.planPacket.affectedSurfaces,b.recommendations)}}}function s6($){return[...new Set($)]}var qy=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],$7=[...qy,{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 Kn($){return $==="minimal"?qy:$7}function _n($){return $.filter((b)=>!b.dev)}function Un($){return $.filter((b)=>b.dev)}import{exec as b7}from"child_process";import{promisify as A7}from"util";var m7=A7(b7),n7={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function IL($,b,A=n7){let m=Kn(b.mode),n=_n(m),W=Un(m),w=[],j=[],y=[],B=$.join(b.workspaceRoot,"package.json");if(!await $.exists(B))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 Q=await $.readFile(B),Z=JSON.parse(Q),G=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),X=o$(b.workspaceRoot),Y=n.filter((J)=>{if(G.has(J.name)&&!b.force)return j.push({name:J.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),V=W.filter((J)=>{if(G.has(J.name)&&!b.force)return j.push({name:J.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let J=[...Y,...V];return{success:!0,installed:J.map((_)=>({name:_.name,action:"installed",message:`Would install: ${_.description}`,dev:_.dev})),skipped:j,errors:[],summary:`Dry run: would install ${J.length} package(s), skip ${j.length}.`}}if(!b.skipPrompts&&(Y.length>0||V.length>0)){let J=Y.length+V.length;if(!await A.confirm(`Install ${J} package(s) using ${X}?`))return{success:!0,installed:[],skipped:[...j,...Y.map((H)=>({name:H.name,action:"skipped",message:"User cancelled"})),...V.map((H)=>({name:H.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(Y.length>0){let J=await Oy(Y,X,b.workspaceRoot,!1);for(let _ of J)if(_.action==="installed")w.push(_);else y.push(_)}if(V.length>0){let J=await Oy(V,X,b.workspaceRoot,!0);for(let _ of J)if(_.action==="installed")w.push(_);else y.push(_)}let O=y.length===0,K=O?`Successfully installed ${w.length} package(s), skipped ${j.length}.`:`Installed ${w.length}, skipped ${j.length}, failed ${y.length}.`;return{success:O,installed:w,skipped:j,errors:y,summary:K}}async function Oy($,b,A,m){let n=[],W=$.map((w)=>w.version?`${w.name}@${w.version}`:w.name);try{let j=`${VW(b,m)} ${W.join(" ")}`;await m7(j,{cwd:A,timeout:120000});for(let y of $)n.push({name:y.name,action:"installed",message:y.description,dev:m})}catch(w){let j=w instanceof Error?w.message:String(w);for(let y of $)n.push({name:y.name,action:"error",message:`Failed to install: ${j}`,dev:m})}return n}async function EL($,b){let A=$.join(b,"package.json");try{let m=await $.readFile(A),n=JSON.parse(m);return"@contractspec/lib.contracts-spec"in{...n.dependencies,...n.devDependencies}}catch{return!1}}function ML($){let b=Kn($),A=[];A.push(`ContractSpec ${$} installation:`),A.push("");let m=_n(b);if(m.length>0){A.push("Dependencies:");for(let W of m)A.push(` \u2022 ${W.name} - ${W.description}`)}let n=Un(b);if(n.length>0){A.push(""),A.push("Dev Dependencies:");for(let W of n)A.push(` \u2022 ${W.name} - ${W.description}`)}return A.join(`
2325
+ `)}import{RegeneratorService as W7}from"@contractspec/lib.contracts-spec/regenerator";function gL($){return new W7({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class S0{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,A;try{A=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(m){throw Error(`Registry request failed: ${b} (${m instanceof Error?m.message:String(m)})`)}if(!A.ok){let m=await A.text().catch(()=>"");throw Error(`Registry request failed: ${A.status} ${A.statusText} ${m}`)}return await A.json()}}function zn($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function PL($,b,A){let{logger:m}=A,n=zn(b.registryUrl);m.info(`Adding spec to registry: ${$}`,{registryUrl:n}),await new S0({registryUrl:n}).getJson(`/specs/add?path=${encodeURIComponent($)}`),m.info("Spec added to registry successfully")}async function rL($,b){let{logger:A}=b,m=zn($.registryUrl);A.info("Listing specs from registry",{registryUrl:m});let n=new S0({registryUrl:m}),W=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",w=await n.getJson(`/specs${W}`);return A.info(`Found ${w.length} specs`),w}async function fL($,b,A){let{logger:m}=A,n=zn(b.registryUrl);m.info(`Searching registry: ${$}`,{registryUrl:n});let w=await new S0({registryUrl:n}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return m.info(`Found ${w.length} results`),w}class w7{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:A}=$,m=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${m.join(", ")}...`);try{let n=this.fs.join(A,b.rulesDir??".rules");if(!await this.fs.exists(n))return{success:!1,files:[],errors:[`Rules directory not found: ${n}`]};let w=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${w}`);let j=[];for(let y of m){let B=this.getTargetFileName(y);if(B){let S=this.fs.join(A,B);j.push(S)}}return{success:!0,files:j,logs:[`Successfully synchronized rules to ${j.length} targets.`]}}catch(n){let W=n instanceof Error?n.message:String(n);return this.logger.error(`Rule synchronization failed: ${W}`),{success:!1,files:[],errors:[W]}}}async generateConfig($){let{config:b}=$,A={rules:(b.rules??[]).map((m)=>this.fs.join(b.rulesDir??".rules",m)),targets:$.targets||b.targets};return JSON.stringify(A,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}}}function Q0($,b,A,m){let n=ub(b,A),W=j7(A);if(W.test($))return $.replace(W,n);if(m&&Ln($)===Ln(m))return n;return`${n}${$}`}function ub($,b){let A=Ln($);return`${b.startMarker}
2326
+ ${b.note}
2327
+ ${A}
2328
+ ${b.endMarker}
2329
+ `}function Ln($){return $.replace(/\r\n/g,`
2330
+ `).trimEnd()}function j7($){return new RegExp(`${Vy($.startMarker)}[\\s\\S]*?${Vy($.endMarker)}(?:\\r?\\n)?`)}function Vy($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var y7="<!-- contractspec:init:agents:start -->",B7="<!-- contractspec:init:agents:end -->",S7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Jy={endMarker:B7,note:S7,startMarker:y7};async function Rn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"AGENTS.md");try{let W=await $.exists(n),w=fw(b);if(W){let j=await $.readFile(n);if(b.interactive){if(!await A.confirm(`${n} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:n,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(n,Q0(j,w,Jy,w)),{target:"agents-md",filePath:n,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(n,ub(w,Jy)),{target:"agents-md",filePath:n,action:"created",message:"Created AI agent guide"}}catch(W){return{target:"agents-md",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}import{generateArtifactsForAudience as Q7,generateBiomePreset as Z7}from"@contractspec/biome-config";async function Cn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"biome.jsonc"),W=$.join(m,".contractspec","biome"),w=$.join(W,"plugins"),j=$.join(W,"ai"),y=Q7("consumer");try{let B=await $.exists(n);if(B&&b.interactive){if(!await A.confirm(`${n} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:n,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(w),await $.mkdir(j),await $.writeFile(n,Z7("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(y.plugins))await $.writeFile($.join(w,S),Q);return await $.writeFile($.join(j,"consumer.md"),y.aiRules),{target:"biome-config",filePath:n,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:n,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function In($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,".contractsrc.json");try{let W=await $.exists(n),w=bb(b);if(W){let j=await $.readFile(n),y=p(j);if(!y)return{target:"cli-config",filePath:n,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${n} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:n,action:"skipped",message:"User skipped merge"}}let B=$$(y,w);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof w==="object"&&w!==null){let S={};if("connect"in w)S.connect=w.connect;if("builder"in w)S.builder=w.builder;await $.writeFile(n,N(Vm(B,S)))}else await $.writeFile(n,N(B));return{target:"cli-config",filePath:n,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(n,N(w)),{target:"cli-config",filePath:n,action:"created",message:"Created CLI configuration"}}catch(W){return{target:"cli-config",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function En($,b,A){let m=$.join(b.workspaceRoot,".cursor","rules"),n=$.join(m,"contractspec.mdc");try{let W=$.join(b.workspaceRoot,".cursor");if(!await $.exists(W))await $.mkdir(W);if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(n),j=rw(b);if(w)if(b.interactive){if(!await A.confirm(`${n} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:n,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:n,action:"skipped",message:"File already exists"};return await $.writeFile(n,j),{target:"cursor-rules",filePath:n,action:w?"merged":"created",message:w?"Updated Cursor rules":"Created Cursor rules"}}catch(W){return{target:"cursor-rules",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function Mn($,b,A){let m=gA();try{let n=await $.exists(m),W=Pw();if(b.interactive){if(!await A.confirm(`Configure Claude Desktop at ${m}?`))return{target:"mcp-claude",filePath:m,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(n){let y=await $.readFile(m),B=p(y);if(!B)return{target:"mcp-claude",filePath:m,action:"error",message:"Existing file is not valid JSON"};let S=$$(B,W);return await $.writeFile(m,N(S)),{target:"mcp-claude",filePath:m,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let w=m.substring(0,m.lastIndexOf("/"));if(!await $.exists(w))await $.mkdir(w);return await $.writeFile(m,N(W)),{target:"mcp-claude",filePath:m,action:"created",message:"Created Claude Desktop configuration"}}catch(n){return{target:"mcp-claude",filePath:m,action:"error",message:n instanceof Error?n.message:"Unknown error"}}}async function xn($,b,A){let m=$.join(b.workspaceRoot,".cursor"),n=$.join(m,"mcp.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(n),j=Lb();if(w){let y=await $.readFile(n),B=p(y);if(!B)return{target:"mcp-cursor",filePath:n,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${n} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:n,action:"skipped",message:"User skipped merge"}}let S=$$(B,j);return await $.writeFile(n,N(S)),{target:"mcp-cursor",filePath:n,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(n,N(j)),{target:"mcp-cursor",filePath:n,action:"created",message:"Created Cursor MCP configuration"}}catch(W){return{target:"mcp-cursor",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var G7="<!-- contractspec:init:usage:start -->",X7="<!-- contractspec:init:usage:end -->",Y7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Ky={endMarker:X7,note:Y7,startMarker:G7};async function Tn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"USAGE.md");try{let W=await $.exists(n),w=hw(b);if(W){let j=await $.readFile(n);if(b.interactive){if(!await A.confirm(`${n} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:n,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(n,Q0(j,w,Ky,w)),{target:"usage-md",filePath:n,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(n,ub(w,Ky)),{target:"usage-md",filePath:n,action:"created",message:"Created usage guide"}}catch(W){return{target:"usage-md",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function Dn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,".vscode"),W=$.join(n,"settings.json");try{if(!await $.exists(n))await $.mkdir(n);let j=await $.exists(W),y=vA(b);if(j){let B=await $.readFile(W),S=p(B);if(!S)return{target:"vscode-settings",filePath:W,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${W} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:W,action:"skipped",message:"User skipped merge"}}let Q=$$(S,y);if("contractspec.api.baseUrl"in y)Q["contractspec.api.baseUrl"]=y["contractspec.api.baseUrl"];return await $.writeFile(W,N(Q)),{target:"vscode-settings",filePath:W,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(W,N(y)),{target:"vscode-settings",filePath:W,action:"created",message:"Created VS Code settings"}}catch(w){return{target:"vscode-settings",filePath:W,action:"error",message:w instanceof Error?w.message:"Unknown error"}}}var H7={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((A)=>A.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((A)=>A.selected!==!1).map((A)=>A.value),input:async($,b)=>b??""};async function IR($,b,A=H7){let m=[],n=b.targets.length>0?b.targets:_b,W=b.workspaceRoot,w=M(W),j=b.packageRoot??r(W),y=b.isMonorepo??Gb(w),B=b.packageName??(y?T$(j):void 0),S=await _y($,[j,w]),Q=b.preset??zb(S);if(b.interactive&&!b.preset)Q=await A.select("Select initialization preset:",Tw.map((C)=>({value:C,label:Dw[C],description:Nw[C],selected:C===Q})));let Z=b.scope??"workspace",G=j!==w;if(y&&b.interactive&&G)Z=await A.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${B??j})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${w})`,description:"Create config files at the workspace root"}]);let X=y&&Z==="package"?j:w,Y=await _y($,[X]),V={...b,workspaceRoot:w,packageRoot:j,isMonorepo:y,scope:Z,packageName:B,preset:Q,builderApiBaseUrl:b.builderApiBaseUrl??Y?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??Y?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??Y?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??Y?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??Y?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??Y?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??Y?.connect?.studio?.queue},O=Fw(Q,n);if(b.interactive)O=await A.multiSelect("Select components to configure:",_b.map((C)=>({value:C,label:xw[C],selected:O.includes(C)})));let K=V.projectName;if(b.interactive&&!K){let C=Z==="package"&&B?B:X.split("/").pop()??"my-project";K=await A.input("Project name:",C)}let J=V.builderApiBaseUrl;if(b.interactive&&Q.startsWith("builder-"))J=await A.input("Builder API base URL:",J??"https://api.contractspec.io");let{builderLocalRuntimeId:_,builderLocalGrantedTo:H}=V;if(b.interactive&&(Q==="builder-local"||Q==="builder-hybrid"))_=await A.input("Default local runtime target id:",_??"rt_local_daemon"),H=await A.input("Default local runtime grant target:",H??"local:operator");let q={...V,projectName:K,targets:O,builderApiBaseUrl:J,builderLocalRuntimeId:_,builderLocalGrantedTo:H};for(let C of O){let F=await q7($,C,q,A);m.push(F)}let U=await sA($,{behavior:q.gitignoreBehavior,interactive:q.interactive,patterns:kw({preset:Q}),prompts:A,root:w});if(q.gitignoreBehavior!=="skip"||U.action!=="skipped")m.push(U);let z=m.filter((C)=>C.action!=="error").length,L=m.filter((C)=>C.action==="error").length,I=y?` (${Z} level)`:"";return{success:L===0,preset:Q,files:m,summary:`Setup complete${I}: ${z} configured, ${L} failed.`,nextSteps:gw(q)}}async function q7($,b,A,m){switch(b){case"agents-md":return Rn($,A,m);case"cli-config":return In($,A,m);case"biome-config":return Cn($,A,m);case"vscode-settings":return Dn($,A,m);case"mcp-cursor":return xn($,A,m);case"mcp-claude":return Mn($,A,m);case"cursor-rules":return En($,A,m);case"usage-md":return Tn($,A,m);default:return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}}async function _y($,b){for(let A of b){let m=$.join(A,".contractsrc.json");if(!await $.exists(m))continue;let n=p(await $.readFile(m));if(n)return n}return null}import{validateBlueprint as O7}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as V7}from"path";async function cR($,b){let{fs:A}=b,m=V7(process.cwd(),$);if(!await A.exists(m))return{valid:!1,errors:[`Blueprint file not found: ${m}`]};try{let n=await n$(m),W=J7(n.exports),w=O7(W);return{spec:W,report:w,valid:w.valid,errors:w.errors.map((j)=>`[${j.code}] ${j.path}: ${j.message}`)}}catch(n){return{valid:!1,errors:[n instanceof Error?n.message:String(n)]}}}function J7($){let b=Object.values($).filter(K7);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function K7($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as _7,dirname as Nn,join as ob}from"path";async function iR($,b,A,m,n){let{fs:W}=n,w=m.implementationPath;if(!w){let S=Nn($),Q=_7($,".ts"),Z=[ob(S,Q.replace(".contracts",".handler")+".ts"),ob(S,Q.replace(".presentation","")+".tsx"),ob(S,Q.replace(".form",".form")+".tsx"),ob(Nn(S),"handlers",Q.replace(".contracts",".handler")+".ts"),ob(Nn(S),"components",Q.replace(".presentation","")+".tsx")];for(let G of Z)if(await W.exists(G)){w=G;break}}if(!w||!await W.exists(w))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let j=await W.readFile(w),B=await new BA(A).validate(b,j);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as U7,validateBuilderReadinessReport as z7,validateBuilderWorkspace as L7,validateBuilderWorkspaceSnapshot as R7}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as C7,validateExternalPatchProposal as I7,validateProviderRoutingPolicy as E7,validateRuntimeTarget as M7}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as x7,validateLayoutSlots as T7}from"@contractspec/lib.surface-runtime/spec";async function sR($,b){if(!g7($.specType))return{valid:!0,errors:[],warnings:[]};let A=i7($.filePath),m=[`${A}/package.json`,`${A}/README.md`,`${A}/src/index.ts`,$.filePath],n=[];for(let j of m)if(!await b.exists(j))n.push(`Missing package scaffold file: ${j}`);if(n.length>0)return{valid:!1,errors:n,warnings:[]};let W;try{W=(await n$($.filePath)).exports}catch(j){return{valid:!1,errors:[j instanceof Error?j.message:String(j)],warnings:[]}}let w=$.specType==="module-bundle"?D7(W):$.specType==="builder-spec"?N7(W):F7(W);return{valid:n.length===0&&w.errors.length===0,errors:[...n,...w.errors],warnings:w.warnings.map((j)=>`[${$.filePath}] ${j}`)}}function D7($){let b=[],A=[],m=v7($,k7);if(m.length===0)return A.push(Fn("module-bundle","bundle")),{errors:b,warnings:A};for(let n of m){let W=Object.values(n.value.surfaces);for(let w of W){try{T7(w)}catch(j){b.push(`[${n.exportName}] ${j instanceof Error?j.message:String(j)}`)}for(let j of x7(w).warnings)A.push(`[${n.exportName}] ${j}`)}}return{errors:b,warnings:A}}function N7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(P7(W)){m+=1,b.push(...Z0(n,L7(W)));continue}if(r7(W)){m+=1,b.push(...Z0(n,U7(W)));continue}if(f7(W)){m+=1,b.push(...Z0(n,z7(W)));continue}if(h7(W))m+=1,b.push(...Z0(n,R7(W)))}if(m===0)A.push(Fn("builder-spec","builder"));return{errors:b,warnings:A}}function F7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(c7(W)){m+=1,b.push(...G0(n,M7(W)));continue}if(d7(W)){m+=1,b.push(...G0(n,E7(W)));continue}if(u7(W)){m+=1,b.push(...G0(n,C7(W)));continue}if(o7(W))m+=1,b.push(...G0(n,I7(W)))}if(m===0)A.push(Fn("provider-spec","provider"));return{errors:b,warnings:A}}function v7($,b){return Object.entries($).filter(([A,m])=>A!=="__esModule"&&b(m)).map(([A,m])=>({exportName:A,value:m}))}function Z0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function G0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function g7($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function k7($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function P7($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function r7($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function f7($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function h7($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function c7($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function d7($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function u7($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function o7($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function i7($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Fn($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as l7}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as t7}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as p7}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as a7}from"@contractspec/module.workspace";async function zy($,b={}){let A=[],m=[],n;if(!b.skipStructure){n=a7($),A.push(...n.errors),m.push(...n.warnings);let W=await e7($);A.push(...W.errors),m.push(...W.warnings)}return{valid:A.length===0,structureResult:n,errors:A,warnings:m,code:$.sourceBlock}}async function jC($,b={}){return Promise.all($.map(async(A)=>({spec:A,...await zy(A,b)})))}async function d$($,b,A={}){let{fs:m}=b;if(!await m.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let W=await m.readFile($),w=[],j=[],y=void 0;if(!A.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await zy(S,A);y=Q.structureResult,w.push(...Q.errors),j.push(...Q.warnings)}}return{valid:w.length===0,structureResult:y,errors:w,warnings:j,code:W}}async function yC($,b,A={}){let m=new Map;for(let n of $){let W=await d$(n,b,A);m.set(n,W)}return m}async function e7($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await n$($.filePath);if($.specType==="app-config"){let n=s7(b.exports,$),W=l7(n);return{errors:W.errors.map((w)=>Uy(w)),warnings:[...W.warnings,...W.info].map((w)=>Uy(w))}}if($.specType==="feature"){let n=$Z(b.exports,$),W=t7(n);return{errors:W.issues.filter((w)=>w.level==="error").map((w)=>X0(w)),warnings:W.issues.filter((w)=>w.level!=="error").map((w)=>X0(w))}}let A=bZ(b.exports,$),m=p7(A);return{errors:m.issues.filter((n)=>n.level==="error").map((n)=>X0(n)),warnings:m.issues.filter((n)=>n.level!=="error").map((n)=>X0(n))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function s7($,b){return vn($,b.exportName,AZ)}function $Z($,b){return vn($,b.exportName,mZ)}function bZ($,b){return vn($,b.exportName,nZ)}function vn($,b,A){if(b&&A($[b]))return $[b];let m=Object.values($).find(A);if(!m)throw Error("Expected authored module to export a compatible spec value.");return m}function AZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function mZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function nZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function Uy($){let b=$.code?`[${$.code}] `:"",A=$.path?`${$.path}: `:"";return`${b}${A}${$.message}`}function X0($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as WZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as kn}from"fs/promises";import{resolve as Y0}from"path";async function XC($,b,A,m){let{fs:n}=m,W=Y0(process.cwd(),b);if(!await n.exists(W))return{valid:!1,errors:[`Tenant config file not found: ${W}`]};try{let w=await wZ(W),j=await jZ(A.connections,n),y=await yZ(A.translationCatalog,n),B=await BZ(A.integrationRegistrars),S={};if(j.length>0)S.tenantConnections=j;if(y)S.translationCatalogs={blueprint:[y],platform:[]};if(B)S.integrationSpecs=B;let Q=WZ($,w,S);return{config:w,report:Q,valid:Q.valid,errors:Q.errors.map((Z)=>`[${Z.code}] ${Z.path}: ${Z.message}`)}}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)]}}}async function wZ($){if($.endsWith(".json")){let m=await kn($,"utf-8"),n=JSON.parse(m);if(!Ly(n))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return n}let b=await n$($),A=Object.values(b.exports).filter(Ly);if(A.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return A[0]}function Ly($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function Ey($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((A)=>A.trim()).filter(Boolean)}async function jZ($,b){let A=Ey($);if(!A.length)return[];let m=[];for(let n of A){let W=Y0(process.cwd(),n);if(!await b.exists(W)){console.warn(`Warning: Connection file not found: ${W}`);continue}if(W.endsWith(".json")){let j=await kn(W,"utf-8"),y=JSON.parse(j);m.push(...gn(y));continue}let w=await n$(W);m.push(...gn(w.exports))}return m}function gn($){if(Array.isArray($)){let b=$.filter(Ry);if(b.length)return b}if(Ry($))return[$];if($&&typeof $==="object"){let A=Object.values($).flatMap((m)=>gn(m));if(A.length)return A}return[]}function Ry($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function yZ($,b){if(!$)return;let A=Y0(process.cwd(),$);if(!await b.exists(A))return;if(A.endsWith(".json")){let W=await kn(A,"utf-8"),w=JSON.parse(W);if(Cy(w))return Iy(w);return}let m=await n$(A),n=Object.values(m.exports).filter(Cy);if(n.length===0)return;return Iy(n[0])}function Cy($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function Iy($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function BZ($){let b=Ey($);if(!b.length)return;let{IntegrationSpecRegistry:A}=await import("@contractspec/lib.contracts-integrations"),m=new A;for(let n of b){let{modulePath:W,exportName:w}=SZ(n);if(!W)continue;let j=Y0(process.cwd(),W);try{let y=await n$(j),B=QZ(y.exports,w);if(B)await B(m)}catch(y){console.warn(`Failed to load registrar from ${j}: ${y}`)}}return m}function SZ($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),m=b?.trim()??null,n=A?.trim();return{modulePath:m,exportName:n}}function QZ($,b){if(b){let A=$[b];if(typeof A==="function")return A;return}if(typeof $.default==="function")return $.default;for(let A of Object.values($))if(typeof A==="function")return A;return}async function LC($,b,A={},m){let{fs:n,logger:W}=$,w=await n.glob({pattern:A.pattern}),j=A.outputDirs?.length?A.outputDirs:[void 0],y=[],B=m?.validate??((Q)=>d$(Q,{fs:n,logger:W})),S=m?.build??((Q,Z)=>$b(Q,{fs:n,logger:W},Z?{...b,outputDir:Z}:b,{...A.buildOptions??{},outputDir:Z}));for(let Q of w)for(let Z of j){let G={specPath:Q,outputDir:Z};if(A.validate)try{G.validation=await B(Q)}catch(X){G.error={phase:"validate",message:X instanceof Error?X.message:String(X)},y.push(G);continue}if(!A.dryRun)try{G.build=await S(Q,Z)}catch(X){G.error={phase:"build",message:X instanceof Error?X.message:String(X)},y.push(G);continue}else W.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});y.push(G)}return{specs:w,runs:y}}import{generateText as ZZ}from"ai";var GZ=`
2011
2331
  You are an expert software test engineer specializing in ContractSpec.
2012
2332
  Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
2013
2333
 
@@ -2025,7 +2345,7 @@ Generate scenarios covering:
2025
2345
  - Happy path (valid input, successful execution)
2026
2346
  - Edge cases (boundary values, optional fields)
2027
2347
  - Error cases (invalid input, business rule violations)
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=`
2348
+ `.trim();class XZ{logger;defaultModel;constructor($,b){this.logger=$;this.defaultModel=b}async generateTests($,b={}){let A=b.model??this.defaultModel;if(!A)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let m=`
2029
2349
  Generate a TestSpec for the following Operation:
2030
2350
 
2031
2351
  \`\`\`json
@@ -2034,23 +2354,23 @@ ${JSON.stringify($,null,2)}
2034
2354
 
2035
2355
  The output must be a valid JSON object conforming to the TestSpec interface.
2036
2356
  Do not include markdown formatting or explanations, just the JSON.
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(`
2357
+ `.trim();try{let{text:n,usage:W}=await ZZ({model:A,system:GZ,prompt:m});this.logUsage(W);let w=this.parseResponse(n);return this.enrichSpec(w,$)}catch(n){throw this.logger.error("Failed to generate tests",{error:n}),n}}parseResponse($){try{let b=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(b)}catch(b){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,b){let A={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},m={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:A,target:m,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let b=$;this.logger.debug(`AI Usage: ${b.promptTokens} prompt + ${b.completionTokens} completion = ${b.totalTokens} total tokens`)}}import{OperationSpecRegistry as My}from"@contractspec/lib.contracts-spec";import{TestRunner as xy}from"@contractspec/lib.contracts-spec/tests";import{resolve as Pn}from"path";async function DC($,b){let A=new xy({registry:b}),m=[],n=0,W=0;for(let w of $){let j=await A.run(w);m.push(j),n+=j.passed,W+=j.failed}return{results:m,passed:n,failed:W}}async function NC($,b,A){let{logger:m}=A,n;if(b.registry)n=await HZ(Pn(b.registry));else n=new My,m.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let W=new xy({registry:n}),w=[],j=!0;for(let y of $)try{let B=Pn(y),S=await y0(B),Q=Ty(S);if(Q.length===0){m.warn(`No TestSpec exports found in ${y}`);continue}for(let Z of Q){m.info(`Running ${Z.meta.key}...`);let G=await W.run(Z);if(w.push(G),G.failed>0)j=!1,m.error(`${Z.meta.key} failed (${G.failed}/${G.scenarios.length})`);else m.info(`${Z.meta.key} passed (${G.passed}/${G.scenarios.length})`)}}catch(B){m.error(`Failed to load/run spec ${y}: ${B instanceof Error?B.message:String(B)}`),j=!1}return{results:w,passed:j}}async function FC($,b){let A=[];for(let m of $)try{let n=Pn(m),W=await y0(n),w=Ty(W);A.push(...w)}catch(n){b.logger.warn(`Failed to load tests from ${m}: ${n instanceof Error?n.message:String(n)}`)}return A}function Ty($){let b=[];for(let A of Object.values($))if(YZ(A))b.push(A);return b}function YZ($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function HZ($){return yy($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof My,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as ib}from"@contractspec/module.workspace";import{IndentationText as qZ,Node as jb,Project as OZ,QuoteKind as VZ,SyntaxKind as JZ}from"ts-morph";function KZ($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function cC($,b,A={}){let{fs:m,logger:n}=b;if(!await m.exists($))return{specPath:$,specInfo:KZ($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let w=await m.readFile($),j;if(A.content!==void 0)j=A.content;else if(A.fields?.length)j=_Z(w,A.fields);else return{specPath:$,specInfo:ib(w,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!A.skipValidation){await m.writeFile($,j);let y=await d$($,b);if(y.errors.length>0)return await m.writeFile($,w),{specPath:$,specInfo:ib(j,$),updated:!1,errors:y.errors,warnings:y.warnings};if(y.warnings.length>0&&!A.allowWarnings)return await m.writeFile($,w),{specPath:$,specInfo:ib(j,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:y.warnings};return n.info(`Updated spec: ${$}`),{specPath:$,specInfo:ib(j,$),updated:!0,errors:[],warnings:y.warnings}}return await m.writeFile($,j),n.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:ib(j,$),updated:!0,errors:[],warnings:[]}}function _Z($,b){let m=new OZ({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:qZ.TwoSpaces,quoteKind:VZ.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),n=zZ(m);if(!n)return $;for(let W of b)UZ(n,W);return m.getFullText()}function UZ($,b){let A=b.key.split(".").map((j)=>j.trim()).filter(Boolean);if(A.length===0)return;let m=$;for(let j of A.slice(0,-1)){if(!m.getProperty(j))m.addPropertyAssignment({name:j,initializer:"{}"});let B=m.getPropertyOrThrow(j);if(!jb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!jb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(JZ.ObjectLiteralExpression);if(!Q)return;m=Q}let n=A[A.length-1];if(!n)return;let W=LZ(b.value),w=m.getProperty(n);if(w&&jb.isPropertyAssignment(w)){w.setInitializer(W);return}m.addPropertyAssignment({name:n,initializer:W})}function zZ($){for(let b of $.getVariableDeclarations()){let A=b.getInitializer();if(!A)continue;if(jb.isObjectLiteralExpression(A))return A;if(jb.isCallExpression(A)){let m=A.getArguments()[0];if(m&&jb.isObjectLiteralExpression(m))return m}}return}function LZ($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var ly={};P(ly,{getPackageUpgradeCommand:()=>hy,getDefaultVersioningConfig:()=>q0,getDefaultHooksConfig:()=>O0,applyGuidedUpgrade:()=>iy,applyConfigUpgrades:()=>fy,analyzeUpgrades:()=>H0,analyzeGuidedUpgrade:()=>cn});import{GeneratedReleaseManifestSchema as uy}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as NZ,DEFAULT_CONTRACTSRC as FZ}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function Dy($){return $.packages.map((b)=>{let A=b.version?`@${b.version}`:"";return`- ${b.name}${A} (${b.releaseType})`})}function Ny($){return $.map((b)=>` - ${b}`)}function rn($,b){return $.audiences.filter((A)=>b.includes(A.kind)).map((A)=>`- ${RZ(A.kind)}: ${A.summary}`)}function Fy($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...Dy($),...rn($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));return b.join(`
2358
+ `)}function vy($){let b=[`### ${$.summary}`,...Dy($),...rn($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`);return b.join(`
2359
+ `)}function gy($){let b=[`### ${$.summary}`,...rn($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
2360
+ `);for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`),b.push(...Ny(A.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let A of $.upgradeSteps)b.push(` - [${A.level}] ${A.title}: ${A.summary}`),b.push(...A.instructions.map((m)=>` - ${m}`))}return b.join(`
2361
+ `)}function fn($){return["# Patch Notes","",...$.releases.map(Fy)].join(`
2042
2362
 
2043
- `)}function pj($){return["# Customer Upgrade Guide","",...$.releases.map(K9)].join(`
2363
+ `)}function hn($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[vy(b),"",gy(b)])].join(`
2044
2364
 
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(`
2365
+ `)}function ky($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...Ny(b.instructions)].join(`
2046
2366
  `)).join(`
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
2367
+ `)}function yb($,b){let A=b.targetPackages.map((m)=>`${m.name}: ${m.currentVersion??"unknown"} -> ${m.targetVersion??"latest"}`).join(`
2368
+ `);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",A||"- No package version targets were inferred.","","Required steps:",ky(b)].join(`
2369
+ `)}function RZ($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as ry,countUpgradePlanStepLevels as CZ,createAgentPromptBundles as IZ,dedupeUpgradePlanSteps as EZ,sortReleaseManifest as Py}from"@contractspec/lib.contracts-spec";function MZ($,b){if(b.length===0)return Py($);let A=new Map(b.map((m)=>[m.name,m.currentVersion??"0.0.0"]));return Py({...$,releases:$.releases.filter((m)=>m.packages.some((n)=>{let W=A.get(n.name);if(!W||!n.version)return!1;return ry(n.version,W)===1}))})}function lb($,b,A,m){let n=MZ($,b),W=xZ(n,b),w=EZ(n.flatMap((S)=>S.upgradeSteps)),j=CZ(w),y={generatedAt:new Date().toISOString(),targetPackages:W,releases:n,steps:w,autofixCount:j.auto,manualCount:j.manual,assistedCount:j.assisted,agentPrompts:[]},B=IZ(y,A,m);return{...y,agentPrompts:B}}function xZ($,b){let A=new Map(b.map((n)=>[n.name,n.currentVersion])),m=new Map;for(let n of $)for(let W of n.packages){let w=A.get(W.name),j=m.get(W.name);if(!j){m.set(W.name,{name:W.name,currentVersion:w,targetVersion:W.version});continue}if(W.version&&j.targetVersion&&ry(W.version,j.targetVersion)===1)j.targetVersion=W.version}return Array.from(m.values()).sort((n,W)=>n.name.localeCompare(W.name))}async function H0($,b){let{fs:A,logger:m}=$,n=r(b.workspaceRoot),W=M(b.workspaceRoot),w=o$(W);m.info("Analyzing available upgrades...",{workspaceRoot:W,packageRoot:n,packageManager:w});let j=await TZ(A,n),y=await DZ(A,n,W),B=j.length>0||y.length>0;return{packageManager:w,packages:j,configUpgrades:y,hasUpgrades:B}}async function TZ($,b){let A=$.join(b,"package.json");if(!await $.exists(A))return[];try{let m=await $.readFile(A),n=JSON.parse(m),W=n.dependencies??{},w=n.devDependencies??{},j=[],y={...W,...w};for(let[B,S]of Object.entries(y))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))j.push({name:B,currentVersion:S,isDevDependency:!!w[B]});return j}catch{return[]}}async function DZ($,b,A){let m=$.join(b,".contractsrc.json"),n=Kb({configRoot:b,workspaceRoot:A});if(!await $.exists(m))return[];try{let W=await $.readFile(m),w=JSON.parse(W),j=[],y=w.$schema;if(!y||y!==n)j.push({key:"$schema",currentValue:y,suggestedValue:n,isNew:!y});if(!w.versioning)j.push({key:"versioning",currentValue:void 0,suggestedValue:q0(),isNew:!0});else if(w.versioning.integrateWithChangesets===void 0)j.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!w.hooks)j.push({key:"hooks",currentValue:void 0,suggestedValue:O0(),isNew:!0});if(!w.release)j.push({key:"release",currentValue:void 0,suggestedValue:cy(),isNew:!0});if(!w.upgrade)j.push({key:"upgrade",currentValue:void 0,suggestedValue:dy(),isNew:!0});return j}catch{return[]}}async function fy($,b){let{fs:A,logger:m}=$,n=r(b.workspaceRoot),W=M(b.workspaceRoot),w=Kb({configRoot:n,workspaceRoot:W});if(b.dryRun)m.info("Dry run - no changes will be made");let j=A.join(n,".contractsrc.json");if(!await A.exists(j))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let y=await A.readFile(j),B=JSON.parse(y),S=0,Q=B.$schema;if(!Q||Q!==w)B.$schema=w,S++;if(!B.versioning)B.versioning=q0(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=O0(),S++;if(!B.release)B.release=cy(),S++;if(!B.upgrade)B.upgrade=dy(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await A.writeFile(j,JSON.stringify(B,null,2)+`
2370
+ `),m.info("Configuration upgraded",{sectionsUpgraded:S});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:S,summary:b.dryRun?`Would upgrade ${S} config section(s)`:`Upgraded ${S} config section(s)`}}catch(y){let B=y instanceof Error?y.message:String(y);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function hy($,b,A){let m=A?b.map((n)=>`${n.name}@latest`).join(" "):b.map((n)=>n.name).join(" ");switch($){case"bun":return`bun add ${m}`;case"pnpm":return`pnpm add ${m}`;case"yarn":return`yarn add ${m}`;default:return`npm install ${m}`}}function q0(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function O0(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function cy(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function dy(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var vZ="**/*.{ts,tsx,js,jsx,mjs,cjs}",oy=FZ.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function cn($,b){let{fs:A}=$,m=r(b.workspaceRoot),n=M(b.workspaceRoot),W=await kZ(A,m,n),w=await gZ(A,m,n,b.manifestPaths??W.manifestPaths),j=await H0($,{workspaceRoot:m,dryRun:b.dryRun}),y=[b.agentTarget??W.defaultAgentTarget??"codex"],B=lb(w.manifest,j.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),y,yb),S=PZ(B,j.packages,j.configUpgrades);return{packageManager:j.packageManager,manifestPath:w.path,plan:S,humanChecklist:rZ(S)}}async function iy($,b){let{fs:A,logger:m}=$,n=r(b.workspaceRoot),W=await cn($,b),w=[];if(!b.dryRun){for(let y of W.plan.steps){if(y.level!=="auto")continue;for(let B of y.autofixes??[])if(await fZ(A,n,B))w.push(B.id)}m.info("Applied guided upgrade autofixes",{count:w.length,workspaceRoot:n})}let j=W.plan.steps.filter((y)=>y.level!=="auto");return{success:!0,packagesUpgraded:w.filter((y)=>y.startsWith("pkg:")).length,configSectionsUpgraded:w.filter((y)=>y.startsWith("config:")).length,summary:b.dryRun?`Would apply ${W.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${w.length} deterministic upgrade autofix(es)`,appliedAutofixes:w,remainingSteps:j,humanChecklist:W.humanChecklist,promptBundle:W.plan.agentPrompts[0],plan:W.plan,manifestPath:W.manifestPath}}async function gZ($,b,A,m){let n=m??["generated/releases/upgrade-manifest.json"],W=Array.from(new Set([b,A]));for(let w of n){let j=w.startsWith("/")?[w]:W.map((y)=>$.join(y,w));for(let y of j){if(!await $.exists(y))continue;let B=uy.parse(JSON.parse(await $.readFile(y)));return{path:y,manifest:B}}}return{manifest:uy.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function kZ($,b,A){for(let m of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(A,".contractsrc.json")]))){if(!await $.exists(m))continue;try{let n=JSON.parse(await $.readFile(m)),W=NZ.safeParse(n);if(W.success)return{...oy,...W.data.upgrade}}catch{continue}}return oy}function PZ($,b,A){let m=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;m.push({id:`pkg:${S.name}`,kind:"package-json",title:`Update ${S.name}`,summary:`Update ${S.name} to ${Q.targetVersion}`,packageName:S.name,dependencyType:S.isDevDependency?"devDependencies":"dependencies",from:S.currentVersion,to:Q.targetVersion})}let n=A.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),W=[];if(m.length>0)W.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:m.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:m.map((S)=>S.packageName??""),autofixes:m});if(n.length>0)W.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:n.map((S)=>`${S.configPath} -> updated`),autofixes:n});let w=[...W,...$.steps],j=w.filter((S)=>S.level==="auto").length,y=w.filter((S)=>S.level==="assisted").length,B=w.filter((S)=>S.level==="manual").length;return{...$,steps:w,autofixCount:j,assistedCount:y,manualCount:B,agentPrompts:lb({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),yb).agentPrompts}}function rZ($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function fZ($,b,A){switch(A.kind){case"package-json":return hZ($,b,A);case"contractsrc":return cZ($,b,A);case"import-rewrite":return dZ($,b,A);case"codemod":return!1}}async function hZ($,b,A){let m=$.join(b,"package.json");if(!await $.exists(m))return!1;let n=JSON.parse(await $.readFile(m)),W=A.dependencyType??"dependencies",w=n[W]??{};if(!A.packageName||!A.to||!w[A.packageName])return!1;return w[A.packageName]=A.to,n[W]=w,await $.writeFile(m,JSON.stringify(n,null,2)+`
2371
+ `),!0}async function cZ($,b,A){let m=$.join(b,".contractsrc.json"),n=await $.exists(m)?JSON.parse(await $.readFile(m)):{};if(!A.configPath)return!1;return uZ(n,A.configPath,A.value),await $.writeFile(m,JSON.stringify(n,null,2)+`
2372
+ `),!0}async function dZ($,b,A){if(!A.from||!A.to)return!1;let m=await $.glob({pattern:A.path??vZ,cwd:b,absolute:!0}),n=!1;for(let W of m){let w=await $.readFile(W);if(!w.includes(A.from))continue;await $.writeFile(W,w.split(A.from).join(A.to)),n=!0}return n}function uZ($,b,A){let m=b.split("."),n=$;for(let w of m.slice(0,-1)){let j=n[w];if(!j||typeof j!=="object"||Array.isArray(j))n[w]={};n=n[w]}let W=m.at(-1);if(W)n[W]=A}import{existsSync as dn,mkdirSync as oZ,readFileSync as iZ,renameSync as lZ,statSync as tZ,writeFileSync as pZ}from"fs";import{dirname as aZ,join as eZ}from"path";var sZ=".contractspec/verification-cache.json",ty=1;class py{filePath;cache;isDirty=!1;constructor($,b){let A=b??process.cwd();this.filePath=$??eZ(A,sZ),this.cache=new Map,this.loadSync()}loadSync(){try{if(!dn(this.filePath))return;let $=iZ(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==ty)return;for(let[A,m]of Object.entries(b.entries))this.cache.set(A,m)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=aZ(this.filePath);if(!dn($))oZ($,{recursive:!0});let b={version:ty,entries:Object.fromEntries(this.cache.entries())},A=`${this.filePath}.tmp`;pZ(A,JSON.stringify(b,null,2),"utf-8"),lZ(A,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}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(dn(this.filePath))$=tZ(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function BI($,b){return new py($,b)}class ay{cache=new Map;async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b)}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[b,A]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(A).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function QI(){return new ay}class ey{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 b=this.getStorageKey($);return this.store.get(b)??null}async set($,b){let A=this.getStorageKey($);if(await this.store.update(A,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),A=this.keyIndex.has($);if(A)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return A}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function GI($){return new ey($)}import{createHash as $G}from"crypto";var sy={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function $1($){return $G("sha256").update($).digest("hex")}function b1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function bG($){try{let b=$.split("|"),A=new Map;for(let w of b){let[j,y]=w.split(":");if(j&&y)A.set(j,y)}let m=A.get("spec"),n=A.get("impl"),W=A.get("tier");if(!m||!n||!W)return null;return{specHash:m,implHash:n,tier:W,aiModelVersion:A.get("model")}}catch{return null}}function AG($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class A1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...sy,...b},this.stats={hits:0,misses:0}}createKey($,b,A,m){return{specHash:$1($),implHash:$1(b),tier:A,aiModelVersion:A==="ai_review"?m:void 0}}async lookup($){let b=b1($),A=await this.storage.get(b);if(!A)return this.stats.misses++,{hit:!1,reason:"not_found"};if(A.meta.expiresAt){let m=new Date(A.meta.expiresAt).getTime();if(Date.now()>m)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(A.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(A.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&A.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:A}}async store($,b,A={}){let m=b1($),n=AG($.tier,this.config),W={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+n).toISOString(),dependencies:A.dependencies??[],specName:A.specName,implPath:A.implPath}};await this.storage.set(m,W),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),A=0;for(let m of b){let n=await this.storage.get(m);if(!n)continue;if(n.meta.dependencies.includes($))await this.storage.delete(m),A++;if(n.meta.specName===$||n.meta.implPath===$)await this.storage.delete(m),A++}return A}async invalidateForSpec($){let b=await this.storage.keys(),A=0;for(let m of b){let n=bG(m);if(n&&n.specHash.startsWith($.substring(0,16)))await this.storage.delete(m),A++}return A}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 b=[];for(let m of $){let n=await this.storage.get(m);if(n)b.push({key:m,createdAt:new Date(n.meta.createdAt).getTime()})}b.sort((m,n)=>m.createdAt-n.createdAt);let A=b.length-this.config.maxEntries;for(let m=0;m<A;m++){let n=b[m];if(n)await this.storage.delete(n.key)}}}function _I($,b){return new A1($,b)}import{generateVerificationPrompt as mG}from"@contractspec/lib.contracts-spec/llm";function nG($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let y=JSON.parse(b[1]);return{compliant:y.passed??!1,confidence:(y.score??0)/100,findings:(y.issues??[]).map((B)=>({category:String(B.category??"semantic"),severity:String(B.severity??"warning"),message:String(B.message??""),location:B.location?String(B.location):void 0,suggestion:B.suggestion?String(B.suggestion):void 0})),rawResponse:$}}catch{}let A=[],m=$.split(`
2373
+ `),n="info";for(let y of m){let B=y.toLowerCase();if(B.includes("error")||B.includes("critical"))n="error";else if(B.includes("warning")||B.includes("should"))n="warning";else if(B.includes("info")||B.includes("note"))n="info";let S=y.match(/^[-*\u2022]\s*(.+)$/),Q=y.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)A.push({category:"semantic",severity:n,message:Z})}}let W=A.some((y)=>y.severity==="error"),w=!W,j=W?0.3:A.length===0?0.9:0.7;return{compliant:w,confidence:j,findings:A,rawResponse:$}}async function m1($,b){if(!b.aiApiKey)return`\`\`\`json
2054
2374
  {
2055
2375
  "passed": true,
2056
2376
  "score": 50,
@@ -2067,23 +2387,23 @@ Do not include markdown formatting or explanations, just the JSON.
2067
2387
  ],
2068
2388
  "summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
2069
2389
  }
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
2390
+ \`\`\``;try{let A=b.aiProvider??"anthropic";if(A==="anthropic"){let{anthropic:m}=await import("@ai-sdk/anthropic"),{generateText:n}=await import("ai");return(await n({model:m("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(A==="openai"){let{openai:m}=await import("@ai-sdk/openai"),{generateText:n}=await import("ai");return(await n({model:m("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: ${A}`)}catch(A){return`\`\`\`json
2071
2391
  {
2072
2392
  "passed": false,
2073
2393
  "score": 0,
2074
2394
  "issues": [
2075
- { "severity": "error", "category": "semantic", "message": "AI verification failed: ${j instanceof Error?j.message:"Unknown error"}" }
2395
+ { "severity": "error", "category": "semantic", "message": "AI verification failed: ${A instanceof Error?A.message:"Unknown error"}" }
2076
2396
  ],
2077
2397
  "summary": "AI verification encountered an error"
2078
2398
  }
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.
2399
+ \`\`\``}}async function tb($,b={}){let{spec:A,implementationCode:m,implementationPath:n}=$,W=Date.now(),w=mG(A,m),j=await m1(w.taskPrompt,b),y=nG(j),B=y.findings.map((G)=>({severity:G.severity,category:"semantic",message:G.message,location:G.location?{file:G.location}:n?{file:n}:void 0,suggestion:G.suggestion})),S=Math.round(y.confidence*100),Q=y.compliant,Z=y.findings.filter((G)=>G.suggestion).map((G)=>G.suggestion);return{tier:"ai_review",passed:Q,score:S,issues:B,suggestions:Z,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Q?1:0}},meta:{specName:A.meta.key,specVersion:A.meta.version,implementationPath:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-W}}}function V0($){let{spec:b,implementationCode:A,implementationPath:m}=$,n=Date.now(),W=[];if(A.includes("console.log"))W.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(A.includes("// TODO")||A.includes("// FIXME"))W.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(b.policy.auth!=="anonymous"&&!A.includes("auth"))W.push({severity:"warning",category:"semantic",message:`Spec requires ${b.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let w=W.filter((y)=>y.severity==="error").length===0?80:40,j=W.filter((y)=>y.severity==="error").length===0;return{tier:"ai_review",passed:j,score:w,issues:W,suggestions:W.filter((y)=>y.suggestion).map((y)=>y.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:j?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-n}}}function WG($,b){return`You are analyzing a code implementation against its specification.
2080
2400
 
2081
2401
  ## Spec Schema Fields
2082
2402
  ${$}
2083
2403
 
2084
2404
  ## Implementation Code
2085
2405
  \`\`\`typescript
2086
- ${W}
2406
+ ${b}
2087
2407
  \`\`\`
2088
2408
 
2089
2409
  ## Task
@@ -2123,42 +2443,43 @@ Match types:
2123
2443
  - "compatible": Semantically similar (e.g., "email" vs "emailAddress")
2124
2444
  - "mismatch": Different meaning despite similar naming
2125
2445
  - "missing": Spec field not found in implementation
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(`
2446
+ `}function wG($){let b=[],A=(m,n)=>{try{let w=m?._def?.shape;if(w&&typeof w==="function"){let j=w();for(let[y,B]of Object.entries(j)){let Q=B?._def?.typeName??"unknown";b.push(`- ${y}: ${String(Q).replace("Zod","").toLowerCase()} (${n})`)}}}catch{b.push(`- [unable to extract ${n} fields]`)}};if($.io.input)A($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))A($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
2447
+ `)}function jG($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let A=JSON.parse(b[1]);return{fieldMappings:(A.fieldMappings??[]).map((m)=>({specField:String(m.specField??""),specType:String(m.specType??"unknown"),implementationField:m.implementationField?String(m.implementationField):void 0,implementationType:m.implementationType?String(m.implementationType):void 0,match:m.match??"missing",aiConfidence:typeof m.aiConfidence==="number"?m.aiConfidence:0.5,suggestion:m.suggestion?String(m.suggestion):void 0})),intentAlignment:{score:typeof A.intentAlignment?.score==="number"?A.intentAlignment.score:50,issues:Array.isArray(A.intentAlignment?.issues)?A.intentAlignment.issues:[],suggestions:Array.isArray(A.intentAlignment?.suggestions)?A.intentAlignment.suggestions:[]},semanticIssues:(A.semanticIssues??[]).map((m)=>({category:String(m.category??"semantic"),severity:m.severity??"warning",message:String(m.message??""),suggestion:m.suggestion?String(m.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function n1($,b={}){let{spec:A,implementationCode:m}=$,n=wG(A),W=WG(n,m),w=await m1(W,b);return jG(w)}async function yG($,b={}){let{spec:A,implementationCode:m,implementationPath:n}=$,W=Date.now(),w=await tb($,b),j;if(b.aiApiKey)try{j=await n1($,b)}catch{}if(j){let y=[];for(let Z of j.fieldMappings)if(Z.match==="missing")y.push({severity:"error",category:"semantic",message:`Missing field: '${Z.specField}' (${Z.specType}) not found in implementation`,suggestion:Z.suggestion??`Add field '${Z.specField}' to implementation`});else if(Z.match==="mismatch")y.push({severity:"warning",category:"semantic",message:`Field mismatch: '${Z.specField}' has incorrect implementation as '${Z.implementationField}'`,suggestion:Z.suggestion});else if(Z.match==="compatible"&&Z.aiConfidence<0.8)y.push({severity:"info",category:"semantic",message:`Field naming: '${Z.specField}' implemented as '${Z.implementationField}' (compatible but not exact)`,suggestion:Z.suggestion});for(let Z of j.intentAlignment.issues)y.push({severity:"warning",category:"semantic",message:Z});for(let Z of j.semanticIssues)y.push({severity:Z.severity,category:"semantic",message:Z.message,suggestion:Z.suggestion});w.issues=[...w.issues,...y];let B=j.fieldMappings.length,S=j.fieldMappings.filter((Z)=>Z.match==="exact"||Z.match==="compatible").length;if(B>0){let Z=Math.round(S/B*100);w.score=Math.round((w.score+Z)/2),w.coverage.fields={total:B,implemented:S}}if(y.some((Z)=>Z.severity==="error"))w.passed=!1;w.suggestions=[...w.suggestions,...j.intentAlignment.suggestions]}return w.meta={...w.meta,duration:Date.now()-W},w}import{isEmitDeclRef as BG}from"@contractspec/lib.contracts-spec/operations";function SG($,b){let A=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),m=$.toLowerCase(),n=A.filter((B)=>m.includes(B)),W=A.length>0?n.length/A.length:0,w=b.key.toLowerCase().replace(/\s+/g,""),j=m.includes(w)||m.includes(`test('${b.key.toLowerCase()}'`)||m.includes(`it('${b.key.toLowerCase()}'`)||m.includes(`describe('${b.key.toLowerCase()}'`),y=W>=0.3||j;return{name:b.key,type:"scenario",passed:y,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:y?void 0:`Scenario keywords not found in implementation (${Math.round(W*100)}% coverage)`}}function QG($,b){let A=JSON.stringify(b.input),m=JSON.stringify(b.output),n=W1(b.input),W=W1(b.output),w=$.toLowerCase(),j=n.filter((G)=>w.includes(G.toLowerCase())),y=W.filter((G)=>w.includes(G.toLowerCase())),B=n.length>0?j.length/n.length:1,S=W.length>0?y.length/W.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${A.slice(0,100)}...; Output: ${m.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function W1($){let b=[];function A(m){if(typeof m==="string"&&m.length>2)b.push(m);else if(Array.isArray(m))m.forEach(A);else if(m&&typeof m==="object")Object.values(m).forEach(A)}return A($),b}function ZG($,b,A){let m=$.includes(b),n=A.http?$.includes(String(A.http)):!0,W=A.when.toLowerCase().split(/\s+/).filter((S)=>S.length>3),w=$.toLowerCase(),j=W.filter((S)=>w.includes(S)),y=W.length>0?j.length/W.length:1,B=m&&(n||y>=0.3);return{name:`Error: ${b}`,type:"error",passed:B,expected:`When: ${A.when}; Return: ${b} (HTTP ${A.http??400})`,details:B?void 0:!m?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function GG($,b){let A=b.sideEffects?.emits??[],m=[];for(let n of A){let W=BG(n)?n.ref.key:n.key,w=n.when,j=w.toLowerCase().split(/\s+/).filter((Z)=>Z.length>3),y=$.toLowerCase(),B=y.includes(W.toLowerCase()),S=j.filter((Z)=>y.includes(Z)),Q=j.length>0?S.length/j.length:1;m.push({name:`Event: ${W}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${W} when: ${w}`,details:!B?`Event '${W}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return m}function XG($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let A=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],m=$.toLowerCase(),n=A.some((W)=>m.includes(W));return{name:"Idempotency",type:"scenario",passed:n,expected:"Operation should be idempotent (safe to retry)",details:n?void 0:"No idempotency pattern found for idempotent operation"}}function J0($){let{spec:b,implementationCode:A,implementationPath:m}=$,n=Date.now(),W=[];for(let X of b.acceptance?.scenarios??[])W.push(SG(A,X));for(let X of b.acceptance?.examples??[])W.push(QG(A,X));for(let[X,Y]of Object.entries(b.io.errors??{}))W.push(ZG(A,X,Y));W.push(...GG(A,b));let w=XG(A,b);if(w)W.push(w);let j=W.filter((X)=>!X.passed).map((X)=>({severity:X.type==="error"?"error":"warning",category:X.type==="scenario"?"scenario":X.type==="example"?"scenario":"error_handling",message:X.details??`${X.type} not covered: ${X.name}`,location:m?{file:m}:void 0,suggestion:X.expected?`Expected: ${X.expected}`:void 0})),y=W.filter((X)=>X.type==="scenario"),B=W.filter((X)=>X.type==="error"),S=W.filter((X)=>X.passed).length,Q=W.length>0?Math.round(S/W.length*100):100,Z=j.filter((X)=>X.severity==="error").length===0,G=W.filter((X)=>!X.passed&&X.expected).map((X)=>`${X.name}: ${X.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:j,suggestions:G,coverage:{scenarios:{total:y.length,covered:y.filter((X)=>X.passed).length},errors:{total:B.length,handled:B.filter((X)=>X.passed).length},fields:{total:W.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-n}}}import{isEmitDeclRef as YG}from"@contractspec/lib.contracts-spec/operations";function HG($){let b=/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:b,details:b?void 0:"No exported handler function found",suggestion:"Export a function that handles the operation: export async function handle(...) { }"}}function qG($){if(!$)return!1;let b=$.replace(/\\/g,"/");return b.includes("/packages/libs/contracts-spec/src/")||b.includes("/packages/libs/contracts-integrations/src/")||b.includes("/packages/libs/contracts-runtime-")}function OG($,b){if(qG(b))return{name:"contracts_import",passed:!0};let A=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function VG($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let m=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:m,details:m?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function JG($){let b=/:\s*any\b|as\s+any\b|<any>/,A=$.split(`
2448
+ `),m=[];for(let n=0;n<A.length;n++){let W=A[n]??"";if(W.trim().startsWith("//")||W.trim().startsWith("*"))continue;if(b.test(W))m.push(n+1)}return{name:"no_any_type",passed:m.length===0,details:m.length>0?`Found 'any' type on lines: ${m.slice(0,5).join(", ")}${m.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function KG($,b){let A=b.io.errors;if(!A||Object.keys(A).length===0)return{name:"error_handling",passed:!0};let m=Object.keys(A),n=[];for(let W of m)if(!$.includes(W))n.push(W);return{name:"error_handling",passed:n.length===0,details:n.length>0?`Missing error handling for: ${n.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function _G($,b){let A=b.sideEffects?.emits;if(!A||A.length===0)return{name:"event_emission",passed:!0};let m=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),n=A.map((w)=>{if(YG(w))return w.ref.key;return w.key}),W=n.filter((w)=>$.includes(w));return{name:"event_emission",passed:m&&W.length>0,details:!m?"No event emission pattern found":W.length===0?`Events not referenced: ${n.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function UG($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let A=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:A,details:A?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function zG($,b){let A=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:A,details:A?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function pb($){let{spec:b,implementationCode:A,implementationPath:m}=$,n=Date.now(),W=[HG(A),OG(A,m),VG(A,b),JG(A),KG(A,b),_G(A,b),UG(A,b),zG(A,b)],w=W.filter((G)=>!G.passed).map((G)=>({severity:G.name==="no_any_type"?"warning":"error",category:G.name.includes("import")?"import":G.name.includes("export")?"export":"type",message:G.details??`Check failed: ${G.name}`,location:m?{file:m}:void 0,suggestion:G.suggestion})),j=W.filter((G)=>G.passed).length,y=Math.round(j/W.length*100),B=w.filter((G)=>G.severity==="error").length===0,S=W.filter((G)=>!G.passed&&G.suggestion).map((G)=>G.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=W.find((G)=>G.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:y,issues:w,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:W.length,implemented:j}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-n}}}var LG={verbose:!1},RG=["structure","behavior","ai_review"];class K0{config;constructor($={}){this.config={...LG,...$}}async verify($,b,A={}){let m=Date.now(),n=new Map,W=[],w={spec:$,implementationCode:b},j=A.tiers??["structure","behavior"];for(let Z of RG){if(!j.includes(Z))continue;let G;switch(Z){case"structure":G=pb(w);break;case"behavior":G=J0(w);break;case"ai_review":if(this.config.aiApiKey)G=await tb(w,this.config);else G=V0(w);break;default:continue}if(n.set(Z,G),W.push(...G.issues),A.failFast&&!G.passed)break}let y=Array.from(n.values()),B=y.every((Z)=>Z.passed),S=y.length>0?Math.round(y.reduce((Z,G)=>Z+G.score,0)/y.length):100,Q=this.generateSummary(y,W);return{passed:B,score:S,reports:n,allIssues:W,summary:Q,duration:Date.now()-m}}verifyStructure($,b,A){return pb({spec:$,implementationCode:b,implementationPath:A})}verifyBehavior($,b,A){return J0({spec:$,implementationCode:b,implementationPath:A})}async verifyAI($,b,A){let m={spec:$,implementationCode:b,implementationPath:A};if(this.config.aiApiKey)return tb(m,this.config);return V0(m)}quickVerify($,b){return pb({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[m,n]of $.reports){if(b.push(`## ${this.formatTierName(m)}`),b.push(""),b.push(`**Status:** ${n.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${n.score}/100`),b.push(""),n.issues.length>0){b.push("### Issues"),b.push("");for(let W of n.issues){let w=W.severity==="error"?"\u274C":W.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(b.push(`${w} **${W.category}**: ${W.message}`),W.suggestion)b.push(` - Suggestion: ${W.suggestion}`)}b.push("")}if(n.coverage.scenarios.total>0)b.push(`**Scenarios:** ${n.coverage.scenarios.covered}/${n.coverage.scenarios.total}`);if(n.coverage.errors.total>0)b.push(`**Errors handled:** ${n.coverage.errors.handled}/${n.coverage.errors.total}`);b.push("")}let A=Array.from($.reports.values()).flatMap((m)=>m.suggestions);if(A.length>0){b.push("## Suggestions"),b.push("");for(let m of A.slice(0,10))b.push(`- ${m}`);if(A.length>10)b.push(`- ... and ${A.length-10} more`);b.push("")}return b.join(`
2449
+ `)}configure($){this.config={...this.config,...$}}generateSummary($,b){let A=[],m=$.every((y)=>y.passed),n=$.length>0?Math.round($.reduce((y,B)=>y+B.score,0)/$.length):100;A.push(m?"\u2713 Verification passed":"\u2717 Verification failed"),A.push(`Score: ${n}/100`),A.push("");for(let y of $){let B=y.passed?"\u2713":"\u2717";A.push(`${B} ${y.tier}: ${y.score}/100`)}A.push("");let W=b.filter((y)=>y.severity==="error"),w=b.filter((y)=>y.severity==="warning"),j=b.filter((y)=>y.severity==="info");if(W.length>0)A.push(`Errors: ${W.length}`);if(w.length>0)A.push(`Warnings: ${w.length}`);if(j.length>0)A.push(`Info: ${j.length}`);return A.join(`
2450
+ `)}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 CG($){return new K0($)}var IG=new K0;var R1={};P(R1,{saveReleaseDraft:()=>O1,renderUpgradePrompt:()=>yb,renderUpgradeChecklist:()=>ky,renderPatchNotes:()=>fn,renderMigrationGuide:()=>gy,renderMaintainerSummary:()=>Fy,renderCustomerPatchNote:()=>vy,renderCustomerGuide:()=>hn,prepareReleaseAuthoring:()=>q1,parseConventionalCommit:()=>z0,isConventionalCommit:()=>FG,initReleaseArtifacts:()=>_1,getHighestBumpType:()=>on,getBumpTypeFromCommit:()=>un,generateChangelogs:()=>H1,formatKeepAChangelog:()=>ab,formatConventionalChangelog:()=>j1,formatChangelogJson:()=>_0,filterCommitsByScope:()=>vG,filterBumpableCommits:()=>gG,commitsToChangeEntries:()=>ln,commitToChangeEntry:()=>B1,checkReleaseArtifacts:()=>z1,buildReleaseArtifacts:()=>U1,applyVersionBump:()=>Y1,analyzeVersionsFromCommits:()=>Bb,analyzeVersions:()=>AA,DEFAULT_COMMIT_TYPE_MAP:()=>U0});import{basename as EG,dirname as MG}from"path";function ab($){let b=["# 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).",""],A=[...$].sort((m,n)=>y1(m.version,n.version));for(let m of A){b.push(`## [${m.version}] - ${m.date}`),b.push("");let n=m.changes.filter((Q)=>Q.type==="added"),W=m.changes.filter((Q)=>Q.type==="changed"),w=m.changes.filter((Q)=>Q.type==="deprecated"),j=m.changes.filter((Q)=>Q.type==="removed"),y=m.changes.filter((Q)=>Q.type==="fixed"),B=m.changes.filter((Q)=>Q.type==="security"),S=m.breakingChanges??m.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### \u26A0\uFE0F Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(n.length>0)b.push("### Added"),n.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(W.length>0)b.push("### Changed"),W.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(w.length>0)b.push("### Deprecated"),w.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(j.length>0)b.push("### Removed"),j.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(y.length>0)b.push("### Fixed"),y.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(B.length>0)b.push("### Security"),B.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("")}return b.join(`
2451
+ `)}function j1($){let b=["# Changelog",""],A=[...$].sort((m,n)=>y1(m.version,n.version));for(let m of A){let n=m.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":m.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${m.version} (${m.date}) - ${n}`),b.push("");let W={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let w of m.changes){let j=W[w.type]??"chore",y=w.path?`(${w.path})`:"",B=w.type==="breaking"?"!":"";b.push(`- **${j}${y}${B}**: ${w.description}`)}b.push("")}return b.join(`
2452
+ `)}function _0($,b){let A=$.analyses.filter((W)=>W.needsBump),m=new Date().toISOString(),n=m.split("T")[0]??"";return{generatedAt:m,baseline:b,specs:A.map((W)=>({key:W.specKey,version:W.suggestedVersion,path:W.specPath,entries:[{version:W.suggestedVersion,date:n,bumpType:W.bumpType,changes:W.changes,breakingChanges:W.changes.filter((w)=>w.type==="breaking")}]})),libraries:TG(A,n)}}function xG($){let b=$.split("/"),A=b.lastIndexOf("packages");if(A>=0&&A+2<b.length)return b.slice(0,A+3).join("/");return MG($)}var w1={major:3,minor:2,patch:1};function TG($,b){let A=new Map;for(let m of $){let n=xG(m.specPath),W=A.get(n);if(W)W.push(m);else A.set(n,[m])}return Array.from(A.entries()).flatMap(([m,n])=>{let W=n[0];if(!W)return[];let w=n.reduce((j,y)=>{return(w1[y.bumpType]??0)>(w1[j.bumpType]??0)?y:j},W);return[{name:EG(m),path:m,version:w.suggestedVersion,entries:[{version:w.suggestedVersion,date:b,bumpType:w.bumpType,changes:n.flatMap((j)=>j.changes),breakingChanges:n.flatMap((j)=>j.changes).filter((j)=>j.type==="breaking")}]}]})}function y1($,b){let A=(W)=>{return W.split(".").map((j)=>parseInt(j,10)||0)},m=A($),n=A(b);for(let W=0;W<3;W++){let w=m[W]??0,j=n[W]??0;if(w!==j)return j-w}return 0}var U0={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},DG=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,NG=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function z0($){let b=$.split(`
2453
+ `),A=b[0]?.trim();if(!A)return null;let m=A.match(DG);if(!m)return null;let[,n,W,w,j]=m;if(!n||!j)return null;let y=b.slice(1).join(`
2454
+ `).trim()||void 0,B=y?.match(NG),S=B?.[1];return{type:n.toLowerCase(),scope:W?.toLowerCase(),breaking:!!w||!!B,description:j.trim(),body:y,breakingDescription:S,raw:$}}function FG($){return z0($)!==null}function un($,b=U0){if($.breaking)return"major";return b[$.type]??null}function on($,b=U0){let A=["major","minor","patch"],m=null;for(let n of $){let W=un(n,b);if(!W)continue;if(!m){m=W;continue}let w=A.indexOf(m);if(A.indexOf(W)<w)m=W}return m}function B1($){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 ln($){return $.map(B1)}function vG($,b){return $.filter((A)=>A.scope?.toLowerCase()===b.toLowerCase())}function gG($,b=U0){return $.filter((A)=>un(A,b)!==null)}import{z as T}from"zod";import{ReleaseCapsuleSchema as S1}from"@contractspec/lib.contracts-spec";import{dump as kG,load as PG}from"js-yaml";var rG=".changeset/*.md",fG=".changeset/*.release.yaml",hG=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,cG=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function dG($,b){return(await $.glob({pattern:rG,cwd:b,absolute:!0})).filter((m)=>$.basename(m)!=="README.md")}async function eb($,b){let A=await dG($,b),m=[];for(let n of A){let W=await $.readFile(n);m.push(uG($.basename(n),W))}return m}async function sb($,b,A){let m=await $.glob({pattern:fG,cwd:b,absolute:!0}),n=new Map(A.map((j)=>[j.slug,j.packages])),W=new Map,w=[];for(let j of m){let y=$.basename(j).replace(/\.release\.yaml$/,"");try{let B=PG(await $.readFile(j)),S=oG(B,y,n.get(y)??[]);W.set(y,S)}catch(B){w.push(iG(j,y,B))}}return{capsules:W,issues:w}}async function $A($,b){let A=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),m=[];for(let n of A){let W=JSON.parse(await $.readFile(n));if(!W.name||!W.version||W.private===!0)continue;let w=$.relative(b,$.dirname(n))||".";m.push({name:W.name,dir:w,version:W.version})}return m.sort((n,W)=>n.dir.localeCompare(W.dir))}function L0($,b){let A=new Set;for(let m of $){let n=b.find((W)=>W.dir==="."?!m.startsWith("packages/"):m===W.dir||m.startsWith(`${W.dir}/`));if(n)A.add(n.name)}return Array.from(A).sort((m,n)=>m.localeCompare(n))}function R0($,b){return`---
2455
+ ${b.map((m)=>`"${m.name}": ${m.releaseType}`).join(`
2136
2456
  `)}
2137
2457
  ---
2138
2458
 
2139
2459
  ${$}
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}
2460
+ `}function C0($){return kG(S1.parse($),{noRefs:!0,lineWidth:100})}function bA($){return $.map((b)=>{let A=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",m=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${A} ${b.message}.${m}`.trim()}).join(`
2461
+ `)}function uG($,b){let A=$.replace(/\.md$/,""),m=b.match(hG);if(!m)return{slug:A,summary:b.trim(),packages:[]};let n=m[1]??"",W=(m[2]??"").trim(),w=[];for(let j of n.split(`
2462
+ `)){let y=j.trim().match(cG);if(!y)continue;let B=y[1],S=y[2];if(!B||S==="none")continue;w.push({name:B,releaseType:S})}return{slug:A,summary:W,packages:w}}function oG($,b,A){let m=typeof $==="object"&&$!==null?$:{},n=Array.isArray(m.packageNames)?m.packageNames.filter((W)=>typeof W==="string").map((W)=>({name:W,releaseType:m.releaseType??"patch"})):[];return S1.parse({...m,slug:b,packages:Array.isArray(m.packages)&&m.packages.length>0?m.packages:n.length>0?n:A})}function iG($,b,A){let m=typeof A==="object"&&A!==null?A:null,n=Array.isArray(m?.issues)?m.issues.map((w)=>w.message).filter((w)=>typeof w==="string"):[],W=n.length>0?`Release capsule validation failed: ${n.join("; ")}`:typeof m?.reason==="string"?`Release capsule YAML parse failed: ${m.reason}`:`Release capsule parse failed: ${A instanceof Error?A.message:String(A)}`;return{slug:b,filePath:$,message:W,line:typeof m?.mark?.line==="number"?m.mark.line+1:void 0,column:typeof m?.mark?.column==="number"?m.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as X1,determineBumpType as lG}from"@contractspec/lib.contracts-spec";async function AA($,b={}){let{fs:A,git:m,logger:n}=$,W=b.workspaceRoot??process.cwd();n.info("Starting version analysis...",{baseline:b.baseline});let w=b.pattern??"**/*.{operation,event,presentation}.ts",y=(await A.glob({pattern:w,cwd:W})).filter((G)=>!G.includes(".test.")&&!G.includes(".spec.")&&!G.includes("node_modules"));n.debug(`Found ${y.length} spec files`);let B=[],S=0,Q=0;for(let G of y)try{let X=await A.readFile(G),Y=I0(X);if(!Y)continue;let V=null;if(b.baseline)try{V=await m.showFile(b.baseline,G)}catch{V=null}let O=tG(X,V),K=O.some((U)=>U.type==="breaking"),J=O.length>0&&!K,_=O.length>0;if(K)S++;if(J)Q++;let H=lG(K,J),q=_?X1(Y.version,H):Y.version;B.push({specPath:G,specKey:Y.key,currentVersion:Y.version,suggestedVersion:q,bumpType:H,changes:O,hasBreaking:K,needsBump:_})}catch(X){n.warn(`Failed to analyze ${G}:`,{error:X instanceof Error?X.message:String(X)})}let Z=B.filter((G)=>G.needsBump).length;return n.info("Version analysis complete",{totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q}),{analyses:B,totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q,baseline:b.baseline}}async function Bb($,b={}){let{git:A,logger:m}=$,n=b.baseline??"HEAD~10";m.info("Analyzing commits for version bump...",{baseline:n});try{let W=await A.log(n),w=[],j=[];for(let Q of W){let Z=z0(Q.message);if(Z)w.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),j.push(Z)}let y=on(j),B=ln(j),S=w.filter((Q)=>Q.breaking).length;return m.info("Commit analysis complete",{totalCommits:w.length,breakingCommits:S,suggestedBumpType:y}),{suggestedBumpType:y,commits:w,changes:B,totalCommits:w.length,breakingCommits:S}}catch(W){return m.warn("Failed to analyze commits",{error:W instanceof Error?W.message:String(W)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function Y1($,b){let{fs:A,logger:m}=$,{specPath:n,dryRun:W=!1,config:w}=b;m.info("Applying version bump...",{specPath:n,bumpType:b.bumpType});try{let j=await A.readFile(n),y=I0(j);if(!y)return{success:!1,specPath:n,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:Z1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=X1(y.version,B),Q=b.changes??[];if(b.changeDescription)Q.push({type:B==="major"?"breaking":"changed",description:b.changeDescription});let Z={version:S,date:new Date().toISOString().split("T")[0]??"",bumpType:B,changes:Q,breakingChanges:Q.filter((G)=>G.type==="breaking")};if(!W){let G=aG(j,y.version,S);await A.writeFile(n,G)}if(m.info("Version bump applied",{specPath:n,previousVersion:y.version,newVersion:S}),w?.integrateWithChangesets)await $2($,{specPath:n,bumpType:B,summary:b.changeDescription??`Bump ${y.key} to ${S}`,dryRun:W});return{success:!0,specPath:n,specKey:y.key,previousVersion:y.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(j){let y=j instanceof Error?j.message:String(j);return m.error("Version bump failed",{specPath:n,error:y}),{success:!1,specPath:n,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:Z1(),error:y}}}async function H1($,b={}){let{logger:A}=$,m=b.tiers??["spec","library","monorepo"],n=b.format??"keep-a-changelog";A.info("Generating changelogs...",{tiers:m,format:n});let W=await AA($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),w=[],j=new Map,y="",B=0;if(m.includes("spec"))for(let Q of W.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:eG(Q),kind:"changelog",specKey:Q.specKey,specVersion:Q.suggestedVersion,entries:[{version:Q.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:Q.bumpType,changes:Q.changes,breakingChanges:Q.changes.filter((G)=>G.type==="breaking")}]};w.push(Z),B++}if(m.includes("library")){let Q=sG(W.analyses);for(let[Z,G]of Q){let X=G.filter((Y)=>Y.needsBump);if(X.length>0)j.set(Z,ab(X.map(G1))),B+=X.length}}if(m.includes("monorepo")){let Q=W.analyses.filter((Z)=>Z.needsBump).map(G1);y=ab(Q)}let S=_0(W,b.baseline);return A.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:w,libraryMarkdown:j,monorepoMarkdown:y,json:S,totalEntries:B}}function I0($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),A=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!A)return null;let m=b[1],n=A[1];if(!m||!n)return null;return{key:m,version:n}}function tG($,b){let A=[];if(!b)return A.push({type:"added",description:"New spec added"}),A;let m=I0($),n=I0(b);if(!m||!n)return A;if(m.version!==n.version)A.push({type:"changed",description:`Version updated from ${n.version} to ${m.version}`,path:"meta.version"});let W=pG($,b);if(W.breaking)A.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(W.nonBreaking)A.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return A}function pG($,b){let A=/io:\s*\{[\s\S]*?\}/,m=$.match(A)?.[0]??"",n=b.match(A)?.[0]??"";if(m===n)return{breaking:!1,nonBreaking:!1};let W=Q1(m),w=Q1(n),j=w.filter((B)=>!W.includes(B)),y=W.filter((B)=>!w.includes(B));return{breaking:j.length>0,nonBreaking:y.length>0&&j.length===0}}function Q1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((m)=>m[1]).filter((m)=>!!m)}function aG($,b,A){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${A}'`)}function Z1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function eG($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],A=$.changes.filter((W)=>W.type==="breaking"),m=$.changes.filter((W)=>W.type==="changed"),n=$.changes.filter((W)=>W.type==="added");if(A.length>0)b.push("### Breaking Changes"),A.forEach((W)=>b.push(`- ${W.description}`)),b.push("");if(n.length>0)b.push("### Added"),n.forEach((W)=>b.push(`- ${W.description}`)),b.push("");if(m.length>0)b.push("### Changed"),m.forEach((W)=>b.push(`- ${W.description}`)),b.push("");return b.join(`
2463
+ `)}function sG($){let b=new Map;for(let A of $){let W=A.specPath.match(/(.+?\/src\/)/)?.[1]??A.specPath,w=b.get(W)??[];w.push(A),b.set(W,w)}return b}function G1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function $2($,b){let{fs:A,logger:m}=$,{specPath:n,bumpType:W,summary:w,dryRun:j}=b;try{let y=r(n),B=T$(y);if(!B){m.warn("Could not determine package name for changeset",{specPath:n});return}let S=y,Q=null;while(!0){let Y=A.join(S,".changeset");if(await A.exists(Y)){Q=Y;break}let V=A.dirname(S);if(V===S)break;S=V}if(!Q){m.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${b2()}.md`,G=A.join(Q,Z),X=`---
2464
+ "${B}": ${W}
2144
2465
  ---
2145
2466
 
2146
- ${X}
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.
2467
+ ${w}
2468
+ `;if(!j)await A.writeFile(G,X),m.info("Generated changeset",{filePath:G});else m.info("Would generate changeset",{filePath:G,content:X})}catch(y){m.error("Failed to generate changeset",{error:y instanceof Error?y.message:String(y)})}}function b2(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],A=["run","fly","hop","eat","nap","cry","sing"],m=$[Math.floor(Math.random()*$.length)],n=b[Math.floor(Math.random()*b.length)],W=A[Math.floor(Math.random()*A.length)],w=Math.floor(Math.random()*1000);return`${m}-${n}-${W}-${w}`}var A2=T.object({summary:T.string(),maintainerSummary:T.string(),customerSummary:T.string(),integratorSummary:T.string(),deprecations:T.array(T.string()).default([]),migrationInstructions:T.array(T.object({id:T.string(),title:T.string(),summary:T.string(),required:T.boolean().default(!1),when:T.string().optional(),steps:T.array(T.string()).default([])})).default([]),upgradeSteps:T.array(T.object({id:T.string(),title:T.string(),summary:T.string(),level:T.enum(["auto","assisted","manual"]).default("manual"),instructions:T.array(T.string()).default([])})).default([]),validationCommands:T.array(T.string()).default([]),validationEvidence:T.array(T.string()).default([])});async function q1($,b={}){let{fs:A,git:m,logger:n,ai:W}=$,w=M(b.workspaceRoot),j=await $A(A,w),y=b.baseline?await m.diffFiles(b.baseline):[],B=await eb(A,w),S=await sb(A,w,B),Q=b.packages&&b.packages.length>0?b.packages:L0(y,j),Z=b.baseline?await Bb($,{baseline:b.baseline,workspaceRoot:w}):null,G=b.baseline?await V$($,{baseline:b.baseline,workspaceRoot:w}):null,X=b.slug??j2(B,S.capsules,Q),Y=X?A.join(w,".changeset",`${X}.md`):void 0,V=X?A.join(w,".changeset",`${X}.release.yaml`):void 0,O=X?B.find((q)=>q.slug===X):void 0,K=X?S.capsules.get(X):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((G?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??y2(Q)),_=(Y?await A.exists(Y):!1)||(V?await A.exists(V):!1),H=await n2(W,m2({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:j,isBreaking:J==="major"||(G?.summary.breaking??0)>0,selectedSlug:X}),{changedFiles:y,commitMessages:b.baseline?(await m.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},n);return{workspaceRoot:w,source:_?"existing":"created",changesetPath:Y??A.join(w,".changeset",`${H.slug}.md`),capsulePath:V??A.join(w,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${bA(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:W!==void 0}}async function O1($,b){let{fs:A}=$,m=M(b.workspaceRoot),n=mA(b.draft),W=A.join(m,".changeset",`${n.slug}.md`),w=A.join(m,".changeset",`${n.slug}.release.yaml`),j=await A.exists(W)||await A.exists(w)?"updated":"created",y=R0(n.summary,n.packages),B=C0(w2(n));return await A.writeFile(W,y),await A.writeFile(w,B),{source:j,changesetPath:W,capsulePath:w,changesetContent:y,capsuleContent:B}}function m2($){if($.existingCapsule)return mA({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((m)=>({...m,version:$.workspacePackages.find((n)=>n.name===m.name)?.version??m.version})):$.packageNames.map((m)=>({name:m,releaseType:$.releaseType,version:$.workspacePackages.find((n)=>n.name===m)?.version})),A=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return mA({slug:$.selectedSlug??B2(A),summary:A,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:V1(A),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function n2($,b,A,m){if(!$)return b;try{let n=await $.generateStructured({schema:A2,systemPrompt:"You write structured release metadata for a TypeScript monorepo. Be concise, concrete, and safe for public release notes.",prompt:JSON.stringify({draft:b,changedFiles:A.changedFiles.slice(0,40),commitMessages:A.commitMessages.slice(0,20),parseIssues:A.parseIssues})});return W2(b,n.object)}catch(n){return m.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:n instanceof Error?n.message:String(n)}),b}}function W2($,b){let A=[...$.audiences];return tn(A,"maintainer",b.maintainerSummary),tn(A,"customer",b.customerSummary),tn(A,"integrator",b.integratorSummary),mA({...$,summary:J1($.summary)?b.summary:$.summary,audiences:A,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function mA($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:V1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function w2($){let{releaseType:b,...A}=mA($);return{schemaVersion:"1",...A}}function V1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function tn($,b,A){let m=$.find((n)=>n.kind===b);if(m&&!J1(m.summary))return;if(m){m.summary=A;return}$.push({kind:b,summary:A})}function j2($,b,A){let m=new Set([...$.map((W)=>W.slug),...b.keys()].filter((W)=>W!=="auto-dependent-bumps"));if(m.size===1)return Array.from(m)[0];if(A.length===0)return;let n=Array.from(m).filter((W)=>{let w=b.get(W),j=$.find((B)=>B.slug===W);return(w?.packages.map((B)=>B.name)??j?.packages.map((B)=>B.name)??[]).some((B)=>A.includes(B))});return n.length===1?n[0]:void 0}function y2($){return $.length>0?"minor":"patch"}function J1($){return $.trim().startsWith("Describe the ")}function B2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as S2}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as Q2,DEFAULT_CONTRACTSRC as Z2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var K1="generated/releases",E0=Z2.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function _1($,b={}){let{fs:A,git:m,logger:n}=$,W=M(b.workspaceRoot),w=await $A(A,W),j=b.baseline?await m.diffFiles(b.baseline):[],y=b.packages&&b.packages.length>0?b.packages:L0(j,w),B=b.baseline?await Bb($,{baseline:b.baseline,workspaceRoot:W}):null,S=b.baseline?await V$($,{baseline:b.baseline,workspaceRoot:W}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??G2(y),Z=b.releaseType??Q,G=b.summary??`Describe the ${Z} release for ${y[0]??"the workspace"}`,X=b.slug??Y2(G),Y=y.map((H)=>({name:H,releaseType:Z,version:w.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:X,summary:G,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:Y,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:G},{kind:"customer",summary:G}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=A.join(W,".changeset",`${X}.md`),K=A.join(W,".changeset",`${X}.release.yaml`);if(!b.force){if(await A.exists(O))throw Error(`Changeset already exists: ${O}`);if(await A.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=R0(G,Y),_=C0(V);if(!b.dryRun)await A.writeFile(O,J),await A.writeFile(K,_);return n.info("Initialized release artifacts",{slug:X,workspaceRoot:W}),{slug:X,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:_,packages:Y,releaseType:Z,isBreaking:V.isBreaking}}async function U1($,b={}){let{fs:A,logger:m}=$,n=M(b.workspaceRoot),W=await L1(A,n),w=A.join(n,b.outputDir??K1),j=await eb(A,n),y=await sb(A,n,j);if(y.issues.length>0)throw Error(bA(y.issues));let B=y.capsules,S=await $A(A,n),Q=await Promise.all(Array.from(B.entries()).map(async([_,H])=>{let q=A.join(n,".changeset",`${_}.release.yaml`),U=await A.stat(q);return{slug:_,version:X2(H,S),summary:H.summary,date:U.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:H.isBreaking,packages:H.packages.map((z)=>({...z,version:S.find((L)=>L.name===z.name)?.version??z.version})),affectedRuntimes:[...H.affectedRuntimes],affectedFrameworks:[...H.affectedFrameworks],audiences:[...H.audiences],deprecations:[...H.deprecations],migrationInstructions:[...H.migrationInstructions],upgradeSteps:[...H.upgradeSteps],validation:H.validation}})),Z=S2.parse({generatedAt:new Date().toISOString(),releases:Q}),G=b.agentTargets??W.agentTargets??["codex"],X=lb(Z,[],G,yb),Y=A.join(w,"manifest.json"),V=A.join(w,"upgrade-manifest.json"),O=A.join(w,"patch-notes.md"),K=A.join(w,"customer-guide.md"),J=Object.fromEntries(X.agentPrompts.map((_)=>[_.agent,A.join(w,"prompts",`${_.agent}.md`)]));if(!b.dryRun){await A.writeFile(Y,JSON.stringify(Z,null,2)),await A.writeFile(V,JSON.stringify(Z,null,2)),await A.writeFile(O,fn(Z)),await A.writeFile(K,hn(Z));for(let _ of X.agentPrompts)await A.writeFile(J[_.agent]??"",_.prompt)}return m.info("Built release artifacts",{outputDir:w,releasesBuilt:Z.releases.length}),{outputDir:w,manifestPath:Y,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:X,releasesBuilt:Z.releases.length}}async function z1($,b={}){let{fs:A}=$,m=M(b.workspaceRoot),n=await L1(A,m),W=A.join(m,b.outputDir??K1),w=[],j=[],y=[],B=await eb(A,m),S=await sb(A,m,B),Q=S.capsules,Z=B.length>0,G=!Z&&Q.size>0;y.push(...S.issues.map((X)=>bA([X]))),Sb(w,Z||G,"changesets",Z?`Found ${B.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let X of B)if(!Q.has(X.slug)&&n.requireReleaseCapsule)y.push(`Missing release capsule for changeset ${X.slug}.`);for(let[X,Y]of Q){if(Y.isBreaking&&Y.migrationInstructions.length===0)y.push(`Breaking release ${X} is missing migration instructions.`);if(Y.validation.commands.length===0)y.push(`Release capsule ${X} is missing validation commands.`);if(Y.validation.evidence.length===0)y.push(`Release capsule ${X} is missing validation evidence.`)}if(b.baseline){try{let X=await V$($,{baseline:b.baseline,workspaceRoot:m});if(Sb(w,!0,"impact",`Impact status: ${X.status}`),X.summary.breaking>0&&!Array.from(Q.values()).some((Y)=>Y.isBreaking))y.push("Breaking impact detected without a breaking release capsule.")}catch(X){Sb(w,!1,"impact",M0(X)),y.push(`Impact detection failed: ${M0(X)}`)}try{let X=await AA($,{baseline:b.baseline,workspaceRoot:m});Sb(w,!0,"versioning",`${X.specsNeedingBump} spec(s) need version review.`)}catch(X){Sb(w,!1,"versioning",M0(X)),y.push(`Version analysis failed: ${M0(X)}`)}}if(b.strict)for(let X of n.publishArtifacts??[]){let Y=A.join(W,X);if(!await A.exists(Y))y.push(`Missing generated release artifact: ${Y}`)}if(Sb(w,y.length===0,"capsules",y.length===0?"All release capsules are complete.":y[0]??""),!Z&&!G)j.push("No pending release changesets were found.");return{success:y.length===0,errors:y,warnings:j,checks:w}}async function L1($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return E0;try{let m=JSON.parse(await $.readFile(A)),n=Q2.safeParse(m);return n.success?{...E0,...n.data.release}:E0}catch{return E0}}function G2($){return $.length>0?"minor":"patch"}function X2($,b){return $.packages.map((m)=>b.find((n)=>n.name===m.name)?.version??m.version).find((m)=>typeof m==="string")??"0.0.0"}function Y2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Sb($,b,A,m){$.push({name:A,ok:b,message:m})}function M0($){return $ instanceof Error?$.message:String($)}var g1={};P(g1,{silentLogger:()=>E1,runWorkflow:()=>M1,loadWorkflows:()=>en,loadVibeConfig:()=>T0,installPack:()=>v1,getWorkflow:()=>T1,exportContext:()=>I1,consoleLogger:()=>an,builtinWorkflows:()=>D0,DEFAULT_VIBE_CONFIG:()=>x0});import{existsSync as H2}from"fs";import{readFile as q2}from"fs/promises";import{join as pn}from"path";import O2 from"js-yaml";var x0={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function T0($){let b=$??process.cwd(),A=M(b)??b,m=[pn(A,".contractspec","vibe","config.json"),pn(A,".contractspec","vibe","config.yaml"),pn(A,".contractspec","vibe","config.yml")],n={};for(let W of m)if(H2(W))try{let w=await q2(W,"utf-8");if(W.endsWith(".json"))n=JSON.parse(w);else n=O2.load(w);break}catch(w){console.warn(`Warning: Failed to parse ${W}`,w)}return{...x0,...n}}import{existsSync as V2}from"fs";import{copyFile as J2,mkdir as C1,readFile as K2,writeFile as _2}from"fs/promises";import{dirname as U2,join as Qb}from"path";import{glob as z2}from"glob";var L2=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function I1($){let b=$??process.cwd(),A=M(b)??b,m=await T0(b),n=Qb(A,".contractspec","context"),W=Qb(n,"files"),w=[...L2],j=Qb(A,".gitignore");if(V2(j)){let Y=(await K2(j,"utf-8")).split(`
2469
+ `).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));w=[...w,...Y]}let y=m.contextExportAllowlist.length>0?m.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let X of y){let Y=await z2(X,{cwd:A,ignore:w,nodir:!0,dot:!0});B.push(...Y)}let S=Array.from(new Set(B)).sort();if(S.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await C1(W,{recursive:!0});let Q=[];for(let X of S){let Y=Qb(A,X),V=Qb(W,X);await C1(U2(V),{recursive:!0}),await J2(Y,V),Q.push({path:X,size:0})}let Z=Qb(n,"index.json"),G={generatedAt:new Date().toISOString(),files:Q.map((X)=>X.path),config:{allowlist:m.contextExportAllowlist,ignores:w.length}};return await _2(Z,JSON.stringify(G,null,2)),{success:!0,files:S,indexPath:Z}}var D0=[{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.
2149
2470
  Please review them and move selected files to contracts/ directory.
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(`
2471
+ 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:"release",label:"Prepare Release",command:"contractspec release prepare"},{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 R2}from"child_process";var E1={log:()=>{},warn:()=>{},error:()=>{}},an={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function M1($,b,A){let m=A?.logger??an,n=A?.prompter;if(m.log(`
2472
+ Running Workflow: ${$.name}`),$.description)m.log($.description);if(m.log(`Track: ${b.track}`),b.dryRun)m.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
2473
+ `);let W={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let w of $.steps){let j={id:w.id,name:w.label,status:"skip",command:w.command};if(w.tracks&&!w.tracks.includes(b.track)){W.steps.push(j);continue}if(w.condition){if(!await w.condition(b)){W.steps.push(j);continue}}if(m.log(`
2474
+ \uD83D\uDC49 Step: ${w.label}`),b.dryRun&&w.command)m.log(` Command: ${w.command}`);if(w.manualCheckpoint){if(b.dryRun)m.warn(" [Manual Checkpoint] Would pause here for user input.");else if(n){if(w.manualMessage)m.log(w.manualMessage);let y=await n.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(y==="abort")return m.warn("Workflow aborted by user."),W.success=!1,W.steps.push({...j,status:"skip",error:"Aborted by user"}),W;if(y==="skip"){m.warn(" \u2192 Skipped by user."),W.steps.push(j);continue}}}if(!b.dryRun)try{if(w.execute)await w.execute(b);else if(w.command)await C2(w.command,b.root);j.status="pass",W.stepsExecuted.push(w.id),W.steps.push(j),m.log(" \u2713 Completed")}catch(y){let B=y instanceof Error?y.message:String(y);return m.error(` \u274C Failed: ${B}`),W.success=!1,W.error=y instanceof Error?y:Error(String(y)),j.status="fail",j.error=B,W.stepsExecuted.push(w.id),W.steps.push(j),W}else W.steps.push(j)}return W}async function C2($,b){let A=$.split(" "),m=A[0],n=A.slice(1);if(!m)throw Error("Invalid command");return new Promise((W,w)=>{let j=R2(m,n,{cwd:b,stdio:"inherit",shell:!0});j.on("error",w),j.on("exit",(y)=>{if(y===0)W();else w(Error(`Command exited with code ${y}`))})})}import{existsSync as I2}from"fs";import{readdir as E2,readFile as M2}from"fs/promises";import{join as x1}from"path";import x2 from"js-yaml";async function en($){let b=[...D0],A=$??process.cwd(),m=M(A)??A,n=x1(m,".contractspec","vibe","workflows");if(I2(n))try{let W=await E2(n);for(let w of W)if(w.endsWith(".json")||w.endsWith(".yaml")||w.endsWith(".yml")){let j=await M2(x1(n,w),"utf-8");try{let y;if(w.endsWith(".json"))y=JSON.parse(j);else y=x2.load(j);if(y.id&&y.steps)b.push(y)}catch(y){console.warn(`Failed to parse workflow ${w}:`,y)}}}catch(W){console.warn("Error loading user workflows:",W)}return b}async function T1($,b){return(await en(b)).find((m)=>m.id===$)}import{existsSync as sn}from"fs";import{copyFile as D1,mkdir as N1,readdir as F1,stat as T2}from"fs/promises";import{join as E$,resolve as D2}from"path";async function v1($,b){let A=b??process.cwd(),m=M(A)??A;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let n=D2(A,$);if(!sn(n))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${n}`};let W=0,w=0,j=E$(n,"workflows");if(sn(j)){let B=E$(m,".contractspec","vibe","workflows");await N1(B,{recursive:!0});let S=await F1(j);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await D1(E$(j,Q),E$(B,Q)),W++}let y=E$(n,"templates");if(sn(y)){let B=E$(m,".contractspec","vibe","templates");await N1(B,{recursive:!0});let S=await F1(y);for(let Q of S){let Z=E$(y,Q),G=E$(B,Q);if((await T2(Z)).isFile())await D1(Z,G),w++}}return{success:!0,workflowsInstalled:W,templatesInstalled:w}}import{loadSpecFromSource as N2}from"@contractspec/module.workspace";var k1=["product","eng","qa"];function F2($){return k1.includes($)}async function yM($,b){if(!F2(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${k1.join(", ")}`);let A,m,n;if(b.specFiles&&b.specFiles.length>0)A=b.specFiles;else{let w=await v2($,{baseline:b.baseline});if(m=w.totalSpecs,n=w.changedFilesCount,b.baseline){if(w.changedFilesCount===0)return{views:[],totalSpecs:m,changedFilesCount:0,status:"no_changes"};if(w.specFiles.length===0)return{views:[],totalSpecs:m,changedFilesCount:n,status:"no_changed_specs"}}A=w.specFiles}if(A.length===0)return{views:[],totalSpecs:m,changedFilesCount:n,status:"no_specs"};let W=[];for(let w of A){let j=await g2(w,b.audience,$);W.push({filePath:w,content:j})}return{views:W,totalSpecs:m,changedFilesCount:n,status:"success"}}async function v2($,b={}){let m=(await j$({fs:$.fs})).map((j)=>j.filePath),n=m.length;if(!b.baseline)return{specFiles:m,totalSpecs:n};let W=await $.git.diffFiles(b.baseline);if(W.length===0)return{specFiles:[],totalSpecs:n,changedFilesCount:0,hasChanges:!1};let w=m.filter((j)=>W.some((y)=>j.endsWith(y)||y.endsWith(j)||j.includes(y)||y.includes(j)));return{specFiles:w,totalSpecs:n,changedFilesCount:W.length,hasChanges:w.length>0}}async function g2($,b,A){if(!await A.fs.exists($))throw Error(`File not found: ${$}`);let m=await N2($);if(m.length===0)return`No specs found in ${$} (Parse result empty)`;return m.map((n)=>k2(n,b)).join(`
2154
2475
 
2155
2476
  ---
2156
2477
 
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
2478
+ `)}function k2($,b){let A=[];switch(b){case"product":P2($,A);break;case"eng":r2($,A);break;case"qa":f2($,A);break}return A.join(`
2479
+ `)}function P2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
2159
2480
  ${$.meta.goal}
2160
- `);if($.meta.context)W.push(`### Context
2481
+ `);if($.meta.context)b.push(`### Context
2161
2482
  ${$.meta.context}
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};
2483
+ `);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- \u2705 Enforces Business Policies");if($.hasIo)b.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((A)=>b.push(`- **${A.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function r2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function f2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
2484
+ `);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((A)=>b.push(`- \uD83E\uDDEA \`${A.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((A)=>b.push(`- [ ] Verify event \`${A.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((A)=>b.push(`- [ ] Test Operation flow: \`${A.name}\``));if($.presentations?.length)$.presentations.forEach((A)=>b.push(`- [ ] Test UI Component: \`${A.name}\``))}}function ZM($,b,A,m){let{watcher:n,fs:W,logger:w}=$,j=n.watch(A),y=m?.validate??(async(S)=>{await d$(S,{fs:W,logger:w})}),B=m?.build??(async(S)=>{await $b(S,{fs:W,logger:w},b)});return j.on(async(S)=>{if(S.type!=="change")return;if(w.info("watchSpecs.changed",{path:S.path}),A.runValidate)await y(S.path);if(A.runBuild)if(A.dryRun)w.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),j}async function YM($,b){let A=OW(b),m=$.join(A.workspaceRoot,".contractsrc.json"),n=$.join(A.packageRoot,".contractsrc.json"),W=await $.exists(m),w=A.workspaceRoot!==A.packageRoot?await $.exists(n):!1,j;if(W)try{let y=await $.readFile(m),B=JSON.parse(y);if(B.packages||B.excludePackages||B.recursive)j={packages:B.packages,excludePackages:B.excludePackages,recursive:B.recursive}}catch{}return{...A,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?n:void 0}}async function HM($,b){let A=[],m=$.join(b,".contractsrc.json");if(await $.exists(m))A.push(m);let n=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let W of n)if(W!==m)A.push(W);return A}async function qM($,b,A){let m={};if(b&&await $.exists(b))try{let n=await $.readFile(b);m=JSON.parse(n)}catch{}if(A&&await $.exists(A))try{let n=await $.readFile(A),W=JSON.parse(n);m=P1(m,W)}catch{}return m}function P1($,b){let A={...$};for(let m of Object.keys(b)){let n=$[m],W=b[m];if(typeof n==="object"&&n!==null&&!Array.isArray(n)&&typeof W==="object"&&W!==null&&!Array.isArray(W))A[m]=P1(n,W);else A[m]=W}return A}function OM($){let b=[];if(b.push(`Package Manager: ${$.packageManager}`),b.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(b.push("Monorepo: Yes"),b.push(`Package Root: ${$.packageRoot}`),$.packageName)b.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)b.push(`Package Patterns: ${$.packages.join(", ")}`)}else b.push("Monorepo: No");if($.workspaceConfigPath)b.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)b.push(`Package Config: ${$.packageConfigPath}`);return b.join(`
2485
+ `)}export{ZM as watchSpecs,g1 as vibe,R1 as versioning,yG as verifyWithAIEnhanced,tb as verifyWithAI,pb as verifyStructure,IG as verifyService,n1 as verifySemanticFields,R6 as verifyImportedContracts,cz as verifyImplementationAgainstParsedSpec,J0 as verifyBehavior,XC as validateTenantConfig,yC as validateSpecs,d$ as validateSpec,zy as validateScannedSpec,sR as validatePackageScaffold,iR as validateImplementationWithAgent,dA as validateImplementationFiles,jC as validateDiscoveredSpecs,cR as validateBlueprint,F2 as validateAudience,WU as validateAgainstOpenApiService,Ew as utils,ly as upgrade,cC as updateSpec,TS as toKebabCase,Kw as templates,AU as syncWithOpenApiService,LC as syncSpecs,bG as stringToCacheKey,Tn as setupUsageMd,sA as setupGitignore,Rn as setupAgentsMd,fL as searchRegistry,p as safeParseJson,DC as runTests,NC as runTestSpecs,IR as runSetup,IL as runQuickstart,ew as runDoctor,IJ as runCIChecks,Fw as resolveSetupTargets,U$ as resolveSetupPreset,zn as resolveRegistryUrl,kS as resolveImplementations,wm as resolveDefaultBuildTargets,Sy as resolveAuthoredModuleValue,Sj as resolveAllImplementations,ub as renderManagedMarkdownBlock,IW as prompts,HW as parseGitModules,jj as parseExplicitImplementations,vY as operationRegistry,Hy as onboarding,Ln as normalizeMarkdownContent,Sx as module,qM as mergeMonorepoConfigs,Q0 as mergeManagedMarkdown,FQ as mergeGitignoreContent,g as loadWorkspaceConfig,fO as loadPackageAuthoredDocBlocks,yy as loadAuthoredModuleValue,nL as loadAuthoredModuleIfExists,y0 as loadAuthoredModuleExports,n$ as loadAuthoredModule,rO as loadAuthoredDocBlocksFromSourceFiles,FC as listTests,v2 as listSpecsForView,j$ as listSpecs,rL as listFromRegistry,bm as listAgentTypes,Gb as isMonorepo,EL as isContractSpecInstalled,vq as isConnectPreset,Fq as isBuilderPreset,zb as inferSetupPresetFromConfig,xS as inferImplementationType,V6 as importFromSourceService,lj as importFromOpenApiService,Uj as impact,Wy as hooks,pV as groupSpecsByType,UB as getWorkspacePackages,OW as getWorkspaceInfo,LX as getRunCommand,_n as getProductionDependencies,T$ as getPackageName,LB as getMetaRepoInfo,VW as getInstallCommand,qV as getImplementationSummary,Oq as getGraphStats,YM as getExtendedWorkspaceInfo,RX as getExecCommand,Un as getDevDependencies,Kn as getDependencies,wj as getConventionPaths,Hq as getContractNode,gA as getClaudeDesktopConfigPath,Om as getBuilderRuntimeModeForPreset,vw as getBuilderBootstrapPresetForSetupPreset,Rw as getApiKey,kV as getAllSpecs,$O as getAllLayerLocations,Yb as getAgentAdapter,d0 as getAIProvider,OA as genericMCPAdapter,Jw as generateWorkflowSpec,EA as generateWorkflowRunnerTemplate,zA as generateWorkflowDevkitWorkflowTemplate,CA as generateWorkflowDevkitStreamRouteTemplate,LA as generateWorkflowDevkitStartRouteTemplate,IA as generateWorkflowDevkitGenericTemplate,RA as generateWorkflowDevkitFollowUpRouteTemplate,vA as generateVscodeSettings,oW as generateVisualizationSpec,yM as generateViews,g2 as generateView,hw as generateUsageGuide,dW as generateTranslationSpec,Vw as generateThemeSpec,Sw as generateTestTemplate,cW as generateTestSpec,Ow as generateTelemetrySpec,tW as generateProductIntentSpec,qw as generatePresentationSpec,hW as generatePolicySpec,Hw as generateOperationSpec,Yw as generateMigrationSpec,fz as generateMermaidDiagram,z6 as generateMarkdownReport,Gw as generateKnowledgeSpaceSpec,uW as generateJobSpec,Zw as generateIntegrationSpec,aW as generateHarnessSuiteSpec,pW as generateHarnessScenarioSpec,yw as generateHandlerTemplate,T6 as generateGuideFromParsedSpec,jw as generateFormSpec,ww as generateFeatureSpec,lz as generateFeatureContextMarkdown,Ww as generateExperimentSpec,iW as generateExampleSpec,nw as generateEventSpec,bj as generateDocsFromSpecs,mw as generateDataViewSpec,_A as generateDataViewRendererTemplate,D6 as generateCursorRulesFromParsedSpec,rw as generateCursorRules,Lb as generateCursorMcpConfig,bb as generateContractsrcConfig,Bw as generateComponentTemplate,L6 as generateCliReport,Pw as generateClaudeMcpConfig,fW as generateCapabilitySpec,mj as generateArtifacts,Aw as generateAppBlueprintSpec,fw as generateAgentsGuide,lW as generateAgentSpec,xW as formatters,OM as formatWorkspaceInfo,dz as formatVerificationReport,ML as formatQuickstartPreview,By as formatModuleLoadError,N as formatJson,Xz as formatFiles,EO as formatDoctorSummary,MO as formatCheckResult,$y as fix,M as findWorkspaceRoot,r as findPackageRoot,qW as findMetaRepoRoot,HM as findAllConfigFiles,PV as filterIssuesByType,rV as filterIssuesBySeverity,pj as features,nj as extractSpecReferences,YU as extractContracts,tz as exportSpecForLLM,E4 as exportOpenApi,qq as exportGraphAsDot,Uw as ensurePackageScaffold,xA as discoverSpecs,g$ as discoverSpecFiles,PA as discoverLayers,uA as discoverImplementationsForSpec,ZV as discoverAllImplementations,yj as determineStatus,RB as detectRepositoryType,o$ as detectPackageManager,r_ as deleteSpec,$$ as deepMergePreserve,Vm as deepMergeOverwrite,HA as cursorCLIAdapter,GI as createWorkspaceStateCacheStorage,tB as createWorkspaceRegistry,CG as createVerifyService,_I as createVerificationCacheService,N_ as createSpecCreator,gw as createSetupNextSteps,kw as createSetupGitignorePatterns,gL as createRegeneratorService,V0 as createQuickAIReview,zw as createPackageTargetSpecSource,QW as createNoopLoggerAdapter,ZW as createNodeWatcherAdapter,BW as createNodeGitAdapter,jW as createNodeFsAdapter,mW as createNodeAiAdapter,XX as createNodeAdapters,QI as createInMemoryCacheStorage,BI as createFileSystemCacheStorage,P9 as createEmptyLayerInventory,SW as createConsoleLoggerAdapter,JX as createBunFsAdapter,q9 as createBuilderWorkspaceId,C5 as createAgentGuideService,cj as connect,$1 as computeContentHash,c_ as compareSpecs,vJ as cleanArtifacts,XA as claudeCodeAdapter,b1 as cacheKeyToString,$b as buildSpec,DA as analyzeWorkspaceDocBlocks,oA as analyzeIntegrity,Oz as analyzeGap,Mw as analyzeDeps,I5 as agentGuideService,$m as agentAdapters,s0 as adoption,PL as addToRegistry,WL as __moduleLoaderInternals,ey as WorkspaceStateCacheStorage,K0 as VerifyService,A1 as VerificationCacheService,k1 as VALID_AUDIENCES,XZ as TestGeneratorService,uj as SpecCreatorService,yA as SimpleAgent,xw as SETUP_TARGET_LABELS,Dw as SETUP_PRESET_LABELS,Nw as SETUP_PRESET_DESCRIPTIONS,Ub as SETUP_GITIGNORE_PATTERNS,w7 as RuleSyncService,S0 as RegistryClient,eB as PrActionService,jA as OpenAICodexAgent,qy as MINIMAL_DEPENDENCIES,ay as InMemoryCacheStorage,qA as GenericMCPAdapter,py as FileSystemCacheStorage,$7 as FULL_DEPENDENCIES,pB as DriftActionService,X$ as DEFAULT_SPEC_PATTERNS,x$ as DEFAULT_FS_IGNORES,sy as DEFAULT_CACHE_CONFIG,YA as CursorCLIAdapter,wA as CursorAgent,WA as ClaudeCodeAgent,GA as ClaudeCodeAdapter,G7 as CONTRACTSPEC_USAGE_BLOCK_START,X7 as CONTRACTSPEC_USAGE_BLOCK_END,y7 as CONTRACTSPEC_AGENTS_BLOCK_START,B7 as CONTRACTSPEC_AGENTS_BLOCK_END,xJ as CI_CHECK_CATEGORY_LABELS,aw as CHECK_CATEGORY_LABELS,BA as AgentOrchestrator,VA as AgentGuideService,_b as ALL_SETUP_TARGETS,Tw as ALL_SETUP_PRESETS,MJ as ALL_CI_CHECK_CATEGORIES,pw as ALL_CHECK_CATEGORIES,A0 as AIGenerator};