@contractspec/bundle.workspace 4.5.0 → 4.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundles/WorkspaceBundle.d.ts +34 -0
- package/dist/contracts/operations/init.operation.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +634 -539
- package/dist/node/index.js +634 -539
- package/dist/services/index.d.ts +1 -0
- package/dist/services/package-declarations/helpers.d.ts +13 -0
- package/dist/services/package-declarations/index.d.ts +5 -0
- package/dist/services/package-declarations/inventory.d.ts +4 -0
- package/dist/services/package-declarations/render.d.ts +41 -0
- package/dist/services/package-declarations/sync.d.ts +8 -0
- package/dist/services/package-declarations/sync.test.d.ts +1 -0
- package/dist/services/package-declarations/types.d.ts +48 -0
- package/dist/services/setup/setup-service.d.ts +17 -2
- package/dist/services/test/test-generator-service.d.ts +5 -1
- package/dist/services/workspace-info.d.ts +4 -1
- package/package.json +15 -15
package/dist/node/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)){if(!
|
|
3
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
4
|
-
`).map((
|
|
1
|
+
import{createRequire as VB}from"node:module";var HB=Object.defineProperty;var qB=($)=>$;function OB($,b){this[$]=qB.bind(null,b)}var f=($,b)=>{for(var n in b)HB($,n,{get:b[n],enumerable:!0,configurable:!0,set:OB.bind(b,n)})};var _y=($,b)=>()=>($&&(b=$($=0)),b);var F$=VB(import.meta.url);import{ContractsrcSchema as q8,DEFAULT_CONTRACTSRC as fn}from"@contractspec/lib.contracts-spec/workspace-config";async function P($,b){let n=$.join(b??".",".contractsrc.json");if(!await $.exists(n))return fn;try{let m=await $.readFile(n),y=JSON.parse(m),W=q8.safeParse(y);return{...fn,...W.data,conventions:{...fn.conventions,...W.data?.conventions||{}}}}catch{return fn}}function tW($){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 $$=()=>{};var Jj={};f(Jj,{AIGenerator:()=>GA});import{createProvider as G6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as H6,buildEventSpecPrompt as q6,buildFormPrompt as O6,buildHandlerPrompt as V6,buildOperationSpecPrompt as J6,buildPresentationSpecPrompt as U6,buildTestPrompt as K6,getCodeGenSystemPrompt as tb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Mm,generateText as YA,streamText as _6}from"ai";import*as R from"zod";class GA{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||tW(this.config.aiProvider),n={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return G6(n).getModel()}async generateOperationSpec($,b){let n=this.getModel(),A=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([])}),m=J6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateEventSpec($){let b=this.getModel(),n=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([])}),A=q6($);return(await Mm({model:b,schema:n,prompt:A,system:Em()})).object}async generatePresentationSpec($,b){let n=this.getModel(),A=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()}),m=U6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateHandler($){let b=this.getModel();return(await YA({model:b,prompt:V6($),system:tb()})).text}async generateComponent($){let b=this.getModel();return(await YA({model:b,prompt:H6($),system:tb()})).text}async generateForm($){let b=this.getModel();return(await YA({model:b,prompt:O6($),system:tb()})).text}async generateTests($,b,n){let A=this.getModel();return(await YA({model:A,prompt:K6($,b,n),system:tb()})).text}async streamCodeGeneration($,b){let n=this.getModel(),A=await _6({model:n,prompt:$,system:tb()}),m="";for await(let y of A.textStream)m+=y,b(y);return m}}var HA=_y(()=>{$$()});import*as gT from"@contractspec/module.workspace";import{anthropic as JB}from"@ai-sdk/anthropic";import{openai as zy}from"@ai-sdk/openai";import{DEFAULT_MODELS as Ly}from"@contractspec/lib.ai-providers/models";import{generateObject as UB,generateText as KB,streamText as _B}from"ai";import{ollama as zB}from"ollama-ai-provider";function Ry($){return{async validateProvider(b){try{let{aiProvider:n}=b;if(n==="ollama")return{success:!0};if(n==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(n==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}},async generateText(b){let n=tA($);return{text:(await KB({model:n,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let A={model:tA($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await UB(A)).object}},async streamText(b,n){let A=tA($),m=await _B({model:A,prompt:b.prompt,system:b.systemPrompt}),y="";for await(let W of m.textStream)y+=W,n(W);return y}}}function tA($){let{aiProvider:b,aiModel:n,customEndpoint:A}=$;switch(b){case"claude":{let m=n??Ly.anthropic;return JB(m)}case"openai":{let m=n??Ly.openai;return zy(m)}case"ollama":return zB(n??"codellama");case"custom":{if(!A)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return zy(n??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as hB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as LB,stat as RB,mkdir as Cy,readFile as CB,rm as xB,writeFile as IB}from"node:fs/promises";import{basename as EB,dirname as xy,isAbsolute as MB,join as TB,relative as DB,resolve as Iy}from"node:path";import{glob as NB}from"glob";var q$=["**/*.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","**/blueprint.ts","**/integration.ts","**/example.ts","**/bundles/*Bundle.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"],v$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function Ey($){let b=$??process.cwd();return{async exists(A){try{return await LB(n(A)),!0}catch{return!1}},async readFile(A){return CB(n(A),"utf-8")},async writeFile(A,m){let y=n(A),W=xy(y);await Cy(W,{recursive:!0}),await IB(y,m,"utf-8")},async remove(A){await xB(n(A),{recursive:!0,force:!0})},async stat(A){let m=await RB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await Cy(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return(await NB(m,{cwd:W,ignore:y,absolute:w})).sort((B,S)=>B.localeCompare(S))},resolve(...A){let[m,...y]=A;if(!m)return b;return Iy(b,m,...y)},dirname(A){return xy(A)},basename(A){return EB(A)},join(...A){return TB(...A)},relative(A,m){return DB(A,m)}};function n(A){return MB(A)?A:Iy(b,A)}}import{spawnSync as FB}from"node:child_process";import{existsSync as My,readFileSync as Ty}from"node:fs";import{access as vB}from"node:fs/promises";import{resolve as Xn}from"node:path";function Dy($){let b=$??process.cwd();return{async currentBranch(){try{let n=Ob(["rev-parse","--abbrev-ref","HEAD"],b).trim()||gB(b);return n.length>0?n:void 0}catch{return}},async showFile(n,A){try{let m=Ob(["show",`${n}:${A}`],b);if(m.length>0||n!=="HEAD")return m;return PB(b,A)??m}catch(m){throw Error(`Could not load ${A} at ref ${n}: ${m instanceof Error?m.message:String(m)}`)}},async clean(n){let A=[];if(n?.force)A.push("-f");if(n?.directories)A.push("-d");if(n?.ignored)A.push("-x");if(n?.dryRun)A.push("--dry-run");Ob(["clean",...A],b,{inherit:!0})},async isGitRepo(n){let A=n?Xn(b,n):b;try{return await vB(Xn(A,".git")),!0}catch{return!1}},async log(n){let A=n??"HEAD~10",m="--format=%H|||%s|||%an|||%aI";try{let y=Ob(["log",`${A}..HEAD`,"--format=%H|||%s|||%an|||%aI"],b),W=[];for(let w of y.trim().split(`
|
|
2
|
+
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(n,A){try{let m=A&&A.length>0?["--",...A]:[];return Ob(["diff","--name-only",`${n}...HEAD`,...m],b).trim().split(`
|
|
3
|
+
`).filter(Boolean)}catch{return[]}}}}function gB($){let b=Xn($,".git","HEAD");if(!My(b))return"";let n=Ty(b,"utf8").trim(),A="ref: refs/heads/";return n.startsWith(A)?n.slice(A.length):n}function PB($,b){let n=Xn($,b);if(!My(n))return;return Ty(n,"utf8")}function Ob($,b,n={}){let A=FB("git",$,{cwd:b,encoding:"utf-8",stdio:n.inherit?"inherit":["ignore","pipe","pipe"]});if(A.error)throw A.error;if(A.status!==0)throw Error(typeof A.stderr==="string"&&A.stderr.length>0?A.stderr:`git ${$.join(" ")} failed with status ${A.status??"unknown"}`);return typeof A.stdout==="string"?A.stdout:""}function Ny(){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 kB()}}}function Fy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:rB}}function kB(){return{start($){console.warn(`⏳ ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`✅ ${$??"Done"}`)},fail($){console.error(`❌ ${$??"Failed"}`)},warn($){console.warn(`⚠️ ${$??"Warning"}`)},stop(){}}}function rB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import fB from"chokidar";var cB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function vy($){let b=$??process.cwd();return{watch(n){let A=[],m,y=fB.watch(n.pattern,{cwd:b,ignored:n.ignore??cB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),W=(w)=>{if(n.debounceMs&&n.debounceMs>0)clearTimeout(m),m=setTimeout(()=>{A.forEach((j)=>j(w))},n.debounceMs);else A.forEach((j)=>j(w))};return y.on("add",(w)=>{W({type:"add",path:w})}),y.on("change",(w)=>{W({type:"change",path:w})}),y.on("unlink",(w)=>{W({type:"unlink",path:w})}),{on(w){A.push(w)},async close(){clearTimeout(m),await y.close()}}}}}function HG($={}){let{cwd:b,config:n,silent:A}=$,m=n??hB;return{fs:Ey(b),git:Dy(b),watcher:vy(b),ai:Ry(m),logger:A?Fy():Ny()}}import{stat as dB,mkdir as uB}from"node:fs/promises";import{basename as oB,dirname as iB,isAbsolute as tB,join as lB,relative as pB,resolve as gy}from"node:path";import{glob as aB}from"glob";function KG($){let b=$??process.cwd();return{async exists(A){let m=Bun.file(n(A));try{return await m.exists(),!0}catch{return!1}},async readFile(A){return Bun.file(n(A)).text()},async writeFile(A,m){let y=n(A);await Bun.write(y,m)},async remove(A){await Bun.file(n(A)).delete()},async stat(A){let m=await dB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await uB(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return await aB(m,{cwd:W,ignore:y,absolute:w})},resolve(...A){let[m,...y]=A;if(!m)return b;return gy(b,m,...y)},dirname(A){return iB(A)},basename(A){return oB(A)},join(...A){return lB(...A)},relative(A,m){return pB(A,m)}};function n(A){return tB(A)?A:gy(b,A)}}import{existsSync as u,readFileSync as z$}from"node:fs";import{tmpdir as eB}from"node:os";import{dirname as lA,isAbsolute as sB,join as d,relative as $S,resolve as p$}from"node:path";var Py={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},ky=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function bS($,b){let n=$S(b,$);return n===""||!n.startsWith("..")&&!sB(n)}function pA($){let b=p$($),n=p$(eB());return bS(b,n)?n:void 0}function c($=process.cwd()){let b=p$($),n=pA($);while(!0){if(u(d(b,"package.json")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return $}function I($=process.cwd()){let b=p$($),n=null,A=pA($);while(!0){for(let W of ky)if(u(d(b,W)))return b;let m=d(b,"package.json");if(u(m)){n=b;try{if(JSON.parse(z$(m,"utf-8")).workspaces)return b}catch{}}for(let W of Object.keys(Py))if(u(d(b,W)))return b;let y=lA(b);if(y===b||b===A)break;b=y}return n??$}function a$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let A of b){let m=Object.entries(Py).filter(([,y])=>y===A);for(let[y]of m)if(u(d($,y)))return A}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(A.packageManager){let m=A.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(m)return m[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Vb($=process.cwd()){for(let n of ky)if(u(d($,n)))return!0;let b=d($,"package.json");if(u(b))try{if(JSON.parse(z$(b,"utf-8")).workspaces)return!0}catch{}return!1}function nS($){let b=d($,"pnpm-workspace.yaml");if(u(b))try{let m=z$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(m?.[1])return m[1].split(`
|
|
4
|
+
`).map((W)=>W.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"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 g$($){let b=d($,"package.json");if(u(b))try{return JSON.parse(z$(b,"utf-8")).name}catch{}return}function ry($){let b=d($,".gitmodules");if(!u(b))return[];try{let n=z$(b,"utf-8"),A=[],m=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,y;while((y=m.exec(n))!==null){let[,W,w,j]=y;if(W&&w&&j){let B=d($,w),S=u(d(B,"package.json"))&&AS(B);A.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return A}catch{return[]}}function AS($){let b=d($,"package.json");if(u(b))try{let n=JSON.parse(z$(b,"utf-8"));return Boolean(n.workspaces)}catch{}return u(d($,"pnpm-workspace.yaml"))}function fy($){let b=p$($),n=pA($);while(!0){if(u(d(b,".gitmodules")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return}function mS($){let b=fy($);if(!b)return;let n=ry(b);if(n.length===0)return;let A=p$($),m=n.find((y)=>A.startsWith(y.absolutePath));return{root:b,submodules:n,activeSubmodule:m}}function yS($,b){let n=fy($);if(n){if(ry(n).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function cy($=process.cwd()){let b=c($),n=I($),A=a$(n),m=Vb(n),y=m?nS(n):void 0,W=g$(b),w=yS($,m),j=w==="meta-repo"?mS($):void 0;return{packageManager:A,workspaceRoot:n,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function CG($,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 xG($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function hy($,b=!1){let n=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${n}`.trim();case"pnpm":return`pnpm add ${n}`.trim();case"yarn":return`yarn add ${n}`.trim();case"npm":return`npm install ${n}`.trim()}}import{anthropic as dy}from"@ai-sdk/anthropic";import{generateText as uy}from"ai";class Yn{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=dy("claude-3-7-sonnet-20250219"),n=this.buildSystemPrompt($),A=this.buildUserPrompt($),m=await uy({model:b,prompt:A,system:n,temperature:0.2});return{success:!0,code:this.extractCode(m.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:m.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=dy("claude-3-7-sonnet-20250219"),n=`
|
|
5
5
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
6
6
|
|
|
7
7
|
SPECIFICATION:
|
|
@@ -30,7 +30,7 @@ Provide a structured validation report:
|
|
|
30
30
|
- Are there any missing edge cases?
|
|
31
31
|
|
|
32
32
|
Be thorough and precise. Use a critical but constructive tone.
|
|
33
|
-
`,
|
|
33
|
+
`,A=await uy({model:b,prompt:n,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),suggestions:this.extractSuggestions(A.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.
|
|
34
34
|
|
|
35
35
|
Your code is:
|
|
36
36
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -73,10 +73,10 @@ Spec:
|
|
|
73
73
|
${$.specCode}
|
|
74
74
|
|
|
75
75
|
Code:
|
|
76
|
-
${$.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"],
|
|
77
|
-
`);for(let
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
76
|
+
${$.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"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
77
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("error")||m.includes("bug")||m.includes("incorrect")||m.includes("missing"))b.push(A.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],n=$.split(`
|
|
78
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("warning")||m.includes("should")||m.includes("consider"))b.push(A.trim())}return b}extractSuggestions($){let b=[],n=$.split(`
|
|
79
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("suggest")||m.includes("recommend")||m.includes("could")||m.includes("improvement"))b.push(A.trim())}return b}}import{spawn as WS}from"child_process";import{existsSync as oy}from"fs";import{mkdir as iy,readFile as wS,rm as jS,writeFile as Y$}from"fs/promises";import{homedir as aA,tmpdir as ty}from"os";import{join as o}from"path";class Gn{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=o(ty(),`cursor-agent-${Date.now()}`);await iy(b,{recursive:!0});let n=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=o(ty(),`cursor-validate-${Date.now()}`);await iy(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let n=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),n}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",o(aA(),".cursor","cursor"),o(aA(),"AppData","Local","Programs","cursor","Cursor.exe"),o(aA(),"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(oy(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let n=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let A of n)try{let m=await A.fn();if(m.success)return m}catch(m){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 n=o(b,"spec.ts"),A=o(b,"output.ts"),m=o(b,"INSTRUCTIONS.md");if(await Y$(n,$.specCode),await Y$(m,this.buildDetailedPrompt($)),$.existingCode)await Y$(o(b,"existing.ts"),$.existingCode);return new Promise((y,W)=>{let w=["--wait","--new-window",b],j=WS(this.cursorPath,w,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";j.stdout?.on("data",(Q)=>{B+=Q.toString()}),j.stderr?.on("data",(Q)=>{S+=Q.toString()}),j.on("error",(Q)=>{W(Q)}),j.on("close",async(Q)=>{if(oy(A))try{let Z=await wS(A,"utf-8");y({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(()=>{j.kill(),W(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let n=o(b,"SPECIFICATION.ts"),A=o(b,"INSTRUCTIONS.md"),m=o(b,"template.ts");return await Y$(n,$.specCode),await Y$(A,this.buildDetailedPrompt($)),await Y$(m,this.generateTemplate($)),await Y$(o(b,"README.md"),`# Cursor Agent Workspace
|
|
80
80
|
|
|
81
81
|
This workspace was prepared for Cursor AI code generation.
|
|
82
82
|
|
|
@@ -92,18 +92,18 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
92
92
|
4. Save the result as output.ts
|
|
93
93
|
|
|
94
94
|
Workspace path: ${b}
|
|
95
|
-
`),{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
|
|
95
|
+
`),{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 Y$(o(b,"specification.ts"),$.specCode),await Y$(o(b,"implementation.ts"),$.existingCode||"// No implementation"),await Y$(o(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let n=[{path:"spec.ts",content:$.specCode}];if($.existingCode)n.push({path:"existing.ts",content:$.existingCode});return n}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
96
96
|
|
|
97
97
|
**Task Type:** ${$.type}
|
|
98
98
|
**Generated:** ${new Date().toISOString()}
|
|
99
99
|
|
|
100
|
-
`,
|
|
100
|
+
`,n=`## Specification
|
|
101
101
|
|
|
102
102
|
\`\`\`typescript
|
|
103
103
|
${$.specCode}
|
|
104
104
|
\`\`\`
|
|
105
105
|
|
|
106
|
-
`,
|
|
106
|
+
`,A={generate:`## Task: Generate Implementation
|
|
107
107
|
|
|
108
108
|
### Requirements:
|
|
109
109
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -196,7 +196,7 @@ ${$.existingCode||""}
|
|
|
196
196
|
- Enhance error messages
|
|
197
197
|
|
|
198
198
|
### Output Format:
|
|
199
|
-
Refactored code that maintains functionality while improving quality.`};return b+
|
|
199
|
+
Refactored code that maintains functionality while improving quality.`};return b+n+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
200
200
|
|
|
201
201
|
## Specification
|
|
202
202
|
\`\`\`typescript
|
|
@@ -254,7 +254,7 @@ export function implementation() {
|
|
|
254
254
|
// Implementation goes here
|
|
255
255
|
throw new Error('Not implemented');
|
|
256
256
|
}
|
|
257
|
-
`}async cleanupWorkDir($){try{await
|
|
257
|
+
`}async cleanupWorkDir($){try{await jS($,{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 ly}from"@ai-sdk/openai";import{generateText as py}from"ai";class Hn{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 n=this.isComplexTask($)?"o1":"gpt-5.4",A=ly(n),m=this.buildSystemPrompt($),y=this.buildUserPrompt($),W=await py({model:A,prompt:y,system:m,temperature:0.2});return{success:!0,code:this.extractCode(W.text),metadata:{model:n,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=ly("gpt-5.4"),n=`
|
|
258
258
|
Review this code implementation against its specification.
|
|
259
259
|
|
|
260
260
|
SPECIFICATION:
|
|
@@ -274,7 +274,7 @@ Provide a detailed validation report including:
|
|
|
274
274
|
4. Recommendations for improvement
|
|
275
275
|
|
|
276
276
|
Format as a structured report.
|
|
277
|
-
`,
|
|
277
|
+
`,A=await py({model:b,prompt:n,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.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"],n=($.specCode+($.existingCode||"")).toLowerCase();return b.some((A)=>n.includes(A))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
278
278
|
|
|
279
279
|
Generate production-quality code that is:
|
|
280
280
|
- Type-safe and well-typed
|
|
@@ -311,9 +311,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
311
311
|
${$.existingCode}
|
|
312
312
|
|
|
313
313
|
Spec:
|
|
314
|
-
${$.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"],
|
|
315
|
-
`);for(let
|
|
316
|
-
`);for(let
|
|
314
|
+
${$.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"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
315
|
+
`);for(let A of n)if(A.toLowerCase().includes("error")||A.toLowerCase().includes("bug")||A.toLowerCase().includes("fails"))b.push(A.trim());return b}extractWarnings($){let b=[],n=$.split(`
|
|
316
|
+
`);for(let A of n)if(A.toLowerCase().includes("warning")||A.toLowerCase().includes("should")||A.toLowerCase().includes("consider"))b.push(A.trim());return b}}import P$ from"chalk";import QS from"ora";import{generateText as ay}from"ai";var A0={};f(A0,{getCodeGenSystemPrompt:()=>n0,buildTestPrompt:()=>b0,buildHandlerPrompt:()=>eA,buildFormPrompt:()=>$0,buildComponentPrompt:()=>sA});function eA($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
317
317
|
|
|
318
318
|
Here is the contract spec:
|
|
319
319
|
|
|
@@ -332,7 +332,7 @@ Generate a complete handler implementation that:
|
|
|
332
332
|
|
|
333
333
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
334
334
|
|
|
335
|
-
Return only the TypeScript code for the handler function.`}function
|
|
335
|
+
Return only the TypeScript code for the handler function.`}function sA($){return`You are a senior React developer creating a component for a presentation specification.
|
|
336
336
|
|
|
337
337
|
Here is the presentation spec:
|
|
338
338
|
|
|
@@ -351,7 +351,7 @@ Generate a complete React component that:
|
|
|
351
351
|
|
|
352
352
|
The component should follow Atomic Design principles and be reusable.
|
|
353
353
|
|
|
354
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
354
|
+
Return only the TypeScript/TSX code for the component.`}function $0($){return`You are a senior React developer creating a form component from a form specification.
|
|
355
355
|
|
|
356
356
|
Here is the form spec:
|
|
357
357
|
|
|
@@ -371,7 +371,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
371
371
|
|
|
372
372
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
373
373
|
|
|
374
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
374
|
+
Return only the TypeScript/TSX code for the form component.`}function b0($,b,n){return`You are a senior developer writing comprehensive tests.
|
|
375
375
|
|
|
376
376
|
Spec:
|
|
377
377
|
\`\`\`typescript
|
|
@@ -384,7 +384,7 @@ ${b}
|
|
|
384
384
|
\`\`\`
|
|
385
385
|
|
|
386
386
|
Generate complete test suite using Vitest that:
|
|
387
|
-
${
|
|
387
|
+
${n==="handler"?`
|
|
388
388
|
- Test all acceptance scenarios from the spec
|
|
389
389
|
- Test error cases defined in spec.io.errors
|
|
390
390
|
- Verify events are emitted correctly
|
|
@@ -398,7 +398,7 @@ ${A==="handler"?`
|
|
|
398
398
|
|
|
399
399
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
400
400
|
|
|
401
|
-
Return only the TypeScript test code.`}function
|
|
401
|
+
Return only the TypeScript test code.`}function n0(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
402
402
|
- Type-safe API design
|
|
403
403
|
- React and modern hooks
|
|
404
404
|
- Test-driven development
|
|
@@ -412,7 +412,7 @@ Generate production-ready code that is:
|
|
|
412
412
|
- Defensive and error-safe
|
|
413
413
|
- Easy to maintain and extend
|
|
414
414
|
|
|
415
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
415
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as BS}from"@contractspec/lib.ai-providers";function m0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return BS(b)}class qn{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=m0(this.config),n=this.buildPrompt($),A=await ay({model:b,prompt:n,system:n0()});return{success:!0,code:A.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=m0(this.config),n=`
|
|
416
416
|
Review the following implementation against its specification.
|
|
417
417
|
|
|
418
418
|
Specification:
|
|
@@ -426,15 +426,15 @@ Provide a detailed validation report:
|
|
|
426
426
|
2. Are there any missing features?
|
|
427
427
|
3. Are there any bugs or issues?
|
|
428
428
|
4. Suggestions for improvement
|
|
429
|
-
`,
|
|
430
|
-
${$.specCode}`;case"test":return
|
|
431
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
429
|
+
`,A=await ay({model:b,prompt:n,system:"You are a code review expert. Provide thorough, constructive feedback."}),m=A.text.toLowerCase().includes("error")||A.text.toLowerCase().includes("missing")||A.text.toLowerCase().includes("incorrect");return{success:!m,code:A.text,warnings:m?["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 eA($.specCode);else if($.specCode.includes(".presentation."))return sA($.specCode);else if($.specCode.includes(".form."))return $0($.specCode);return`Generate implementation for:
|
|
430
|
+
${$.specCode}`;case"test":return b0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
431
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as SS}from"@contractspec/lib.ai-agent/agent/unified-agent";class y0{name;agent;constructor($,b,n={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=SS(n,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),n=await this.agent.run(b);return{success:!0,code:n.text,metadata:{finishReason:n.finishReason,usage:n.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:
|
|
432
432
|
${$.specCode}
|
|
433
433
|
|
|
434
434
|
`;if($.existingCode)b+=`Existing Code:
|
|
435
435
|
${$.existingCode}
|
|
436
436
|
|
|
437
|
-
`;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
|
|
437
|
+
`;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 On{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new qn($),n=new Gn,A=new Yn,m=new Hn;this.agents.set("simple",b),this.agents.set("cursor",n),this.agents.set("claude-code",A),this.agents.set("openai-codex",m),this.defaultAgent=b,this.agents.set("opencode-sdk",new y0("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),n=this.agents.get(b);if(!n)return console.log(P$.yellow(`⚠️ Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!n.canHandle($))return console.log(P$.yellow(`⚠️ Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let A=QS(`Executing with ${b} agent...`).start();try{let m=$.type==="validate"?await n.validate($):await n.generate($);if(m.success)return A.succeed(P$.green(`${b} agent completed successfully`)),m;A.warn(P$.yellow(`${b} agent failed, trying fallback...`));let y=this.getFallbackMode(b);if(y&&y!==b){let W=this.agents.get(y);if(W&&W.canHandle($))return $.type==="validate"?await W.validate($):await W.generate($)}return A.info(P$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(m){return A.fail(P$.red("Agent execution failed")),console.log(P$.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,n]of this.agents){let A={type:"generate",specCode:"test"},m=n.canHandle(A);$.push({mode:b,available:m,reason:m?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 ey={};f(ey,{specCreation:()=>W0,codeGeneration:()=>A0});var W0={};f(W0,{getSystemPrompt:()=>GS,buildPresentationSpecPrompt:()=>YS,buildOperationSpecPrompt:()=>ZS,buildEventSpecPrompt:()=>XS,addExampleContext:()=>HS});function ZS($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
438
438
|
|
|
439
439
|
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
440
440
|
|
|
@@ -452,7 +452,7 @@ Create a complete contract specification following these guidelines:
|
|
|
452
452
|
8. **Feature Flags**: Any flags that gate this operation
|
|
453
453
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
454
454
|
|
|
455
|
-
Respond with a structured spec.`}function
|
|
455
|
+
Respond with a structured spec.`}function XS($){return`You are a senior software architect creating an event specification.
|
|
456
456
|
|
|
457
457
|
User description: ${$}
|
|
458
458
|
|
|
@@ -466,7 +466,7 @@ Create a complete event specification following these guidelines:
|
|
|
466
466
|
|
|
467
467
|
Events represent things that have already happened and should use past tense.
|
|
468
468
|
|
|
469
|
-
Respond with a structured spec.`}function
|
|
469
|
+
Respond with a structured spec.`}function YS($,b){return`You are a senior software architect creating a presentation specification.
|
|
470
470
|
|
|
471
471
|
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]}.
|
|
472
472
|
|
|
@@ -484,7 +484,7 @@ Create a complete presentation specification following these guidelines:
|
|
|
484
484
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
485
485
|
- Data structure description`}
|
|
486
486
|
|
|
487
|
-
Respond with a structured spec.`}function
|
|
487
|
+
Respond with a structured spec.`}function GS(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
488
488
|
|
|
489
489
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
490
490
|
|
|
@@ -494,7 +494,7 @@ Your specs are:
|
|
|
494
494
|
- Business-oriented (capturing the "why" not just "what")
|
|
495
495
|
- Designed for both humans and AI agents to understand
|
|
496
496
|
|
|
497
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
497
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function HS($,b){if(b.length===0)return $;return`${$}
|
|
498
498
|
|
|
499
499
|
Here are some good examples for reference:
|
|
500
500
|
|
|
@@ -502,29 +502,29 @@ ${b.join(`
|
|
|
502
502
|
|
|
503
503
|
`)}
|
|
504
504
|
|
|
505
|
-
Follow this structure and quality level.`}var
|
|
506
|
-
`)}function
|
|
505
|
+
Follow this structure and quality level.`}import{defineModuleBundle as qS}from"@contractspec/lib.surface-runtime/spec";var L3=qS({meta:{key:"bundles.workspace",version:"1.0.0",title:"Workspace",description:"Workspace utilities for monorepo development"},routes:[{routeId:"default",path:"/",defaultSurface:"main"}],surfaces:{main:{surfaceId:"main",kind:"workbench",title:"Workspace",slots:[],layouts:[],data:[],verification:{dimensions:{guidance:"Scaffolded guidance profile for Workspace.",density:"Scaffolded density profile for Workspace.",dataDepth:"Scaffolded data-depth profile for Workspace.",control:"Scaffolded control profile for Workspace.",media:"Scaffolded media profile for Workspace.",pace:"Scaffolded pace profile for Workspace.",narrative:"Scaffolded narrative profile for Workspace."}}}}});var bW={};f(bW,{sarifToJson:()=>_S,formatAsTextLines:()=>$W,formatAsText:()=>zS,formatAsSarif:()=>JS,formatAsJson:()=>OS});function OS($,b={}){let{pretty:n=!0,driftResult:A}=b,m=$.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})),y=$.categories.filter((S)=>S.passed).length,W=$.totalErrors,w=$.totalWarnings,j=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:m,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:A?.hasDrift?"detected":"none",files:A?.files??[]},summary:{pass:y,fail:W,warn:w,note:j,total:y+W+w+j,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return n?JSON.stringify(B,null,2):JSON.stringify(B)}var VS={"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 JS($,b={}){let{toolName:n="ContractSpec",toolVersion:A="1.0.0",toolUri:m="https://contractspec.io",repositoryUri:y,workingDirectory:W}=b,w=new Map,j=new Map,B=$.issues.filter((X)=>X.file);for(let X of B)if(!w.has(X.ruleId)){let Y=VS[X.ruleId]??{name:X.ruleId,description:`Rule: ${X.ruleId}`},G={id:X.ruleId,name:Y.name,shortDescription:{text:Y.description},defaultConfiguration:{level:sy(X.severity)}};if(Y.helpUri)G.helpUri=Y.helpUri;j.set(X.ruleId,w.size),w.set(X.ruleId,G)}let S=B.map((X)=>{let Y={ruleId:X.ruleId,ruleIndex:j.get(X.ruleId)??0,level:sy(X.severity),message:{text:X.message}},G={physicalLocation:{artifactLocation:{uri:US(X.file),uriBaseId:"%SRCROOT%"}}};if(X.line!==void 0)G.physicalLocation.region={startLine:X.line,startColumn:X.column??1,endLine:X.endLine??X.line,endColumn:X.endColumn};return Y.locations=[G],Y.partialFingerprints={primaryLocationLineHash:KS(X)},Y}),Q=[];if(y)Q.push({repositoryUri:y,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:n,version:A,informationUri:m,rules:Array.from(w.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 sy($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function US($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function KS($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function _S($){return JSON.stringify($,null,2)}function $W($,b={}){let n=[],{verbose:A=!1,showTiming:m=!0,groupByFile:y=!1}=b;if(n.push({text:"",style:"normal"}),n.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),n.push({text:"",style:"normal"}),$.commitSha||$.branch){let w=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");n.push({text:`Git: ${w}`,style:"muted"})}n.push({text:"",style:"normal"}),n.push({text:"Check Results:",style:"bold"});for(let w of $.categories){let j=w.passed?"✓":"✗",B=w.passed?"success":"error",S=LS(w),Q=m?` (${w.durationMs}ms)`:"";n.push({text:` ${j} ${w.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(n.push({text:"",style:"normal"}),n.push({text:"Issues:",style:"bold"}),y){let w=RS($.issues);for(let[j,B]of w){n.push({text:"",style:"normal"}),n.push({text:` ${j||"(no file)"}`,style:"bold",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}else{let w=$.issues.filter((S)=>S.severity==="error"),j=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(w.length>0){n.push({text:"",style:"normal"}),n.push({text:" Errors:",style:"error",indent:1});for(let S of w)n.push(...Vn(S,A,2))}if(j.length>0){n.push({text:"",style:"normal"}),n.push({text:" Warnings:",style:"warning",indent:1});for(let S of j)n.push(...Vn(S,A,2))}if(B.length>0&&A){n.push({text:"",style:"normal"}),n.push({text:" Notes:",style:"muted",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}n.push({text:"",style:"normal"}),n.push({text:"─".repeat(50),style:"muted"});let W=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&A?`${$.totalNotes} note(s)`:null].filter(Boolean);if(W.length>0)n.push({text:`Found: ${W.join(", ")}`,style:$.success?"warning":"error"});if(m)n.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(n.push({text:"",style:"normal"}),$.success)n.push({text:"✅ All CI checks passed!",style:"success"});else n.push({text:"❌ CI checks failed",style:"error"});return n.push({text:"",style:"normal"}),n}function zS($,b={}){return $W($,b).map((A)=>" ".repeat(A.indent??0)+A.text).join(`
|
|
506
|
+
`)}function LS($){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 Vn($,b,n){let A=[],m=$.severity==="error"?"✗":$.severity==="warning"?"⚠":"○",y=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",W=`${m} ${$.message}`;if($.file){let w=$.line?`:${$.line}`:"";W+=` (${$.file}${w})`}if(A.push({text:W,style:y,indent:n}),b&&$.context){let w=JSON.stringify($.context);if(w!=="{}")A.push({text:`Context: ${w}`,style:"muted",indent:n+1})}return A}function RS($){let b=new Map;for(let n of $){let A=n.file??"";if(!b.has(A))b.set(A,[]);let m=b.get(A);if(m)m.push(n)}return new Map([...b.entries()].sort(([n],[A])=>n.localeCompare(A)))}import{OperationSpecRegistry as CS}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as xS}from"@contractspec/lib.contracts-spec/operations/report";function IS(){let $=new CS;return xS($),$}var f3=IS();class ES{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 n=$.drift?.status==="fail",A=!1;if(n&&b==="fail")A=!0;return{driftDetected:n,shouldFail:A}}}function MS($){if(!$)return"—";let b=new Date($),A=new Date().getTime()-b.getTime(),m=Math.floor(A/86400000);if(m<1)return"today";if(m===1)return"yesterday";return`${m} days ago`}class TS{collectChanges($,b,n){if($){let A=$.endsWith("/")?$:`${$}/`;return n.filter((m)=>m.startsWith(A))}if(b){let A=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return n.filter((m)=>A.test(m))}return n}detectDrift($){let b=$.map((n)=>n.slice(3)).filter((n)=>n&&n.trim().length>0).filter((n)=>n!==".contractspec-ci"&&!n.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},n=b.breaking||0,A=b.nonBreaking||0,m=b.total;if(m===void 0)m=n+A;let y=$?.breaking||!1,W="unknown";if($){if(y||n>0)W="breaking",y=!0;else if(A>0)W="non-breaking";else if(m===0)W="no-impact"}return{status:W,breaking:y,breakingCount:n,nonBreakingCount:A,total:m||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,n=this.deriveImpactStatus($.impactJson),A={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:n.status,breaking:n.breakingCount,nonBreaking:n.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 m=this.finalizeResults(A,$.failOn);if(m.shouldFail)A.nextSteps?.unshift(`CI failed: ${m.failReasons.join(", ")} (fail_on=${$.failOn}).`);return A}finalizeResults($,b){let n=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,A=$.drift?.status==="fail",m=$.validation?.status==="fail",y=$.risk?.status==="unknown",W=[],w=!1;if(b!=="never"){if(b==="breaking"){if(n)W.push("breaking changes detected");if(y)W.push("impact status unknown")}else if(b==="drift"){if(A)W.push("drift detected");if(y)W.push("impact status unknown")}else if(b==="any"){if(n)W.push("breaking changes detected");if(A)W.push("drift detected");if(m)W.push("validation failed");if(y)W.push("impact status unknown")}else W.push(`invalid fail_on value (${b})`);if(W.length>0)w=!0}return{driftDetected:A,breakingChangeDetected:n,validationFailed:m,shouldFail:w,failReasons:W}}generateReportMarkdown($,b){let n=(j,B=60000)=>{if(j.length<=B)return j;return`${j.slice(0,B)}
|
|
507
507
|
|
|
508
|
-
*(output truncated)*`},
|
|
509
|
-
`)},n
|
|
508
|
+
*(output truncated)*`},A=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
509
|
+
`)},m=n($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),y=n($.validation?.outputPath?b($.validation.outputPath):""),W=$.drift?.files??[],w=[];if(w.push("## ContractSpec Report"),w.push(""),$.contracts&&$.contracts.length>0){w.push("### Overall verification status"),w.push(""),w.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),w.push("| --- | --- | --- | --- | --- |");for(let j of $.contracts){let B=j.lastVerifiedSha??"—",S=MS(j.lastVerifiedDate),Q=j.surfaces.join(", ");w.push(`| ${j.name} | ${S} | ${j.driftMismatches} | ${Q} | ${B} |`)}w.push("")}if(w.push("### 1) What changed"),$.whatChanged?.summary)w.push($.whatChanged.summary);else w.push("No contract changes detected.");if(m.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Contract view (product)</summary>"),w.push(""),w.push(m),w.push(""),w.push("</details>");if(w.push(""),w.push("### 2) Risk classification"),$.risk?.status){let j=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);w.push(j.join(" | "))}else w.push("Impact analysis unavailable.");if(w.push(""),w.push("### 3) Validation results"),$.validation?.status){if(w.push(`Status: ${$.validation.status}`),y.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Validation output</summary>"),w.push(""),w.push(y),w.push(""),w.push("</details>")}else w.push("Validation step not run.");if(w.push(""),w.push("### 4) Drift results"),$.drift?.status){if(w.push(`Status: ${$.drift.status}`),W.length>0)w.push(""),w.push("<details>"),w.push("<summary>Drifted files</summary>"),w.push(""),w.push(A(W)),w.push(""),w.push("</details>")}else w.push("Drift check not run.");if(w.push(""),w.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)w.push(A($.nextSteps));else w.push("- No action required.");return`${w.join(`
|
|
510
510
|
`)}
|
|
511
|
-
`}}var s0={};P(s0,{uniqueTokens:()=>N$,tokenize:()=>i$,syncAdoptionCatalog:()=>K5,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 $5=[...vW,...TW,...DW,...NW,...FW];function QA(){return[...$5].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function i0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:QA()}}import{DEFAULT_CONTRACTSRC as B5}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 b5}from"node:path";import{ContractsrcSchema as A5,DEFAULT_CONTRACTSRC as t0}from"@contractspec/lib.contracts-spec/workspace-config";async function l$($,b={}){let A=b5(b.cwd??process.cwd()),m=b.workspaceRoot??M(A),n=b.packageRoot??r(A),W=b.config?PW(t0,b.config):await m5($,m,n);return{adoption:W.connect?.adoption??t0.connect.adoption,config:W,cwd:A,packageRoot:n,workspaceRoot:m}}async function m5($,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=A5.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 n5=["package.json","packages/*/package.json"];async function p0($,b){let[A,m]=await Promise.all([W5($,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 W5($,b){let A=await $.glob({patterns:n5,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:y5(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:j5(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 j5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function y5($){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=O5(b),n=N$([m,b.symbol??"",...b.paths??[]]),W=await p0($.fs,A),w=await V5($,A),j=await a0($.fs,A),y=S5(A,n,b,[...W.packageCandidates,...W.fileCandidates,...w,...J5(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=Y5(A,B,S,b.currentTarget);return{ambiguous:S,candidates:y,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:m,reason:q5(B,S),selected:B,verdict:Q}}function S5($,b,A,m){return m.filter((n)=>n.family===A.family&&G5($,n.family)).filter((n)=>X5(n,A.platform)).map((n)=>Q5(n,b,A.paths)).filter((n)=>n.score>40).sort((n,W)=>W.score-n.score).slice(0,8)}function Q5($,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:Z5($.source)+($.resolutionPriority??0)+w+j}}function Z5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function G5($,b){return $.adoption.families?.[b]??!0}function X5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function Y5($,b,A,m){let n=$.adoption.thresholds??B5.connect.adoption.thresholds;if(A)return n.ambiguous??"require_review";if(!b)return n.newImplementation??"require_review";if(b.candidate.source==="workspace")return H5(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 H5($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function q5($,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 O5($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function V5($,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 J5($,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 K5($,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)}
|
|
512
|
-
`),{catalog:
|
|
511
|
+
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>$5,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>Un,normalizeText:()=>wW,inferFamilyFromPath:()=>Z0,hasLocalShadcnRegistry:()=>Q0,getContractSpecAdoptionCatalog:()=>Jn,createAdoptionCatalogDocument:()=>w0,candidateTokens:()=>j0});function x($,b,n,A,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:n,packageKind:A,title:j.title??b,description:w,capabilityTags:y,preferredUseCases:W,avoidWhen:j.avoidWhen,platforms:j.platforms,replacementImportHints:j.replacementImportHints,resolutionPriority:m,runtimes:j.runtimes}}var nW=[x("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."),x("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."),x("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."),x("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."),x("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 AW=[x("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"]}),x("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"]}),x("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"]}),x("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"]}),x("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."),x("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."),x("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."),x("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 mW=[x("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."),x("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."),x("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."),x("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),x("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."),x("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."),x("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."),x("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."),x("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 yW=[x("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."),x("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."),x("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."),x("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."),x("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."),x("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 WW=[x("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."}]}),x("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"]}),x("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 DS=[...WW,...nW,...AW,...mW,...yW];function Jn(){return[...DS].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function w0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:Jn()}}import{DEFAULT_CONTRACTSRC as cS}from"@contractspec/lib.contracts-spec/workspace-config";function wW($){return $.toLowerCase().trim()}function e$($){return wW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function k$($){return[...new Set($.flatMap((b)=>e$(b)))]}function j0($){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 k$(b)}function Un($,b){let n=new Set(b);return $.filter((A)=>n.has(A)).length}import{resolve as NS}from"node:path";import{ContractsrcSchema as FS,DEFAULT_CONTRACTSRC as B0}from"@contractspec/lib.contracts-spec/workspace-config";async function s$($,b={}){let n=NS(b.cwd??process.cwd()),A=b.workspaceRoot??I(n),m=b.packageRoot??c(n),y=b.config?BW(B0,b.config):await vS($,A,m);return{adoption:y.connect?.adoption??B0.connect.adoption,config:y,cwd:n,packageRoot:m,workspaceRoot:A}}async function vS($,b,n){let A=B0;if(b!==n)A=await jW($,A,$.join(b,".contractsrc.json"));return jW($,A,$.join(n,".contractsrc.json"))}async function jW($,b,n){if(!await $.exists(n))return b;try{let A=JSON.parse(await $.readFile(n)),m=FS.safeParse(A);if(!m.success)return b;return BW(b,m.data)}catch{return b}}function BW($,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 gS=["package.json","packages/*/package.json"];async function S0($,b){let[n,A]=await Promise.all([PS($,b),kS($,b)]);return{fileCandidates:A,packageCandidates:n}}async function Q0($,b){let n=$.join(b.workspaceRoot,"components.json");if(await $.exists(n))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 PS($,b){let n=await $.glob({patterns:gS,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),A=[];for(let m of n)try{let y=JSON.parse(await $.readFile($.join(b.workspaceRoot,m))),W=Z0(m);if(!W)continue;let w=y.name??$.dirname(m);A.push({id:`workspace.package.${w}`,source:"workspace",family:W,title:w,description:y.description??`Local reusable package at ${m}.`,packageKind:fS(m),packageRef:w,capabilityTags:k$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return A}async function kS($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((A)=>{let m=Z0(A);if(!m)return[];let y=A.split("/").pop()?.replace(/\.[^.]+$/,"")??A;return[{id:`workspace.file.${A}`,source:"workspace",family:m,title:y,description:`Local reusable source at ${A}.`,filePath:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:rS(m,A)}]})}function Z0($){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 rS($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function fS($){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 Jb($,b){let n=await s$($.fs,b),A=aS(b),m=k$([A,b.symbol??"",...b.paths??[]]),y=await S0($.fs,n),W=await eS($,n),w=await Q0($.fs,n),j=hS(n,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...sS(b.family,b.platform,w)]),B=j[0]??null,S=j.length>1&&B!=null&&B.candidate.source===j[1].candidate.source&&Math.abs(B.score-j[1].score)<=40,Q=tS(n,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:A,reason:pS(B,S),selected:B,verdict:Q}}function hS($,b,n,A){return A.filter((m)=>m.family===n.family&&oS($,m.family)).filter((m)=>iS(m,n.platform)).map((m)=>dS(m,b,n.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function dS($,b,n){let A=j0($),m=k$(n??[]),y=[],W=Un(b,A)*25,w=Un(m,A)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:uS($.source)+($.resolutionPriority??0)+W+w}}function uS($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function oS($,b){return $.adoption.families?.[b]??!0}function iS($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function tS($,b,n,A){let m=$.adoption.thresholds??cS.connect.adoption.thresholds;if(n)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return lS(b.candidate,A)?"permit":m.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return m.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return m.newImplementation??"require_review";return m.newExternalDependency??"require_review"}function lS($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function pS($,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 aS($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function eS($,b){let n=Jn(),A=b.adoption.catalog?.overrideManifestPath;if(!A||!await $.fs.exists($.fs.join(b.workspaceRoot,A)))return n;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,A)),y=JSON.parse(m);return[...n,...Array.isArray(y)?y:y.entries??[]]}catch{return n}}function sS($,b,n){if($==="ui"&&b==="web"&&n)return[$b("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[$b("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[$b("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[$b("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[$b("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[$b("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function $b($,b,n,A,m){return{id:$,source:"ecosystem",packageRef:n,family:b,packageKind:"primitive",title:A,description:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:m}}async function $5($,b={}){let n=await s$($.fs,b),A=w0(),m=$.fs.join(n.workspaceRoot,n.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(m,`${JSON.stringify(A,null,2)}
|
|
512
|
+
`),{catalog:A,catalogPath:m}}import{AGENT_SYSTEM_PROMPTS as b5}from"@contractspec/lib.contracts-spec/llm";class Kn{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 n of $.fileStructure){let A=n.type==="create"?"\uD83D\uDCDD":"✏️";b.push(`${A} \`${n.path}\``),b.push(` ${n.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let n of $.steps){b.push(`### ${n.order}. ${n.title}`),b.push(""),b.push(n.description),b.push(""),b.push("**Acceptance Criteria:**");for(let A of n.acceptanceCriteria)b.push(`- [ ] ${A}`);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 n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let n of $.constraints.security)b.push(`- ⚠️ ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);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:b5["claude-code"],taskPrompt:b.join(`
|
|
513
513
|
`)}}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(`
|
|
514
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let
|
|
515
|
-
`)}}generateConfig($){let b=$.meta,
|
|
516
|
-
`)}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
|
|
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 b=$.meta,
|
|
518
|
-
`)}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
|
|
514
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let n=[],A=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let m of A){let y=$.matchAll(m);for(let W of y)if(W[1])n.push(W[1])}if(n.length>0)return{errors:n};return{code:$}}}var _n=new Kn;import{AGENT_SYSTEM_PROMPTS as n5}from"@contractspec/lib.contracts-spec/llm";class zn{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 A of $.fileStructure)b.push(`- ${A.type}: \`${A.path}\` - ${A.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let A of $.steps)b.push(`${A.order}. **${A.title}**: ${A.description}`);b.push("");let n=[...$.constraints.policy,...$.constraints.security.map((A)=>`⚠️ ${A}`)];if(n.length>0){b.push("## Constraints"),b.push("");for(let A of n)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((A)=>`\`${A}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:n5["cursor-cli"],taskPrompt:b.join(`
|
|
515
|
+
`)}}generateConfig($){let b=$.meta,n=[];if(n.push("---"),n.push(`description: Implementation rules for ${b.key}.v${b.version}`),n.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),n.push("alwaysApply: false"),n.push("---"),n.push(""),n.push(`# ${b.key} Implementation Rules`),n.push(""),n.push(`This ${b.kind} operation must follow the ContractSpec specification.`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Requirements"),n.push(""),n.push("1. Input/output types MUST match the spec schema exactly"),n.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)n.push("3. Events MUST be emitted as specified");if(n.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)n.push(`5. Idempotency: ${$.policy.idempotent}`);if(n.push(""),$.io.errors&&Object.keys($.io.errors).length>0){n.push("## Error Cases"),n.push("");for(let[A,m]of Object.entries($.io.errors))n.push(`- \`${A}\` (HTTP ${m.http??400}): ${m.when}`);n.push("")}if($.sideEffects?.emits?.length){n.push("## Events to Emit"),n.push("");for(let A of $.sideEffects.emits)if("ref"in A)n.push(`- \`${A.ref.key}.v${A.ref.version}\`: ${A.when}`);else n.push(`- \`${A.key}.v${A.version}\`: ${A.when}`);n.push("")}if($.policy.pii?.length){n.push("## PII Handling"),n.push(""),n.push("These fields contain PII and must be handled with care:");for(let A of $.policy.pii)n.push(`- \`${A}\``);n.push("")}if($.acceptance?.scenarios?.length){n.push("## Acceptance Scenarios"),n.push("");for(let A of $.acceptance.scenarios)n.push(`### ${A.key}`),n.push(`- Given: ${A.given.join("; ")}`),n.push(`- When: ${A.when.join("; ")}`),n.push(`- Then: ${A.then.join("; ")}`),n.push("")}return n.join(`
|
|
516
|
+
`)}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 Ln=new zn;import{AGENT_SYSTEM_PROMPTS as A5}from"@contractspec/lib.contracts-spec/llm";class Rn{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 n of $.fileStructure)b.push(`| \`${n.path}\` | ${n.type} | ${n.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let n of $.steps)if(b.push(`### Step ${n.order}: ${n.title}`),b.push(""),b.push(n.description),b.push(""),n.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let A of n.acceptanceCriteria)b.push(`- ${A}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let n of $.constraints.security)b.push(`- ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),{agent:"generic-mcp",systemPrompt:A5["generic-mcp"],taskPrompt:b.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 b=$.meta,n=[];return n.push(`# ${b.key} v${b.version}`),n.push(""),n.push(`**Type:** ${b.kind}`),n.push(`**Stability:** ${b.stability}`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Description"),n.push(""),n.push(b.description),n.push(""),n.join(`
|
|
518
|
+
`)}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 n=JSON.parse($);if(typeof n.code==="string")return{code:n.code};if(typeof n.errors==="object")return{errors:Array.isArray(n.errors)?n.errors:[String(n.errors)]}}catch{}return{code:$}}}var Cn=new Rn;var Y0={"claude-code":_n,"cursor-cli":Ln,"generic-mcp":Cn};function Ub($){let b=Y0[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function G0(){return Object.keys(Y0)}import{featureToMarkdown as H0,generateImplementationPlan as SW,operationSpecToAgentPrompt as m5,operationSpecToFullMarkdown as y5}from"@contractspec/lib.contracts-spec/llm";var W5={defaultAgent:"generic-mcp",verbose:!1};class xn{config;constructor($={}){this.config={...W5,...$}}generateGuide($,b={}){let n=b.agent??this.config.defaultAgent,A=Ub(n),m=SW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),y=A.formatPlan(m),W=y5($);return{plan:m,prompt:y,markdown:W}}generateFeatureGuide($,b,n={}){let A=n.agent??this.config.defaultAgent,m=Ub(A),y=$.operations?.[0],W=y?b.specs?.get(y.key,y.version):void 0,w;if(W)w=SW(W,{projectRoot:this.config.projectRoot}),w.target={type:"feature",key:$.meta.key,version:"1.0.0"},w.context.goal=$.meta.description??w.context.goal;else w={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:H0($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(w.specMarkdown=H0($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)w.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 j=m.formatPlan(w),B=H0($,b);return{plan:w,prompt:j,markdown:B}}generateAgentConfig($,b){return Ub(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,n="implement",A){return m5($,{taskType:n,existingCode:A})}listAgentTypes(){return G0()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function w5($){return new xn($)}var j5=new xn;import{detectAuthoringTarget as $8,generateComponentTemplate as b8,generateHandlerTemplate as n8,generateTestTemplate as A8,getAuthoringTargetDefinition as m8,inferSpecTypeFromFilePath as y8,scanSpecSource as W8}from"@contractspec/module.workspace";var dW={};f(dW,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});function QW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
519
519
|
|
|
520
|
-
export const ${
|
|
520
|
+
export const ${nb($.key)}Capability = defineCapability({
|
|
521
521
|
meta: {
|
|
522
522
|
key: '${$.key}',
|
|
523
523
|
version: '${$.version}',
|
|
524
524
|
kind: '${$.kind??"api"}',
|
|
525
|
-
title: '${k(
|
|
525
|
+
title: '${k(bb($))}',
|
|
526
526
|
description: '${k($.description)}',
|
|
527
|
-
domain: '${k(
|
|
527
|
+
domain: '${k(r$($))}',
|
|
528
528
|
owners: [${W$($.owners)}],
|
|
529
529
|
tags: [${W$($.tags)}],
|
|
530
530
|
stability: '${$.stability}',
|
|
@@ -532,15 +532,15 @@ export const ${a$($.key)}Capability = defineCapability({
|
|
|
532
532
|
provides: [],
|
|
533
533
|
requires: [],
|
|
534
534
|
});
|
|
535
|
-
`}function
|
|
535
|
+
`}function ZW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
536
536
|
|
|
537
|
-
export const ${
|
|
537
|
+
export const ${nb($.key)}Policy = definePolicy({
|
|
538
538
|
meta: {
|
|
539
539
|
key: '${$.key}',
|
|
540
540
|
version: '${$.version}',
|
|
541
|
-
title: '${k(
|
|
541
|
+
title: '${k(bb($))}',
|
|
542
542
|
description: '${k($.description)}',
|
|
543
|
-
domain: '${k(
|
|
543
|
+
domain: '${k(r$($))}',
|
|
544
544
|
owners: [${W$($.owners)}],
|
|
545
545
|
tags: [${W$($.tags)}],
|
|
546
546
|
stability: '${$.stability}',
|
|
@@ -550,27 +550,27 @@ export const ${a$($.key)}Policy = definePolicy({
|
|
|
550
550
|
{
|
|
551
551
|
effect: 'allow',
|
|
552
552
|
actions: ['read'],
|
|
553
|
-
resource: { type: '${k(
|
|
553
|
+
resource: { type: '${k(r$($))}' },
|
|
554
554
|
reason: 'TODO: replace with real access rules',
|
|
555
555
|
},
|
|
556
556
|
],
|
|
557
557
|
});
|
|
558
|
-
`}function
|
|
558
|
+
`}function XW($){let b=$.targetVersion??"1.0.0",n=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
559
559
|
|
|
560
|
-
export const ${
|
|
560
|
+
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
561
561
|
meta: {
|
|
562
562
|
key: '${$.key}',
|
|
563
563
|
version: '${$.version}',
|
|
564
|
-
title: '${k(
|
|
564
|
+
title: '${k(bb($))}',
|
|
565
565
|
description: '${k($.description)}',
|
|
566
|
-
domain: '${k(
|
|
566
|
+
domain: '${k(r$($))}',
|
|
567
567
|
owners: [${W$($.owners)}],
|
|
568
568
|
tags: [${W$($.tags)}],
|
|
569
569
|
stability: '${$.stability}',
|
|
570
570
|
},
|
|
571
571
|
target: {
|
|
572
572
|
type: '${$.targetType}',
|
|
573
|
-
${$.targetType}: ${
|
|
573
|
+
${$.targetType}: ${n},
|
|
574
574
|
},
|
|
575
575
|
scenarios: [
|
|
576
576
|
{
|
|
@@ -580,13 +580,13 @@ export const ${a$($.key)}TestSpec = defineTestSpec({
|
|
|
580
580
|
},
|
|
581
581
|
],
|
|
582
582
|
});
|
|
583
|
-
`}function
|
|
583
|
+
`}function YW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
584
584
|
|
|
585
|
-
export const ${
|
|
585
|
+
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
586
586
|
meta: {
|
|
587
587
|
key: '${$.key}',
|
|
588
588
|
version: '${$.version}',
|
|
589
|
-
domain: '${k(
|
|
589
|
+
domain: '${k(r$($))}',
|
|
590
590
|
description: '${k($.description)}',
|
|
591
591
|
owners: [${W$($.owners)}],
|
|
592
592
|
tags: [${W$($.tags)}],
|
|
@@ -596,20 +596,20 @@ export const ${a$(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
|
596
596
|
fallback: '${$.fallback??$.locale}',
|
|
597
597
|
messages: {
|
|
598
598
|
'${$.key}.title': {
|
|
599
|
-
value: '${k(
|
|
599
|
+
value: '${k(bb($))}',
|
|
600
600
|
description: 'TODO: replace with a real localized message',
|
|
601
601
|
},
|
|
602
602
|
},
|
|
603
603
|
});
|
|
604
|
-
`}function
|
|
604
|
+
`}function GW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
|
|
605
605
|
|
|
606
|
-
export const ${
|
|
606
|
+
export const ${nb($.key)}Job = defineJob({
|
|
607
607
|
meta: {
|
|
608
608
|
key: '${$.key}',
|
|
609
609
|
version: '${$.version}',
|
|
610
|
-
title: '${k(
|
|
610
|
+
title: '${k(bb($))}',
|
|
611
611
|
description: '${k($.description)}',
|
|
612
|
-
domain: '${k(
|
|
612
|
+
domain: '${k(r$($))}',
|
|
613
613
|
owners: [${W$($.owners)}],
|
|
614
614
|
tags: [${W$($.tags)}],
|
|
615
615
|
stability: '${$.stability}',
|
|
@@ -617,17 +617,17 @@ export const ${a$($.key)}Job = defineJob({
|
|
|
617
617
|
payload: { schema: {} },
|
|
618
618
|
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
619
619
|
});
|
|
620
|
-
`}function
|
|
620
|
+
`}function HW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
621
621
|
|
|
622
|
-
export const ${
|
|
622
|
+
export const ${nb($.key)}Visualization = defineVisualization({
|
|
623
623
|
meta: {
|
|
624
624
|
key: '${$.key}',
|
|
625
625
|
version: '${$.version}',
|
|
626
|
-
title: '${k(
|
|
626
|
+
title: '${k(bb($))}',
|
|
627
627
|
description: '${k($.description)}',
|
|
628
628
|
goal: 'TODO: describe the decision this visualization supports',
|
|
629
629
|
context: 'TODO: describe where this visualization appears',
|
|
630
|
-
domain: '${k(
|
|
630
|
+
domain: '${k(r$($))}',
|
|
631
631
|
owners: [${W$($.owners)}],
|
|
632
632
|
tags: [${W$($.tags)}],
|
|
633
633
|
stability: '${$.stability}',
|
|
@@ -645,19 +645,19 @@ export const ${a$($.key)}Visualization = defineVisualization({
|
|
|
645
645
|
measure: 'value',
|
|
646
646
|
},
|
|
647
647
|
});
|
|
648
|
-
`}function
|
|
648
|
+
`}function bb($){return $.title??B5($.key.split(".").at(-1)??$.key)}function r$($){return $.domain??$.key.split(".")[0]??"contractspec"}function W$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function nb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function B5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function In($){let b=$.packageName??`@contractspec/example.${Q5($.key.split(".").at(-1)??$.key)}`,n=`${Kb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
649
649
|
|
|
650
|
-
|
|
650
|
+
const ${n} = defineExample({
|
|
651
651
|
meta: {
|
|
652
652
|
key: '${$.key}',
|
|
653
653
|
version: '${$.version}',
|
|
654
|
-
title: '${
|
|
655
|
-
description: '${
|
|
654
|
+
title: '${t(En($))}',
|
|
655
|
+
description: '${t($.description)}',
|
|
656
656
|
kind: 'template',
|
|
657
657
|
visibility: 'experimental',
|
|
658
658
|
stability: '${$.stability}',
|
|
659
|
-
owners: [${
|
|
660
|
-
tags: [${
|
|
659
|
+
owners: [${S$($.owners)}],
|
|
660
|
+
tags: [${S$($.tags)}],
|
|
661
661
|
},
|
|
662
662
|
surfaces: {
|
|
663
663
|
templates: true,
|
|
@@ -669,49 +669,52 @@ export const ${Hb($.key)}Example = defineExample({
|
|
|
669
669
|
packageName: '${b}',
|
|
670
670
|
},
|
|
671
671
|
});
|
|
672
|
-
`}function lW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
673
672
|
|
|
674
|
-
export
|
|
673
|
+
export default ${n};
|
|
674
|
+
export { ${n} };
|
|
675
|
+
`}function qW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
676
|
+
|
|
677
|
+
export const ${Kb($.key)}Agent = defineAgent({
|
|
675
678
|
meta: {
|
|
676
679
|
key: '${$.key}',
|
|
677
680
|
version: '${$.version}',
|
|
678
|
-
description: '${
|
|
679
|
-
owners: [${
|
|
680
|
-
tags: [${
|
|
681
|
+
description: '${t($.description)}',
|
|
682
|
+
owners: [${S$($.owners)}],
|
|
683
|
+
tags: [${S$($.tags)}],
|
|
681
684
|
stability: '${$.stability}',
|
|
682
685
|
},
|
|
683
|
-
instructions: '${
|
|
686
|
+
instructions: '${t($.instructions)}',
|
|
684
687
|
tools: [{ name: 'todo' }],
|
|
685
688
|
});
|
|
686
|
-
`}function
|
|
689
|
+
`}function OW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
687
690
|
|
|
688
|
-
export const ${
|
|
691
|
+
export const ${Kb($.key)}ProductIntent = defineProductIntentSpec({
|
|
689
692
|
id: '${$.id??`${$.key}-run`}',
|
|
690
693
|
meta: {
|
|
691
694
|
key: '${$.key}',
|
|
692
695
|
version: '${$.version}',
|
|
693
|
-
title: '${
|
|
694
|
-
description: '${
|
|
696
|
+
title: '${t(En($))}',
|
|
697
|
+
description: '${t($.description)}',
|
|
695
698
|
goal: 'TODO: capture the desired product outcome',
|
|
696
699
|
context: 'TODO: capture the decision context',
|
|
697
700
|
stability: '${$.stability}',
|
|
698
|
-
owners: [${
|
|
699
|
-
tags: [${
|
|
701
|
+
owners: [${S$($.owners)}],
|
|
702
|
+
tags: [${S$($.tags)}],
|
|
700
703
|
},
|
|
701
|
-
question: '${
|
|
704
|
+
question: '${t($.question)}',
|
|
702
705
|
insights: { insights: [] },
|
|
703
706
|
});
|
|
704
|
-
`}function
|
|
707
|
+
`}function VW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
705
708
|
|
|
706
|
-
export const ${
|
|
709
|
+
export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
707
710
|
meta: {
|
|
708
711
|
key: '${$.key}',
|
|
709
712
|
version: '${$.version}',
|
|
710
|
-
title: '${
|
|
711
|
-
description: '${
|
|
712
|
-
domain: '${
|
|
713
|
-
owners: [${
|
|
714
|
-
tags: [${
|
|
713
|
+
title: '${t(En($))}',
|
|
714
|
+
description: '${t($.description)}',
|
|
715
|
+
domain: '${t(UW($))}',
|
|
716
|
+
owners: [${S$($.owners)}],
|
|
717
|
+
tags: [${S$($.tags)}],
|
|
715
718
|
stability: '${$.stability}',
|
|
716
719
|
},
|
|
717
720
|
target: {
|
|
@@ -736,17 +739,17 @@ export const ${Hb($.key)}HarnessScenario = defineHarnessScenario({
|
|
|
736
739
|
},
|
|
737
740
|
],
|
|
738
741
|
});
|
|
739
|
-
`}function
|
|
742
|
+
`}function JW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
740
743
|
|
|
741
|
-
export const ${
|
|
744
|
+
export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
742
745
|
meta: {
|
|
743
746
|
key: '${$.key}',
|
|
744
747
|
version: '${$.version}',
|
|
745
|
-
title: '${
|
|
746
|
-
description: '${
|
|
747
|
-
domain: '${
|
|
748
|
-
owners: [${
|
|
749
|
-
tags: [${
|
|
748
|
+
title: '${t(En($))}',
|
|
749
|
+
description: '${t($.description)}',
|
|
750
|
+
domain: '${t(UW($))}',
|
|
751
|
+
owners: [${S$($.owners)}],
|
|
752
|
+
tags: [${S$($.tags)}],
|
|
750
753
|
stability: '${$.stability}',
|
|
751
754
|
},
|
|
752
755
|
scenarios: [
|
|
@@ -759,94 +762,94 @@ export const ${Hb($.key)}HarnessSuite = defineHarnessSuite({
|
|
|
759
762
|
weight: 1,
|
|
760
763
|
},
|
|
761
764
|
],
|
|
762
|
-
summary: '${
|
|
763
|
-
tags: [${
|
|
765
|
+
summary: '${t($.description)}',
|
|
766
|
+
tags: [${S$($.tags)}],
|
|
764
767
|
});
|
|
765
|
-
`}function
|
|
766
|
-
`:"";return`import
|
|
768
|
+
`}function En($){return $.title??S5($.key.split(".").at(-1)??$.key)}function UW($){return $.domain??$.key.split(".")[0]??"contractspec"}function S$($){return $.map((b)=>`'${t(b)}'`).join(", ")}function Kb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function S5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Q5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function LW($){let b=J5($.key.split(".").pop()??"App")+"AppConfig",n=Z5($),A=X5($),m=KW("dataViews",$.dataViews),y=KW("workflows",$.workflows),W=Y5($),w=G5($),j=H5($),B=q5($),S=O5($),Q=V5($),Z=$.notes?` notes: '${T($.notes)}',
|
|
769
|
+
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
767
770
|
|
|
768
|
-
export const ${b}
|
|
771
|
+
export const ${b} = defineAppConfig({
|
|
769
772
|
meta: {
|
|
770
|
-
key: '${
|
|
773
|
+
key: '${T($.key)}',
|
|
771
774
|
version: '${$.version}',
|
|
772
|
-
title: '${
|
|
773
|
-
description: '${
|
|
774
|
-
domain: '${
|
|
775
|
-
owners: [${$.owners.map((
|
|
776
|
-
tags: [${$.tags.map((
|
|
775
|
+
title: '${T($.title)}',
|
|
776
|
+
description: '${T($.description)}',
|
|
777
|
+
domain: '${T($.domain)}',
|
|
778
|
+
owners: [${$.owners.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
779
|
+
tags: [${$.tags.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
777
780
|
stability: '${$.stability}',
|
|
778
|
-
appId: '${
|
|
781
|
+
appId: '${T($.appId)}',
|
|
779
782
|
},
|
|
780
|
-
${A}${m}${
|
|
781
|
-
`}function
|
|
782
|
-
`:"",
|
|
783
|
+
${n}${A}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
784
|
+
`}function Z5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((A)=>_W(A)).join(", ")}],
|
|
785
|
+
`:"",n=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((A)=>_W(A)).join(", ")}],
|
|
783
786
|
`:"";return` capabilities: {
|
|
784
|
-
${b}${
|
|
785
|
-
`}function
|
|
786
|
-
`:"",
|
|
787
|
+
${b}${n} },
|
|
788
|
+
`}function X5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
789
|
+
`:"",n=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
787
790
|
`:"";return` features: {
|
|
788
|
-
${b}${
|
|
789
|
-
`}function
|
|
790
|
-
key: '${
|
|
791
|
-
version: '${
|
|
791
|
+
${b}${n} },
|
|
792
|
+
`}function KW($,b){if(b.length===0)return"";let n=b.map((A)=>` ${A.slot}: {
|
|
793
|
+
key: '${T(A.key)}'${A.version?`,
|
|
794
|
+
version: '${A.version}'`:""}
|
|
792
795
|
}`).join(`,
|
|
793
796
|
`);return` ${$}: {
|
|
794
|
-
${
|
|
797
|
+
${n}
|
|
795
798
|
},
|
|
796
|
-
`}function
|
|
797
|
-
${$.policyRefs.map((
|
|
798
|
-
key: '${
|
|
799
|
-
version: '${
|
|
799
|
+
`}function Y5($){if($.policyRefs.length===0)return"";return` policies: [
|
|
800
|
+
${$.policyRefs.map((n)=>` {
|
|
801
|
+
key: '${T(n.key)}'${n.version?`,
|
|
802
|
+
version: '${n.version}'`:""}
|
|
800
803
|
}`).join(`,
|
|
801
804
|
`)}
|
|
802
805
|
],
|
|
803
|
-
`}function
|
|
804
|
-
`,
|
|
806
|
+
`}function G5($){if(!$.theme)return"";let b=` primary: { key: '${T($.theme.key)}', version: '${$.theme.version}' },
|
|
807
|
+
`,n=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((A)=>`{ key: '${T(A.key)}', version: '${A.version}' }`).join(", ")}],
|
|
805
808
|
`:"";return` theme: {
|
|
806
|
-
${b}${
|
|
807
|
-
`}function
|
|
809
|
+
${b}${n} },
|
|
810
|
+
`}function H5($){if(!$.telemetry)return"";return` telemetry: {
|
|
808
811
|
spec: {
|
|
809
|
-
key: '${
|
|
812
|
+
key: '${T($.telemetry.key)}'${$.telemetry.version?`,
|
|
810
813
|
version: '${$.telemetry.version}'`:""}
|
|
811
814
|
},
|
|
812
815
|
},
|
|
813
|
-
`}function
|
|
814
|
-
`:"",
|
|
816
|
+
`}function q5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((A)=>zW(A)).join(", ")}],
|
|
817
|
+
`:"",n=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((A)=>zW(A)).join(", ")}],
|
|
815
818
|
`:"";return` experiments: {
|
|
816
|
-
${b}${
|
|
817
|
-
`}function
|
|
818
|
-
${$.featureFlags.map((
|
|
819
|
-
key: '${
|
|
820
|
-
enabled: ${
|
|
821
|
-
${
|
|
822
|
-
${
|
|
819
|
+
${b}${n} },
|
|
820
|
+
`}function O5($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
821
|
+
${$.featureFlags.map((n)=>` {
|
|
822
|
+
key: '${T(n.key)}',
|
|
823
|
+
enabled: ${n.enabled},
|
|
824
|
+
${n.variant?`variant: '${T(n.variant)}',`:""}
|
|
825
|
+
${n.description?`description: '${T(n.description)}',`:""}
|
|
823
826
|
}`).join(`,
|
|
824
827
|
`)}
|
|
825
828
|
],
|
|
826
|
-
`}function
|
|
827
|
-
${$.routes.map((
|
|
829
|
+
`}function V5($){if($.routes.length===0)return"";return` routes: [
|
|
830
|
+
${$.routes.map((n)=>{return` { ${[`path: '${T(n.path)}'`,n.label?`label: '${T(n.label)}'`:null,n.dataView?`dataView: '${T(n.dataView)}'`:null,n.workflow?`workflow: '${T(n.workflow)}'`:null,n.guardKey?`guard: { key: '${T(n.guardKey)}'${n.guardVersion?`, version: '${n.guardVersion}'`:""} }`:null,n.featureFlag?`featureFlag: '${T(n.featureFlag)}'`:null,n.experimentKey?`experiment: { key: '${T(n.experimentKey)}'${n.experimentVersion?`, version: '${n.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
828
831
|
`)}
|
|
829
832
|
],
|
|
830
|
-
`}function
|
|
831
|
-
key: '${
|
|
832
|
-
label: '${
|
|
833
|
-
dataPath: '${
|
|
834
|
-
${
|
|
835
|
-
${
|
|
836
|
-
${
|
|
833
|
+
`}function _W($){return`{ key: '${T($)}' }`}function zW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${T($.key)}'${b} }`}function J5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=U5($.name.split(".").pop()??"DataView")+"DataView",n=$.fields.map((y)=>` {
|
|
834
|
+
key: '${y.key}',
|
|
835
|
+
label: '${Mn(y.label)}',
|
|
836
|
+
dataPath: '${y.dataPath}',
|
|
837
|
+
${y.format?`format: '${y.format}',`:""}
|
|
838
|
+
${y.sortable?"sortable: true,":""}
|
|
839
|
+
${y.filterable?"filterable: true,":""}
|
|
837
840
|
}`).join(`,
|
|
838
|
-
`),
|
|
841
|
+
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((y)=>`'${y}'`).join(", ")}],`:"",m=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
839
842
|
|
|
840
843
|
export const ${b}: DataViewSpec = {
|
|
841
844
|
meta: {
|
|
842
845
|
key: '${$.name}',
|
|
843
846
|
version: ${$.version},
|
|
844
847
|
entity: '${$.entity}',
|
|
845
|
-
title: '${
|
|
846
|
-
description: '${
|
|
847
|
-
domain: '${
|
|
848
|
-
owners: [${$.owners.map((
|
|
849
|
-
tags: [${$.tags.map((
|
|
848
|
+
title: '${Mn($.title)}',
|
|
849
|
+
description: '${Mn($.description||"Describe the purpose of this data view.")}',
|
|
850
|
+
domain: '${Mn($.domain||$.entity)}',
|
|
851
|
+
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
852
|
+
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
850
853
|
stability: '${$.stability}',
|
|
851
854
|
},
|
|
852
855
|
source: {
|
|
@@ -854,7 +857,7 @@ export const ${b}: DataViewSpec = {
|
|
|
854
857
|
name: '${$.primaryOperation.name}',
|
|
855
858
|
version: ${$.primaryOperation.version},
|
|
856
859
|
},
|
|
857
|
-
${
|
|
860
|
+
${m}
|
|
858
861
|
refreshEvents: [
|
|
859
862
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
860
863
|
],
|
|
@@ -862,10 +865,10 @@ export const ${b}: DataViewSpec = {
|
|
|
862
865
|
view: {
|
|
863
866
|
kind: '${$.kind}',
|
|
864
867
|
fields: [
|
|
865
|
-
${
|
|
868
|
+
${n}
|
|
866
869
|
],
|
|
867
870
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
868
|
-
${
|
|
871
|
+
${A}
|
|
869
872
|
filters: [
|
|
870
873
|
// Example filter:
|
|
871
874
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -880,13 +883,13 @@ ${A}
|
|
|
880
883
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
881
884
|
},
|
|
882
885
|
};
|
|
883
|
-
`}function
|
|
886
|
+
`}function U5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Mn($){return $.replace(/'/g,"\\'")}function Tn({exportName:$,specImportPath:b,rendererName:n,viewKind:A}){return`'use client';
|
|
884
887
|
|
|
885
888
|
import * as React from 'react';
|
|
886
889
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
887
890
|
import { ${$} } from '${b}';
|
|
888
891
|
|
|
889
|
-
export interface ${
|
|
892
|
+
export interface ${n}Props {
|
|
890
893
|
items?: Record<string, unknown>[];
|
|
891
894
|
item?: Record<string, unknown> | null;
|
|
892
895
|
className?: string;
|
|
@@ -896,17 +899,17 @@ export interface ${A}Props {
|
|
|
896
899
|
}
|
|
897
900
|
|
|
898
901
|
/**
|
|
899
|
-
* Auto-generated renderer for the "${
|
|
902
|
+
* Auto-generated renderer for the "${A}" data view.
|
|
900
903
|
* Customize as needed for app-specific behaviour.
|
|
901
904
|
*/
|
|
902
|
-
export function ${
|
|
905
|
+
export function ${n}({
|
|
903
906
|
items = [],
|
|
904
907
|
item = null,
|
|
905
908
|
className,
|
|
906
909
|
renderActions,
|
|
907
910
|
onSelect,
|
|
908
911
|
onRowClick,
|
|
909
|
-
}: ${
|
|
912
|
+
}: ${n}Props) {
|
|
910
913
|
return (
|
|
911
914
|
<DataViewRenderer
|
|
912
915
|
spec={${$}}
|
|
@@ -919,7 +922,7 @@ export function ${A}({
|
|
|
919
922
|
/>
|
|
920
923
|
);
|
|
921
924
|
}
|
|
922
|
-
`}function
|
|
925
|
+
`}function CW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,piiFields:w}=$,j=K5(b.replace(/\./g,"_"))+"V"+n,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
923
926
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
924
927
|
|
|
925
928
|
// TODO: Define event payload schema
|
|
@@ -932,80 +935,80 @@ export const ${B} = new SchemaModel({
|
|
|
932
935
|
},
|
|
933
936
|
});
|
|
934
937
|
|
|
935
|
-
export const ${
|
|
938
|
+
export const ${j} = defineEvent({
|
|
936
939
|
name: '${b}',
|
|
937
940
|
name: '${b}',
|
|
938
|
-
version: '${
|
|
939
|
-
description: '${
|
|
940
|
-
description: '${
|
|
941
|
-
stability: '${
|
|
942
|
-
owners: [${
|
|
943
|
-
tags: [${
|
|
944
|
-
${
|
|
941
|
+
version: '${n}',
|
|
942
|
+
description: '${A}',
|
|
943
|
+
description: '${A}',
|
|
944
|
+
stability: '${m}',
|
|
945
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
946
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
947
|
+
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
945
948
|
payload: ${B},
|
|
946
949
|
});
|
|
947
|
-
`}function
|
|
948
|
-
${
|
|
949
|
-
type: '${
|
|
950
|
-
target: '${
|
|
951
|
-
${typeof
|
|
950
|
+
`}function K5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function xW($){let b=z5($.name.split(".").pop()??"Experiment")+"Experiment",n=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
951
|
+
${y.overrides.map((w)=>` {
|
|
952
|
+
type: '${w.type}',
|
|
953
|
+
target: '${h(w.target)}',
|
|
954
|
+
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
952
955
|
}`).join(`,
|
|
953
956
|
`)}
|
|
954
957
|
],`:"";return` {
|
|
955
|
-
id: '${
|
|
956
|
-
name: '${
|
|
957
|
-
${
|
|
958
|
-
${typeof
|
|
959
|
-
${
|
|
958
|
+
id: '${h(y.id)}',
|
|
959
|
+
name: '${h(y.name)}',
|
|
960
|
+
${y.description?`description: '${h(y.description)}',`:""}
|
|
961
|
+
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
962
|
+
${W}
|
|
960
963
|
}`}).join(`,
|
|
961
|
-
`),
|
|
962
|
-
${$.successMetrics.map((
|
|
963
|
-
name: '${
|
|
964
|
-
telemetryEvent: { name: '${
|
|
965
|
-
aggregation: '${
|
|
966
|
-
${typeof
|
|
964
|
+
`),A=_5($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
965
|
+
${$.successMetrics.map((y)=>` {
|
|
966
|
+
name: '${h(y.name)}',
|
|
967
|
+
telemetryEvent: { name: '${h(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
968
|
+
aggregation: '${y.aggregation}',
|
|
969
|
+
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
967
970
|
}`).join(`,
|
|
968
971
|
`)}
|
|
969
972
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
970
973
|
|
|
971
974
|
export const ${b}: ExperimentSpec = {
|
|
972
975
|
meta: {
|
|
973
|
-
key: '${
|
|
976
|
+
key: '${h($.name)}',
|
|
974
977
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
975
|
-
title: '${
|
|
976
|
-
description: '${
|
|
977
|
-
domain: '${
|
|
978
|
-
owners: [${$.owners.map((
|
|
979
|
-
tags: [${$.tags.map((
|
|
978
|
+
title: '${h($.name)} experiment',
|
|
979
|
+
description: '${h($.description||"Describe the experiment goal.")}',
|
|
980
|
+
domain: '${h($.domain)}',
|
|
981
|
+
owners: [${$.owners.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
982
|
+
tags: [${$.tags.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
980
983
|
stability: '${$.stability}',
|
|
981
984
|
},
|
|
982
|
-
controlVariant: '${
|
|
985
|
+
controlVariant: '${h($.controlVariant)}',
|
|
983
986
|
variants: [
|
|
984
|
-
${A}
|
|
985
|
-
],
|
|
986
|
-
allocation: ${m},
|
|
987
987
|
${n}
|
|
988
|
+
],
|
|
989
|
+
allocation: ${A},
|
|
990
|
+
${m}
|
|
988
991
|
};
|
|
989
|
-
`}function
|
|
992
|
+
`}function _5($){switch($.type){case"random":return`{
|
|
990
993
|
type: 'random',
|
|
991
|
-
${$.salt?`salt: '${
|
|
994
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
992
995
|
}`;case"sticky":return`{
|
|
993
996
|
type: 'sticky',
|
|
994
997
|
attribute: '${$.attribute}',
|
|
995
|
-
${$.salt?`salt: '${
|
|
998
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
996
999
|
}`;case"targeted":return`{
|
|
997
1000
|
type: 'targeted',
|
|
998
1001
|
rules: [
|
|
999
1002
|
${$.rules.map((b)=>` {
|
|
1000
|
-
variantId: '${
|
|
1003
|
+
variantId: '${h(b.variantId)}',
|
|
1001
1004
|
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1002
|
-
${b.policy?`policy: { name: '${
|
|
1003
|
-
${b.expression?`expression: '${
|
|
1005
|
+
${b.policy?`policy: { name: '${h(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1006
|
+
${b.expression?`expression: '${h(b.expression)}',`:""}
|
|
1004
1007
|
}`).join(`,
|
|
1005
1008
|
`)}
|
|
1006
1009
|
],
|
|
1007
1010
|
fallback: '${$.fallback??"control"}',
|
|
1008
|
-
}`;default:return
|
|
1011
|
+
}`;default:return L5($)}}function z5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function L5($){throw Error(`Unsupported allocation type ${$}`)}function R5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function IW($){let b=(n)=>n.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
1009
1012
|
`);return`/**
|
|
1010
1013
|
* ${$.title} Feature
|
|
1011
1014
|
*
|
|
@@ -1014,15 +1017,15 @@ ${$.rules.map((b)=>` {
|
|
|
1014
1017
|
|
|
1015
1018
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
1016
1019
|
|
|
1017
|
-
export const ${
|
|
1020
|
+
export const ${R5($.key)}Feature = defineFeature({
|
|
1018
1021
|
meta: {
|
|
1019
1022
|
key: '${$.key}',
|
|
1020
1023
|
version: '${$.version}',
|
|
1021
1024
|
title: '${$.title}',
|
|
1022
1025
|
description: '${$.description||"TODO: Add description"}',
|
|
1023
1026
|
domain: '${$.domain}',
|
|
1024
|
-
owners: [${$.owners.map((
|
|
1025
|
-
tags: [${$.tags.map((
|
|
1027
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1028
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
1026
1029
|
stability: '${$.stability||"beta"}',
|
|
1027
1030
|
},
|
|
1028
1031
|
|
|
@@ -1042,7 +1045,7 @@ ${b($.presentations)||" // Add presentations here"}
|
|
|
1042
1045
|
${b($.experiments)||" // Add experiments here"}
|
|
1043
1046
|
],
|
|
1044
1047
|
});
|
|
1045
|
-
`}function
|
|
1048
|
+
`}function C5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function EW($){let b=C5($.key),n=`${b}FormModel`,A=`${b}Form`;return`/**
|
|
1046
1049
|
* ${$.title} Form
|
|
1047
1050
|
*
|
|
1048
1051
|
* Auto-generated form spec.
|
|
@@ -1051,8 +1054,8 @@ ${b($.experiments)||" // Add experiments here"}
|
|
|
1051
1054
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
1052
1055
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
1053
1056
|
|
|
1054
|
-
const ${
|
|
1055
|
-
name: '${
|
|
1057
|
+
const ${n} = defineSchemaModel({
|
|
1058
|
+
name: '${n}',
|
|
1056
1059
|
description: '${$.description||"TODO: Add form model description"}',
|
|
1057
1060
|
fields: {
|
|
1058
1061
|
${$.primaryFieldKey}: {
|
|
@@ -1062,18 +1065,18 @@ const ${A} = defineSchemaModel({
|
|
|
1062
1065
|
},
|
|
1063
1066
|
});
|
|
1064
1067
|
|
|
1065
|
-
export const ${
|
|
1068
|
+
export const ${A} = defineFormSpec({
|
|
1066
1069
|
meta: {
|
|
1067
1070
|
key: '${$.key}',
|
|
1068
1071
|
version: '${$.version}',
|
|
1069
1072
|
title: '${$.title}',
|
|
1070
1073
|
description: '${$.description||"TODO: Add description"}',
|
|
1071
1074
|
domain: '${$.domain}',
|
|
1072
|
-
owners: [${$.owners.map((
|
|
1073
|
-
tags: [${$.tags.map((
|
|
1075
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1076
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1074
1077
|
stability: '${$.stability||"beta"}',
|
|
1075
1078
|
},
|
|
1076
|
-
model: ${
|
|
1079
|
+
model: ${n},
|
|
1077
1080
|
fields: [
|
|
1078
1081
|
{
|
|
1079
1082
|
kind: 'text',
|
|
@@ -1098,13 +1101,13 @@ export const ${m} = defineFormSpec({
|
|
|
1098
1101
|
form: 'react-hook-form',
|
|
1099
1102
|
},
|
|
1100
1103
|
});
|
|
1101
|
-
`}function
|
|
1102
|
-
import { ${
|
|
1104
|
+
`}function MW($,b){let n=x5($.split(".").pop()||"unknown")+"Handler",A=Dn($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1105
|
+
import { ${A} } from '../contracts/${NW($)}.contracts';
|
|
1103
1106
|
|
|
1104
1107
|
/**
|
|
1105
1108
|
* Handler for ${$}
|
|
1106
1109
|
*/
|
|
1107
|
-
export const ${
|
|
1110
|
+
export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
1108
1111
|
input,
|
|
1109
1112
|
context
|
|
1110
1113
|
) => {
|
|
@@ -1124,27 +1127,27 @@ export const ${A}: ContractHandler<typeof ${m}> = async (
|
|
|
1124
1127
|
throw error;
|
|
1125
1128
|
}
|
|
1126
1129
|
};
|
|
1127
|
-
`}function
|
|
1130
|
+
`}function TW($,b){let n=Dn($);return`import React from 'react';
|
|
1128
1131
|
|
|
1129
|
-
interface ${
|
|
1132
|
+
interface ${n}Props {
|
|
1130
1133
|
// TODO: Define props based on presentation spec
|
|
1131
1134
|
}
|
|
1132
1135
|
|
|
1133
1136
|
/**
|
|
1134
1137
|
* ${b}
|
|
1135
1138
|
*/
|
|
1136
|
-
export const ${
|
|
1139
|
+
export const ${n}: React.FC<${n}Props> = (props) => {
|
|
1137
1140
|
return (
|
|
1138
1141
|
<div>
|
|
1139
1142
|
{/* TODO: Implement component UI */}
|
|
1140
|
-
<p>Component: ${
|
|
1143
|
+
<p>Component: ${n}</p>
|
|
1141
1144
|
</div>
|
|
1142
1145
|
);
|
|
1143
1146
|
};
|
|
1144
|
-
`}function
|
|
1145
|
-
import { ${
|
|
1147
|
+
`}function DW($,b){let n=b==="handler"?"../handlers":"../components",A=Dn($);return`import { describe, it, expect } from 'bun:test';
|
|
1148
|
+
import { ${A} } from '${n}/${NW($)}';
|
|
1146
1149
|
|
|
1147
|
-
describe('${
|
|
1150
|
+
describe('${A}', () => {
|
|
1148
1151
|
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
1149
1152
|
// TODO: Implement test
|
|
1150
1153
|
expect(true).toBe(true);
|
|
@@ -1160,16 +1163,16 @@ describe('${m}', () => {
|
|
|
1160
1163
|
// TODO: Test accessibility
|
|
1161
1164
|
});`}
|
|
1162
1165
|
});
|
|
1163
|
-
`}function
|
|
1164
|
-
`),
|
|
1165
|
-
${$.capabilitiesRequired.map((
|
|
1166
|
+
`}function x5($){let b=Dn($);return b.charAt(0).toLowerCase()+b.slice(1)}function Dn($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function NW($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function FW($){let b=g5($.name.split(".").pop()??"Integration"),n=`${b}IntegrationSpec`,A=`register${b}Integration`,m=$.supportedModes.length?$.supportedModes:["managed"],y=m.map((G)=>`'${G}'`).join(", "),W=$.capabilitiesProvided.map((G)=>` { key: '${G.key}', version: '${G.version}' }`).join(`,
|
|
1167
|
+
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1168
|
+
${$.capabilitiesRequired.map((G)=>{let V=G.version!==void 0?`, version: '${G.version}'`:"",O=G.optional?", optional: true":"",K=G.reason?`, reason: '${w$(G.reason)}'`:"";return` { key: '${G.key}'${V}${O}${K} }`}).join(`,
|
|
1166
1169
|
`)}
|
|
1167
|
-
],`:"",
|
|
1168
|
-
`:"",
|
|
1170
|
+
],`:"",j=I5($.configFields),B=M5($.configFields),S=E5($.secretFields),Q=T5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
|
|
1171
|
+
`:"",X=D5($.rateLimitRpm,$.rateLimitRph),Y=N5(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1169
1172
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
1170
1173
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
1171
1174
|
|
|
1172
|
-
export const ${
|
|
1175
|
+
export const ${n}: IntegrationSpec = {
|
|
1173
1176
|
meta: {
|
|
1174
1177
|
key: '${$.name}',
|
|
1175
1178
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
@@ -1178,145 +1181,145 @@ export const ${A}: IntegrationSpec = {
|
|
|
1178
1181
|
title: '${w$($.title)}',
|
|
1179
1182
|
description: '${w$($.description)}',
|
|
1180
1183
|
domain: '${w$($.domain)}',
|
|
1181
|
-
owners: [${$.owners.map((
|
|
1182
|
-
tags: [${$.tags.map((
|
|
1183
|
-
stability: StabilityEnum.${
|
|
1184
|
+
owners: [${$.owners.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1185
|
+
tags: [${$.tags.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1186
|
+
stability: StabilityEnum.${v5($.stability)},
|
|
1184
1187
|
},
|
|
1185
|
-
supportedModes: [${
|
|
1188
|
+
supportedModes: [${y}],
|
|
1186
1189
|
capabilities: {
|
|
1187
1190
|
provides: [
|
|
1188
|
-
${
|
|
1191
|
+
${W}
|
|
1189
1192
|
],
|
|
1190
|
-
${
|
|
1193
|
+
${w.length>0?`${w}
|
|
1191
1194
|
`:""} },
|
|
1192
1195
|
configSchema: {
|
|
1193
|
-
${
|
|
1196
|
+
${j}
|
|
1194
1197
|
example: ${B},
|
|
1195
1198
|
},
|
|
1196
1199
|
secretSchema: {
|
|
1197
1200
|
${S}
|
|
1198
1201
|
example: ${Q},
|
|
1199
1202
|
},
|
|
1200
|
-
${Z}${
|
|
1203
|
+
${Z}${X}${Y} healthCheck: {
|
|
1201
1204
|
method: '${$.healthCheckMethod}',
|
|
1202
1205
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
1203
1206
|
},
|
|
1204
1207
|
};
|
|
1205
1208
|
|
|
1206
|
-
export function ${
|
|
1209
|
+
export function ${A}(
|
|
1207
1210
|
registry: IntegrationSpecRegistry
|
|
1208
1211
|
): IntegrationSpecRegistry {
|
|
1209
|
-
return registry.register(${
|
|
1212
|
+
return registry.register(${n});
|
|
1210
1213
|
}
|
|
1211
|
-
`}function
|
|
1212
|
-
`:"",
|
|
1214
|
+
`}function I5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1215
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: '${F5(m.type)}'${y} }`}).join(`,
|
|
1213
1216
|
`):"";return` schema: {
|
|
1214
1217
|
type: 'object',
|
|
1215
|
-
${
|
|
1216
|
-
${
|
|
1218
|
+
${n} properties: {
|
|
1219
|
+
${A||" "}
|
|
1217
1220
|
},
|
|
1218
1221
|
},
|
|
1219
|
-
`}function
|
|
1220
|
-
`:"",
|
|
1222
|
+
`}function E5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1223
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
1221
1224
|
`):"";return` schema: {
|
|
1222
1225
|
type: 'object',
|
|
1223
|
-
${
|
|
1224
|
-
${
|
|
1226
|
+
${n} properties: {
|
|
1227
|
+
${A||" "}
|
|
1225
1228
|
},
|
|
1226
1229
|
},
|
|
1227
|
-
`}function
|
|
1228
|
-
${$.map((
|
|
1230
|
+
`}function M5($){if($.length===0)return"{}";return`{
|
|
1231
|
+
${$.map((n)=>{switch(n.type){case"number":return` ${n.key}: 0`;case"boolean":return` ${n.key}: true`;case"string":default:return` ${n.key}: '${n.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
1229
1232
|
`)}
|
|
1230
|
-
}`}function
|
|
1231
|
-
${$.map((
|
|
1233
|
+
}`}function T5($){if($.length===0)return"{}";return`{
|
|
1234
|
+
${$.map((n)=>` ${n.key}: '${n.key.toUpperCase()}_SECRET'`).join(`,
|
|
1232
1235
|
`)}
|
|
1233
|
-
}`}function
|
|
1236
|
+
}`}function D5($,b){if($==null&&b==null)return"";let n=[];if($!=null)n.push(` rpm: ${$}`);if(b!=null)n.push(` rph: ${b}`);return` constraints: {
|
|
1234
1237
|
rateLimit: {
|
|
1235
|
-
${
|
|
1238
|
+
${n.join(`,
|
|
1236
1239
|
`)}
|
|
1237
1240
|
},
|
|
1238
1241
|
},
|
|
1239
|
-
`}function
|
|
1240
|
-
`:"",n
|
|
1241
|
-
`:"";if(!m
|
|
1242
|
-
${
|
|
1243
|
-
`}function
|
|
1242
|
+
`}function N5($,b,n){if(!$.includes("byok"))return"";let A=b?` setupInstructions: '${w$(b)}',
|
|
1243
|
+
`:"",m=n&&n.length?` requiredScopes: [${n.map((y)=>`'${w$(y)}'`).join(", ")}],
|
|
1244
|
+
`:"";if(!A&&!m)return"";return` byokSetup: {
|
|
1245
|
+
${A}${m} },
|
|
1246
|
+
`}function F5($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function v5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function g5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function w$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function vW($){let b=c5($.name.split(".").pop()??"KnowledgeSpace"),n=`${b}KnowledgeSpace`,A=`register${b}KnowledgeSpace`,m=P5($),y=k5($),W=r5($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1244
1247
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1245
1248
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1246
1249
|
|
|
1247
|
-
export const ${
|
|
1250
|
+
export const ${n}: KnowledgeSpaceSpec = {
|
|
1248
1251
|
meta: {
|
|
1249
1252
|
key: '${$.name}',
|
|
1250
1253
|
version: ${$.version},
|
|
1251
1254
|
category: '${$.category}',
|
|
1252
|
-
displayName: '${
|
|
1253
|
-
title: '${
|
|
1254
|
-
description: '${
|
|
1255
|
-
domain: '${
|
|
1256
|
-
owners: [${$.owners.map((
|
|
1257
|
-
tags: [${$.tags.map((
|
|
1258
|
-
stability: StabilityEnum.${
|
|
1259
|
-
},
|
|
1260
|
-
retention: ${
|
|
1255
|
+
displayName: '${O$($.displayName)}',
|
|
1256
|
+
title: '${O$($.title)}',
|
|
1257
|
+
description: '${O$($.description)}',
|
|
1258
|
+
domain: '${O$($.domain)}',
|
|
1259
|
+
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1260
|
+
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1261
|
+
stability: StabilityEnum.${f5($.stability)},
|
|
1262
|
+
},
|
|
1263
|
+
retention: ${m},
|
|
1261
1264
|
access: {
|
|
1262
|
-
${
|
|
1265
|
+
${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${w}
|
|
1263
1266
|
`:""} },
|
|
1264
|
-
${
|
|
1267
|
+
${W} description: '${O$($.description||$.displayName)}',
|
|
1265
1268
|
};
|
|
1266
1269
|
|
|
1267
|
-
export function ${
|
|
1270
|
+
export function ${A}(
|
|
1268
1271
|
registry: KnowledgeSpaceRegistry
|
|
1269
1272
|
): KnowledgeSpaceRegistry {
|
|
1270
|
-
return registry.register(${
|
|
1273
|
+
return registry.register(${n});
|
|
1271
1274
|
}
|
|
1272
|
-
`}function
|
|
1273
|
-
`,
|
|
1274
|
-
`;return`${b}${
|
|
1275
|
+
`}function P5($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",n=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${n} }`}function k5($){let b=` trustLevel: '${$.trustLevel}',
|
|
1276
|
+
`,n=` automationWritable: ${$.automationWritable},
|
|
1277
|
+
`;return`${b}${n}`}function r5($){let b=[];if($.embeddingModel)b.push(` embeddingModel: '${O$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")b.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)b.push(` vectorDbIntegration: '${O$($.vectorDbIntegration)}'`);if(b.length===0)return"";return` indexing: {
|
|
1275
1278
|
${b.join(`,
|
|
1276
1279
|
`)}
|
|
1277
1280
|
},
|
|
1278
|
-
`}function
|
|
1281
|
+
`}function f5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function c5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function O$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function PW($){let n=`${h5($.name.split(".").pop()??"Migration")}Migration`,A=$.dependencies.length>0?`dependencies: [${$.dependencies.map((m)=>`'${m}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1279
1282
|
|
|
1280
|
-
export const ${
|
|
1283
|
+
export const ${n}: MigrationSpec = {
|
|
1281
1284
|
meta: {
|
|
1282
1285
|
key: '${$.name}',
|
|
1283
1286
|
version: ${$.version},
|
|
1284
|
-
title: '${
|
|
1285
|
-
description: '${
|
|
1286
|
-
domain: '${
|
|
1287
|
-
owners: [${$.owners.map((
|
|
1288
|
-
tags: [${$.tags.map((
|
|
1287
|
+
title: '${f$($.title)}',
|
|
1288
|
+
description: '${f$($.description??"")}',
|
|
1289
|
+
domain: '${f$($.domain)}',
|
|
1290
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1291
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1289
1292
|
stability: '${$.stability}',
|
|
1290
1293
|
},
|
|
1291
1294
|
plan: {
|
|
1292
1295
|
up: [
|
|
1293
|
-
${
|
|
1296
|
+
${gW($.up)}
|
|
1294
1297
|
],${$.down&&$.down.length?`
|
|
1295
1298
|
down: [
|
|
1296
|
-
${
|
|
1299
|
+
${gW($.down)}
|
|
1297
1300
|
],`:""}
|
|
1298
1301
|
},
|
|
1299
|
-
${
|
|
1302
|
+
${A}
|
|
1300
1303
|
};
|
|
1301
|
-
`}function
|
|
1304
|
+
`}function gW($){return $.map((b)=>{let n=b.description?`description: '${f$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1302
1305
|
kind: 'schema',
|
|
1303
|
-
${
|
|
1304
|
-
sql: \`${
|
|
1306
|
+
${n}
|
|
1307
|
+
sql: \`${f$(b.sql??"")}\`,
|
|
1305
1308
|
}`;case"data":return` {
|
|
1306
1309
|
kind: 'data',
|
|
1307
|
-
${
|
|
1308
|
-
script: \`${
|
|
1310
|
+
${n}
|
|
1311
|
+
script: \`${f$(b.script??"")}\`,
|
|
1309
1312
|
}`;case"validation":default:return` {
|
|
1310
1313
|
kind: 'validation',
|
|
1311
|
-
${
|
|
1312
|
-
assertion: \`${
|
|
1314
|
+
${n}
|
|
1315
|
+
assertion: \`${f$(b.assertion??"")}\`,
|
|
1313
1316
|
}`}}).join(`,
|
|
1314
|
-
`)}function
|
|
1317
|
+
`)}function h5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function kW($){let{name:b,version:n,kind:A,description:m,goal:y,context:W,stability:w,owners:j,tags:B,auth:S,flags:Q}=$,Z=d5(b.split(".").pop()||"Unknown")+"Spec",X=Z.replace("Spec","Input"),Y=Z.replace("Spec","Output");return`import { define${q0(A)} } from '@contractspec/lib.contracts-spec';
|
|
1315
1318
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1316
1319
|
|
|
1317
1320
|
// TODO: Define input schema
|
|
1318
|
-
export const ${
|
|
1319
|
-
name: '${
|
|
1321
|
+
export const ${X} = new SchemaModel({
|
|
1322
|
+
name: '${X}',
|
|
1320
1323
|
description: 'Input for ${b}',
|
|
1321
1324
|
fields: {
|
|
1322
1325
|
// Add your fields here
|
|
@@ -1325,8 +1328,8 @@ export const ${G} = new SchemaModel({
|
|
|
1325
1328
|
});
|
|
1326
1329
|
|
|
1327
1330
|
// TODO: Define output schema
|
|
1328
|
-
export const ${
|
|
1329
|
-
name: '${
|
|
1331
|
+
export const ${Y} = new SchemaModel({
|
|
1332
|
+
name: '${Y}',
|
|
1330
1333
|
description: 'Output for ${b}',
|
|
1331
1334
|
fields: {
|
|
1332
1335
|
// Add your fields here
|
|
@@ -1334,23 +1337,23 @@ export const ${X} = new SchemaModel({
|
|
|
1334
1337
|
},
|
|
1335
1338
|
});
|
|
1336
1339
|
|
|
1337
|
-
export const ${Z} = define${
|
|
1340
|
+
export const ${Z} = define${q0(A)}({
|
|
1338
1341
|
meta: {
|
|
1339
1342
|
key: '${b}',
|
|
1340
1343
|
key: '${b}',
|
|
1341
|
-
version: '${
|
|
1342
|
-
stability: '${
|
|
1343
|
-
stability: '${
|
|
1344
|
-
owners: [${
|
|
1345
|
-
tags: [${B.map((
|
|
1346
|
-
description: '${
|
|
1347
|
-
goal: '${
|
|
1348
|
-
context: '${
|
|
1344
|
+
version: '${n}',
|
|
1345
|
+
stability: '${w}',
|
|
1346
|
+
stability: '${w}',
|
|
1347
|
+
owners: [${j.map((G)=>`'${G}'`).join(", ")}],
|
|
1348
|
+
tags: [${B.map((G)=>`'${G}'`).join(", ")}],
|
|
1349
|
+
description: '${m}',
|
|
1350
|
+
goal: '${y}',
|
|
1351
|
+
context: '${W}',
|
|
1349
1352
|
},
|
|
1350
1353
|
|
|
1351
1354
|
io: {
|
|
1352
|
-
input: ${
|
|
1353
|
-
output: ${
|
|
1355
|
+
input: ${X},
|
|
1356
|
+
output: ${Y},
|
|
1354
1357
|
errors: {
|
|
1355
1358
|
// Define possible errors
|
|
1356
1359
|
// EXAMPLE_ERROR: {
|
|
@@ -1363,7 +1366,7 @@ export const ${Z} = define${mm(m)}({
|
|
|
1363
1366
|
|
|
1364
1367
|
policy: {
|
|
1365
1368
|
auth: '${S}',
|
|
1366
|
-
${Q.length>0?`flags: [${Q.map((
|
|
1369
|
+
${Q.length>0?`flags: [${Q.map((G)=>`'${G}'`).join(", ")}],`:"// flags: [],"}
|
|
1367
1370
|
},
|
|
1368
1371
|
|
|
1369
1372
|
sideEffects: {
|
|
@@ -1377,9 +1380,9 @@ export const ${Z} = define${mm(m)}({
|
|
|
1377
1380
|
},
|
|
1378
1381
|
|
|
1379
1382
|
transport: {
|
|
1380
|
-
rest: { method: '${
|
|
1383
|
+
rest: { method: '${A==="command"?"POST":"GET"}' },
|
|
1381
1384
|
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1382
|
-
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(
|
|
1385
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(n).replace(/\./g,"_")}' },
|
|
1383
1386
|
},
|
|
1384
1387
|
|
|
1385
1388
|
acceptance: {
|
|
@@ -1400,12 +1403,12 @@ export const ${Z} = define${mm(m)}({
|
|
|
1400
1403
|
],
|
|
1401
1404
|
},
|
|
1402
1405
|
});
|
|
1403
|
-
`}function
|
|
1406
|
+
`}function q0($){return $.charAt(0).toUpperCase()+$.slice(1)}function d5($){return $.split(/[-_.]/).map(q0).join("")}function rW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,presentationKind:w}=$,j=u5(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1404
1407
|
kind: 'web_component',
|
|
1405
1408
|
framework: 'react',
|
|
1406
1409
|
componentKey: '${b.replace(/\./g,"_")}',
|
|
1407
1410
|
props: new SchemaModel({
|
|
1408
|
-
name: '${
|
|
1411
|
+
name: '${j}Props',
|
|
1409
1412
|
description: 'Props for ${b}',
|
|
1410
1413
|
fields: {
|
|
1411
1414
|
// TODO: Define component props
|
|
@@ -1417,7 +1420,7 @@ export const ${Z} = define${mm(m)}({
|
|
|
1417
1420
|
},`;break;case"markdown":B=` content: {
|
|
1418
1421
|
kind: 'markdown',
|
|
1419
1422
|
content: \`
|
|
1420
|
-
# ${
|
|
1423
|
+
# ${A}
|
|
1421
1424
|
|
|
1422
1425
|
TODO: Add markdown content here
|
|
1423
1426
|
\`,
|
|
@@ -1426,7 +1429,7 @@ TODO: Add markdown content here
|
|
|
1426
1429
|
kind: 'data',
|
|
1427
1430
|
mimeType: 'application/json',
|
|
1428
1431
|
model: new SchemaModel({
|
|
1429
|
-
name: '${
|
|
1432
|
+
name: '${j}Data',
|
|
1430
1433
|
description: 'Data structure for ${b}',
|
|
1431
1434
|
fields: {
|
|
1432
1435
|
// TODO: Define data structure
|
|
@@ -1435,14 +1438,14 @@ TODO: Add markdown content here
|
|
|
1435
1438
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1436
1439
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1437
1440
|
|
|
1438
|
-
export const ${
|
|
1441
|
+
export const ${j}: PresentationSpec = {
|
|
1439
1442
|
meta: {
|
|
1440
1443
|
key: '${b}',
|
|
1441
|
-
version: ${
|
|
1442
|
-
stability: '${
|
|
1443
|
-
owners: [${
|
|
1444
|
-
tags: [${
|
|
1445
|
-
description: '${
|
|
1444
|
+
version: ${n},
|
|
1445
|
+
stability: '${m}',
|
|
1446
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1447
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1448
|
+
description: '${A}',
|
|
1446
1449
|
},
|
|
1447
1450
|
|
|
1448
1451
|
policy: {
|
|
@@ -1452,50 +1455,50 @@ export const ${y}: PresentationSpec = {
|
|
|
1452
1455
|
|
|
1453
1456
|
${B}
|
|
1454
1457
|
};
|
|
1455
|
-
`}function
|
|
1456
|
-
${$.providers.map((
|
|
1457
|
-
type: '${
|
|
1458
|
-
config: ${
|
|
1458
|
+
`}function u5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function fW($){let b=o5($.name.split(".").pop()??"Telemetry")+"Telemetry",n=$.providers?.length?`providers: [
|
|
1459
|
+
${$.providers.map((m)=>` {
|
|
1460
|
+
type: '${m.type}',
|
|
1461
|
+
config: ${i5(m.config)},
|
|
1459
1462
|
}`).join(`,
|
|
1460
1463
|
`)}
|
|
1461
|
-
],`:"",
|
|
1462
|
-
type: '${
|
|
1463
|
-
${
|
|
1464
|
-
${
|
|
1465
|
-
${
|
|
1466
|
-
${
|
|
1464
|
+
],`:"",A=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1465
|
+
type: '${w.type}',
|
|
1466
|
+
${w.required?"required: true,":""}
|
|
1467
|
+
${w.pii?"pii: true,":""}
|
|
1468
|
+
${w.redact?"redact: true,":""}
|
|
1469
|
+
${w.description?`description: '${l(w.description)}',`:""}
|
|
1467
1470
|
}`).join(`,
|
|
1468
|
-
`),
|
|
1471
|
+
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1469
1472
|
enabled: true,
|
|
1470
|
-
${typeof
|
|
1473
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1471
1474
|
thresholds: [
|
|
1472
|
-
${
|
|
1473
|
-
metric: '${l(
|
|
1474
|
-
${typeof
|
|
1475
|
-
${typeof
|
|
1475
|
+
${m.anomalyRules.map((w)=>` {
|
|
1476
|
+
metric: '${l(w.metric)}',
|
|
1477
|
+
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1478
|
+
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1476
1479
|
}`).join(`,
|
|
1477
1480
|
`)}
|
|
1478
1481
|
],
|
|
1479
|
-
actions: [${(
|
|
1480
|
-
},`:
|
|
1482
|
+
actions: [${(m.anomalyActions??[]).map((w)=>`'${w}'`).join(", ")}],
|
|
1483
|
+
},`:m.anomalyEnabled?` anomalyDetection: {
|
|
1481
1484
|
enabled: true,
|
|
1482
|
-
${typeof
|
|
1485
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1483
1486
|
},`:"";return` {
|
|
1484
|
-
name: '${l(
|
|
1485
|
-
version: ${
|
|
1487
|
+
name: '${l(m.name)}',
|
|
1488
|
+
version: ${m.version},
|
|
1486
1489
|
semantics: {
|
|
1487
|
-
what: '${l(
|
|
1488
|
-
${
|
|
1489
|
-
${
|
|
1490
|
+
what: '${l(m.what)}',
|
|
1491
|
+
${m.who?`who: '${l(m.who)}',`:""}
|
|
1492
|
+
${m.why?`why: '${l(m.why)}',`:""}
|
|
1490
1493
|
},
|
|
1491
|
-
privacy: '${
|
|
1494
|
+
privacy: '${m.privacy}',
|
|
1492
1495
|
properties: {
|
|
1493
|
-
${
|
|
1496
|
+
${y}
|
|
1494
1497
|
},
|
|
1495
|
-
${typeof
|
|
1496
|
-
${typeof
|
|
1497
|
-
${
|
|
1498
|
-
${
|
|
1498
|
+
${typeof m.retentionDays==="number"?`retention: { days: ${m.retentionDays}, ${m.retentionPolicy?`policy: '${m.retentionPolicy}'`:""} },`:""}
|
|
1499
|
+
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${l(m.samplingConditions)}']`:""} },`:""}
|
|
1500
|
+
${W}
|
|
1501
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${l(w)}'`).join(", ")}],`:""}
|
|
1499
1502
|
}`}).join(`,
|
|
1500
1503
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1501
1504
|
|
|
@@ -1506,21 +1509,21 @@ export const ${b}: TelemetrySpec = {
|
|
|
1506
1509
|
title: '${l($.name)} telemetry',
|
|
1507
1510
|
description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1508
1511
|
domain: '${l($.domain)}',
|
|
1509
|
-
owners: [${$.owners.map((
|
|
1510
|
-
tags: [${$.tags.map((
|
|
1512
|
+
owners: [${$.owners.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1513
|
+
tags: [${$.tags.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1511
1514
|
stability: '${$.stability}',
|
|
1512
1515
|
},
|
|
1513
1516
|
config: {
|
|
1514
1517
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1515
1518
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1516
1519
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1517
|
-
${
|
|
1520
|
+
${n}
|
|
1518
1521
|
},
|
|
1519
1522
|
events: [
|
|
1520
|
-
${
|
|
1523
|
+
${A}
|
|
1521
1524
|
],
|
|
1522
1525
|
};
|
|
1523
|
-
`}function
|
|
1526
|
+
`}function o5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function i5($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function t5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function cW($){return`/**
|
|
1524
1527
|
* ${$.title} Theme
|
|
1525
1528
|
*
|
|
1526
1529
|
* Auto-generated theme spec.
|
|
@@ -1528,7 +1531,7 @@ ${m}
|
|
|
1528
1531
|
|
|
1529
1532
|
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1530
1533
|
|
|
1531
|
-
export const ${
|
|
1534
|
+
export const ${t5($.key)}Theme = defineTheme({
|
|
1532
1535
|
meta: {
|
|
1533
1536
|
key: '${$.key}',
|
|
1534
1537
|
version: '${$.version}',
|
|
@@ -1548,11 +1551,11 @@ export const ${Y8($.key)}Theme = defineTheme({
|
|
|
1548
1551
|
},
|
|
1549
1552
|
},
|
|
1550
1553
|
});
|
|
1551
|
-
`}function
|
|
1552
|
-
`),
|
|
1553
|
-
from: '${
|
|
1554
|
-
to: '${
|
|
1555
|
-
${
|
|
1554
|
+
`}function hW($){let b=p5($.name.split(".").pop()??"Workflow")+"Workflow",n=$.steps.map((m)=>l5(m)).join(`,
|
|
1555
|
+
`),A=$.transitions.map((m)=>` {
|
|
1556
|
+
from: '${m.from}',
|
|
1557
|
+
to: '${m.to}',
|
|
1558
|
+
${m.condition?` condition: '${Ab(m.condition)}',`:""}
|
|
1556
1559
|
}`).join(`,
|
|
1557
1560
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1558
1561
|
|
|
@@ -1568,32 +1571,32 @@ export const ${b}: WorkflowSpec = {
|
|
|
1568
1571
|
meta: {
|
|
1569
1572
|
key: '${$.name}',
|
|
1570
1573
|
version: ${$.version},
|
|
1571
|
-
title: '${
|
|
1572
|
-
description: '${
|
|
1573
|
-
domain: '${
|
|
1574
|
+
title: '${Ab($.title)}',
|
|
1575
|
+
description: '${Ab($.description)}',
|
|
1576
|
+
domain: '${Ab($.domain)}',
|
|
1574
1577
|
stability: '${$.stability}',
|
|
1575
|
-
owners: [${$.owners.map((
|
|
1576
|
-
tags: [${$.tags.map((
|
|
1578
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1579
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1577
1580
|
},
|
|
1578
1581
|
definition: {
|
|
1579
1582
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1580
1583
|
`:""} steps: [
|
|
1581
|
-
${
|
|
1584
|
+
${n}
|
|
1582
1585
|
],
|
|
1583
1586
|
transitions: [
|
|
1584
|
-
${
|
|
1587
|
+
${A}
|
|
1585
1588
|
],
|
|
1586
1589
|
},
|
|
1587
1590
|
${$.policyFlags.length>0?`policy: {
|
|
1588
|
-
flags: [${$.policyFlags.map((
|
|
1591
|
+
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1589
1592
|
},`:"// policy: { flags: [] },"}
|
|
1590
1593
|
};
|
|
1591
|
-
`}function
|
|
1592
|
-
`)}function
|
|
1594
|
+
`}function l5($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${Ab($.label)}',`];if($.description)b.push(` description: '${Ab($.description)}',`);let n=[];if($.operation)n.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)n.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(n.length)b.push(` action: { ${n.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1595
|
+
`)}function p5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ab($){return $.replace(/'/g,"\\'")}function Nn({exportName:$,specImportPath:b,workflowFunctionName:n}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1593
1596
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1594
1597
|
import { ${$} } from '${b}';
|
|
1595
1598
|
|
|
1596
|
-
export async function ${
|
|
1599
|
+
export async function ${n}(input = {}, bridge = {}) {
|
|
1597
1600
|
"use workflow";
|
|
1598
1601
|
|
|
1599
1602
|
// Keep the workflow function deterministic.
|
|
@@ -1610,7 +1613,7 @@ export async function ${A}(input = {}, bridge = {}) {
|
|
|
1610
1613
|
},
|
|
1611
1614
|
});
|
|
1612
1615
|
}
|
|
1613
|
-
`}function
|
|
1616
|
+
`}function Fn($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1614
1617
|
import { ${b} } from '${$}';
|
|
1615
1618
|
|
|
1616
1619
|
export const POST = createWorkflowDevkitStartRoute({
|
|
@@ -1619,17 +1622,17 @@ export const POST = createWorkflowDevkitStartRoute({
|
|
|
1619
1622
|
return [body];
|
|
1620
1623
|
},
|
|
1621
1624
|
});
|
|
1622
|
-
`}function
|
|
1625
|
+
`}function vn(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1623
1626
|
|
|
1624
1627
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1625
1628
|
resolveToken({ runId }) {
|
|
1626
1629
|
return \`workflow-session:\${runId}\`;
|
|
1627
1630
|
},
|
|
1628
1631
|
});
|
|
1629
|
-
`}function
|
|
1632
|
+
`}function gn(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1630
1633
|
|
|
1631
1634
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1632
|
-
`}function
|
|
1635
|
+
`}function Pn($,b){return`import { ${b} } from '${$}';
|
|
1633
1636
|
|
|
1634
1637
|
export const workflowDevkitBootstrap = {
|
|
1635
1638
|
workflow: ${b},
|
|
@@ -1641,13 +1644,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1641
1644
|
};
|
|
1642
1645
|
},
|
|
1643
1646
|
};
|
|
1644
|
-
`}function
|
|
1647
|
+
`}function kn({exportName:$,specImportPath:b,runnerName:n,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1645
1648
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1646
1649
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1647
1650
|
import { ${$} } from '${b}';
|
|
1648
1651
|
|
|
1649
1652
|
/**
|
|
1650
|
-
* Runner wiring for ${
|
|
1653
|
+
* Runner wiring for ${A}.
|
|
1651
1654
|
*
|
|
1652
1655
|
* TODO:
|
|
1653
1656
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1659,7 +1662,7 @@ registry.register(${$});
|
|
|
1659
1662
|
|
|
1660
1663
|
const stateStore = new InMemoryStateStore();
|
|
1661
1664
|
|
|
1662
|
-
export const ${
|
|
1665
|
+
export const ${n} = new WorkflowRunner({
|
|
1663
1666
|
registry,
|
|
1664
1667
|
stateStore,
|
|
1665
1668
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1681,12 +1684,12 @@ export const ${A} = new WorkflowRunner({
|
|
|
1681
1684
|
// console.log(event, payload);
|
|
1682
1685
|
},
|
|
1683
1686
|
});
|
|
1684
|
-
`}import{getAuthoringTargetDefinition as
|
|
1685
|
-
`],[
|
|
1687
|
+
`}import{getAuthoringTargetDefinition as a5}from"@contractspec/module.workspace";var uW={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function oW($,b){let n=e5($,b.specPath),A=s5($,b.target,n),m=$.join(n,"package.json"),y=$.join(n,"README.md"),W=$.join(n,"src"),w=$.join(W,"index.ts"),j=O0($.relative(W,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(W);let B=[[m,JSON.stringify({name:A,version:"0.1.0",description:uW[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1688
|
+
`],[y,`# ${A}
|
|
1686
1689
|
|
|
1687
|
-
${
|
|
1688
|
-
`],[
|
|
1689
|
-
`],[b.specPath,b.specCode]],S={packageRoot:
|
|
1690
|
+
${uW[b.target]}.
|
|
1691
|
+
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1692
|
+
`],[b.specPath,b.specCode]],S={packageRoot:n,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 rn($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1690
1693
|
|
|
1691
1694
|
export const ${$.exportName} = defineModuleBundle({
|
|
1692
1695
|
meta: {
|
|
@@ -1711,7 +1714,15 @@ export const ${$.exportName} = defineModuleBundle({
|
|
|
1711
1714
|
layouts: [],
|
|
1712
1715
|
data: [],
|
|
1713
1716
|
verification: {
|
|
1714
|
-
|
|
1717
|
+
dimensions: {
|
|
1718
|
+
guidance: "Scaffolded guidance profile for ${$.title}.",
|
|
1719
|
+
density: "Scaffolded density profile for ${$.title}.",
|
|
1720
|
+
dataDepth: "Scaffolded data-depth profile for ${$.title}.",
|
|
1721
|
+
control: "Scaffolded control profile for ${$.title}.",
|
|
1722
|
+
media: "Scaffolded media profile for ${$.title}.",
|
|
1723
|
+
pace: "Scaffolded pace profile for ${$.title}.",
|
|
1724
|
+
narrative: "Scaffolded narrative profile for ${$.title}.",
|
|
1725
|
+
},
|
|
1715
1726
|
},
|
|
1716
1727
|
},
|
|
1717
1728
|
},
|
|
@@ -1747,22 +1758,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1747
1758
|
supportedArtifactTypes: ["patch"],
|
|
1748
1759
|
knownConstraints: [],
|
|
1749
1760
|
};
|
|
1750
|
-
`}}function
|
|
1761
|
+
`}}function e5($,b){let n=O0(b),A="/src/",m=n.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return n.slice(0,m)}function s5($,b,n){let A=a5(b),m=O0($.basename(n));return`${A.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${m}`}function O0($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function yb($,b,n,A={}){let{fs:m,logger:y,workspace:W}=b,w=W?.scanSpecSource??W8,j=W?.inferSpecTypeFromFilePath??y8,B=W?.generateHandlerTemplate??n8,S=W?.generateComponentTemplate??b8,Q=W?.generateTestTemplate??A8,{targets:Z=void 0,outputDir:X=n.outputDir,overwrite:Y=!1,dryRun:G=!1,includeTests:V=!1,runtimeGeneration:O}=A,K=await m.readFile($),J=w(K,$),U=$8(K,$),H=U==="unknown"?j($):U,q=Z??J0(H,{includeTests:V});y.info(`Building from spec: ${$}`,{targetId:H});let _=[],z={};for(let L of q)try{let C=await w8(L,$,K,J,H,{fs:m,logger:y},X,Y,G,O,z,{genHandler:B,genComponent:S,genTest:Q});if(_.push(C),C.success&&C.generatedCode)z[L]=C.generatedCode}catch(C){_.push({target:L,outputPath:"",success:!1,error:C instanceof Error?C.message:String(C),skipped:!1})}return{specPath:$,specInfo:J,targetId:H,results:_}}async function w8($,b,n,A,m,y,W,w,j,B,S,Q){let{fs:Z,logger:X}=y,{genHandler:Y,genComponent:G,genTest:V}=Q,O,K,J=[];switch($){case"handler":{if(m!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${m})`};let q=A.kind==="command"||A.kind==="query"?A.kind:"command",_=Y(s(n,A,b),q);K=mb(b,W,"handlers",s(n,A,b),".handler.ts",y.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:n,outputPath:K,fallbackCode:_})??_;break}case"component":{if(m!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${m})`};let q=G(s(n,A,b),A.description??"");K=mb(b,W,"components",s(n,A,b),".tsx",y.fs),O=await B?.generateArtifact?.({kind:"component",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"test":{let q=m==="operation"?"handler":"component",_=m==="operation"?S.handler??"":m==="presentation"?S.component??"":m==="form"?S.form??"":"",z=V(s(n,A,b),q);K=mb(b,W,"__tests__",s(n,A,b),".test.ts",y.fs),O=await B?.generateTest?.({kind:q,specCode:n,outputPath:K,existingCode:_,fallbackCode:z})??z;break}case"form":{if(m!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${m})`};let q=`import * as React from "react";
|
|
1751
1762
|
|
|
1752
|
-
export interface ${
|
|
1763
|
+
export interface ${V$(s(n,A,b))}Props {
|
|
1753
1764
|
className?: string;
|
|
1754
1765
|
}
|
|
1755
1766
|
|
|
1756
|
-
export function ${
|
|
1767
|
+
export function ${V$(s(n,A,b))}Form({
|
|
1757
1768
|
className,
|
|
1758
|
-
}: ${
|
|
1759
|
-
return <form className={className}>TODO: implement ${
|
|
1769
|
+
}: ${V$(s(n,A,b))}Props) {
|
|
1770
|
+
return <form className={className}>TODO: implement ${s(n,A,b)}</form>;
|
|
1760
1771
|
}
|
|
1761
|
-
`;K=
|
|
1772
|
+
`;K=mb(b,W,"forms",s(n,A,b),".form.tsx",y.fs),O=await B?.generateArtifact?.({kind:"form",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"workflow-runner":{if(m!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${m})`};let q=s(n,A,b),_=Q8(n)??`${V$(q)}Workflow`,z=`${V$(q)}Runner`,L=U0(q);if(K=mb(b,W,"workflows",q,".runner.ts",y.fs),O=kn({exportName:_,specImportPath:V0(y.fs,K,b),runnerName:z,workflowName:q}),Y8(n)){let C=`${V$(q)}WorkflowDevkit`,D=_b(y.fs,K,`${L}.workflow-devkit.ts`),F=_b(y.fs,K,`${L}.workflow-devkit.start.route.ts`),E=_b(y.fs,K,`${L}.workflow-devkit.follow-up.route.ts`),r=_b(y.fs,K,`${L}.workflow-devkit.stream.route.ts`),g=_b(y.fs,K,`${L}.workflow-devkit.generic.ts`);J=[{path:D,code:Nn({exportName:_,specImportPath:V0(y.fs,D,b),workflowFunctionName:C})},{path:F,code:Fn(iW(y.fs,F,D),C)},{path:E,code:vn()},{path:r,code:gn()},{path:g,code:Pn(iW(y.fs,g,D),C)}]}break}case"data-view-renderer":{if(m!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${m})`};let q=s(n,A,b),_=Z8(n)??`${V$(q)}DataView`,z=`${V$(q)}Renderer`;K=mb(b,W,"data-views",q,".renderer.tsx",y.fs),O=Tn({exportName:_,specImportPath:V0(y.fs,K,b),rendererName:z,viewKind:X8(n)??"table"});break}case"package-scaffold":{if(m!=="module-bundle"&&m!=="builder-spec"&&m!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${m})`};if(j){let z=B8(b);return X.info(`[dry-run] Would scaffold package: ${z}`),{target:$,outputPath:z,success:!0}}let q=n.trim().length>0?n:rn({target:m,key:A.key??y.fs.basename(b),title:A.key??y.fs.basename(b),description:A.description??m8(m).title,exportName:V$(A.key??y.fs.basename(b))});return K=(await oW(y.fs,{target:m,specPath:b,specCode:q,overwrite:w})).packageRoot,X.info(`Generated package scaffold: ${K}`),{target:$,outputPath:K,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let U=[{path:K,code:O},...J],H=w?void 0:await j8(U,Z);if(H)return{target:$,outputPath:H,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(j){for(let q of U)X.info(`[dry-run] Would write: ${q.path}`);return{target:$,outputPath:K,success:!0,generatedCode:U[0]?.code}}for(let q of U)await Z.mkdir(Z.dirname(q.path)),await Z.writeFile(q.path,G8(q.code)),X.info(`Generated: ${q.path}`);return{target:$,outputPath:K,success:!0}}function J0($,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 mb($,b,n,A,m,y){let W=U0(A.split(".").pop()??"unknown"),w;if(b.startsWith("."))w=y.resolve(y.dirname($),"..",b,n);else w=y.resolve(b,n);return y.join(w,`${W}${m}`)}async function j8($,b){for(let n of $)if(await b.exists(n.path))return n.path;return}function U0($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function V$($){return U0($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function K0($){return $.replace(/\.[^.]+$/,"")}function B8($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function V0($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function iW($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function _b($,b,n){return $.join($.dirname(b),n)}function s($,b,n){return S8($,"name")??b.key??K0(H8(n))}function S8($,b){let n=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(n)?.[1]??null}function Q8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function Z8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function X8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function Y8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function G8($){return $.endsWith(`
|
|
1762
1773
|
`)?$:`${$}
|
|
1763
|
-
`}function g8($){return $.replaceAll("\\","/").split("/").pop()??$}s();import{scanAllSpecsFromSource as c8,scanSpecSource as d8}from"@contractspec/module.workspace";import u8 from"micromatch";var Ew={};P(Ew,{validators:()=>h8,urlSchema:()=>f8,isValidVersion:()=>P8,isValidIdentifier:()=>Cw,isValidDotName:()=>Iw,isTestFile:()=>Ob,isLibraryDefinitionFile:()=>Vb,emailSchema:()=>r8});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 P8($){return Number.isInteger($)&&$>0}var r8=q$.string().email(),f8=q$.string().url(),h8={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 o8($){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 i8($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function l8($,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:o8(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&&u8.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=c8(w,W),y=j.length>0?j:[d8(w,W)];for(let B of y)if(i8(B,b,m))n.push(B)}catch{}}return n.sort(l8)}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=t8(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 t8($,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 p8,buildReverseEdges as a8,createContractGraph as e8,detectCycles as s8,findMissingDependencies as $9,parseImportedSpecNames as b9,toDot as A9}from"@contractspec/module.workspace";async function Mw($,b={}){let{fs:A}=$,m=await g$(A,{config:b.config,pattern:b.pattern}),n=e8();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=b9(y,j);p8(n,S,B,Q)}a8(n);let W=s8(n),w=$9(n);return{graph:n,total:n.size,cycles:W,missing:w}}function Oq($,b){return $.get(b)}function Vq($){return A9($)}function Jq($){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(" → ")}`,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 m9}from"@contractspec/module.workspace";var n9=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function W9($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:n9}),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 W9($,b);for(let n of m){let W=m9({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 j9($,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 j9($,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+=`
|
|
1764
|
-
`}return Z+=`${
|
|
1765
|
-
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${
|
|
1774
|
+
`}function H8($){return $.replaceAll("\\","/").split("/").pop()??$}$$();import{scanAllSpecsFromSource as K8,scanSpecSource as _8}from"@contractspec/module.workspace";import z8 from"micromatch";var aW={};f(aW,{validators:()=>U8,urlSchema:()=>J8,isValidVersion:()=>O8,isValidIdentifier:()=>lW,isValidDotName:()=>pW,isTestFile:()=>zb,isLibraryDefinitionFile:()=>Lb,emailSchema:()=>V8});import _0 from"micromatch";function zb($,b){let n=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _0.isMatch($,n)}function Lb($){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(_0.isMatch($,b))return!1;let n=["**/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 _0.isMatch($,n)}import*as J$ from"zod";function lW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function pW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function O8($){return Number.isInteger($)&&$>0}var V8=J$.string().email(),J8=J$.string().url(),U8={specName:J$.string().refine(pW,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:J$.number().int().positive(),identifier:J$.string().refine(lW,{message:"Must be a valid TypeScript identifier"}),owner:J$.string().startsWith("@"),tag:J$.string().min(1)};function Rb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function L8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],n=[...Rb($?.conventions.models),...Rb($?.conventions.operations),...Rb($?.conventions.events),...Rb($?.conventions.presentations),...Rb($?.conventions.forms)];return[...new Set(b.flatMap((A)=>{let m=A==="**"?"":`${A}/`,y=q$.map((w)=>`${m}${w}`),W=n.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function R8($,b,n){if($.specType==="unknown")return!1;if(b.type&&!n.includes($.specType))return!1;return!0}function C8($,b){let n=$.filePath.localeCompare(b.filePath);if(n!==0)return n;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function c$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((n,A)=>n.localeCompare(A));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:L8(b.config)})}async function cn($,b={}){let n=await c$($.fs,b),A=b.type?Array.isArray(b.type)?b.type:[b.type]:[],m=[];for(let y of n){if(b.config?.excludePackages&&z8.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||zb(y,b.config)||Lb(y))continue;try{let W=await $.fs.readFile(y),w=K8(W,y),j=w.length>0?w:[_8(W,y)];for(let B of j)if(R8(B,b,A))m.push(B)}catch{}}return m.sort(C8)}function L$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function hn($){let b=JSON.parse($),n=new Map,A=0,m=0,y=0,W=0,w=0,j=0,B=0,S=0;for(let[Z,X]of Object.entries(b)){let Y=x8(Z,X);n.set(Z,Y),A+=Y.statements.total,m+=Y.statements.covered,y+=Y.branches.total,W+=Y.branches.covered,w+=Y.functions.total,j+=Y.functions.covered,B+=Y.lines.total,S+=Y.lines.covered}let Q={statements:{covered:m,total:A,pct:L$(m,A)},branches:{covered:W,total:y,pct:L$(W,y)},functions:{covered:j,total:w,pct:L$(j,w)},lines:{covered:S,total:B,pct:L$(S,B)}};return{files:n,total:Q}}function x8($,b){let n=Object.keys(b.statementMap).length,A=Object.values(b.s).filter((S)=>S>0).length,m=Object.keys(b.fnMap).length,y=Object.values(b.f).filter((S)=>S>0).length,W=0,w=0;for(let S of Object.values(b.b))W+=S.length,w+=S.filter((Q)=>Q>0).length;let j=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(j.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:A,total:n,pct:L$(A,n)},branches:{covered:w,total:W,pct:L$(w,W)},functions:{covered:y,total:m,pct:L$(y,m)},lines:{covered:B.size,total:j.size,pct:L$(B.size,j.size)}}}function z0($){switch($){case"istanbul":return{parse:hn};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 L0($,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 R0($,b,n,A){let m=[];if(n.statements!==void 0&&A.statements.pct<n.statements)m.push({metric:"statements",required:n.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${n.statements}%`});if(n.branches!==void 0&&A.branches.pct<n.branches)m.push({metric:"branches",required:n.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${n.branches}%`});if(n.functions!==void 0&&A.functions.pct<n.functions)m.push({metric:"functions",required:n.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${n.functions}%`});if(n.lines!==void 0&&A.lines.pct<n.lines)m.push({metric:"lines",required:n.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${n.lines}%`});if(n.mutations!==void 0)m.push({metric:"mutations",required:n.mutations,actual:0,message:`Mutation coverage required (${n.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:n,actual:A,passed:m.length===0,failures:m}}async function C0($,b,n){let{fs:A,logger:m}=$,y=[],W=n.workspaceRoot?`${n.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await A.exists(X)){j=await A.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=L0(B??"coverage.json"),Z=z0(S).parse(j);for(let X of b){if(X.specType!=="test-spec"||!X.key||!X.version||!X.sourceBlock)continue;let Y=X.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!Y||!Y[1])continue;let G=Y[1],V={},O=G.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=G.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=G.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let U=G.match(/lines\s*:\s*(\d+)/);if(U&&U[1])V.lines=parseInt(U[1],10);if(Object.keys(V).length===0)continue;let H=R0(X.key,X.version,V,Z.total);for(let q of H.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:q.metric,required:q.required,actual:q.actual}})}return y}$$();import{addContractNode as I8,buildReverseEdges as E8,createContractGraph as M8,detectCycles as T8,findMissingDependencies as D8,parseImportedSpecNames as N8,toDot as F8}from"@contractspec/module.workspace";async function eW($,b={}){let{fs:n}=$,A=await c$(n,{config:b.config,pattern:b.pattern}),m=M8();for(let w of A){let j=await n.readFile(w),B=n.relative(".",w),S=n.basename(w).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=N8(j,w);I8(m,S,B,Q)}E8(m);let y=T8(m),W=D8(m);return{graph:m,total:m.size,cycles:y,missing:W}}function UO($,b){return $.get(b)}function KO($){return F8($)}function _O($){let b=Array.from($.values()),n=b.filter((W)=>W.dependencies.length>0),A=b.filter((W)=>W.dependencies.length===0),m=b.filter((W)=>W.dependents.length>0),y=b.filter((W)=>W.dependents.length===0);return{total:$.size,withDeps:n.length,withoutDeps:A.length,used:m.length,unused:y.length}}async function x0($,b){let n=[],A=await P($.fs),m=await eW($,{config:A,pattern:b.pattern});for(let y of m.cycles)n.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${y.join(" → ")}`,category:"deps",context:{cycle:y}});for(let y of m.missing)for(let W of y.missing)n.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${y.contract} requires ${W}`,category:"deps",context:{contract:y.contract,missing:W}});return n}import{analyzePackageDocBlocks as v8}from"@contractspec/module.workspace";var g8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function P8($,b){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:g8}),A=new Map;for(let W of n){let w=$.dirname(W),j=$.join(w,"src");if(!await $.exists(j))continue;try{let B=JSON.parse(await $.readFile(W));A.set(w,{packageName:B.name??$.relative(b,w),packageRoot:w,srcRoot:j})}catch{continue}}let m=$.join(b,"package.json"),y=$.join(b,"src");if(await $.exists(m)&&await $.exists(y))try{let W=JSON.parse(await $.readFile(m));A.set(b,{packageName:W.name??b,packageRoot:b,srcRoot:y})}catch{}return[...A.values()].sort((W,w)=>W.packageRoot.localeCompare(w.packageRoot))}async function dn($,b){let n=[],A=await P8($,b);for(let m of A){let y=v8({packageName:m.packageName,srcRoot:m.srcRoot});for(let W of y.diagnostics)n.push({...W,packageName:m.packageName,packageRoot:m.packageRoot,srcRoot:m.srcRoot})}return n}async function I0($,b){let n=b.workspaceRoot??process.cwd();return(await dn($.fs,n)).map((m)=>({ruleId:m.ruleId,severity:m.severity==="warning"?"warning":"error",message:m.message,category:"docs",file:m.file,line:m.line,column:m.column,context:{packageName:m.packageName,packageRoot:m.packageRoot,...m.context}}))}async function E0($,b,n){let A=[],m=await k8($,b);if(A.push(m),m.status==="pass")A.push(await r8($,b,n));return A}async function k8($,b){let n=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(n))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let m=await $.readFile(n),y=JSON.parse(m),W=y.aiProvider??"claude",w=y.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${W}, Model: ${w}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function r8($,b,n){let A=$.join(b.workspaceRoot,".contractsrc.json");try{let m=await $.readFile(A),W=JSON.parse(m).aiProvider??"claude",j={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[W];if(!j)return{category:"ai",name:"API Key",status:"pass",message:`${W} does not require an API key`};if(!!process.env[j])return{category:"ai",name:"API Key",status:"pass",message:`${j} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${j} not set`,details:`Set ${j} in your environment to use AI features`,fix:n?{description:`Set ${j} environment variable`,apply:async()=>{let S=await n.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(`${j}=`))return{success:!1,message:`${j} already in .env, update manually`};Z+=`
|
|
1775
|
+
`}return Z+=`${j}=${S}
|
|
1776
|
+
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${j} 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 f8}from"node:child_process";import{promisify as c8}from"node:util";var un=c8(f8);async function M0($,b){let n=[];return n.push(await h8(b)),n.push(await d8(b)),n.push(await u8($,b)),n}async function h8($){try{return await un("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 un("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 d8($){try{let{stdout:b}=await un("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 u8($,b){let n=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(n))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let w=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(w))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let m=await $.readFile(n),y=JSON.parse(m);if(y.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||y.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 un("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(w){return{success:!1,message:`Failed to install: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}$$();import{DEFAULT_CONTRACTSRC as on}from"@contractspec/lib.contracts-spec/workspace-config";import{join as o8,relative as i8}from"node:path";var t8="contractspec",l8="contractsrc.schema.json";function p8($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Cb($){return p8(i8($.configRoot,o8($.workspaceRoot,"node_modules",t8,l8)))}var xb=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],sW={"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)"},$w=["core","connect","builder-managed","builder-local","builder-hybrid"],bw={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 Ib={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function Eb($){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 R$($){return $.preset??"core"}function Aw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return xb}}function T0($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function mw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function rO($){return $.startsWith("builder-")}function fO($){return $==="connect"}function yw($){let b=R$($),n=a8($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset managed-mvp`,`contractspec builder status --workspace-id ${n}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function a8($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function Ww($){let b=R$($),n=[Ib.verificationCache];if(b==="connect")n.unshift(Ib.connect);return n}function Wb($){let b=$.isMonorepo&&$.scope==="package",n=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,A=e8($),m=s8($);return{$schema:Cb({configRoot:n,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}:{},...m?{builder:m}:{},...b&&$.packageName?{package:$.packageName}:{}}}function tn($){let b=R$($),n={"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(T0(b))n["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return n}function Mb(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function ww(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function jw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1766
1777
|
|
|
1767
1778
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1768
1779
|
|
|
@@ -1783,10 +1794,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1783
1794
|
## Contract Locations
|
|
1784
1795
|
|
|
1785
1796
|
Contracts are located in:
|
|
1786
|
-
- \`${
|
|
1787
|
-
- \`${
|
|
1788
|
-
- \`${
|
|
1789
|
-
- \`${
|
|
1797
|
+
- \`${A}/operations/\` - Command and query specs
|
|
1798
|
+
- \`${A}/events/\` - Event specs
|
|
1799
|
+
- \`${A}/presentations/\` - UI presentation specs
|
|
1800
|
+
- \`${A}/features/\` - Feature module specs
|
|
1790
1801
|
|
|
1791
1802
|
## When Making Changes
|
|
1792
1803
|
|
|
@@ -1828,7 +1839,7 @@ defineCommand({
|
|
|
1828
1839
|
- Events must be declared in contracts before being emitted.
|
|
1829
1840
|
- UI components should reference presentation contracts.
|
|
1830
1841
|
- Feature flags should be defined in feature modules.
|
|
1831
|
-
`}function
|
|
1842
|
+
`}function Bw($){let b=$.projectName??"this project",n=$.isMonorepo&&$.scope==="package",A=R$($),m=n&&$.packageName?`${$.packageName} package`:b,y="src/contracts",W=$.isMonorepo?n?`
|
|
1832
1843
|
## Monorepo Scope
|
|
1833
1844
|
|
|
1834
1845
|
This guide is scoped to the current package.
|
|
@@ -1842,7 +1853,7 @@ This guide is scoped to the workspace root.
|
|
|
1842
1853
|
- Prefer the nearest package guide when working inside a specific package.
|
|
1843
1854
|
`:"";return`# ContractSpec AI Guide
|
|
1844
1855
|
|
|
1845
|
-
Scope: \`${
|
|
1856
|
+
Scope: \`${m}\`
|
|
1846
1857
|
|
|
1847
1858
|
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1848
1859
|
|
|
@@ -1852,7 +1863,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
|
|
|
1852
1863
|
- Validate contracts after changes with \`contractspec validate\`.
|
|
1853
1864
|
- Regenerate derived artifacts before considering the work complete.
|
|
1854
1865
|
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1855
|
-
${
|
|
1866
|
+
${W}
|
|
1856
1867
|
## Contract Locations
|
|
1857
1868
|
|
|
1858
1869
|
- \`src/contracts/operations/\` - command and query specs
|
|
@@ -1888,8 +1899,8 @@ ${w}
|
|
|
1888
1899
|
|
|
1889
1900
|
## Initialization Preset
|
|
1890
1901
|
|
|
1891
|
-
- This workspace was initialized with the \`${
|
|
1892
|
-
`}function
|
|
1902
|
+
- This workspace was initialized with the \`${A}\` setup preset.
|
|
1903
|
+
`}function Sw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1893
1904
|
|
|
1894
1905
|
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1895
1906
|
|
|
@@ -1918,16 +1929,100 @@ This workspace uses ContractSpec to keep contracts, generated artifacts, and AI
|
|
|
1918
1929
|
|
|
1919
1930
|
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1920
1931
|
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1921
|
-
`}function
|
|
1922
|
-
`}async function Jm($,b){let A=[];return 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.push(await C9($,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 K9($,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 _9($,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 U9($,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 z9($,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 L9($,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 R9($,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 C9($,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 I9}from"node:child_process";import{promisify as E9}from"node:util";var P$=E9(I9);async function Km($,b){let A=[];return A.push(await M9(b)),A.push(await x9(b)),A.push(await T9($,b)),A.push(await D9($,b)),A.push(await N9($,b)),A}async function M9($){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 x9($){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 T9($,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 D9($,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 N9($,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 F9,isFeatureFile as v9,scanAllSpecsFromSource as g9,scanExampleSource as k9,scanFeatureSource as P9}from"@contractspec/module.workspace";function r9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function PA($,b={}){let{fs:A,logger:m}=$,n=r9(),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(v9(y)){let S=P9(B,y);n.features.set(S.key,S);continue}if(F9(y)){let S=k9(B,y);n.examples.set(S.key,S);continue}if(y.includes(".app-config.")||y.includes(".blueprint.")){let S=g9(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 AO($){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(f9(n.stats.features)),A.push(h9(n.stats.examples)),A.push(c9(n.inventory.features,m,b)),A.push(d9(n.inventory.examples)),A.push(u9(n.inventory.workspaceConfigs)),A}function f9($){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 h9($){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 c9($,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 d9($){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 u9($){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 o9($,b)),A.push(await i9($,b)),A.push(await l9($,b)),A}async function o9($,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 i9($,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 l9($,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 t9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],uw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function p9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,m])=>{if(typeof m==="string")b[A]=m;return b},{})}function a9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function e9($,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=p9(y.scripts),S=await $.glob({patterns:t9,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:a9(B),testFileCount:S.length,tier:cw(j,A)})}catch{continue}}return n}function s9($){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 $S($){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 e9($,b,A),n=[];for(let w of m){if(w.tier==="critical")n.push(...s9(w));n.push(...$S(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 bS=["src/contracts","contracts","src/specs","specs"];async function Rm($,b){let A=[];return A.push(AS(b)),A.push(await mS($,b)),A.push(await nS($,b)),A.push(await WS($,b)),A.push(await jS($,b)),A.push(...await tw($,b)),A}function AS($){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 mS($,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 nS($,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 bS){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 WS($,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 jS($,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 yS={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$}},BS={confirm:async()=>!1,input:async()=>""};async function ew($,b,A=BS,m=yS){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 SS(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(`✓ ${U.message}`),H.status="pass",H.message=`Fixed: ${U.message}`,H.fix=void 0;else W.warn(`✗ ${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 SS($,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 xO($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("✓ All checks passed!");else b.push("✗ Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1923
|
-
`)}function
|
|
1924
|
-
${$.details}`;if($.fix)
|
|
1925
|
-
Fix available: ${$.fix.description}`;return
|
|
1926
|
-
|
|
1927
|
-
${$.body}`;await
|
|
1928
|
-
`).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 XV($,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 DS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function wj($,b,A){let m=DS(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 NS,SyntaxKind as FS}from"ts-morph";function jj($){let b=[],m=new NS({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(FS.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 VV($){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 kS={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Bj($){return vS("sha256").update($).digest("hex")}async function PS($,b,A,m={},n){let W={...kS,...m},w=W.computeHashes?Bj($.sourceBlock||""):void 0,j=$.key??gS.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 PS(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 hS,scanAllSpecsFromSource as cS,scanFeatureSource as dS}from"@contractspec/module.workspace";function rS($,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=rS(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=fS(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 fS($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function b$($,b){return`${$}.v${b}`}function uS(){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=uS(),w=[],j=[];for(let H of n){if((await A.stat(H)).isDirectory)continue;let U=await A.readFile(H);if(hS(H)){let z=dS(U,H);w.push(z)}else{let z=cS(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 rV($){let b=[];for(let A of Object.values($))for(let m of A.values())b.push(m);return b}function fV($,b){return $.filter((A)=>A.type===b)}function hV($,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 iS,DEFAULT_CONTRACTSRC as iA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as oS}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:A,scan:m=oS}=$,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 eV($){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 lS=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,tS=/@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?)?['"]/,pS=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,aS=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,eS=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,sS=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,$Q=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function lA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function bQ($,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 AQ($,b,A){let m=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(m))return!1;if(m.includes("/node_modules/")||m.includes("/dist/")||eS.test(m)||aS.test(m)||m.endsWith(".d.ts")||m.endsWith(".test.ts")||m.endsWith(".spec.ts"))return!1;if(b.has(m))return!1;if(bQ(m,A))return!1;return lS.test(m)}function Gj($){return $.replaceAll("\\","/").match(sS)?.[1]??null}function mQ($){let b=$.split(`
|
|
1929
|
-
`).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 nQ($){if(!$)return iA;let b=iS.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?nQ(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(!AQ(S,j,W))continue;try{let Q=await A.readFile(S);if(mQ(Q))continue;let Z=Gj(S);if(!(Z!==null&&$Q.test(Z)&&y.has(Z))&&!pS.test(Q))continue;if(tS.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 WQ}from"@contractspec/module.workspace";async function Pm($){let b=[];for(let A of $){let m=WQ(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 MJ($,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 TJ=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],DJ={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 kJ($,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:()=>Z4,resolveWorkspace:()=>o,resolveStoragePaths:()=>Q$,replayConnectDecision:()=>dQ,persistLatestArtifacts:()=>$n,persistDecisionArtifacts:()=>Nb,normalizeEvalInput:()=>FQ,matchConfiguredPath:()=>Ib,loadStoredDecision:()=>vb,listStoredReviewPackets:()=>mn,listConnectReviewPackets:()=>uQ,isReviewCommand:()=>hm,isDeniedCommand:()=>cm,isAllowedCommand:()=>tA,initConnectWorkspace:()=>rQ,inferSurfaces:()=>xb,evaluateConnectDecision:()=>DQ,ensureStorage:()=>Db,defaultActor:()=>Mb,decisionArtifactRefs:()=>nb,createConnectControlPlaneRuntime:()=>b4,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:()=>BQ,ACP_FS_ACCESS_REF:()=>yQ});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(jQ);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((m)=>!tA($,m)),state:"unknown"}}function jQ($){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"},yQ={key:"acp.fs.access",version:"1.0.0",kind:"command"},BQ={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=SQ({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=QQ({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 SQ($){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(ZQ)[0]??"permit"}function QQ($){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 ZQ($,b){return Oj($)-Oj(b)}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as xQ}from"crypto";var Uj={};P(Uj,{formatPrComment:()=>Vj,formatMinimalComment:()=>lm,formatJson:()=>Kj,formatCheckRun:()=>Jj,detectImpact:()=>V$,ImpactDetectionOverviewDocBlock:()=>OQ});function Vj($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)A.push("⚠️ **Contract changed (non-breaking)**");else A.push("✅ **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(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| ➖ 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("### ⚠️ 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("### ✅ No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
1930
|
-
|
|
1932
|
+
`}function e8($){if(R$($)!=="connect")return;return{...on.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:{...on.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:on.connect?.studio}}function s8($){let b=T0(R$($)),n=mw(R$($));if(!b||!n)return;let A=!0,m=b==="local"||b==="hybrid";return{...on.builder,enabled:!0,runtimeMode:b,bootstrapPreset:n,api:A?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:m?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function ln(){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$($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(m===void 0)n[A]=y;else if(pn(m)&&pn(y))n[A]=b$(m,y)}return n}function D0($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(y===void 0)continue;if(pn(m)&&pn(y))n[A]=D0(m,y);else n[A]=y}return n}function pn($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function a($){try{return JSON.parse($)}catch{return null}}function N($){return JSON.stringify($,null,2)+`
|
|
1933
|
+
`}async function N0($,b){let n=[];return n.push(await $9($,b)),n.push(await b9($,b)),n.push(await n9($,b)),n.push(await A9($,b)),n.push(await m9($,b)),n.push(await y9($,b)),n.push(await W9($,b)),n}async function h$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function $9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(await $.exists(n))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 m=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(m)),{success:!0,message:"Created .contractsrc.json"}}catch(m){return{success:!1,message:`Failed to create: ${m instanceof Error?m.message:String(m)}`}}}}}}async function b9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n);return JSON.parse(m),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(m){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:m instanceof Error?m.message:String(m),fix:{description:"Replace with valid default config",apply:async()=>{try{let W=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,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 n9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m),W=[];if(!y.outputDir)W.push("outputDir");if(!y.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 w=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let j of W)if(w[j]!==void 0)y[j]=w[j];return await $.writeFile(n,N(y)),{success:!0,message:"Added missing fields"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function A9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:y.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 y.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(n,N(y)),{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 m9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.hooks){let j=y.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(j).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 y.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(n,N(y)),{success:!0,message:"Added hooks configuration"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}};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 y9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[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((S)=>S!==null),j=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(w.length===0&&!j)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: ${[...w,...j?["connect.studio.endpoint"]:[]].join(", ")}`}}let y=[],W=A.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!A.builder?.api?.baseUrl)y.push("builder.api.baseUrl");if(m.startsWith("builder-")&&!W)y.push("builder.api.controlPlaneTokenEnvVar");if(m.startsWith("builder-")&&W&&!process.env[W])y.push(`env:${W}`);if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)y.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:y.length===0?"pass":"warn",message:y.length===0?`Builder preset inferred (${m}) and required config is present`:`Builder preset inferred (${m}) but setup is missing ${y.join(", ")}`}}async function W9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(n,".vscode","settings.json"),W=A.builder?.api?.baseUrl;if(!W)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let w=await $.readFile(y).catch(()=>""),j=w?a(w):void 0;if(j?.["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(n,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...tn({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,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 w9}from"node:child_process";import{promisify as j9}from"node:util";var d$=j9(w9);async function F0($,b){let n=[];return n.push(await B9(b)),n.push(await S9(b)),n.push(await Q9($,b)),n.push(await Z9($,b)),n.push(await X9($,b)),n}async function B9($){try{let{stdout:b}=await d$("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 S9($){try{let{stdout:b}=await d$("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 Q9($,b){let n=[{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:m,name:y}of n){let W=$.join(b.workspaceRoot,m);if(await $.exists(W)){A=y;break}}if(!A){let m=$.join(b.workspaceRoot,".."),y=$.join(b.workspaceRoot,"../.."),W=[m,y];for(let w of W){for(let{file:j,name:B}of n){let S=$.join(w,j);if(await $.exists(S)){A=B;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 d$(`${A} --version`,{cwd:b.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 Z9($,b){let n=$.join(b.workspaceRoot,"node_modules");if(await $.exists(n))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 d$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function X9($,b){let n=$.join(b.workspaceRoot,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A),y={...m.dependencies,...m.devDependencies};if("@contractspec/lib.contracts-spec"in y)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${y["@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 d$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("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 v0($,b){let n=await dn($,b.workspaceRoot);if(n.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return n.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(b.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as Y9,isFeatureFile as G9,scanAllSpecsFromSource as H9,scanExampleSource as q9,scanFeatureSource as O9}from"@contractspec/module.workspace";function V9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function an($,b={}){let{fs:n,logger:A}=$,m=V9(),y=b.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let W=await n.glob({pattern:y});for(let j of W){if(j.includes("node_modules")||j.includes("/dist/"))continue;try{let B=await n.readFile(j);if(G9(j)){let S=O9(B,j);m.features.set(S.key,S);continue}if(Y9(j)){let S=q9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=H9(B,j);for(let Q of S)if(Q.specType==="app-config"&&Q.key)m.appConfigs.set(Q.key,Q)}}catch{}}try{let j=await n.glob({pattern:"**/.contractsrc.json"});for(let B of j){if(B.includes("node_modules"))continue;try{let S=await n.readFile(B),Q=JSON.parse(S);m.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){m.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let w={features:m.features.size,examples:m.examples.size,appConfigs:m.appConfigs.size,workspaceConfigs:m.workspaceConfigs.size,total:m.features.size+m.examples.size+m.appConfigs.size+m.workspaceConfigs.size};return A.info(`Discovered ${w.features} features, ${w.examples} examples, ${w.appConfigs} app configs, ${w.workspaceConfigs} workspace configs`),{inventory:m,stats:w}}function yV($){let b=[];for(let[n,A]of $.features)b.push({key:n,file:A.filePath,type:"feature"});for(let[n,A]of $.examples)b.push({key:n,version:A.version,file:A.filePath,type:"example"});for(let[n,A]of $.appConfigs)b.push({key:n,version:A.version,file:A.filePath,type:"app-config"});for(let[,n]of $.workspaceConfigs)b.push({key:n.file,file:n.file,type:"workspace-config"});return b}function en($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function g0($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function sn($,b){let n=$.join(b,"config/stability-policy.json");if(!await $.exists(n))return;try{let A=await $.readFile(n),m=JSON.parse(A);return{version:typeof m.version==="number"&&Number.isFinite(m.version)?m.version:1,criticalPackages:g0(m.criticalPackages).map(en),criticalFeatureKeys:g0(m.criticalFeatureKeys),smokePackages:g0(m.smokePackages)}}catch{return}}function Qw($,b){let n=en($);if(b?.criticalPackages.includes(n))return"critical";return"non-critical"}function Zw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function wb($){return en(`${en($)}/config/stability-policy.json`)}async function P0($,b){let n=[],A=await sn($,b.workspaceRoot),m=await an({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return n.push(J9(m.stats.features)),n.push(U9(m.stats.examples)),n.push(K9(m.inventory.features,A,b)),n.push(_9(m.inventory.examples)),n.push(z9(m.inventory.workspaceConfigs)),n}function J9($){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 U9($){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 K9($,b,n){let A=[],m=[];for(let[y,W]of $)if(!(Boolean(W.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(W.sourceBlock??"")))if(Zw(y,b))m.push(y);else A.push(y);if(m.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:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:m.length>0?"fail":"warn",message:m.length>0?`${m.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:m.length>0?`Critical features: ${m.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:m,missingFeatures:A}}}function _9($){let b=[];for(let[n,A]of $)if(!A.entrypoints.packageName)b.push(n);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 z9($){let b=[];for(let[,n]of $)if(!n.valid)b.push(n.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 k0($,b){let n=[];return n.push(await L9($,b)),n.push(await R9($,b)),n.push(await C9($,b)),n}async function L9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(n))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 m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Mb();return await $.writeFile(n,N(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function R9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(n))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.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 w=Mb(),j=b$(y,w);return await $.writeFile(n,N(j)),{success:!0,message:"Registered MCP server"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function C9($,b){let n=ln();try{if(!await $.exists(n))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let m=await $.readFile(n);if(JSON.parse(m).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 x9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Xw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function I9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[n,A])=>{if(typeof A==="string")b[n]=A;return b},{})}function E9($){return Object.entries($).some(([b,n])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(n)})}async function M9($,b,n){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:Xw}),m=[];for(let y of A){let W=$.dirname(y),w=$.relative(b,W);try{let j=JSON.parse(await $.readFile(y)),B=I9(j.scripts),S=await $.glob({patterns:x9,cwd:W,ignore:Xw});m.push({packageName:j.name??w,packagePath:w.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:E9(B),testFileCount:S.length,tier:Qw(w,n)})}catch{continue}}return m}function T9($){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 D9($){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 Yw($,b,n){let A=await M9($,b,n),m=[];for(let W of A){if(W.tier==="critical")m.push(...T9(W));m.push(...D9(W))}let y=A.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:m,criticalPackages:y}}function Hw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Gw($,b,n,A){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||n.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:Hw(b),context:{findings:b}}}async function qw($,b){let n=await sn($,b.workspaceRoot);if(!n)return[];let A=await Yw($,b.workspaceRoot,n),m=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"]),y=A.findings.filter((j)=>m.has(j.code)),W=A.findings.filter((j)=>j.code==="tests-without-test-script"),w=A.findings.filter((j)=>j.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:y.length>0?"fail":"pass",message:y.length>0?`${y.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?Hw(y):b.verbose?`Policy: ${wb(b.workspaceRoot)}`:void 0,context:{policyPath:wb(b.workspaceRoot),criticalPackages:A.criticalPackages,findings:y}},Gw("Package Test Scripts",W,new Set,"All tested packages expose a test script"),Gw("Buildable Packages Without Tests",w,new Set,"All buildable packages have tests or explicit test scripts")]}var N9=["src/contracts","contracts","src/specs","specs"];async function r0($,b){let n=[];return n.push(F9(b)),n.push(await v9($,b)),n.push(await g9($,b)),n.push(await P9($,b)),n.push(await r9($,b)),n.push(...await qw($,b)),n}function F9($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",n=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${n}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function v9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let A of n){let m=$.join(A,"package.json");if(await $.exists(m))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.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 g9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],A=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let W of n)for(let w of N9){let j=$.join(W,w);if(await $.exists(j)){let B=W===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${w}`,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 m=b.isMonorepo?"src/contracts":"src/contracts",y=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${m}/${y} to organize your specs`,fix:{description:`Create ${m}/ directory${y}`,apply:async()=>{try{let W=$.join(A,"src","contracts");return await $.mkdir(W),{success:!0,message:`Created ${m}/`}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}async function P9($,b){try{let n=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=b.isMonorepo?b.packageRoot:b.workspaceRoot,m=await $.glob({patterns:n,ignore:["node_modules/**","dist/**"],cwd:A});if(m.length>0){let W=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${m.length} contract file(s)${W}`,details:b.verbose?m.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 k9($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let A=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.packageRoot,level:"package"}}let n=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(n))return{path:n,root:b.workspaceRoot,level:"workspace"};return null}async function r9($,b){try{let n=await k9($,b);if(!n)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 A=await $.readFile(n.path),m=JSON.parse(A),y=m.outputDir??"./src",W=$.join(n.root,y),w=b.isMonorepo?` (${n.level} level)`:"";if(await $.exists(W))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${y}${w}`,details:b.verbose?`Resolved to: ${W}`:void 0};let B=y==="./src"||y==="src",S=Array.isArray(m.packages)&&m.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||n.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 ${n.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${y}${w}`,details:b.verbose?`Expected at: ${W}`:void 0,fix:{description:`Create ${y} directory`,apply:async()=>{try{return await $.mkdir(W),{success:!0,message:`Created ${y}`}}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 Ow=["cli","config","mcp","deps","docs","workspace","ai","layers"],Vw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var f9={checks:{runCliChecks:M0,runConfigChecks:N0,runMcpChecks:k0,runDepsChecks:F0,runDocChecks:v0,runWorkspaceChecks:r0,runAiChecks:E0,runLayerChecks:P0},workspace:{findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$}},c9={confirm:async()=>!1,input:async()=>""};async function Jw($,b,n=c9,A=f9){let{fs:m,logger:y}=$,W=b.categories??Ow,{checks:w,workspace:j}=A,B=j.findWorkspaceRoot(b.workspaceRoot),S=j.findPackageRoot(b.workspaceRoot),Q=j.isMonorepo(B),Z=Q?j.getPackageName(S):void 0,X={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${J}`)}let Y=[];for(let J of W){if(b.skipAi&&J==="ai")continue;y.info(`Checking ${Vw[J]}...`);let U=await h9(J,m,X,n,w);for(let H of U){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await n.confirm(`Fix "${H.name}"? ${H.fix.description}`)){y.info(`Applying fix: ${H.fix.description}`);let _=await H.fix.apply();if(_.success)y.info(`✓ ${_.message}`),H.status="pass",H.message=`Fixed: ${_.message}`,H.fix=void 0;else y.warn(`✗ ${_.message}`)}}Y.push(H)}}let G=Y.filter((J)=>J.status==="pass").length,V=Y.filter((J)=>J.status==="warn").length,O=Y.filter((J)=>J.status==="fail").length,K=Y.filter((J)=>J.status==="skip").length;return{checks:Y,passed:G,warnings:V,failures:O,skipped:K,healthy:O===0}}async function h9($,b,n,A,m){switch($){case"cli":return m.runCliChecks(b,n);case"config":return m.runConfigChecks(b,n);case"mcp":return m.runMcpChecks(b,n);case"deps":return m.runDepsChecks(b,n);case"docs":return m.runDocChecks(b,n);case"workspace":return m.runWorkspaceChecks(b,n);case"ai":return m.runAiChecks(b,n,A);case"layers":return m.runLayerChecks(b,n);default:return[]}}function NV($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("✓ All checks passed!");else b.push("✗ Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1934
|
+
`)}function FV($){let n=`${$.status==="pass"?"✓":$.status==="warn"?"⚠":$.status==="fail"?"✗":"○"} ${$.name}: ${$.message}`;if($.details)n+=`
|
|
1935
|
+
${$.details}`;if($.fix)n+=`
|
|
1936
|
+
Fix available: ${$.fix.description}`;return n}async function f0($,b){let n=[],A=b.workspaceRoot??process.cwd(),m=await Jw($,{workspaceRoot:A,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let y of m.checks)if(y.status==="fail")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});else if(y.status==="warn")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});return n}$$();import{mkdtemp as yQ,rm as WQ}from"node:fs/promises";import{tmpdir as wQ}from"node:os";import Tb from"path";import{DEFAULT_CONTRACTSRC as a9}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as e9}from"@contractspec/module.workspace";import s9 from"path";import{packageDocBlocks as d9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as u9,convertSpecToDocBlock as o9,extractModuleDocData as i9,loadSpecFromSource as t9,scanAllSpecsFromSource as l9,scanSpecSource as p9}from"@contractspec/module.workspace";import h0 from"path";import{dirname as Uw,sep as $A}from"path";class c0{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let n;if(b.specType==="app-config")n="app-config";else if(b.specType==="example")n="example";else if(b.specType==="feature")n="feature";if(n&&b.key){let A=Uw(b.filePath);this.modules.push({type:n,key:b.key,dirPath:A})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=Uw($),n=this.modules.filter((A)=>{let m=A.dirPath.endsWith($A)?A.dirPath:A.dirPath+$A;return(b.endsWith($A)?b:b+$A).startsWith(m)||b===A.dirPath});if(n.length===0)return;return n.sort((A,m)=>{let y={"app-config":3,example:2,feature:1},W=y[A.type],w=y[m.type];if(W!==w)return w-W;return m.dirPath.length-A.dirPath.length}),n[0]}}async function _w($,b,n){let{fs:A,logger:m}=n,y=[];if(m.info(`Generating docs for ${$.length} files...`),b.outputDir)await A.mkdir(b.outputDir);let W=new c0(n),w=[];for(let B of $)try{let S=await A.readFile(B),Q=l9(S,B);if(Q.length>0)w.push(...Q);else{let Z=p9(S,B);if(Z.specType!=="unknown")w.push(Z)}}catch(S){}W.initialize(w);let j=await zw($,n);for(let B of j)if(y.push(B.entry.block),m.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await Kw(B.entry.block,B.filePath,b.outputDir,W,A);for(let B of $)try{let S=await t9(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=o9(Q,{rootPath:b.rootPath});if(y.push(Z),m.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await Kw(Z,B,b.outputDir,W,A)}}catch(S){m.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)m.info(`Wrote ${y.length} doc files to ${b.outputDir}`);return{blocks:y,count:y.length}}async function uV($,b){return(await zw($,b)).map(({entry:A})=>A.block)}function oV($,b){return d9(u9({packageName:$,srcRoot:b}))}async function zw($,b){let n=[...new Set($)].sort((m,y)=>m.localeCompare(y)),A=[];for(let m of n){let y=await b.fs.readFile(m),W=m.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),w=i9(y,m,W);for(let j of w.entries)A.push({entry:j,filePath:m})}return A}async function Kw($,b,n,A,m){let y=A.resolve(b),W=y?h0.join(n,y.key):h0.join(n,"_common");await m.mkdir(W);let w=h0.join(W,`${$.id}.md`),j=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1937
|
+
|
|
1938
|
+
${$.body}`;await m.writeFile(w,j)}async function Lw($,b,n,A,m={}){let y=m.config,W=await cn($,{cwd:m.specSearchRoot,config:y,pattern:m.specPattern??bQ(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=s9.join(nQ(n,y),"docs"),j=await _w(W.map((S)=>S.filePath),{outputDir:w,format:"markdown",rootPath:A},$),B=0;for(let S of W){let Q=$Q(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await yb(S.filePath,$,y??a9,{targets:J0(S.specType,{includeTests:Boolean(m.includeRuntimeTests)}),outputDir:y?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((X)=>X.success).length}return{specsCount:W.length,docsCount:j.count,materializedCount:B}}function $Q($){return e9($.specType)}function bQ($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${d0($)}/**/*.ts`:void 0}function nQ($,b){let n=(b?.connect?.policy?.generatedPaths??[]).map(mQ).filter(Boolean);if(n.length>0)return n[0];if(b?.outputDir&&b.outputDir!=="./src")return d0(b.outputDir);return $}function AQ($){return d0($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function mQ($){let b=AQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function d0($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function bA($,b,n,A={}){let m=await yQ(Tb.join(wQ(),"contractspec-drift-"));try{await Lw($,b,m,A.rootPath,A.generation);let y=[],W=await import("node:fs/promises");async function w(Z){let X=await W.readdir(Z,{withFileTypes:!0}),Y=[];for(let G of X){let V=Tb.resolve(Z,G.name);if(G.isDirectory())Y.push(...await w(V));else Y.push(V)}return Y}let j=async(Z)=>{if(!await W.stat(Z).catch(()=>!1))return[];return(await w(Z)).map((Y)=>Tb.relative(Z,Y)).sort()},B=await j(m),S=await j(n),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){y.push(Z);continue}if(!B.includes(Z)){y.push(Z);continue}let X=await W.readFile(Tb.join(m,Z)),Y=await W.readFile(Tb.join(n,Z));if(!X.equals(Y))y.push(Z)}return{hasDrift:y.length>0,files:y}}finally{await WQ(m,{recursive:!0,force:!0})}}async function u0($,b){let{fs:n,logger:A}=$,m=[],y=await P(n);if(!y.outputDir)return A.info("No outputDir configured, skipping drift checks"),m;let W="./contracts",w=y.outputDir;if(!await n.exists(w))return A.info("Generated directory does not exist, skipping drift checks"),m;try{let j=await bA($,W,w);if(j.hasDrift)for(let B of j.files)m.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${w}/${B}`,context:{file:B}})}catch(j){A.warn("Drift detection failed",{error:j instanceof Error?j.message:String(j)})}return m}$$();function jQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function BQ($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function nA($,b,n,A={}){let{fs:m}=b,y=[],W=[],w=$.key??m.basename($.filePath).replace(/\.[jt]s$/,""),j=A.outputDir??n.outputDir??"./src",B=jQ(w),S={};if($.specType==="operation")S.handlerPath=m.join(j,"handlers",`${B}.handler.ts`),S.handlerTestPath=m.join(j,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=m.join(j,"components",`${B}.tsx`),S.componentTestPath=m.join(j,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=m.join(j,"forms",`${B}.form.tsx`),S.formTestPath=m.join(j,"forms",`${B}.form.test.tsx`);if(A.checkHandlers&&S.handlerPath)if(!await m.exists(S.handlerPath))y.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await m.readFile(S.handlerPath),X=`${BQ(w.split(".").pop()??w)}Spec`,Y=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),G=new RegExp(`typeof\\s+${X}\\b`).test(Z);if(!Y)W.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!G)W.push(`Handler ContractHandler typing does not reference expected spec var (${X}): ${S.handlerPath}`)}if(A.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await m.exists(Z))y.push(`Missing test file: ${Z}`)}return{valid:y.length===0,errors:y,warnings:W,expected:S}}async function o0($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkHandlers:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"handler-missing",severity:"warning",message:w,category:"handlers",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"handler-warning",severity:"warning",message:w,category:"handlers",file:y.filePath})}return A}$$();import{createHash as GQ}from"crypto";import HQ from"path";var Db={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},SQ={".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 QQ($){let b=$.toLowerCase();for(let[n,A]of Object.entries(SQ))if(b.endsWith(n))return A;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 Rw($,b){let n=[],A=new Set,m=(Z,X,Y)=>{let G=`${Z}:${X}`;if(A.has(G))return;A.add(G),n.push({filePath:b,specKey:Z,referenceType:X,lineNumber:Y,inferredType:QQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1939
|
+
`).length},W,w=new RegExp(Db.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Db.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Db.namedImport);while((W=B.exec($))!==null){let X=W[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(X)for(let Y of X)m(Y,"import",y(W.index))}let S=new RegExp(Db.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Db.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return n}var Cw=["**/*.ts(x)"];async function AA($,b,n={}){let{fs:A}=b,m=n.includePatterns??Cw,y=n.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await A.glob({pattern:w,ignore:y});for(let B of j)try{let S=await A.readFile(B),Z=Rw(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function qJ($,b={}){let{fs:n}=$,A=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of A){let w=await n.glob({pattern:W,ignore:m});for(let j of w)try{let B=await n.readFile(j),S=Rw(B,j);for(let Q of S){let Z=y.get(Q.specKey)??[];Z.push(Q),y.set(Q.specKey,Z)}}catch{}}return y}function ZQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,n){let A=ZQ(b),m=[];if($==="operation")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")m.push({path:`${n}/components/${A}.tsx`,type:"component"}),m.push({path:`${n}/components/${A}.test.tsx`,type:"test"});if($==="form")m.push({path:`${n}/forms/${A}.form.tsx`,type:"form"}),m.push({path:`${n}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});return m}import{Node as p,Project as XQ,SyntaxKind as YQ}from"ts-morph";function Iw($){let b=[],A=new XQ({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),m=(j)=>{if(!p.isObjectLiteralExpression(j))return;let B=j.getProperty("implementations");if(B&&p.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&p.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(p.isObjectLiteralExpression(Q)){let Z,X,Y,G=Q.getProperty("path");if(G&&p.isPropertyAssignment(G)){let K=G.getInitializer();if(p.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&p.isPropertyAssignment(V)){let K=V.getInitializer();if(p.isStringLiteral(K))X=K.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let K=O.getInitializer();if(p.isStringLiteral(K))Y=K.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=A.getDescendantsOfKind(YQ.CallExpression);for(let j of y){let B=j.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=j.getArguments();if(S.length>0&&p.isObjectLiteralExpression(S[0]))return m(S[0]),b}}let W=A.getVariableStatements();for(let j of W)if(j.isExported())for(let B of j.getDeclarations()){let S=B.getInitializer();if(S&&p.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return m(S),b}}let w=A.getExportAssignment((j)=>!j.isExportEquals());if(w){let j=w.getExpression();if(p.isObjectLiteralExpression(j))m(j);else if(p.isAsExpression(j)&&p.isObjectLiteralExpression(j.getExpression()))m(j.getExpression())}return b}function Ew($){if($.length===0)return"missing";let b=$.filter((m)=>m.exists),n=$.filter((m)=>m.type!=="test");if(b.filter((m)=>m.type!=="test").length===0)return"missing";if($.every((m)=>m.exists))return"implemented";return"partial"}function KJ($){let b=$.filter((m)=>m.status==="implemented").length,n=$.filter((m)=>m.status==="partial").length,A=$.filter((m)=>m.status==="missing").length;return{total:$.length,implemented:b,partial:n,missing:A,coverage:$.length>0?Math.round(b/$.length*100):100}}var qQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Mw($){return GQ("sha256").update($).digest("hex")}async function OQ($,b,n,A={},m){let y={...qQ,...A},W=y.computeHashes?Mw($.sourceBlock||""):void 0,w=$.key??HQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,G,V,O)=>{if(Q.has(Y))return;Q.add(Y);let K=await B.exists(Y),J=void 0,U=void 0;if(K&&y.computeHashes)try{J=await B.readFile(Y),U=Mw(J)}catch{}S.push({path:Y,type:G,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:U,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Iw($.sourceBlock);for(let G of Y)await Z(G.path,G.type,"explicit",G.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await AA(w,b,y);for(let G of Y){if(G.filePath===$.filePath)continue;await Z(G.filePath,G.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??n.outputDir??"./src",G=xw($.specType,w,Y);for(let{path:V,type:O}of G)await Z(V,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Ew(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function Tw($,b,n,A={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await OQ(W,b,n,A,m);y.push(w)}catch(w){console.error(`Failed to resolve implementations for ${W}:`,w)}}return y}async function i0($,b,n){let{fs:A}=$,m=[],y=await P(A),W=n.implementation??{},w=b.filter((B)=>B.specType==="operation"),j=await Tw(w,{fs:A},y,{computeHashes:W.useCache??!0});for(let B of j){if(W.requireImplemented&&B.status==="missing")m.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")m.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);m.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)m.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 m}$$();import{isFeatureFile as UQ,scanAllSpecsFromSource as KQ,scanFeatureSource as _Q}from"@contractspec/module.workspace";function VQ($,b){return`${$}.v${b}`}function t0($,b,n,A,m,y={}){let{treatMissingAsError:W=!0}=y;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let w=[],j=[],B=[];for(let S of A){let Q=VQ(S.key,S.version);if(m.has(Q))w.push(S);else if(j.push(S),W)B.push(`Spec ${b}.v${n} references test ${S.key}.v${S.version} which does not exist`)}return{valid:j.length===0,foundTests:w,missingTests:j,errors:B,specFile:$}}function Dw($,b){return`${$}.v${b}`}function Nw($,b){let n=new Map,A=new Map,m=[],y=[];for(let W of $){if(!W.key||!W.version)continue;let w=Dw(W.key,W.version);if(!W.testTarget){y.push(w);continue}let{type:j,key:B,version:S}=W.testTarget,Q=S??W.version,Z=Dw(B,Q),X=JQ(b,j);if(!X||!X.has(Z)){m.push(w);continue}if(A.set(w,Z),!n.has(Z))n.set(Z,new Set);n.get(Z)?.add(w)}return{targetToTests:n,testToTarget:A,orphanedTests:m,testsWithoutTarget:y}}function JQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function zQ(){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 l0($,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 mA($,b={}){let{fs:n,logger:A}=$;A.info("Starting integrity analysis...",{options:b});let m=await c$(n,{config:b.config,cwd:b.cwd,pattern:b.pattern}),y=zQ(),W=[],w=[];for(let H of m){if((await n.stat(H)).isDirectory)continue;let _=await n.readFile(H);if(UQ(H)){let z=_Q(_,H);W.push(z)}else{let z=KQ(_,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let C=l0(y,L.specType);if(C&&L.key&&L.version!==void 0){let D=n$(L.key,L.version);C.set(D,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let j=b.featureKey?W.filter((H)=>H.key===b.featureKey):W,B=new Set;for(let H of j){for(let q of H.operations){let _=n$(q.key,q.version);if(B.add(`operation:${_}`),!y.operations.has(_))w.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 _=n$(q.key,q.version);if(B.add(`event:${_}`),!y.events.has(_))w.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 _=n$(q.key,q.version);if(B.add(`presentation:${_}`),!y.presentations.has(_))w.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 _=n$(q.key,q.version);if(B.add(`experiment:${_}`),!y.experiments.has(_))w.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 _=n$(q.key,q.version);if(B.add(`capability:${_}`),!y.capabilities.has(_))w.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 _=n$(q.key,q.version);B.add(`capability:${_}`)}for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=n$(q.pres.key,q.pres.version);if(!y.operations.has(_))w.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(!y.presentations.has(z))w.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 _=n$(q.key,q.version);if(!y.presentations.has(_))w.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=l0(y,H);if(!q)continue;for(let[_,z]of q)if(!B.has(`${H}:${_}`))S.push(z),w.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 y.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 X=Nw(Z,y);for(let H of j)for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=X.targetToTests.get(_),L=!1,C=!1;if(z)for(let D of z){let F=y.testSpecs.get(D);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)C=!0}}if(!z||!L||!C){let D=[];if(!L)D.push("success scenario");if(!C)D.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${D.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let Y={},G=0;for(let H of Q){let q=l0(y,H);if(!q)continue;let _=q.size,z=0,L=0,C=b.requireTestsFor?.includes(H);for(let[D,F]of q){if(B.has(`${H}:${D}`))z++;if(C){let E=n$(F.key,F.version),r=X.targetToTests.has(E),g=`${F.key}.test`,iA=y.testSpecs.has(n$(g,F.version));if(!r&&!iA)L++,G++,w.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})}}Y[H]={total:_,covered:z,orphaned:_-z,missingTest:C?L:0}}let V=Object.values(Y).reduce((H,q)=>H+q.total,0),O=Object.values(Y).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:G,byType:Y},U=!w.some((H)=>H.severity==="error");return A.info("Integrity analysis complete",{features:W.length,totalSpecs:V,orphaned:S.length,issues:w.length,healthy:U}),{inventory:y,features:j,coverage:K,issues:w,orphanedSpecs:S,healthy:U}}function hJ($){let b=[];for(let n of Object.values($))for(let A of n.values())b.push(A);return b}function dJ($,b){return $.filter((n)=>n.type===b)}function uJ($,b){return $.filter((n)=>n.severity===b)}async function p0($,b){let n=[],A=await P($.fs),m=await mA($,{config:A,pattern:b.pattern,all:!0});for(let y of m.issues)n.push({ruleId:`integrity-${y.type}`,severity:y.severity==="error"?"error":"warning",message:y.message,category:"integrity",file:y.file,context:{specKey:y.specKey,specType:y.specType,featureKey:y.featureKey,ref:y.ref}});return n}async function a0($,b){let n=[],A=await an($,{});for(let[m,y]of A.inventory.features){if(!y.key)n.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:y.filePath,context:{key:m}});if(!y.owners?.length)n.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${m}' missing 'owners' field`,category:"layers",file:y.filePath,context:{key:m}});if(y.operations.length===0&&y.events.length===0&&y.presentations.length===0)n.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${m}' has no operations, events, or presentations`,category:"layers",file:y.filePath,context:{key:m}})}for(let[m,y]of A.inventory.examples){if(!y.entrypoints.packageName)n.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${m}' missing 'packageName' in entrypoints`,category:"layers",file:y.filePath,context:{key:m}});if(!y.surfaces.templates&&!y.surfaces.sandbox.enabled&&!y.surfaces.studio.enabled&&!y.surfaces.mcp.enabled)n.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${m}' has no enabled surfaces`,category:"layers",file:y.filePath,context:{key:m}})}for(let m of A.inventory.workspaceConfigs.values())if(!m.valid)for(let y of m.errors)n.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${y}`,category:"layers",file:m.file});return n}$$();import{ContractsrcSchema as dQ,DEFAULT_CONTRACTSRC as WA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as LQ}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:n,scan:A=LQ}=$,m=await c$(n,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(zb(w,b.config))continue;if(Lb(w))continue;try{let j=await n.readFile(w),B=A(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function bU($){let b=new Map;for(let n of $){let A=b.get(n.specType)??[];A.push(n),b.set(n.specType,A)}return b}var cw={};f(cw,{toPascalCase:()=>yA,syncPackageDeclarations:()=>rQ,resolvePackageDeclarationConfig:()=>Nb,renderPackageDeclaration:()=>Wm,normalizePath:()=>C$,matchesAllowMissing:()=>ym,inferWorkspacePackageKind:()=>s0,getIndexExportPath:()=>bm,getCanonicalDeclarationRelativePath:()=>$m,discoverWorkspacePackages:()=>gw,createPackageDeclarationIssue:()=>wm,buildPackageTitle:()=>Fb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>G$,buildDomain:()=>Am,buildDeclarationTags:()=>mm,auditPackageDeclarations:()=>vb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>e0,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>Fw});var Fw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},e0={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function Nb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...Fw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function s0($){let b=C$($);for(let[n,A]of Object.entries(e0))if(b.startsWith(n))return A;return null}function $m($,b){switch($){case"libs":case"modules":return`src/${b}.feature.ts`;case"integrations":return"src/integration.ts";case"apps":case"appsRegistry":return"src/blueprint.ts";case"bundles":return`src/bundles/${yA(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function bm($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${yA(b)}Bundle`;case"examples":return"./example"}}function nm($){return C$($).replace(/^packages\//,"").replace(/\//g,".")}function Fb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Am($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function mm($,b,n){return[...new Set([...n,"package",b,$])]}function ym($,b,n){return $.some((A)=>{let m=C$(A);return m===C$(b)||m===n})}function C$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function yA($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function G$($,b){let n=yA(b);switch($){case"feature":return`${n}Feature`;case"integration":return`${n}IntegrationSpec`;case"app-config":return`${n}Blueprint`;case"module-bundle":return`${n}Bundle`;case"example":return`${n}Example`}}import{scanAllSpecsFromSource as RQ,scanSpecSource as CQ}from"@contractspec/module.workspace";var xQ=["packages/libs/*/package.json","packages/modules/*/package.json","packages/integrations/*/package.json","packages/bundles/*/package.json","packages/apps/*/package.json","packages/apps-registry/*/package.json","packages/examples/*/package.json"];async function gw($,b={}){let n=C$(b.workspaceRoot??process.cwd()),A=await IQ($,n,b.config),m=await $.glob({cwd:n,patterns:A,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=Nb(b.config),W=[];for(let w of m){let j=C$($.dirname(w)),B=s0(j);if(!B)continue;let S=await Pw($,$.join(n,w)),Q=$.basename(j),Z=$.join(n,j),X=y.requiredByKind?.[MQ(B)];if(!X)continue;let Y=$m(B,Q);W.push({workspaceRoot:n,relativePackageRoot:j,packageRoot:Z,packageName:typeof S.name==="string"?S.name:j,packageDirName:Q,description:typeof S.description==="string"?S.description:void 0,kind:B,target:X,canonicalDeclarationRelativePath:Y,canonicalDeclarationPath:$.join(Z,Y),indexPath:$.join(Z,"src/index.ts"),indexExportPath:bm(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function vb($,b={}){let n=await gw($,b),A=[];for(let m of n){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=RQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[CQ(j,m.canonicalDeclarationPath)]).find((Q)=>Q.specType!=="unknown")?.specType,w=W===m.target}A.push({...m,exists:y,matchesExpectedTarget:w,detectedSpecType:W})}return A}async function IQ($,b,n){let A=$.join(b,"package.json");if(await $.exists(A)){let m=await Pw($,A),y=EQ(m);if(y.length>0)return y.map((W)=>`${vw(W)}/package.json`)}if(n?.packages?.length)return n.packages.map((m)=>`${vw(m)}/package.json`);return xQ}function EQ($){if(Array.isArray($.workspaces))return $.workspaces.filter((n)=>typeof n==="string");let b=$.workspaces;if(Array.isArray(b?.packages))return b.packages.filter((n)=>typeof n==="string");return[]}function MQ($){return $==="appsRegistry"?"appsRegistry":$}function vw($){return $.replace(/\/+$/,"")}async function Pw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function Wm($){let{pkg:b,refs:n,owners:A,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:Fb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:Am(b.packageDirName),owners:A,tags:mm(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return TQ(b,n,y);case"integration":return DQ(b,n,y);case"app-config":return NQ(b,n,y);case"module-bundle":return rn({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:G$("module-bundle",b.packageDirName)});case"example":return In({key:y.key,version:y.version,description:y.description,title:y.title,domain:y.domain,owners:y.owners,tags:y.tags,stability:y.stability,packageName:b.packageName})}}function TQ($,b,n){let A=[jb("operations",b.operations),jb("events",b.events),jb("presentations",b.presentations),jb("experiments",b.experiments),jb("workflows",b.workflows),jb("dataViews",b.dataViews)].filter(Boolean);return`${$.packageName==="@contractspec/lib.contracts-spec"?"import { defineFeature } from './features';":"import { defineFeature } from '@contractspec/lib.contracts-spec/features';"}
|
|
1940
|
+
|
|
1941
|
+
export const ${G$("feature",$.packageDirName)} = defineFeature({
|
|
1942
|
+
meta: ${FQ(n)},
|
|
1943
|
+
${A.length>0?`${A.join(`
|
|
1944
|
+
`)}
|
|
1945
|
+
`:""}});
|
|
1946
|
+
`}function DQ($,b,n){let A=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1947
|
+
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1948
|
+
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1949
|
+
|
|
1950
|
+
const ${G$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1951
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1952
|
+
description: 'Managed configuration for ${$.packageName}.',
|
|
1953
|
+
fields: {},
|
|
1954
|
+
});
|
|
1955
|
+
|
|
1956
|
+
const ${G$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1957
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1958
|
+
description: 'Secret material for ${$.packageName}.',
|
|
1959
|
+
fields: {},
|
|
1960
|
+
});
|
|
1961
|
+
|
|
1962
|
+
export const ${G$("integration",$.packageDirName)} = defineIntegration({
|
|
1963
|
+
meta: {
|
|
1964
|
+
...${rw(n)},
|
|
1965
|
+
category: 'custom',
|
|
1966
|
+
},
|
|
1967
|
+
supportedModes: ['managed'],
|
|
1968
|
+
capabilities: {
|
|
1969
|
+
provides: [
|
|
1970
|
+
${A||" // Add capability refs here"}
|
|
1971
|
+
],
|
|
1972
|
+
},
|
|
1973
|
+
configSchema: { schema: ${G$("integration",$.packageDirName)}Config, example: {} },
|
|
1974
|
+
secretSchema: { schema: ${G$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1975
|
+
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1976
|
+
});
|
|
1977
|
+
`}function NQ($,b,n){let A=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
1978
|
+
`),m=kw(b.workflows),y=kw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1979
|
+
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1980
|
+
|
|
1981
|
+
export const ${G$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1982
|
+
meta: {
|
|
1983
|
+
...${rw(n)},
|
|
1984
|
+
appId: '${Q$($.packageDirName)}',
|
|
1985
|
+
},
|
|
1986
|
+
capabilities: {
|
|
1987
|
+
enabled: [
|
|
1988
|
+
${W||" // Add capability refs here"}
|
|
1989
|
+
],
|
|
1990
|
+
},${A?`
|
|
1991
|
+
features: {
|
|
1992
|
+
include: [
|
|
1993
|
+
${A}
|
|
1994
|
+
],
|
|
1995
|
+
},`:""}${y?`
|
|
1996
|
+
dataViews: {
|
|
1997
|
+
${y}
|
|
1998
|
+
},`:""}${m?`
|
|
1999
|
+
workflows: {
|
|
2000
|
+
${m}
|
|
2001
|
+
},`:""}
|
|
2002
|
+
});
|
|
2003
|
+
`}function jb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2004
|
+
${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
2005
|
+
`)}
|
|
2006
|
+
],`}function kw($){return $.map((b,n)=>` ${n===0?"primary":`item${n+1}`}: {
|
|
2007
|
+
key: '${b.key}',
|
|
2008
|
+
version: '${b.version}',
|
|
2009
|
+
},`).join(`
|
|
2010
|
+
`)}function FQ($){return`{
|
|
2011
|
+
key: '${$.key}',
|
|
2012
|
+
version: '${$.version}',
|
|
2013
|
+
title: '${Q$($.title)}',
|
|
2014
|
+
description: '${Q$($.description)}',
|
|
2015
|
+
domain: '${Q$($.domain)}',
|
|
2016
|
+
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2017
|
+
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
|
+
stability: '${$.stability}',
|
|
2019
|
+
}`}function rw($){return`{ key: '${$.key}', version: '${$.version}', title: '${Q$($.title)}', description: '${Q$($.description)}', domain: '${Q$($.domain)}', owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}], tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}], stability: '${$.stability}' }`}function Q$($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{scanAllSpecsFromSource as vQ}from"@contractspec/module.workspace";var gQ={feature:["@contractspec/lib.contracts-spec"],integration:["@contractspec/lib.contracts-integrations","@contractspec/lib.schema"],"app-config":["@contractspec/lib.contracts-spec"],"module-bundle":["@contractspec/lib.surface-runtime"],example:["@contractspec/lib.contracts-spec"]};function PQ($){return $.packageName!=="@contractspec/lib.schema"}function kQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function rQ($,b={}){let n=await vb($,b),A=[],m=[],y=[];for(let W of n){if(!b.force&&W.exists&&W.matchesExpectedTarget){y.push({...W,action:"skipped",declarationCreated:!1,indexUpdated:!1,packageJsonUpdated:!1,dependenciesUpdated:[]});continue}let w=await fQ($,W),j=Wm({pkg:W,refs:w,owners:b.config?.defaultOwners?.length?b.config.defaultOwners:["@contractspec-core"],defaultTags:b.config?.defaultTags??[]});if(!b.dryRun)await $.writeFile(W.canonicalDeclarationPath,`${j.trimEnd()}
|
|
2020
|
+
`);let B=await cQ($,W,b.dryRun,PQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await hQ($,W,b.dryRun);if(W.exists)m.push(W.canonicalDeclarationPath);else A.push(W.canonicalDeclarationPath);if(B)m.push(W.indexPath);if(Q)m.push($.join(W.packageRoot,"package.json"));y.push({...W,action:W.exists?"updated":"created",declarationCreated:!W.exists,indexUpdated:B,packageJsonUpdated:Q,dependenciesUpdated:S})}return{packages:y,createdFiles:A,updatedFiles:m}}function wm($,b){return{allowlisted:ym(b,$.relativePackageRoot,$.packageName),message:$.exists?`Package declaration at ${$.canonicalDeclarationRelativePath} must be a ${$.target} spec.`:`Package ${$.relativePackageRoot} is missing its canonical ${$.target} declaration at ${$.canonicalDeclarationRelativePath}.`}}async function fQ($,b){let n=await $.glob({cwd:b.packageRoot,patterns:["src/**/*.{ts,tsx}"],absolute:!1,ignore:["**/dist/**","**/*.test.*","**/*.spec.*","**/*.stories.*"]}),A={operations:[],events:[],presentations:[],experiments:[],workflows:[],dataViews:[],capabilities:[],features:[]};for(let m of n){if(m===b.canonicalDeclarationRelativePath)continue;let y=await $.readFile($.join(b.packageRoot,m)),W=vQ(y,m);for(let w of W){if(!w.key||!w.version)continue;let j={key:w.key,version:w.version};switch(w.specType){case"operation":x$(A.operations,j);break;case"event":x$(A.events,j);break;case"presentation":x$(A.presentations,j);break;case"experiment":x$(A.experiments,j);break;case"workflow":x$(A.workflows,j);break;case"data-view":x$(A.dataViews,j);break;case"capability":x$(A.capabilities,j);break;case"feature":x$(A.features,j);break}}}return A}function x$($,b){if(!$.some((n)=>n.key===b.key&&n.version===b.version))$.push(b)}async function cQ($,b,n=!1,A=!0){if(!A)return!1;let m=`export * from "${b.indexExportPath}";`,y=new RegExp(`export \\* from ['"]${b.indexExportPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"];`),W=await $.exists(b.indexPath)?await $.readFile(b.indexPath):"";if(y.test(W))return!1;if(W=`${W.trimEnd()}
|
|
2021
|
+
${m}
|
|
2022
|
+
`.trimStart(),!n)await $.writeFile(b.indexPath,W);return!0}async function hQ($,b,n=!1){let A=$.join(b.packageRoot,"package.json"),m=JSON.parse(await $.readFile(A)),y=fw(m,"dependencies"),W=[],w=!1;for(let B of gQ[b.target]){if(!kQ(b,B)){if(B in y)delete y[B],w=!0;continue}if(typeof y[B]!=="string")y[B]="workspace:*",W.push(B)}let j=fw(m,"exports");if(w=w||W.length>0,typeof j["."]!=="string")j["."]="./src/index.ts",w=!0;if(w&&!n)await $.writeFile(A,`${JSON.stringify(m,null,"\t")}
|
|
2023
|
+
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function fw($,b){let n=$[b];if(typeof n==="object"&&n!==null&&!Array.isArray(n))return n;let A={};return $[b]=A,A}var uQ=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,oQ=/@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?)?['"]/,iQ=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,tQ=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,lQ=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,pQ=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,aQ=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function wA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function eQ($,b){let n=$.replaceAll("\\","/"),A=new Set(["contracts","features",...wA(b?.conventions?.operations),...wA(b?.conventions?.events),...wA(b?.conventions?.presentations),...wA(b?.conventions?.forms)]);return n.split("/").some((m)=>A.has(m))}function sQ($,b,n){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||lQ.test(A)||tQ.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(b.has(A))return!1;if(eQ(A,n))return!1;return uQ.test(A)}function hw($){return $.replaceAll("\\","/").match(pQ)?.[1]??null}function $4($){let b=$.split(`
|
|
2024
|
+
`).map((n)=>n.trim()).filter((n)=>n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")&&!n.startsWith("*/"));return b.length>0&&b.every((n)=>n.startsWith("import ")||n.startsWith("export *")||n.startsWith("export {")||n.startsWith("export type {")||n==="'use client';"||n==='"use client";'||n==="'use server';"||n==='"use server";')}function b4($){if(!$)return WA;let b=dQ.safeParse($),n=b.success?b.data:{};return{...WA,...n,conventions:{...WA.conventions,...n.conventions??{}},ci:{...WA.ci,...n.ci??{}}}}async function jm($,b){let{fs:n,logger:A}=$,m=[],y=b.config?b4(b.config):await P(n),W=Nb(y),w=await j$({fs:n},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>hw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await n.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!sQ(Q,j,y))continue;try{let Z=await n.readFile(Q);if($4(Z))continue;let X=hw(Q);if(!(X!==null&&aQ.test(X)&&B.has(X))&&!iQ.test(Z))continue;if(oQ.test(Z))continue;m.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:Q})}catch(Z){A.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await vb(n,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=wm(Z,W.allowMissing??[]);m.push({ruleId:"policy-package-declaration",severity:X.allowlisted||W.severity==="warning"?"warning":"error",message:X.message,category:"policy",file:Z.canonicalDeclarationPath,context:{allowlisted:X.allowlisted,expectedTarget:Z.target,packageName:Z.packageName,packageRoot:Z.relativePackageRoot}})}}return m}import{validateSpecStructure as n4}from"@contractspec/module.workspace";async function Bm($){let b=[];for(let n of $){let A=n4(n);for(let m of A.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:m,category:"structure",file:n.filePath});for(let m of A.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:m,category:"structure",file:n.filePath})}return b}async function Sm($){let b=[],n=new Map,A=new Map;for(let m of $){if(!m.key||!m.version)continue;if(m.specType==="test-spec"){let y=`${m.key}.v${m.version}`;n.set(y,{key:m.key,version:m.version,file:m.filePath,type:"test-spec"})}if(m.testRefs&&m.testRefs.length>0){if(!A.has(m.filePath))A.set(m.filePath,[]);A.get(m.filePath)?.push({key:m.key,version:m.version,testRefs:m.testRefs})}}for(let[m,y]of A)for(let W of y){if(!W.testRefs)continue;let w=t0(m,W.key,W.version,W.testRefs,n,{treatMissingAsError:!0});for(let j of w.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:j,category:"test-refs",file:m,context:{specKey:W.key,specVersion:W.version,missingTests:w.missingTests}})}return b}$$();async function Qm($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkTests:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"test-missing",severity:"warning",message:w,category:"tests",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"test-warning",severity:"warning",message:w,category:"tests",file:y.filePath})}return A}function e($,b,n){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"},m=b.filter((w)=>w.severity==="error").length,y=b.filter((w)=>w.severity==="warning").length,W=b.filter((w)=>w.severity==="note").length;return{category:$,label:A[$],errors:m,warnings:y,notes:W,passed:m===0,durationMs:n}}async function dw($){try{if(!await $.exists(".git/HEAD"))return{};let n=await $.readFile(".git/HEAD"),A=n.match(/^ref: (.+)$/m);if(A){let y=A[1]?.replace("refs/heads/",""),W=`.git/${A[1]}`;if(await $.exists(W))return{commitSha:(await $.readFile(W)).trim(),branch:y};return{branch:y}}return{commitSha:n.trim()}}catch{return{}}}function uw($){let b=$.config?.ci?.checks,n=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)n.push("handlers");if($.checkTests)n.push("tests");if($.implementation)n.push("implementation");if($.checkDrift)n.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return n.filter((A)=>!$.skip?.includes(A));return n}async function bK($,b={}){let n=Date.now(),{fs:A,logger:m}=$,y=[],W=[],w=uw(b);m.info("Starting CI checks...",{checks:w});let j=await P(A),B=await cn($,{config:j,pattern:b.pattern});if(w.includes("structure")){let V=Date.now(),O=await Bm(B);y.push(...O),W.push(e("structure",O,Date.now()-V))}if(w.includes("integrity")){let V=Date.now(),O=await p0($,b);y.push(...O),W.push(e("integrity",O,Date.now()-V))}if(w.includes("deps")){let V=Date.now(),O=await x0($,b);y.push(...O),W.push(e("deps",O,Date.now()-V))}if(w.includes("doctor")){let V=Date.now(),O=await f0($,b);y.push(...O),W.push(e("doctor",O,Date.now()-V))}if(w.includes("docs")){let V=Date.now(),O=await I0($,b);y.push(...O),W.push(e("docs",O,Date.now()-V))}if(w.includes("policy")){let V=Date.now(),O=await jm($,b);y.push(...O),W.push(e("policy",O,Date.now()-V))}if(w.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await o0($,B);y.push(...O),W.push(e("handlers",O,Date.now()-V))}if(w.includes("tests")||b.checkTests){let V=Date.now(),O=await Qm($,B);y.push(...O),W.push(e("tests",O,Date.now()-V))}if(w.includes("test-refs")){let V=Date.now(),O=await Sm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-V))}if(w.includes("coverage")){let V=Date.now(),O=await C0($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-V))}if(w.includes("implementation")){let V=Date.now(),O=await i0($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-V))}if(w.includes("layers")){let V=Date.now(),O=await a0($,b);y.push(...O),W.push(e("layers",O,Date.now()-V))}if(w.includes("drift")){let V=Date.now(),O=await u0($,b);y.push(...O),W.push(e("drift",O,Date.now()-V))}let S=y.filter((V)=>V.severity==="error").length,Q=y.filter((V)=>V.severity==="warning").length,Z=y.filter((V)=>V.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await dw(A),G={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:G.durationMs}),G}var AK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],mK={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 BK($,b={}){let{fs:n,logger:A}=$,m=(b.outputDir??"./src").replace(/\\/g,"/"),y=["generated/**","dist/**",".turbo/**"],W=[`${m}/handlers/**/*.handler.ts`,`${m}/handlers/**/*.handler.test.ts`,`${m}/components/**/*.tsx`,`${m}/components/**/*.test.tsx`,`${m}/forms/**/*.form.tsx`,`${m}/forms/**/*.form.test.tsx`,`${m}/**/*.runner.ts`,`${m}/**/*.renderer.tsx`],w=b.generatedOnly?[...y,...W]:[...y,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...W],j=await n.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await n.stat(Q),X=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&X<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)A.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await n.remove(Q),A.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}}$$();var Vj={};f(Vj,{writeReviewPacket:()=>Rm,writeDecisionEnvelope:()=>db,withBranch:()=>o$,verifyConnectMutation:()=>B6,resolveWorkspace:()=>i,resolveStoragePaths:()=>X$,replayConnectDecision:()=>f4,persistLatestArtifacts:()=>zm,persistDecisionArtifacts:()=>hb,normalizeEvalInput:()=>T4,matchConfiguredPath:()=>gb,loadStoredDecision:()=>ub,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>c4,isReviewCommand:()=>Zm,isDeniedCommand:()=>Xm,isAllowedCommand:()=>jA,initConnectWorkspace:()=>g4,inferSurfaces:()=>rb,evaluateConnectDecision:()=>E4,ensureStorage:()=>cb,defaultActor:()=>kb,decisionArtifactRefs:()=>Sb,createConnectControlPlaneRuntime:()=>e4,connectVerdictToPolicy:()=>I$,configuredThreshold:()=>u$,compileConnectPlanPacket:()=>ob,buildConnectContextPack:()=>fb,assessConnectPolicy:()=>Pb,assertConnectEnabled:()=>A$,artifactRef:()=>_$,appendAuditRecord:()=>Lm,analyzeConnectImpact:()=>i$,CONTROL_PLANE_TRACE_GET_REF:()=>BA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>SA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>qm,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Hm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>U$,AGENT_APPROVALS_REF:()=>QA,ACP_TERMINAL_EXEC_REF:()=>W4,ACP_FS_ACCESS_REF:()=>y4});import A4 from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function gb($,b,n){if(!n||n.length===0)return!1;let A=b.replaceAll("\\","/");return A4.isMatch(A,n,{contains:!0})}function u$($,b,n){return $.config.connect?.policy?.reviewThresholds?.[b]??n}function jA($,b){return Ym($.config.connect?.commands?.allow,b)}function Zm($,b){return Ym($.config.connect?.commands?.review,b)}function Xm($,b){return Ym($.config.connect?.commands?.deny,b)}function Ym($,b){if(!$||$.length===0)return!1;return $.some((n)=>b===n||b.startsWith(`${n} `))}function iw($,b){if(b.length===0)return{state:"none"};for(let A of b)if(Xm($,A))return{commandMatch:A,state:"deny"};for(let A of b)if(Zm($,A))return{commandMatch:A,state:"review"};if(b.every((A)=>jA($,A)))return{state:"allow"};let n=b.find(m4);if(n)return{commandMatch:n,state:"destructive"};return{commandMatch:b.find((A)=>!jA($,A)),state:"unknown"}}function m4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return ow(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return ow(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function ow($,b){return b.every((n)=>$.includes(n)||$.includes(n.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Hm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},BA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},SA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},U$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},y4={key:"acp.fs.access",version:"1.0.0",kind:"command"},W4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},QA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Pb($,b){let n=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.immutablePaths)),A=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=iw($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=w4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(n),protectedPath:Boolean(A),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=j4({breakingChange:b.impactAnalysis.breakingChange,commandMatch:y,commandState:W,contractDrift:j,protectedPath:A,unknownPaths:b.impactAnalysis.unknownPaths}),Q=I$(B);return{commandMatch:y,commandState:W,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:m,immutablePath:n,protectedPath:A,requiredApprovals:Q.requiresApproval?[{capability:U$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function I$($){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 w4($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(u$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(u$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(u$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(u$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(u$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(B4)[0]??"permit"}function j4($){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 B4($,b){return tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as x4}from"crypto";var sw={};f(sw,{formatPrComment:()=>lw,formatMinimalComment:()=>Om,formatJson:()=>aw,formatCheckRun:()=>pw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>G4});function lw($,b={template:"detailed"}){let n=[];if(n.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),n.push(""),$.hasBreaking)n.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)n.push("⚠️ **Contract changed (non-breaking)**");else n.push("✅ **No contract impact**");if(n.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(n.push("### Summary"),n.push(""),n.push("| Type | Count |"),n.push("|------|-------|"),$.summary.breaking>0)n.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)n.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)n.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)n.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)n.push(`| ➖ Removed | ${$.summary.removed} |`);n.push("")}if(b.template==="detailed"&&$.deltas.length>0){n.push("### Changes"),n.push("");let A=$.deltas.filter((y)=>y.severity==="breaking"),m=$.deltas.filter((y)=>y.severity==="non_breaking");if(A.length>0){n.push("#### \uD83D\uDD34 Breaking Changes"),n.push("");for(let y of A)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}if(m.length>0){n.push("#### \uD83D\uDFE1 Non-breaking Changes"),n.push("");for(let y of m)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}}if($.addedSpecs.length>0){n.push("### Added Specs"),n.push("");for(let A of $.addedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if($.removedSpecs.length>0){n.push("### Removed Specs"),n.push("");for(let A of $.removedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if(b.drift)if(b.drift.hasDrift){n.push("### ⚠️ Drift Detected"),n.push(""),n.push("The following generated files are out of sync with their specs:"),n.push("");for(let A of b.drift.files)n.push(`- \`${A}\``);n.push(""),n.push("Run `contractspec generate` to regenerate artifacts."),n.push("")}else n.push("### ✅ No Drift Detected"),n.push("");return n.push("---"),n.push(`*Generated by ContractSpec at ${$.timestamp}*`),n.join(`
|
|
2025
|
+
`)}function Om($){if($.hasBreaking)return`❌ **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`⚠️ **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"✅ **No contract impact**"}function pw($,b,n={}){let A=n.key??"ContractSpec Impact",m=n.failOnBreaking??!0,y,W;if($.hasBreaking)y=m?"failure":"neutral",W=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)y="success",W=`Non-breaking changes (${$.summary.nonBreaking})`;else y="success",W="No contract impact";let w=Om($);return{name:A,headSha:b,conclusion:y,title:W,summary:w,annotations:$.deltas.filter((j)=>j.severity==="breaking").slice(0,50).map((j)=>({path:j.path,startLine:1,endLine:1,annotationLevel:"failure",message:j.description,title:`Breaking: ${j.rule}`}))}}function aw($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((n)=>({type:n.rule,path:n.specKey,summary:n.description,severity:n.severity==="breaking"?"breaking":n.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as S4,computeIoDiff as Q4,generateSnapshot as ew}from"@contractspec/module.workspace";async function K$($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting impact detection...",{baseline:b.baseline});let w=(await n.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${w.length} spec files`);let j=await Z4(n,w,y),B=ew(j),S;if(b.baseline){let X=await X4(n,A,w,b.baseline,y);S=ew(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=Y4(S.specs,B.specs),Z=S4(S.specs,B.specs,Q);return m.info("Impact detection complete",{status:Z.status,breaking:Z.summary.breaking,nonBreaking:Z.summary.nonBreaking}),{...Z,workspaceRoot:y,specsAnalyzed:w.length,baseRef:b.baseline}}async function Z4($,b,n){let A=[];for(let m of b){let y=await $.readFile(m);A.push({path:m,content:y})}return A}async function X4($,b,n,A,m){let y=[];for(let W of n)try{let w=await b.showFile(A,W);y.push({path:W,content:w})}catch{}return y}function Y4($,b){let n=[],A=new Map($.map((y)=>[`${y.key}@${y.version}`,y])),m=new Map(b.map((y)=>[`${y.key}@${y.version}`,y]));for(let[y,W]of m){let w=A.get(y);if(w&&W.type==="operation"&&w.type==="operation"){let j=Q4(w.io,W.io);n.push(...j)}}return n}var G4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1931
2026
|
# Contract Impact Detection
|
|
1932
2027
|
|
|
1933
2028
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -1973,49 +2068,49 @@ The system consists of three layers:
|
|
|
1973
2068
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1974
2069
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1975
2070
|
3. **Integrations**: CLI command + GitHub Action
|
|
1976
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
1977
|
-
`;await $.writeFile(b.auditFile,`${
|
|
1978
|
-
`)}async function
|
|
1979
|
-
`);if(
|
|
1980
|
-
`)?
|
|
2071
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as bj,readFileSync as nj}from"node:fs";import{basename as H4,join as Vm,resolve as q4}from"node:path";import{ContractsrcSchema as O4,DEFAULT_CONTRACTSRC as V4}from"@contractspec/lib.contracts-spec/workspace-config";function i($={}){let b=q4($.cwd??process.cwd()),n=$.workspaceRoot??I(b),A=$.packageRoot??c(b),m=$.config??J4(n,A),y=U4(A,n);return{cwd:b,workspaceRoot:n,packageRoot:A,config:m,repoId:y,branch:"unknown"}}function o$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function kb($,b){return b??{id:`cli:${$}`,type:"human"}}function rb($){let b=new Set;for(let n of $){if(n.includes("/cli-")||n.includes("/apps/cli-"))b.add("cli");if(n.includes("/contracts-spec/")||n.includes("/specs/"))b.add("contract");if(n.includes("/components/")||n.includes("/ui/")||n.endsWith(".tsx")||n.endsWith(".jsx"))b.add("ui");if(n.includes("/integrations/")||n.includes("/provider"))b.add("integration");if(n.includes("/libs/")||n.includes("/shared/")||n.includes("/utils/"))b.add("library");if(n.includes("/modules/")||n.includes("/bundles/")||n.includes("/examples/"))b.add("solution");if(n.includes("/runtime/"))b.add("runtime");if(n.includes("/harness"))b.add("harness");if(n.includes("/ai-agent/"))b.add("agent");if(n.includes("/knowledge/"))b.add("knowledge");if(n.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function J4($,b){let n={...V4};if($!==b)n=$j(n,Vm($,".contractsrc.json"));return $j(n,Vm(b,".contractsrc.json"))}function $j($,b){if(!bj(b))return $;try{let n=nj(b,"utf-8"),A=JSON.parse(n),m=O4.safeParse(A);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function U4($,b){let n=Vm($,"package.json");if(bj(n))try{let A=JSON.parse(nj(n,"utf-8"));if(A.name)return A.name}catch{}return H4(b)}async function i$($,b){let n=await j$({fs:$.fs},{config:b.workspace.config}),A=new Map(n.filter((j)=>typeof j.key==="string").map((j)=>[j.key,j])),m=b.touchedPaths.map((j)=>K4($.fs,b.workspace,j,n,A)),y=b.baseline!=null?await K$({...$,logger:$.logger??mj},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,W=await _4($,b.workspace,b.touchedPaths),w=_m([...m.flatMap((j)=>j.contracts),...(y?.deltas??[]).map((j)=>({key:j.specKey,version:j.specVersion,kind:j.specType==="event"?"event":"command"}))]);return{breakingChange:y?.hasBreaking===!0,driftFiles:W,impactResult:y,impactedContracts:w,pathImpacts:m,unknownPaths:m.filter((j)=>j.contracts.length===0).map((j)=>j.path)}}function K4($,b,n,A,m){let y=$.resolve(b.workspaceRoot,n),W=Km(n),w=A.map((Y)=>{let G=m$($.relative(b.workspaceRoot,Y.filePath));return{score:R4(n,W,G,Y.key),spec:Y}}).filter((Y)=>Y.score>=45).sort((Y,G)=>G.score-Y.score).slice(0,3),j=A.find((Y)=>Y.filePath===y),B=j?[{score:100,spec:j}]:w,S=B.filter((Y)=>typeof Y.spec.key==="string").map((Y)=>Um(Y.spec.key,Y.spec.version,Y.spec.kind)),Q=B.flatMap((Y)=>[...Y.spec.emittedEvents??[],...Y.spec.policyRefs??[],...Y.spec.testRefs??[]].map((G)=>m.get(G.key)).filter(Boolean).map((G)=>Um(G.key,G.version,G.kind))),Z=_m([...S,...Q]),X=_m([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((Y)=>Y.spec.policyRefs??[]).map((Y)=>Um(Y.key,Y.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:n,policies:X,reasons:B.map((Y)=>`${Y.spec.key??Y.spec.filePath} matched with score ${Y.score}`),surfaces:rb([n])}}async function _4($,b,n){let A=z4($.fs,b,n),m=await Promise.all(A.map(async(y)=>{let W=$.fs.resolve(b.packageRoot,y.comparisonRoot),w=await bA({...$,logger:$.logger??mj},b.workspaceRoot,W,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),j=y.filterPrefix&&y.filterPrefix!==y.comparisonRoot?m$($.fs.relative(y.comparisonRoot,y.filterPrefix)):void 0;return w.files.filter((B)=>j?m$(B)===j||m$(B).startsWith(`${j}/`):!0).map((B)=>m$($.fs.join(y.comparisonRoot,B)))}));return[...new Set(m.flat())].sort()}function z4($,b,n){let A=(b.config.connect?.policy?.generatedPaths??[]).map(C4).filter(Boolean),m=b.config.outputDir&&b.config.outputDir!=="./src"?m$(b.config.outputDir):void 0,y=new Map;for(let W of n){let w=m$(W);if(m&&w.startsWith(m))y.set(m,{comparisonRoot:m});for(let j of A)if(w.startsWith(j)){let B=L4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function L4($,b,n){if(b&&n.startsWith(b))return b;return $.basename(n)==="docs"?m$($.dirname(n)):n}function R4($,b,n,A){if(m$($)===m$(n))return 100;let m=Km(n),y=Km(A??""),W=Aj($)===Aj(n)?40:0,w=Jm($.split("/"),n.split("/"),5),j=Jm(b,m,5),B=Jm(b,y,4);return W+w+j+B}function Jm($,b,n){let A=new Set(b);return $.filter((m)=>A.has(m)).length*n}function Km($){return m$($).split(/[\/._-]+/).filter(Boolean)}function Aj($){return m$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function C4($){return m$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function m$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Um($,b,n){return{key:$,version:String(b??"1.0.0"),kind:n==="query"||n==="event"||n==="policy"||n==="capability"?n:"command"}}function _m($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var mj={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function fb($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let A=kb(b.taskId,b.actor),m=await I4($,n.workspaceRoot,b),y=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),W=n.config.connect?.canonPacks??[];return{id:`connect.ctx_${x4()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:A,knowledge:W.map((w)=>({spaceKey:w.ref,category:"canonical",trustLevel:w.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:y.impactedContracts,affectedSurfaces:y.pathImpacts.length>0?[...new Set(y.pathImpacts.flatMap((w)=>w.surfaces))].sort():rb(m),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...W.map((w)=>({key:w.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...W.map((w)=>({kind:"canon-pack",ref:w.ref}))],acceptanceChecks:n.config.connect?.policy?.smokeChecks??[]}}async function I4($,b,n){let A=n.paths??[];if(A.length>0)return A.map((y)=>yj($.fs,b,y));if(!n.baseline)return[];return(await $.git.diffFiles(n.baseline)).map((y)=>yj($.fs,b,y))}function yj($,b,n){let A=$.resolve(b,n);return $.relative(b,A).replaceAll("\\","/")}import{resolve as t$}from"node:path";function X$($){let b=$.config.connect?.storage,n=t$($.packageRoot,b?.root??".contractspec/connect");return{root:n,contextPack:t$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:t$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:t$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:t$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:t$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:t$(n,"decisions")}}async function cb($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function zm($,b,n){if(n.contextPack)await Z$($,b.contextPack,n.contextPack);if(n.planPacket)await Z$($,b.planPacket,n.planPacket);if(n.patchVerdict)await Z$($,b.patchVerdict,n.patchVerdict)}async function hb($,b,n,A){let m=$.join(b.decisionsDir,n);if(await $.mkdir(m),A.contextPack)await Z$($,$.join(m,"context-pack.json"),A.contextPack);if(A.planPacket)await Z$($,$.join(m,"plan-packet.json"),A.planPacket);if(A.patchVerdict)await Z$($,$.join(m,"patch-verdict.json"),A.patchVerdict);if(A.reviewPacket)await Z$($,$.join(m,"review-packet.json"),A.reviewPacket);if(A.evaluationResult!==void 0)await Z$($,$.join(m,"evaluation-result.json"),A.evaluationResult);if(A.replayBundle!==void 0)await Z$($,$.join(m,"replay-bundle.json"),A.replayBundle);return m}async function db($,b,n,A){let m=$.join(b.decisionsDir,n,"decision-envelope.json");return await Z$($,m,A),m}async function Lm($,b,n){let A=await Wj($,b.auditFile)??"",m=`${JSON.stringify(n)}
|
|
2072
|
+
`;await $.writeFile(b.auditFile,`${A}${m}`)}async function Rm($,b,n){let A=$.join(b.reviewPacketsDir,`${n.id}.json`);return await Z$($,A,n),A}async function ub($,b,n){let A=$.join(b.decisionsDir,n);return{historyDir:A,contextPack:await Bb($,$.join(A,"context-pack.json")),planPacket:await Bb($,$.join(A,"plan-packet.json")),patchVerdict:await Bb($,$.join(A,"patch-verdict.json")),reviewPacket:await Bb($,$.join(A,"review-packet.json")),envelope:await Bb($,$.join(A,"decision-envelope.json"))}}async function Cm($,b){let n=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),A=[];for(let m of n){let y=await Bb($,m);if(y)A.push({filePath:m,packet:y})}return A.sort((m,y)=>m.packet.id.localeCompare(y.packet.id))}function _$($,b,n){return $.relative(b.packageRoot,$.resolve(n)).replaceAll("\\","/")}function Sb($,b,n,A,m){let y=$.join(n.decisionsDir,A);return{contextPack:_$($,b,$.join(y,"context-pack.json")),planPacket:_$($,b,$.join(y,"plan-packet.json")),patchVerdict:_$($,b,$.join(y,"patch-verdict.json")),reviewPacket:m.reviewPacket?_$($,b,$.join(y,"review-packet.json")):void 0,evaluationResult:m.evaluationResult?_$($,b,$.join(y,"evaluation-result.json")):void 0,replayBundle:m.replayBundle?_$($,b,$.join(y,"replay-bundle.json")):void 0}}async function Z$($,b,n){await $.writeFile(b,`${JSON.stringify(n,null,2)}
|
|
2073
|
+
`)}async function Bb($,b){let n=await Wj($,b);if(!n)return;try{return JSON.parse(n)}catch{return}}async function Wj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function E4($,b,n){let A=i(b);if(A$(A),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let m=X$(A),y=await ub($.fs,m,b.decisionId),W=M4(A,y),w=b.scenarioKey?await n.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:W}):await n.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:W}),j=await hb($.fs,m,b.decisionId,{evaluationResult:w}),B=await $.fs.exists($.fs.join(j,"replay-bundle.json")),S={artifacts:Sb($.fs,A,m,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(y.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:y.envelope?.createdAt??new Date().toISOString(),runtimeLink:y.envelope?.runtimeLink,taskId:y.contextPack?.taskId??b.decisionId,verdict:y.patchVerdict?.verdict??"permit"};return await db($.fs,m,b.decisionId,S),{historyDir:j,evaluation:w,context:W}}function M4($,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 T4($){return $}import{DEFAULT_CONTRACTSRC as v4}from"@contractspec/lib.contracts-spec/workspace-config";async function ZA($,b){let n=$.join(b.root,".gitignore"),A=b.behavior??"auto",m=Bj(b.patterns);if(m.length===0||A==="skip")return{target:"gitignore",filePath:n,action:"skipped",message:A==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(A==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${n}?`,!0))return{target:"gitignore",filePath:n,action:"skipped",message:"User skipped ContractSpec gitignore update"};let y=await $.exists(n),W=y?await $.readFile(n):"",w=D4(W,m);if(jj(W)===jj(w))return{target:"gitignore",filePath:n,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(n,w),{target:"gitignore",filePath:n,action:y?"merged":"created",message:y?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(y){return{target:"gitignore",filePath:n,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}function D4($,b){let n=N4(b),A=F4(),m=$.replace(/\r\n/g,`
|
|
2074
|
+
`);if(A.test(m))return m.replace(A,n);if(m.trim().length===0)return n;return`${m.endsWith(`
|
|
2075
|
+
`)?m:`${m}
|
|
1981
2076
|
`}
|
|
1982
|
-
${
|
|
2077
|
+
${n}`}function N4($){return`# contractspec:init:gitignore:start
|
|
1983
2078
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1984
|
-
${
|
|
2079
|
+
${Bj($).join(`
|
|
1985
2080
|
`)}
|
|
1986
2081
|
# contractspec:init:gitignore:end
|
|
1987
|
-
`}function
|
|
1988
|
-
`).trimEnd()}function Dj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function rQ($,b={}){let A=o(b),m=b.scope==="package"?A.packageRoot:A.workspaceRoot,n=$.join(m,".contractsrc.json"),W={connect:{...PQ.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}=fQ(b.candidate),W=await Tb($,{...b,paths:n}),w=Mb(b.taskId,b.actor),j=hQ(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:cQ(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 fQ($){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 hQ($,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 cQ($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function dQ($,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 uQ($,b={}){let A=o(b);return A$(A),mn($.fs,Q$(A))}import{buildChannelPlanTrace as oQ,compileChannelPlan as iQ,finalizeChannelPlan as lQ,replayExecutionTrace as tQ,resolveChannelExecutionActor as pQ}from"@contractspec/integration.runtime/channel";import{createHash as aQ}from"crypto";var kb="connect.local",eQ="connect.runtime-link.v1",sQ="connect.adapter.v1",$4="connect-control-plane-bridge";function b4($){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:W4(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 A4($.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=pQ(B,{actorId:W.actor.id,actorType:W.actor.type,capabilityGrants:n4(n.verdict),capabilitySource:"connect",sessionId:W.actor.sessionId}),G=iQ({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:j}),X=lQ({plan:G,decision:m4(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:$4,promptVersion:eQ,policyVersion:sQ,toolTrace:oQ(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?tQ(A):null}}}async function A4($,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 m4($){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 n4($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function W4($,b){return`${$} [${b.tool}]`}function w4($){return aQ("sha256").update($).digest("hex")}function Fj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as Q4}from"crypto";async function vj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=j4(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"?y4(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 j4($){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 y4($){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 B4}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_${B4()}`,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:S4(w),reviewPacketRef:j,replay:{traceQuery:pA,policyExplain:aA}}}function S4($){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 Z4($,b,A={}){let m=o(b);A$(m),m=f$(m,await $.git.currentBranch());let n=`connect.dec_${Q4()}`,W=(A.now??(()=>new Date))().toISOString(),w=Q$(m);await Db($.fs,w);let{contextPack:j,planPacket:y}=await gb($,{...b,candidate:Y4(b)}),B=H4(b),S=await h$($,{baseline:b.baseline,touchedPaths:B,workspace:m}),Q=await q4(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=G4(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 G4($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return X4($.verdict,b)}function X4($,b){if(!b)return $;return hj($)<=hj(b)?$:b}function hj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Y4($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function H4($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function q4($,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 v_($){return new uj($)}import{scanSpecSource as C4}from"@contractspec/module.workspace";function oj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function h_($,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=C4(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 I4}from"@contractspec/module.workspace";async function u_($,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=I4(j,$,y,B,{breakingOnly:m.breakingOnly});return{spec1:$,spec2:B,differences:S}}s();import{openApiForRegistry as E4}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Bn}from"@contractspec/lib.contracts-spec/operations";async function M4($,b){let{fs:A,logger:m}=b,{registryPath:n,outputPath:W="./openapi.json"}=$;m.info("Loading registry...",{registryPath:n});let w=await x4(n,A);m.info("Generating OpenAPI document...");let j=E4(w,{title:$.title,version:$.version,description:$.description,servers:$.servers}),y=JSON.stringify(j,null,2)+`
|
|
1989
|
-
`,B=
|
|
2082
|
+
`}function F4(){return new RegExp(`${wj("# contractspec:init:gitignore:start")}[\\s\\S]*?${wj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function wj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jj($){return $.replace(/\r\n/g,`
|
|
2083
|
+
`).trimEnd()}function Bj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function g4($,b={}){let n=i(b),A=b.scope==="package"?n.packageRoot:n.workspaceRoot,m=$.join(A,".contractsrc.json"),y={connect:{...v4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=b$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,N(S)),W="merged"}else await $.writeFile(m,N(y));let w=X$(i({...b,workspaceRoot:A,packageRoot:A}));await cb($,w);let j=await ZA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ib.connect,Ib.verificationCache],prompts:b.prompts,root:n.workspaceRoot});return{configPath:m,targetRoot:A,action:W,gitignore:j}}import{randomUUID as XA}from"crypto";async function ob($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let{commands:A,touchedPaths:m}=P4(b.candidate),y=await fb($,{...b,paths:m}),W=kb(b.taskId,b.actor),w=k4(b.candidate.steps,b.candidate),j=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),B=Pb(n,{commands:A,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${XA()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:n.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:r4(m.length,A.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:Hm,planVerify:qm,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function P4($){let b=new Set($.touchedPaths??[]),n=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let m of A.paths??[])b.add(m);for(let m of A.commands??[])n.add(m)}return{commands:[...n],touchedPaths:[...b]}}function k4($,b){if(!$||$.length===0)return[{id:`step_${XA()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((n)=>typeof n==="string"?{id:`step_${XA()}`,summary:n}:{id:`step_${XA()}`,summary:n.summary,paths:n.paths,commands:n.commands,contractRefs:n.contractRefs})}function r4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function f4($,b,n){let A=i(b);A$(A);let m=X$(A),y=await ub($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=n&&(W.decisionId||W.traceId)?await n.getExecutionTrace(W):null,j=n&&w?await n.replayExecutionTrace(W):null;return{decisionId:b.decisionId,historyDir:y.historyDir,contextPack:y.contextPack,planPacket:y.planPacket,patchVerdict:y.patchVerdict,reviewPacket:y.reviewPacket,trace:w??void 0,replay:j??void 0,source:w?"local+control-plane":"local"}}async function c4($,b={}){let n=i(b);return A$(n),Cm($.fs,X$(n))}import{buildChannelPlanTrace as h4,compileChannelPlan as d4,finalizeChannelPlan as u4,replayExecutionTrace as o4,resolveChannelExecutionActor as i4}from"@contractspec/integration.runtime/channel";import{createHash as t4}from"crypto";var ib="connect.local",l4="connect.runtime-link.v1",p4="connect.adapter.v1",a4="connect-control-plane-bridge";function e4($){return{linkDecision:async({connectDecisionId:b,createdAt:n,input:A,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(n),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:A.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:ib,externalEventId:b,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:n6(y.objective,A)},metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`}),rawPayload:j},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:A6(j),traceId:B.traceId});if(S.duplicate)return s4($.store,W.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:w}),Z=i4(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:b6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=d4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=u4({plan:X,decision:$6(m),approvalTimeoutMs:900000,now:w}),G=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:Y.policy?.verdict??"blocked",riskTier:Y.policy?.riskTier??"blocked",confidence:Y.policy?.confidence??0.5,modelName:a4,promptVersion:l4,policyVersion:p4,toolTrace:h4(Y),actionPlan:Y,requiresApproval:Y.approval.required,approvalStatus:Y.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:Y.approval.required?"pending":"processed",decisionId:G.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:ib,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,tool:A.tool})}),{approvalStatus:G.approvalStatus,decisionId:G.id,planId:Y.id,providerKey:ib,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Sj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let n=await Sj($.traceService,b);return n?o4(n):null}}}async function s4($,b,n){let m=(await $.listDecisions({externalEventId:n,limit:1,providerKey:ib,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:ib,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Sj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function $6($){let b=I$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((n)=>`${n.status}:${n.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 b6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function n6($,b){return`${$} [${b.tool}]`}function A6($){return t4("sha256").update($).digest("hex")}function Qj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as j6}from"crypto";async function Zj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let n=m6(b);if(!n)return{};let A=await Jb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:n,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:n==="ui"?y6(b):void 0,query:xm(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:A.verdict==="permit"?"pass":A.verdict==="rewrite"?"warn":"fail",detail:A.reason},reason:A.reason,remediation:A.selected!=null?[`Prefer ${A.selected.candidate.source} candidate ${A.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:A,verdict:A.verdict}}function m6($){let b=xm($).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 xm($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function y6($){let b=xm($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function Xj($){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 W6}from"crypto";function Yj($,b,n){let A=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:n?`Generated path: ${n}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||n?"warn":"pass",detail:A}}function Gj($,b){let n=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:n,detail:A}}function Hj($,b,n){return{id:"impact-analysis",status:$?"fail":b||n?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":n?"Impact could not be resolved.":"Impact resolved."}}function qj($,b,n,A,m,y){let W=y.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${y.runtimeLink.decisionId}`:y.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${y.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${W6()}`,sourceDecisionId:b,objective:A.objective,reason:y.reason,summary:{paths:m,impactedContracts:n.impactedContracts,affectedSurfaces:n.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:y.artifactRefs.contextPack},{type:"plan-packet",ref:y.artifactRefs.planPacket},{type:"patch-verdict",ref:y.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:W}],requiredApprovals:[{capability:U$.key,reason:y.reason}],controlPlane:{traceQuery:BA,policyExplain:SA,approvalStatus:y.runtimeLink?.approvalStatus,decisionId:y.runtimeLink?.decisionId,traceId:y.runtimeLink?.traceId??n.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Im($,b,n,A,m,y,W,w,j){let B=I$(W);return{decisionId:$,summary:A.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:m,checks:y,verdict:W,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:j?.approvalStatus,decisionId:j?.decisionId,traceId:j?.traceId??n.actor.traceId},approvalOperationRefs:W==="require_review"?[`${U$.key}@${U$.version}`,`${QA.key}@${QA.version}`]:void 0,remediation:w6(W),reviewPacketRef:w,replay:{traceQuery:BA,policyExplain:SA}}}function w6($){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 B6($,b,n={}){let A=i(b);A$(A),A=o$(A,await $.git.currentBranch());let m=`connect.dec_${j6()}`,y=(n.now??(()=>new Date))().toISOString(),W=X$(A);await cb($.fs,W);let{contextPack:w,planPacket:j}=await ob($,{...b,candidate:Z6(b)}),B=X6(b),S=await i$($,{baseline:b.baseline,touchedPaths:B,workspace:A}),Q=await Y6(n,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=Pb(A,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await Zj($,b),G=[Yj(X.immutablePath,X.protectedPath,X.generatedPath),Gj(X.commandState,X.commandMatch),Hj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],V=S6(X,Y.verdict),O=I$(V),K=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:U$.key,reason:K}]:[],U={...j,requiredApprovals:J,verificationStatus:O.verificationStatus},H=Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((r)=>({file:r.path,contracts:r.contracts,policies:r.policies,surfaces:r.surfaces})):B.map((r)=>({file:r,contracts:w.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:w.affectedSurfaces})),_=Im(m,b,w,U,q,G,V,void 0),z=n.controlPlane?await n.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:_,planPacket:U,workspace:A}):null,L=z?{...j,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:z.decisionId,traceId:z.traceId??j.controlPlane.traceId}}:U,C=V==="require_review"?qj(A,m,w,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,D=Im(m,b,w,L,q,G,V,C?_$($.fs,A,$.fs.join(W.reviewPacketsDir,`${C.id}.json`)):void 0,z);if(Y.remediation?.length)D.remediation=Y.remediation;if(await zm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:D}),C)await Rm($.fs,W,C);let F=await hb($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C}),E={artifacts:Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(C)}),connectDecisionId:m,createdAt:y,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await db($.fs,W,m,E),await Lm($.fs,W,Xj({contextPack:w,createdAt:y,envelope:E,reviewPacket:C,verifyInput:b,workspace:A})),{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C,historyDir:F}}function S6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return Q6($.verdict,b)}function Q6($,b){if(!b)return $;return Oj($)<=Oj(b)?$:b}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Z6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function X6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function Y6($,b,n){if(!$.runCommand)return[];let A=[];for(let m of b){let y=await $.runCommand(m,{cwd:n});A.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return A}HA();var Tm={};f(Tm,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});HA();class Uj{ai;templates=Tm;constructor($){this.ai=new GA($)}}function wz($){return new Uj($)}import{scanSpecSource as z6}from"@contractspec/module.workspace";function Kj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Xz($,b,n={}){let{fs:A,logger:m}=b,y=await A.exists($);if(!y&&!n.force)return{specPath:$,specInfo:Kj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let W=Kj($),w;if(y)try{let B=await A.readFile($);W=z6(B,$),w=W.key}catch{}let j=[];if(n.clean&&w)try{let B=await AA(w,{fs:A});for(let S of B)try{await A.remove(S.filePath),j.push(S.filePath),m.info(`Removed artifact: ${S.filePath}`)}catch{m.warn(`Could not remove artifact: ${S.filePath}`)}}catch{m.warn("Could not discover implementations for cleanup")}if(y)await A.remove($),m.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:W,deleted:!0,cleanedFiles:j,errors:[]}}import{computeSemanticDiff as L6}from"@contractspec/module.workspace";async function Hz($,b,n,A={}){let{fs:m,git:y}=n;if(!await m.exists($))throw Error(`Spec file not found: ${$}`);let w=await m.readFile($),j,B;if(A.baseline)j=await y.showFile(A.baseline,$),B=`${A.baseline}:${$}`;else{if(!await m.exists(b))throw Error(`Spec file not found: ${b}`);j=await m.readFile(b),B=b}let S=L6(w,$,j,B,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:B,differences:S}}$$();import{openApiForRegistry as R6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Dm}from"@contractspec/lib.contracts-spec/operations";async function C6($,b){let{fs:n,logger:A}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;A.info("Loading registry...",{registryPath:m});let W=await x6(m,n);A.info("Generating OpenAPI document...");let w=R6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2084
|
+
`,B=n.resolve(y);return await n.mkdir(n.dirname(B)),await n.writeFile(B,j),A.info(`OpenAPI document written to ${B}`),{document:w,outputPath:B,json:j}}async function x6($,b){let A=await import(b.resolve($));if(A instanceof Dm)return A;if(A.registry instanceof Dm)return A.registry;let m=typeof A.createRegistry==="function"?A.createRegistry:typeof A.default==="function"?A.default:void 0;if(m){let y=await m();if(y instanceof Dm)return y}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as I6,parseOpenApi as E6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Nm,dirname as _j,join as Qb}from"path";function M6($,b,n){if(b.outputDir)return b.outputDir;let{outputDir:A,conventions:m}=n;switch($){case"operation":return Qb(A,m.operations.split("|")[0]??"operations");case"event":return Qb(A,m.events);case"model":return Qb(A,"models");default:return A}}async function zj($,b,n){let{fs:A,logger:m}=n,{source:y,prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;m.info(`Importing from OpenAPI: ${y}`);let X=await E6(y,{fetch:globalThis.fetch,readFile:(J)=>A.readFile(J)});if(X.warnings.length>0)for(let J of X.warnings)m.warn(`Parse warning: ${J}`);m.info(`Parsed ${X.operations.length} operations from ${X.info.title} v${X.info.version}`);let Y=I6(X,$,{prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q});m.info(`Import result: ${Y.summary.imported} imported, ${Y.summary.skipped} skipped, ${Y.summary.errors} errors`);let G=[],V=[],O=[],K=new Map;for(let J of Y.operationSpecs){let U="operation",H=null;if(J.code.includes("defineEvent("))U="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("))U="model";else U="operation",H=J.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let q=M6(U,b,$),_=Qb(q,J.fileName);if(!H&&U==="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)m.info(`[DRY RUN] Would create: ${_}`);else{let z=_j(_);if(!await A.exists(z))await A.mkdir(z);await A.writeFile(_,J.code),m.info(`Created: ${_}`)}if(G.push({path:_,operationId:J.source.sourceId,specName:J.fileName.replace(".ts","")}),H){let z=_j(_),L=K.get(z)||[];L.push({file:Nm(_),name:H[1],type:U}),K.set(z,L)}}if(!Z&&G.length>0)for(let[J,U]of K.entries()){if(U.length===0)continue;let H=U.map((E)=>E.type),q=H.every((E)=>E==="operation"),_=H.every((E)=>E==="event"),z=H.every((E)=>E==="model"),L=`/**
|
|
1990
2085
|
* Auto-generated registry file.
|
|
1991
2086
|
*/
|
|
1992
|
-
`;
|
|
2087
|
+
`;U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;L+=`import { ${E.name} } from '${r}';
|
|
1993
2088
|
`}),L+=`
|
|
1994
|
-
`;let
|
|
2089
|
+
`;let C=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1995
2090
|
|
|
1996
2091
|
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
1997
|
-
`,
|
|
1998
|
-
`}),
|
|
2092
|
+
`,U.forEach((E)=>{L+=`operationRegistry.register(${E.name});
|
|
2093
|
+
`}),C=!0;else if(_)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
1999
2094
|
|
|
2000
2095
|
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2001
|
-
`,
|
|
2002
|
-
`}),
|
|
2096
|
+
`,U.forEach((E)=>{L+=`eventRegistry.register(${E.name});
|
|
2097
|
+
`}),C=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
2003
2098
|
|
|
2004
2099
|
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2005
|
-
`,
|
|
2006
|
-
`}),
|
|
2100
|
+
`,U.forEach((E)=>{L+=`modelRegistry.register(${E.name});
|
|
2101
|
+
`}),C=!0;if(C){let E=Qb(J,"registry.ts");await A.writeFile(E,L),m.info(`Created/Updated registry: ${E}`)}let D=`/**
|
|
2007
2102
|
* Auto-generated barrel file.
|
|
2008
2103
|
*/
|
|
2009
2104
|
|
|
2010
|
-
`;if(
|
|
2011
|
-
`}),
|
|
2012
|
-
`;let F=
|
|
2013
|
-
{ key: '${b.key}', version: ${
|
|
2105
|
+
`;if(U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;D+=`export * from '${r}';
|
|
2106
|
+
`}),C)D+=`export * from './registry';
|
|
2107
|
+
`;let F=Qb(J,"index.ts");await A.writeFile(F,D),m.info(`Created/Updated index: ${F}`)}for(let J of Y.skipped)V.push({operationId:J.sourceId,reason:J.reason}),m.debug(`Skipped: ${J.sourceId} - ${J.reason}`);for(let J of Y.errors)O.push({operationId:J.sourceId,error:J.error}),m.error(`Error: ${J.sourceId} - ${J.error}`);return{imported:Y.summary.imported,skipped:Y.summary.skipped,errors:Y.summary.errors,files:G,skippedOperations:V,errorMessages:O}}import{importFromOpenApi as T6,parseOpenApi as D6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as N6,join as F6}from"path";async function Iz($,b,n){let{fs:A,logger:m}=n,{sources:y,sourceName:W,interactive:w,force:j,dryRun:B}=$,{outputDir:S}=b,Q=y??b.openapi?.sources??[];if(W){if(Q=Q.filter((X)=>X.name===W),Q.length===0)throw Error(`Source not found: ${W}`)}if(Q.length===0)return m.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 X of Q){m.info(`Syncing with source: ${X.name}`);let Y=X.url??X.file;if(!Y){m.warn(`Source ${X.name} has no url or file configured`);continue}let G=await D6(Y,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});m.info(`Parsed ${G.operations.length} operations from ${X.name}`);let V=T6(G,b,{prefix:X.prefix,tags:X.tags,exclude:X.exclude,defaultStability:X.defaultStability,defaultAuth:X.defaultAuth});for(let O of V.operationSpecs){let K=F6(S,O.fileName);if(!await A.exists(K)){if(!B){let U=N6(K);await A.mkdir(U),await A.writeFile(K,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:K}),m.info(`Added: ${O.source.sourceId}`)}else if(await A.readFile(K)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K});else if(j==="openapi"){if(!B)await A.writeFile(K,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:K}),m.info(`Updated: ${O.source.sourceId}`)}else if(j==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K}),m.info(`Kept: ${O.source.sourceId}`);else if(w)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId}`)}}return m.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as v6}from"@contractspec/lib.contracts-transformers/openapi";async function Tz($,b){let{fs:n,logger:A}=b,{specPath:m,openApiSource:y,ignoreDescriptions:W,ignoreTags:w,ignoreTransport:j}=$;A.info(`Validating specs against OpenAPI: ${y}`);let B=await v6(y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});A.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,X=0,Y=await n.stat(m),G=[];if(Y.isDirectory){let O=await n.glob({pattern:"**/*.ts",cwd:m,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});G.push(...O)}else G.push(m);A.info(`Found ${G.length} spec files to validate`);for(let O of G)try{let K=await n.readFile(O),J=K.match(/operationId:\s*['"]([^'"]+)['"]/)||K.match(/name:\s*['"]([^'"]+)['"]/)||K.match(/export\s+const\s+(\w+)Spec\s*=/);if(!J||!J[1]){A.debug(`Could not extract operationId from ${O}`);continue}let U=J[1];Z++;let H;if(H=S.get(U),!H){let z=U.replace(/([A-Z])/g,"_$1").toLowerCase();H=S.get(z)}if(!H){for(let[z,L]of S)if(z.toLowerCase().includes(U.toLowerCase())||U.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: ${U}`}]}),X++;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(!j){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(!j){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 _=q.length===0;if(!_)X++;Q.push({specPath:O,operationId:H.operationId,valid:_,diffs:q})}catch(K){A.error(`Error validating ${O}: ${K}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${K instanceof Error?K.message:String(K)}`}]}),X++}let V=X===0;return A.info(`Validation ${V?"passed":"failed"}: ${Z} specs checked, ${X} with differences`),{valid:V,specsValidated:Z,specsWithDiffs:X,results:Q}}async function cz($,b,n){let{fs:A,logger:m}=$,{source:y,outputDir:W}=b,w=A.resolve(n??process.cwd(),y);if(!await A.exists(w))throw Error(`Source file not found: ${w}`);let B={...await P(A,n),outputDir:W};return m.info(`Extracting contracts from ${w} to ${W}`),zj(B,{source:w,outputDir:W,dryRun:!1},$)}var Rj={};f(Rj,{validateFeatureRefs:()=>k6,getArrayNameForSpecType:()=>Lj,detectFeatureContext:()=>g6,computeAddSpecEdit:()=>P6});function g6($,b){let n=[{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:Q,regex:Z,specType:X}of n){let Y;Z.lastIndex=0;while((Y=Z.exec($))!==null)if(!A||Y.index>A.index)A={type:Q,specType:X,index:Y.index}}if(!A)return null;let m=$.slice(A.index)+b,y=A.type;new RegExp(`${y}\\s*:\\s*\\[`).exec(m);let w=$.slice(A.index),j=0,B=!1,S="";for(let Q=0;Q<w.length;Q++){let Z=w[Q],X=Q>0?w[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&X!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")j++;else if(Z==="]"){if(j--,j===0)return null}}if(j>0)return{type:A.type,specType:A.specType};return null}function P6($,b){let n=Lj(b.type),m=new RegExp(`${n}\\s*:\\s*\\[`,"g").exec($);if(m){let y=m.index+m[0].length,W=typeof b.version==="string"?`'${b.version}'`:b.version,w=`
|
|
2108
|
+
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function Lj($){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 k6($,b){let n=[],A=(m,y,W)=>{for(let w of m){let j=`${w.key}.v${w.version}`;if(!y.has(j))n.push({key:w.key,version:w.version,type:W,message:`${W} ${w.key}.v${w.version} not found`})}};return A($.operations,b.operations,"Operation"),A($.events,b.events,"Event"),A($.presentations,b.presentations,"Presentation"),A($.experiments,b.experiments,"Experiment"),n}var Ej={};f(Ej,{removeReferenceStrategy:()=>JA,implementSkeletonStrategy:()=>VA,implementAiStrategy:()=>OA,generateFixLinks:()=>r6,FixService:()=>Ij,FIX_STRATEGY_STABILITY:()=>sb,FIX_STRATEGY_LABELS:()=>o6,CiOutputSchema:()=>A7});function r6($,b){let n=[];if(!$.ref||!$.file)return n;if(b.includeCli)n.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let A=$.file.startsWith("/")?$.file:`/${$.file}`,m=$.ref,y=m.line||1,W=m.column||1;n.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${A}:${y}:${W}`})}if(b.includeGithubIssue&&b.repository){let A=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),m=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
2014
2109
|
|
|
2015
2110
|
> ${$.message}
|
|
2016
2111
|
|
|
2017
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
2018
|
-
`)}function
|
|
2112
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${A}&body=${m}`})}return n}import i6 from"node:path";function E$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function M$($,b){let n=$.enrichment?.owners?.length?$.enrichment.owners.map((W)=>`'${W}'`).join(", "):"'@team'",A=$.enrichment?.tags?.length?$.enrichment.tags.map((W)=>`'${W}'`).join(", "):"",m=$.description||`TODO: Add description for ${$.key}`,y=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([W,w])=>{if(w!==void 0)y.push(`${W}: ${w}`)});return y.push(`owners: [${n}]`),y.push(`tags: [${A}]`),y.push(`description: '${m}'`),y.join(`,
|
|
2113
|
+
`)}function lb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=M$($,{kind:"'api'"});return`/**
|
|
2019
2114
|
* Capability: ${$.key}
|
|
2020
2115
|
*
|
|
2021
2116
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2026,9 +2121,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);A.push({type:"github-issue",labe
|
|
|
2026
2121
|
|
|
2027
2122
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
2028
2123
|
|
|
2029
|
-
export const ${
|
|
2124
|
+
export const ${n} = defineCapability({
|
|
2030
2125
|
meta: {
|
|
2031
|
-
${
|
|
2126
|
+
${A}
|
|
2032
2127
|
},
|
|
2033
2128
|
|
|
2034
2129
|
provides: [
|
|
@@ -2052,7 +2147,7 @@ export const ${A} = defineCapability({
|
|
|
2052
2147
|
// }
|
|
2053
2148
|
],
|
|
2054
2149
|
});
|
|
2055
|
-
`}function
|
|
2150
|
+
`}function pb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"EventSpec",A=n.replace("Spec","Payload"),m=M$($);return`/**
|
|
2056
2151
|
* Event: ${$.key}
|
|
2057
2152
|
*
|
|
2058
2153
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2065,8 +2160,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
2065
2160
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2066
2161
|
|
|
2067
2162
|
// TODO: Define event payload schema
|
|
2068
|
-
export const ${
|
|
2069
|
-
name: '${
|
|
2163
|
+
export const ${A} = new SchemaModel({
|
|
2164
|
+
name: '${A}',
|
|
2070
2165
|
description: 'Payload for ${$.key} event',
|
|
2071
2166
|
fields: {
|
|
2072
2167
|
// Add your payload fields here
|
|
@@ -2076,12 +2171,12 @@ export const ${m} = new SchemaModel({
|
|
|
2076
2171
|
},
|
|
2077
2172
|
});
|
|
2078
2173
|
|
|
2079
|
-
export const ${
|
|
2174
|
+
export const ${n} = defineEvent({
|
|
2080
2175
|
meta: {
|
|
2081
|
-
${
|
|
2176
|
+
${m}
|
|
2082
2177
|
},
|
|
2083
2178
|
|
|
2084
|
-
payload: ${
|
|
2179
|
+
payload: ${A},
|
|
2085
2180
|
|
|
2086
2181
|
// TODO: Specify PII fields if any
|
|
2087
2182
|
// piiFields: ['user.email'],
|
|
@@ -2092,7 +2187,7 @@ export const ${A} = defineEvent({
|
|
|
2092
2187
|
// policy: 'archive',
|
|
2093
2188
|
// },
|
|
2094
2189
|
});
|
|
2095
|
-
`}function
|
|
2190
|
+
`}function f6($){let b=$.toLowerCase(),n=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let A of n)if(b.includes(A))return"query";return"command"}function ab($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=n.replace("Spec","Input"),m=n.replace("Spec","Output"),y=f6($.key),W=y==="query"?"defineQuery":"defineCommand",w=$.enrichment?.goal||"TODO: Define the business goal",j=$.enrichment?.context||"TODO: Provide context",B=M$($,{goal:`'${w}'`,context:`'${j}'`});return`/**
|
|
2096
2191
|
* Operation: ${$.key}
|
|
2097
2192
|
*
|
|
2098
2193
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2101,12 +2196,12 @@ export const ${A} = defineEvent({
|
|
|
2101
2196
|
* Referenced by feature: ${$.featureKey||"unknown"}
|
|
2102
2197
|
*/
|
|
2103
2198
|
|
|
2104
|
-
import { ${
|
|
2199
|
+
import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
2105
2200
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2106
2201
|
|
|
2107
2202
|
// TODO: Define input schema
|
|
2108
|
-
export const ${
|
|
2109
|
-
name: '${
|
|
2203
|
+
export const ${A} = new SchemaModel({
|
|
2204
|
+
name: '${A}',
|
|
2110
2205
|
description: 'Input for ${$.key}',
|
|
2111
2206
|
fields: {
|
|
2112
2207
|
// Add your input fields here
|
|
@@ -2115,8 +2210,8 @@ export const ${m} = new SchemaModel({
|
|
|
2115
2210
|
});
|
|
2116
2211
|
|
|
2117
2212
|
// TODO: Define output schema
|
|
2118
|
-
export const ${
|
|
2119
|
-
name: '${
|
|
2213
|
+
export const ${m} = new SchemaModel({
|
|
2214
|
+
name: '${m}',
|
|
2120
2215
|
description: 'Output for ${$.key}',
|
|
2121
2216
|
fields: {
|
|
2122
2217
|
// Add your output fields here
|
|
@@ -2124,14 +2219,14 @@ export const ${n} = new SchemaModel({
|
|
|
2124
2219
|
},
|
|
2125
2220
|
});
|
|
2126
2221
|
|
|
2127
|
-
export const ${
|
|
2222
|
+
export const ${n} = ${W}({
|
|
2128
2223
|
meta: {
|
|
2129
2224
|
${B}
|
|
2130
2225
|
},
|
|
2131
2226
|
|
|
2132
2227
|
io: {
|
|
2133
|
-
input: ${
|
|
2134
|
-
output: ${
|
|
2228
|
+
input: ${A},
|
|
2229
|
+
output: ${m},
|
|
2135
2230
|
errors: {
|
|
2136
2231
|
// TODO: Define possible errors
|
|
2137
2232
|
// EXAMPLE_ERROR: {
|
|
@@ -2153,7 +2248,7 @@ export const ${A} = ${w}({
|
|
|
2153
2248
|
},
|
|
2154
2249
|
|
|
2155
2250
|
transport: {
|
|
2156
|
-
rest: { method: '${
|
|
2251
|
+
rest: { method: '${y==="command"?"POST":"GET"}' },
|
|
2157
2252
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
2158
2253
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
2159
2254
|
},
|
|
@@ -2170,7 +2265,7 @@ export const ${A} = ${w}({
|
|
|
2170
2265
|
examples: [],
|
|
2171
2266
|
},
|
|
2172
2267
|
});
|
|
2173
|
-
`}function
|
|
2268
|
+
`}function c6($){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 eb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"PresentationSpec",A=c6($.key),m=M$($);return`/**
|
|
2174
2269
|
* Presentation: ${$.key}
|
|
2175
2270
|
*
|
|
2176
2271
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2181,12 +2276,12 @@ export const ${A} = ${w}({
|
|
|
2181
2276
|
|
|
2182
2277
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
2183
2278
|
|
|
2184
|
-
export const ${
|
|
2279
|
+
export const ${n} = definePresentation({
|
|
2185
2280
|
meta: {
|
|
2186
|
-
${
|
|
2281
|
+
${m}
|
|
2187
2282
|
},
|
|
2188
2283
|
|
|
2189
|
-
kind: '${
|
|
2284
|
+
kind: '${A}',
|
|
2190
2285
|
|
|
2191
2286
|
// TODO: Define content structure
|
|
2192
2287
|
content: {
|
|
@@ -2210,7 +2305,7 @@ export const ${A} = definePresentation({
|
|
|
2210
2305
|
// focusable: true,
|
|
2211
2306
|
// },
|
|
2212
2307
|
});
|
|
2213
|
-
`}import G$ from"node:path";function n0($,b){if(b.outputDir)return Qn(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=o4($.featureFile);if(A)return Qn(A,$.ref.key,$.specType)}return Qn(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function o4($){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=i4(A),W=l4(A);return G$.join($,W,`${m}${n}`)}function i4($){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 l4($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var t4={"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 a4(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=$6(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=p4.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 a4($,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=e4(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=s4($.key,$.specType);return{...$,description:m.description,enrichment:{goal:m.goal,context:m.context,owners:["@team"],tags:m.tags}}}function e4($){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 s4($,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 $6($){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 b6 from"node: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=A6(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=b6.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 A6($){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=m6(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 m6($,b,A){if(!n6(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=W6(j),j}function n6($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function ej($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W6($){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 j6}from"node:child_process";import{promisify as y6}from"node:util";var B6=y6(j6),by={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function Hz($,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 B6(`${n} ${y}`,{cwd:m})}catch(B){}}}import C$ from"path";async function Jz($,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 S6}from"node:child_process";import{promisify as Q6}from"node:util";var Z6=Q6(S6);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 Z6(Z,{cwd:w,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:G,stderr:X}),m.info(`✓ ${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(`✗ ${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?`✓ All ${y.length} command(s) passed`:`✗ ${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 G6,extractFromProject as X6}from"@contractspec/lib.source-extractors";import{generateOperations as Y6,generateRegistry as H6,generateSchemas as q6}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as O6}from"@contractspec/lib.source-extractors/extractors";import{dirname as V6,join as Zn}from"path";async function J6($,b,A,m){let{fs:n,logger:W}=A,w=m??process.cwd();O6(),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 G6(w,{readFile:(_)=>n.readFile(_),glob:(_)=>n.glob({pattern:_})});if(y.frameworks.length===0)return W.warn("No supported frameworks detected"),{success:!1,report:K6(),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 X6(y,S);if(!Q.success||!Q.ir)return{success:!1,report:_6(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:U6(Z)};let G=b.outputDir??Zn($.outputDir,"generated"),X={outputDir:G,defaultAuth:"user"},Y=Y6(Z,X),V=q6(Z,X),O=H6(Y),K=[...Y,...V,O];if(!b.dryRun)for(let _ of K){let H=Zn(G,_.path),q=V6(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:z6(Z,J,b)}}function K6(){return`# Import Report
|
|
2308
|
+
`}import H$ from"node:path";function qA($,b){if(b.outputDir)return Fm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let n=h6($.featureFile);if(n)return Fm(n,$.ref.key,$.specType)}return Fm(H$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function h6($){let b=H$.dirname($),n=H$.parse($).root,A=0;while(b!==n&&A<50){if(H$.basename(b)==="src")return b;b=H$.dirname(b),A++}b=H$.dirname($),A=0;while(b!==n&&A<50)b=H$.dirname(b),A++;let m=$.lastIndexOf(`${H$.sep}src${H$.sep}`);if(m!==-1)return $.substring(0,m+5);return null}function Fm($,b,n){let A=b.replace(/\./g,"-").toLowerCase(),m=d6(n),y=u6(n);return H$.join($,y,`${A}${m}`)}function d6($){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 u6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var o6={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},sb={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function OA($,b,n){let{fs:A,logger:m}=n,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:sb["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await t6(j,b,m)}catch(X){m.warn("AI enrichment failed, falling back to skeleton",{error:X instanceof Error?X.message:String(X)})}else m.info("No AI config provided, using skeleton with experimental stability");let S=a6(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=qA($,b),Z=[];if(!b.dryRun){let X=i6.dirname(Q);await A.mkdir(X),await A.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(j){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}async function t6($,b,n){if(n.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:m}=await Promise.resolve().then(() => (HA(),Jj)),y=l6(b),W=new m(y),w=$.specType==="operation"?"command":$.specType,j=`${Cj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await W.generateOperationSpec(j,w);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(j);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(m){n.warn("AIGenerator call failed, falling back to heuristics",{error:m instanceof Error?m.message:String(m)})}let A=p6($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function l6($){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 p6($,b){let n=$.split("."),A=n[0]||"unknown",m=n.slice(1).join(" ").replace(/_/g," "),y=[A],W=m.toLowerCase().split(" "),j=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>W.some((S)=>S.includes(B)));return{description:`${Cj(b)} for ${A} ${m}`,goal:`Enable ${m} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...y,...j]}}function a6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import e6 from"node:path";async function VA($,b,n){let{fs:A}=n,{ref:m,specType:y,featureKey:W}=$;try{let w={key:m.key,version:m.version,specType:y,stability:sb["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=s6(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=qA($,b),S=[];if(!b.dryRun){let Q=e6.dirname(B);await A.mkdir(Q),await A.writeFile(B,j),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function s6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}async function JA($,b,n){let{fs:A}=n,{ref:m,featureFile:y,specType:W}=$;try{let w=await A.readFile(y),j=w,B=$7(w,m,W);if(B===w)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${m.key}.v${m.version} in ${y}`};let S=[];if(!b.dryRun)await A.writeFile(y,B),S.push({path:y,action:"modified",previousContent:j});else S.push({path:y,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function $7($,b,n){if(!b7(n))return $;let m=xj(b.key),y=xj(b.version),W=[new RegExp(`\\{\\s*key:\\s*['"]${m}['"],\\s*version:\\s*['"]${y}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${y}['"],\\s*key:\\s*['"]${m}['"]\\s*\\},?\\s*`,"g")],w=$;for(let j of W)w=w.replace(j,"");return w=n7(w),w}function b7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n7($){return $.replace(/,(\s*)\]/g,"$1]")}class Ij{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,n)=>JA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,n)=>VA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,n)=>OA(b,n,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 n=this.strategies.get(b.strategy);if(!n)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}),n.fix($,b)}async batchFix($){let b=[],n=0,A=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)n++;else A++}catch(y){A++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:n,failed:A,results:b}}async scanAndGetFixables($={}){return(await mA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((n)=>this.getToFix(n)).filter((n)=>n!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let n=this.parseFixableIssue($);if(!n)return null;return{...n,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:n,preferAi:A,select:m}=b;if(n)return Promise.resolve(n);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 m==="function")return m($,$.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 Zb}from"zod";var A7=Zb.union([Zb.array(Zb.unknown()),Zb.object({issues:Zb.array(Zb.unknown())}).transform(($)=>$.issues)]);import{exec as m7}from"node:child_process";import{promisify as y7}from"node:util";var W7=y7(m7),Mj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function fL($,b,n={}){if($.length===0)return;let A=n.cwd??process.cwd(),m=Mj[n.type??"biome"]??Mj.biome,y=50;for(let W=0;W<$.length;W+=y){let j=$.slice(W,W+y).map((B)=>`"${B}"`).join(" ");try{await W7(`${m} ${j}`,{cwd:A})}catch(B){}}}import T$ from"path";async function uL($,b){let n=T$.join(b,"contracts"),A=T$.join(b,"generated"),m=T$.join(A,"docs"),y=await $.fs.exists(n),W=await $.fs.exists(A);if(!y)return{hasContracts:!1,hasGenerated:W,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let w=await j$($,{pattern:"contracts/**/*.ts"}),j=[];if(W)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts"),G=T$.join(m,`${Y}.md`);if(!await $.fs.exists(G))j.push(Y)}else if(w.length>0)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts");j.push(Y)}let B=T$.join(n,"index.ts"),S=T$.join(n,"registry.ts"),Q=w.length>0&&!await $.fs.exists(B),Z=w.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:W,missingDocs:j,missingIndex:Q,missingRegistry:Z,totalSpecs:w.length}}var Fj={};f(Fj,{runHook:()=>Tj,getAvailableHooks:()=>Dj});import{exec as w7}from"node:child_process";import{promisify as j7}from"node:util";var B7=j7(w7);async function Tj($,b){let{fs:n,logger:A}=$,{hookName:m,dryRun:y=!1}=b,W=I(b.workspaceRoot);A.info(`Running hook: ${m}`,{workspaceRoot:W,dryRun:y});let w=await Nj(n,W);if(!w)return{hookName:m,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let j=w[m];if(!j||j.length===0)return{hookName:m,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${m}`};A.info(`Found ${j.length} command(s) for ${m}`);let B=[],S=!0;for(let Z of j){if(y){A.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${Z}`);try{let{stdout:X,stderr:Y}=await B7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),A.info(`✓ ${Z}`)}catch(X){S=!1;let Y=X;B.push({command:Z,success:!1,exitCode:Y.code??1,stdout:Y.stdout??"",stderr:Y.stderr??Y.message??String(X)}),A.error(`✗ ${Z}`,{exitCode:Y.code,stderr:Y.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:m,success:S,commandResults:B,totalCommands:j.length,successfulCommands:Q,summary:S?`✓ All ${j.length} command(s) passed`:`✗ ${Q}/${j.length} command(s) passed`}}async function Dj($,b){let n=await Nj($.fs,b);return n?Object.keys(n):[]}async function Nj($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return null;try{let A=await $.readFile(n);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as S7,extractFromProject as Q7}from"@contractspec/lib.source-extractors";import{generateOperations as Z7,generateRegistry as X7,generateSchemas as Y7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as G7}from"@contractspec/lib.source-extractors/extractors";import{dirname as H7,join as vm}from"path";async function q7($,b,n,A){let{fs:m,logger:y}=n,W=A??process.cwd();G7(),y.info(`Scanning source code in ${W}...`);let w={readFile:(U)=>m.readFile(U),glob:(U,H)=>m.glob({pattern:U,cwd:H?.cwd}),exists:(U)=>m.exists(U)},j=await S7(W,{readFile:(U)=>m.readFile(U),glob:(U)=>m.glob({pattern:U})});if(j.frameworks.length===0)return y.warn("No supported frameworks detected"),{success:!1,report:O7(),errors:["No supported frameworks detected in project"]};y.info(`Detected frameworks: ${j.frameworks.map((U)=>U.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let U of B.getAll())if("setFs"in U&&typeof U.setFs==="function")U.setFs(w);let S={scope:b.scope,framework:b.framework},Q=await Q7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:V7(Q.errors??[]),errors:Q.errors?.map((U)=>U.message)};let Z=Q.ir;if(y.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:J7(Z)};let X=b.outputDir??vm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},G=Z7(Z,Y),V=Y7(Z,Y),O=X7(G),K=[...G,...V,O];if(!b.dryRun)for(let U of K){let H=vm(X,U.path),q=H7(H);if(!await m.exists(q))await m.mkdir(q);await m.writeFile(H,U.content),y.info(`Created: ${H}`)}else for(let U of K)y.info(`[DRY RUN] Would create: ${vm(X,U.path)}`);let J={files:K,operationsGenerated:G.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:U7(Z,J,b)}}function O7(){return`# Import Report
|
|
2214
2309
|
|
|
2215
2310
|
## ❌ No Supported Frameworks Detected
|
|
2216
2311
|
|
|
@@ -2227,13 +2322,13 @@ No supported frameworks were detected in the project.
|
|
|
2227
2322
|
- Next.js API Routes
|
|
2228
2323
|
|
|
2229
2324
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
2230
|
-
`}function
|
|
2325
|
+
`}function V7($){return`# Import Report
|
|
2231
2326
|
|
|
2232
2327
|
## ❌ Extraction Failed
|
|
2233
2328
|
|
|
2234
2329
|
${$.map((b)=>`- ${b.message}`).join(`
|
|
2235
2330
|
`)}
|
|
2236
|
-
`}function
|
|
2331
|
+
`}function J7($){return`# Import Analysis Report
|
|
2237
2332
|
|
|
2238
2333
|
## Summary
|
|
2239
2334
|
|
|
@@ -2265,7 +2360,7 @@ ${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).jo
|
|
|
2265
2360
|
|
|
2266
2361
|
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
2267
2362
|
`):"None"}
|
|
2268
|
-
`}function
|
|
2363
|
+
`}function U7($,b,n){return`# Import Report${n.dryRun?" (Dry Run)":""}
|
|
2269
2364
|
|
|
2270
2365
|
## ✅ Import Successful
|
|
2271
2366
|
|
|
@@ -2291,42 +2386,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
|
2291
2386
|
|
|
2292
2387
|
### Next Steps
|
|
2293
2388
|
|
|
2294
|
-
1. Review generated contracts in \`${
|
|
2389
|
+
1. Review generated contracts in \`${n.outputDir??"generated/"}\`
|
|
2295
2390
|
2. Fill in TODO placeholders with business context
|
|
2296
2391
|
3. Run \`contractspec validate\` to verify contracts
|
|
2297
2392
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
2298
|
-
`}function
|
|
2299
|
-
`)}function
|
|
2300
|
-
`)}async function
|
|
2301
|
-
`)}function
|
|
2302
|
-
`)}function
|
|
2303
|
-
`)}function
|
|
2304
|
-
`);
|
|
2305
|
-
`)}function
|
|
2306
|
-
`)}async function
|
|
2393
|
+
`}function K7($,b,n={}){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(""),n.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 m of $.project.frameworks)A.push(`- **${m.name}** (${m.confidence})`);if(A.push(""),n.includeEndpoints!==!1&&$.endpoints.length>0){A.push("## Endpoints"),A.push(""),A.push("| Method | Path | Kind | Confidence |"),A.push("|--------|------|------|------------|");for(let m of $.endpoints)A.push(`| ${m.method} | \`${m.path}\` | ${m.kind} | ${m.confidence.level} |`);A.push("")}if(n.includeSchemas!==!1&&$.schemas.length>0){A.push("## Schemas"),A.push(""),A.push("| Name | Type | Confidence |"),A.push("|------|------|------------|");for(let m of $.schemas)A.push(`| ${m.name} | ${m.schemaType} | ${m.confidence.level} |`);A.push("")}if(b&&n.includeIssues!==!1){A.push("## Verification"),A.push(""),A.push("| Status | Count |"),A.push("|--------|-------|"),A.push(`| Valid | ${b.summary.validEndpoints} |`),A.push(`| Warnings | ${b.summary.warningEndpoints} |`),A.push(`| Errors | ${b.summary.errorEndpoints} |`),A.push("");let m=b.endpointResults.filter((y)=>y.issues.length>0);if(m.length>0){A.push("### Issues"),A.push("");for(let y of m){A.push(`#### ${y.endpoint.method} ${y.endpoint.path}`);for(let W of y.issues){let w=W.severity==="error"?"❌":W.severity==="warning"?"⚠️":"ℹ️";if(A.push(`- ${w} **${W.code}**: ${W.message}`),W.suggestion)A.push(` - *Suggestion*: ${W.suggestion}`)}A.push("")}}}if(n.includeAmbiguities!==!1&&$.ambiguities.length>0){A.push("## Ambiguities (Require Review)"),A.push("");for(let m of $.ambiguities)if(A.push(`- **${m.type}** (${m.itemId}): ${m.description}`),m.suggestion)A.push(` - *Suggestion*: ${m.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(`
|
|
2394
|
+
`)}function _7($,b){let n=[];n.push(""),n.push("\uD83D\uDCCA Summary"),n.push(` Files scanned: ${$.stats.filesScanned}`),n.push(` Endpoints: ${$.stats.endpointsFound}`),n.push(` Schemas: ${$.stats.schemasFound}`),n.push(""),n.push("\uD83D\uDCC8 Confidence"),n.push(` High: ${$.stats.highConfidence}`),n.push(` Medium: ${$.stats.mediumConfidence}`),n.push(` Low: ${$.stats.lowConfidence}`),n.push(""),n.push("\uD83D\uDD27 Frameworks");for(let A of $.project.frameworks)n.push(` • ${A.name}`);if(n.push(""),b)n.push("✅ Verification"),n.push(` Valid: ${b.summary.validEndpoints}`),n.push(` Warnings: ${b.summary.warningEndpoints}`),n.push(` Errors: ${b.summary.errorEndpoints}`),n.push("");return n.join(`
|
|
2395
|
+
`)}async function z7($,b,n){let{logger:A}=n,m=[],y=[...$.ambiguities];A.info(`Verifying ${$.endpoints.length} endpoints...`);for(let w of $.endpoints){let j=[];if(w.confidence.level==="low"||w.confidence.level==="ambiguous")j.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${w.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!w.input&&(w.method==="POST"||w.method==="PUT"||w.method==="PATCH"))j.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!w.output)j.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!==w.id&&Q.path===w.path&&Q.method===w.method).length>0)j.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${w.method} ${w.path} found`,severity:"error"})}if(b.checkConflicts){let S=L7(w,$.endpoints);for(let Q of S)j.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=j.some((S)=>S.severity==="error")?"error":j.some((S)=>S.severity==="warning")?"warning":"valid";m.push({endpoint:w,status:B,issues:j})}if(b.validateSchemas){for(let w of $.schemas)if(!w.fields||w.fields.length===0)y.push({type:"schema",itemId:w.id,description:`Schema ${w.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:w.source})}let W={totalEndpoints:m.length,validEndpoints:m.filter((w)=>w.status==="valid").length,warningEndpoints:m.filter((w)=>w.status==="warning").length,errorEndpoints:m.filter((w)=>w.status==="error").length,totalIssues:m.reduce((w,j)=>w+j.issues.length,0)};return A.info(`Verification complete: ${W.validEndpoints} valid, ${W.warningEndpoints} warnings, ${W.errorEndpoints} errors`),{valid:W.errorEndpoints===0,endpointResults:m,ambiguities:y,summary:W}}function L7($,b){let n=[],A=$.path.split("/").filter(Boolean);for(let m of b){if(m.id===$.id)continue;if(m.method!==$.method)continue;let y=m.path.split("/").filter(Boolean);if(y.length!==A.length)continue;let W=!0;for(let w=0;w<A.length;w++){let j=A[w]??"",B=y[w]??"",S=j.startsWith(":")||j.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&j!==B){W=!1;break}}if(W&&$.path!==m.path)n.push(m)}return n}function YR($,b="feature-map",n={}){switch(b){case"feature-map":return km($,n);case"orphans":return R7($,n);case"dependencies":return C7($,n);case"full":return x7($,n);default:return km($,n)}}function km($,b){let{direction:n="LR",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=$.features;if(b.featureKeys&&b.featureKeys.length>0)W=W.filter((Z)=>b.featureKeys?.includes(Z.key));let w=0,j=!1;if(W.length>0){y.push(" subgraph features [Features]");for(let Z of W){if(w>=m)break;let X=v(`F_${Z.key}`),Y=Z.title??Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let B=gm(W,"operations",$.inventory);if(B.length>0&&w<m){y.push(" subgraph ops [Operations]");for(let Z of B){if(w>=m)break;let X=v(`O_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let S=gm(W,"events",$.inventory);if(S.length>0&&w<m){y.push(" subgraph events [Events]");for(let Z of S){if(w>=m)break;let X=v(`E_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let Q=gm(W,"presentations",$.inventory);if(Q.length>0&&w<m){y.push(" subgraph presentations [Presentations]");for(let Z of Q){if(w>=m)break;let X=v(`P_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}for(let Z of W){let X=v(`F_${Z.key}`);for(let Y of Z.operations){let G=v(`O_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}for(let Y of Z.events){let G=v(`E_${Y.key}_v${Y.version}`);y.push(` ${X} -.-> ${G}`)}for(let Y of Z.presentations){let G=v(`P_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}}if(j)y.push(` note["... and more (truncated at ${m} nodes)"]`);return y.join(`
|
|
2396
|
+
`)}function R7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=new Set,w=new Set,j=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)w.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)j.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){y.push(" subgraph features [Features]");for(let Q of $.features){if(B>=m)break;let Z=v(`F_${Q.key}`);y.push(` ${Z}["${B$(Q.title??Q.key)}"]`),B++}y.push(" end")}if($.orphanedSpecs.length>0){y.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=m)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}let S=[];for(let Q of W){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"operation",key:Z,version:X})}for(let Q of w){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"event",key:Z,version:X})}for(let Q of j){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"presentation",key:Z,version:X})}if(S.length>0&&B<m){y.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=m)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let X of Q.operations){let Y=v(`operation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}for(let X of Q.events){let Y=v(`event_${X.key}_v${X.version}`);y.push(` ${Z} -.-> ${Y}`)}for(let X of Q.presentations){let Y=v(`presentation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}}return y.join(`
|
|
2397
|
+
`)}function C7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=0;for(let w of $.features){if(W>=m)break;let j=v(`F_${w.key}`);y.push(` ${j}["${B$(w.title??w.key)}"]`),W++;for(let B of w.operations){if(W>=m)break;let S=v(`O_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.events){if(W>=m)break;let S=v(`E_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} -.-> ${S}`),W++}for(let B of w.presentations){if(W>=m)break;let S=v(`P_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);y.push(` ${S} --> ${Q}`)}}return y.join(`
|
|
2398
|
+
`)}function x7($,b){let n=km($,b);if($.orphanedSpecs.length===0)return n;let A=n.split(`
|
|
2399
|
+
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let m of $.orphanedSpecs.slice(0,20)){let y=v(`orphan_${m.type}_${m.key}_v${m.version}`),W=`${m.key}.v${m.version}`;A.push(` ${y}["${B$(W)}"]:::orphan`)}return A.push(" end"),A.push(" classDef orphan stroke-dasharray: 5 5"),A.join(`
|
|
2400
|
+
`)}function gm($,b,n){let A=new Set,m=[];for(let y of $)for(let W of y[b]){let w=`${W.key}.v${W.version}`;if(!A.has(w))A.add(w),m.push(W)}return m}function Pm($){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 B$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as I7,specToMarkdown as D$}from"@contractspec/module.workspace";function HR($,b,n){let A=[];if(n.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))A.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))A.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(n.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))A.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))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(b))A.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return A}function qR($,b){let n=[];n.push(`# Verification Report: ${$.meta.key}`),n.push("");let A=b.filter((W)=>W.severity==="error"),m=b.filter((W)=>W.severity==="warning"),y=b.filter((W)=>W.severity==="info");if(n.push("## Summary"),n.push(""),n.push(`- Errors: ${A.length}`),n.push(`- Warnings: ${m.length}`),n.push(`- Info: ${y.length}`),n.push(""),A.length>0){n.push("## Errors"),n.push("");for(let W of A)n.push(`- ❌ **${W.category}**: ${W.message}`);n.push("")}if(m.length>0){n.push("## Warnings"),n.push("");for(let W of m)n.push(`- ⚠️ **${W.category}**: ${W.message}`);n.push("")}if(y.length>0){n.push("## Info"),n.push("");for(let W of y)n.push(`- ℹ️ **${W.category}**: ${W.message}`);n.push("")}return n.join(`
|
|
2401
|
+
`)}async function UR($,b){let n=[];n.push(D$($,"context"));let A=await j$(b),m=async(y)=>{let W=A.find((j)=>j.key===y.name&&j.version===y.version);if(!W)return null;return(await I7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){n.push(`
|
|
2307
2402
|
## Operations (${$.operations.length})
|
|
2308
|
-
`);for(let
|
|
2403
|
+
`);for(let y of $.operations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2309
2404
|
|
|
2310
|
-
*Spec not found*`);
|
|
2405
|
+
*Spec not found*`);n.push("---")}}if($.events?.length){n.push(`
|
|
2311
2406
|
## Events (${$.events.length})
|
|
2312
|
-
`);for(let
|
|
2407
|
+
`);for(let y of $.events){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2313
2408
|
|
|
2314
|
-
*Spec not found*`);
|
|
2409
|
+
*Spec not found*`);n.push("---")}}if($.presentations?.length){n.push(`
|
|
2315
2410
|
## Presentations (${$.presentations.length})
|
|
2316
|
-
`);for(let
|
|
2317
|
-
|
|
2318
|
-
*Spec not found*`);
|
|
2319
|
-
`)}function
|
|
2320
|
-
`)}function
|
|
2321
|
-
`)}function
|
|
2322
|
-
`)}function
|
|
2323
|
-
`)}function
|
|
2324
|
-
`)}import{RegeneratorService as
|
|
2411
|
+
`);for(let y of $.presentations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2412
|
+
|
|
2413
|
+
*Spec not found*`);n.push("---")}}return n.join(`
|
|
2414
|
+
`)}function E7($,b){let n=[];if(n.push(`# Implementation Guide: ${$.meta.key}`),n.push(""),n.push(`**Target Agent**: ${b}`),n.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),n.push(""),$.meta.description)n.push("## Overview"),n.push(""),n.push($.meta.description),n.push("");if($.meta.goal)n.push("## Goal"),n.push(""),n.push($.meta.goal),n.push("");if($.meta.context)n.push("## Context"),n.push(""),n.push($.meta.context),n.push("");if(n.push("## Implementation Steps"),n.push(""),$.specType==="operation"){if(n.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)n.push("2. Implement input validation according to the schema"),n.push("3. Implement the core business logic"),n.push("4. Return output matching the expected schema");if($.hasPolicy)n.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){n.push("6. Emit events on success:");for(let A of $.emittedEvents)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("7. Add error handling for expected failure cases"),n.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(n.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){n.push("2. Implement operations:");for(let A of $.operations)n.push(` - \`${A.name}\` (v${A.version})`)}if($.presentations&&$.presentations.length>0){n.push("3. Implement presentations:");for(let A of $.presentations)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("4. Wire up feature exports"),n.push("5. Add integration tests")}else n.push("1. Review the spec requirements"),n.push("2. Implement the core logic"),n.push("3. Add tests"),n.push("4. Document the implementation");if(n.push(""),n.push("## Constraints"),n.push(""),n.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)n.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)n.push(`- Tags: ${$.meta.tags.join(", ")}`);if(n.push(""),b==="cursor-cli")n.push("## Cursor Notes"),n.push(""),n.push("- Use Composer mode for multi-file changes"),n.push("- Reference this guide in your cursor rules"),n.push("- Break implementation into small, focused commits");else if(b==="claude-code")n.push("## Claude Code Notes"),n.push(""),n.push("- Use extended thinking for complex logic"),n.push("- Ask for clarification on ambiguous requirements"),n.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")n.push("## General Notes"),n.push(""),n.push("- Use inline comments to guide generation"),n.push("- Review generated code carefully");return n.push(""),n.push("## Spec Definition"),n.push(""),n.push(D$($,"full")),n.join(`
|
|
2415
|
+
`)}function M7($){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(`
|
|
2416
|
+
`)}function KR($,b,n="generic-mcp"){switch(b){case"guide":return E7($,n);case"rules":return M7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as T7}from"node:fs/promises";import{createRequire as D7}from"node:module";import{dirname as N7,resolve as gj}from"node:path";import{pathToFileURL as F7}from"node:url";import vj from"node:vm";import rm from"typescript";async function y$($,b={}){let n=gj(process.cwd(),$),A=b.runtime??P7();try{let m=A==="bun"?await v7(n):await g7(n);return{modulePath:n,exports:m}}catch(m){throw Error(kj(n,m))}}async function MR($,b){let n=gj(process.cwd(),$);if(!await b.exists(n))return null;return y$(n)}async function UA($,b={}){return(await y$($,b)).exports}async function Pj($,b){let n=await UA($);return rj(n,$,b)}function kj($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function rj($,b,n){if(n.isValue($))return $;for(let A of n.instanceKeys??[])if(n.isValue($[A]))return $[A];for(let A of n.factoryKeys??[]){let m=$[A];if(typeof m!=="function")continue;let y=await m();if(n.isValue(y))return y}throw Error(`${n.description} module ${b} must export a supported instance or factory.`)}async function v7($){return await import(F7($).href)}async function g7($){return await k7($)??{}}function P7(){return typeof globalThis.Bun<"u"?"bun":"node"}var TR={formatModuleLoadError:kj,resolveAuthoredModuleValue:rj};async function k7($){let b=await T7($,"utf-8"),n=rm.transpileModule(b,{compilerOptions:{module:rm.ModuleKind.CommonJS,target:rm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),A={},m={exports:A},y=D7($),W=vj.createContext({module:m,exports:A,require:y,__dirname:N7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new vj.Script(n.outputText,{filename:$}).runInContext(W),m.exports}var oj={};f(oj,{renderOnboardingGuides:()=>hm,listOnboardingTracks:()=>KA,getOnboardingTrack:()=>cm,createOnboardingConnectArtifacts:()=>p7,buildOnboardingPlan:()=>l7,ONBOARDING_TRACKS:()=>fm});var fm=[{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 KA(){return fm}function cm($){return fm.find((b)=>b.id===$)}function hm($){return{agentGuide:r7($),humanGuide:c7($)}}function r7($){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 n of $.recommendations)b.push(...f7(n.track,n.reason));return b.join(`
|
|
2417
|
+
`)}function f7($,b){let n=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return[...n,""]}function c7($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((n,A)=>`${A+1}. \`${n}\``),"","## Track Guide",""];for(let n of $.recommendations)b.push(...h7(n.track,n.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let n of $.builderNextSteps)b.push(`- \`${n}\``);b.push("")}return b.join(`
|
|
2418
|
+
`)}function h7($,b){let n=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)n.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(n.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)n.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);n.push("","Commands:");for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return n.push("",`Packages: ${$.packages.map((A)=>`\`${A}\``).join(", ")}`,""),n}import{buildContext as d7}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as u7}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as o7}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function fj($,b,n,A){let m=d7({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:n,workspaceId:A}),y=await u7(o7(i7(b)),m);return{journeyContext:m,journeyPlan:y}}function cj($){if(!$||$.length===0)return[...KA()];return $.map((b)=>{let n=cm(b);if(!n)throw Error(`Unknown onboarding track: ${b}`);return n})}function hj($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function dj($){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 uj($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let n of KA()){if(n.starterExample.key===b)return n.starterExample;if(n.advancedExample?.key===b)return n.advancedExample}return}function dm($,b){return t7($,b.flatMap((n)=>n.track.connectSurfaces))}function i7($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((n)=>({defaultSurface:n.id,path:`/onboard/${n.id}`,routeId:`onboard-${n.id}`})),surfaces:Object.fromEntries($.map((n)=>[n.id,{commands:n.recommendedCommands.map((A,m)=>({commandId:`${n.id}-${m}`,intent:`Run ${A}`,title:A})),data:[{hydrateInto:"track",recipeId:`track-${n.id}`,source:{entityType:`onboarding.${n.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${n.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:n.id,title:n.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 t7($,b){return[...new Set([...$,...b])].sort()}async function l7($,b={}){let n=await s$($.fs,b),A=cj(b.selectedTracks),m=hj(n.config),W=[...await Promise.all(A.map(async(Y)=>{let G=await Jb($,{config:n.config,cwd:n.cwd,family:Y.reuseFamily,packageRoot:n.packageRoot,platform:Y.adoptionPlatform,query:Y.adoptionQuery,workspaceRoot:n.workspaceRoot});return{reason:G.reason,resolution:G,score:G.selected?.score??0,selected:!1,track:Y}}))].sort((Y,G)=>G.score-Y.score).map((Y,G)=>({...Y,selected:G===0})),w=W[0]?.track;if(!w)throw Error("No onboarding tracks are available.");let{journeyContext:j,journeyPlan:B}=await fj(w,A,n.workspaceRoot,n.packageRoot),S=uj(w,b.forcedExampleKey)??w.starterExample,Q=a7(["contractspec onboard",...w.recommendedCommands,"contractspec doctor"]),Z=dj(m),X={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:m,builderNextSteps:Z,config:n.config,cwd:n.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:j,journeyPlan:B,nextCommands:Q,packageRoot:n.packageRoot,primaryTrack:w,recommendations:W,selectedExample:S,workspaceRoot:n.workspaceRoot};return{...X,guides:hm(X)}}async function p7($,b){if(!b.config.connect?.enabled)return;let n=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,A=[b.agentGuidePath,b.humanGuidePath],m=await fb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot}),y=await ob($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((W)=>W.track.id).join(", ")}`,steps:b.recommendations.map((W)=>({commands:W.track.recommendedCommands,paths:A,summary:`Adopt ${W.track.title}`})),touchedPaths:A},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot});return{contextPack:{...m,affectedSurfaces:dm(m.affectedSurfaces,b.recommendations)},planPacket:{...y.planPacket,affectedSurfaces:dm(y.planPacket.affectedSurfaces,b.recommendations)}}}function a7($){return[...new Set($)]}var ij=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],e7=[...ij,{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 um($){return $==="minimal"?ij:e7}function om($){return $.filter((b)=>!b.dev)}function im($){return $.filter((b)=>b.dev)}import{exec as s7}from"node:child_process";import{promisify as $Z}from"node:util";var bZ=$Z(s7),nZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function bC($,b,n=nZ){let A=um(b.mode),m=om(A),y=im(A),W=[],w=[],j=[],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),X=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),Y=a$(b.workspaceRoot),G=m.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),V=y.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let J=[...G,...V];return{success:!0,installed:J.map((U)=>({name:U.name,action:"installed",message:`Would install: ${U.description}`,dev:U.dev})),skipped:w,errors:[],summary:`Dry run: would install ${J.length} package(s), skip ${w.length}.`}}if(!b.skipPrompts&&(G.length>0||V.length>0)){let J=G.length+V.length;if(!await n.confirm(`Install ${J} package(s) using ${Y}?`))return{success:!0,installed:[],skipped:[...w,...G.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(G.length>0){let J=await tj(G,Y,b.workspaceRoot,!1);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}if(V.length>0){let J=await tj(V,Y,b.workspaceRoot,!0);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}let O=j.length===0,K=O?`Successfully installed ${W.length} package(s), skipped ${w.length}.`:`Installed ${W.length}, skipped ${w.length}, failed ${j.length}.`;return{success:O,installed:W,skipped:w,errors:j,summary:K}}async function tj($,b,n,A){let m=[],y=$.map((W)=>W.version?`${W.name}@${W.version}`:W.name);try{let w=`${hy(b,A)} ${y.join(" ")}`;await bZ(w,{cwd:n,timeout:120000});for(let j of $)m.push({name:j.name,action:"installed",message:j.description,dev:A})}catch(W){let w=W instanceof Error?W.message:String(W);for(let j of $)m.push({name:j.name,action:"error",message:`Failed to install: ${w}`,dev:A})}return m}async function nC($,b){let n=$.join(b,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A);return"@contractspec/lib.contracts-spec"in{...m.dependencies,...m.devDependencies}}catch{return!1}}function AC($){let b=um($),n=[];n.push(`ContractSpec ${$} installation:`),n.push("");let A=om(b);if(A.length>0){n.push("Dependencies:");for(let y of A)n.push(` • ${y.name} - ${y.description}`)}let m=im(b);if(m.length>0){n.push(""),n.push("Dev Dependencies:");for(let y of m)n.push(` • ${y.name} - ${y.description}`)}return n.join(`
|
|
2419
|
+
`)}import{RegeneratorService as AZ}from"@contractspec/lib.contracts-spec/regenerator";function SC($){return new AZ({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class _A{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,n;try{n=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(A){throw Error(`Registry request failed: ${b} (${A instanceof Error?A.message:String(A)})`)}if(!n.ok){let A=await n.text().catch(()=>"");throw Error(`Registry request failed: ${n.status} ${n.statusText} ${A}`)}return await n.json()}}function tm($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function ZC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Adding spec to registry: ${$}`,{registryUrl:m}),await new _A({registryUrl:m}).getJson(`/specs/add?path=${encodeURIComponent($)}`),A.info("Spec added to registry successfully")}async function XC($,b){let{logger:n}=b,A=tm($.registryUrl);n.info("Listing specs from registry",{registryUrl:A});let m=new _A({registryUrl:A}),y=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",W=await m.getJson(`/specs${y}`);return n.info(`Found ${W.length} specs`),W}async function YC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Searching registry: ${$}`,{registryUrl:m});let W=await new _A({registryUrl:m}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return A.info(`Found ${W.length} results`),W}class mZ{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:n}=$,A=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${A.join(", ")}...`);try{let m=this.fs.join(n,b.rulesDir??".rules");if(!await this.fs.exists(m))return{success:!1,files:[],errors:[`Rules directory not found: ${m}`]};let W=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${W}`);let w=[];for(let j of A){let B=this.getTargetFileName(j);if(B){let S=this.fs.join(n,B);w.push(S)}}return{success:!0,files:w,logs:[`Successfully synchronized rules to ${w.length} targets.`]}}catch(m){let y=m instanceof Error?m.message:String(m);return this.logger.error(`Rule synchronization failed: ${y}`),{success:!1,files:[],errors:[y]}}}async generateConfig($){let{config:b}=$,n={rules:(b.rules??[]).map((A)=>this.fs.join(b.rulesDir??".rules",A)),targets:$.targets||b.targets};return JSON.stringify(n,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 zA($,b,n,A){let m=$n(b,n),y=yZ(n);if(y.test($))return $.replace(y,m);if(A&&lm($)===lm(A))return m;return`${m}${$}`}function $n($,b){let n=lm($);return`${b.startMarker}
|
|
2325
2420
|
${b.note}
|
|
2326
|
-
${
|
|
2421
|
+
${n}
|
|
2327
2422
|
${b.endMarker}
|
|
2328
|
-
`}function
|
|
2329
|
-
`).trimEnd()}function y7($){return new RegExp(`${Vy($.startMarker)}[\\s\\S]*?${Vy($.endMarker)}(?:\\r?\\n)?`)}function Vy($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var B7="<!-- contractspec:init:agents:start -->",S7="<!-- contractspec:init:agents:end -->",Q7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Jy={endMarker:S7,note:Q7,startMarker:B7};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 Z7,generateBiomePreset as G7}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=Z7("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,G7("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 X7="<!-- contractspec:init:usage:start -->",Y7="<!-- contractspec:init:usage:end -->",H7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Ky={endMarker:Y7,note:H7,startMarker:X7};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 q7={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 MR($,b,A=q7){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 O7($,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 O7($,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 V7}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as J7}from"path";async function uR($,b){let{fs:A}=b,m=J7(process.cwd(),$);if(!await A.exists(m))return{valid:!1,errors:[`Blueprint file not found: ${m}`]};try{let n=await n$(m),W=K7(n.exports),w=V7(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 K7($){let b=Object.values($).filter(_7);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function _7($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as U7,dirname as Nn,join as ob}from"path";async function tR($,b,A,m,n){let{fs:W}=n,w=m.implementationPath;if(!w){let S=Nn($),Q=U7($,".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 z7,validateBuilderReadinessReport as L7,validateBuilderWorkspace as R7,validateBuilderWorkspaceSnapshot as C7}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as I7,validateExternalPatchProposal as E7,validateProviderRoutingPolicy as M7,validateRuntimeTarget as x7}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as T7,validateLayoutSlots as D7}from"@contractspec/lib.surface-runtime/spec";async function bC($,b){if(!k7($.specType))return{valid:!0,errors:[],warnings:[]};let A=l7($.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"?N7(W):$.specType==="builder-spec"?F7(W):v7(W);return{valid:n.length===0&&w.errors.length===0,errors:[...n,...w.errors],warnings:w.warnings.map((j)=>`[${$.filePath}] ${j}`)}}function N7($){let b=[],A=[],m=g7($,P7);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{D7(w)}catch(j){b.push(`[${n.exportName}] ${j instanceof Error?j.message:String(j)}`)}for(let j of T7(w).warnings)A.push(`[${n.exportName}] ${j}`)}}return{errors:b,warnings:A}}function F7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(r7(W)){m+=1,b.push(...Z0(n,R7(W)));continue}if(f7(W)){m+=1,b.push(...Z0(n,z7(W)));continue}if(h7(W)){m+=1,b.push(...Z0(n,L7(W)));continue}if(c7(W))m+=1,b.push(...Z0(n,C7(W)))}if(m===0)A.push(Fn("builder-spec","builder"));return{errors:b,warnings:A}}function v7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(d7(W)){m+=1,b.push(...G0(n,x7(W)));continue}if(u7(W)){m+=1,b.push(...G0(n,M7(W)));continue}if(o7(W)){m+=1,b.push(...G0(n,I7(W)));continue}if(i7(W))m+=1,b.push(...G0(n,E7(W)))}if(m===0)A.push(Fn("provider-spec","provider"));return{errors:b,warnings:A}}function g7($,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 k7($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function P7($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function r7($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function f7($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function h7($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function c7($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function d7($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function u7($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function o7($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function i7($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function l7($){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 t7}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as p7}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as a7}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as e7}from"@contractspec/module.workspace";async function zy($,b={}){let A=[],m=[],n;if(!b.skipStructure){n=e7($),A.push(...n.errors),m.push(...n.warnings);let W=await s7($);A.push(...W.errors),m.push(...W.warnings)}return{valid:A.length===0,structureResult:n,errors:A,warnings:m,code:$.sourceBlock}}async function BC($,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 SC($,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 s7($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await n$($.filePath);if($.specType==="app-config"){let n=$Z(b.exports,$),W=t7(n);return{errors:W.errors.map((w)=>Uy(w)),warnings:[...W.warnings,...W.info].map((w)=>Uy(w))}}if($.specType==="feature"){let n=bZ(b.exports,$),W=p7(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=AZ(b.exports,$),m=a7(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 $Z($,b){return vn($,b.exportName,mZ)}function bZ($,b){return vn($,b.exportName,nZ)}function AZ($,b){return vn($,b.exportName,WZ)}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 mZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function nZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function WZ($){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 HC($,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 jZ(W),j=await yZ(A.connections,n),y=await BZ(A.translationCatalog,n),B=await SZ(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 jZ($){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 yZ($,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 BZ($,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 SZ($){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}=QZ(n);if(!W)continue;let j=Y0(process.cwd(),W);try{let y=await n$(j),B=ZZ(y.exports,w);if(B)await B(m)}catch(y){console.warn(`Failed to load registrar from ${j}: ${y}`)}}return m}function QZ($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),m=b?.trim()??null,n=A?.trim();return{modulePath:m,exportName:n}}function ZZ($,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 CC($,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 GZ}from"ai";var XZ=`
|
|
2423
|
+
`}function lm($){return $.replace(/\r\n/g,`
|
|
2424
|
+
`).trimEnd()}function yZ($){return new RegExp(`${lj($.startMarker)}[\\s\\S]*?${lj($.endMarker)}(?:\\r?\\n)?`)}function lj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var WZ="<!-- contractspec:init:agents:start -->",wZ="<!-- contractspec:init:agents:end -->",jZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",pj={endMarker:wZ,note:jZ,startMarker:WZ};async function pm($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"AGENTS.md");try{let y=await $.exists(m),W=Bw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:m,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(m,zA(w,W,pj,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,$n(W,pj)),{target:"agents-md",filePath:m,action:"created",message:"Created AI agent guide"}}catch(y){return{target:"agents-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}import{generateArtifactsForAudience as BZ,generateBiomePreset as SZ}from"@contractspec/biome-config";async function am($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"biome.jsonc"),y=$.join(A,".contractspec","biome"),W=$.join(y,"plugins"),w=$.join(y,"ai"),j=BZ("consumer");try{let B=await $.exists(m);if(B&&b.interactive){if(!await n.confirm(`${m} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:m,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(W),await $.mkdir(w),await $.writeFile(m,SZ("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(j.plugins))await $.writeFile($.join(W,S),Q);return await $.writeFile($.join(w,"consumer.md"),j.aiRules),{target:"biome-config",filePath:m,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:m,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function em($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".contractsrc.json");try{let y=await $.exists(m),W=Wb(b);if(y){let w=await $.readFile(m),j=a(w);if(!j)return{target:"cli-config",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=b$(j,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(m,N(D0(B,S)))}else await $.writeFile(m,N(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,N(W)),{target:"cli-config",filePath:m,action:"created",message:"Created CLI configuration"}}catch(y){return{target:"cli-config",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function sm($,b,n){let A=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(A,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=jw(b);if(W)if(b.interactive){if(!await n.confirm(`${m} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:m,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:m,action:"skipped",message:"File already exists"};return await $.writeFile(m,w),{target:"cursor-rules",filePath:m,action:W?"merged":"created",message:W?"Updated Cursor rules":"Created Cursor rules"}}catch(y){return{target:"cursor-rules",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function $y($,b,n){let A=ln();try{let m=await $.exists(A),y=ww();if(b.interactive){if(!await n.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(A),B=a(j);if(!B)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let S=b$(B,y);return await $.writeFile(A,N(S)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(A,N(y)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:A,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function by($,b,n){let A=$.join(b.workspaceRoot,".cursor"),m=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=Mb();if(W){let j=await $.readFile(m),B=a(j);if(!B)return{target:"mcp-cursor",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=b$(B,w);return await $.writeFile(m,N(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,N(w)),{target:"mcp-cursor",filePath:m,action:"created",message:"Created Cursor MCP configuration"}}catch(y){return{target:"mcp-cursor",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}var QZ="<!-- contractspec:init:usage:start -->",ZZ="<!-- contractspec:init:usage:end -->",XZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:ZZ,note:XZ,startMarker:QZ};async function ny($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"USAGE.md");try{let y=await $.exists(m),W=Sw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:m,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(m,zA(w,W,aj,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,$n(W,aj)),{target:"usage-md",filePath:m,action:"created",message:"Created usage guide"}}catch(y){return{target:"usage-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function Ay($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=tn(b);if(w){let B=await $.readFile(y),S=a(B);if(!S)return{target:"vscode-settings",filePath:y,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=b$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,N(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,N(j)),{target:"vscode-settings",filePath:y,action:"created",message:"Created VS Code settings"}}catch(W){return{target:"vscode-settings",filePath:y,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var YZ={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((n)=>n.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((n)=>n.selected!==!1).map((n)=>n.value),input:async($,b)=>b??""},GZ={"agents-md":pm,"biome-config":am,"cli-config":em,"cursor-rules":sm,"mcp-claude":$y,"mcp-cursor":by,"usage-md":ny,"vscode-settings":Ay},HZ={findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$};async function bx($,b,n=YZ,A={}){let m=[],y=b.targets.length>0?b.targets:xb,W={...HZ,...A.workspace},w={...GZ,...A.targets},j=A.setupGitignore??ZA,B=b.workspaceRoot,S=W.findWorkspaceRoot(B),Q=b.packageRoot??W.findPackageRoot(B),Z=b.isMonorepo??W.isMonorepo(S),X=b.packageName??(Z?W.getPackageName(Q):void 0),Y=await ej($,[Q,S]),G=b.preset??Eb(Y);if(b.interactive&&!b.preset)G=await n.select("Select initialization preset:",$w.map((g)=>({value:g,label:bw[g],description:nw[g],selected:g===G})));let V=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)V=await n.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${X??Q})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${S})`,description:"Create config files at the workspace root"}]);let K=Z&&V==="package"?Q:S,J=await ej($,[K]),U={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:V,packageName:X,preset:G,builderApiBaseUrl:b.builderApiBaseUrl??J?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??J?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??J?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??J?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??J?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??J?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??J?.connect?.studio?.queue},H=Aw(G,y);if(b.interactive)H=await n.multiSelect("Select components to configure:",xb.map((g)=>({value:g,label:sW[g],selected:H.includes(g)})));let q=U.projectName;if(b.interactive&&!q){let g=V==="package"&&X?X:K.split("/").pop()??"my-project";q=await n.input("Project name:",g)}let _=U.builderApiBaseUrl;if(b.interactive&&G.startsWith("builder-"))_=await n.input("Builder API base URL:",_??"https://api.contractspec.io");let{builderLocalRuntimeId:z,builderLocalGrantedTo:L}=U;if(b.interactive&&(G==="builder-local"||G==="builder-hybrid"))z=await n.input("Default local runtime target id:",z??"rt_local_daemon"),L=await n.input("Default local runtime grant target:",L??"local:operator");let C={...U,projectName:q,targets:H,builderApiBaseUrl:_,builderLocalRuntimeId:z,builderLocalGrantedTo:L};for(let g of H){let iA=await qZ($,g,C,n,w);m.push(iA)}let D=await j($,{behavior:C.gitignoreBehavior,interactive:C.interactive,patterns:Ww({preset:G}),prompts:n,root:S});if(C.gitignoreBehavior!=="skip"||D.action!=="skipped")m.push(D);let F=m.filter((g)=>g.action!=="error").length,E=m.filter((g)=>g.action==="error").length,r=Z?` (${V} level)`:"";return{success:E===0,preset:G,files:m,summary:`Setup complete${r}: ${F} configured, ${E} failed.`,nextSteps:yw(C)}}async function qZ($,b,n,A,m){let y=m[b];if(y)return y($,n,A);return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}async function ej($,b){for(let n of b){let A=$.join(n,".contractsrc.json");if(!await $.exists(A))continue;let m=a(await $.readFile(A));if(m)return m}return null}import{validateBlueprint as OZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as VZ}from"path";async function Hx($,b){let{fs:n}=b,A=VZ(process.cwd(),$);if(!await n.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let m=await y$(A),y=JZ(m.exports),W=OZ(y);return{spec:y,report:W,valid:W.valid,errors:W.errors.map((w)=>`[${w.code}] ${w.path}: ${w.message}`)}}catch(m){return{valid:!1,errors:[m instanceof Error?m.message:String(m)]}}}function JZ($){let b=Object.values($).filter(UZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function UZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as KZ,dirname as my,join as bn}from"path";async function Jx($,b,n,A,m){let{fs:y}=m,W=A.implementationPath;if(!W){let S=my($),Q=KZ($,".ts"),Z=[bn(S,Q.replace(".contracts",".handler")+".ts"),bn(S,Q.replace(".presentation","")+".tsx"),bn(S,Q.replace(".form",".form")+".tsx"),bn(my(S),"handlers",Q.replace(".contracts",".handler")+".ts"),bn(my(S),"components",Q.replace(".presentation","")+".tsx")];for(let X of Z)if(await y.exists(X)){W=X;break}}if(!W||!await y.exists(W))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let w=await y.readFile(W),B=await new On(n).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as _Z,validateBuilderReadinessReport as zZ,validateBuilderWorkspace as LZ,validateBuilderWorkspaceSnapshot as RZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as CZ,validateExternalPatchProposal as xZ,validateProviderRoutingPolicy as IZ,validateRuntimeTarget as EZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as MZ,validateLayoutSlots as TZ}from"@contractspec/lib.surface-runtime/spec";async function Rx($,b){if(!gZ($.specType))return{valid:!0,errors:[],warnings:[]};let n=iZ($.filePath),A=[`${n}/package.json`,`${n}/README.md`,`${n}/src/index.ts`,$.filePath],m=[];for(let w of A)if(!await b.exists(w))m.push(`Missing package scaffold file: ${w}`);if(m.length>0)return{valid:!1,errors:m,warnings:[]};let y;try{y=(await y$($.filePath)).exports}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)],warnings:[]}}let W=$.specType==="module-bundle"?DZ(y):$.specType==="builder-spec"?NZ(y):FZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function DZ($){let b=[],n=[],A=vZ($,PZ);if(A.length===0)return n.push(yy("module-bundle","bundle")),{errors:b,warnings:n};for(let m of A){let y=Object.values(m.value.surfaces);for(let W of y){try{TZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of MZ(W).warnings)n.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:n}}function NZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(kZ(y)){A+=1,b.push(...LA(m,LZ(y)));continue}if(rZ(y)){A+=1,b.push(...LA(m,_Z(y)));continue}if(fZ(y)){A+=1,b.push(...LA(m,zZ(y)));continue}if(cZ(y))A+=1,b.push(...LA(m,RZ(y)))}if(A===0)n.push(yy("builder-spec","builder"));return{errors:b,warnings:n}}function FZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(hZ(y)){A+=1,b.push(...RA(m,EZ(y)));continue}if(dZ(y)){A+=1,b.push(...RA(m,IZ(y)));continue}if(uZ(y)){A+=1,b.push(...RA(m,CZ(y)));continue}if(oZ(y))A+=1,b.push(...RA(m,xZ(y)))}if(A===0)n.push(yy("provider-spec","provider"));return{errors:b,warnings:n}}function vZ($,b){return Object.entries($).filter(([n,A])=>n!=="__esModule"&&b(A)).map(([n,A])=>({exportName:n,value:A}))}function LA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function RA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function gZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function PZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function kZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function rZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function fZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function cZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function hZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function dZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function uZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function oZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function iZ($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function yy($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as tZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as lZ}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as pZ}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as aZ}from"@contractspec/module.workspace";async function $1($,b={}){let n=[],A=[],m;if(!b.skipStructure){m=aZ($),n.push(...m.errors),A.push(...m.warnings);let y=await eZ($);n.push(...y.errors),A.push(...y.warnings)}return{valid:n.length===0,structureResult:m,errors:n,warnings:A,code:$.sourceBlock}}async function Nx($,b={}){return Promise.all($.map(async(n)=>({spec:n,...await $1(n,b)})))}async function l$($,b,n={}){let{fs:A}=b;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let y=await A.readFile($),W=[],w=[],j=void 0;if(!n.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await $1(S,n);j=Q.structureResult,W.push(...Q.errors),w.push(...Q.warnings)}}return{valid:W.length===0,structureResult:j,errors:W,warnings:w,code:y}}async function Fx($,b,n={}){let A=new Map;for(let m of $){let y=await l$(m,b,n);A.set(m,y)}return A}async function eZ($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await y$($.filePath);if($.specType==="app-config"){let m=sZ(b.exports,$),y=tZ(m);return{errors:y.errors.map((W)=>sj(W)),warnings:[...y.warnings,...y.info].map((W)=>sj(W))}}if($.specType==="feature"){let m=$2(b.exports,$),y=lZ(m);return{errors:y.issues.filter((W)=>W.level==="error").map((W)=>CA(W)),warnings:y.issues.filter((W)=>W.level!=="error").map((W)=>CA(W))}}let n=b2(b.exports,$),A=pZ(n);return{errors:A.issues.filter((m)=>m.level==="error").map((m)=>CA(m)),warnings:A.issues.filter((m)=>m.level!=="error").map((m)=>CA(m))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function sZ($,b){return Wy($,b.exportName,n2)}function $2($,b){return Wy($,b.exportName,A2)}function b2($,b){return Wy($,b.exportName,m2)}function Wy($,b,n){if(b&&n($[b]))return $[b];let A=Object.values($).find(n);if(!A)throw Error("Expected authored module to export a compatible spec value.");return A}function n2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function A2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function m2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function sj($){let b=$.code?`[${$.code}] `:"",n=$.path?`${$.path}: `:"";return`${b}${n}${$.message}`}function CA($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as y2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as jy}from"fs/promises";import{resolve as xA}from"path";async function fx($,b,n,A){let{fs:m}=A,y=xA(process.cwd(),b);if(!await m.exists(y))return{valid:!1,errors:[`Tenant config file not found: ${y}`]};try{let W=await W2(y),w=await w2(n.connections,m),j=await j2(n.translationCatalog,m),B=await B2(n.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=y2($,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 W2($){if($.endsWith(".json")){let A=await jy($,"utf-8"),m=JSON.parse(A);if(!b1(m))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return m}let b=await y$($),n=Object.values(b.exports).filter(b1);if(n.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return n[0]}function b1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function y1($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((n)=>n.trim()).filter(Boolean)}async function w2($,b){let n=y1($);if(!n.length)return[];let A=[];for(let m of n){let y=xA(process.cwd(),m);if(!await b.exists(y)){console.warn(`Warning: Connection file not found: ${y}`);continue}if(y.endsWith(".json")){let w=await jy(y,"utf-8"),j=JSON.parse(w);A.push(...wy(j));continue}let W=await y$(y);A.push(...wy(W.exports))}return A}function wy($){if(Array.isArray($)){let b=$.filter(n1);if(b.length)return b}if(n1($))return[$];if($&&typeof $==="object"){let n=Object.values($).flatMap((A)=>wy(A));if(n.length)return n}return[]}function n1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function j2($,b){if(!$)return;let n=xA(process.cwd(),$);if(!await b.exists(n))return;if(n.endsWith(".json")){let y=await jy(n,"utf-8"),W=JSON.parse(y);if(A1(W))return m1(W);return}let A=await y$(n),m=Object.values(A.exports).filter(A1);if(m.length===0)return;return m1(m[0])}function A1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function m1($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function B2($){let b=y1($);if(!b.length)return;let{IntegrationSpecRegistry:n}=await import("@contractspec/lib.contracts-integrations"),A=new n;for(let m of b){let{modulePath:y,exportName:W}=S2(m);if(!y)continue;let w=xA(process.cwd(),y);try{let j=await y$(w),B=Q2(j.exports,W);if(B)await B(A)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return A}function S2($){if(!$)return{modulePath:null};let[b,n]=$.split("#"),A=b?.trim()??null,m=n?.trim();return{modulePath:A,exportName:m}}function Q2($,b){if(b){let n=$[b];if(typeof n==="function")return n;return}if(typeof $.default==="function")return $.default;for(let n of Object.values($))if(typeof n==="function")return n;return}async function ex($,b,n={},A){let{fs:m,logger:y}=$,W=await m.glob({pattern:n.pattern}),w=n.outputDirs?.length?n.outputDirs:[void 0],j=[],B=A?.validate??((Q)=>l$(Q,{fs:m,logger:y})),S=A?.build??((Q,Z)=>yb(Q,{fs:m,logger:y},Z?{...b,outputDir:Z}:b,{...n.buildOptions??{},outputDir:Z}));for(let Q of W)for(let Z of w){let X={specPath:Q,outputDir:Z};if(n.validate)try{X.validation=await B(Q)}catch(Y){X.error={phase:"validate",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}if(!n.dryRun)try{X.build=await S(Q,Z)}catch(Y){X.error={phase:"build",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}else y.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});j.push(X)}return{specs:W,runs:j}}import{generateText as Z2}from"ai";var X2=`
|
|
2330
2425
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2331
2426
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2332
2427
|
|
|
@@ -2344,7 +2439,7 @@ Generate scenarios covering:
|
|
|
2344
2439
|
- Happy path (valid input, successful execution)
|
|
2345
2440
|
- Edge cases (boundary values, optional fields)
|
|
2346
2441
|
- Error cases (invalid input, business rule violations)
|
|
2347
|
-
`.trim();class
|
|
2442
|
+
`.trim();class Y2{logger;defaultModel;generateTextImpl;constructor($,b,n=Z2){this.logger=$;this.defaultModel=b;this.generateTextImpl=n}async generateTests($,b={}){let n=b.model??this.defaultModel;if(!n)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let A=`
|
|
2348
2443
|
Generate a TestSpec for the following Operation:
|
|
2349
2444
|
|
|
2350
2445
|
\`\`\`json
|
|
@@ -2353,23 +2448,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2353
2448
|
|
|
2354
2449
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2355
2450
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2356
|
-
`.trim();try{let{text:
|
|
2357
|
-
`)}function
|
|
2358
|
-
`)}function
|
|
2359
|
-
`);for(let
|
|
2360
|
-
`)}function
|
|
2451
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:n,system:X2,prompt:A});this.logUsage(y);let W=this.parseResponse(m);return this.enrichSpec(W,$)}catch(m){throw this.logger.error("Failed to generate tests",{error:m}),m}}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 n={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},A={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:n,target:A,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 W1}from"@contractspec/lib.contracts-spec";import{TestRunner as w1}from"@contractspec/lib.contracts-spec/tests";import{resolve as By}from"path";async function WI($,b){let n=new w1({registry:b}),A=[],m=0,y=0;for(let W of $){let w=await n.run(W);A.push(w),m+=w.passed,y+=w.failed}return{results:A,passed:m,failed:y}}async function wI($,b,n){let{logger:A}=n,m;if(b.registry)m=await H2(By(b.registry));else m=new W1,A.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let y=new w1({registry:m}),W=[],w=!0;for(let j of $)try{let B=By(j),S=await UA(B),Q=j1(S);if(Q.length===0){A.warn(`No TestSpec exports found in ${j}`);continue}for(let Z of Q){A.info(`Running ${Z.meta.key}...`);let X=await y.run(Z);if(W.push(X),X.failed>0)w=!1,A.error(`${Z.meta.key} failed (${X.failed}/${X.scenarios.length})`);else A.info(`${Z.meta.key} passed (${X.passed}/${X.scenarios.length})`)}}catch(B){A.error(`Failed to load/run spec ${j}: ${B instanceof Error?B.message:String(B)}`),w=!1}return{results:W,passed:w}}async function jI($,b){let n=[];for(let A of $)try{let m=By(A),y=await UA(m),W=j1(y);n.push(...W)}catch(m){b.logger.warn(`Failed to load tests from ${A}: ${m instanceof Error?m.message:String(m)}`)}return n}function j1($){let b=[];for(let n of Object.values($))if(G2(n))b.push(n);return b}function G2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function H2($){return Pj($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof W1,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as nn}from"@contractspec/module.workspace";import{IndentationText as q2,Node as Xb,Project as O2,QuoteKind as V2,SyntaxKind as J2}from"ts-morph";function U2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function HI($,b,n={}){let{fs:A,logger:m}=b;if(!await A.exists($))return{specPath:$,specInfo:U2($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let W=await A.readFile($),w;if(n.content!==void 0)w=n.content;else if(n.fields?.length)w=K2(W,n.fields);else return{specPath:$,specInfo:nn(W,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!n.skipValidation){await A.writeFile($,w);let j=await l$($,b);if(j.errors.length>0)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:j.errors,warnings:j.warnings};if(j.warnings.length>0&&!n.allowWarnings)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:j.warnings};return m.info(`Updated spec: ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:j.warnings}}return await A.writeFile($,w),m.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:[]}}function K2($,b){let A=new O2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:q2.TwoSpaces,quoteKind:V2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=z2(A);if(!m)return $;for(let y of b)_2(m,y);return A.getFullText()}function _2($,b){let n=b.key.split(".").map((w)=>w.trim()).filter(Boolean);if(n.length===0)return;let A=$;for(let w of n.slice(0,-1)){if(!A.getProperty(w))A.addPropertyAssignment({name:w,initializer:"{}"});let B=A.getPropertyOrThrow(w);if(!Xb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!Xb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(J2.ObjectLiteralExpression);if(!Q)return;A=Q}let m=n[n.length-1];if(!m)return;let y=L2(b.value),W=A.getProperty(m);if(W&&Xb.isPropertyAssignment(W)){W.setInitializer(y);return}A.addPropertyAssignment({name:m,initializer:y})}function z2($){for(let b of $.getVariableDeclarations()){let n=b.getInitializer();if(!n)continue;if(Xb.isObjectLiteralExpression(n))return n;if(Xb.isCallExpression(n)){let A=n.getArguments()[0];if(A&&Xb.isObjectLiteralExpression(A))return A}}return}function L2($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var z1={};f(z1,{getPackageUpgradeCommand:()=>O1,getDefaultVersioningConfig:()=>EA,getDefaultHooksConfig:()=>MA,applyGuidedUpgrade:()=>_1,applyConfigUpgrades:()=>q1,analyzeUpgrades:()=>IA,analyzeGuidedUpgrade:()=>Xy});import{GeneratedReleaseManifestSchema as U1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as N2,DEFAULT_CONTRACTSRC as F2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function B1($){return $.packages.map((b)=>{let n=b.version?`@${b.version}`:"";return`- ${b.name}${n} (${b.releaseType})`})}function S1($){return $.map((b)=>` - ${b}`)}function Sy($,b){return $.audiences.filter((n)=>b.includes(n.kind)).map((n)=>`- ${R2(n.kind)}: ${n.summary}`)}function Q1($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...B1($),...Sy($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));return b.join(`
|
|
2452
|
+
`)}function Z1($){let b=[`### ${$.summary}`,...B1($),...Sy($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`);return b.join(`
|
|
2453
|
+
`)}function X1($){let b=[`### ${$.summary}`,...Sy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2454
|
+
`);for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`),b.push(...S1(n.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let n of $.upgradeSteps)b.push(` - [${n.level}] ${n.title}: ${n.summary}`),b.push(...n.instructions.map((A)=>` - ${A}`))}return b.join(`
|
|
2455
|
+
`)}function Qy($){return["# Patch Notes","",...$.releases.map(Q1)].join(`
|
|
2361
2456
|
|
|
2362
|
-
`)}function
|
|
2457
|
+
`)}function Zy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[Z1(b),"",X1(b)])].join(`
|
|
2363
2458
|
|
|
2364
|
-
`)}function
|
|
2459
|
+
`)}function Y1($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...S1(b.instructions)].join(`
|
|
2365
2460
|
`)).join(`
|
|
2366
|
-
`)}function
|
|
2367
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2368
|
-
`)}function
|
|
2369
|
-
`),
|
|
2370
|
-
`),!0}async function
|
|
2371
|
-
`),!0}async function
|
|
2372
|
-
`),
|
|
2461
|
+
`)}function Yb($,b){let n=b.targetPackages.map((A)=>`${A.name}: ${A.currentVersion??"unknown"} -> ${A.targetVersion??"latest"}`).join(`
|
|
2462
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",n||"- No package version targets were inferred.","","Required steps:",Y1(b)].join(`
|
|
2463
|
+
`)}function R2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as H1,countUpgradePlanStepLevels as C2,createAgentPromptBundles as x2,dedupeUpgradePlanSteps as I2,sortReleaseManifest as G1}from"@contractspec/lib.contracts-spec";function E2($,b){if(b.length===0)return G1($);let n=new Map(b.map((A)=>[A.name,A.currentVersion??"0.0.0"]));return G1({...$,releases:$.releases.filter((A)=>A.packages.some((m)=>{let y=n.get(m.name);if(!y||!m.version)return!1;return H1(m.version,y)===1}))})}function An($,b,n,A){let m=E2($,b),y=M2(m,b),W=I2(m.flatMap((S)=>S.upgradeSteps)),w=C2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=x2(j,n,A);return{...j,agentPrompts:B}}function M2($,b){let n=new Map(b.map((m)=>[m.name,m.currentVersion])),A=new Map;for(let m of $)for(let y of m.packages){let W=n.get(y.name),w=A.get(y.name);if(!w){A.set(y.name,{name:y.name,currentVersion:W,targetVersion:y.version});continue}if(y.version&&w.targetVersion&&H1(y.version,w.targetVersion)===1)w.targetVersion=y.version}return Array.from(A.values()).sort((m,y)=>m.name.localeCompare(y.name))}async function IA($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=a$(y);A.info("Analyzing available upgrades...",{workspaceRoot:y,packageRoot:m,packageManager:W});let w=await T2(n,m),j=await D2(n,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function T2($,b){let n=$.join(b,"package.json");if(!await $.exists(n))return[];try{let A=await $.readFile(n),m=JSON.parse(A),y=m.dependencies??{},W=m.devDependencies??{},w=[],j={...y,...W};for(let[B,S]of Object.entries(j))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))w.push({name:B,currentVersion:S,isDevDependency:!!W[B]});return w}catch{return[]}}async function D2($,b,n){let A=$.join(b,".contractsrc.json"),m=Cb({configRoot:b,workspaceRoot:n});if(!await $.exists(A))return[];try{let y=await $.readFile(A),W=JSON.parse(y),w=[],j=W.$schema;if(!j||j!==m)w.push({key:"$schema",currentValue:j,suggestedValue:m,isNew:!j});if(!W.versioning)w.push({key:"versioning",currentValue:void 0,suggestedValue:EA(),isNew:!0});else if(W.versioning.integrateWithChangesets===void 0)w.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!W.hooks)w.push({key:"hooks",currentValue:void 0,suggestedValue:MA(),isNew:!0});if(!W.release)w.push({key:"release",currentValue:void 0,suggestedValue:V1(),isNew:!0});if(!W.upgrade)w.push({key:"upgrade",currentValue:void 0,suggestedValue:J1(),isNew:!0});return w}catch{return[]}}async function q1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=Cb({configRoot:m,workspaceRoot:y});if(b.dryRun)A.info("Dry run - no changes will be made");let w=n.join(m,".contractsrc.json");if(!await n.exists(w))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let j=await n.readFile(w),B=JSON.parse(j),S=0,Q=B.$schema;if(!Q||Q!==W)B.$schema=W,S++;if(!B.versioning)B.versioning=EA(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=MA(),S++;if(!B.release)B.release=V1(),S++;if(!B.upgrade)B.upgrade=J1(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await n.writeFile(w,JSON.stringify(B,null,2)+`
|
|
2464
|
+
`),A.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(j){let B=j instanceof Error?j.message:String(j);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function O1($,b,n){let A=n?b.map((m)=>`${m.name}@latest`).join(" "):b.map((m)=>m.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 EA(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function MA(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function V1(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function J1(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var v2="**/*.{ts,tsx,js,jsx,mjs,cjs}",K1=F2.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Xy($,b){let{fs:n}=$,A=c(b.workspaceRoot),m=I(b.workspaceRoot),y=await P2(n,A,m),W=await g2(n,A,m,b.manifestPaths??y.manifestPaths),w=await IA($,{workspaceRoot:A,dryRun:b.dryRun}),j=[b.agentTarget??y.defaultAgentTarget??"codex"],B=An(W.manifest,w.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),j,Yb),S=k2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:r2(S)}}async function _1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=await Xy($,b),W=[];if(!b.dryRun){for(let j of y.plan.steps){if(j.level!=="auto")continue;for(let B of j.autofixes??[])if(await f2(n,m,B))W.push(B.id)}A.info("Applied guided upgrade autofixes",{count:W.length,workspaceRoot:m})}let w=y.plan.steps.filter((j)=>j.level!=="auto");return{success:!0,packagesUpgraded:W.filter((j)=>j.startsWith("pkg:")).length,configSectionsUpgraded:W.filter((j)=>j.startsWith("config:")).length,summary:b.dryRun?`Would apply ${y.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${W.length} deterministic upgrade autofix(es)`,appliedAutofixes:W,remainingSteps:w,humanChecklist:y.humanChecklist,promptBundle:y.plan.agentPrompts[0],plan:y.plan,manifestPath:y.manifestPath}}async function g2($,b,n,A){let m=A??["generated/releases/upgrade-manifest.json"],y=Array.from(new Set([b,n]));for(let W of m){let w=W.startsWith("/")?[W]:y.map((j)=>$.join(j,W));for(let j of w){if(!await $.exists(j))continue;let B=U1.parse(JSON.parse(await $.readFile(j)));return{path:j,manifest:B}}}return{manifest:U1.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function P2($,b,n){for(let A of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(n,".contractsrc.json")]))){if(!await $.exists(A))continue;try{let m=JSON.parse(await $.readFile(A)),y=N2.safeParse(m);if(y.success)return{...K1,...y.data.upgrade}}catch{continue}}return K1}function k2($,b,n){let A=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;A.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 m=n.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})),y=[];if(A.length>0)y.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:A.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:A.map((S)=>S.packageName??""),autofixes:A});if(m.length>0)y.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:m.map((S)=>`${S.configPath} -> updated`),autofixes:m});let W=[...y,...$.steps],w=W.filter((S)=>S.level==="auto").length,j=W.filter((S)=>S.level==="assisted").length,B=W.filter((S)=>S.level==="manual").length;return{...$,steps:W,autofixCount:w,assistedCount:j,manualCount:B,agentPrompts:An({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),Yb).agentPrompts}}function r2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function f2($,b,n){switch(n.kind){case"package-json":return c2($,b,n);case"contractsrc":return h2($,b,n);case"import-rewrite":return d2($,b,n);case"codemod":return!1}}async function c2($,b,n){let A=$.join(b,"package.json");if(!await $.exists(A))return!1;let m=JSON.parse(await $.readFile(A)),y=n.dependencyType??"dependencies",W=m[y]??{};if(!n.packageName||!n.to||!W[n.packageName])return!1;return W[n.packageName]=n.to,m[y]=W,await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2465
|
+
`),!0}async function h2($,b,n){let A=$.join(b,".contractsrc.json"),m=await $.exists(A)?JSON.parse(await $.readFile(A)):{};if(!n.configPath)return!1;return u2(m,n.configPath,n.value),await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2466
|
+
`),!0}async function d2($,b,n){if(!n.from||!n.to)return!1;let A=await $.glob({pattern:n.path??v2,cwd:b,absolute:!0}),m=!1;for(let y of A){let W=await $.readFile(y);if(!W.includes(n.from))continue;await $.writeFile(y,W.split(n.from).join(n.to)),m=!0}return m}function u2($,b,n){let A=b.split("."),m=$;for(let W of A.slice(0,-1)){let w=m[W];if(!w||typeof w!=="object"||Array.isArray(w))m[W]={};m=m[W]}let y=A.at(-1);if(y)m[y]=n}import{existsSync as Yy,mkdirSync as o2,readFileSync as i2,renameSync as t2,statSync as l2,writeFileSync as p2}from"fs";import{dirname as a2,join as e2}from"path";var s2=".contractspec/verification-cache.json",L1=1;class R1{filePath;cache;isDirty=!1;constructor($,b){let n=b??process.cwd();this.filePath=$??e2(n,s2),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Yy(this.filePath))return;let $=i2(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==L1)return;for(let[n,A]of Object.entries(b.entries))this.cache.set(n,A)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=a2(this.filePath);if(!Yy($))o2($,{recursive:!0});let b={version:L1,entries:Object.fromEntries(this.cache.entries())},n=`${this.filePath}.tmp`;p2(n,JSON.stringify(b,null,2),"utf-8"),t2(n,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(Yy(this.filePath))$=l2(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function vI($,b){return new R1($,b)}class C1{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,n]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(n).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function PI(){return new C1}class x1{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 n=this.getStorageKey($);if(await this.store.update(n,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),n=this.keyIndex.has($);if(n)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return n}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 rI($){return new x1($)}import{createHash as $X}from"crypto";var I1={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function E1($){return $X("sha256").update($).digest("hex")}function M1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function bX($){try{let b=$.split("|"),n=new Map;for(let W of b){let[w,j]=W.split(":");if(w&&j)n.set(w,j)}let A=n.get("spec"),m=n.get("impl"),y=n.get("tier");if(!A||!m||!y)return null;return{specHash:A,implHash:m,tier:y,aiModelVersion:n.get("model")}}catch{return null}}function nX($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class T1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...I1,...b},this.stats={hits:0,misses:0}}createKey($,b,n,A){return{specHash:E1($),implHash:E1(b),tier:n,aiModelVersion:n==="ai_review"?A:void 0}}async lookup($){let b=M1($),n=await this.storage.get(b);if(!n)return this.stats.misses++,{hit:!1,reason:"not_found"};if(n.meta.expiresAt){let A=new Date(n.meta.expiresAt).getTime();if(Date.now()>A)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(n.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(n.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&n.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:n}}async store($,b,n={}){let A=M1($),m=nX($.tier,this.config),y={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+m).toISOString(),dependencies:n.dependencies??[],specName:n.specName,implPath:n.implPath}};await this.storage.set(A,y),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),n=0;for(let A of b){let m=await this.storage.get(A);if(!m)continue;if(m.meta.dependencies.includes($))await this.storage.delete(A),n++;if(m.meta.specName===$||m.meta.implPath===$)await this.storage.delete(A),n++}return n}async invalidateForSpec($){let b=await this.storage.keys(),n=0;for(let A of b){let m=bX(A);if(m&&m.specHash.startsWith($.substring(0,16)))await this.storage.delete(A),n++}return n}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 A of $){let m=await this.storage.get(A);if(m)b.push({key:A,createdAt:new Date(m.meta.createdAt).getTime()})}b.sort((A,m)=>A.createdAt-m.createdAt);let n=b.length-this.config.maxEntries;for(let A=0;A<n;A++){let m=b[A];if(m)await this.storage.delete(m.key)}}}function lI($,b){return new T1($,b)}import{generateVerificationPrompt as AX}from"@contractspec/lib.contracts-spec/llm";function mX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let j=JSON.parse(b[1]);return{compliant:j.passed??!1,confidence:(j.score??0)/100,findings:(j.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 n=[],A=$.split(`
|
|
2467
|
+
`),m="info";for(let j of A){let B=j.toLowerCase();if(B.includes("error")||B.includes("critical"))m="error";else if(B.includes("warning")||B.includes("should"))m="warning";else if(B.includes("info")||B.includes("note"))m="info";let S=j.match(/^[-*•]\s*(.+)$/),Q=j.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)n.push({category:"semantic",severity:m,message:Z})}}let y=n.some((j)=>j.severity==="error"),W=!y,w=y?0.3:n.length===0?0.9:0.7;return{compliant:W,confidence:w,findings:n,rawResponse:$}}async function D1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2373
2468
|
{
|
|
2374
2469
|
"passed": true,
|
|
2375
2470
|
"score": 50,
|
|
@@ -2386,16 +2481,16 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2386
2481
|
],
|
|
2387
2482
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2388
2483
|
}
|
|
2389
|
-
\`\`\``;try{let
|
|
2484
|
+
\`\`\``;try{let n=b.aiProvider??"anthropic";if(n==="anthropic"){let{anthropic:A}=await import("@ai-sdk/anthropic"),{generateText:m}=await import("ai");return(await m({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(n==="openai"){let{openai:A}=await import("@ai-sdk/openai"),{generateText:m}=await import("ai");return(await m({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: ${n}`)}catch(n){return`\`\`\`json
|
|
2390
2485
|
{
|
|
2391
2486
|
"passed": false,
|
|
2392
2487
|
"score": 0,
|
|
2393
2488
|
"issues": [
|
|
2394
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2489
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${n instanceof Error?n.message:"Unknown error"}" }
|
|
2395
2490
|
],
|
|
2396
2491
|
"summary": "AI verification encountered an error"
|
|
2397
2492
|
}
|
|
2398
|
-
\`\`\``}}async function
|
|
2493
|
+
\`\`\``}}async function mn($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=AX(n,A),w=await D1(W.taskPrompt,b),j=mX(w),B=j.findings.map((X)=>({severity:X.severity,category:"semantic",message:X.message,location:X.location?{file:X.location}:m?{file:m}:void 0,suggestion:X.suggestion})),S=Math.round(j.confidence*100),Q=j.compliant,Z=j.findings.filter((X)=>X.suggestion).map((X)=>X.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:n.meta.key,specVersion:n.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-y}}}function TA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];if(n.includes("console.log"))y.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(n.includes("// TODO")||n.includes("// FIXME"))y.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"&&!n.includes("auth"))y.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=y.filter((j)=>j.severity==="error").length===0?80:40,w=y.filter((j)=>j.severity==="error").length===0;return{tier:"ai_review",passed:w,score:W,issues:y,suggestions:y.filter((j)=>j.suggestion).map((j)=>j.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:w?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}function yX($,b){return`You are analyzing a code implementation against its specification.
|
|
2399
2494
|
|
|
2400
2495
|
## Spec Schema Fields
|
|
2401
2496
|
${$}
|
|
@@ -2442,43 +2537,43 @@ Match types:
|
|
|
2442
2537
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2443
2538
|
- "mismatch": Different meaning despite similar naming
|
|
2444
2539
|
- "missing": Spec field not found in implementation
|
|
2445
|
-
`}function
|
|
2446
|
-
`)}function
|
|
2447
|
-
`),
|
|
2448
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let
|
|
2449
|
-
`)}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
|
|
2450
|
-
`)}function
|
|
2451
|
-
`)}function
|
|
2452
|
-
`),
|
|
2453
|
-
`).trim()||void 0,B=
|
|
2454
|
-
${b.map((
|
|
2540
|
+
`}function WX($){let b=[],n=(A,m)=>{try{let W=A?._def?.shape;if(W&&typeof W==="function"){let w=W();for(let[j,B]of Object.entries(w)){let Q=B?._def?.typeName??"unknown";b.push(`- ${j}: ${String(Q).replace("Zod","").toLowerCase()} (${m})`)}}}catch{b.push(`- [unable to extract ${m} fields]`)}};if($.io.input)n($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))n($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2541
|
+
`)}function wX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let n=JSON.parse(b[1]);return{fieldMappings:(n.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 n.intentAlignment?.score==="number"?n.intentAlignment.score:50,issues:Array.isArray(n.intentAlignment?.issues)?n.intentAlignment.issues:[],suggestions:Array.isArray(n.intentAlignment?.suggestions)?n.intentAlignment.suggestions:[]},semanticIssues:(n.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 N1($,b={}){let{spec:n,implementationCode:A}=$,m=WX(n),y=yX(m,A),W=await D1(y,b);return wX(W)}async function jX($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=await mn($,b),w;if(b.aiApiKey)try{w=await N1($,b)}catch{}if(w){let j=[];for(let Z of w.fieldMappings)if(Z.match==="missing")j.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")j.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)j.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 w.intentAlignment.issues)j.push({severity:"warning",category:"semantic",message:Z});for(let Z of w.semanticIssues)j.push({severity:Z.severity,category:"semantic",message:Z.message,suggestion:Z.suggestion});W.issues=[...W.issues,...j];let B=w.fieldMappings.length,S=w.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(j.some((Z)=>Z.severity==="error"))W.passed=!1;W.suggestions=[...W.suggestions,...w.intentAlignment.suggestions]}return W.meta={...W.meta,duration:Date.now()-y},W}import{isEmitDeclRef as BX}from"@contractspec/lib.contracts-spec/operations";function SX($,b){let n=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),A=$.toLowerCase(),m=n.filter((B)=>A.includes(B)),y=n.length>0?m.length/n.length:0,W=b.key.toLowerCase().replace(/\s+/g,""),w=A.includes(W)||A.includes(`test('${b.key.toLowerCase()}'`)||A.includes(`it('${b.key.toLowerCase()}'`)||A.includes(`describe('${b.key.toLowerCase()}'`),j=y>=0.3||w;return{name:b.key,type:"scenario",passed:j,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:j?void 0:`Scenario keywords not found in implementation (${Math.round(y*100)}% coverage)`}}function QX($,b){let n=JSON.stringify(b.input),A=JSON.stringify(b.output),m=F1(b.input),y=F1(b.output),W=$.toLowerCase(),w=m.filter((X)=>W.includes(X.toLowerCase())),j=y.filter((X)=>W.includes(X.toLowerCase())),B=m.length>0?w.length/m.length:1,S=y.length>0?j.length/y.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${n.slice(0,100)}...; Output: ${A.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function F1($){let b=[];function n(A){if(typeof A==="string"&&A.length>2)b.push(A);else if(Array.isArray(A))A.forEach(n);else if(A&&typeof A==="object")Object.values(A).forEach(n)}return n($),b}function ZX($,b,n){let A=$.includes(b),m=n.http?$.includes(String(n.http)):!0,y=n.when??n.description,W=y.toLowerCase().split(/\s+/).filter((Q)=>Q.length>3),w=$.toLowerCase(),j=W.filter((Q)=>w.includes(Q)),B=W.length>0?j.length/W.length:1,S=A&&(m||B>=0.3);return{name:`Error: ${b}`,type:"error",passed:S,expected:`When: ${y}; Return: ${b} (HTTP ${n.http??400})`,details:S?void 0:!A?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function XX($,b){let n=b.sideEffects?.emits??[],A=[];for(let m of n){let y=BX(m)?m.ref.key:m.key,W=m.when,w=W.toLowerCase().split(/\s+/).filter((Z)=>Z.length>3),j=$.toLowerCase(),B=j.includes(y.toLowerCase()),S=w.filter((Z)=>j.includes(Z)),Q=w.length>0?S.length/w.length:1;A.push({name:`Event: ${y}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${y} when: ${W}`,details:!B?`Event '${y}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return A}function YX($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let n=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],A=$.toLowerCase(),m=n.some((y)=>A.includes(y));return{name:"Idempotency",type:"scenario",passed:m,expected:"Operation should be idempotent (safe to retry)",details:m?void 0:"No idempotency pattern found for idempotent operation"}}function DA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];for(let Y of b.acceptance?.scenarios??[])y.push(SX(n,Y));for(let Y of b.acceptance?.examples??[])y.push(QX(n,Y));for(let[Y,G]of Object.entries(b.io.errors??{}))y.push(ZX(n,Y,G));y.push(...XX(n,b));let W=YX(n,b);if(W)y.push(W);let w=y.filter((Y)=>!Y.passed).map((Y)=>({severity:Y.type==="error"?"error":"warning",category:Y.type==="scenario"?"scenario":Y.type==="example"?"scenario":"error_handling",message:Y.details??`${Y.type} not covered: ${Y.name}`,location:A?{file:A}:void 0,suggestion:Y.expected?`Expected: ${Y.expected}`:void 0})),j=y.filter((Y)=>Y.type==="scenario"),B=y.filter((Y)=>Y.type==="error"),S=y.filter((Y)=>Y.passed).length,Q=y.length>0?Math.round(S/y.length*100):100,Z=w.filter((Y)=>Y.severity==="error").length===0,X=y.filter((Y)=>!Y.passed&&Y.expected).map((Y)=>`${Y.name}: ${Y.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:w,suggestions:X,coverage:{scenarios:{total:j.length,covered:j.filter((Y)=>Y.passed).length},errors:{total:B.length,handled:B.filter((Y)=>Y.passed).length},fields:{total:y.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}import{isEmitDeclRef as GX}from"@contractspec/lib.contracts-spec/operations";function HX($){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 qX($){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 OX($,b){if(qX(b))return{name:"contracts_import",passed:!0};let n=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:n,details:n?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function VX($,b){if(!(b.io.input!==null||b.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 JX($){let b=/:\s*any\b|as\s+any\b|<any>/,n=$.split(`
|
|
2542
|
+
`),A=[];for(let m=0;m<n.length;m++){let y=n[m]??"";if(y.trim().startsWith("//")||y.trim().startsWith("*"))continue;if(b.test(y))A.push(m+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 UX($,b){let n=b.io.errors;if(!n||Object.keys(n).length===0)return{name:"error_handling",passed:!0};let A=Object.keys(n),m=[];for(let y of A)if(!$.includes(y))m.push(y);return{name:"error_handling",passed:m.length===0,details:m.length>0?`Missing error handling for: ${m.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function KX($,b){let n=b.sideEffects?.emits;if(!n||n.length===0)return{name:"event_emission",passed:!0};let A=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),m=n.map((W)=>{if(GX(W))return W.ref.key;return W.key}),y=m.filter((W)=>$.includes(W));return{name:"event_emission",passed:A&&y.length>0,details:!A?"No event emission pattern found":y.length===0?`Events not referenced: ${m.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function _X($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let n=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:n,details:n?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function zX($,b){let n=/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:n,details:n?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function yn($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[HX(n),OX(n,A),VX(n,b),JX(n),UX(n,b),KX(n,b),_X(n,b),zX(n,b)],W=y.filter((X)=>!X.passed).map((X)=>({severity:X.name==="no_any_type"?"warning":"error",category:X.name.includes("import")?"import":X.name.includes("export")?"export":"type",message:X.details??`Check failed: ${X.name}`,location:A?{file:A}:void 0,suggestion:X.suggestion})),w=y.filter((X)=>X.passed).length,j=Math.round(w/y.length*100),B=W.filter((X)=>X.severity==="error").length===0,S=y.filter((X)=>!X.passed&&X.suggestion).map((X)=>X.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=y.find((X)=>X.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:j,issues:W,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:y.length,implemented:w}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}var LX={verbose:!1},RX=["structure","behavior","ai_review"];class NA{config;constructor($={}){this.config={...LX,...$}}async verify($,b,n={}){let A=Date.now(),m=new Map,y=[],W={spec:$,implementationCode:b},w=n.tiers??["structure","behavior"];for(let Z of RX){if(!w.includes(Z))continue;let X;switch(Z){case"structure":X=yn(W);break;case"behavior":X=DA(W);break;case"ai_review":if(this.config.aiApiKey)X=await mn(W,this.config);else X=TA(W);break;default:continue}if(m.set(Z,X),y.push(...X.issues),n.failFast&&!X.passed)break}let j=Array.from(m.values()),B=j.every((Z)=>Z.passed),S=j.length>0?Math.round(j.reduce((Z,X)=>Z+X.score,0)/j.length):100,Q=this.generateSummary(j,y);return{passed:B,score:S,reports:m,allIssues:y,summary:Q,duration:Date.now()-A}}verifyStructure($,b,n){return yn({spec:$,implementationCode:b,implementationPath:n})}verifyBehavior($,b,n){return DA({spec:$,implementationCode:b,implementationPath:n})}async verifyAI($,b,n){let A={spec:$,implementationCode:b,implementationPath:n};if(this.config.aiApiKey)return mn(A,this.config);return TA(A)}quickVerify($,b){return yn({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[A,m]of $.reports){if(b.push(`## ${this.formatTierName(A)}`),b.push(""),b.push(`**Status:** ${m.passed?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${m.score}/100`),b.push(""),m.issues.length>0){b.push("### Issues"),b.push("");for(let y of m.issues){let W=y.severity==="error"?"❌":y.severity==="warning"?"⚠️":"ℹ️";if(b.push(`${W} **${y.category}**: ${y.message}`),y.suggestion)b.push(` - Suggestion: ${y.suggestion}`)}b.push("")}if(m.coverage.scenarios.total>0)b.push(`**Scenarios:** ${m.coverage.scenarios.covered}/${m.coverage.scenarios.total}`);if(m.coverage.errors.total>0)b.push(`**Errors handled:** ${m.coverage.errors.handled}/${m.coverage.errors.total}`);b.push("")}let n=Array.from($.reports.values()).flatMap((A)=>A.suggestions);if(n.length>0){b.push("## Suggestions"),b.push("");for(let A of n.slice(0,10))b.push(`- ${A}`);if(n.length>10)b.push(`- ... and ${n.length-10} more`);b.push("")}return b.join(`
|
|
2543
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let n=[],A=$.every((j)=>j.passed),m=$.length>0?Math.round($.reduce((j,B)=>j+B.score,0)/$.length):100;n.push(A?"✓ Verification passed":"✗ Verification failed"),n.push(`Score: ${m}/100`),n.push("");for(let j of $){let B=j.passed?"✓":"✗";n.push(`${B} ${j.tier}: ${j.score}/100`)}n.push("");let y=b.filter((j)=>j.severity==="error"),W=b.filter((j)=>j.severity==="warning"),w=b.filter((j)=>j.severity==="info");if(y.length>0)n.push(`Errors: ${y.length}`);if(W.length>0)n.push(`Warnings: ${W.length}`);if(w.length>0)n.push(`Info: ${w.length}`);return n.join(`
|
|
2544
|
+
`)}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 CX($){return new NA($)}var xX=new NA;var nB={};f(nB,{saveReleaseDraft:()=>t1,renderUpgradePrompt:()=>Yb,renderUpgradeChecklist:()=>Y1,renderPatchNotes:()=>Qy,renderMigrationGuide:()=>X1,renderMaintainerSummary:()=>Q1,renderCustomerPatchNote:()=>Z1,renderCustomerGuide:()=>Zy,prepareReleaseAuthoring:()=>i1,parseConventionalCommit:()=>gA,isConventionalCommit:()=>FX,initReleaseArtifacts:()=>e1,getHighestBumpType:()=>Hy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>o1,formatKeepAChangelog:()=>Wn,formatConventionalChangelog:()=>g1,formatChangelogJson:()=>FA,filterCommitsByScope:()=>vX,filterBumpableCommits:()=>gX,commitsToChangeEntries:()=>qy,commitToChangeEntry:()=>k1,checkReleaseArtifacts:()=>$B,buildReleaseArtifacts:()=>s1,applyVersionBump:()=>u1,analyzeVersionsFromCommits:()=>Gb,analyzeVersions:()=>Qn,DEFAULT_COMMIT_TYPE_MAP:()=>vA});import{basename as IX,dirname as EX}from"node:path";function Wn($){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).",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){b.push(`## [${A.version}] - ${A.date}`),b.push("");let m=A.changes.filter((Q)=>Q.type==="added"),y=A.changes.filter((Q)=>Q.type==="changed"),W=A.changes.filter((Q)=>Q.type==="deprecated"),w=A.changes.filter((Q)=>Q.type==="removed"),j=A.changes.filter((Q)=>Q.type==="fixed"),B=A.changes.filter((Q)=>Q.type==="security"),S=A.breakingChanges??A.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### ⚠️ Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(m.length>0)b.push("### Added"),m.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(y.length>0)b.push("### Changed"),y.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(w.length>0)b.push("### Removed"),w.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(j.length>0)b.push("### Fixed"),j.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(`
|
|
2545
|
+
`)}function g1($){let b=["# Changelog",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){let m=A.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":A.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${A.version} (${A.date}) - ${m}`),b.push("");let y={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let W of A.changes){let w=y[W.type]??"chore",j=W.path?`(${W.path})`:"",B=W.type==="breaking"?"!":"";b.push(`- **${w}${j}${B}**: ${W.description}`)}b.push("")}return b.join(`
|
|
2546
|
+
`)}function FA($,b){let n=$.analyses.filter((y)=>y.needsBump),A=new Date().toISOString(),m=A.split("T")[0]??"";return{generatedAt:A,baseline:b,specs:n.map((y)=>({key:y.specKey,version:y.suggestedVersion,path:y.specPath,entries:[{version:y.suggestedVersion,date:m,bumpType:y.bumpType,changes:y.changes,breakingChanges:y.changes.filter((W)=>W.type==="breaking")}]})),libraries:TX(n,m)}}function MX($){let b=$.split("/"),n=b.lastIndexOf("packages");if(n>=0&&n+2<b.length)return b.slice(0,n+3).join("/");return EX($)}var v1={major:3,minor:2,patch:1};function TX($,b){let n=new Map;for(let A of $){let m=MX(A.specPath),y=n.get(m);if(y)y.push(A);else n.set(m,[A])}return Array.from(n.entries()).flatMap(([A,m])=>{let y=m[0];if(!y)return[];let W=m.reduce((w,j)=>{return(v1[j.bumpType]??0)>(v1[w.bumpType]??0)?j:w},y);return[{name:IX(A),path:A,version:W.suggestedVersion,entries:[{version:W.suggestedVersion,date:b,bumpType:W.bumpType,changes:m.flatMap((w)=>w.changes),breakingChanges:m.flatMap((w)=>w.changes).filter((w)=>w.type==="breaking")}]}]})}function P1($,b){let n=(y)=>{return y.split(".").map((w)=>parseInt(w,10)||0)},A=n($),m=n(b);for(let y=0;y<3;y++){let W=A[y]??0,w=m[y]??0;if(W!==w)return w-W}return 0}var vA={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},DX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,NX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function gA($){let b=$.split(`
|
|
2547
|
+
`),n=b[0]?.trim();if(!n)return null;let A=n.match(DX);if(!A)return null;let[,m,y,W,w]=A;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2548
|
+
`).trim()||void 0,B=j?.match(NX),S=B?.[1];return{type:m.toLowerCase(),scope:y?.toLowerCase(),breaking:!!W||!!B,description:w.trim(),body:j,breakingDescription:S,raw:$}}function FX($){return gA($)!==null}function Gy($,b=vA){if($.breaking)return"major";return b[$.type]??null}function Hy($,b=vA){let n=["major","minor","patch"],A=null;for(let m of $){let y=Gy(m,b);if(!y)continue;if(!A){A=y;continue}let W=n.indexOf(A);if(n.indexOf(y)<W)A=y}return A}function k1($){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 qy($){return $.map(k1)}function vX($,b){return $.filter((n)=>n.scope?.toLowerCase()===b.toLowerCase())}function gX($,b=vA){return $.filter((n)=>Gy(n,b)!==null)}import{z as M}from"zod";import{ReleaseCapsuleSchema as r1}from"@contractspec/lib.contracts-spec";import{dump as PX,load as kX}from"js-yaml";var rX=".changeset/*.md",fX=".changeset/*.release.yaml",cX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,hX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function dX($,b){return(await $.glob({pattern:rX,cwd:b,absolute:!0})).filter((A)=>$.basename(A)!=="README.md")}async function wn($,b){let n=await dX($,b),A=[];for(let m of n){let y=await $.readFile(m);A.push(uX($.basename(m),y))}return A}async function jn($,b,n){let A=await $.glob({pattern:fX,cwd:b,absolute:!0}),m=new Map(n.map((w)=>[w.slug,w.packages])),y=new Map,W=[];for(let w of A){let j=$.basename(w).replace(/\.release\.yaml$/,"");try{let B=kX(await $.readFile(w)),S=oX(B,j,m.get(j)??[]);y.set(j,S)}catch(B){W.push(iX(w,j,B))}}return{capsules:y,issues:W}}async function Bn($,b){let n=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),A=[];for(let m of n){let y=JSON.parse(await $.readFile(m));if(!y.name||!y.version||y.private===!0)continue;let W=$.relative(b,$.dirname(m))||".";A.push({name:y.name,dir:W,version:y.version})}return A.sort((m,y)=>m.dir.localeCompare(y.dir))}function PA($,b){let n=new Set;for(let A of $){let m=b.find((y)=>y.dir==="."?!A.startsWith("packages/"):A===y.dir||A.startsWith(`${y.dir}/`));if(m)n.add(m.name)}return Array.from(n).sort((A,m)=>A.localeCompare(m))}function kA($,b){return`---
|
|
2549
|
+
${b.map((A)=>`"${A.name}": ${A.releaseType}`).join(`
|
|
2455
2550
|
`)}
|
|
2456
2551
|
---
|
|
2457
2552
|
|
|
2458
2553
|
${$}
|
|
2459
|
-
`}function
|
|
2460
|
-
`)}function
|
|
2461
|
-
`)){let
|
|
2462
|
-
`)}function
|
|
2463
|
-
"${B}": ${
|
|
2554
|
+
`}function rA($){return PX(r1.parse($),{noRefs:!0,lineWidth:100})}function Sn($){return $.map((b)=>{let n=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",A=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${n} ${b.message}.${A}`.trim()}).join(`
|
|
2555
|
+
`)}function uX($,b){let n=$.replace(/\.md$/,""),A=b.match(cX);if(!A)return{slug:n,summary:b.trim(),packages:[]};let m=A[1]??"",y=(A[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2556
|
+
`)){let j=w.trim().match(hX);if(!j)continue;let B=j[1],S=j[2];if(!B||S==="none")continue;W.push({name:B,releaseType:S})}return{slug:n,summary:y,packages:W}}function oX($,b,n){let A=typeof $==="object"&&$!==null?$:{},m=Array.isArray(A.packageNames)?A.packageNames.filter((y)=>typeof y==="string").map((y)=>({name:y,releaseType:A.releaseType??"patch"})):[];return r1.parse({...A,slug:b,packages:Array.isArray(A.packages)&&A.packages.length>0?A.packages:m.length>0?m:n})}function iX($,b,n){let A=typeof n==="object"&&n!==null?n:null,m=Array.isArray(A?.issues)?A.issues.map((W)=>W.message).filter((W)=>typeof W==="string"):[],y=m.length>0?`Release capsule validation failed: ${m.join("; ")}`:typeof A?.reason==="string"?`Release capsule YAML parse failed: ${A.reason}`:`Release capsule parse failed: ${n instanceof Error?n.message:String(n)}`;return{slug:b,filePath:$,message:y,line:typeof A?.mark?.line==="number"?A.mark.line+1:void 0,column:typeof A?.mark?.column==="number"?A.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as d1,determineBumpType as tX}from"@contractspec/lib.contracts-spec";async function Qn($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting version analysis...",{baseline:b.baseline});let W=b.pattern??"**/*.{operation,event,presentation}.ts",j=(await n.glob({pattern:W,cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${j.length} spec files`);let B=[],S=0,Q=0;for(let X of j)try{let Y=await n.readFile(X),G=fA(Y);if(!G)continue;let V=null;if(b.baseline)try{V=await A.showFile(b.baseline,X)}catch{V=null}let O=lX(Y,V),K=O.some((_)=>_.type==="breaking"),J=O.length>0&&!K,U=O.length>0;if(K)S++;if(J)Q++;let H=tX(K,J),q=U?d1(G.version,H):G.version;B.push({specPath:X,specKey:G.key,currentVersion:G.version,suggestedVersion:q,bumpType:H,changes:O,hasBreaking:K,needsBump:U})}catch(Y){m.warn(`Failed to analyze ${X}:`,{error:Y instanceof Error?Y.message:String(Y)})}let Z=B.filter((X)=>X.needsBump).length;return m.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 Gb($,b={}){let{git:n,logger:A}=$,m=b.baseline??"HEAD~10";A.info("Analyzing commits for version bump...",{baseline:m});try{let y=await n.log(m),W=[],w=[];for(let Q of y){let Z=gA(Q.message);if(Z)W.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),w.push(Z)}let j=Hy(w),B=qy(w),S=W.filter((Q)=>Q.breaking).length;return A.info("Commit analysis complete",{totalCommits:W.length,breakingCommits:S,suggestedBumpType:j}),{suggestedBumpType:j,commits:W,changes:B,totalCommits:W.length,breakingCommits:S}}catch(y){return A.warn("Failed to analyze commits",{error:y instanceof Error?y.message:String(y)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function u1($,b){let{fs:n,logger:A}=$,{specPath:m,dryRun:y=!1,config:W}=b;A.info("Applying version bump...",{specPath:m,bumpType:b.bumpType});try{let w=await n.readFile(m),j=fA(w);if(!j)return{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:c1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=d1(j.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((X)=>X.type==="breaking")};if(!y){let X=aX(w,j.version,S);await n.writeFile(m,X)}if(A.info("Version bump applied",{specPath:m,previousVersion:j.version,newVersion:S}),W?.integrateWithChangesets)await $Y($,{specPath:m,bumpType:B,summary:b.changeDescription??`Bump ${j.key} to ${S}`,dryRun:y});return{success:!0,specPath:m,specKey:j.key,previousVersion:j.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(w){let j=w instanceof Error?w.message:String(w);return A.error("Version bump failed",{specPath:m,error:j}),{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:c1(),error:j}}}async function o1($,b={}){let{logger:n}=$,A=b.tiers??["spec","library","monorepo"],m=b.format??"keep-a-changelog";n.info("Generating changelogs...",{tiers:A,format:m});let y=await Qn($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),W=[],w=new Map,j="",B=0;if(A.includes("spec"))for(let Q of y.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:eX(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((X)=>X.type==="breaking")}]};W.push(Z),B++}if(A.includes("library")){let Q=sX(y.analyses);for(let[Z,X]of Q){let Y=X.filter((G)=>G.needsBump);if(Y.length>0)w.set(Z,Wn(Y.map(h1))),B+=Y.length}}if(A.includes("monorepo")){let Q=y.analyses.filter((Z)=>Z.needsBump).map(h1);j=Wn(Q)}let S=FA(y,b.baseline);return n.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:W,libraryMarkdown:w,monorepoMarkdown:j,json:S,totalEntries:B}}function fA($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),n=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!n)return null;let A=b[1],m=n[1];if(!A||!m)return null;return{key:A,version:m}}function lX($,b){let n=[];if(!b)return n.push({type:"added",description:"New spec added"}),n;let A=fA($),m=fA(b);if(!A||!m)return n;if(A.version!==m.version)n.push({type:"changed",description:`Version updated from ${m.version} to ${A.version}`,path:"meta.version"});let y=pX($,b);if(y.breaking)n.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(y.nonBreaking)n.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return n}function pX($,b){let n=/io:\s*\{[\s\S]*?\}/,A=$.match(n)?.[0]??"",m=b.match(n)?.[0]??"";if(A===m)return{breaking:!1,nonBreaking:!1};let y=f1(A),W=f1(m),w=W.filter((B)=>!y.includes(B)),j=y.filter((B)=>!W.includes(B));return{breaking:w.length>0,nonBreaking:j.length>0&&w.length===0}}function f1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((A)=>A[1]).filter((A)=>!!A)}function aX($,b,n){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${n}'`)}function c1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function eX($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],n=$.changes.filter((y)=>y.type==="breaking"),A=$.changes.filter((y)=>y.type==="changed"),m=$.changes.filter((y)=>y.type==="added");if(n.length>0)b.push("### Breaking Changes"),n.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(m.length>0)b.push("### Added"),m.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(A.length>0)b.push("### Changed"),A.forEach((y)=>b.push(`- ${y.description}`)),b.push("");return b.join(`
|
|
2557
|
+
`)}function sX($){let b=new Map;for(let n of $){let y=n.specPath.match(/(.+?\/src\/)/)?.[1]??n.specPath,W=b.get(y)??[];W.push(n),b.set(y,W)}return b}function h1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function $Y($,b){let{fs:n,logger:A}=$,{specPath:m,bumpType:y,summary:W,dryRun:w}=b;try{let j=c(m),B=g$(j);if(!B){A.warn("Could not determine package name for changeset",{specPath:m});return}let S=j,Q=null;while(!0){let G=n.join(S,".changeset");if(await n.exists(G)){Q=G;break}let V=n.dirname(S);if(V===S)break;S=V}if(!Q){A.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${bY()}.md`,X=n.join(Q,Z),Y=`---
|
|
2558
|
+
"${B}": ${y}
|
|
2464
2559
|
---
|
|
2465
2560
|
|
|
2466
|
-
${
|
|
2467
|
-
`;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 A2(){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 m2=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??y2(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??B2(Q)),_=(Y?await A.exists(Y):!1)||(V?await A.exists(V):!1),H=await W2(W,n2({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(j2(n));return await A.writeFile(W,y),await A.writeFile(w,B),{source:j,changesetPath:W,capsulePath:w,changesetContent:y,capsuleContent:B}}function n2($){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??S2(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 W2($,b,A,m){if(!$)return b;try{let n=await $.generateStructured({schema:m2,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 j2($){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 y2($,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 B2($){return $.length>0?"minor":"patch"}function J1($){return $.trim().startsWith("Describe the ")}function S2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as Q2}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as Z2,DEFAULT_CONTRACTSRC as G2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var K1="generated/releases",E0=G2.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??X2(y),Z=b.releaseType??Q,G=b.summary??`Describe the ${Z} release for ${y[0]??"the workspace"}`,X=b.slug??H2(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:Y2(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=Q2.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=Z2.safeParse(m);return n.success?{...E0,...n.data.release}:E0}catch{return E0}}function X2($){return $.length>0?"minor":"patch"}function Y2($,b){return $.packages.map((m)=>b.find((n)=>n.name===m.name)?.version??m.version).find((m)=>typeof m==="string")??"0.0.0"}function H2($){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 q2}from"node:fs";import{readFile as O2}from"node:fs/promises";import{join as pn}from"node:path";import V2 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(q2(W))try{let w=await O2(W,"utf-8");if(W.endsWith(".json"))n=JSON.parse(w);else n=V2.load(w);break}catch(w){console.warn(`Warning: Failed to parse ${W}`,w)}return{...x0,...n}}import{existsSync as J2}from"node:fs";import{copyFile as K2,mkdir as C1,readFile as _2,writeFile as U2}from"node:fs/promises";import{dirname as z2,join as Qb}from"node:path";import{glob as L2}from"glob";var R2=["**/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=[...R2],j=Qb(A,".gitignore");if(J2(j)){let Y=(await _2(j,"utf-8")).split(`
|
|
2468
|
-
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));
|
|
2561
|
+
${W}
|
|
2562
|
+
`;if(!w)await n.writeFile(X,Y),A.info("Generated changeset",{filePath:X});else A.info("Would generate changeset",{filePath:X,content:Y})}catch(j){A.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function bY(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],n=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],m=b[Math.floor(Math.random()*b.length)],y=n[Math.floor(Math.random()*n.length)],W=Math.floor(Math.random()*1000);return`${A}-${m}-${y}-${W}`}var nY=M.object({summary:M.string(),maintainerSummary:M.string(),customerSummary:M.string(),integratorSummary:M.string(),deprecations:M.array(M.string()).default([]),migrationInstructions:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),required:M.boolean().default(!1),when:M.string().optional(),steps:M.array(M.string()).default([])})).default([]),upgradeSteps:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),level:M.enum(["auto","assisted","manual"]).default("manual"),instructions:M.array(M.string()).default([])})).default([]),validationCommands:M.array(M.string()).default([]),validationEvidence:M.array(M.string()).default([])});async function i1($,b={}){let{fs:n,git:A,logger:m,ai:y}=$,W=I(b.workspaceRoot),w=await Bn(n,W),j=b.baseline?await A.diffFiles(b.baseline):[],B=await wn(n,W),S=await jn(n,W,B),Q=b.packages&&b.packages.length>0?b.packages:PA(j,w),Z=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??wY(B,S.capsules,Q),G=Y?n.join(W,".changeset",`${Y}.md`):void 0,V=Y?n.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((q)=>q.slug===Y):void 0,K=Y?S.capsules.get(Y):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??jY(Q)),U=(G?await n.exists(G):!1)||(V?await n.exists(V):!1),H=await mY(y,AY({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:w,isBreaking:J==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await A.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},m);return{workspaceRoot:W,source:U?"existing":"created",changesetPath:G??n.join(W,".changeset",`${H.slug}.md`),capsulePath:V??n.join(W,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${Sn(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:n}=$,A=I(b.workspaceRoot),m=Zn(b.draft),y=n.join(A,".changeset",`${m.slug}.md`),W=n.join(A,".changeset",`${m.slug}.release.yaml`),w=await n.exists(y)||await n.exists(W)?"updated":"created",j=kA(m.summary,m.packages),B=rA(WY(m));return await n.writeFile(y,j),await n.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function AY($){if($.existingCapsule)return Zn({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((A)=>({...A,version:$.workspacePackages.find((m)=>m.name===A.name)?.version??A.version})):$.packageNames.map((A)=>({name:A,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===A)?.version})),n=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return Zn({slug:$.selectedSlug??BY(n),summary:n,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:l1(n),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function mY($,b,n,A){if(!$)return b;try{let m=await $.generateStructured({schema:nY,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:n.changedFiles.slice(0,40),commitMessages:n.commitMessages.slice(0,20),parseIssues:n.parseIssues})});return yY(b,m.object)}catch(m){return A.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:m instanceof Error?m.message:String(m)}),b}}function yY($,b){let n=[...$.audiences];return Oy(n,"maintainer",b.maintainerSummary),Oy(n,"customer",b.customerSummary),Oy(n,"integrator",b.integratorSummary),Zn({...$,summary:p1($.summary)?b.summary:$.summary,audiences:n,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 Zn($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:l1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function WY($){let{releaseType:b,...n}=Zn($);return{schemaVersion:"1",...n}}function l1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Oy($,b,n){let A=$.find((m)=>m.kind===b);if(A&&!p1(A.summary))return;if(A){A.summary=n;return}$.push({kind:b,summary:n})}function wY($,b,n){let A=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(A.size===1)return Array.from(A)[0];if(n.length===0)return;let m=Array.from(A).filter((y)=>{let W=b.get(y),w=$.find((B)=>B.slug===y);return(W?.packages.map((B)=>B.name)??w?.packages.map((B)=>B.name)??[]).some((B)=>n.includes(B))});return m.length===1?m[0]:void 0}function jY($){return $.length>0?"minor":"patch"}function p1($){return $.trim().startsWith("Describe the ")}function BY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as SY}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as QY,DEFAULT_CONTRACTSRC as ZY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var a1="generated/releases",cA=ZY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function e1($,b={}){let{fs:n,git:A,logger:m}=$,y=I(b.workspaceRoot),W=await Bn(n,y),w=b.baseline?await A.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:PA(w,W),B=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:y}):null,S=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:y}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??XY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??GY(X),G=j.map((H)=>({name:H,releaseType:Z,version:W.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:G,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:X},{kind:"customer",summary:X}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=n.join(y,".changeset",`${Y}.md`),K=n.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await n.exists(O))throw Error(`Changeset already exists: ${O}`);if(await n.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=kA(X,G),U=rA(V);if(!b.dryRun)await n.writeFile(O,J),await n.writeFile(K,U);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:U,packages:G,releaseType:Z,isBreaking:V.isBreaking}}async function s1($,b={}){let{fs:n,logger:A}=$,m=I(b.workspaceRoot),y=await bB(n,m),W=n.join(m,b.outputDir??a1),w=await wn(n,m),j=await jn(n,m,w);if(j.issues.length>0)throw Error(Sn(j.issues));let B=j.capsules,S=await Bn(n,m),Q=await Promise.all(Array.from(B.entries()).map(async([U,H])=>{let q=n.join(m,".changeset",`${U}.release.yaml`),_=await n.stat(q);return{slug:U,version:YY(H,S),summary:H.summary,date:_.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=SY.parse({generatedAt:new Date().toISOString(),releases:Q}),X=b.agentTargets??y.agentTargets??["codex"],Y=An(Z,[],X,Yb),G=n.join(W,"manifest.json"),V=n.join(W,"upgrade-manifest.json"),O=n.join(W,"patch-notes.md"),K=n.join(W,"customer-guide.md"),J=Object.fromEntries(Y.agentPrompts.map((U)=>[U.agent,n.join(W,"prompts",`${U.agent}.md`)]));if(!b.dryRun){await n.writeFile(G,JSON.stringify(Z,null,2)),await n.writeFile(V,JSON.stringify(Z,null,2)),await n.writeFile(O,Qy(Z)),await n.writeFile(K,Zy(Z));for(let U of Y.agentPrompts)await n.writeFile(J[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:W,releasesBuilt:Z.releases.length}),{outputDir:W,manifestPath:G,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:Y,releasesBuilt:Z.releases.length}}async function $B($,b={}){let{fs:n}=$,A=I(b.workspaceRoot),m=await bB(n,A),y=n.join(A,b.outputDir??a1),W=[],w=[],j=[],B=await wn(n,A),S=await jn(n,A,B),Q=S.capsules,Z=B.length>0,X=!Z&&Q.size>0;j.push(...S.issues.map((Y)=>Sn([Y]))),Hb(W,Z||X,"changesets",Z?`Found ${B.length} release changeset(s).`:X?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let Y of B)if(!Q.has(Y.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${Y.slug}.`);for(let[Y,G]of Q){if(G.isBreaking&&G.migrationInstructions.length===0)j.push(`Breaking release ${Y} is missing migration instructions.`);if(G.validation.commands.length===0)j.push(`Release capsule ${Y} is missing validation commands.`);if(G.validation.evidence.length===0)j.push(`Release capsule ${Y} is missing validation evidence.`)}if(b.baseline){try{let Y=await K$($,{baseline:b.baseline,workspaceRoot:A});if(Hb(W,!0,"impact",`Impact status: ${Y.status}`),Y.summary.breaking>0&&!Array.from(Q.values()).some((G)=>G.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(Y){Hb(W,!1,"impact",hA(Y)),j.push(`Impact detection failed: ${hA(Y)}`)}try{let Y=await Qn($,{baseline:b.baseline,workspaceRoot:A});Hb(W,!0,"versioning",`${Y.specsNeedingBump} spec(s) need version review.`)}catch(Y){Hb(W,!1,"versioning",hA(Y)),j.push(`Version analysis failed: ${hA(Y)}`)}}if(b.strict)for(let Y of m.publishArtifacts??[]){let G=n.join(y,Y);if(!await n.exists(G))j.push(`Missing generated release artifact: ${G}`)}if(Hb(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!Z&&!X)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function bB($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return cA;try{let A=JSON.parse(await $.readFile(n)),m=QY.safeParse(A);return m.success?{...cA,...m.data.release}:cA}catch{return cA}}function XY($){return $.length>0?"minor":"patch"}function YY($,b){return $.packages.map((A)=>b.find((m)=>m.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function GY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Hb($,b,n,A){$.push({name:n,ok:b,message:A})}function hA($){return $ instanceof Error?$.message:String($)}var XB={};f(XB,{silentLogger:()=>yB,runWorkflow:()=>WB,loadWorkflows:()=>Uy,loadVibeConfig:()=>uA,installPack:()=>ZB,getWorkflow:()=>jB,exportContext:()=>mB,consoleLogger:()=>Jy,builtinWorkflows:()=>oA,DEFAULT_VIBE_CONFIG:()=>dA});import{existsSync as HY}from"node:fs";import{readFile as qY}from"node:fs/promises";import{join as Vy}from"node:path";import OY from"js-yaml";var dA={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function uA($){let b=$??process.cwd(),n=I(b)??b,A=[Vy(n,".contractspec","vibe","config.json"),Vy(n,".contractspec","vibe","config.yaml"),Vy(n,".contractspec","vibe","config.yml")],m={};for(let y of A)if(HY(y))try{let W=await qY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=OY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...dA,...m}}import{existsSync as VY}from"node:fs";import{copyFile as JY,mkdir as AB,readFile as UY,writeFile as KY}from"node:fs/promises";import{dirname as _Y,join as qb}from"node:path";import{glob as zY}from"glob";var LY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function mB($){let b=$??process.cwd(),n=I(b)??b,A=await uA(b),m=qb(n,".contractspec","context"),y=qb(m,"files"),W=[...LY],w=qb(n,".gitignore");if(VY(w)){let G=(await UY(w,"utf-8")).split(`
|
|
2563
|
+
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));W=[...W,...G]}let j=A.contextExportAllowlist.length>0?A.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let Y of j){let G=await zY(Y,{cwd:n,ignore:W,nodir:!0,dot:!0});B.push(...G)}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 AB(y,{recursive:!0});let Q=[];for(let Y of S){let G=qb(n,Y),V=qb(y,Y);await AB(_Y(V),{recursive:!0}),await JY(G,V),Q.push({path:Y,size:0})}let Z=qb(m,"index.json"),X={generatedAt:new Date().toISOString(),files:Q.map((Y)=>Y.path),config:{allowlist:A.contextExportAllowlist,ignores:W.length}};return await KY(Z,JSON.stringify(X,null,2)),{success:!0,files:S,indexPath:Z}}var oA=[{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.
|
|
2469
2564
|
Please review them and move selected files to contracts/ directory.
|
|
2470
|
-
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
|
|
2471
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2472
|
-
`);let
|
|
2473
|
-
\uD83D\uDC49 Step: ${
|
|
2565
|
+
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 RY}from"node:child_process";var yB={log:()=>{},warn:()=>{},error:()=>{}},Jy={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function WB($,b,n){let A=n?.logger??Jy,m=n?.prompter;if(A.log(`
|
|
2566
|
+
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${b.track}`),b.dryRun)A.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2567
|
+
`);let y={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let W of $.steps){let w={id:W.id,name:W.label,status:"skip",command:W.command};if(W.tracks&&!W.tracks.includes(b.track)){y.steps.push(w);continue}if(W.condition){if(!await W.condition(b)){y.steps.push(w);continue}}if(A.log(`
|
|
2568
|
+
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)A.log(` Command: ${W.command}`);if(W.manualCheckpoint){if(b.dryRun)A.warn(" [Manual Checkpoint] Would pause here for user input.");else if(m){if(W.manualMessage)A.log(W.manualMessage);let j=await m.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(j==="abort")return A.warn("Workflow aborted by user."),y.success=!1,y.steps.push({...w,status:"skip",error:"Aborted by user"}),y;if(j==="skip"){A.warn(" → Skipped by user."),y.steps.push(w);continue}}}if(!b.dryRun)try{if(W.execute)await W.execute(b);else if(W.command)await CY(W.command,b.root);w.status="pass",y.stepsExecuted.push(W.id),y.steps.push(w),A.log(" ✓ Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return A.error(` ❌ Failed: ${B}`),y.success=!1,y.error=j instanceof Error?j:Error(String(j)),w.status="fail",w.error=B,y.stepsExecuted.push(W.id),y.steps.push(w),y}else y.steps.push(w)}return y}async function CY($,b){let n=$.split(" "),A=n[0],m=n.slice(1);if(!A)throw Error("Invalid command");return new Promise((y,W)=>{let w=RY(A,m,{cwd:b,stdio:"inherit",shell:!0});w.on("error",W),w.on("exit",(j)=>{if(j===0)y();else W(Error(`Command exited with code ${j}`))})})}import{existsSync as xY}from"node:fs";import{readdir as IY,readFile as EY}from"node:fs/promises";import{join as wB}from"node:path";import MY from"js-yaml";async function Uy($){let b=[...oA],n=$??process.cwd(),A=I(n)??n,m=wB(A,".contractspec","vibe","workflows");if(xY(m))try{let y=await IY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await EY(wB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=MY.load(w);if(j.id&&j.steps)b.push(j)}catch(j){console.warn(`Failed to parse workflow ${W}:`,j)}}}catch(y){console.warn("Error loading user workflows:",y)}return b}async function jB($,b){return(await Uy(b)).find((A)=>A.id===$)}import{existsSync as Ky}from"node:fs";import{copyFile as BB,mkdir as SB,readdir as QB,stat as TY}from"node:fs/promises";import{join as N$,resolve as DY}from"node:path";async function ZB($,b){let n=b??process.cwd(),A=I(n)??n;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let m=DY(n,$);if(!Ky(m))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${m}`};let y=0,W=0,w=N$(m,"workflows");if(Ky(w)){let B=N$(A,".contractspec","vibe","workflows");await SB(B,{recursive:!0});let S=await QB(w);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await BB(N$(w,Q),N$(B,Q)),y++}let j=N$(m,"templates");if(Ky(j)){let B=N$(A,".contractspec","vibe","templates");await SB(B,{recursive:!0});let S=await QB(j);for(let Q of S){let Z=N$(j,Q),X=N$(B,Q);if((await TY(Z)).isFile())await BB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as NY}from"@contractspec/module.workspace";var YB=["product","eng","qa"];function FY($){return YB.includes($)}async function FM($,b){if(!FY(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${YB.join(", ")}`);let n,A,m;if(b.specFiles&&b.specFiles.length>0)n=b.specFiles;else{let W=await vY($,{baseline:b.baseline});if(A=W.totalSpecs,m=W.changedFilesCount,b.baseline){if(W.changedFilesCount===0)return{views:[],totalSpecs:A,changedFilesCount:0,status:"no_changes"};if(W.specFiles.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_changed_specs"}}n=W.specFiles}if(n.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_specs"};let y=[];for(let W of n){let w=await gY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:A,changedFilesCount:m,status:"success"}}async function vY($,b={}){let A=(await j$({fs:$.fs})).map((w)=>w.filePath),m=A.length;if(!b.baseline)return{specFiles:A,totalSpecs:m};let y=await $.git.diffFiles(b.baseline);if(y.length===0)return{specFiles:[],totalSpecs:m,changedFilesCount:0,hasChanges:!1};let W=A.filter((w)=>y.some((j)=>w.endsWith(j)||j.endsWith(w)||w.includes(j)||j.includes(w)));return{specFiles:W,totalSpecs:m,changedFilesCount:y.length,hasChanges:W.length>0}}async function gY($,b,n){if(!await n.fs.exists($))throw Error(`File not found: ${$}`);let A=await NY($);if(A.length===0)return`No specs found in ${$} (Parse result empty)`;return A.map((m)=>PY(m,b)).join(`
|
|
2474
2569
|
|
|
2475
2570
|
---
|
|
2476
2571
|
|
|
2477
|
-
`)}function
|
|
2478
|
-
`)}function
|
|
2572
|
+
`)}function PY($,b){let n=[];switch(b){case"product":kY($,n);break;case"eng":rY($,n);break;case"qa":fY($,n);break}return n.join(`
|
|
2573
|
+
`)}function kY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2479
2574
|
${$.meta.goal}
|
|
2480
2575
|
`);if($.meta.context)b.push(`### Context
|
|
2481
2576
|
${$.meta.context}
|
|
2482
|
-
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((
|
|
2483
|
-
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((
|
|
2484
|
-
`)}export{
|
|
2577
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- ✅ Enforces Business Policies");if($.hasIo)b.push("- ✅ Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((n)=>b.push(`- **${n.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function rY($,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?"✅ Defined":"❌ Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"✅ Defined":"❌ None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function fY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2578
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((n)=>b.push(`- \uD83E\uDDEA \`${n.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((n)=>b.push(`- [ ] Verify event \`${n.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((n)=>b.push(`- [ ] Test Operation flow: \`${n.name}\``));if($.presentations?.length)$.presentations.forEach((n)=>b.push(`- [ ] Test UI Component: \`${n.name}\``))}}function kM($,b,n,A){let{watcher:m,fs:y,logger:W}=$,w=m.watch(n),j=A?.validate??(async(S)=>{await l$(S,{fs:y,logger:W})}),B=A?.build??(async(S)=>{await yb(S,{fs:y,logger:W},b)});return w.on(async(S)=>{if(S.type!=="change")return;if(W.info("watchSpecs.changed",{path:S.path}),n.runValidate)await j(S.path);if(n.runBuild)if(n.dryRun)W.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),w}async function cM($,b,n={}){let A=(n.getWorkspaceInfo??cy)(b),m=$.join(A.workspaceRoot,".contractsrc.json"),y=$.join(A.packageRoot,".contractsrc.json"),W=await $.exists(m),w=A.workspaceRoot!==A.packageRoot?await $.exists(y):!1,j;if(W)try{let B=await $.readFile(m),S=JSON.parse(B);if(S.packages||S.excludePackages||S.recursive)j={packages:S.packages,excludePackages:S.excludePackages,recursive:S.recursive}}catch{}return{...A,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?y:void 0}}async function hM($,b){let n=[],A=$.join(b,".contractsrc.json");if(await $.exists(A))n.push(A);let m=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let y of m)if(y!==A)n.push(y);return n}async function dM($,b,n){let A={};if(b&&await $.exists(b))try{let m=await $.readFile(b);A=JSON.parse(m)}catch{}if(n&&await $.exists(n))try{let m=await $.readFile(n),y=JSON.parse(m);A=GB(A,y)}catch{}return A}function GB($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(typeof m==="object"&&m!==null&&!Array.isArray(m)&&typeof y==="object"&&y!==null&&!Array.isArray(y))n[A]=GB(m,y);else n[A]=y}return n}function uM($){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(`
|
|
2579
|
+
`)}export{kM as watchSpecs,XB as vibe,nB as versioning,jX as verifyWithAIEnhanced,mn as verifyWithAI,yn as verifyStructure,xX as verifyService,N1 as verifySemanticFields,z7 as verifyImportedContracts,HR as verifyImplementationAgainstParsedSpec,DA as verifyBehavior,fx as validateTenantConfig,Fx as validateSpecs,l$ as validateSpec,$1 as validateScannedSpec,Rx as validatePackageScaffold,Jx as validateImplementationWithAgent,nA as validateImplementationFiles,Nx as validateDiscoveredSpecs,Hx as validateBlueprint,FY as validateAudience,Tz as validateAgainstOpenApiService,aW as utils,z1 as upgrade,HI as updateSpec,ZQ as toKebabCase,dW as templates,Iz as syncWithOpenApiService,ex as syncSpecs,bX as stringToCacheKey,ny as setupUsageMd,ZA as setupGitignore,pm as setupAgentsMd,YC as searchRegistry,a as safeParseJson,WI as runTests,wI as runTestSpecs,bx as runSetup,bC as runQuickstart,Jw as runDoctor,bK as runCIChecks,Aw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,OQ as resolveImplementations,J0 as resolveDefaultBuildTargets,rj as resolveAuthoredModuleValue,Tw as resolveAllImplementations,$n as renderManagedMarkdownBlock,ey as prompts,ry as parseGitModules,Iw as parseExplicitImplementations,cw as packageDeclarations,f3 as operationRegistry,oj as onboarding,lm as normalizeMarkdownContent,gT as module,dM as mergeMonorepoConfigs,zA as mergeManagedMarkdown,D4 as mergeGitignoreContent,P as loadWorkspaceConfig,oV as loadPackageAuthoredDocBlocks,Pj as loadAuthoredModuleValue,MR as loadAuthoredModuleIfExists,UA as loadAuthoredModuleExports,y$ as loadAuthoredModule,uV as loadAuthoredDocBlocksFromSourceFiles,jI as listTests,vY as listSpecsForView,j$ as listSpecs,XC as listFromRegistry,G0 as listAgentTypes,Vb as isMonorepo,nC as isContractSpecInstalled,fO as isConnectPreset,rO as isBuilderPreset,Eb as inferSetupPresetFromConfig,QQ as inferImplementationType,q7 as importFromSourceService,zj as importFromOpenApiService,sw as impact,Fj as hooks,bU as groupSpecsByType,nS as getWorkspacePackages,cy as getWorkspaceInfo,CG as getRunCommand,om as getProductionDependencies,g$ as getPackageName,mS as getMetaRepoInfo,hy as getInstallCommand,KJ as getImplementationSummary,_O as getGraphStats,cM as getExtendedWorkspaceInfo,xG as getExecCommand,im as getDevDependencies,um as getDependencies,xw as getConventionPaths,UO as getContractNode,ln as getClaudeDesktopConfigPath,T0 as getBuilderRuntimeModeForPreset,mw as getBuilderBootstrapPresetForSetupPreset,tW as getApiKey,hJ as getAllSpecs,yV as getAllLayerLocations,Ub as getAgentAdapter,m0 as getAIProvider,Cn as genericMCPAdapter,hW as generateWorkflowSpec,kn as generateWorkflowRunnerTemplate,Nn as generateWorkflowDevkitWorkflowTemplate,gn as generateWorkflowDevkitStreamRouteTemplate,Fn as generateWorkflowDevkitStartRouteTemplate,Pn as generateWorkflowDevkitGenericTemplate,vn as generateWorkflowDevkitFollowUpRouteTemplate,tn as generateVscodeSettings,HW as generateVisualizationSpec,FM as generateViews,gY as generateView,Sw as generateUsageGuide,YW as generateTranslationSpec,cW as generateThemeSpec,DW as generateTestTemplate,XW as generateTestSpec,fW as generateTelemetrySpec,OW as generateProductIntentSpec,rW as generatePresentationSpec,ZW as generatePolicySpec,kW as generateOperationSpec,PW as generateMigrationSpec,YR as generateMermaidDiagram,K7 as generateMarkdownReport,vW as generateKnowledgeSpaceSpec,GW as generateJobSpec,FW as generateIntegrationSpec,JW as generateHarnessSuiteSpec,VW as generateHarnessScenarioSpec,MW as generateHandlerTemplate,E7 as generateGuideFromParsedSpec,EW as generateFormSpec,IW as generateFeatureSpec,UR as generateFeatureContextMarkdown,xW as generateExperimentSpec,In as generateExampleSpec,CW as generateEventSpec,_w as generateDocsFromSpecs,RW as generateDataViewSpec,Tn as generateDataViewRendererTemplate,M7 as generateCursorRulesFromParsedSpec,jw as generateCursorRules,Mb as generateCursorMcpConfig,Wb as generateContractsrcConfig,TW as generateComponentTemplate,_7 as generateCliReport,ww as generateClaudeMcpConfig,QW as generateCapabilitySpec,Lw as generateArtifacts,LW as generateAppBlueprintSpec,Bw as generateAgentsGuide,qW as generateAgentSpec,bW as formatters,uM as formatWorkspaceInfo,qR as formatVerificationReport,AC as formatQuickstartPreview,kj as formatModuleLoadError,N as formatJson,fL as formatFiles,NV as formatDoctorSummary,FV as formatCheckResult,Ej as fix,I as findWorkspaceRoot,c as findPackageRoot,fy as findMetaRepoRoot,hM as findAllConfigFiles,dJ as filterIssuesByType,uJ as filterIssuesBySeverity,Rj as features,Rw as extractSpecReferences,cz as extractContracts,KR as exportSpecForLLM,C6 as exportOpenApi,KO as exportGraphAsDot,oW as ensurePackageScaffold,cn as discoverSpecs,c$ as discoverSpecFiles,an as discoverLayers,AA as discoverImplementationsForSpec,qJ as discoverAllImplementations,Ew as determineStatus,yS as detectRepositoryType,a$ as detectPackageManager,Xz as deleteSpec,b$ as deepMergePreserve,D0 as deepMergeOverwrite,Ln as cursorCLIAdapter,rI as createWorkspaceStateCacheStorage,IS as createWorkspaceRegistry,CX as createVerifyService,lI as createVerificationCacheService,wz as createSpecCreator,yw as createSetupNextSteps,Ww as createSetupGitignorePatterns,SC as createRegeneratorService,TA as createQuickAIReview,rn as createPackageTargetSpecSource,Fy as createNoopLoggerAdapter,vy as createNodeWatcherAdapter,Dy as createNodeGitAdapter,Ey as createNodeFsAdapter,Ry as createNodeAiAdapter,HG as createNodeAdapters,PI as createInMemoryCacheStorage,vI as createFileSystemCacheStorage,V9 as createEmptyLayerInventory,Ny as createConsoleLoggerAdapter,KG as createBunFsAdapter,a8 as createBuilderWorkspaceId,w5 as createAgentGuideService,Vj as connect,E1 as computeContentHash,Hz as compareSpecs,BK as cleanArtifacts,_n as claudeCodeAdapter,M1 as cacheKeyToString,yb as buildSpec,dn as analyzeWorkspaceDocBlocks,mA as analyzeIntegrity,uL as analyzeGap,eW as analyzeDeps,j5 as agentGuideService,Y0 as agentAdapters,X0 as adoption,ZC as addToRegistry,TR as __moduleLoaderInternals,x1 as WorkspaceStateCacheStorage,L3 as WorkspaceBundle,NA as VerifyService,T1 as VerificationCacheService,YB as VALID_AUDIENCES,Y2 as TestGeneratorService,Uj as SpecCreatorService,qn as SimpleAgent,sW as SETUP_TARGET_LABELS,bw as SETUP_PRESET_LABELS,nw as SETUP_PRESET_DESCRIPTIONS,Ib as SETUP_GITIGNORE_PATTERNS,mZ as RuleSyncService,_A as RegistryClient,TS as PrActionService,Hn as OpenAICodexAgent,ij as MINIMAL_DEPENDENCIES,C1 as InMemoryCacheStorage,Rn as GenericMCPAdapter,R1 as FileSystemCacheStorage,e7 as FULL_DEPENDENCIES,ES as DriftActionService,q$ as DEFAULT_SPEC_PATTERNS,v$ as DEFAULT_FS_IGNORES,I1 as DEFAULT_CACHE_CONFIG,zn as CursorCLIAdapter,Gn as CursorAgent,Yn as ClaudeCodeAgent,Kn as ClaudeCodeAdapter,QZ as CONTRACTSPEC_USAGE_BLOCK_START,ZZ as CONTRACTSPEC_USAGE_BLOCK_END,WZ as CONTRACTSPEC_AGENTS_BLOCK_START,wZ as CONTRACTSPEC_AGENTS_BLOCK_END,mK as CI_CHECK_CATEGORY_LABELS,Vw as CHECK_CATEGORY_LABELS,On as AgentOrchestrator,xn as AgentGuideService,xb as ALL_SETUP_TARGETS,$w as ALL_SETUP_PRESETS,AK as ALL_CI_CHECK_CATEGORIES,Ow as ALL_CHECK_CATEGORIES,GA as AIGenerator};
|