@contractspec/bundle.workspace 4.5.6 → 4.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.js +521 -489
- package/dist/node/index.js +521 -489
- package/dist/ports/git.d.ts +16 -0
- package/dist/services/versioning/release-files.d.ts +1 -1
- package/dist/services/versioning/release-service.types.d.ts +4 -0
- package/dist/templates/advanced-contracts.template.d.ts +5 -0
- package/dist/templates/advanced-contracts.template.test.d.ts +1 -0
- package/dist/templates/environment.template.d.ts +3 -0
- package/dist/templates/environment.template.test.d.ts +1 -0
- package/dist/templates/index.d.ts +1 -0
- package/package.json +13 -11
package/dist/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)){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
|
|
4
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
5
|
-
`).map((
|
|
2
|
+
var zB=Object.defineProperty;var LB=($)=>$;function RB($,b){this[$]=LB.bind(null,b)}var f=($,b)=>{for(var A in b)zB($,A,{get:b[A],enumerable:!0,configurable:!0,set:RB.bind(b,A)})};var zy=($,b)=>()=>($&&(b=$($=0)),b);var F$=import.meta.require;import{ContractsrcSchema as IS,DEFAULT_CONTRACTSRC as fA}from"@contractspec/lib.contracts-spec/workspace-config";async function P($,b){let A=$.join(b??".",".contractsrc.json");if(!await $.exists(A))return fA;try{let m=await $.readFile(A),y=JSON.parse(m),W=IS.safeParse(y);return{...fA,...W.data,conventions:{...fA.conventions,...W.data?.conventions||{}}}}catch{return fA}}function sW($){switch($){case"claude":return process.env.ANTHROPIC_API_KEY;case"openai":return process.env.OPENAI_API_KEY;case"custom":return process.env.CONTRACTSPEC_LLM_API_KEY;case"ollama":return;default:return}}var b$=()=>{};var Lj={};f(Lj,{AIGenerator:()=>Y0});import{createProvider as L6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as R6,buildEventSpecPrompt as I6,buildFormPrompt as C6,buildHandlerPrompt as x6,buildOperationSpecPrompt as M6,buildPresentationSpecPrompt as E6,buildTestPrompt as T6,getCodeGenSystemPrompt as pb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Tm,generateText as X0,streamText as D6}from"ai";import*as R from"zod";class Y0{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||sW(this.config.aiProvider),A={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return L6(A).getModel()}async generateOperationSpec($,b){let A=this.getModel(),n=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=M6($,b);return(await Tm({model:A,schema:n,prompt:m,system:Em()})).object}async generateEventSpec($){let b=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),n=I6($);return(await Tm({model:b,schema:A,prompt:n,system:Em()})).object}async generatePresentationSpec($,b){let A=this.getModel(),n=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=E6($,b);return(await Tm({model:A,schema:n,prompt:m,system:Em()})).object}async generateHandler($){let b=this.getModel();return(await X0({model:b,prompt:x6($),system:pb()})).text}async generateComponent($){let b=this.getModel();return(await X0({model:b,prompt:R6($),system:pb()})).text}async generateForm($){let b=this.getModel();return(await X0({model:b,prompt:C6($),system:pb()})).text}async generateTests($,b,A){let n=this.getModel();return(await X0({model:n,prompt:T6($,b,A),system:pb()})).text}async streamCodeGeneration($,b){let A=this.getModel(),n=await D6({model:A,prompt:$,system:pb()}),m="";for await(let y of n.textStream)m+=y,b(y);return m}}var H0=zy(()=>{b$()});import*as $D from"@contractspec/module.workspace";import{anthropic as IB}from"@ai-sdk/anthropic";import{openai as Ly}from"@ai-sdk/openai";import{DEFAULT_MODELS as Ry}from"@contractspec/lib.ai-providers/models";import{generateObject as CB,generateText as xB,streamText as MB}from"ai";import{ollama as EB}from"ollama-ai-provider";function Iy($){return{async validateProvider(b){try{let{aiProvider:A}=b;if(A==="ollama")return{success:!0};if(A==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(A==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(A){return{success:!1,error:A instanceof Error?A.message:String(A)}}},async generateText(b){let A=i0($);return{text:(await xB({model:A,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let n={model:i0($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await CB(n)).object}},async streamText(b,A){let n=i0($),m=await MB({model:n,prompt:b.prompt,system:b.systemPrompt}),y="";for await(let W of m.textStream)y+=W,A(W);return y}}}function i0($){let{aiProvider:b,aiModel:A,customEndpoint:n}=$;switch(b){case"claude":{let m=A??Ry.anthropic;return IB(m)}case"openai":{let m=A??Ry.openai;return Ly(m)}case"ollama":return EB(A??"codellama");case"custom":{if(!n)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return Ly(A??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as eB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as TB,stat as DB,mkdir as Cy,readFile as NB,rm as FB,writeFile as vB}from"fs/promises";import{basename as gB,dirname as xy,isAbsolute as PB,join as kB,relative as rB,resolve as My}from"path";import{glob as fB}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(n){try{return await TB(A(n)),!0}catch{return!1}},async readFile(n){return NB(A(n),"utf-8")},async writeFile(n,m){let y=A(n),W=xy(y);await Cy(W,{recursive:!0}),await vB(y,m,"utf-8")},async remove(n){await FB(A(n),{recursive:!0,force:!0})},async stat(n){let m=await DB(A(n));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(n){await Cy(A(n),{recursive:!0})},async glob(n){let m=n.patterns??(n.pattern?[n.pattern]:q$),y=n.ignore??v$,W=n.cwd??b,w=n.absolute??!0;return(await fB(m,{cwd:W,ignore:y,absolute:w})).sort((B,S)=>B.localeCompare(S))},resolve(...n){let[m,...y]=n;if(!m)return b;return My(b,m,...y)},dirname(n){return xy(n)},basename(n){return gB(n)},join(...n){return kB(...n)},relative(n,m){return rB(n,m)}};function A(n){return PB(n)?n:My(b,n)}}import{spawnSync as cB}from"child_process";import{existsSync as Ty,readFileSync as Dy}from"fs";import{access as hB}from"fs/promises";import{resolve as HA}from"path";function Ny($){let b=$??process.cwd();return{async currentBranch(){try{let A=g$(["rev-parse","--abbrev-ref","HEAD"],b).trim()||dB(b);return A.length>0?A:void 0}catch{return}},async showFile(A,n){try{let m=g$(["show",`${A}:${n}`],b);if(m.length>0||A!=="HEAD")return m;return uB(b,n)??m}catch(m){throw Error(`Could not load ${n} at ref ${A}: ${m instanceof Error?m.message:String(m)}`)}},async clean(A){let n=[];if(A?.force)n.push("-f");if(A?.directories)n.push("-d");if(A?.ignored)n.push("-x");if(A?.dryRun)n.push("--dry-run");g$(["clean",...n],b,{inherit:!0})},async isGitRepo(A){let n=A?HA(b,A):b;try{return await hB(HA(n,".git")),!0}catch{return!1}},async log(A){let n=A??"HEAD~10",m="--format=%H|||%s|||%an|||%aI";try{let y=g$(["log",`${n}..HEAD`,"--format=%H|||%s|||%an|||%aI"],b),W=[];for(let w of y.trim().split(`
|
|
3
|
+
`)){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(A,n){try{let m=n&&n.length>0?["--",...n]:[];return g$(["diff","--name-only",`${A}...HEAD`,...m],b).trim().split(`
|
|
4
|
+
`).filter(Boolean)}catch{return[]}},async statusFiles(A){try{let n=A&&A.length>0?["--",...A]:[],m=g$(["status","--short","--untracked-files=all",...n],b);return oB(m)}catch{return[]}},async diffNameStatus(A,n){try{let m=n&&n.length>0?["--",...n]:[],y=g$(["diff","--name-status",`${A}..HEAD`,...m],b);return iB(y)}catch{return[]}}}}function dB($){let b=HA($,".git","HEAD");if(!Ty(b))return"";let A=Dy(b,"utf8").trim(),n="ref: refs/heads/";return A.startsWith(n)?A.slice(n.length):A}function uB($,b){let A=HA($,b);if(!Ty(A))return;return Dy(A,"utf8")}function g$($,b,A={}){let n=cB("git",$,{cwd:b,encoding:"utf-8",stdio:A.inherit?"inherit":["ignore","pipe","pipe"]});if(n.error)throw n.error;if(n.status!==0)throw Error(typeof n.stderr==="string"&&n.stderr.length>0?n.stderr:`git ${$.join(" ")} failed with status ${n.status??"unknown"}`);return typeof n.stdout==="string"?n.stdout:""}function oB($){return $.split(`
|
|
5
|
+
`).map((b)=>b.trimEnd()).filter(Boolean).map((b)=>{let A=b.slice(0,2).trim()||b.slice(0,1),n=b.slice(3),[m,y]=n.includes(" -> ")?n.split(" -> "):[void 0,n];return{status:A,path:y??n,previousPath:m}})}function iB($){return $.split(`
|
|
6
|
+
`).map((b)=>b.trim()).filter(Boolean).map((b)=>{let[A="",n="",m]=b.split("\t");return{status:A,path:m??n,previousPath:m?n:void 0}})}function Fy(){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 lB()}}}function vy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:tB}}function lB(){return{start($){console.warn(`\u23F3 ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`\u2705 ${$??"Done"}`)},fail($){console.error(`\u274C ${$??"Failed"}`)},warn($){console.warn(`\u26A0\uFE0F ${$??"Warning"}`)},stop(){}}}function tB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import pB from"chokidar";var aB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function gy($){let b=$??process.cwd();return{watch(A){let n=[],m,y=pB.watch(A.pattern,{cwd:b,ignored:A.ignore??aB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),W=(w)=>{if(A.debounceMs&&A.debounceMs>0)clearTimeout(m),m=setTimeout(()=>{n.forEach((j)=>j(w))},A.debounceMs);else n.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){n.push(w)},async close(){clearTimeout(m),await y.close()}}}}}function M3($={}){let{cwd:b,config:A,silent:n}=$,m=A??eB;return{fs:Ey(b),git:Ny(b),watcher:gy(b),ai:Iy(m),logger:n?vy():Fy()}}import{stat as sB,mkdir as $5}from"fs/promises";import{basename as b5,dirname as A5,isAbsolute as n5,join as m5,relative as y5,resolve as Py}from"path";import{glob as W5}from"glob";function v3($){let b=$??process.cwd();return{async exists(n){let m=Bun.file(A(n));try{return await m.exists(),!0}catch{return!1}},async readFile(n){return Bun.file(A(n)).text()},async writeFile(n,m){let y=A(n);await Bun.write(y,m)},async remove(n){await Bun.file(A(n)).delete()},async stat(n){let m=await sB(A(n));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(n){await $5(A(n),{recursive:!0})},async glob(n){let m=n.patterns??(n.pattern?[n.pattern]:q$),y=n.ignore??v$,W=n.cwd??b,w=n.absolute??!0;return await W5(m,{cwd:W,ignore:y,absolute:w})},resolve(...n){let[m,...y]=n;if(!m)return b;return Py(b,m,...y)},dirname(n){return A5(n)},basename(n){return b5(n)},join(...n){return m5(...n)},relative(n,m){return y5(n,m)}};function A(n){return n5(n)?n:Py(b,n)}}import{existsSync as o,readFileSync as z$}from"fs";import{tmpdir as w5}from"os";import{dirname as l0,isAbsolute as j5,join as u,relative as B5,resolve as a$}from"path";var ky={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},ry=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function S5($,b){let A=B5(b,$);return A===""||!A.startsWith("..")&&!j5(A)}function t0($){let b=a$($),A=a$(w5());return S5(b,A)?A:void 0}function c($=process.cwd()){let b=a$($),A=t0($);while(!0){if(o(u(b,"package.json")))return b;let n=l0(b);if(n===b||b===A)break;b=n}return $}function x($=process.cwd()){let b=a$($),A=null,n=t0($);while(!0){for(let W of ry)if(o(u(b,W)))return b;let m=u(b,"package.json");if(o(m)){A=b;try{if(JSON.parse(z$(m,"utf-8")).workspaces)return b}catch{}}for(let W of Object.keys(ky))if(o(u(b,W)))return b;let y=l0(b);if(y===b||b===n)break;b=y}return A??$}function e$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let n of b){let m=Object.entries(ky).filter(([,y])=>y===n);for(let[y]of m)if(o(u($,y)))return n}let A=u($,"package.json");if(o(A))try{let n=JSON.parse(z$(A,"utf-8"));if(n.packageManager){let m=n.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 Ub($=process.cwd()){for(let A of ry)if(o(u($,A)))return!0;let b=u($,"package.json");if(o(b))try{if(JSON.parse(z$(b,"utf-8")).workspaces)return!0}catch{}return!1}function Q5($){let b=u($,"pnpm-workspace.yaml");if(o(b))try{let m=z$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(m?.[1])return m[1].split(`
|
|
7
|
+
`).map((W)=>W.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let A=u($,"package.json");if(o(A))try{let n=JSON.parse(z$(A,"utf-8"));if(Array.isArray(n.workspaces))return n.workspaces;if(n.workspaces?.packages&&Array.isArray(n.workspaces.packages))return n.workspaces.packages}catch{}return}function P$($){let b=u($,"package.json");if(o(b))try{return JSON.parse(z$(b,"utf-8")).name}catch{}return}function fy($){let b=u($,".gitmodules");if(!o(b))return[];try{let A=z$(b,"utf-8"),n=[],m=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,y;while((y=m.exec(A))!==null){let[,W,w,j]=y;if(W&&w&&j){let B=u($,w),S=o(u(B,"package.json"))&&Z5(B);n.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return n}catch{return[]}}function Z5($){let b=u($,"package.json");if(o(b))try{let A=JSON.parse(z$(b,"utf-8"));return Boolean(A.workspaces)}catch{}return o(u($,"pnpm-workspace.yaml"))}function cy($){let b=a$($),A=t0($);while(!0){if(o(u(b,".gitmodules")))return b;let n=l0(b);if(n===b||b===A)break;b=n}return}function X5($){let b=cy($);if(!b)return;let A=fy(b);if(A.length===0)return;let n=a$($),m=A.find((y)=>n.startsWith(y.absolutePath));return{root:b,submodules:A,activeSubmodule:m}}function Y5($,b){let A=cy($);if(A){if(fy(A).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function hy($=process.cwd()){let b=c($),A=x($),n=e$(A),m=Ub(A),y=m?Q5(A):void 0,W=P$(b),w=Y5($,m),j=w==="meta-repo"?X5($):void 0;return{packageManager:n,workspaceRoot:A,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function f3($,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 c3($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function dy($,b=!1){let A=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${A}`.trim();case"pnpm":return`pnpm add ${A}`.trim();case"yarn":return`yarn add ${A}`.trim();case"npm":return`npm install ${A}`.trim()}}import{anthropic as uy}from"@ai-sdk/anthropic";import{generateText as oy}from"ai";class GA{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=uy("claude-3-7-sonnet-20250219"),A=this.buildSystemPrompt($),n=this.buildUserPrompt($),m=await oy({model:b,prompt:n,system:A,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=uy("claude-3-7-sonnet-20250219"),A=`
|
|
6
8
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
7
9
|
|
|
8
10
|
SPECIFICATION:
|
|
@@ -31,7 +33,7 @@ Provide a structured validation report:
|
|
|
31
33
|
- Are there any missing edge cases?
|
|
32
34
|
|
|
33
35
|
Be thorough and precise. Use a critical but constructive tone.
|
|
34
|
-
`,
|
|
36
|
+
`,n=await oy({model:b,prompt:A,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),m=this.detectIssues(n.text);return{success:!m,code:n.text,errors:m?this.extractErrors(n.text):[],warnings:this.extractWarnings(n.text),suggestions:this.extractSuggestions(n.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
35
37
|
|
|
36
38
|
Your code is:
|
|
37
39
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -74,10 +76,10 @@ Spec:
|
|
|
74
76
|
${$.specCode}
|
|
75
77
|
|
|
76
78
|
Code:
|
|
77
|
-
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
80
|
-
`);for(let
|
|
79
|
+
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],A=$.toLowerCase();return b.some((n)=>A.includes(n))}extractErrors($){let b=[],A=$.split(`
|
|
80
|
+
`);for(let n of A){let m=n.toLowerCase();if(m.includes("error")||m.includes("bug")||m.includes("incorrect")||m.includes("missing"))b.push(n.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],A=$.split(`
|
|
81
|
+
`);for(let n of A){let m=n.toLowerCase();if(m.includes("warning")||m.includes("should")||m.includes("consider"))b.push(n.trim())}return b}extractSuggestions($){let b=[],A=$.split(`
|
|
82
|
+
`);for(let n of A){let m=n.toLowerCase();if(m.includes("suggest")||m.includes("recommend")||m.includes("could")||m.includes("improvement"))b.push(n.trim())}return b}}import{spawn as H5}from"child_process";import{existsSync as iy}from"fs";import{mkdir as ly,readFile as G5,rm as q5,writeFile as Y$}from"fs/promises";import{homedir as p0,tmpdir as ty}from"os";import{join as i}from"path";class qA{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=i(ty(),`cursor-agent-${Date.now()}`);await ly(b,{recursive:!0});let A=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=i(ty(),`cursor-validate-${Date.now()}`);await ly(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let A=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",i(p0(),".cursor","cursor"),i(p0(),"AppData","Local","Programs","cursor","Cursor.exe"),i(p0(),"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(iy(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let A=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let n of A)try{let m=await n.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 A=i(b,"spec.ts"),n=i(b,"output.ts"),m=i(b,"INSTRUCTIONS.md");if(await Y$(A,$.specCode),await Y$(m,this.buildDetailedPrompt($)),$.existingCode)await Y$(i(b,"existing.ts"),$.existingCode);return new Promise((y,W)=>{let w=["--wait","--new-window",b],j=H5(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(iy(n))try{let Z=await G5(n,"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 A=i(b,"SPECIFICATION.ts"),n=i(b,"INSTRUCTIONS.md"),m=i(b,"template.ts");return await Y$(A,$.specCode),await Y$(n,this.buildDetailedPrompt($)),await Y$(m,this.generateTemplate($)),await Y$(i(b,"README.md"),`# Cursor Agent Workspace
|
|
81
83
|
|
|
82
84
|
This workspace was prepared for Cursor AI code generation.
|
|
83
85
|
|
|
@@ -93,18 +95,18 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
93
95
|
4. Save the result as output.ts
|
|
94
96
|
|
|
95
97
|
Workspace path: ${b}
|
|
96
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Y$(
|
|
98
|
+
`),{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$(i(b,"specification.ts"),$.specCode),await Y$(i(b,"implementation.ts"),$.existingCode||"// No implementation"),await Y$(i(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let A=[{path:"spec.ts",content:$.specCode}];if($.existingCode)A.push({path:"existing.ts",content:$.existingCode});return A}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
97
99
|
|
|
98
100
|
**Task Type:** ${$.type}
|
|
99
101
|
**Generated:** ${new Date().toISOString()}
|
|
100
102
|
|
|
101
|
-
`,
|
|
103
|
+
`,A=`## Specification
|
|
102
104
|
|
|
103
105
|
\`\`\`typescript
|
|
104
106
|
${$.specCode}
|
|
105
107
|
\`\`\`
|
|
106
108
|
|
|
107
|
-
`,
|
|
109
|
+
`,n={generate:`## Task: Generate Implementation
|
|
108
110
|
|
|
109
111
|
### Requirements:
|
|
110
112
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -197,7 +199,7 @@ ${$.existingCode||""}
|
|
|
197
199
|
- Enhance error messages
|
|
198
200
|
|
|
199
201
|
### Output Format:
|
|
200
|
-
Refactored code that maintains functionality while improving quality.`};return b+
|
|
202
|
+
Refactored code that maintains functionality while improving quality.`};return b+A+(n[$.type]||n.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
201
203
|
|
|
202
204
|
## Specification
|
|
203
205
|
\`\`\`typescript
|
|
@@ -255,7 +257,7 @@ export function implementation() {
|
|
|
255
257
|
// Implementation goes here
|
|
256
258
|
throw new Error('Not implemented');
|
|
257
259
|
}
|
|
258
|
-
`}async cleanupWorkDir($){try{await
|
|
260
|
+
`}async cleanupWorkDir($){try{await q5($,{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 py}from"@ai-sdk/openai";import{generateText as ay}from"ai";class OA{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let A=this.isComplexTask($)?"o1":"gpt-5.4",n=py(A),m=this.buildSystemPrompt($),y=this.buildUserPrompt($),W=await ay({model:n,prompt:y,system:m,temperature:0.2});return{success:!0,code:this.extractCode(W.text),metadata:{model:A,agentMode:"openai-codex",usage:W.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=py("gpt-5.4"),A=`
|
|
259
261
|
Review this code implementation against its specification.
|
|
260
262
|
|
|
261
263
|
SPECIFICATION:
|
|
@@ -275,7 +277,7 @@ Provide a detailed validation report including:
|
|
|
275
277
|
4. Recommendations for improvement
|
|
276
278
|
|
|
277
279
|
Format as a structured report.
|
|
278
|
-
`,
|
|
280
|
+
`,n=await ay({model:b,prompt:A,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),m=this.detectIssues(n.text);return{success:!m,code:n.text,errors:m?this.extractErrors(n.text):[],warnings:this.extractWarnings(n.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],A=($.specCode+($.existingCode||"")).toLowerCase();return b.some((n)=>A.includes(n))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
279
281
|
|
|
280
282
|
Generate production-quality code that is:
|
|
281
283
|
- Type-safe and well-typed
|
|
@@ -312,9 +314,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
312
314
|
${$.existingCode}
|
|
313
315
|
|
|
314
316
|
Spec:
|
|
315
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],
|
|
316
|
-
`);for(let
|
|
317
|
-
`);for(let
|
|
317
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],A=$.toLowerCase();return b.some((n)=>A.includes(n))}extractErrors($){let b=[],A=$.split(`
|
|
318
|
+
`);for(let n of A)if(n.toLowerCase().includes("error")||n.toLowerCase().includes("bug")||n.toLowerCase().includes("fails"))b.push(n.trim());return b}extractWarnings($){let b=[],A=$.split(`
|
|
319
|
+
`);for(let n of A)if(n.toLowerCase().includes("warning")||n.toLowerCase().includes("should")||n.toLowerCase().includes("consider"))b.push(n.trim());return b}}import k$ from"chalk";import U5 from"ora";import{generateText as ey}from"ai";var An={};f(An,{getCodeGenSystemPrompt:()=>bn,buildTestPrompt:()=>$n,buildHandlerPrompt:()=>a0,buildFormPrompt:()=>s0,buildComponentPrompt:()=>e0});function a0($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
318
320
|
|
|
319
321
|
Here is the contract spec:
|
|
320
322
|
|
|
@@ -333,7 +335,7 @@ Generate a complete handler implementation that:
|
|
|
333
335
|
|
|
334
336
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
335
337
|
|
|
336
|
-
Return only the TypeScript code for the handler function.`}function
|
|
338
|
+
Return only the TypeScript code for the handler function.`}function e0($){return`You are a senior React developer creating a component for a presentation specification.
|
|
337
339
|
|
|
338
340
|
Here is the presentation spec:
|
|
339
341
|
|
|
@@ -352,7 +354,7 @@ Generate a complete React component that:
|
|
|
352
354
|
|
|
353
355
|
The component should follow Atomic Design principles and be reusable.
|
|
354
356
|
|
|
355
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
357
|
+
Return only the TypeScript/TSX code for the component.`}function s0($){return`You are a senior React developer creating a form component from a form specification.
|
|
356
358
|
|
|
357
359
|
Here is the form spec:
|
|
358
360
|
|
|
@@ -372,7 +374,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
372
374
|
|
|
373
375
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
374
376
|
|
|
375
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
377
|
+
Return only the TypeScript/TSX code for the form component.`}function $n($,b,A){return`You are a senior developer writing comprehensive tests.
|
|
376
378
|
|
|
377
379
|
Spec:
|
|
378
380
|
\`\`\`typescript
|
|
@@ -385,7 +387,7 @@ ${b}
|
|
|
385
387
|
\`\`\`
|
|
386
388
|
|
|
387
389
|
Generate complete test suite using Vitest that:
|
|
388
|
-
${
|
|
390
|
+
${A==="handler"?`
|
|
389
391
|
- Test all acceptance scenarios from the spec
|
|
390
392
|
- Test error cases defined in spec.io.errors
|
|
391
393
|
- Verify events are emitted correctly
|
|
@@ -399,7 +401,7 @@ ${n==="handler"?`
|
|
|
399
401
|
|
|
400
402
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
401
403
|
|
|
402
|
-
Return only the TypeScript test code.`}function
|
|
404
|
+
Return only the TypeScript test code.`}function bn(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
403
405
|
- Type-safe API design
|
|
404
406
|
- React and modern hooks
|
|
405
407
|
- Test-driven development
|
|
@@ -413,7 +415,7 @@ Generate production-ready code that is:
|
|
|
413
415
|
- Defensive and error-safe
|
|
414
416
|
- Easy to maintain and extend
|
|
415
417
|
|
|
416
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
418
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as O5}from"@contractspec/lib.ai-providers";function nn($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return O5(b)}class JA{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=nn(this.config),A=this.buildPrompt($),n=await ey({model:b,prompt:A,system:bn()});return{success:!0,code:n.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:n.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=nn(this.config),A=`
|
|
417
419
|
Review the following implementation against its specification.
|
|
418
420
|
|
|
419
421
|
Specification:
|
|
@@ -427,15 +429,15 @@ Provide a detailed validation report:
|
|
|
427
429
|
2. Are there any missing features?
|
|
428
430
|
3. Are there any bugs or issues?
|
|
429
431
|
4. Suggestions for improvement
|
|
430
|
-
`,
|
|
431
|
-
${$.specCode}`;case"test":return
|
|
432
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
432
|
+
`,n=await ey({model:b,prompt:A,system:"You are a code review expert. Provide thorough, constructive feedback."}),m=n.text.toLowerCase().includes("error")||n.text.toLowerCase().includes("missing")||n.text.toLowerCase().includes("incorrect");return{success:!m,code:n.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 a0($.specCode);else if($.specCode.includes(".presentation."))return e0($.specCode);else if($.specCode.includes(".form."))return s0($.specCode);return`Generate implementation for:
|
|
433
|
+
${$.specCode}`;case"test":return $n($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
434
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as J5}from"@contractspec/lib.ai-agent/agent/unified-agent";class mn{name;agent;constructor($,b,A={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=J5(A,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),A=await this.agent.run(b);return{success:!0,code:A.text,metadata:{finishReason:A.finishReason,usage:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
433
435
|
${$.specCode}
|
|
434
436
|
|
|
435
437
|
`;if($.existingCode)b+=`Existing Code:
|
|
436
438
|
${$.existingCode}
|
|
437
439
|
|
|
438
|
-
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class
|
|
440
|
+
`;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 UA{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new JA($),A=new qA,n=new GA,m=new OA;this.agents.set("simple",b),this.agents.set("cursor",A),this.agents.set("claude-code",n),this.agents.set("openai-codex",m),this.defaultAgent=b,this.agents.set("opencode-sdk",new mn("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),A=this.agents.get(b);if(!A)return console.log(k$.yellow(`\u26A0\uFE0F Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!A.canHandle($))return console.log(k$.yellow(`\u26A0\uFE0F Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let n=U5(`Executing with ${b} agent...`).start();try{let m=$.type==="validate"?await A.validate($):await A.generate($);if(m.success)return n.succeed(k$.green(`${b} agent completed successfully`)),m;n.warn(k$.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 n.info(k$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(m){return n.fail(k$.red("Agent execution failed")),console.log(k$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,A]of this.agents){let n={type:"generate",specCode:"test"},m=A.canHandle(n);$.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 sy={};f(sy,{specCreation:()=>yn,codeGeneration:()=>An});var yn={};f(yn,{getSystemPrompt:()=>z5,buildPresentationSpecPrompt:()=>_5,buildOperationSpecPrompt:()=>V5,buildEventSpecPrompt:()=>K5,addExampleContext:()=>L5});function V5($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
439
441
|
|
|
440
442
|
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
441
443
|
|
|
@@ -453,7 +455,7 @@ Create a complete contract specification following these guidelines:
|
|
|
453
455
|
8. **Feature Flags**: Any flags that gate this operation
|
|
454
456
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
455
457
|
|
|
456
|
-
Respond with a structured spec.`}function
|
|
458
|
+
Respond with a structured spec.`}function K5($){return`You are a senior software architect creating an event specification.
|
|
457
459
|
|
|
458
460
|
User description: ${$}
|
|
459
461
|
|
|
@@ -467,7 +469,7 @@ Create a complete event specification following these guidelines:
|
|
|
467
469
|
|
|
468
470
|
Events represent things that have already happened and should use past tense.
|
|
469
471
|
|
|
470
|
-
Respond with a structured spec.`}function
|
|
472
|
+
Respond with a structured spec.`}function _5($,b){return`You are a senior software architect creating a presentation specification.
|
|
471
473
|
|
|
472
474
|
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
473
475
|
|
|
@@ -485,7 +487,7 @@ Create a complete presentation specification following these guidelines:
|
|
|
485
487
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
486
488
|
- Data structure description`}
|
|
487
489
|
|
|
488
|
-
Respond with a structured spec.`}function
|
|
490
|
+
Respond with a structured spec.`}function z5(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
489
491
|
|
|
490
492
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
491
493
|
|
|
@@ -495,7 +497,7 @@ Your specs are:
|
|
|
495
497
|
- Business-oriented (capturing the "why" not just "what")
|
|
496
498
|
- Designed for both humans and AI agents to understand
|
|
497
499
|
|
|
498
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
500
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function L5($,b){if(b.length===0)return $;return`${$}
|
|
499
501
|
|
|
500
502
|
Here are some good examples for reference:
|
|
501
503
|
|
|
@@ -503,47 +505,47 @@ ${b.join(`
|
|
|
503
505
|
|
|
504
506
|
`)}
|
|
505
507
|
|
|
506
|
-
Follow this structure and quality level.`}import{defineModuleBundle as
|
|
507
|
-
`)}function
|
|
508
|
+
Follow this structure and quality level.`}import{defineModuleBundle as R5}from"@contractspec/lib.surface-runtime/spec";var kH=R5({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 AW={};f(AW,{sarifToJson:()=>T5,formatAsTextLines:()=>bW,formatAsText:()=>D5,formatAsSarif:()=>x5,formatAsJson:()=>I5});function I5($,b={}){let{pretty:A=!0,driftResult:n}=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:n?.hasDrift?"detected":"none",files:n?.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 A?JSON.stringify(B,null,2):JSON.stringify(B)}var C5={"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 x5($,b={}){let{toolName:A="ContractSpec",toolVersion:n="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=C5[X.ruleId]??{name:X.ruleId,description:`Rule: ${X.ruleId}`},H={id:X.ruleId,name:Y.name,shortDescription:{text:Y.description},defaultConfiguration:{level:$W(X.severity)}};if(Y.helpUri)H.helpUri=Y.helpUri;j.set(X.ruleId,w.size),w.set(X.ruleId,H)}let S=B.map((X)=>{let Y={ruleId:X.ruleId,ruleIndex:j.get(X.ruleId)??0,level:$W(X.severity),message:{text:X.message}},H={physicalLocation:{artifactLocation:{uri:M5(X.file),uriBaseId:"%SRCROOT%"}}};if(X.line!==void 0)H.physicalLocation.region={startLine:X.line,startColumn:X.column??1,endLine:X.endLine??X.line,endColumn:X.endColumn};return Y.locations=[H],Y.partialFingerprints={primaryLocationLineHash:E5(X)},Y}),Q=[];if(y)Q.push({repositoryUri:y,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:A,version:n,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 $W($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function M5($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function E5($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function T5($){return JSON.stringify($,null,2)}function bW($,b={}){let A=[],{verbose:n=!1,showTiming:m=!0,groupByFile:y=!1}=b;if(A.push({text:"",style:"normal"}),A.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),A.push({text:"",style:"normal"}),$.commitSha||$.branch){let w=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");A.push({text:`Git: ${w}`,style:"muted"})}A.push({text:"",style:"normal"}),A.push({text:"Check Results:",style:"bold"});for(let w of $.categories){let j=w.passed?"\u2713":"\u2717",B=w.passed?"success":"error",S=N5(w),Q=m?` (${w.durationMs}ms)`:"";A.push({text:` ${j} ${w.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(A.push({text:"",style:"normal"}),A.push({text:"Issues:",style:"bold"}),y){let w=F5($.issues);for(let[j,B]of w){A.push({text:"",style:"normal"}),A.push({text:` ${j||"(no file)"}`,style:"bold",indent:1});for(let S of B)A.push(...VA(S,n,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){A.push({text:"",style:"normal"}),A.push({text:" Errors:",style:"error",indent:1});for(let S of w)A.push(...VA(S,n,2))}if(j.length>0){A.push({text:"",style:"normal"}),A.push({text:" Warnings:",style:"warning",indent:1});for(let S of j)A.push(...VA(S,n,2))}if(B.length>0&&n){A.push({text:"",style:"normal"}),A.push({text:" Notes:",style:"muted",indent:1});for(let S of B)A.push(...VA(S,n,2))}}A.push({text:"",style:"normal"}),A.push({text:"\u2500".repeat(50),style:"muted"});let W=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&n?`${$.totalNotes} note(s)`:null].filter(Boolean);if(W.length>0)A.push({text:`Found: ${W.join(", ")}`,style:$.success?"warning":"error"});if(m)A.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(A.push({text:"",style:"normal"}),$.success)A.push({text:"\u2705 All CI checks passed!",style:"success"});else A.push({text:"\u274C CI checks failed",style:"error"});return A.push({text:"",style:"normal"}),A}function D5($,b={}){return bW($,b).map((n)=>" ".repeat(n.indent??0)+n.text).join(`
|
|
509
|
+
`)}function N5($){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 VA($,b,A){let n=[],m=$.severity==="error"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",y=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",W=`${m} ${$.message}`;if($.file){let w=$.line?`:${$.line}`:"";W+=` (${$.file}${w})`}if(n.push({text:W,style:y,indent:A}),b&&$.context){let w=JSON.stringify($.context);if(w!=="{}")n.push({text:`Context: ${w}`,style:"muted",indent:A+1})}return n}function F5($){let b=new Map;for(let A of $){let n=A.file??"";if(!b.has(n))b.set(n,[]);let m=b.get(n);if(m)m.push(A)}return new Map([...b.entries()].sort(([A],[n])=>A.localeCompare(n)))}import{OperationSpecRegistry as v5}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as g5}from"@contractspec/lib.contracts-spec/operations/report";function P5(){let $=new v5;return g5($),$}var bG=P5();class k5{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let A=$.drift?.status==="fail",n=!1;if(A&&b==="fail")n=!0;return{driftDetected:A,shouldFail:n}}}function r5($){if(!$)return"\u2014";let b=new Date($),n=new Date().getTime()-b.getTime(),m=Math.floor(n/86400000);if(m<1)return"today";if(m===1)return"yesterday";return`${m} days ago`}class f5{collectChanges($,b,A){if($){let n=$.endsWith("/")?$:`${$}/`;return A.filter((m)=>m.startsWith(n))}if(b){let n=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return A.filter((m)=>n.test(m))}return A}detectDrift($){let b=$.map((A)=>A.slice(3)).filter((A)=>A&&A.trim().length>0).filter((A)=>A!==".contractspec-ci"&&!A.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},A=b.breaking||0,n=b.nonBreaking||0,m=b.total;if(m===void 0)m=A+n;let y=$?.breaking||!1,W="unknown";if($){if(y||A>0)W="breaking",y=!0;else if(n>0)W="non-breaking";else if(m===0)W="no-impact"}return{status:W,breaking:y,breakingCount:A,nonBreakingCount:n,total:m||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,A=this.deriveImpactStatus($.impactJson),n={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:A.status,breaking:A.breakingCount,nonBreaking:A.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(n.validation?.status==="fail")n.nextSteps?.push("Fix validation errors and rerun the workflow.");if(n.risk?.status==="breaking")n.nextSteps?.push("Review breaking changes and plan a migration.");if(n.risk?.status==="unknown")n.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(n.drift?.status==="fail")n.nextSteps?.push("Run the generate command locally and commit drift fixes.");let m=this.finalizeResults(n,$.failOn);if(m.shouldFail)n.nextSteps?.unshift(`CI failed: ${m.failReasons.join(", ")} (fail_on=${$.failOn}).`);return n}finalizeResults($,b){let A=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,n=$.drift?.status==="fail",m=$.validation?.status==="fail",y=$.risk?.status==="unknown",W=[],w=!1;if(b!=="never"){if(b==="breaking"){if(A)W.push("breaking changes detected");if(y)W.push("impact status unknown")}else if(b==="drift"){if(n)W.push("drift detected");if(y)W.push("impact status unknown")}else if(b==="any"){if(A)W.push("breaking changes detected");if(n)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:n,breakingChangeDetected:A,validationFailed:m,shouldFail:w,failReasons:W}}generateReportMarkdown($,b){let A=(j,B=60000)=>{if(j.length<=B)return j;return`${j.slice(0,B)}
|
|
508
510
|
|
|
509
|
-
*(output truncated)*`},
|
|
510
|
-
`)},m=
|
|
511
|
+
*(output truncated)*`},n=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
512
|
+
`)},m=A($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),y=A($.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??"\u2014",S=r5(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(n(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(n($.nextSteps));else w.push("- No action required.");return`${w.join(`
|
|
511
513
|
`)}
|
|
512
|
-
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>sS,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>Kn,normalizeText:()=>wW,inferFamilyFromPath:()=>Z0,hasLocalShadcnRegistry:()=>Q0,getContractSpecAdoptionCatalog:()=>Un,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 TS=[...WW,...nW,...AW,...mW,...yW];function Un(){return[...TS].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function w0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:Un()}}import{DEFAULT_CONTRACTSRC as fS}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 Kn($,b){let n=new Set(b);return $.filter((A)=>n.has(A)).length}import{resolve as DS}from"path";import{ContractsrcSchema as NS,DEFAULT_CONTRACTSRC as B0}from"@contractspec/lib.contracts-spec/workspace-config";async function s$($,b={}){let n=DS(b.cwd??process.cwd()),A=b.workspaceRoot??I(n),m=b.packageRoot??c(n),y=b.config?BW(B0,b.config):await FS($,A,m);return{adoption:y.connect?.adoption??B0.connect.adoption,config:y,cwd:n,packageRoot:m,workspaceRoot:A}}async function FS($,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=NS.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 vS=["package.json","packages/*/package.json"];async function S0($,b){let[n,A]=await Promise.all([gS($,b),PS($,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 gS($,b){let n=await $.glob({patterns:vS,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:rS(m),packageRef:w,capabilityTags:k$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return A}async function PS($,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:kS(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 kS($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function rS($){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=pS(b),m=k$([A,b.symbol??"",...b.paths??[]]),y=await S0($.fs,n),W=await aS($,n),w=await Q0($.fs,n),j=cS(n,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...eS(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=iS(n,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:A,reason:lS(B,S),selected:B,verdict:Q}}function cS($,b,n,A){return A.filter((m)=>m.family===n.family&&uS($,m.family)).filter((m)=>oS(m,n.platform)).map((m)=>hS(m,b,n.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function hS($,b,n){let A=j0($),m=k$(n??[]),y=[],W=Kn(b,A)*25,w=Kn(m,A)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:dS($.source)+($.resolutionPriority??0)+W+w}}function dS($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function uS($,b){return $.adoption.families?.[b]??!0}function oS($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function iS($,b,n,A){let m=$.adoption.thresholds??fS.connect.adoption.thresholds;if(n)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return tS(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 tS($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function lS($,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 pS($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function aS($,b){let n=Un(),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 eS($,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 sS($,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)}
|
|
513
|
-
`),{catalog:
|
|
514
|
+
`}}var Zn={};f(Zn,{uniqueTokens:()=>r$,tokenize:()=>s$,syncAdoptionCatalog:()=>B8,scanWorkspaceAdoptionCandidates:()=>Bn,resolveAdoptionWorkspace:()=>$b,resolveAdoption:()=>Vb,overlap:()=>_A,normalizeText:()=>jW,inferFamilyFromPath:()=>Qn,hasLocalShadcnRegistry:()=>Sn,getContractSpecAdoptionCatalog:()=>KA,createAdoptionCatalogDocument:()=>Wn,candidateTokens:()=>wn});function C($,b,A,n,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:A,packageKind:n,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=[C("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."),C("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."),C("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."),C("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."),C("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 mW=[C("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"]}),C("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"]}),C("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"]}),C("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"]}),C("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."),C("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."),C("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."),C("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 yW=[C("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."),C("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."),C("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."),C("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),C("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."),C("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."),C("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."),C("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."),C("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 WW=[C("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."),C("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."),C("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."),C("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."),C("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."),C("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=[C("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."}]}),C("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"]}),C("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 c5=[...wW,...nW,...mW,...yW,...WW];function KA(){return[...c5].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function Wn($=new Date){return{version:1,generatedAt:$.toISOString(),entries:KA()}}import{DEFAULT_CONTRACTSRC as a5}from"@contractspec/lib.contracts-spec/workspace-config";function jW($){return $.toLowerCase().trim()}function s$($){return jW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function r$($){return[...new Set($.flatMap((b)=>s$(b)))]}function wn($){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 r$(b)}function _A($,b){let A=new Set(b);return $.filter((n)=>A.has(n)).length}import{resolve as h5}from"path";import{ContractsrcSchema as d5,DEFAULT_CONTRACTSRC as jn}from"@contractspec/lib.contracts-spec/workspace-config";async function $b($,b={}){let A=h5(b.cwd??process.cwd()),n=b.workspaceRoot??x(A),m=b.packageRoot??c(A),y=b.config?SW(jn,b.config):await u5($,n,m);return{adoption:y.connect?.adoption??jn.connect.adoption,config:y,cwd:A,packageRoot:m,workspaceRoot:n}}async function u5($,b,A){let n=jn;if(b!==A)n=await BW($,n,$.join(b,".contractsrc.json"));return BW($,n,$.join(A,".contractsrc.json"))}async function BW($,b,A){if(!await $.exists(A))return b;try{let n=JSON.parse(await $.readFile(A)),m=d5.safeParse(n);if(!m.success)return b;return SW(b,m.data)}catch{return b}}function SW($,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 o5=["package.json","packages/*/package.json"];async function Bn($,b){let[A,n]=await Promise.all([i5($,b),l5($,b)]);return{fileCandidates:n,packageCandidates:A}}async function Sn($,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 i5($,b){let A=await $.glob({patterns:o5,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),n=[];for(let m of A)try{let y=JSON.parse(await $.readFile($.join(b.workspaceRoot,m))),W=Qn(m);if(!W)continue;let w=y.name??$.dirname(m);n.push({id:`workspace.package.${w}`,source:"workspace",family:W,title:w,description:y.description??`Local reusable package at ${m}.`,packageKind:p5(m),packageRef:w,capabilityTags:r$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return n}async function l5($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((n)=>{let m=Qn(n);if(!m)return[];let y=n.split("/").pop()?.replace(/\.[^.]+$/,"")??n;return[{id:`workspace.file.${n}`,source:"workspace",family:m,title:y,description:`Local reusable source at ${n}.`,filePath:n,capabilityTags:s$(n),preferredUseCases:[n],resolutionPriority:t5(m,n)}]})}function Qn($){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 t5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function p5($){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 Vb($,b){let A=await $b($.fs,b),n=W8(b),m=r$([n,b.symbol??"",...b.paths??[]]),y=await Bn($.fs,A),W=await w8($,A),w=await Sn($.fs,A),j=e5(A,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...j8(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=n8(A,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:n,reason:y8(B,S),selected:B,verdict:Q}}function e5($,b,A,n){return n.filter((m)=>m.family===A.family&&b8($,m.family)).filter((m)=>A8(m,A.platform)).map((m)=>s5(m,b,A.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function s5($,b,A){let n=wn($),m=r$(A??[]),y=[],W=_A(b,n)*25,w=_A(m,n)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:$8($.source)+($.resolutionPriority??0)+W+w}}function $8($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function b8($,b){return $.adoption.families?.[b]??!0}function A8($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function n8($,b,A,n){let m=$.adoption.thresholds??a5.connect.adoption.thresholds;if(A)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return m8(b.candidate,n)?"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 m8($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function y8($,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 W8($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function w8($,b){let A=KA(),n=b.adoption.catalog?.overrideManifestPath;if(!n||!await $.fs.exists($.fs.join(b.workspaceRoot,n)))return A;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,n)),y=JSON.parse(m);return[...A,...Array.isArray(y)?y:y.entries??[]]}catch{return A}}function j8($,b,A){if($==="ui"&&b==="web"&&A)return[bb("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[bb("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[bb("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[bb("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[bb("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[bb("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function bb($,b,A,n,m){return{id:$,source:"ecosystem",packageRef:A,family:b,packageKind:"primitive",title:n,description:n,capabilityTags:s$(n),preferredUseCases:[n],resolutionPriority:m}}async function B8($,b={}){let A=await $b($.fs,b),n=Wn(),m=$.fs.join(A.workspaceRoot,A.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(m,`${JSON.stringify(n,null,2)}
|
|
515
|
+
`),{catalog:n,catalogPath:m}}import{AGENT_SYSTEM_PROMPTS as S8}from"@contractspec/lib.contracts-spec/llm";class zA{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let A of $.fileStructure){let n=A.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";b.push(`${n} \`${A.path}\``),b.push(` ${A.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let A of $.steps){b.push(`### ${A.order}. ${A.title}`),b.push(""),b.push(A.description),b.push(""),b.push("**Acceptance Criteria:**");for(let n of A.acceptanceCriteria)b.push(`- [ ] ${n}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let A of $.constraints.security)b.push(`- \u26A0\uFE0F ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:S8["claude-code"],taskPrompt:b.join(`
|
|
514
516
|
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
515
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let
|
|
516
|
-
`)}}generateConfig($){let b=$.meta,
|
|
517
|
-
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var
|
|
518
|
-
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,
|
|
519
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let
|
|
517
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let A=[],n=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let m of n){let y=$.matchAll(m);for(let W of y)if(W[1])A.push(W[1])}if(A.length>0)return{errors:A};return{code:$}}}var LA=new zA;import{AGENT_SYSTEM_PROMPTS as Q8}from"@contractspec/lib.contracts-spec/llm";class RA{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 n of $.fileStructure)b.push(`- ${n.type}: \`${n.path}\` - ${n.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let n of $.steps)b.push(`${n.order}. **${n.title}**: ${n.description}`);b.push("");let A=[...$.constraints.policy,...$.constraints.security.map((n)=>`\u26A0\uFE0F ${n}`)];if(A.length>0){b.push("## Constraints"),b.push("");for(let n of A)b.push(`- ${n}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((n)=>`\`${n}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:Q8["cursor-cli"],taskPrompt:b.join(`
|
|
518
|
+
`)}}generateConfig($){let b=$.meta,A=[];if(A.push("---"),A.push(`description: Implementation rules for ${b.key}.v${b.version}`),A.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),A.push("alwaysApply: false"),A.push("---"),A.push(""),A.push(`# ${b.key} Implementation Rules`),A.push(""),A.push(`This ${b.kind} operation must follow the ContractSpec specification.`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Requirements"),A.push(""),A.push("1. Input/output types MUST match the spec schema exactly"),A.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)A.push("3. Events MUST be emitted as specified");if(A.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)A.push(`5. Idempotency: ${$.policy.idempotent}`);if(A.push(""),$.io.errors&&Object.keys($.io.errors).length>0){A.push("## Error Cases"),A.push("");for(let[n,m]of Object.entries($.io.errors))A.push(`- \`${n}\` (HTTP ${m.http??400}): ${m.when}`);A.push("")}if($.sideEffects?.emits?.length){A.push("## Events to Emit"),A.push("");for(let n of $.sideEffects.emits)if("ref"in n)A.push(`- \`${n.ref.key}.v${n.ref.version}\`: ${n.when}`);else A.push(`- \`${n.key}.v${n.version}\`: ${n.when}`);A.push("")}if($.policy.pii?.length){A.push("## PII Handling"),A.push(""),A.push("These fields contain PII and must be handled with care:");for(let n of $.policy.pii)A.push(`- \`${n}\``);A.push("")}if($.acceptance?.scenarios?.length){A.push("## Acceptance Scenarios"),A.push("");for(let n of $.acceptance.scenarios)A.push(`### ${n.key}`),A.push(`- Given: ${n.given.join("; ")}`),A.push(`- When: ${n.when.join("; ")}`),A.push(`- Then: ${n.then.join("; ")}`),A.push("")}return A.join(`
|
|
519
|
+
`)}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 IA=new RA;import{AGENT_SYSTEM_PROMPTS as Z8}from"@contractspec/lib.contracts-spec/llm";class CA{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let A of $.fileStructure)b.push(`| \`${A.path}\` | ${A.type} | ${A.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let A of $.steps)if(b.push(`### Step ${A.order}: ${A.title}`),b.push(""),b.push(A.description),b.push(""),A.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let n of A.acceptanceCriteria)b.push(`- ${n}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let A of $.constraints.security)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),{agent:"generic-mcp",systemPrompt:Z8["generic-mcp"],taskPrompt:b.join(`
|
|
520
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,A=[];return A.push(`# ${b.key} v${b.version}`),A.push(""),A.push(`**Type:** ${b.kind}`),A.push(`**Stability:** ${b.stability}`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Description"),A.push(""),A.push(b.description),A.push(""),A.join(`
|
|
521
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let A=JSON.parse($);if(typeof A.code==="string")return{code:A.code};if(typeof A.errors==="object")return{errors:Array.isArray(A.errors)?A.errors:[String(A.errors)]}}catch{}return{code:$}}}var xA=new CA;var Xn={"claude-code":LA,"cursor-cli":IA,"generic-mcp":xA};function Kb($){let b=Xn[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function Yn(){return Object.keys(Xn)}import{featureToMarkdown as Hn,generateImplementationPlan as QW,operationSpecToAgentPrompt as X8,operationSpecToFullMarkdown as Y8}from"@contractspec/lib.contracts-spec/llm";var H8={defaultAgent:"generic-mcp",verbose:!1};class MA{config;constructor($={}){this.config={...H8,...$}}generateGuide($,b={}){let A=b.agent??this.config.defaultAgent,n=Kb(A),m=QW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),y=n.formatPlan(m),W=Y8($);return{plan:m,prompt:y,markdown:W}}generateFeatureGuide($,b,A={}){let n=A.agent??this.config.defaultAgent,m=Kb(n),y=$.operations?.[0],W=y?b.specs?.get(y.key,y.version):void 0,w;if(W)w=QW(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:Hn($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(w.specMarkdown=Hn($,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=Hn($,b);return{plan:w,prompt:j,markdown:B}}generateAgentConfig($,b){return Kb(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,A="implement",n){return X8($,{taskType:A,existingCode:n})}listAgentTypes(){return Yn()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function G8($){return new MA($)}var q8=new MA;import{detectAuthoringTarget as SS,generateComponentTemplate as QS,generateHandlerTemplate as ZS,generateTestTemplate as XS,getAuthoringTargetDefinition as YS,inferSpecTypeFromFilePath as HS,scanSpecSource as GS}from"@contractspec/module.workspace";var tW={};f(tW,{generateWorkspaceEnvExample:()=>MW,generateWorkflowSpec:()=>lW,generateWorkflowRunnerTemplate:()=>kA,generateWorkflowDevkitWorkflowTemplate:()=>NA,generateWorkflowDevkitStreamRouteTemplate:()=>gA,generateWorkflowDevkitStartRouteTemplate:()=>FA,generateWorkflowDevkitGenericTemplate:()=>PA,generateWorkflowDevkitFollowUpRouteTemplate:()=>vA,generateVisualizationSpec:()=>qW,generateTranslationSpec:()=>HW,generateThemeSpec:()=>iW,generateTestTemplate:()=>PW,generateTestSpec:()=>YW,generateTelemetrySpec:()=>oW,generateTargetEnvExample:()=>EW,generatePwaAppManifestSpec:()=>KW,generateProductIntentSpec:()=>JW,generatePresentationSpec:()=>uW,generatePolicySpec:()=>XW,generateOperationSpec:()=>dW,generateMigrationSpec:()=>hW,generateKnowledgeSpaceSpec:()=>fW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>rW,generateHarnessSuiteSpec:()=>VW,generateHarnessScenarioSpec:()=>UW,generateHandlerTemplate:()=>vW,generateFormSpec:()=>FW,generateFeatureSpec:()=>NW,generateExperimentSpec:()=>DW,generateExampleSpec:()=>EA,generateEventSpec:()=>TW,generateDataViewSpec:()=>IW,generateDataViewRendererTemplate:()=>TA,generateComponentTemplate:()=>gW,generateCapabilitySpec:()=>ZW,generateAppBlueprintSpec:()=>RW,generateAgentSpec:()=>OW});function ZW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
520
522
|
|
|
521
523
|
export const ${nb($.key)}Capability = defineCapability({
|
|
522
524
|
meta: {
|
|
523
525
|
key: '${$.key}',
|
|
524
526
|
version: '${$.version}',
|
|
525
527
|
kind: '${$.kind??"api"}',
|
|
526
|
-
title: '${k(
|
|
528
|
+
title: '${k(Ab($))}',
|
|
527
529
|
description: '${k($.description)}',
|
|
528
|
-
domain: '${k(
|
|
529
|
-
owners: [${
|
|
530
|
-
tags: [${
|
|
530
|
+
domain: '${k(f$($))}',
|
|
531
|
+
owners: [${w$($.owners)}],
|
|
532
|
+
tags: [${w$($.tags)}],
|
|
531
533
|
stability: '${$.stability}',
|
|
532
534
|
},
|
|
533
535
|
provides: [],
|
|
534
536
|
requires: [],
|
|
535
537
|
});
|
|
536
|
-
`}function
|
|
538
|
+
`}function XW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
537
539
|
|
|
538
540
|
export const ${nb($.key)}Policy = definePolicy({
|
|
539
541
|
meta: {
|
|
540
542
|
key: '${$.key}',
|
|
541
543
|
version: '${$.version}',
|
|
542
|
-
title: '${k(
|
|
544
|
+
title: '${k(Ab($))}',
|
|
543
545
|
description: '${k($.description)}',
|
|
544
|
-
domain: '${k(
|
|
545
|
-
owners: [${
|
|
546
|
-
tags: [${
|
|
546
|
+
domain: '${k(f$($))}',
|
|
547
|
+
owners: [${w$($.owners)}],
|
|
548
|
+
tags: [${w$($.tags)}],
|
|
547
549
|
stability: '${$.stability}',
|
|
548
550
|
scope: '${$.scope??"feature"}',
|
|
549
551
|
},
|
|
@@ -551,27 +553,27 @@ export const ${nb($.key)}Policy = definePolicy({
|
|
|
551
553
|
{
|
|
552
554
|
effect: 'allow',
|
|
553
555
|
actions: ['read'],
|
|
554
|
-
resource: { type: '${k(
|
|
556
|
+
resource: { type: '${k(f$($))}' },
|
|
555
557
|
reason: 'TODO: replace with real access rules',
|
|
556
558
|
},
|
|
557
559
|
],
|
|
558
560
|
});
|
|
559
|
-
`}function
|
|
561
|
+
`}function YW($){let b=$.targetVersion??"1.0.0",A=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
560
562
|
|
|
561
563
|
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
562
564
|
meta: {
|
|
563
565
|
key: '${$.key}',
|
|
564
566
|
version: '${$.version}',
|
|
565
|
-
title: '${k(
|
|
567
|
+
title: '${k(Ab($))}',
|
|
566
568
|
description: '${k($.description)}',
|
|
567
|
-
domain: '${k(
|
|
568
|
-
owners: [${
|
|
569
|
-
tags: [${
|
|
569
|
+
domain: '${k(f$($))}',
|
|
570
|
+
owners: [${w$($.owners)}],
|
|
571
|
+
tags: [${w$($.tags)}],
|
|
570
572
|
stability: '${$.stability}',
|
|
571
573
|
},
|
|
572
574
|
target: {
|
|
573
575
|
type: '${$.targetType}',
|
|
574
|
-
${$.targetType}: ${
|
|
576
|
+
${$.targetType}: ${A},
|
|
575
577
|
},
|
|
576
578
|
scenarios: [
|
|
577
579
|
{
|
|
@@ -581,23 +583,23 @@ export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
|
581
583
|
},
|
|
582
584
|
],
|
|
583
585
|
});
|
|
584
|
-
`}function
|
|
586
|
+
`}function HW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
585
587
|
|
|
586
588
|
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
587
589
|
meta: {
|
|
588
590
|
key: '${$.key}',
|
|
589
591
|
version: '${$.version}',
|
|
590
|
-
domain: '${k(
|
|
592
|
+
domain: '${k(f$($))}',
|
|
591
593
|
description: '${k($.description)}',
|
|
592
|
-
owners: [${
|
|
593
|
-
tags: [${
|
|
594
|
+
owners: [${w$($.owners)}],
|
|
595
|
+
tags: [${w$($.tags)}],
|
|
594
596
|
stability: '${$.stability}',
|
|
595
597
|
},
|
|
596
598
|
locale: '${$.locale}',
|
|
597
599
|
fallback: '${$.fallback??$.locale}',
|
|
598
600
|
messages: {
|
|
599
601
|
'${$.key}.title': {
|
|
600
|
-
value: '${k(
|
|
602
|
+
value: '${k(Ab($))}',
|
|
601
603
|
description: 'TODO: replace with a real localized message',
|
|
602
604
|
},
|
|
603
605
|
},
|
|
@@ -608,29 +610,29 @@ export const ${nb($.key)}Job = defineJob({
|
|
|
608
610
|
meta: {
|
|
609
611
|
key: '${$.key}',
|
|
610
612
|
version: '${$.version}',
|
|
611
|
-
title: '${k(
|
|
613
|
+
title: '${k(Ab($))}',
|
|
612
614
|
description: '${k($.description)}',
|
|
613
|
-
domain: '${k(
|
|
614
|
-
owners: [${
|
|
615
|
-
tags: [${
|
|
615
|
+
domain: '${k(f$($))}',
|
|
616
|
+
owners: [${w$($.owners)}],
|
|
617
|
+
tags: [${w$($.tags)}],
|
|
616
618
|
stability: '${$.stability}',
|
|
617
619
|
},
|
|
618
620
|
payload: { schema: {} },
|
|
619
621
|
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
620
622
|
});
|
|
621
|
-
`}function
|
|
623
|
+
`}function qW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
622
624
|
|
|
623
625
|
export const ${nb($.key)}Visualization = defineVisualization({
|
|
624
626
|
meta: {
|
|
625
627
|
key: '${$.key}',
|
|
626
628
|
version: '${$.version}',
|
|
627
|
-
title: '${k(
|
|
629
|
+
title: '${k(Ab($))}',
|
|
628
630
|
description: '${k($.description)}',
|
|
629
631
|
goal: 'TODO: describe the decision this visualization supports',
|
|
630
632
|
context: 'TODO: describe where this visualization appears',
|
|
631
|
-
domain: '${k(
|
|
632
|
-
owners: [${
|
|
633
|
-
tags: [${
|
|
633
|
+
domain: '${k(f$($))}',
|
|
634
|
+
owners: [${w$($.owners)}],
|
|
635
|
+
tags: [${w$($.tags)}],
|
|
634
636
|
stability: '${$.stability}',
|
|
635
637
|
},
|
|
636
638
|
source: {
|
|
@@ -646,19 +648,19 @@ export const ${nb($.key)}Visualization = defineVisualization({
|
|
|
646
648
|
measure: 'value',
|
|
647
649
|
},
|
|
648
650
|
});
|
|
649
|
-
`}function
|
|
651
|
+
`}function Ab($){return $.title??O8($.key.split(".").at(-1)??$.key)}function f$($){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 O8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function EA($){let b=$.packageName??`@contractspec/example.${U8($.key.split(".").at(-1)??$.key)}`,A=`${mb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
650
652
|
|
|
651
|
-
const ${
|
|
653
|
+
const ${A} = defineExample({
|
|
652
654
|
meta: {
|
|
653
655
|
key: '${$.key}',
|
|
654
656
|
version: '${$.version}',
|
|
655
|
-
title: '${
|
|
656
|
-
description: '${
|
|
657
|
+
title: '${h(_b($))}',
|
|
658
|
+
description: '${h($.description)}',
|
|
657
659
|
kind: 'template',
|
|
658
660
|
visibility: 'experimental',
|
|
659
661
|
stability: '${$.stability}',
|
|
660
|
-
owners: [${
|
|
661
|
-
tags: [${
|
|
662
|
+
owners: [${s($.owners)}],
|
|
663
|
+
tags: [${s($.tags)}],
|
|
662
664
|
},
|
|
663
665
|
surfaces: {
|
|
664
666
|
templates: true,
|
|
@@ -671,51 +673,51 @@ const ${n} = defineExample({
|
|
|
671
673
|
},
|
|
672
674
|
});
|
|
673
675
|
|
|
674
|
-
export default ${
|
|
675
|
-
export { ${
|
|
676
|
+
export default ${A};
|
|
677
|
+
export { ${A} };
|
|
676
678
|
`}function OW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
677
679
|
|
|
678
|
-
export const ${
|
|
680
|
+
export const ${mb($.key)}Agent = defineAgent({
|
|
679
681
|
meta: {
|
|
680
682
|
key: '${$.key}',
|
|
681
683
|
version: '${$.version}',
|
|
682
|
-
description: '${
|
|
683
|
-
owners: [${
|
|
684
|
-
tags: [${
|
|
684
|
+
description: '${h($.description)}',
|
|
685
|
+
owners: [${s($.owners)}],
|
|
686
|
+
tags: [${s($.tags)}],
|
|
685
687
|
stability: '${$.stability}',
|
|
686
688
|
},
|
|
687
|
-
instructions: '${
|
|
689
|
+
instructions: '${h($.instructions)}',
|
|
688
690
|
tools: [{ name: 'todo' }],
|
|
689
691
|
});
|
|
690
|
-
`}function
|
|
692
|
+
`}function JW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
691
693
|
|
|
692
|
-
export const ${
|
|
694
|
+
export const ${mb($.key)}ProductIntent = defineProductIntentSpec({
|
|
693
695
|
id: '${$.id??`${$.key}-run`}',
|
|
694
696
|
meta: {
|
|
695
697
|
key: '${$.key}',
|
|
696
698
|
version: '${$.version}',
|
|
697
|
-
title: '${
|
|
698
|
-
description: '${
|
|
699
|
+
title: '${h(_b($))}',
|
|
700
|
+
description: '${h($.description)}',
|
|
699
701
|
goal: 'TODO: capture the desired product outcome',
|
|
700
702
|
context: 'TODO: capture the decision context',
|
|
701
703
|
stability: '${$.stability}',
|
|
702
|
-
owners: [${
|
|
703
|
-
tags: [${
|
|
704
|
+
owners: [${s($.owners)}],
|
|
705
|
+
tags: [${s($.tags)}],
|
|
704
706
|
},
|
|
705
|
-
question: '${
|
|
707
|
+
question: '${h($.question)}',
|
|
706
708
|
insights: { insights: [] },
|
|
707
709
|
});
|
|
708
|
-
`}function
|
|
710
|
+
`}function UW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
709
711
|
|
|
710
|
-
export const ${
|
|
712
|
+
export const ${mb($.key)}HarnessScenario = defineHarnessScenario({
|
|
711
713
|
meta: {
|
|
712
714
|
key: '${$.key}',
|
|
713
715
|
version: '${$.version}',
|
|
714
|
-
title: '${
|
|
715
|
-
description: '${
|
|
716
|
-
domain: '${
|
|
717
|
-
owners: [${
|
|
718
|
-
tags: [${
|
|
716
|
+
title: '${h(_b($))}',
|
|
717
|
+
description: '${h($.description)}',
|
|
718
|
+
domain: '${h(Gn($))}',
|
|
719
|
+
owners: [${s($.owners)}],
|
|
720
|
+
tags: [${s($.tags)}],
|
|
719
721
|
stability: '${$.stability}',
|
|
720
722
|
},
|
|
721
723
|
target: {
|
|
@@ -740,17 +742,17 @@ export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
|
740
742
|
},
|
|
741
743
|
],
|
|
742
744
|
});
|
|
743
|
-
`}function
|
|
745
|
+
`}function VW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
744
746
|
|
|
745
|
-
export const ${
|
|
747
|
+
export const ${mb($.key)}HarnessSuite = defineHarnessSuite({
|
|
746
748
|
meta: {
|
|
747
749
|
key: '${$.key}',
|
|
748
750
|
version: '${$.version}',
|
|
749
|
-
title: '${
|
|
750
|
-
description: '${
|
|
751
|
-
domain: '${
|
|
752
|
-
owners: [${
|
|
753
|
-
tags: [${
|
|
751
|
+
title: '${h(_b($))}',
|
|
752
|
+
description: '${h($.description)}',
|
|
753
|
+
domain: '${h(Gn($))}',
|
|
754
|
+
owners: [${s($.owners)}],
|
|
755
|
+
tags: [${s($.tags)}],
|
|
754
756
|
stability: '${$.stability}',
|
|
755
757
|
},
|
|
756
758
|
scenarios: [
|
|
@@ -763,92 +765,122 @@ export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
|
763
765
|
weight: 1,
|
|
764
766
|
},
|
|
765
767
|
],
|
|
766
|
-
summary: '${
|
|
767
|
-
tags: [${
|
|
768
|
+
summary: '${h($.description)}',
|
|
769
|
+
tags: [${s($.tags)}],
|
|
768
770
|
});
|
|
769
|
-
`}function
|
|
771
|
+
`}function KW($){let b=$.currentRelease??$.version;return`import { definePwaAppManifest } from '@contractspec/lib.contracts-spec/pwa';
|
|
772
|
+
|
|
773
|
+
export const ${mb($.key)}PwaApp = definePwaAppManifest({
|
|
774
|
+
meta: {
|
|
775
|
+
key: '${$.key}',
|
|
776
|
+
version: '${$.version}',
|
|
777
|
+
appId: '${$.appId??$.key}',
|
|
778
|
+
title: '${h(_b($))}',
|
|
779
|
+
description: '${h($.description)}',
|
|
780
|
+
domain: '${h(Gn($))}',
|
|
781
|
+
stability: '${$.stability}',
|
|
782
|
+
owners: [${s($.owners)}],
|
|
783
|
+
tags: [${s($.tags)}],
|
|
784
|
+
},
|
|
785
|
+
currentRelease: '${b}',
|
|
786
|
+
defaultUpdatePolicy: {
|
|
787
|
+
mode: 'optional',
|
|
788
|
+
minSupportedVersion: '${b}',
|
|
789
|
+
},
|
|
790
|
+
releases: [
|
|
791
|
+
{
|
|
792
|
+
version: '${b}',
|
|
793
|
+
releasedAt: new Date().toISOString(),
|
|
794
|
+
notes: 'Initial release manifest.',
|
|
795
|
+
},
|
|
796
|
+
],
|
|
797
|
+
offline: {
|
|
798
|
+
supported: true,
|
|
799
|
+
},
|
|
800
|
+
});
|
|
801
|
+
`}function _b($){return $.title??J8($.key.split(".").at(-1)??$.key)}function Gn($){return $.domain??$.key.split(".")[0]??"contractspec"}function s($){return $.map((b)=>`'${h(b)}'`).join(", ")}function mb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function J8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function U8($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=x8($.key.split(".").pop()??"App")+"AppConfig",A=V8($),n=K8($),m=_W("dataViews",$.dataViews),y=_W("workflows",$.workflows),W=_8($),w=z8($),j=L8($),B=R8($),S=I8($),Q=C8($),Z=$.notes?` notes: '${D($.notes)}',
|
|
770
802
|
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
771
803
|
|
|
772
804
|
export const ${b} = defineAppConfig({
|
|
773
805
|
meta: {
|
|
774
|
-
key: '${
|
|
806
|
+
key: '${D($.key)}',
|
|
775
807
|
version: '${$.version}',
|
|
776
|
-
title: '${
|
|
777
|
-
description: '${
|
|
778
|
-
domain: '${
|
|
779
|
-
owners: [${$.owners.map((X)=>`'${
|
|
780
|
-
tags: [${$.tags.map((X)=>`'${
|
|
808
|
+
title: '${D($.title)}',
|
|
809
|
+
description: '${D($.description)}',
|
|
810
|
+
domain: '${D($.domain)}',
|
|
811
|
+
owners: [${$.owners.map((X)=>`'${D(X)}'`).join(", ")}],
|
|
812
|
+
tags: [${$.tags.map((X)=>`'${D(X)}'`).join(", ")}],
|
|
781
813
|
stability: '${$.stability}',
|
|
782
|
-
appId: '${
|
|
814
|
+
appId: '${D($.appId)}',
|
|
783
815
|
},
|
|
784
|
-
${
|
|
785
|
-
`}function
|
|
786
|
-
`:"",
|
|
816
|
+
${A}${n}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
817
|
+
`}function V8($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((n)=>zW(n)).join(", ")}],
|
|
818
|
+
`:"",A=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((n)=>zW(n)).join(", ")}],
|
|
787
819
|
`:"";return` capabilities: {
|
|
788
|
-
${b}${
|
|
789
|
-
`}function
|
|
790
|
-
`:"",
|
|
820
|
+
${b}${A} },
|
|
821
|
+
`}function K8($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((n)=>`{ key: '${D(n)}' }`).join(", ")}],
|
|
822
|
+
`:"",A=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((n)=>`{ key: '${D(n)}' }`).join(", ")}],
|
|
791
823
|
`:"";return` features: {
|
|
792
|
-
${b}${
|
|
793
|
-
`}function
|
|
794
|
-
key: '${
|
|
795
|
-
version: '${
|
|
824
|
+
${b}${A} },
|
|
825
|
+
`}function _W($,b){if(b.length===0)return"";let A=b.map((n)=>` ${n.slot}: {
|
|
826
|
+
key: '${D(n.key)}'${n.version?`,
|
|
827
|
+
version: '${n.version}'`:""}
|
|
796
828
|
}`).join(`,
|
|
797
829
|
`);return` ${$}: {
|
|
798
|
-
${
|
|
830
|
+
${A}
|
|
799
831
|
},
|
|
800
|
-
`}function
|
|
801
|
-
${$.policyRefs.map((
|
|
802
|
-
key: '${
|
|
803
|
-
version: '${
|
|
832
|
+
`}function _8($){if($.policyRefs.length===0)return"";return` policies: [
|
|
833
|
+
${$.policyRefs.map((A)=>` {
|
|
834
|
+
key: '${D(A.key)}'${A.version?`,
|
|
835
|
+
version: '${A.version}'`:""}
|
|
804
836
|
}`).join(`,
|
|
805
837
|
`)}
|
|
806
838
|
],
|
|
807
|
-
`}function
|
|
808
|
-
`,
|
|
839
|
+
`}function z8($){if(!$.theme)return"";let b=` primary: { key: '${D($.theme.key)}', version: '${$.theme.version}' },
|
|
840
|
+
`,A=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((n)=>`{ key: '${D(n.key)}', version: '${n.version}' }`).join(", ")}],
|
|
809
841
|
`:"";return` theme: {
|
|
810
|
-
${b}${
|
|
811
|
-
`}function
|
|
842
|
+
${b}${A} },
|
|
843
|
+
`}function L8($){if(!$.telemetry)return"";return` telemetry: {
|
|
812
844
|
spec: {
|
|
813
|
-
key: '${
|
|
845
|
+
key: '${D($.telemetry.key)}'${$.telemetry.version?`,
|
|
814
846
|
version: '${$.telemetry.version}'`:""}
|
|
815
847
|
},
|
|
816
848
|
},
|
|
817
|
-
`}function
|
|
818
|
-
`:"",
|
|
849
|
+
`}function R8($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((n)=>LW(n)).join(", ")}],
|
|
850
|
+
`:"",A=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((n)=>LW(n)).join(", ")}],
|
|
819
851
|
`:"";return` experiments: {
|
|
820
|
-
${b}${
|
|
821
|
-
`}function
|
|
822
|
-
${$.featureFlags.map((
|
|
823
|
-
key: '${
|
|
824
|
-
enabled: ${
|
|
825
|
-
${
|
|
826
|
-
${
|
|
852
|
+
${b}${A} },
|
|
853
|
+
`}function I8($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
854
|
+
${$.featureFlags.map((A)=>` {
|
|
855
|
+
key: '${D(A.key)}',
|
|
856
|
+
enabled: ${A.enabled},
|
|
857
|
+
${A.variant?`variant: '${D(A.variant)}',`:""}
|
|
858
|
+
${A.description?`description: '${D(A.description)}',`:""}
|
|
827
859
|
}`).join(`,
|
|
828
860
|
`)}
|
|
829
861
|
],
|
|
830
|
-
`}function
|
|
831
|
-
${$.routes.map((
|
|
862
|
+
`}function C8($){if($.routes.length===0)return"";return` routes: [
|
|
863
|
+
${$.routes.map((A)=>{return` { ${[`path: '${D(A.path)}'`,A.label?`label: '${D(A.label)}'`:null,A.dataView?`dataView: '${D(A.dataView)}'`:null,A.workflow?`workflow: '${D(A.workflow)}'`:null,A.guardKey?`guard: { key: '${D(A.guardKey)}'${A.guardVersion?`, version: '${A.guardVersion}'`:""} }`:null,A.featureFlag?`featureFlag: '${D(A.featureFlag)}'`:null,A.experimentKey?`experiment: { key: '${D(A.experimentKey)}'${A.experimentVersion?`, version: '${A.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
832
864
|
`)}
|
|
833
865
|
],
|
|
834
|
-
`}function
|
|
866
|
+
`}function zW($){return`{ key: '${D($)}' }`}function LW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${D($.key)}'${b} }`}function x8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function D($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function IW($){let b=M8($.name.split(".").pop()??"DataView")+"DataView",A=$.fields.map((y)=>` {
|
|
835
867
|
key: '${y.key}',
|
|
836
|
-
label: '${
|
|
868
|
+
label: '${zb(y.label)}',
|
|
837
869
|
dataPath: '${y.dataPath}',
|
|
838
|
-
${y.format?`format: ${
|
|
870
|
+
${y.format?`format: ${E8(y.format)},`:""}
|
|
839
871
|
${y.sortable?"sortable: true,":""}
|
|
840
872
|
${y.filterable?"filterable: true,":""}
|
|
841
873
|
}`).join(`,
|
|
842
|
-
`),
|
|
874
|
+
`),n=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((y)=>`'${y}'`).join(", ")}],`:"",m=$.itemOperation?`item: { key: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
843
875
|
|
|
844
876
|
export const ${b}: DataViewSpec = {
|
|
845
877
|
meta: {
|
|
846
878
|
key: '${$.name}',
|
|
847
879
|
version: ${$.version},
|
|
848
880
|
entity: '${$.entity}',
|
|
849
|
-
title: '${
|
|
850
|
-
description: '${
|
|
851
|
-
domain: '${
|
|
881
|
+
title: '${zb($.title)}',
|
|
882
|
+
description: '${zb($.description||"Describe the purpose of this data view.")}',
|
|
883
|
+
domain: '${zb($.domain||$.entity)}',
|
|
852
884
|
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
853
885
|
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
854
886
|
stability: '${$.stability}',
|
|
@@ -866,10 +898,10 @@ export const ${b}: DataViewSpec = {
|
|
|
866
898
|
view: {
|
|
867
899
|
kind: '${$.kind}',
|
|
868
900
|
fields: [
|
|
869
|
-
${
|
|
901
|
+
${A}
|
|
870
902
|
],
|
|
871
903
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
872
|
-
${
|
|
904
|
+
${n}
|
|
873
905
|
filters: [
|
|
874
906
|
// Example filter:
|
|
875
907
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -884,13 +916,13 @@ ${n}
|
|
|
884
916
|
// error: { key: 'app.data.error', version: '1.0.0' },
|
|
885
917
|
},
|
|
886
918
|
};
|
|
887
|
-
`}function
|
|
919
|
+
`}function M8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function zb($){return $.replace(/'/g,"\\'")}function E8($){if(typeof $==="string")return`'${zb($)}'`;return JSON.stringify($)}function TA({exportName:$,specImportPath:b,rendererName:A,viewKind:n}){return`'use client';
|
|
888
920
|
|
|
889
921
|
import * as React from 'react';
|
|
890
922
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
891
923
|
import { ${$} } from '${b}';
|
|
892
924
|
|
|
893
|
-
export interface ${
|
|
925
|
+
export interface ${A}Props {
|
|
894
926
|
items?: Record<string, unknown>[];
|
|
895
927
|
item?: Record<string, unknown> | null;
|
|
896
928
|
className?: string;
|
|
@@ -900,17 +932,17 @@ export interface ${n}Props {
|
|
|
900
932
|
}
|
|
901
933
|
|
|
902
934
|
/**
|
|
903
|
-
* Auto-generated renderer for the "${
|
|
935
|
+
* Auto-generated renderer for the "${n}" data view.
|
|
904
936
|
* Customize as needed for app-specific behaviour.
|
|
905
937
|
*/
|
|
906
|
-
export function ${
|
|
938
|
+
export function ${A}({
|
|
907
939
|
items = [],
|
|
908
940
|
item = null,
|
|
909
941
|
className,
|
|
910
942
|
renderActions,
|
|
911
943
|
onSelect,
|
|
912
944
|
onRowClick,
|
|
913
|
-
}: ${
|
|
945
|
+
}: ${A}Props) {
|
|
914
946
|
return (
|
|
915
947
|
<DataViewRenderer
|
|
916
948
|
spec={${$}}
|
|
@@ -923,7 +955,7 @@ export function ${n}({
|
|
|
923
955
|
/>
|
|
924
956
|
);
|
|
925
957
|
}
|
|
926
|
-
`}function CW($){let{name:b,version:
|
|
958
|
+
`}import{buildEnvExample as CW,resolveEnvironmentForTarget as xW}from"@contractspec/integration.runtime/environment";function MW($){return CW(xW({config:$}))}function EW($,b,A){return CW(xW({config:$,targetId:b,profile:A}))}function TW($){let{name:b,version:A,description:n,stability:m,owners:y,tags:W,piiFields:w}=$,j=T8(b.replace(/\./g,"_"))+"V"+A,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
927
959
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
928
960
|
|
|
929
961
|
// TODO: Define event payload schema
|
|
@@ -939,33 +971,33 @@ export const ${B} = new SchemaModel({
|
|
|
939
971
|
export const ${j} = defineEvent({
|
|
940
972
|
name: '${b}',
|
|
941
973
|
name: '${b}',
|
|
942
|
-
version: '${
|
|
943
|
-
description: '${
|
|
944
|
-
description: '${
|
|
974
|
+
version: '${A}',
|
|
975
|
+
description: '${n}',
|
|
976
|
+
description: '${n}',
|
|
945
977
|
stability: '${m}',
|
|
946
978
|
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
947
979
|
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
948
980
|
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
949
981
|
payload: ${B},
|
|
950
982
|
});
|
|
951
|
-
`}function
|
|
983
|
+
`}function T8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function DW($){let b=N8($.name.split(".").pop()??"Experiment")+"Experiment",A=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
952
984
|
${y.overrides.map((w)=>` {
|
|
953
985
|
type: '${w.type}',
|
|
954
|
-
target: '${
|
|
986
|
+
target: '${d(w.target)}',
|
|
955
987
|
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
956
988
|
}`).join(`,
|
|
957
989
|
`)}
|
|
958
990
|
],`:"";return` {
|
|
959
|
-
id: '${
|
|
960
|
-
name: '${
|
|
961
|
-
${y.description?`description: '${
|
|
991
|
+
id: '${d(y.id)}',
|
|
992
|
+
name: '${d(y.name)}',
|
|
993
|
+
${y.description?`description: '${d(y.description)}',`:""}
|
|
962
994
|
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
963
995
|
${W}
|
|
964
996
|
}`}).join(`,
|
|
965
|
-
`),
|
|
997
|
+
`),n=D8($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
966
998
|
${$.successMetrics.map((y)=>` {
|
|
967
|
-
name: '${
|
|
968
|
-
telemetryEvent: { name: '${
|
|
999
|
+
name: '${d(y.name)}',
|
|
1000
|
+
telemetryEvent: { name: '${d(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
969
1001
|
aggregation: '${y.aggregation}',
|
|
970
1002
|
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
971
1003
|
}`).join(`,
|
|
@@ -974,42 +1006,42 @@ ${$.successMetrics.map((y)=>` {
|
|
|
974
1006
|
|
|
975
1007
|
export const ${b}: ExperimentSpec = {
|
|
976
1008
|
meta: {
|
|
977
|
-
key: '${
|
|
1009
|
+
key: '${d($.name)}',
|
|
978
1010
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
979
|
-
title: '${
|
|
980
|
-
description: '${
|
|
981
|
-
domain: '${
|
|
982
|
-
owners: [${$.owners.map((y)=>`'${
|
|
983
|
-
tags: [${$.tags.map((y)=>`'${
|
|
1011
|
+
title: '${d($.name)} experiment',
|
|
1012
|
+
description: '${d($.description||"Describe the experiment goal.")}',
|
|
1013
|
+
domain: '${d($.domain)}',
|
|
1014
|
+
owners: [${$.owners.map((y)=>`'${d(y)}'`).join(", ")}],
|
|
1015
|
+
tags: [${$.tags.map((y)=>`'${d(y)}'`).join(", ")}],
|
|
984
1016
|
stability: '${$.stability}',
|
|
985
1017
|
},
|
|
986
|
-
controlVariant: '${
|
|
1018
|
+
controlVariant: '${d($.controlVariant)}',
|
|
987
1019
|
variants: [
|
|
988
|
-
${
|
|
1020
|
+
${A}
|
|
989
1021
|
],
|
|
990
|
-
allocation: ${
|
|
1022
|
+
allocation: ${n},
|
|
991
1023
|
${m}
|
|
992
1024
|
};
|
|
993
|
-
`}function
|
|
1025
|
+
`}function D8($){switch($.type){case"random":return`{
|
|
994
1026
|
type: 'random',
|
|
995
|
-
${$.salt?`salt: '${
|
|
1027
|
+
${$.salt?`salt: '${d($.salt)}',`:""}
|
|
996
1028
|
}`;case"sticky":return`{
|
|
997
1029
|
type: 'sticky',
|
|
998
1030
|
attribute: '${$.attribute}',
|
|
999
|
-
${$.salt?`salt: '${
|
|
1031
|
+
${$.salt?`salt: '${d($.salt)}',`:""}
|
|
1000
1032
|
}`;case"targeted":return`{
|
|
1001
1033
|
type: 'targeted',
|
|
1002
1034
|
rules: [
|
|
1003
1035
|
${$.rules.map((b)=>` {
|
|
1004
|
-
variantId: '${
|
|
1036
|
+
variantId: '${d(b.variantId)}',
|
|
1005
1037
|
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1006
|
-
${b.policy?`policy: { name: '${
|
|
1007
|
-
${b.expression?`expression: '${
|
|
1038
|
+
${b.policy?`policy: { name: '${d(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1039
|
+
${b.expression?`expression: '${d(b.expression)}',`:""}
|
|
1008
1040
|
}`).join(`,
|
|
1009
1041
|
`)}
|
|
1010
1042
|
],
|
|
1011
1043
|
fallback: '${$.fallback??"control"}',
|
|
1012
|
-
}`;default:return
|
|
1044
|
+
}`;default:return F8($)}}function N8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function d($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function F8($){throw Error(`Unsupported allocation type ${$}`)}function v8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function NW($){let b=(A)=>A.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
1013
1045
|
`);return`/**
|
|
1014
1046
|
* ${$.title} Feature
|
|
1015
1047
|
*
|
|
@@ -1018,15 +1050,15 @@ ${$.rules.map((b)=>` {
|
|
|
1018
1050
|
|
|
1019
1051
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
1020
1052
|
|
|
1021
|
-
export const ${
|
|
1053
|
+
export const ${v8($.key)}Feature = defineFeature({
|
|
1022
1054
|
meta: {
|
|
1023
1055
|
key: '${$.key}',
|
|
1024
1056
|
version: '${$.version}',
|
|
1025
1057
|
title: '${$.title}',
|
|
1026
1058
|
description: '${$.description||"TODO: Add description"}',
|
|
1027
1059
|
domain: '${$.domain}',
|
|
1028
|
-
owners: [${$.owners.map((
|
|
1029
|
-
tags: [${$.tags.map((
|
|
1060
|
+
owners: [${$.owners.map((A)=>`'${A}'`).join(", ")}],
|
|
1061
|
+
tags: [${$.tags.map((A)=>`'${A}'`).join(", ")}],
|
|
1030
1062
|
stability: '${$.stability||"beta"}',
|
|
1031
1063
|
},
|
|
1032
1064
|
|
|
@@ -1046,7 +1078,7 @@ ${b($.presentations)||" // Add presentations here"}
|
|
|
1046
1078
|
${b($.experiments)||" // Add experiments here"}
|
|
1047
1079
|
],
|
|
1048
1080
|
});
|
|
1049
|
-
`}function
|
|
1081
|
+
`}function g8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function FW($){let b=g8($.key),A=`${b}FormModel`,n=`${b}Form`;return`/**
|
|
1050
1082
|
* ${$.title} Form
|
|
1051
1083
|
*
|
|
1052
1084
|
* Auto-generated form spec.
|
|
@@ -1055,8 +1087,8 @@ ${b($.experiments)||" // Add experiments here"}
|
|
|
1055
1087
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
1056
1088
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
1057
1089
|
|
|
1058
|
-
const ${
|
|
1059
|
-
name: '${
|
|
1090
|
+
const ${A} = defineSchemaModel({
|
|
1091
|
+
name: '${A}',
|
|
1060
1092
|
description: '${$.description||"TODO: Add form model description"}',
|
|
1061
1093
|
fields: {
|
|
1062
1094
|
${$.primaryFieldKey}: {
|
|
@@ -1066,7 +1098,7 @@ const ${n} = defineSchemaModel({
|
|
|
1066
1098
|
},
|
|
1067
1099
|
});
|
|
1068
1100
|
|
|
1069
|
-
export const ${
|
|
1101
|
+
export const ${n} = defineFormSpec({
|
|
1070
1102
|
meta: {
|
|
1071
1103
|
key: '${$.key}',
|
|
1072
1104
|
version: '${$.version}',
|
|
@@ -1077,7 +1109,7 @@ export const ${A} = defineFormSpec({
|
|
|
1077
1109
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1078
1110
|
stability: '${$.stability||"beta"}',
|
|
1079
1111
|
},
|
|
1080
|
-
model: ${
|
|
1112
|
+
model: ${A},
|
|
1081
1113
|
fields: [
|
|
1082
1114
|
{
|
|
1083
1115
|
kind: 'text',
|
|
@@ -1102,13 +1134,13 @@ export const ${A} = defineFormSpec({
|
|
|
1102
1134
|
form: 'react-hook-form',
|
|
1103
1135
|
},
|
|
1104
1136
|
});
|
|
1105
|
-
`}function
|
|
1106
|
-
import { ${
|
|
1137
|
+
`}function vW($,b){let A=P8($.split(".").pop()||"unknown")+"Handler",n=DA($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1138
|
+
import { ${n} } from '../contracts/${kW($)}.contracts';
|
|
1107
1139
|
|
|
1108
1140
|
/**
|
|
1109
1141
|
* Handler for ${$}
|
|
1110
1142
|
*/
|
|
1111
|
-
export const ${
|
|
1143
|
+
export const ${A}: ContractHandler<typeof ${n}> = async (
|
|
1112
1144
|
input,
|
|
1113
1145
|
context
|
|
1114
1146
|
) => {
|
|
@@ -1128,27 +1160,27 @@ export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
|
1128
1160
|
throw error;
|
|
1129
1161
|
}
|
|
1130
1162
|
};
|
|
1131
|
-
`}function
|
|
1163
|
+
`}function gW($,b){let A=DA($);return`import React from 'react';
|
|
1132
1164
|
|
|
1133
|
-
interface ${
|
|
1165
|
+
interface ${A}Props {
|
|
1134
1166
|
// TODO: Define props based on presentation spec
|
|
1135
1167
|
}
|
|
1136
1168
|
|
|
1137
1169
|
/**
|
|
1138
1170
|
* ${b}
|
|
1139
1171
|
*/
|
|
1140
|
-
export const ${
|
|
1172
|
+
export const ${A}: React.FC<${A}Props> = (props) => {
|
|
1141
1173
|
return (
|
|
1142
1174
|
<div>
|
|
1143
1175
|
{/* TODO: Implement component UI */}
|
|
1144
|
-
<p>Component: ${
|
|
1176
|
+
<p>Component: ${A}</p>
|
|
1145
1177
|
</div>
|
|
1146
1178
|
);
|
|
1147
1179
|
};
|
|
1148
|
-
`}function
|
|
1149
|
-
import { ${
|
|
1180
|
+
`}function PW($,b){let A=b==="handler"?"../handlers":"../components",n=DA($);return`import { describe, it, expect } from 'bun:test';
|
|
1181
|
+
import { ${n} } from '${A}/${kW($)}';
|
|
1150
1182
|
|
|
1151
|
-
describe('${
|
|
1183
|
+
describe('${n}', () => {
|
|
1152
1184
|
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
1153
1185
|
// TODO: Implement test
|
|
1154
1186
|
expect(true).toBe(true);
|
|
@@ -1164,27 +1196,27 @@ describe('${A}', () => {
|
|
|
1164
1196
|
// TODO: Test accessibility
|
|
1165
1197
|
});`}
|
|
1166
1198
|
});
|
|
1167
|
-
`}function
|
|
1199
|
+
`}function P8($){let b=DA($);return b.charAt(0).toLowerCase()+b.slice(1)}function DA($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function kW($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function rW($){let b=i8($.name.split(".").pop()??"Integration"),A=`${b}IntegrationSpec`,n=`register${b}Integration`,m=$.supportedModes.length?$.supportedModes:["managed"],y=m.map((H)=>`'${H}'`).join(", "),W=$.capabilitiesProvided.map((H)=>` { key: '${H.key}', version: '${H.version}' }`).join(`,
|
|
1168
1200
|
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1169
|
-
${$.capabilitiesRequired.map((
|
|
1201
|
+
${$.capabilitiesRequired.map((H)=>{let J=H.version!==void 0?`, version: '${H.version}'`:"",O=H.optional?", optional: true":"",V=H.reason?`, reason: '${j$(H.reason)}'`:"";return` { key: '${H.key}'${J}${O}${V} }`}).join(`,
|
|
1170
1202
|
`)}
|
|
1171
|
-
],`:"",j=
|
|
1172
|
-
`:"",X=
|
|
1203
|
+
],`:"",j=k8($.configFields),B=f8($.configFields),S=r8($.secretFields),Q=c8($.secretFields),Z=$.docsUrl?` docsUrl: '${j$($.docsUrl)}',
|
|
1204
|
+
`:"",X=h8($.rateLimitRpm,$.rateLimitRph),Y=d8(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1173
1205
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
1174
1206
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
1175
1207
|
|
|
1176
|
-
export const ${
|
|
1208
|
+
export const ${A}: IntegrationSpec = {
|
|
1177
1209
|
meta: {
|
|
1178
1210
|
key: '${$.name}',
|
|
1179
1211
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
1180
1212
|
category: '${$.category}',
|
|
1181
|
-
displayName: '${
|
|
1182
|
-
title: '${
|
|
1183
|
-
description: '${
|
|
1184
|
-
domain: '${
|
|
1185
|
-
owners: [${$.owners.map((
|
|
1186
|
-
tags: [${$.tags.map((
|
|
1187
|
-
stability: StabilityEnum.${
|
|
1213
|
+
displayName: '${j$($.displayName)}',
|
|
1214
|
+
title: '${j$($.title)}',
|
|
1215
|
+
description: '${j$($.description)}',
|
|
1216
|
+
domain: '${j$($.domain)}',
|
|
1217
|
+
owners: [${$.owners.map((H)=>`'${j$(H)}'`).join(", ")}],
|
|
1218
|
+
tags: [${$.tags.map((H)=>`'${j$(H)}'`).join(", ")}],
|
|
1219
|
+
stability: StabilityEnum.${o8($.stability)},
|
|
1188
1220
|
},
|
|
1189
1221
|
supportedModes: [${y}],
|
|
1190
1222
|
capabilities: {
|
|
@@ -1207,115 +1239,115 @@ ${Z}${X}${Y} healthCheck: {
|
|
|
1207
1239
|
},
|
|
1208
1240
|
};
|
|
1209
1241
|
|
|
1210
|
-
export function ${
|
|
1242
|
+
export function ${n}(
|
|
1211
1243
|
registry: IntegrationSpecRegistry
|
|
1212
1244
|
): IntegrationSpecRegistry {
|
|
1213
|
-
return registry.register(${
|
|
1245
|
+
return registry.register(${A});
|
|
1214
1246
|
}
|
|
1215
|
-
`}function
|
|
1216
|
-
`:"",
|
|
1247
|
+
`}function k8($){let b=$.filter((m)=>m.required),A=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1248
|
+
`:"",n=$.length?$.map((m)=>{let y=m.description?`, description: '${j$(m.description)}'`:"";return` ${m.key}: { type: '${u8(m.type)}'${y} }`}).join(`,
|
|
1217
1249
|
`):"";return` schema: {
|
|
1218
1250
|
type: 'object',
|
|
1219
|
-
${
|
|
1220
|
-
${
|
|
1251
|
+
${A} properties: {
|
|
1252
|
+
${n||" "}
|
|
1221
1253
|
},
|
|
1222
1254
|
},
|
|
1223
|
-
`}function
|
|
1224
|
-
`:"",
|
|
1255
|
+
`}function r8($){let b=$.filter((m)=>m.required),A=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1256
|
+
`:"",n=$.length?$.map((m)=>{let y=m.description?`, description: '${j$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
1225
1257
|
`):"";return` schema: {
|
|
1226
1258
|
type: 'object',
|
|
1227
|
-
${
|
|
1228
|
-
${
|
|
1259
|
+
${A} properties: {
|
|
1260
|
+
${n||" "}
|
|
1229
1261
|
},
|
|
1230
1262
|
},
|
|
1231
|
-
`}function
|
|
1232
|
-
${$.map((
|
|
1263
|
+
`}function f8($){if($.length===0)return"{}";return`{
|
|
1264
|
+
${$.map((A)=>{switch(A.type){case"number":return` ${A.key}: 0`;case"boolean":return` ${A.key}: true`;case"string":default:return` ${A.key}: '${A.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
1233
1265
|
`)}
|
|
1234
|
-
}`}function
|
|
1235
|
-
${$.map((
|
|
1266
|
+
}`}function c8($){if($.length===0)return"{}";return`{
|
|
1267
|
+
${$.map((A)=>` ${A.key}: '${A.key.toUpperCase()}_SECRET'`).join(`,
|
|
1236
1268
|
`)}
|
|
1237
|
-
}`}function
|
|
1269
|
+
}`}function h8($,b){if($==null&&b==null)return"";let A=[];if($!=null)A.push(` rpm: ${$}`);if(b!=null)A.push(` rph: ${b}`);return` constraints: {
|
|
1238
1270
|
rateLimit: {
|
|
1239
|
-
${
|
|
1271
|
+
${A.join(`,
|
|
1240
1272
|
`)}
|
|
1241
1273
|
},
|
|
1242
1274
|
},
|
|
1243
|
-
`}function
|
|
1244
|
-
`:"",m=
|
|
1245
|
-
`:"";if(!
|
|
1246
|
-
${
|
|
1247
|
-
`}function
|
|
1275
|
+
`}function d8($,b,A){if(!$.includes("byok"))return"";let n=b?` setupInstructions: '${j$(b)}',
|
|
1276
|
+
`:"",m=A&&A.length?` requiredScopes: [${A.map((y)=>`'${j$(y)}'`).join(", ")}],
|
|
1277
|
+
`:"";if(!n&&!m)return"";return` byokSetup: {
|
|
1278
|
+
${n}${m} },
|
|
1279
|
+
`}function u8($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function o8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function i8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function j$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function fW($){let b=e8($.name.split(".").pop()??"KnowledgeSpace"),A=`${b}KnowledgeSpace`,n=`register${b}KnowledgeSpace`,m=l8($),y=t8($),W=p8($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1248
1280
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1249
1281
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1250
1282
|
|
|
1251
|
-
export const ${
|
|
1283
|
+
export const ${A}: KnowledgeSpaceSpec = {
|
|
1252
1284
|
meta: {
|
|
1253
1285
|
key: '${$.name}',
|
|
1254
1286
|
version: ${$.version},
|
|
1255
1287
|
category: '${$.category}',
|
|
1256
|
-
displayName: '${
|
|
1257
|
-
title: '${
|
|
1258
|
-
description: '${
|
|
1259
|
-
domain: '${
|
|
1260
|
-
owners: [${$.owners.map((j)=>`'${
|
|
1261
|
-
tags: [${$.tags.map((j)=>`'${
|
|
1262
|
-
stability: StabilityEnum.${
|
|
1288
|
+
displayName: '${O$($.displayName)}',
|
|
1289
|
+
title: '${O$($.title)}',
|
|
1290
|
+
description: '${O$($.description)}',
|
|
1291
|
+
domain: '${O$($.domain)}',
|
|
1292
|
+
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1293
|
+
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1294
|
+
stability: StabilityEnum.${a8($.stability)},
|
|
1263
1295
|
},
|
|
1264
1296
|
retention: ${m},
|
|
1265
1297
|
access: {
|
|
1266
1298
|
${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${w}
|
|
1267
1299
|
`:""} },
|
|
1268
|
-
${W} description: '${
|
|
1300
|
+
${W} description: '${O$($.description||$.displayName)}',
|
|
1269
1301
|
};
|
|
1270
1302
|
|
|
1271
|
-
export function ${
|
|
1303
|
+
export function ${n}(
|
|
1272
1304
|
registry: KnowledgeSpaceRegistry
|
|
1273
1305
|
): KnowledgeSpaceRegistry {
|
|
1274
|
-
return registry.register(${
|
|
1306
|
+
return registry.register(${A});
|
|
1275
1307
|
}
|
|
1276
|
-
`}function
|
|
1277
|
-
`,
|
|
1278
|
-
`;return`${b}${
|
|
1308
|
+
`}function l8($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",A=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${A} }`}function t8($){let b=` trustLevel: '${$.trustLevel}',
|
|
1309
|
+
`,A=` automationWritable: ${$.automationWritable},
|
|
1310
|
+
`;return`${b}${A}`}function p8($){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: {
|
|
1279
1311
|
${b.join(`,
|
|
1280
1312
|
`)}
|
|
1281
1313
|
},
|
|
1282
|
-
`}function
|
|
1314
|
+
`}function a8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function e8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function O$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function hW($){let A=`${s8($.name.split(".").pop()??"Migration")}Migration`,n=$.dependencies.length>0?`dependencies: [${$.dependencies.map((m)=>`'${m}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1283
1315
|
|
|
1284
|
-
export const ${
|
|
1316
|
+
export const ${A}: MigrationSpec = {
|
|
1285
1317
|
meta: {
|
|
1286
1318
|
key: '${$.name}',
|
|
1287
1319
|
version: ${$.version},
|
|
1288
|
-
title: '${
|
|
1289
|
-
description: '${
|
|
1290
|
-
domain: '${
|
|
1320
|
+
title: '${c$($.title)}',
|
|
1321
|
+
description: '${c$($.description??"")}',
|
|
1322
|
+
domain: '${c$($.domain)}',
|
|
1291
1323
|
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1292
1324
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1293
1325
|
stability: '${$.stability}',
|
|
1294
1326
|
},
|
|
1295
1327
|
plan: {
|
|
1296
1328
|
up: [
|
|
1297
|
-
${
|
|
1329
|
+
${cW($.up)}
|
|
1298
1330
|
],${$.down&&$.down.length?`
|
|
1299
1331
|
down: [
|
|
1300
|
-
${
|
|
1332
|
+
${cW($.down)}
|
|
1301
1333
|
],`:""}
|
|
1302
1334
|
},
|
|
1303
|
-
${
|
|
1335
|
+
${n}
|
|
1304
1336
|
};
|
|
1305
|
-
`}function
|
|
1337
|
+
`}function cW($){return $.map((b)=>{let A=b.description?`description: '${c$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1306
1338
|
kind: 'schema',
|
|
1307
|
-
${
|
|
1308
|
-
sql: \`${
|
|
1339
|
+
${A}
|
|
1340
|
+
sql: \`${c$(b.sql??"")}\`,
|
|
1309
1341
|
}`;case"data":return` {
|
|
1310
1342
|
kind: 'data',
|
|
1311
|
-
${
|
|
1312
|
-
script: \`${
|
|
1343
|
+
${A}
|
|
1344
|
+
script: \`${c$(b.script??"")}\`,
|
|
1313
1345
|
}`;case"validation":default:return` {
|
|
1314
1346
|
kind: 'validation',
|
|
1315
|
-
${
|
|
1316
|
-
assertion: \`${
|
|
1347
|
+
${A}
|
|
1348
|
+
assertion: \`${c$(b.assertion??"")}\`,
|
|
1317
1349
|
}`}}).join(`,
|
|
1318
|
-
`)}function
|
|
1350
|
+
`)}function s8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function c$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function dW($){let{name:b,version:A,kind:n,description:m,goal:y,context:W,stability:w,owners:j,tags:B,auth:S,flags:Q}=$,Z=$S(b.split(".").pop()||"Unknown")+"Spec",X=Z.replace("Spec","Input"),Y=Z.replace("Spec","Output");return`import { define${qn(n)} } from '@contractspec/lib.contracts-spec';
|
|
1319
1351
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1320
1352
|
|
|
1321
1353
|
// TODO: Define input schema
|
|
@@ -1338,15 +1370,15 @@ export const ${Y} = new SchemaModel({
|
|
|
1338
1370
|
},
|
|
1339
1371
|
});
|
|
1340
1372
|
|
|
1341
|
-
export const ${Z} = define${
|
|
1373
|
+
export const ${Z} = define${qn(n)}({
|
|
1342
1374
|
meta: {
|
|
1343
1375
|
key: '${b}',
|
|
1344
1376
|
key: '${b}',
|
|
1345
|
-
version: '${
|
|
1377
|
+
version: '${A}',
|
|
1346
1378
|
stability: '${w}',
|
|
1347
1379
|
stability: '${w}',
|
|
1348
|
-
owners: [${j.map((
|
|
1349
|
-
tags: [${B.map((
|
|
1380
|
+
owners: [${j.map((H)=>`'${H}'`).join(", ")}],
|
|
1381
|
+
tags: [${B.map((H)=>`'${H}'`).join(", ")}],
|
|
1350
1382
|
description: '${m}',
|
|
1351
1383
|
goal: '${y}',
|
|
1352
1384
|
context: '${W}',
|
|
@@ -1367,7 +1399,7 @@ export const ${Z} = define${O0(A)}({
|
|
|
1367
1399
|
|
|
1368
1400
|
policy: {
|
|
1369
1401
|
auth: '${S}',
|
|
1370
|
-
${Q.length>0?`flags: [${Q.map((
|
|
1402
|
+
${Q.length>0?`flags: [${Q.map((H)=>`'${H}'`).join(", ")}],`:"// flags: [],"}
|
|
1371
1403
|
},
|
|
1372
1404
|
|
|
1373
1405
|
sideEffects: {
|
|
@@ -1381,9 +1413,9 @@ export const ${Z} = define${O0(A)}({
|
|
|
1381
1413
|
},
|
|
1382
1414
|
|
|
1383
1415
|
transport: {
|
|
1384
|
-
rest: { method: '${
|
|
1416
|
+
rest: { method: '${n==="command"?"POST":"GET"}' },
|
|
1385
1417
|
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1386
|
-
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(
|
|
1418
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(A).replace(/\./g,"_")}' },
|
|
1387
1419
|
},
|
|
1388
1420
|
|
|
1389
1421
|
acceptance: {
|
|
@@ -1404,7 +1436,7 @@ export const ${Z} = define${O0(A)}({
|
|
|
1404
1436
|
],
|
|
1405
1437
|
},
|
|
1406
1438
|
});
|
|
1407
|
-
`}function
|
|
1439
|
+
`}function qn($){return $.charAt(0).toUpperCase()+$.slice(1)}function $S($){return $.split(/[-_.]/).map(qn).join("")}function uW($){let{name:b,version:A,description:n,stability:m,owners:y,tags:W,presentationKind:w}=$,j=bS(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1408
1440
|
kind: 'web_component',
|
|
1409
1441
|
framework: 'react',
|
|
1410
1442
|
componentKey: '${b.replace(/\./g,"_")}',
|
|
@@ -1421,7 +1453,7 @@ export const ${Z} = define${O0(A)}({
|
|
|
1421
1453
|
},`;break;case"markdown":B=` content: {
|
|
1422
1454
|
kind: 'markdown',
|
|
1423
1455
|
content: \`
|
|
1424
|
-
# ${
|
|
1456
|
+
# ${n}
|
|
1425
1457
|
|
|
1426
1458
|
TODO: Add markdown content here
|
|
1427
1459
|
\`,
|
|
@@ -1442,11 +1474,11 @@ import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
|
1442
1474
|
export const ${j}: PresentationSpec = {
|
|
1443
1475
|
meta: {
|
|
1444
1476
|
key: '${b}',
|
|
1445
|
-
version: ${
|
|
1477
|
+
version: ${A},
|
|
1446
1478
|
stability: '${m}',
|
|
1447
1479
|
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1448
1480
|
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1449
|
-
description: '${
|
|
1481
|
+
description: '${n}',
|
|
1450
1482
|
},
|
|
1451
1483
|
|
|
1452
1484
|
policy: {
|
|
@@ -1456,25 +1488,25 @@ export const ${j}: PresentationSpec = {
|
|
|
1456
1488
|
|
|
1457
1489
|
${B}
|
|
1458
1490
|
};
|
|
1459
|
-
`}function
|
|
1491
|
+
`}function bS($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function oW($){let b=AS($.name.split(".").pop()??"Telemetry")+"Telemetry",A=$.providers?.length?`providers: [
|
|
1460
1492
|
${$.providers.map((m)=>` {
|
|
1461
1493
|
type: '${m.type}',
|
|
1462
|
-
config: ${
|
|
1494
|
+
config: ${nS(m.config)},
|
|
1463
1495
|
}`).join(`,
|
|
1464
1496
|
`)}
|
|
1465
|
-
],`:"",
|
|
1497
|
+
],`:"",n=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1466
1498
|
type: '${w.type}',
|
|
1467
1499
|
${w.required?"required: true,":""}
|
|
1468
1500
|
${w.pii?"pii: true,":""}
|
|
1469
1501
|
${w.redact?"redact: true,":""}
|
|
1470
|
-
${w.description?`description: '${
|
|
1502
|
+
${w.description?`description: '${t(w.description)}',`:""}
|
|
1471
1503
|
}`).join(`,
|
|
1472
1504
|
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1473
1505
|
enabled: true,
|
|
1474
1506
|
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1475
1507
|
thresholds: [
|
|
1476
1508
|
${m.anomalyRules.map((w)=>` {
|
|
1477
|
-
metric: '${
|
|
1509
|
+
metric: '${t(w.metric)}',
|
|
1478
1510
|
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1479
1511
|
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1480
1512
|
}`).join(`,
|
|
@@ -1485,46 +1517,46 @@ ${m.anomalyRules.map((w)=>` {
|
|
|
1485
1517
|
enabled: true,
|
|
1486
1518
|
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1487
1519
|
},`:"";return` {
|
|
1488
|
-
name: '${
|
|
1520
|
+
name: '${t(m.name)}',
|
|
1489
1521
|
version: ${m.version},
|
|
1490
1522
|
semantics: {
|
|
1491
|
-
what: '${
|
|
1492
|
-
${m.who?`who: '${
|
|
1493
|
-
${m.why?`why: '${
|
|
1523
|
+
what: '${t(m.what)}',
|
|
1524
|
+
${m.who?`who: '${t(m.who)}',`:""}
|
|
1525
|
+
${m.why?`why: '${t(m.why)}',`:""}
|
|
1494
1526
|
},
|
|
1495
1527
|
privacy: '${m.privacy}',
|
|
1496
1528
|
properties: {
|
|
1497
1529
|
${y}
|
|
1498
1530
|
},
|
|
1499
1531
|
${typeof m.retentionDays==="number"?`retention: { days: ${m.retentionDays}, ${m.retentionPolicy?`policy: '${m.retentionPolicy}'`:""} },`:""}
|
|
1500
|
-
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${
|
|
1532
|
+
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${t(m.samplingConditions)}']`:""} },`:""}
|
|
1501
1533
|
${W}
|
|
1502
|
-
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${
|
|
1534
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${t(w)}'`).join(", ")}],`:""}
|
|
1503
1535
|
}`}).join(`,
|
|
1504
1536
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1505
1537
|
|
|
1506
1538
|
export const ${b}: TelemetrySpec = {
|
|
1507
1539
|
meta: {
|
|
1508
|
-
key: '${
|
|
1540
|
+
key: '${t($.name)}',
|
|
1509
1541
|
version: ${$.version},
|
|
1510
|
-
title: '${
|
|
1511
|
-
description: '${
|
|
1512
|
-
domain: '${
|
|
1513
|
-
owners: [${$.owners.map((m)=>`'${
|
|
1514
|
-
tags: [${$.tags.map((m)=>`'${
|
|
1542
|
+
title: '${t($.name)} telemetry',
|
|
1543
|
+
description: '${t($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1544
|
+
domain: '${t($.domain)}',
|
|
1545
|
+
owners: [${$.owners.map((m)=>`'${t(m)}'`).join(", ")}],
|
|
1546
|
+
tags: [${$.tags.map((m)=>`'${t(m)}'`).join(", ")}],
|
|
1515
1547
|
stability: '${$.stability}',
|
|
1516
1548
|
},
|
|
1517
1549
|
config: {
|
|
1518
1550
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1519
1551
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1520
1552
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1521
|
-
${
|
|
1553
|
+
${A}
|
|
1522
1554
|
},
|
|
1523
1555
|
events: [
|
|
1524
|
-
${
|
|
1556
|
+
${n}
|
|
1525
1557
|
],
|
|
1526
1558
|
};
|
|
1527
|
-
`}function
|
|
1559
|
+
`}function AS($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function nS($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${t(b)}'`}function mS($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function iW($){return`/**
|
|
1528
1560
|
* ${$.title} Theme
|
|
1529
1561
|
*
|
|
1530
1562
|
* Auto-generated theme spec.
|
|
@@ -1532,7 +1564,7 @@ ${A}
|
|
|
1532
1564
|
|
|
1533
1565
|
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1534
1566
|
|
|
1535
|
-
export const ${
|
|
1567
|
+
export const ${mS($.key)}Theme = defineTheme({
|
|
1536
1568
|
meta: {
|
|
1537
1569
|
key: '${$.key}',
|
|
1538
1570
|
version: '${$.version}',
|
|
@@ -1552,11 +1584,11 @@ export const ${t5($.key)}Theme = defineTheme({
|
|
|
1552
1584
|
},
|
|
1553
1585
|
},
|
|
1554
1586
|
});
|
|
1555
|
-
`}function
|
|
1556
|
-
`),
|
|
1587
|
+
`}function lW($){let b=WS($.name.split(".").pop()??"Workflow")+"Workflow",A=$.steps.map((m)=>yS(m)).join(`,
|
|
1588
|
+
`),n=$.transitions.map((m)=>` {
|
|
1557
1589
|
from: '${m.from}',
|
|
1558
1590
|
to: '${m.to}',
|
|
1559
|
-
${m.condition?` condition: '${
|
|
1591
|
+
${m.condition?` condition: '${yb(m.condition)}',`:""}
|
|
1560
1592
|
}`).join(`,
|
|
1561
1593
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1562
1594
|
|
|
@@ -1572,9 +1604,9 @@ export const ${b}: WorkflowSpec = {
|
|
|
1572
1604
|
meta: {
|
|
1573
1605
|
key: '${$.name}',
|
|
1574
1606
|
version: ${$.version},
|
|
1575
|
-
title: '${
|
|
1576
|
-
description: '${
|
|
1577
|
-
domain: '${
|
|
1607
|
+
title: '${yb($.title)}',
|
|
1608
|
+
description: '${yb($.description)}',
|
|
1609
|
+
domain: '${yb($.domain)}',
|
|
1578
1610
|
stability: '${$.stability}',
|
|
1579
1611
|
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1580
1612
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
@@ -1582,22 +1614,22 @@ export const ${b}: WorkflowSpec = {
|
|
|
1582
1614
|
definition: {
|
|
1583
1615
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1584
1616
|
`:""} steps: [
|
|
1585
|
-
${
|
|
1617
|
+
${A}
|
|
1586
1618
|
],
|
|
1587
1619
|
transitions: [
|
|
1588
|
-
${
|
|
1620
|
+
${n}
|
|
1589
1621
|
],
|
|
1590
1622
|
},
|
|
1591
1623
|
${$.policyFlags.length>0?`policy: {
|
|
1592
1624
|
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1593
1625
|
},`:"// policy: { flags: [] },"}
|
|
1594
1626
|
};
|
|
1595
|
-
`}function
|
|
1596
|
-
`)}function
|
|
1627
|
+
`}function yS($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${yb($.label)}',`];if($.description)b.push(` description: '${yb($.description)}',`);let A=[];if($.operation)A.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)A.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(A.length)b.push(` action: { ${A.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1628
|
+
`)}function WS($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function yb($){return $.replace(/'/g,"\\'")}function NA({exportName:$,specImportPath:b,workflowFunctionName:A}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1597
1629
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1598
1630
|
import { ${$} } from '${b}';
|
|
1599
1631
|
|
|
1600
|
-
export async function ${
|
|
1632
|
+
export async function ${A}(input = {}, bridge = {}) {
|
|
1601
1633
|
"use workflow";
|
|
1602
1634
|
|
|
1603
1635
|
// Keep the workflow function deterministic.
|
|
@@ -1614,7 +1646,7 @@ export async function ${n}(input = {}, bridge = {}) {
|
|
|
1614
1646
|
},
|
|
1615
1647
|
});
|
|
1616
1648
|
}
|
|
1617
|
-
`}function
|
|
1649
|
+
`}function FA($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1618
1650
|
import { ${b} } from '${$}';
|
|
1619
1651
|
|
|
1620
1652
|
export const POST = createWorkflowDevkitStartRoute({
|
|
@@ -1623,17 +1655,17 @@ export const POST = createWorkflowDevkitStartRoute({
|
|
|
1623
1655
|
return [body];
|
|
1624
1656
|
},
|
|
1625
1657
|
});
|
|
1626
|
-
`}function
|
|
1658
|
+
`}function vA(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1627
1659
|
|
|
1628
1660
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1629
1661
|
resolveToken({ runId }) {
|
|
1630
1662
|
return \`workflow-session:\${runId}\`;
|
|
1631
1663
|
},
|
|
1632
1664
|
});
|
|
1633
|
-
`}function
|
|
1665
|
+
`}function gA(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1634
1666
|
|
|
1635
1667
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1636
|
-
`}function
|
|
1668
|
+
`}function PA($,b){return`import { ${b} } from '${$}';
|
|
1637
1669
|
|
|
1638
1670
|
export const workflowDevkitBootstrap = {
|
|
1639
1671
|
workflow: ${b},
|
|
@@ -1645,13 +1677,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1645
1677
|
};
|
|
1646
1678
|
},
|
|
1647
1679
|
};
|
|
1648
|
-
`}function
|
|
1680
|
+
`}function kA({exportName:$,specImportPath:b,runnerName:A,workflowName:n}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1649
1681
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1650
1682
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1651
1683
|
import { ${$} } from '${b}';
|
|
1652
1684
|
|
|
1653
1685
|
/**
|
|
1654
|
-
* Runner wiring for ${
|
|
1686
|
+
* Runner wiring for ${n}.
|
|
1655
1687
|
*
|
|
1656
1688
|
* TODO:
|
|
1657
1689
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1663,7 +1695,7 @@ registry.register(${$});
|
|
|
1663
1695
|
|
|
1664
1696
|
const stateStore = new InMemoryStateStore();
|
|
1665
1697
|
|
|
1666
|
-
export const ${
|
|
1698
|
+
export const ${A} = new WorkflowRunner({
|
|
1667
1699
|
registry,
|
|
1668
1700
|
stateStore,
|
|
1669
1701
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1685,12 +1717,12 @@ export const ${n} = new WorkflowRunner({
|
|
|
1685
1717
|
// console.log(event, payload);
|
|
1686
1718
|
},
|
|
1687
1719
|
});
|
|
1688
|
-
`}import{getAuthoringTargetDefinition as
|
|
1689
|
-
`],[y,`# ${
|
|
1720
|
+
`}import{getAuthoringTargetDefinition as wS}from"@contractspec/module.workspace";var pW={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function aW($,b){let A=jS($,b.specPath),n=BS($,b.target,A),m=$.join(A,"package.json"),y=$.join(A,"README.md"),W=$.join(A,"src"),w=$.join(W,"index.ts"),j=On($.relative(W,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(W);let B=[[m,JSON.stringify({name:n,version:"0.1.0",description:pW[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1721
|
+
`],[y,`# ${n}
|
|
1690
1722
|
|
|
1691
|
-
${
|
|
1723
|
+
${pW[b.target]}.
|
|
1692
1724
|
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1693
|
-
`],[b.specPath,b.specCode]],S={packageRoot:
|
|
1725
|
+
`],[b.specPath,b.specCode]],S={packageRoot:A,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function rA($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1694
1726
|
|
|
1695
1727
|
export const ${$.exportName} = defineModuleBundle({
|
|
1696
1728
|
meta: {
|
|
@@ -1759,22 +1791,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1759
1791
|
supportedArtifactTypes: ["patch"],
|
|
1760
1792
|
knownConstraints: [],
|
|
1761
1793
|
};
|
|
1762
|
-
`}}function
|
|
1794
|
+
`}}function jS($,b){let A=On(b),n="/src/",m=A.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return A.slice(0,m)}function BS($,b,A){let n=wS(b),m=On($.basename(A));return`${n.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${m}`}function On($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function wb($,b,A,n={}){let{fs:m,logger:y,workspace:W}=b,w=W?.scanSpecSource??GS,j=W?.inferSpecTypeFromFilePath??HS,B=W?.generateHandlerTemplate??ZS,S=W?.generateComponentTemplate??QS,Q=W?.generateTestTemplate??XS,{targets:Z=void 0,outputDir:X=A.outputDir,overwrite:Y=!1,dryRun:H=!1,includeTests:J=!1,runtimeGeneration:O}=n,V=await m.readFile($),U=w(V,$),K=SS(V,$),q=K==="unknown"?j($):K,G=Z??Un(q,{includeTests:J});y.info(`Building from spec: ${$}`,{targetId:q});let z=[],_={};for(let L of G)try{let I=await qS(L,$,V,U,q,{fs:m,logger:y},X,Y,H,O,_,{genHandler:B,genComponent:S,genTest:Q});if(z.push(I),I.success&&I.generatedCode)_[L]=I.generatedCode}catch(I){z.push({target:L,outputPath:"",success:!1,error:I instanceof Error?I.message:String(I),skipped:!1})}return{specPath:$,specInfo:U,targetId:q,results:z}}async function qS($,b,A,n,m,y,W,w,j,B,S,Q){let{fs:Z,logger:X}=y,{genHandler:Y,genComponent:H,genTest:J}=Q,O,V,U=[];switch($){case"handler":{if(m!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${m})`};let G=n.kind==="command"||n.kind==="query"?n.kind:"command",z=Y($$(A,n,b),G);V=Wb(b,W,"handlers",$$(A,n,b),".handler.ts",y.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:A,outputPath:V,fallbackCode:z})??z;break}case"component":{if(m!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${m})`};let G=H($$(A,n,b),n.description??"");V=Wb(b,W,"components",$$(A,n,b),".tsx",y.fs),O=await B?.generateArtifact?.({kind:"component",specCode:A,outputPath:V,fallbackCode:G})??G;break}case"test":{let G=m==="operation"?"handler":"component",z=m==="operation"?S.handler??"":m==="presentation"?S.component??"":m==="form"?S.form??"":"",_=J($$(A,n,b),G);V=Wb(b,W,"__tests__",$$(A,n,b),".test.ts",y.fs),O=await B?.generateTest?.({kind:G,specCode:A,outputPath:V,existingCode:z,fallbackCode:_})??_;break}case"form":{if(m!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${m})`};let G=`import * as React from "react";
|
|
1763
1795
|
|
|
1764
|
-
export interface ${
|
|
1796
|
+
export interface ${J$($$(A,n,b))}Props {
|
|
1765
1797
|
className?: string;
|
|
1766
1798
|
}
|
|
1767
1799
|
|
|
1768
|
-
export function ${
|
|
1800
|
+
export function ${J$($$(A,n,b))}Form({
|
|
1769
1801
|
className,
|
|
1770
|
-
}: ${
|
|
1771
|
-
return <form className={className}>TODO: implement ${
|
|
1802
|
+
}: ${J$($$(A,n,b))}Props) {
|
|
1803
|
+
return <form className={className}>TODO: implement ${$$(A,n,b)}</form>;
|
|
1772
1804
|
}
|
|
1773
|
-
`;
|
|
1805
|
+
`;V=Wb(b,W,"forms",$$(A,n,b),".form.tsx",y.fs),O=await B?.generateArtifact?.({kind:"form",specCode:A,outputPath:V,fallbackCode:G})??G;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 G=$$(A,n,b),z=VS(A)??`${J$(G)}Workflow`,_=`${J$(G)}Runner`,L=Vn(G);if(V=Wb(b,W,"workflows",G,".runner.ts",y.fs),O=kA({exportName:z,specImportPath:Jn(y.fs,V,b),runnerName:_,workflowName:G}),zS(A)){let I=`${J$(G)}WorkflowDevkit`,E=Lb(y.fs,V,`${L}.workflow-devkit.ts`),N=Lb(y.fs,V,`${L}.workflow-devkit.start.route.ts`),M=Lb(y.fs,V,`${L}.workflow-devkit.follow-up.route.ts`),r=Lb(y.fs,V,`${L}.workflow-devkit.stream.route.ts`),g=Lb(y.fs,V,`${L}.workflow-devkit.generic.ts`);U=[{path:E,code:NA({exportName:z,specImportPath:Jn(y.fs,E,b),workflowFunctionName:I})},{path:N,code:FA(eW(y.fs,N,E),I)},{path:M,code:vA()},{path:r,code:gA()},{path:g,code:PA(eW(y.fs,g,E),I)}]}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 G=$$(A,n,b),z=KS(A)??`${J$(G)}DataView`,_=`${J$(G)}Renderer`;V=Wb(b,W,"data-views",G,".renderer.tsx",y.fs),O=TA({exportName:z,specImportPath:Jn(y.fs,V,b),rendererName:_,viewKind:_S(A)??"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 _=JS(b);return X.info(`[dry-run] Would scaffold package: ${_}`),{target:$,outputPath:_,success:!0}}let G=A.trim().length>0?A:rA({target:m,key:n.key??y.fs.basename(b),title:n.key??y.fs.basename(b),description:n.description??YS(m).title,exportName:J$(n.key??y.fs.basename(b))});return V=(await aW(y.fs,{target:m,specPath:b,specCode:G,overwrite:w})).packageRoot,X.info(`Generated package scaffold: ${V}`),{target:$,outputPath:V,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let K=[{path:V,code:O},...U],q=w?void 0:await OS(K,Z);if(q)return{target:$,outputPath:q,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(j){for(let G of K)X.info(`[dry-run] Would write: ${G.path}`);return{target:$,outputPath:V,success:!0,generatedCode:K[0]?.code}}for(let G of K)await Z.mkdir(Z.dirname(G.path)),await Z.writeFile(G.path,LS(G.code)),X.info(`Generated: ${G.path}`);return{target:$,outputPath:V,success:!0}}function Un($,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 Wb($,b,A,n,m,y){let W=Vn(n.split(".").pop()??"unknown"),w;if(b.startsWith("."))w=y.resolve(y.dirname($),"..",b,A);else w=y.resolve(b,A);return y.join(w,`${W}${m}`)}async function OS($,b){for(let A of $)if(await b.exists(A.path))return A.path;return}function Vn($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function J$($){return Vn($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Kn($){return $.replace(/\.[^.]+$/,"")}function JS($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Jn($,b,A){let n=Kn($.relative($.dirname(b),A));return n.startsWith(".")?n:`./${n}`}function eW($,b,A){let n=Kn($.relative($.dirname(b),A));return n.startsWith(".")?n:`./${n}`}function Lb($,b,A){return $.join($.dirname(b),A)}function $$($,b,A){return US($,"name")??b.key??Kn(RS(A))}function US($,b){let A=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(A)?.[1]??null}function VS($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function KS($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function _S($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function zS($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function LS($){return $.endsWith(`
|
|
1774
1806
|
`)?$:`${$}
|
|
1775
|
-
`}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:()=>q8,isValidIdentifier:()=>lW,isValidDotName:()=>pW,isTestFile:()=>Lb,isLibraryDefinitionFile:()=>Rb,emailSchema:()=>V8});import _0 from"micromatch";function Lb($,b){let n=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _0.isMatch($,n)}function Rb($){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 q8($){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 Cb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function L8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],n=[...Cb($?.conventions.models),...Cb($?.conventions.operations),...Cb($?.conventions.events),...Cb($?.conventions.presentations),...Cb($?.conventions.forms)];return[...new Set(b.flatMap((A)=>{let m=A==="**"?"":`${A}/`,y=O$.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/")||Lb(y,b.config)||Rb(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={},q=G.match(/statements\s*:\s*(\d+)/);if(q&&q[1])V.statements=parseInt(q[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 O of H.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:O.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:O.metric,required:O.required,actual:O.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 Jq($,b){return $.get(b)}function Uq($){return F8($)}function Kq($){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(" \u2192 ")}`,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+=`
|
|
1807
|
+
`}function RS($){return $.replaceAll("\\","/").split("/").pop()??$}b$();import{scanAllSpecsFromSource as TS,scanSpecSource as DS}from"@contractspec/module.workspace";import NS from"micromatch";var Aw={};f(Aw,{validators:()=>ES,urlSchema:()=>MS,isValidVersion:()=>CS,isValidIdentifier:()=>$w,isValidDotName:()=>bw,isTestFile:()=>Rb,isLibraryDefinitionFile:()=>Ib,emailSchema:()=>xS});import _n from"micromatch";function Rb($,b){let A=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _n.isMatch($,A)}function Ib($){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(_n.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 _n.isMatch($,A)}import*as U$ from"zod";function $w($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function bw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function CS($){return Number.isInteger($)&&$>0}var xS=U$.string().email(),MS=U$.string().url(),ES={specName:U$.string().refine(bw,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:U$.number().int().positive(),identifier:U$.string().refine($w,{message:"Must be a valid TypeScript identifier"}),owner:U$.string().startsWith("@"),tag:U$.string().min(1)};function Cb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function FS($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],A=[...Cb($?.conventions.models),...Cb($?.conventions.operations),...Cb($?.conventions.events),...Cb($?.conventions.presentations),...Cb($?.conventions.forms)];return[...new Set(b.flatMap((n)=>{let m=n==="**"?"":`${n}/`,y=q$.map((w)=>`${m}${w}`),W=A.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function vS($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function gS($,b){let A=$.filePath.localeCompare(b.filePath);if(A!==0)return A;let n=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(n!==0)return n;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function h$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((A,n)=>A.localeCompare(n));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:FS(b.config)})}async function cA($,b={}){let A=await h$($.fs,b),n=b.type?Array.isArray(b.type)?b.type:[b.type]:[],m=[];for(let y of A){if(b.config?.excludePackages&&NS.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||Rb(y,b.config)||Ib(y))continue;try{let W=await $.fs.readFile(y),w=TS(W,y),j=w.length>0?w:[DS(W,y)];for(let B of j)if(vS(B,b,n))m.push(B)}catch{}}return m.sort(gS)}function L$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function hA($){let b=JSON.parse($),A=new Map,n=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=PS(Z,X);A.set(Z,Y),n+=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:n,pct:L$(m,n)},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:A,total:Q}}function PS($,b){let A=Object.keys(b.statementMap).length,n=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:n,total:A,pct:L$(n,A)},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 zn($){switch($){case"istanbul":return{parse:hA};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 Ln($,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 Rn($,b,A,n){let m=[];if(A.statements!==void 0&&n.statements.pct<A.statements)m.push({metric:"statements",required:A.statements,actual:n.statements.pct,message:`Statement coverage ${n.statements.pct}% is below required ${A.statements}%`});if(A.branches!==void 0&&n.branches.pct<A.branches)m.push({metric:"branches",required:A.branches,actual:n.branches.pct,message:`Branch coverage ${n.branches.pct}% is below required ${A.branches}%`});if(A.functions!==void 0&&n.functions.pct<A.functions)m.push({metric:"functions",required:A.functions,actual:n.functions.pct,message:`Function coverage ${n.functions.pct}% is below required ${A.functions}%`});if(A.lines!==void 0&&n.lines.pct<A.lines)m.push({metric:"lines",required:A.lines,actual:n.lines.pct,message:`Line coverage ${n.lines.pct}% is below required ${A.lines}%`});if(A.mutations!==void 0)m.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:n,passed:m.length===0,failures:m}}async function In($,b,A){let{fs:n,logger:m}=$,y=[],W=A.workspaceRoot?`${A.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await n.exists(X)){j=await n.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=Ln(B??"coverage.json"),Z=zn(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 H=Y[1],J={},O=H.match(/statements\s*:\s*(\d+)/);if(O&&O[1])J.statements=parseInt(O[1],10);let V=H.match(/branches\s*:\s*(\d+)/);if(V&&V[1])J.branches=parseInt(V[1],10);let U=H.match(/functions\s*:\s*(\d+)/);if(U&&U[1])J.functions=parseInt(U[1],10);let K=H.match(/lines\s*:\s*(\d+)/);if(K&&K[1])J.lines=parseInt(K[1],10);if(Object.keys(J).length===0)continue;let q=Rn(X.key,X.version,J,Z.total);for(let G of q.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:G.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:G.metric,required:G.required,actual:G.actual}})}return y}b$();import{addContractNode as kS,buildReverseEdges as rS,createContractGraph as fS,detectCycles as cS,findMissingDependencies as hS,parseImportedSpecNames as dS,toDot as uS}from"@contractspec/module.workspace";async function nw($,b={}){let{fs:A}=$,n=await h$(A,{config:b.config,pattern:b.pattern}),m=fS();for(let w of n){let j=await A.readFile(w),B=A.relative(".",w),S=A.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=dS(j,w);kS(m,S,B,Q)}rS(m);let y=cS(m),W=hS(m);return{graph:m,total:m.size,cycles:y,missing:W}}function PO($,b){return $.get(b)}function kO($){return uS($)}function rO($){let b=Array.from($.values()),A=b.filter((W)=>W.dependencies.length>0),n=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:A.length,withoutDeps:n.length,used:m.length,unused:y.length}}async function Cn($,b){let A=[],n=await P($.fs),m=await nw($,{config:n,pattern:b.pattern});for(let y of m.cycles)A.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${y.join(" \u2192 ")}`,category:"deps",context:{cycle:y}});for(let y of m.missing)for(let W of y.missing)A.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${y.contract} requires ${W}`,category:"deps",context:{contract:y.contract,missing:W}});return A}import{analyzePackageDocBlocks as oS}from"@contractspec/module.workspace";var iS=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function lS($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:iS}),n=new Map;for(let W of A){let w=$.dirname(W),j=$.join(w,"src");if(!await $.exists(j))continue;try{let B=JSON.parse(await $.readFile(W));n.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));n.set(b,{packageName:W.name??b,packageRoot:b,srcRoot:y})}catch{}return[...n.values()].sort((W,w)=>W.packageRoot.localeCompare(w.packageRoot))}async function dA($,b){let A=[],n=await lS($,b);for(let m of n){let y=oS({packageName:m.packageName,srcRoot:m.srcRoot});for(let W of y.diagnostics)A.push({...W,packageName:m.packageName,packageRoot:m.packageRoot,srcRoot:m.srcRoot})}return A}async function xn($,b){let A=b.workspaceRoot??process.cwd();return(await dA($.fs,A)).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 Mn($,b,A){let n=[],m=await tS($,b);if(n.push(m),m.status==="pass")n.push(await pS($,b,A));return n}async function tS($,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 m=await $.readFile(A),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 pS($,b,A){let n=$.join(b.workspaceRoot,".contractsrc.json");try{let m=await $.readFile(n),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:A?{description:`Set ${j} 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(`${j}=`))return{success:!1,message:`${j} already in .env, update manually`};Z+=`
|
|
1776
1808
|
`}return Z+=`${j}=${S}
|
|
1777
|
-
`,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
|
|
1809
|
+
`,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 aS}from"child_process";import{promisify as eS}from"util";var uA=eS(aS);async function En($,b){let A=[];return A.push(await sS(b)),A.push(await $9(b)),A.push(await b9($,b)),A}async function sS($){try{return await uA("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 uA("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 $9($){try{let{stdout:b}=await uA("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 b9($,b){let A=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(A))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let 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(A),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 uA("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"}}}b$();import{DEFAULT_CONTRACTSRC as oA}from"@contractspec/lib.contracts-spec/workspace-config";import{join as A9,relative as n9}from"path";var m9="contractspec",y9="contractsrc.schema.json";function W9($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function xb($){return W9(n9($.configRoot,A9($.workspaceRoot,"node_modules",m9,y9)))}var Mb=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],mw={"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)"},yw=["core","connect","builder-managed","builder-local","builder-hybrid"],Ww={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)"},ww={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 Eb={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function Tb($){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 jw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return Mb}}function Tn($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function Bw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function nJ($){return $.startsWith("builder-")}function mJ($){return $==="connect"}function Sw($){let b=R$($),A=w9($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset managed-mvp`,`contractspec builder status --workspace-id ${A}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function w9($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function Qw($){let b=R$($),A=[Eb.verificationCache];if(b==="connect")A.unshift(Eb.connect);return A}function jb($){let b=$.isMonorepo&&$.scope==="package",A=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,n=j9($),m=B9($);return{$schema:xb({configRoot:A,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...n?{connect:n}:{},...m?{builder:m}:{},...b&&$.packageName?{package:$.packageName}:{}}}function iA($){let b=R$($),A={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(Tn(b))A["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return A}function Db(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function Zw(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function Xw($){let b=$.projectName??"this project",n=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1778
1810
|
|
|
1779
1811
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1780
1812
|
|
|
@@ -1795,10 +1827,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1795
1827
|
## Contract Locations
|
|
1796
1828
|
|
|
1797
1829
|
Contracts are located in:
|
|
1798
|
-
- \`${
|
|
1799
|
-
- \`${
|
|
1800
|
-
- \`${
|
|
1801
|
-
- \`${
|
|
1830
|
+
- \`${n}/operations/\` - Command and query specs
|
|
1831
|
+
- \`${n}/events/\` - Event specs
|
|
1832
|
+
- \`${n}/presentations/\` - UI presentation specs
|
|
1833
|
+
- \`${n}/features/\` - Feature module specs
|
|
1802
1834
|
|
|
1803
1835
|
## When Making Changes
|
|
1804
1836
|
|
|
@@ -1840,7 +1872,7 @@ defineCommand({
|
|
|
1840
1872
|
- Events must be declared in contracts before being emitted.
|
|
1841
1873
|
- UI components should reference presentation contracts.
|
|
1842
1874
|
- Feature flags should be defined in feature modules.
|
|
1843
|
-
`}function
|
|
1875
|
+
`}function Yw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package",n=R$($),m=A&&$.packageName?`${$.packageName} package`:b,y="src/contracts",W=$.isMonorepo?A?`
|
|
1844
1876
|
## Monorepo Scope
|
|
1845
1877
|
|
|
1846
1878
|
This guide is scoped to the current package.
|
|
@@ -1900,8 +1932,8 @@ ${W}
|
|
|
1900
1932
|
|
|
1901
1933
|
## Initialization Preset
|
|
1902
1934
|
|
|
1903
|
-
- This workspace was initialized with the \`${
|
|
1904
|
-
`}function
|
|
1935
|
+
- This workspace was initialized with the \`${n}\` setup preset.
|
|
1936
|
+
`}function Hw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1905
1937
|
|
|
1906
1938
|
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1907
1939
|
|
|
@@ -1930,68 +1962,68 @@ This workspace uses ContractSpec to keep contracts, generated artifacts, and AI
|
|
|
1930
1962
|
|
|
1931
1963
|
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1932
1964
|
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1933
|
-
`}function
|
|
1934
|
-
`}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=Mb(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=Mb(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"child_process";import{promisify as j9}from"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 O9,scanFeatureSource as q9}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=q9(B,j);m.features.set(S.key,S);continue}if(Y9(j)){let S=O9(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 mV($){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=Tb();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=Tb(),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 Ow($,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 Ow($,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 qw=["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??qw,{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(`\u2713 ${_.message}`),H.status="pass",H.message=`Fixed: ${_.message}`,H.fix=void 0;else y.warn(`\u2717 ${_.message}`)}}Y.push(H)}}let G=Y.filter((J)=>J.status==="pass").length,V=Y.filter((J)=>J.status==="warn").length,q=Y.filter((J)=>J.status==="fail").length,K=Y.filter((J)=>J.status==="skip").length;return{checks:Y,passed:G,warnings:V,failures:q,skipped:K,healthy:q===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 DV($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1935
|
-
`)}function
|
|
1936
|
-
${$.details}`;if($.fix)
|
|
1937
|
-
Fix available: ${$.fix.description}`;return
|
|
1938
|
-
|
|
1939
|
-
${$.body}`;await m.writeFile(w,j)}async function
|
|
1940
|
-
`).length},W,w=new RegExp(Nb.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Nb.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Nb.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(Nb.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Nb.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$,...O$])],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 HJ($,b={}){let{fs:n}=$,A=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...O$])],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 q=Q.getProperty("description");if(q&&p.isPropertyAssignment(q)){let K=q.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 UJ($){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 OQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Mw($){return GQ("sha256").update($).digest("hex")}async function qQ($,b,n,A={},m){let y={...OQ,...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,q)=>{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:q})};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:q}of G)await Z(V,q,"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 qQ(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 O of H.operations){let _=n$(O.key,O.version);if(B.add(`operation:${_}`),!y.operations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${O.key}.v${O.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:O})}for(let O of H.events){let _=n$(O.key,O.version);if(B.add(`event:${_}`),!y.events.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Event ${O.key}.v${O.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:O})}for(let O of H.presentations){let _=n$(O.key,O.version);if(B.add(`presentation:${_}`),!y.presentations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${O.key}.v${O.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:O})}for(let O of H.experiments){let _=n$(O.key,O.version);if(B.add(`experiment:${_}`),!y.experiments.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${O.key}.v${O.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:O})}for(let O of H.capabilities.provides){let _=n$(O.key,O.version);if(B.add(`capability:${_}`),!y.capabilities.has(_))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${O.key}.v${O.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:O})}for(let O of H.capabilities.requires){let _=n$(O.key,O.version);B.add(`capability:${_}`)}for(let O of H.opToPresentationLinks){let _=n$(O.op.key,O.op.version),z=n$(O.pres.key,O.pres.version);if(!y.operations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked operation ${O.op.key}.v${O.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:O.op});if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${O.pres.key}.v${O.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:O.pres})}if(H.presentationsTargets)for(let O of H.presentationsTargets){let _=n$(O.key,O.version);if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${O.key}.v${O.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:O.key,version:O.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let O=l0(y,H);if(!O)continue;for(let[_,z]of O)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 O of H.opToPresentationLinks){let _=n$(O.op.key,O.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 ${O.op.key}.v${O.op.version} linked to presentation requires tests covering: ${D.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:O.op})}}let Y={},G=0;for(let H of Q){let O=l0(y,H);if(!O)continue;let _=O.size,z=0,L=0,C=b.requireTestsFor?.includes(H);for(let[D,F]of O){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,O)=>H+O.total,0),q=Object.values(Y).reduce((H,O)=>H+O.covered,0),K={total:V,linkedToFeature:q,orphaned:V-q,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 cJ($){let b=[];for(let n of Object.values($))for(let A of n.values())b.push(A);return b}function hJ($,b){return $.filter((n)=>n.type===b)}function dJ($,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(Lb(w,b.config))continue;if(Rb(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 $U($){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:()=>Fb,renderPackageDeclaration:()=>Wm,normalizePath:()=>C$,matchesAllowMissing:()=>ym,inferWorkspacePackageKind:()=>s0,getIndexExportPath:()=>bm,getCanonicalDeclarationRelativePath:()=>$m,discoverWorkspacePackages:()=>gw,createPackageDeclarationIssue:()=>wm,buildPackageTitle:()=>vb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>G$,buildDomain:()=>Am,buildDeclarationTags:()=>mm,auditPackageDeclarations:()=>gb,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 Fb($){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 vb($){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=Fb(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 gb($,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:vb(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 En({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';"}
|
|
1941
|
-
|
|
1942
|
-
export const ${
|
|
1943
|
-
meta: ${
|
|
1944
|
-
${
|
|
1965
|
+
`}function j9($){if(R$($)!=="connect")return;return{...oA.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:{...oA.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:oA.connect?.studio}}function B9($){let b=Tn(R$($)),A=Bw(R$($));if(!b||!A)return;let n=!0,m=b==="local"||b==="hybrid";return{...oA.builder,enabled:!0,runtimeMode:b,bootstrapPreset:A,api:n?{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 lA(){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 A$($,b){let A={...$};for(let n of Object.keys(b)){let m=$[n],y=b[n];if(m===void 0)A[n]=y;else if(tA(m)&&tA(y))A[n]=A$(m,y)}return A}function Dn($,b){let A={...$};for(let n of Object.keys(b)){let m=$[n],y=b[n];if(y===void 0)continue;if(tA(m)&&tA(y))A[n]=Dn(m,y);else A[n]=y}return A}function tA($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function a($){try{return JSON.parse($)}catch{return null}}function F($){return JSON.stringify($,null,2)+`
|
|
1966
|
+
`}async function Nn($,b){let A=[];return A.push(await S9($,b)),A.push(await Q9($,b)),A.push(await Z9($,b)),A.push(await X9($,b)),A.push(await Y9($,b)),A.push(await H9($,b)),A.push(await G9($,b)),A}async function d$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function S9($,b){let A=$.join(await d$($,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 m=jb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,F(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 Q9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A);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=jb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,F(W)),{success:!0,message:"Replaced with valid config"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function Z9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A),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=jb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let j of W)if(w[j]!==void 0)y[j]=w[j];return await $.writeFile(A,F(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 X9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A),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(A,F(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 Y9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A),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(A,F(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 H9($,b){let A=await d$($,b),n=await P($,A),m=Tb(n);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[n.connect?.storage?.root?null:"storage.root",n.connect?.storage?.contextPack?null:"storage.contextPack",n.connect?.storage?.planPacket?null:"storage.planPacket",n.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),j=n.connect?.studio?.enabled&&n.connect?.studio?.mode==="review-bridge"&&!n.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=n.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!n.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")&&!n.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!n.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 G9($,b){let A=await d$($,b),n=await P($,A),m=Tb(n);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(A,".vscode","settings.json"),W=n.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(A,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...iA({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,F(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 q9}from"child_process";import{promisify as O9}from"util";var u$=O9(q9);async function Fn($,b){let A=[];return A.push(await J9(b)),A.push(await U9(b)),A.push(await V9($,b)),A.push(await K9($,b)),A.push(await _9($,b)),A}async function J9($){try{let{stdout:b}=await u$("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 U9($){try{let{stdout:b}=await u$("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 V9($,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"}],n=null;for(let{file:m,name:y}of A){let W=$.join(b.workspaceRoot,m);if(await $.exists(W)){n=y;break}}if(!n){let m=$.join(b.workspaceRoot,".."),y=$.join(b.workspaceRoot,"../.."),W=[m,y];for(let w of W){for(let{file:j,name:B}of A){let S=$.join(w,j);if(await $.exists(S)){n=B;break}}if(n)break}}if(!n)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 u$(`${n} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${n}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${n} detected but not available`,details:`Install ${n} or use a different package manager`}}}async function K9($,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 u$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await u$("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 _9($,b){let A=$.join(b.workspaceRoot,"package.json");try{let n=await $.readFile(A),m=JSON.parse(n),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 u$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await u$("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 vn($,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((n)=>({category:"docs",name:`Same-File DocBlocks (${n.packageName})`,status:n.severity==="warning"?"warn":"fail",message:n.message,details:$.relative(b.workspaceRoot,n.file),context:{ruleId:n.ruleId,file:n.file,line:n.line,column:n.column,packageName:n.packageName}}))}import{isExampleFile as z9,isFeatureFile as L9,scanAllSpecsFromSource as R9,scanExampleSource as I9,scanFeatureSource as C9}from"@contractspec/module.workspace";function x9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function pA($,b={}){let{fs:A,logger:n}=$,m=x9(),y=b.pattern??"**/*.{ts,tsx}";n.info("Scanning for contract layer files...");let W=await A.glob({pattern:y});for(let j of W){if(j.includes("node_modules")||j.includes("/dist/"))continue;try{let B=await A.readFile(j);if(L9(j)){let S=C9(B,j);m.features.set(S.key,S);continue}if(z9(j)){let S=I9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=R9(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 A.glob({pattern:"**/.contractsrc.json"});for(let B of j){if(B.includes("node_modules"))continue;try{let S=await A.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 n.info(`Discovered ${w.features} features, ${w.examples} examples, ${w.appConfigs} app configs, ${w.workspaceConfigs} workspace configs`),{inventory:m,stats:w}}function KJ($){let b=[];for(let[A,n]of $.features)b.push({key:A,file:n.filePath,type:"feature"});for(let[A,n]of $.examples)b.push({key:A,version:n.version,file:n.filePath,type:"example"});for(let[A,n]of $.appConfigs)b.push({key:A,version:n.version,file:n.filePath,type:"app-config"});for(let[,A]of $.workspaceConfigs)b.push({key:A.file,file:A.file,type:"workspace-config"});return b}function aA($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function gn($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function eA($,b){let A=$.join(b,"config/stability-policy.json");if(!await $.exists(A))return;try{let n=await $.readFile(A),m=JSON.parse(n);return{version:typeof m.version==="number"&&Number.isFinite(m.version)?m.version:1,criticalPackages:gn(m.criticalPackages).map(aA),criticalFeatureKeys:gn(m.criticalFeatureKeys),smokePackages:gn(m.smokePackages)}}catch{return}}function Gw($,b){let A=aA($);if(b?.criticalPackages.includes(A))return"critical";return"non-critical"}function qw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function Bb($){return aA(`${aA($)}/config/stability-policy.json`)}async function Pn($,b){let A=[],n=await eA($,b.workspaceRoot),m=await pA({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return A.push(M9(m.stats.features)),A.push(E9(m.stats.examples)),A.push(T9(m.inventory.features,n,b)),A.push(D9(m.inventory.examples)),A.push(N9(m.inventory.workspaceConfigs)),A}function M9($){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 E9($){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 T9($,b,A){let n=[],m=[];for(let[y,W]of $)if(!(Boolean(W.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(W.sourceBlock??"")))if(qw(y,b))m.push(y);else n.push(y);if(m.length===0&&n.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?Bb(A.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`:`${n.length} feature(s) missing owners`,details:m.length>0?`Critical features: ${m.join(", ")}`:`Features: ${n.slice(0,3).join(", ")}${n.length>3?"...":""}`,context:{policyPath:b?Bb(A.workspaceRoot):void 0,criticalMissingFeatures:m,missingFeatures:n}}}function D9($){let b=[];for(let[A,n]of $)if(!n.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 N9($){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 kn($,b){let A=[];return A.push(await F9($,b)),A.push(await v9($,b)),A.push(await g9($,b)),A}async function F9($,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 m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Db();return await $.writeFile(A,F(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function v9($,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 m=await $.readFile(A),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=Db(),j=A$(y,w);return await $.writeFile(A,F(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 g9($,b){let A=lA();try{if(!await $.exists(A))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let m=await $.readFile(A);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 P9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Ow=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function k9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,n])=>{if(typeof n==="string")b[A]=n;return b},{})}function r9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function f9($,b,A){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:Ow}),m=[];for(let y of n){let W=$.dirname(y),w=$.relative(b,W);try{let j=JSON.parse(await $.readFile(y)),B=k9(j.scripts),S=await $.glob({patterns:P9,cwd:W,ignore:Ow});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:r9(B),testFileCount:S.length,tier:Gw(w,A)})}catch{continue}}return m}function c9($){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 h9($){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 Jw($,b,A){let n=await f9($,b,A),m=[];for(let W of n){if(W.tier==="critical")m.push(...c9(W));m.push(...h9(W))}let y=n.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 Vw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Uw($,b,A,n){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:n,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||A.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:Vw(b),context:{findings:b}}}async function Kw($,b){let A=await eA($,b.workspaceRoot);if(!A)return[];let n=await Jw($,b.workspaceRoot,A),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=n.findings.filter((j)=>m.has(j.code)),W=n.findings.filter((j)=>j.code==="tests-without-test-script"),w=n.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 ${n.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?Vw(y):b.verbose?`Policy: ${Bb(b.workspaceRoot)}`:void 0,context:{policyPath:Bb(b.workspaceRoot),criticalPackages:n.criticalPackages,findings:y}},Uw("Package Test Scripts",W,new Set,"All tested packages expose a test script"),Uw("Buildable Packages Without Tests",w,new Set,"All buildable packages have tests or explicit test scripts")]}var d9=["src/contracts","contracts","src/specs","specs"];async function rn($,b){let A=[];return A.push(u9(b)),A.push(await o9($,b)),A.push(await i9($,b)),A.push(await l9($,b)),A.push(await p9($,b)),A.push(...await Kw($,b)),A}function u9($){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 o9($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let n of A){let m=$.join(n,"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: ${n}`: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 i9($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],n=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let W of A)for(let w of d9){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(n,"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 l9($,b){try{let A=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],n=b.isMonorepo?b.packageRoot:b.workspaceRoot,m=await $.glob({patterns:A,ignore:["node_modules/**","dist/**"],cwd:n});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 t9($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let n=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(n))return{path:n,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 p9($,b){try{let A=await t9($,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 n=await $.readFile(A.path),m=JSON.parse(n),y=m.outputDir??"./src",W=$.join(A.root,y),w=b.isMonorepo?` (${A.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||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: ${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 _w=["cli","config","mcp","deps","docs","workspace","ai","layers"],zw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var a9={checks:{runCliChecks:En,runConfigChecks:Nn,runMcpChecks:kn,runDepsChecks:Fn,runDocChecks:vn,runWorkspaceChecks:rn,runAiChecks:Mn,runLayerChecks:Pn},workspace:{findWorkspaceRoot:x,findPackageRoot:c,isMonorepo:Ub,getPackageName:P$}},e9={confirm:async()=>!1,input:async()=>""};async function Lw($,b,A=e9,n=a9){let{fs:m,logger:y}=$,W=b.categories??_w,{checks:w,workspace:j}=n,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 U=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${U}`)}let Y=[];for(let U of W){if(b.skipAi&&U==="ai")continue;y.info(`Checking ${zw[U]}...`);let K=await s9(U,m,X,A,w);for(let q of K){if(q.fix&&(q.status==="fail"||q.status==="warn")){if(b.autoFix?!0:await A.confirm(`Fix "${q.name}"? ${q.fix.description}`)){y.info(`Applying fix: ${q.fix.description}`);let z=await q.fix.apply();if(z.success)y.info(`\u2713 ${z.message}`),q.status="pass",q.message=`Fixed: ${z.message}`,q.fix=void 0;else y.warn(`\u2717 ${z.message}`)}}Y.push(q)}}let H=Y.filter((U)=>U.status==="pass").length,J=Y.filter((U)=>U.status==="warn").length,O=Y.filter((U)=>U.status==="fail").length,V=Y.filter((U)=>U.status==="skip").length;return{checks:Y,passed:H,warnings:J,failures:O,skipped:V,healthy:O===0}}async function s9($,b,A,n,m){switch($){case"cli":return m.runCliChecks(b,A);case"config":return m.runConfigChecks(b,A);case"mcp":return m.runMcpChecks(b,A);case"deps":return m.runDepsChecks(b,A);case"docs":return m.runDocChecks(b,A);case"workspace":return m.runWorkspaceChecks(b,A);case"ai":return m.runAiChecks(b,A,n);case"layers":return m.runLayerChecks(b,A);default:return[]}}function aJ($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1967
|
+
`)}function eJ($){let A=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)A+=`
|
|
1968
|
+
${$.details}`;if($.fix)A+=`
|
|
1969
|
+
Fix available: ${$.fix.description}`;return A}async function fn($,b){let A=[],n=b.workspaceRoot??process.cwd(),m=await Lw($,{workspaceRoot:n,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let y of m.checks)if(y.status==="fail")A.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")A.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 A}b$();import{mkdtemp as HQ,rm as GQ}from"fs/promises";import{tmpdir as qQ}from"os";import Nb from"path";import{DEFAULT_CONTRACTSRC as wQ}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as jQ}from"@contractspec/module.workspace";import BQ from"path";import{packageDocBlocks as $Q}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as bQ,convertSpecToDocBlock as AQ,extractModuleDocData as nQ,loadSpecFromSource as mQ,scanAllSpecsFromSource as yQ,scanSpecSource as WQ}from"@contractspec/module.workspace";import hn from"path";import{dirname as Rw,sep as sA}from"path";class cn{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let A;if(b.specType==="app-config")A="app-config";else if(b.specType==="example")A="example";else if(b.specType==="feature")A="feature";if(A&&b.key){let n=Rw(b.filePath);this.modules.push({type:A,key:b.key,dirPath:n})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=Rw($),A=this.modules.filter((n)=>{let m=n.dirPath.endsWith(sA)?n.dirPath:n.dirPath+sA;return(b.endsWith(sA)?b:b+sA).startsWith(m)||b===n.dirPath});if(A.length===0)return;return A.sort((n,m)=>{let y={"app-config":3,example:2,feature:1},W=y[n.type],w=y[m.type];if(W!==w)return w-W;return m.dirPath.length-n.dirPath.length}),A[0]}}async function Cw($,b,A){let{fs:n,logger:m}=A,y=[];if(m.info(`Generating docs for ${$.length} files...`),b.outputDir)await n.mkdir(b.outputDir);let W=new cn(A),w=[];for(let B of $)try{let S=await n.readFile(B),Q=yQ(S,B);if(Q.length>0)w.push(...Q);else{let Z=WQ(S,B);if(Z.specType!=="unknown")w.push(Z)}}catch(S){}W.initialize(w);let j=await xw($,A);for(let B of j)if(y.push(B.entry.block),m.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await Iw(B.entry.block,B.filePath,b.outputDir,W,n);for(let B of $)try{let S=await mQ(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=AQ(Q,{rootPath:b.rootPath});if(y.push(Z),m.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await Iw(Z,B,b.outputDir,W,n)}}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 jU($,b){return(await xw($,b)).map(({entry:n})=>n.block)}function BU($,b){return $Q(bQ({packageName:$,srcRoot:b}))}async function xw($,b){let A=[...new Set($)].sort((m,y)=>m.localeCompare(y)),n=[];for(let m of A){let y=await b.fs.readFile(m),W=m.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),w=nQ(y,m,W);for(let j of w.entries)n.push({entry:j,filePath:m})}return n}async function Iw($,b,A,n,m){let y=n.resolve(b),W=y?hn.join(A,y.key):hn.join(A,"_common");await m.mkdir(W);let w=hn.join(W,`${$.id}.md`),j=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1970
|
+
|
|
1971
|
+
${$.body}`;await m.writeFile(w,j)}async function Mw($,b,A,n,m={}){let y=m.config,W=await cA($,{cwd:m.specSearchRoot,config:y,pattern:m.specPattern??QQ(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=BQ.join(ZQ(A,y),"docs"),j=await Cw(W.map((S)=>S.filePath),{outputDir:w,format:"markdown",rootPath:n},$),B=0;for(let S of W){let Q=SQ(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await wb(S.filePath,$,y??wQ,{targets:Un(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 SQ($){return jQ($.specType)}function QQ($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${dn($)}/**/*.ts`:void 0}function ZQ($,b){let A=(b?.connect?.policy?.generatedPaths??[]).map(YQ).filter(Boolean);if(A.length>0)return A[0];if(b?.outputDir&&b.outputDir!=="./src")return dn(b.outputDir);return $}function XQ($){return dn($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function YQ($){let b=XQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function dn($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function $0($,b,A,n={}){let m=await HQ(Nb.join(qQ(),"contractspec-drift-"));try{await Mw($,b,m,n.rootPath,n.generation);let y=[],W=await import("fs/promises");async function w(Z){let X=await W.readdir(Z,{withFileTypes:!0}),Y=[];for(let H of X){let J=Nb.resolve(Z,H.name);if(H.isDirectory())Y.push(...await w(J));else Y.push(J)}return Y}let j=async(Z)=>{if(!await W.stat(Z).catch(()=>!1))return[];return(await w(Z)).map((Y)=>Nb.relative(Z,Y)).sort()},B=await j(m),S=await j(A),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(Nb.join(m,Z)),Y=await W.readFile(Nb.join(A,Z));if(!X.equals(Y))y.push(Z)}return{hasDrift:y.length>0,files:y}}finally{await GQ(m,{recursive:!0,force:!0})}}async function un($,b){let{fs:A,logger:n}=$,m=[],y=await P(A);if(!y.outputDir)return n.info("No outputDir configured, skipping drift checks"),m;let W="./contracts",w=y.outputDir;if(!await A.exists(w))return n.info("Generated directory does not exist, skipping drift checks"),m;try{let j=await $0($,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){n.warn("Drift detection failed",{error:j instanceof Error?j.message:String(j)})}return m}b$();function OQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function JQ($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function b0($,b,A,n={}){let{fs:m}=b,y=[],W=[],w=$.key??m.basename($.filePath).replace(/\.[jt]s$/,""),j=n.outputDir??A.outputDir??"./src",B=OQ(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(n.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=`${JQ(w.split(".").pop()??w)}Spec`,Y=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),H=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(!H)W.push(`Handler ContractHandler typing does not reference expected spec var (${X}): ${S.handlerPath}`)}if(n.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 on($,b){let{fs:A}=$,n=[],m=await P(A);for(let y of b){if(y.specType!=="operation")continue;let W=await b0(y,{fs:A},m,{checkHandlers:!0,outputDir:m.outputDir});for(let w of W.errors)n.push({ruleId:"handler-missing",severity:"warning",message:w,category:"handlers",file:y.filePath});for(let w of W.warnings)n.push({ruleId:"handler-warning",severity:"warning",message:w,category:"handlers",file:y.filePath})}return n}b$();import{createHash as LQ}from"crypto";import RQ from"path";var Fb={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},UQ={".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 VQ($){let b=$.toLowerCase();for(let[A,n]of Object.entries(UQ))if(b.endsWith(A))return n;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 Ew($,b){let A=[],n=new Set,m=(Z,X,Y)=>{let H=`${Z}:${X}`;if(n.has(H))return;n.add(H),A.push({filePath:b,specKey:Z,referenceType:X,lineNumber:Y,inferredType:VQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1972
|
+
`).length},W,w=new RegExp(Fb.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Fb.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Fb.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(Fb.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Fb.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return A}var Tw=["**/*.ts(x)"];async function A0($,b,A={}){let{fs:n}=b,m=A.includePatterns??Tw,y=A.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await n.glob({pattern:w,ignore:y});for(let B of j)try{let S=await n.readFile(B),Z=Ew(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function NU($,b={}){let{fs:A}=$,n=b.includePatterns??Tw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of n){let w=await A.glob({pattern:W,ignore:m});for(let j of w)try{let B=await A.readFile(j),S=Ew(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 KQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Dw($,b,A){let n=KQ(b),m=[];if($==="operation")m.push({path:`${A}/handlers/${n}.handler.ts`,type:"handler"}),m.push({path:`${A}/handlers/${n}.handler.test.ts`,type:"test"});if($==="presentation")m.push({path:`${A}/components/${n}.tsx`,type:"component"}),m.push({path:`${A}/components/${n}.test.tsx`,type:"test"});if($==="form")m.push({path:`${A}/forms/${n}.form.tsx`,type:"form"}),m.push({path:`${A}/forms/${n}.form.test.tsx`,type:"test"});if($==="event")m.push({path:`${A}/handlers/${n}.handler.ts`,type:"handler"}),m.push({path:`${A}/handlers/${n}.handler.test.ts`,type:"test"});return m}import{Node as p,Project as _Q,SyntaxKind as zQ}from"ts-morph";function Nw($){let b=[],n=new _Q({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,H=Q.getProperty("path");if(H&&p.isPropertyAssignment(H)){let V=H.getInitializer();if(p.isStringLiteral(V))Z=V.getLiteralText()}let J=Q.getProperty("type");if(J&&p.isPropertyAssignment(J)){let V=J.getInitializer();if(p.isStringLiteral(V))X=V.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let V=O.getInitializer();if(p.isStringLiteral(V))Y=V.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=n.getDescendantsOfKind(zQ.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=n.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=n.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 Fw($){if($.length===0)return"missing";let b=$.filter((m)=>m.exists),A=$.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 kU($){let b=$.filter((m)=>m.status==="implemented").length,A=$.filter((m)=>m.status==="partial").length,n=$.filter((m)=>m.status==="missing").length;return{total:$.length,implemented:b,partial:A,missing:n,coverage:$.length>0?Math.round(b/$.length*100):100}}var IQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function vw($){return LQ("sha256").update($).digest("hex")}async function CQ($,b,A,n={},m){let y={...IQ,...n},W=y.computeHashes?vw($.sourceBlock||""):void 0,w=$.key??RQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,H,J,O)=>{if(Q.has(Y))return;Q.add(Y);let V=await B.exists(Y),U=void 0,K=void 0;if(V&&y.computeHashes)try{U=await B.readFile(Y),K=vw(U)}catch{}S.push({path:Y,type:H,source:J,exists:V,implementationSourceContent:U,implementationSourceHash:K,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Nw($.sourceBlock);for(let H of Y)await Z(H.path,H.type,"explicit",H.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await A0(w,b,y);for(let H of Y){if(H.filePath===$.filePath)continue;await Z(H.filePath,H.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??A.outputDir??"./src",H=Dw($.specType,w,Y);for(let{path:J,type:O}of H)await Z(J,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Fw(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function gw($,b,A,n={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await CQ(W,b,A,n,m);y.push(w)}catch(w){console.error(`Failed to resolve implementations for ${W}:`,w)}}return y}async function ln($,b,A){let{fs:n}=$,m=[],y=await P(n),W=A.implementation??{},w=b.filter((B)=>B.specType==="operation"),j=await gw(w,{fs:n},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}b$();import{isFeatureFile as EQ,scanAllSpecsFromSource as TQ,scanFeatureSource as DQ}from"@contractspec/module.workspace";function xQ($,b){return`${$}.v${b}`}function tn($,b,A,n,m,y={}){let{treatMissingAsError:W=!0}=y;if(!n||n.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let w=[],j=[],B=[];for(let S of n){let Q=xQ(S.key,S.version);if(m.has(Q))w.push(S);else if(j.push(S),W)B.push(`Spec ${b}.v${A} references test ${S.key}.v${S.version} which does not exist`)}return{valid:j.length===0,foundTests:w,missingTests:j,errors:B,specFile:$}}function Pw($,b){return`${$}.v${b}`}function kw($,b){let A=new Map,n=new Map,m=[],y=[];for(let W of $){if(!W.key||!W.version)continue;let w=Pw(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=Pw(B,Q),X=MQ(b,j);if(!X||!X.has(Z)){m.push(w);continue}if(n.set(w,Z),!A.has(Z))A.set(Z,new Set);A.get(Z)?.add(w)}return{targetToTests:A,testToTarget:n,orphanedTests:m,testsWithoutTarget:y}}function MQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function NQ(){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 pn($,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 n0($,b={}){let{fs:A,logger:n}=$;n.info("Starting integrity analysis...",{options:b});let m=await h$(A,{config:b.config,cwd:b.cwd,pattern:b.pattern}),y=NQ(),W=[],w=[];for(let q of m){if((await A.stat(q)).isDirectory)continue;let z=await A.readFile(q);if(EQ(q)){let _=DQ(z,q);W.push(_)}else{let _=TQ(z,q);for(let L of _)if(L.specType!=="unknown"&&L.specType!=="feature"){let I=pn(y,L.specType);if(I&&L.key&&L.version!==void 0){let E=n$(L.key,L.version);I.set(E,{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((q)=>q.key===b.featureKey):W,B=new Set;for(let q of j){for(let G of q.operations){let z=n$(G.key,G.version);if(B.add(`operation:${z}`),!y.operations.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"operation",ref:G})}for(let G of q.events){let z=n$(G.key,G.version);if(B.add(`event:${z}`),!y.events.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Event ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"event",ref:G})}for(let G of q.presentations){let z=n$(G.key,G.version);if(B.add(`presentation:${z}`),!y.presentations.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"presentation",ref:G})}for(let G of q.experiments){let z=n$(G.key,G.version);if(B.add(`experiment:${z}`),!y.experiments.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"experiment",ref:G})}for(let G of q.capabilities.provides){let z=n$(G.key,G.version);if(B.add(`capability:${z}`),!y.capabilities.has(z))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"capability",ref:G})}for(let G of q.capabilities.requires){let z=n$(G.key,G.version);B.add(`capability:${z}`)}for(let G of q.opToPresentationLinks){let z=n$(G.op.key,G.op.version),_=n$(G.pres.key,G.pres.version);if(!y.operations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked operation ${G.op.key}.v${G.op.version} not found`,file:q.filePath,featureKey:q.key,specType:"operation",ref:G.op});if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${G.pres.key}.v${G.pres.version} not found`,file:q.filePath,featureKey:q.key,specType:"presentation",ref:G.pres})}if(q.presentationsTargets)for(let G of q.presentationsTargets){let z=n$(G.key,G.version);if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"presentation",ref:{key:G.key,version:G.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let q of Q){let G=pn(y,q);if(!G)continue;for(let[z,_]of G)if(!B.has(`${q}:${z}`))S.push(_),w.push({severity:"warning",type:"orphaned",message:`${q} ${_.key}.v${_.version} is not linked to any feature`,file:_.file,specKey:_.key,specType:_.type})}let Z=[];for(let[,q]of y.testSpecs)Z.push({filePath:q.file,specType:"test-spec",key:q.key,version:q.version,testTarget:q.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let X=kw(Z,y);for(let q of j)for(let G of q.opToPresentationLinks){let z=n$(G.op.key,G.op.version),_=X.targetToTests.get(z),L=!1,I=!1;if(_)for(let E of _){let N=y.testSpecs.get(E);if(N?.testCoverage){if(N.testCoverage.hasSuccess)L=!0;if(N.testCoverage.hasError)I=!0}}if(!_||!L||!I){let E=[];if(!L)E.push("success scenario");if(!I)E.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${G.op.key}.v${G.op.version} linked to presentation requires tests covering: ${E.join(", ")}`,file:q.filePath,featureKey:q.key,specType:"operation",ref:G.op})}}let Y={},H=0;for(let q of Q){let G=pn(y,q);if(!G)continue;let z=G.size,_=0,L=0,I=b.requireTestsFor?.includes(q);for(let[E,N]of G){if(B.has(`${q}:${E}`))_++;if(I){let M=n$(N.key,N.version),r=X.targetToTests.has(M),g=`${N.key}.test`,o0=y.testSpecs.has(n$(g,N.version));if(!r&&!o0)L++,H++,w.push({severity:"warning",type:"missing-test",message:`${q} ${N.key}.v${N.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:N.file,specKey:N.key,specType:N.type})}}Y[q]={total:z,covered:_,orphaned:z-_,missingTest:I?L:0}}let J=Object.values(Y).reduce((q,G)=>q+G.total,0),O=Object.values(Y).reduce((q,G)=>q+G.covered,0),V={total:J,linkedToFeature:O,orphaned:J-O,missingTest:H,byType:Y},K=!w.some((q)=>q.severity==="error");return n.info("Integrity analysis complete",{features:W.length,totalSpecs:J,orphaned:S.length,issues:w.length,healthy:K}),{inventory:y,features:j,coverage:V,issues:w,orphanedSpecs:S,healthy:K}}function WV($){let b=[];for(let A of Object.values($))for(let n of A.values())b.push(n);return b}function wV($,b){return $.filter((A)=>A.type===b)}function jV($,b){return $.filter((A)=>A.severity===b)}async function an($,b){let A=[],n=await P($.fs),m=await n0($,{config:n,pattern:b.pattern,all:!0});for(let y of m.issues)A.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 A}async function en($,b){let A=[],n=await pA($,{});for(let[m,y]of n.inventory.features){if(!y.key)A.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)A.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)A.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 n.inventory.examples){if(!y.entrypoints.packageName)A.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)A.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 n.inventory.workspaceConfigs.values())if(!m.valid)for(let y of m.errors)A.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${y}`,category:"layers",file:m.file});return A}b$();import{ContractsrcSchema as $4,DEFAULT_CONTRACTSRC as y0}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as FQ}from"@contractspec/module.workspace";async function B$($,b={}){let{fs:A,scan:n=FQ}=$,m=await h$(A,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(Rb(w,b.config))continue;if(Ib(w))continue;try{let j=await A.readFile(w),B=n(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function OV($){let b=new Map;for(let A of $){let n=b.get(A.specType)??[];n.push(A),b.set(A.specType,n)}return b}var iw={};f(iw,{toPascalCase:()=>m0,syncPackageDeclarations:()=>pQ,resolvePackageDeclarationConfig:()=>vb,renderPackageDeclaration:()=>wm,normalizePath:()=>I$,matchesAllowMissing:()=>Wm,inferWorkspacePackageKind:()=>$m,getIndexExportPath:()=>Am,getCanonicalDeclarationRelativePath:()=>bm,discoverWorkspacePackages:()=>cw,createPackageDeclarationIssue:()=>jm,buildPackageTitle:()=>gb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>H$,buildDomain:()=>mm,buildDeclarationTags:()=>ym,auditPackageDeclarations:()=>Pb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>sn,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>rw});var rw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},sn={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function vb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...rw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function $m($){let b=I$($);for(let[A,n]of Object.entries(sn))if(b.startsWith(A))return n;return null}function bm($,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/${m0(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function Am($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${m0(b)}Bundle`;case"examples":return"./example"}}function nm($){return I$($).replace(/^packages\//,"").replace(/\//g,".")}function gb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function mm($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function ym($,b,A){return[...new Set([...A,"package",b,$])]}function Wm($,b,A){return $.some((n)=>{let m=I$(n);return m===I$(b)||m===A})}function I$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function m0($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function H$($,b){let A=m0(b);switch($){case"feature":return`${A}Feature`;case"integration":return`${A}IntegrationSpec`;case"app-config":return`${A}Blueprint`;case"module-bundle":return`${A}Bundle`;case"example":return`${A}Example`}}import{scanAllSpecsFromSource as vQ,scanSpecSource as gQ}from"@contractspec/module.workspace";var PQ=["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 cw($,b={}){let A=I$(b.workspaceRoot??process.cwd()),n=await kQ($,A,b.config),m=await $.glob({cwd:A,patterns:n,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=vb(b.config),W=[];for(let w of m){let j=I$($.dirname(w)),B=$m(j);if(!B)continue;let S=await hw($,$.join(A,w)),Q=$.basename(j),Z=$.join(A,j),X=y.requiredByKind?.[fQ(B)];if(!X)continue;let Y=bm(B,Q);W.push({workspaceRoot:A,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:Am(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function Pb($,b={}){let A=await cw($,b),n=[];for(let m of A){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=vQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[gQ(j,m.canonicalDeclarationPath)]).find((Q)=>Q.specType!=="unknown")?.specType,w=W===m.target}n.push({...m,exists:y,matchesExpectedTarget:w,detectedSpecType:W})}return n}async function kQ($,b,A){let n=$.join(b,"package.json");if(await $.exists(n)){let m=await hw($,n),y=rQ(m);if(y.length>0)return y.map((W)=>`${fw(W)}/package.json`)}if(A?.packages?.length)return A.packages.map((m)=>`${fw(m)}/package.json`);return PQ}function rQ($){if(Array.isArray($.workspaces))return $.workspaces.filter((A)=>typeof A==="string");let b=$.workspaces;if(Array.isArray(b?.packages))return b.packages.filter((A)=>typeof A==="string");return[]}function fQ($){return $==="appsRegistry"?"appsRegistry":$}function fw($){return $.replace(/\/+$/,"")}async function hw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function wm($){let{pkg:b,refs:A,owners:n,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:gb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:mm(b.packageDirName),owners:n,tags:ym(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return cQ(b,A,y);case"integration":return hQ(b,A,y);case"app-config":return dQ(b,A,y);case"module-bundle":return rA({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:H$("module-bundle",b.packageDirName)});case"example":return EA({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 cQ($,b,A){let n=[Sb("operations",b.operations),Sb("events",b.events),Sb("presentations",b.presentations),Sb("experiments",b.experiments),Sb("workflows",b.workflows),Sb("dataViews",b.dataViews)].filter(Boolean);return`${$.packageName==="@contractspec/lib.contracts-spec"?"import { defineFeature } from './features';":"import { defineFeature } from '@contractspec/lib.contracts-spec/features';"}
|
|
1973
|
+
|
|
1974
|
+
export const ${H$("feature",$.packageDirName)} = defineFeature({
|
|
1975
|
+
meta: ${uQ(A)},
|
|
1976
|
+
${n.length>0?`${n.join(`
|
|
1945
1977
|
`)}
|
|
1946
1978
|
`:""}});
|
|
1947
|
-
`}function
|
|
1979
|
+
`}function hQ($,b,A){let n=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1948
1980
|
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1949
1981
|
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1950
1982
|
|
|
1951
|
-
const ${
|
|
1952
|
-
name: '${
|
|
1983
|
+
const ${H$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1984
|
+
name: '${gb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1953
1985
|
description: 'Managed configuration for ${$.packageName}.',
|
|
1954
1986
|
fields: {},
|
|
1955
1987
|
});
|
|
1956
1988
|
|
|
1957
|
-
const ${
|
|
1958
|
-
name: '${
|
|
1989
|
+
const ${H$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1990
|
+
name: '${gb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1959
1991
|
description: 'Secret material for ${$.packageName}.',
|
|
1960
1992
|
fields: {},
|
|
1961
1993
|
});
|
|
1962
1994
|
|
|
1963
|
-
export const ${
|
|
1995
|
+
export const ${H$("integration",$.packageDirName)} = defineIntegration({
|
|
1964
1996
|
meta: {
|
|
1965
|
-
...${
|
|
1997
|
+
...${uw(A)},
|
|
1966
1998
|
category: 'custom',
|
|
1967
1999
|
},
|
|
1968
2000
|
supportedModes: ['managed'],
|
|
1969
2001
|
capabilities: {
|
|
1970
2002
|
provides: [
|
|
1971
|
-
${
|
|
2003
|
+
${n||" // Add capability refs here"}
|
|
1972
2004
|
],
|
|
1973
2005
|
},
|
|
1974
|
-
configSchema: { schema: ${
|
|
1975
|
-
secretSchema: { schema: ${
|
|
2006
|
+
configSchema: { schema: ${H$("integration",$.packageDirName)}Config, example: {} },
|
|
2007
|
+
secretSchema: { schema: ${H$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1976
2008
|
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1977
2009
|
});
|
|
1978
|
-
`}function
|
|
1979
|
-
`),m=
|
|
2010
|
+
`}function dQ($,b,A){let n=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
2011
|
+
`),m=dw(b.workflows),y=dw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1980
2012
|
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1981
2013
|
|
|
1982
|
-
export const ${
|
|
2014
|
+
export const ${H$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1983
2015
|
meta: {
|
|
1984
|
-
...${
|
|
2016
|
+
...${uw(A)},
|
|
1985
2017
|
appId: '${Q$($.packageDirName)}',
|
|
1986
2018
|
},
|
|
1987
2019
|
capabilities: {
|
|
1988
2020
|
enabled: [
|
|
1989
2021
|
${W||" // Add capability refs here"}
|
|
1990
2022
|
],
|
|
1991
|
-
},${
|
|
2023
|
+
},${n?`
|
|
1992
2024
|
features: {
|
|
1993
2025
|
include: [
|
|
1994
|
-
${
|
|
2026
|
+
${n}
|
|
1995
2027
|
],
|
|
1996
2028
|
},`:""}${y?`
|
|
1997
2029
|
dataViews: {
|
|
@@ -2001,14 +2033,14 @@ ${y}
|
|
|
2001
2033
|
${m}
|
|
2002
2034
|
},`:""}
|
|
2003
2035
|
});
|
|
2004
|
-
`}function
|
|
2005
|
-
${b.map((
|
|
2036
|
+
`}function Sb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2037
|
+
${b.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
2006
2038
|
`)}
|
|
2007
|
-
],`}function
|
|
2039
|
+
],`}function dw($){return $.map((b,A)=>` ${A===0?"primary":`item${A+1}`}: {
|
|
2008
2040
|
key: '${b.key}',
|
|
2009
2041
|
version: '${b.version}',
|
|
2010
2042
|
},`).join(`
|
|
2011
|
-
`)}function
|
|
2043
|
+
`)}function uQ($){return`{
|
|
2012
2044
|
key: '${$.key}',
|
|
2013
2045
|
version: '${$.version}',
|
|
2014
2046
|
title: '${Q$($.title)}',
|
|
@@ -2017,13 +2049,13 @@ ${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
|
2017
2049
|
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
2050
|
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2019
2051
|
stability: '${$.stability}',
|
|
2020
|
-
}`}function
|
|
2021
|
-
`);let B=await
|
|
2052
|
+
}`}function uw($){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 oQ}from"@contractspec/module.workspace";var iQ={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 lQ($){return $.packageName!=="@contractspec/lib.schema"}function tQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function pQ($,b={}){let A=await Pb($,b),n=[],m=[],y=[];for(let W of A){if(!b.force&&W.exists&&W.matchesExpectedTarget){y.push({...W,action:"skipped",declarationCreated:!1,indexUpdated:!1,packageJsonUpdated:!1,dependenciesUpdated:[]});continue}let w=await aQ($,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()}
|
|
2053
|
+
`);let B=await eQ($,W,b.dryRun,lQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await sQ($,W,b.dryRun);if(W.exists)m.push(W.canonicalDeclarationPath);else n.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:n,updatedFiles:m}}function jm($,b){return{allowlisted:Wm(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 aQ($,b){let A=await $.glob({cwd:b.packageRoot,patterns:["src/**/*.{ts,tsx}"],absolute:!1,ignore:["**/dist/**","**/*.test.*","**/*.spec.*","**/*.stories.*"]}),n={operations:[],events:[],presentations:[],experiments:[],workflows:[],dataViews:[],capabilities:[],features:[]};for(let m of A){if(m===b.canonicalDeclarationRelativePath)continue;let y=await $.readFile($.join(b.packageRoot,m)),W=oQ(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":C$(n.operations,j);break;case"event":C$(n.events,j);break;case"presentation":C$(n.presentations,j);break;case"experiment":C$(n.experiments,j);break;case"workflow":C$(n.workflows,j);break;case"data-view":C$(n.dataViews,j);break;case"capability":C$(n.capabilities,j);break;case"feature":C$(n.features,j);break}}}return n}function C$($,b){if(!$.some((A)=>A.key===b.key&&A.version===b.version))$.push(b)}async function eQ($,b,A=!1,n=!0){if(!n)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()}
|
|
2022
2054
|
${m}
|
|
2023
|
-
`.trimStart(),!
|
|
2024
|
-
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function
|
|
2025
|
-
`).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=Fb(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 gb(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 $K($,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(),q=await Bm(B);y.push(...q),W.push(e("structure",q,Date.now()-V))}if(w.includes("integrity")){let V=Date.now(),q=await p0($,b);y.push(...q),W.push(e("integrity",q,Date.now()-V))}if(w.includes("deps")){let V=Date.now(),q=await x0($,b);y.push(...q),W.push(e("deps",q,Date.now()-V))}if(w.includes("doctor")){let V=Date.now(),q=await f0($,b);y.push(...q),W.push(e("doctor",q,Date.now()-V))}if(w.includes("docs")){let V=Date.now(),q=await I0($,b);y.push(...q),W.push(e("docs",q,Date.now()-V))}if(w.includes("policy")){let V=Date.now(),q=await jm($,b);y.push(...q),W.push(e("policy",q,Date.now()-V))}if(w.includes("handlers")||b.checkHandlers){let V=Date.now(),q=await o0($,B);y.push(...q),W.push(e("handlers",q,Date.now()-V))}if(w.includes("tests")||b.checkTests){let V=Date.now(),q=await Qm($,B);y.push(...q),W.push(e("tests",q,Date.now()-V))}if(w.includes("test-refs")){let V=Date.now(),q=await Sm(B);y.push(...q),W.push(e("test-refs",q,Date.now()-V))}if(w.includes("coverage")){let V=Date.now(),q=await C0($,B,b);y.push(...q),W.push(e("coverage",q,Date.now()-V))}if(w.includes("implementation")){let V=Date.now(),q=await i0($,B,b);y.push(...q),W.push(e("implementation",q,Date.now()-V))}if(w.includes("layers")){let V=Date.now(),q=await a0($,b);y.push(...q),W.push(e("layers",q,Date.now()-V))}if(w.includes("drift")){let V=Date.now(),q=await u0($,b);y.push(...q),W.push(e("drift",q,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 nK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],AK={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 jK($,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:()=>ub,withBranch:()=>o$,verifyConnectMutation:()=>B6,resolveWorkspace:()=>i,resolveStoragePaths:()=>X$,replayConnectDecision:()=>f4,persistLatestArtifacts:()=>zm,persistDecisionArtifacts:()=>db,normalizeEvalInput:()=>T4,matchConfiguredPath:()=>Pb,loadStoredDecision:()=>ob,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>c4,isReviewCommand:()=>Zm,isDeniedCommand:()=>Xm,isAllowedCommand:()=>jA,initConnectWorkspace:()=>g4,inferSurfaces:()=>fb,evaluateConnectDecision:()=>E4,ensureStorage:()=>hb,defaultActor:()=>rb,decisionArtifactRefs:()=>Sb,createConnectControlPlaneRuntime:()=>e4,connectVerdictToPolicy:()=>I$,configuredThreshold:()=>u$,compileConnectPlanPacket:()=>ib,buildConnectContextPack:()=>cb,assessConnectPolicy:()=>kb,assertConnectEnabled:()=>A$,artifactRef:()=>_$,appendAuditRecord:()=>Lm,analyzeConnectImpact:()=>i$,CONTROL_PLANE_TRACE_GET_REF:()=>BA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>SA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Om,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 Pb($,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"},Om={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 kb($,b){let n=b.touchedPaths.find((Z)=>Pb($,Z,$.config.connect?.policy?.immutablePaths)),A=b.touchedPaths.find((Z)=>Pb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>Pb($,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:()=>qm,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("\u274C **Breaking changes detected**");else if($.hasNonBreaking)n.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else n.push("\u2705 **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(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)n.push(`| \u2796 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("### \u26A0\uFE0F 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("### \u2705 No Drift Detected"),n.push("");return n.push("---"),n.push(`*Generated by ContractSpec at ${$.timestamp}*`),n.join(`
|
|
2026
|
-
`)}function
|
|
2055
|
+
`.trimStart(),!A)await $.writeFile(b.indexPath,W);return!0}async function sQ($,b,A=!1){let n=$.join(b.packageRoot,"package.json"),m=JSON.parse(await $.readFile(n)),y=ow(m,"dependencies"),W=[],w=!1;for(let B of iQ[b.target]){if(!tQ(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=ow(m,"exports");if(w=w||W.length>0,typeof j["."]!=="string")j["."]="./src/index.ts",w=!0;if(w&&!A)await $.writeFile(n,`${JSON.stringify(m,null,"\t")}
|
|
2056
|
+
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function ow($,b){let A=$[b];if(typeof A==="object"&&A!==null&&!Array.isArray(A))return A;let n={};return $[b]=n,n}var b4=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,A4=/@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?)?['"]/,n4=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,m4=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,y4=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,W4=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,w4=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function W0($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function j4($,b){let A=$.replaceAll("\\","/"),n=new Set(["contracts","features",...W0(b?.conventions?.operations),...W0(b?.conventions?.events),...W0(b?.conventions?.presentations),...W0(b?.conventions?.forms)]);return A.split("/").some((m)=>n.has(m))}function B4($,b,A){let n=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(n))return!1;if(n.includes("/node_modules/")||n.includes("/dist/")||y4.test(n)||m4.test(n)||n.endsWith(".d.ts")||n.endsWith(".test.ts")||n.endsWith(".spec.ts"))return!1;if(b.has(n))return!1;if(j4(n,A))return!1;return b4.test(n)}function lw($){return $.replaceAll("\\","/").match(W4)?.[1]??null}function S4($){let b=$.split(`
|
|
2057
|
+
`).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 Q4($){if(!$)return y0;let b=$4.safeParse($),A=b.success?b.data:{};return{...y0,...A,conventions:{...y0.conventions,...A.conventions??{}},ci:{...y0.ci,...A.ci??{}}}}async function Bm($,b){let{fs:A,logger:n}=$,m=[],y=b.config?Q4(b.config):await P(A),W=vb(y),w=await B$({fs:A},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>lw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await A.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!B4(Q,j,y))continue;try{let Z=await A.readFile(Q);if(S4(Z))continue;let X=lw(Q);if(!(X!==null&&w4.test(X)&&B.has(X))&&!n4.test(Z))continue;if(A4.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){n.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await Pb(A,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=jm(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 Z4}from"@contractspec/module.workspace";async function Sm($){let b=[];for(let A of $){let n=Z4(A);for(let m of n.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:m,category:"structure",file:A.filePath});for(let m of n.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:m,category:"structure",file:A.filePath})}return b}async function Qm($){let b=[],A=new Map,n=new Map;for(let m of $){if(!m.key||!m.version)continue;if(m.specType==="test-spec"){let y=`${m.key}.v${m.version}`;A.set(y,{key:m.key,version:m.version,file:m.filePath,type:"test-spec"})}if(m.testRefs&&m.testRefs.length>0){if(!n.has(m.filePath))n.set(m.filePath,[]);n.get(m.filePath)?.push({key:m.key,version:m.version,testRefs:m.testRefs})}}for(let[m,y]of n)for(let W of y){if(!W.testRefs)continue;let w=tn(m,W.key,W.version,W.testRefs,A,{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}b$();async function Zm($,b){let{fs:A}=$,n=[],m=await P(A);for(let y of b){if(y.specType!=="operation")continue;let W=await b0(y,{fs:A},m,{checkTests:!0,outputDir:m.outputDir});for(let w of W.errors)n.push({ruleId:"test-missing",severity:"warning",message:w,category:"tests",file:y.filePath});for(let w of W.warnings)n.push({ruleId:"test-warning",severity:"warning",message:w,category:"tests",file:y.filePath})}return n}function e($,b,A){let n={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:n[$],errors:m,warnings:y,notes:W,passed:m===0,durationMs:A}}async function tw($){try{if(!await $.exists(".git/HEAD"))return{};let A=await $.readFile(".git/HEAD"),n=A.match(/^ref: (.+)$/m);if(n){let y=n[1]?.replace("refs/heads/",""),W=`.git/${n[1]}`;if(await $.exists(W))return{commitSha:(await $.readFile(W)).trim(),branch:y};return{branch:y}}return{commitSha:A.trim()}}catch{return{}}}function pw($){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((n)=>!$.skip?.includes(n));return A}async function OK($,b={}){let A=Date.now(),{fs:n,logger:m}=$,y=[],W=[],w=pw(b);m.info("Starting CI checks...",{checks:w});let j=await P(n),B=await cA($,{config:j,pattern:b.pattern});if(w.includes("structure")){let J=Date.now(),O=await Sm(B);y.push(...O),W.push(e("structure",O,Date.now()-J))}if(w.includes("integrity")){let J=Date.now(),O=await an($,b);y.push(...O),W.push(e("integrity",O,Date.now()-J))}if(w.includes("deps")){let J=Date.now(),O=await Cn($,b);y.push(...O),W.push(e("deps",O,Date.now()-J))}if(w.includes("doctor")){let J=Date.now(),O=await fn($,b);y.push(...O),W.push(e("doctor",O,Date.now()-J))}if(w.includes("docs")){let J=Date.now(),O=await xn($,b);y.push(...O),W.push(e("docs",O,Date.now()-J))}if(w.includes("policy")){let J=Date.now(),O=await Bm($,b);y.push(...O),W.push(e("policy",O,Date.now()-J))}if(w.includes("handlers")||b.checkHandlers){let J=Date.now(),O=await on($,B);y.push(...O),W.push(e("handlers",O,Date.now()-J))}if(w.includes("tests")||b.checkTests){let J=Date.now(),O=await Zm($,B);y.push(...O),W.push(e("tests",O,Date.now()-J))}if(w.includes("test-refs")){let J=Date.now(),O=await Qm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-J))}if(w.includes("coverage")){let J=Date.now(),O=await In($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-J))}if(w.includes("implementation")){let J=Date.now(),O=await ln($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-J))}if(w.includes("layers")){let J=Date.now(),O=await en($,b);y.push(...O),W.push(e("layers",O,Date.now()-J))}if(w.includes("drift")){let J=Date.now(),O=await un($,b);y.push(...O),W.push(e("drift",O,Date.now()-J))}let S=y.filter((J)=>J.severity==="error").length,Q=y.filter((J)=>J.severity==="warning").length,Z=y.filter((J)=>J.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await tw(n),H={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-A,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:H.durationMs}),H}var UK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],VK={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 RK($,b={}){let{fs:A,logger:n}=$,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 A.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await A.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)n.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await A.remove(Q),n.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}}b$();var zj={};f(zj,{writeReviewPacket:()=>Im,writeDecisionEnvelope:()=>ob,withBranch:()=>i$,verifyConnectMutation:()=>J6,resolveWorkspace:()=>l,resolveStoragePaths:()=>X$,replayConnectDecision:()=>a4,persistLatestArtifacts:()=>Lm,persistDecisionArtifacts:()=>ub,normalizeEvalInput:()=>c4,matchConfiguredPath:()=>kb,loadStoredDecision:()=>ib,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>e4,isReviewCommand:()=>Xm,isDeniedCommand:()=>Ym,isAllowedCommand:()=>w0,initConnectWorkspace:()=>i4,inferSurfaces:()=>cb,evaluateConnectDecision:()=>r4,ensureStorage:()=>db,defaultActor:()=>fb,decisionArtifactRefs:()=>Zb,createConnectControlPlaneRuntime:()=>j6,connectVerdictToPolicy:()=>x$,configuredThreshold:()=>o$,compileConnectPlanPacket:()=>lb,buildConnectContextPack:()=>hb,assessConnectPolicy:()=>rb,assertConnectEnabled:()=>m$,artifactRef:()=>_$,appendAuditRecord:()=>Rm,analyzeConnectImpact:()=>l$,CONTROL_PLANE_TRACE_GET_REF:()=>j0,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>B0,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Om,CONTROL_PLANE_PLAN_COMPILE_REF:()=>qm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>V$,AGENT_APPROVALS_REF:()=>S0,ACP_TERMINAL_EXEC_REF:()=>G4,ACP_FS_ACCESS_REF:()=>H4});import X4 from"micromatch";function m$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function kb($,b,A){if(!A||A.length===0)return!1;let n=b.replaceAll("\\","/");return X4.isMatch(n,A,{contains:!0})}function o$($,b,A){return $.config.connect?.policy?.reviewThresholds?.[b]??A}function w0($,b){return Hm($.config.connect?.commands?.allow,b)}function Xm($,b){return Hm($.config.connect?.commands?.review,b)}function Ym($,b){return Hm($.config.connect?.commands?.deny,b)}function Hm($,b){if(!$||$.length===0)return!1;return $.some((A)=>b===A||b.startsWith(`${A} `))}function ew($,b){if(b.length===0)return{state:"none"};for(let n of b)if(Ym($,n))return{commandMatch:n,state:"deny"};for(let n of b)if(Xm($,n))return{commandMatch:n,state:"review"};if(b.every((n)=>w0($,n)))return{state:"allow"};let A=b.find(Y4);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((n)=>!w0($,n)),state:"unknown"}}function Y4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return aw(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return aw(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function aw($,b){return b.every((A)=>$.includes(A)||$.includes(A.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Om={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},j0={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},B0={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},V$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},H4={key:"acp.fs.access",version:"1.0.0",kind:"command"},G4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},S0={key:"agent.approvals",version:"1.0.0",kind:"command"};function rb($,b){let A=b.touchedPaths.find((Z)=>kb($,Z,$.config.connect?.policy?.immutablePaths)),n=b.touchedPaths.find((Z)=>kb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>kb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=ew($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=q4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(A),protectedPath:Boolean(n),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=O4({breakingChange:b.impactAnalysis.breakingChange,commandMatch:y,commandState:W,contractDrift:j,protectedPath:n,unknownPaths:b.impactAnalysis.unknownPaths}),Q=x$(B);return{commandMatch:y,commandState:W,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:m,immutablePath:A,protectedPath:n,requiredApprovals:Q.requiresApproval?[{capability:V$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function x$($){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 q4($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(o$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(o$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(o$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(o$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(o$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(J4)[0]??"permit"}function O4($){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 J4($,b){return sw($)-sw(b)}function sw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as P4}from"crypto";var mj={};f(mj,{formatPrComment:()=>$j,formatMinimalComment:()=>Jm,formatJson:()=>Aj,formatCheckRun:()=>bj,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>L4});function $j($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)A.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else A.push("\u2705 **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| \u2796 Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let n=$.deltas.filter((y)=>y.severity==="breaking"),m=$.deltas.filter((y)=>y.severity==="non_breaking");if(n.length>0){A.push("#### \uD83D\uDD34 Breaking Changes"),A.push("");for(let y of n)A.push(`- **${y.specKey}**: ${y.description}`);A.push("")}if(m.length>0){A.push("#### \uD83D\uDFE1 Non-breaking Changes"),A.push("");for(let y of m)A.push(`- **${y.specKey}**: ${y.description}`);A.push("")}}if($.addedSpecs.length>0){A.push("### Added Specs"),A.push("");for(let n of $.addedSpecs)A.push(`- \`${n.key}\` v${n.version} (${n.type})`);A.push("")}if($.removedSpecs.length>0){A.push("### Removed Specs"),A.push("");for(let n of $.removedSpecs)A.push(`- \`${n.key}\` v${n.version} (${n.type})`);A.push("")}if(b.drift)if(b.drift.hasDrift){A.push("### \u26A0\uFE0F Drift Detected"),A.push(""),A.push("The following generated files are out of sync with their specs:"),A.push("");for(let n of b.drift.files)A.push(`- \`${n}\``);A.push(""),A.push("Run `contractspec generate` to regenerate artifacts."),A.push("")}else A.push("### \u2705 No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
2058
|
+
`)}function Jm($){if($.hasBreaking)return`\u274C **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`\u26A0\uFE0F **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"\u2705 **No contract impact**"}function bj($,b,A={}){let n=A.key??"ContractSpec Impact",m=A.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=Jm($);return{name:n,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 Aj($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((A)=>({type:A.rule,path:A.specKey,summary:A.description,severity:A.severity==="breaking"?"breaking":A.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as U4,computeIoDiff as V4,generateSnapshot as nj}from"@contractspec/module.workspace";async function K$($,b={}){let{fs:A,git:n,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting impact detection...",{baseline:b.baseline});let w=(await A.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 K4(A,w,y),B=nj(j),S;if(b.baseline){let X=await _4(A,n,w,b.baseline,y);S=nj(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=z4(S.specs,B.specs),Z=U4(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 K4($,b,A){let n=[];for(let m of b){let y=await $.readFile(m);n.push({path:m,content:y})}return n}async function _4($,b,A,n,m){let y=[];for(let W of A)try{let w=await b.showFile(n,W);y.push({path:W,content:w})}catch{}return y}function z4($,b){let A=[],n=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=n.get(y);if(w&&W.type==="operation"&&w.type==="operation"){let j=V4(w.io,W.io);A.push(...j)}}return A}var L4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
2027
2059
|
# Contract Impact Detection
|
|
2028
2060
|
|
|
2029
2061
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -2069,49 +2101,49 @@ The system consists of three layers:
|
|
|
2069
2101
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
2070
2102
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
2071
2103
|
3. **Integrations**: CLI command + GitHub Action
|
|
2072
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
2073
|
-
`;await $.writeFile(b.auditFile,`${
|
|
2074
|
-
`)}async function
|
|
2075
|
-
`);if(
|
|
2104
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as Wj,readFileSync as wj}from"fs";import{basename as R4,join as Um,resolve as I4}from"path";import{ContractsrcSchema as C4,DEFAULT_CONTRACTSRC as x4}from"@contractspec/lib.contracts-spec/workspace-config";function l($={}){let b=I4($.cwd??process.cwd()),A=$.workspaceRoot??x(b),n=$.packageRoot??c(b),m=$.config??M4(A,n),y=E4(n,A);return{cwd:b,workspaceRoot:A,packageRoot:n,config:m,repoId:y,branch:"unknown"}}function i$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function fb($,b){return b??{id:`cli:${$}`,type:"human"}}function cb($){let b=new Set;for(let A of $){if(A.includes("/cli-")||A.includes("/apps/cli-"))b.add("cli");if(A.includes("/contracts-spec/")||A.includes("/specs/"))b.add("contract");if(A.includes("/components/")||A.includes("/ui/")||A.endsWith(".tsx")||A.endsWith(".jsx"))b.add("ui");if(A.includes("/integrations/")||A.includes("/provider"))b.add("integration");if(A.includes("/libs/")||A.includes("/shared/")||A.includes("/utils/"))b.add("library");if(A.includes("/modules/")||A.includes("/bundles/")||A.includes("/examples/"))b.add("solution");if(A.includes("/runtime/"))b.add("runtime");if(A.includes("/harness"))b.add("harness");if(A.includes("/ai-agent/"))b.add("agent");if(A.includes("/knowledge/"))b.add("knowledge");if(A.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function M4($,b){let A={...x4};if($!==b)A=yj(A,Um($,".contractsrc.json"));return yj(A,Um(b,".contractsrc.json"))}function yj($,b){if(!Wj(b))return $;try{let A=wj(b,"utf-8"),n=JSON.parse(A),m=C4.safeParse(n);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function E4($,b){let A=Um($,"package.json");if(Wj(A))try{let n=JSON.parse(wj(A,"utf-8"));if(n.name)return n.name}catch{}return R4(b)}async function l$($,b){let A=await B$({fs:$.fs},{config:b.workspace.config}),n=new Map(A.filter((j)=>typeof j.key==="string").map((j)=>[j.key,j])),m=b.touchedPaths.map((j)=>T4($.fs,b.workspace,j,A,n)),y=b.baseline!=null?await K$({...$,logger:$.logger??Bj},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,W=await D4($,b.workspace,b.touchedPaths),w=zm([...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 T4($,b,A,n,m){let y=$.resolve(b.workspaceRoot,A),W=_m(A),w=n.map((Y)=>{let H=y$($.relative(b.workspaceRoot,Y.filePath));return{score:v4(A,W,H,Y.key),spec:Y}}).filter((Y)=>Y.score>=45).sort((Y,H)=>H.score-Y.score).slice(0,3),j=n.find((Y)=>Y.filePath===y),B=j?[{score:100,spec:j}]:w,S=B.filter((Y)=>typeof Y.spec.key==="string").map((Y)=>Km(Y.spec.key,Y.spec.version,Y.spec.kind)),Q=B.flatMap((Y)=>[...Y.spec.emittedEvents??[],...Y.spec.policyRefs??[],...Y.spec.testRefs??[]].map((H)=>m.get(H.key)).filter(Boolean).map((H)=>Km(H.key,H.version,H.kind))),Z=zm([...S,...Q]),X=zm([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((Y)=>Y.spec.policyRefs??[]).map((Y)=>Km(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:A,policies:X,reasons:B.map((Y)=>`${Y.spec.key??Y.spec.filePath} matched with score ${Y.score}`),surfaces:cb([A])}}async function D4($,b,A){let n=N4($.fs,b,A),m=await Promise.all(n.map(async(y)=>{let W=$.fs.resolve(b.packageRoot,y.comparisonRoot),w=await $0({...$,logger:$.logger??Bj},b.workspaceRoot,W,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),j=y.filterPrefix&&y.filterPrefix!==y.comparisonRoot?y$($.fs.relative(y.comparisonRoot,y.filterPrefix)):void 0;return w.files.filter((B)=>j?y$(B)===j||y$(B).startsWith(`${j}/`):!0).map((B)=>y$($.fs.join(y.comparisonRoot,B)))}));return[...new Set(m.flat())].sort()}function N4($,b,A){let n=(b.config.connect?.policy?.generatedPaths??[]).map(g4).filter(Boolean),m=b.config.outputDir&&b.config.outputDir!=="./src"?y$(b.config.outputDir):void 0,y=new Map;for(let W of A){let w=y$(W);if(m&&w.startsWith(m))y.set(m,{comparisonRoot:m});for(let j of n)if(w.startsWith(j)){let B=F4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function F4($,b,A){if(b&&A.startsWith(b))return b;return $.basename(A)==="docs"?y$($.dirname(A)):A}function v4($,b,A,n){if(y$($)===y$(A))return 100;let m=_m(A),y=_m(n??""),W=jj($)===jj(A)?40:0,w=Vm($.split("/"),A.split("/"),5),j=Vm(b,m,5),B=Vm(b,y,4);return W+w+j+B}function Vm($,b,A){let n=new Set(b);return $.filter((m)=>n.has(m)).length*A}function _m($){return y$($).split(/[\/._-]+/).filter(Boolean)}function jj($){return y$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function g4($){return y$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function y$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Km($,b,A){return{key:$,version:String(b??"1.0.0"),kind:A==="query"||A==="event"||A==="policy"||A==="capability"?A:"command"}}function zm($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var Bj={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function hb($,b){let A=l(b);m$(A),A=i$(A,await $.git.currentBranch());let n=fb(b.taskId,b.actor),m=await k4($,A.workspaceRoot,b),y=await l$($,{baseline:b.baseline,touchedPaths:m,workspace:A}),W=A.config.connect?.canonPacks??[];return{id:`connect.ctx_${P4()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:n,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():cb(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:A.config.connect?.policy?.smokeChecks??[]}}async function k4($,b,A){let n=A.paths??[];if(n.length>0)return n.map((y)=>Sj($.fs,b,y));if(!A.baseline)return[];return(await $.git.diffFiles(A.baseline)).map((y)=>Sj($.fs,b,y))}function Sj($,b,A){let n=$.resolve(b,A);return $.relative(b,n).replaceAll("\\","/")}import{resolve as t$}from"path";function X$($){let b=$.config.connect?.storage,A=t$($.packageRoot,b?.root??".contractspec/connect");return{root:A,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$(A,"decisions")}}async function db($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function Lm($,b,A){if(A.contextPack)await Z$($,b.contextPack,A.contextPack);if(A.planPacket)await Z$($,b.planPacket,A.planPacket);if(A.patchVerdict)await Z$($,b.patchVerdict,A.patchVerdict)}async function ub($,b,A,n){let m=$.join(b.decisionsDir,A);if(await $.mkdir(m),n.contextPack)await Z$($,$.join(m,"context-pack.json"),n.contextPack);if(n.planPacket)await Z$($,$.join(m,"plan-packet.json"),n.planPacket);if(n.patchVerdict)await Z$($,$.join(m,"patch-verdict.json"),n.patchVerdict);if(n.reviewPacket)await Z$($,$.join(m,"review-packet.json"),n.reviewPacket);if(n.evaluationResult!==void 0)await Z$($,$.join(m,"evaluation-result.json"),n.evaluationResult);if(n.replayBundle!==void 0)await Z$($,$.join(m,"replay-bundle.json"),n.replayBundle);return m}async function ob($,b,A,n){let m=$.join(b.decisionsDir,A,"decision-envelope.json");return await Z$($,m,n),m}async function Rm($,b,A){let n=await Qj($,b.auditFile)??"",m=`${JSON.stringify(A)}
|
|
2105
|
+
`;await $.writeFile(b.auditFile,`${n}${m}`)}async function Im($,b,A){let n=$.join(b.reviewPacketsDir,`${A.id}.json`);return await Z$($,n,A),n}async function ib($,b,A){let n=$.join(b.decisionsDir,A);return{historyDir:n,contextPack:await Qb($,$.join(n,"context-pack.json")),planPacket:await Qb($,$.join(n,"plan-packet.json")),patchVerdict:await Qb($,$.join(n,"patch-verdict.json")),reviewPacket:await Qb($,$.join(n,"review-packet.json")),envelope:await Qb($,$.join(n,"decision-envelope.json"))}}async function Cm($,b){let A=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),n=[];for(let m of A){let y=await Qb($,m);if(y)n.push({filePath:m,packet:y})}return n.sort((m,y)=>m.packet.id.localeCompare(y.packet.id))}function _$($,b,A){return $.relative(b.packageRoot,$.resolve(A)).replaceAll("\\","/")}function Zb($,b,A,n,m){let y=$.join(A.decisionsDir,n);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,A){await $.writeFile(b,`${JSON.stringify(A,null,2)}
|
|
2106
|
+
`)}async function Qb($,b){let A=await Qj($,b);if(!A)return;try{return JSON.parse(A)}catch{return}}async function Qj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function r4($,b,A){let n=l(b);if(m$(n),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let m=X$(n),y=await ib($.fs,m,b.decisionId),W=f4(n,y),w=b.scenarioKey?await A.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:W}):await A.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:W}),j=await ub($.fs,m,b.decisionId,{evaluationResult:w}),B=await $.fs.exists($.fs.join(j,"replay-bundle.json")),S={artifacts:Zb($.fs,n,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 ob($.fs,m,b.decisionId,S),{historyDir:j,evaluation:w,context:W}}function f4($,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 c4($){return $}import{DEFAULT_CONTRACTSRC as o4}from"@contractspec/lib.contracts-spec/workspace-config";async function Q0($,b){let A=$.join(b.root,".gitignore"),n=b.behavior??"auto",m=Yj(b.patterns);if(m.length===0||n==="skip")return{target:"gitignore",filePath:A,action:"skipped",message:n==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(n==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${A}?`,!0))return{target:"gitignore",filePath:A,action:"skipped",message:"User skipped ContractSpec gitignore update"};let y=await $.exists(A),W=y?await $.readFile(A):"",w=h4(W,m);if(Xj(W)===Xj(w))return{target:"gitignore",filePath:A,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(A,w),{target:"gitignore",filePath:A,action:y?"merged":"created",message:y?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(y){return{target:"gitignore",filePath:A,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}function h4($,b){let A=d4(b),n=u4(),m=$.replace(/\r\n/g,`
|
|
2107
|
+
`);if(n.test(m))return m.replace(n,A);if(m.trim().length===0)return A;return`${m.endsWith(`
|
|
2076
2108
|
`)?m:`${m}
|
|
2077
2109
|
`}
|
|
2078
|
-
${
|
|
2110
|
+
${A}`}function d4($){return`# contractspec:init:gitignore:start
|
|
2079
2111
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
2080
|
-
${
|
|
2112
|
+
${Yj($).join(`
|
|
2081
2113
|
`)}
|
|
2082
2114
|
# contractspec:init:gitignore:end
|
|
2083
|
-
`}function
|
|
2084
|
-
`).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 hb($,w);let j=await ZA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Eb.connect,Eb.verificationCache],prompts:b.prompts,root:n.workspaceRoot});return{configPath:m,targetRoot:A,action:W,gitignore:j}}import{randomUUID as XA}from"crypto";async function ib($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let{commands:A,touchedPaths:m}=P4(b.candidate),y=await cb($,{...b,paths:m}),W=rb(b.taskId,b.actor),w=k4(b.candidate.steps,b.candidate),j=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),B=kb(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:Om,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 ob($.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 tb="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:tb,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:tb,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:tb,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:tb,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:tb,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 Oj($,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 hb($.fs,W);let{contextPack:w,planPacket:j}=await ib($,{...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=kb(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),q=I$(V),K=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",J=q.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:U$.key,reason:K}]:[],U={...j,requiredApprovals:J,verificationStatus:q.verificationStatus},H=Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),O=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,O,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:q.verificationStatus,controlPlane:{...j.controlPlane,decisionId:z.decisionId,traceId:z.traceId??j.controlPlane.traceId}}:U,C=V==="require_review"?Oj(A,m,w,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,D=Im(m,b,w,L,O,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 db($.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 ub($.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 qj($)<=qj(b)?$:b}function qj($){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:()=>qW,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:()=>En,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>OW});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 Zz($,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 Gz($,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)+`
|
|
2085
|
-
`,B=
|
|
2115
|
+
`}function u4(){return new RegExp(`${Zj("# contractspec:init:gitignore:start")}[\\s\\S]*?${Zj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function Zj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xj($){return $.replace(/\r\n/g,`
|
|
2116
|
+
`).trimEnd()}function Yj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function i4($,b={}){let A=l(b),n=b.scope==="package"?A.packageRoot:A.workspaceRoot,m=$.join(n,".contractsrc.json"),y={connect:{...o4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=A$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,F(S)),W="merged"}else await $.writeFile(m,F(y));let w=X$(l({...b,workspaceRoot:n,packageRoot:n}));await db($,w);let j=await Q0($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Eb.connect,Eb.verificationCache],prompts:b.prompts,root:A.workspaceRoot});return{configPath:m,targetRoot:n,action:W,gitignore:j}}import{randomUUID as Z0}from"crypto";async function lb($,b){let A=l(b);m$(A),A=i$(A,await $.git.currentBranch());let{commands:n,touchedPaths:m}=l4(b.candidate),y=await hb($,{...b,paths:m}),W=fb(b.taskId,b.actor),w=t4(b.candidate.steps,b.candidate),j=await l$($,{baseline:b.baseline,touchedPaths:m,workspace:A}),B=rb(A,{commands:n,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${Z0()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:A.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:p4(m.length,n.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:qm,planVerify:Om,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...n.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function l4($){let b=new Set($.touchedPaths??[]),A=new Set($.commands??[]);for(let n of $.steps??[]){if(typeof n==="string")continue;for(let m of n.paths??[])b.add(m);for(let m of n.commands??[])A.add(m)}return{commands:[...A],touchedPaths:[...b]}}function t4($,b){if(!$||$.length===0)return[{id:`step_${Z0()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((A)=>typeof A==="string"?{id:`step_${Z0()}`,summary:A}:{id:`step_${Z0()}`,summary:A.summary,paths:A.paths,commands:A.commands,contractRefs:A.contractRefs})}function p4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function a4($,b,A){let n=l(b);m$(n);let m=X$(n),y=await ib($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=A&&(W.decisionId||W.traceId)?await A.getExecutionTrace(W):null,j=A&&w?await A.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 e4($,b={}){let A=l(b);return m$(A),Cm($.fs,X$(A))}import{buildChannelPlanTrace as s4,compileChannelPlan as $6,finalizeChannelPlan as b6,replayExecutionTrace as A6,resolveChannelExecutionActor as n6}from"@contractspec/integration.runtime/channel";import{createHash as m6}from"crypto";var tb="connect.local",y6="connect.runtime-link.v1",W6="connect.adapter.v1",w6="connect-control-plane-bridge";function j6($){return{linkDecision:async({connectDecisionId:b,createdAt:A,input:n,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(A),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:n.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:tb,externalEventId:b,eventType:n.tool==="acp.fs.access"?`connect.fs.${n.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:Z6(y.objective,n)},metadata:Gj({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:X6(j),traceId:B.traceId});if(S.duplicate)return B6($.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=n6(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:Q6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=$6({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=b6({plan:X,decision:S6(m),approvalTimeoutMs:900000,now:w}),H=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:w6,promptVersion:y6,policyVersion:W6,toolTrace:s4(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:H.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:tb,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Gj({connectDecisionId:b,connectVerdict:m.verdict,tool:n.tool})}),{approvalStatus:H.approvalStatus,decisionId:H.id,planId:Y.id,providerKey:tb,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Hj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let A=await Hj($.traceService,b);return A?A6(A):null}}}async function B6($,b,A){let m=(await $.listDecisions({externalEventId:A,limit:1,providerKey:tb,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:tb,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Hj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function S6($){let b=x$($.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 Q6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function Z6($,b){return`${$} [${b.tool}]`}function X6($){return m6("sha256").update($).digest("hex")}function Gj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as O6}from"crypto";async function qj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=Y6(b);if(!A)return{};let n=await Vb({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"?H6(b):void 0,query:xm(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:n.verdict==="permit"?"pass":n.verdict==="rewrite"?"warn":"fail",detail:n.reason},reason:n.reason,remediation:n.selected!=null?[`Prefer ${n.selected.candidate.source} candidate ${n.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:n,verdict:n.verdict}}function Y6($){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 H6($){let b=xm($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function Oj($){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 G6}from"crypto";function Jj($,b,A){let n=$?`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:n}}function Uj($,b){let A=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",n=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:A,detail:n}}function Vj($,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 Kj($,b,A,n,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_${G6()}`,sourceDecisionId:b,objective:n.objective,reason:y.reason,summary:{paths:m,impactedContracts:A.impactedContracts,affectedSurfaces:A.affectedSurfaces,requiredChecks:n.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:V$.key,reason:y.reason}],controlPlane:{traceQuery:j0,policyExplain:B0,approvalStatus:y.runtimeLink?.approvalStatus,decisionId:y.runtimeLink?.decisionId,traceId:y.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 Mm($,b,A,n,m,y,W,w,j){let B=x$(W);return{decisionId:$,summary:n.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??A.actor.traceId},approvalOperationRefs:W==="require_review"?[`${V$.key}@${V$.version}`,`${S0.key}@${S0.version}`]:void 0,remediation:q6(W),reviewPacketRef:w,replay:{traceQuery:j0,policyExplain:B0}}}function q6($){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 J6($,b,A={}){let n=l(b);m$(n),n=i$(n,await $.git.currentBranch());let m=`connect.dec_${O6()}`,y=(A.now??(()=>new Date))().toISOString(),W=X$(n);await db($.fs,W);let{contextPack:w,planPacket:j}=await lb($,{...b,candidate:K6(b)}),B=_6(b),S=await l$($,{baseline:b.baseline,touchedPaths:B,workspace:n}),Q=await z6(A,n.config.connect?.policy?.smokeChecks??[],n.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=rb(n,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await qj($,b),H=[Jj(X.immutablePath,X.protectedPath,X.generatedPath),Uj(X.commandState,X.commandMatch),Vj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],J=U6(X,Y.verdict),O=x$(J),V=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",U=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:V$.key,reason:V}]:[],K={...j,requiredApprovals:U,verificationStatus:O.verificationStatus},q=Zb($.fs,n,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),G=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})),z=Mm(m,b,w,K,G,H,J,void 0),_=A.controlPlane?await A.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:z,planPacket:K,workspace:n}):null,L=_?{...j,requiredApprovals:U,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:_.decisionId,traceId:_.traceId??j.controlPlane.traceId}}:K,I=J==="require_review"?Kj(n,m,w,L,B,{artifactRefs:q,reason:V,runtimeLink:_}):void 0,E=Mm(m,b,w,L,G,H,J,I?_$($.fs,n,$.fs.join(W.reviewPacketsDir,`${I.id}.json`)):void 0,_);if(Y.remediation?.length)E.remediation=Y.remediation;if(await Lm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:E}),I)await Im($.fs,W,I);let N=await ub($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:E,reviewPacket:I}),M={artifacts:Zb($.fs,n,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:m,createdAt:y,runtimeLink:_??void 0,taskId:b.taskId,verdict:J};return await ob($.fs,W,m,M),await Rm($.fs,W,Oj({contextPack:w,createdAt:y,envelope:M,reviewPacket:I,verifyInput:b,workspace:n})),{contextPack:w,planPacket:L,patchVerdict:E,reviewPacket:I,historyDir:N}}function U6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return V6($.verdict,b)}function V6($,b){if(!b)return $;return _j($)<=_j(b)?$:b}function _j($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function K6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function _6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function z6($,b,A){if(!$.runCommand)return[];let n=[];for(let m of b){let y=await $.runCommand(m,{cwd:A});n.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return n}H0();var Dm={};f(Dm,{generateWorkspaceEnvExample:()=>MW,generateWorkflowSpec:()=>lW,generateWorkflowRunnerTemplate:()=>kA,generateWorkflowDevkitWorkflowTemplate:()=>NA,generateWorkflowDevkitStreamRouteTemplate:()=>gA,generateWorkflowDevkitStartRouteTemplate:()=>FA,generateWorkflowDevkitGenericTemplate:()=>PA,generateWorkflowDevkitFollowUpRouteTemplate:()=>vA,generateVisualizationSpec:()=>qW,generateTranslationSpec:()=>HW,generateThemeSpec:()=>iW,generateTestTemplate:()=>PW,generateTestSpec:()=>YW,generateTelemetrySpec:()=>oW,generateTargetEnvExample:()=>EW,generatePwaAppManifestSpec:()=>KW,generateProductIntentSpec:()=>JW,generatePresentationSpec:()=>uW,generatePolicySpec:()=>XW,generateOperationSpec:()=>dW,generateMigrationSpec:()=>hW,generateKnowledgeSpaceSpec:()=>fW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>rW,generateHarnessSuiteSpec:()=>VW,generateHarnessScenarioSpec:()=>UW,generateHandlerTemplate:()=>vW,generateFormSpec:()=>FW,generateFeatureSpec:()=>NW,generateExperimentSpec:()=>DW,generateExampleSpec:()=>EA,generateEventSpec:()=>TW,generateDataViewSpec:()=>IW,generateDataViewRendererTemplate:()=>TA,generateComponentTemplate:()=>gW,generateCapabilitySpec:()=>ZW,generateAppBlueprintSpec:()=>RW,generateAgentSpec:()=>OW});H0();class Rj{ai;templates=Dm;constructor($){this.ai=new Y0($)}}function zz($){return new Rj($)}import{scanSpecSource as N6}from"@contractspec/module.workspace";function Ij($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Mz($,b,A={}){let{fs:n,logger:m}=b,y=await n.exists($);if(!y&&!A.force)return{specPath:$,specInfo:Ij($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let W=Ij($),w;if(y)try{let B=await n.readFile($);W=N6(B,$),w=W.key}catch{}let j=[];if(A.clean&&w)try{let B=await A0(w,{fs:n});for(let S of B)try{await n.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 n.remove($),m.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:W,deleted:!0,cleanedFiles:j,errors:[]}}import{computeSemanticDiff as F6}from"@contractspec/module.workspace";async function Dz($,b,A,n={}){let{fs:m,git:y}=A;if(!await m.exists($))throw Error(`Spec file not found: ${$}`);let w=await m.readFile($),j,B;if(n.baseline)j=await y.showFile(n.baseline,$),B=`${n.baseline}:${$}`;else{if(!await m.exists(b))throw Error(`Spec file not found: ${b}`);j=await m.readFile(b),B=b}let S=F6(w,$,j,B,{breakingOnly:n.breakingOnly});return{spec1:$,spec2:B,differences:S}}b$();import{openApiForRegistry as v6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Nm}from"@contractspec/lib.contracts-spec/operations";async function g6($,b){let{fs:A,logger:n}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;n.info("Loading registry...",{registryPath:m});let W=await P6(m,A);n.info("Generating OpenAPI document...");let w=v6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2117
|
+
`,B=A.resolve(y);return await A.mkdir(A.dirname(B)),await A.writeFile(B,j),n.info(`OpenAPI document written to ${B}`),{document:w,outputPath:B,json:j}}async function P6($,b){let n=await import(b.resolve($));if(n instanceof Nm)return n;if(n.registry instanceof Nm)return n.registry;let m=typeof n.createRegistry==="function"?n.createRegistry:typeof n.default==="function"?n.default:void 0;if(m){let y=await m();if(y instanceof Nm)return y}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as k6,parseOpenApi as r6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Fm,dirname as Cj,join as Xb}from"path";function f6($,b,A){if(b.outputDir)return b.outputDir;let{outputDir:n,conventions:m}=A;switch($){case"operation":return Xb(n,m.operations.split("|")[0]??"operations");case"event":return Xb(n,m.events);case"model":return Xb(n,"models");default:return n}}async function xj($,b,A){let{fs:n,logger:m}=A,{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 r6(y,{fetch:globalThis.fetch,readFile:(U)=>n.readFile(U)});if(X.warnings.length>0)for(let U of X.warnings)m.warn(`Parse warning: ${U}`);m.info(`Parsed ${X.operations.length} operations from ${X.info.title} v${X.info.version}`);let Y=k6(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 H=[],J=[],O=[],V=new Map;for(let U of Y.operationSpecs){let K="operation",q=null;if(U.code.includes("defineEvent("))K="event",q=U.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((U.code.includes("defineSchemaModel(")||U.code.includes("new EnumType(")||U.code.includes("ScalarTypeEnum.")||U.code.includes("new ZodSchemaType(")||U.code.includes("z.enum(")||U.code.includes("new JsonSchemaType(")||U.code.includes("new GraphQLSchemaType("))&&!U.code.includes("defineCommand(")&&!U.code.includes("defineQuery("))K="model";else K="operation",q=U.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let G=f6(K,b,$),z=Xb(G,U.fileName);if(!q&&K==="model"){if(U.code.includes("new ZodSchemaType("))q=U.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(U.code.includes("new JsonSchemaType("))q=U.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(U.code.includes("new GraphQLSchemaType("))q=U.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!q)q=U.code.match(/export const (\w+)\s*=/)}if(Z)m.info(`[DRY RUN] Would create: ${z}`);else{let _=Cj(z);if(!await n.exists(_))await n.mkdir(_);await n.writeFile(z,U.code),m.info(`Created: ${z}`)}if(H.push({path:z,operationId:U.source.sourceId,specName:U.fileName.replace(".ts","")}),q){let _=Cj(z),L=V.get(_)||[];L.push({file:Fm(z),name:q[1],type:K}),V.set(_,L)}}if(!Z&&H.length>0)for(let[U,K]of V.entries()){if(K.length===0)continue;let q=K.map((M)=>M.type),G=q.every((M)=>M==="operation"),z=q.every((M)=>M==="event"),_=q.every((M)=>M==="model"),L=`/**
|
|
2086
2118
|
* Auto-generated registry file.
|
|
2087
2119
|
*/
|
|
2088
|
-
`;
|
|
2120
|
+
`;K.forEach((M)=>{let r=`./${Fm(M.file,".ts")}`;L+=`import { ${M.name} } from '${r}';
|
|
2089
2121
|
`}),L+=`
|
|
2090
|
-
`;let
|
|
2122
|
+
`;let I=!1;if(G)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
2091
2123
|
|
|
2092
2124
|
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
2093
|
-
`,
|
|
2094
|
-
`}),
|
|
2125
|
+
`,K.forEach((M)=>{L+=`operationRegistry.register(${M.name});
|
|
2126
|
+
`}),I=!0;else if(z)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
2095
2127
|
|
|
2096
2128
|
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2097
|
-
`,
|
|
2098
|
-
`}),
|
|
2129
|
+
`,K.forEach((M)=>{L+=`eventRegistry.register(${M.name});
|
|
2130
|
+
`}),I=!0;else if(_)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
2099
2131
|
|
|
2100
2132
|
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2101
|
-
`,
|
|
2102
|
-
`}),
|
|
2133
|
+
`,K.forEach((M)=>{L+=`modelRegistry.register(${M.name});
|
|
2134
|
+
`}),I=!0;if(I){let M=Xb(U,"registry.ts");await n.writeFile(M,L),m.info(`Created/Updated registry: ${M}`)}let E=`/**
|
|
2103
2135
|
* Auto-generated barrel file.
|
|
2104
2136
|
*/
|
|
2105
2137
|
|
|
2106
|
-
`;if(
|
|
2107
|
-
`}),
|
|
2108
|
-
`;let
|
|
2109
|
-
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function
|
|
2138
|
+
`;if(K.forEach((M)=>{let r=`./${Fm(M.file,".ts")}`;E+=`export * from '${r}';
|
|
2139
|
+
`}),I)E+=`export * from './registry';
|
|
2140
|
+
`;let N=Xb(U,"index.ts");await n.writeFile(N,E),m.info(`Created/Updated index: ${N}`)}for(let U of Y.skipped)J.push({operationId:U.sourceId,reason:U.reason}),m.debug(`Skipped: ${U.sourceId} - ${U.reason}`);for(let U of Y.errors)O.push({operationId:U.sourceId,error:U.error}),m.error(`Error: ${U.sourceId} - ${U.error}`);return{imported:Y.summary.imported,skipped:Y.summary.skipped,errors:Y.summary.errors,files:H,skippedOperations:J,errorMessages:O}}import{importFromOpenApi as c6,parseOpenApi as h6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as d6,join as u6}from"path";async function oz($,b,A){let{fs:n,logger:m}=A,{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 H=await h6(Y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});m.info(`Parsed ${H.operations.length} operations from ${X.name}`);let J=c6(H,b,{prefix:X.prefix,tags:X.tags,exclude:X.exclude,defaultStability:X.defaultStability,defaultAuth:X.defaultAuth});for(let O of J.operationSpecs){let V=u6(S,O.fileName);if(!await n.exists(V)){if(!B){let K=d6(V);await n.mkdir(K),await n.writeFile(V,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:V}),m.info(`Added: ${O.source.sourceId}`)}else if(await n.readFile(V)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:V});else if(j==="openapi"){if(!B)await n.writeFile(V,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:V}),m.info(`Updated: ${O.source.sourceId}`)}else if(j==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:V}),m.info(`Kept: ${O.source.sourceId}`);else if(w)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:V}),m.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:V}),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 o6}from"@contractspec/lib.contracts-transformers/openapi";async function tz($,b){let{fs:A,logger:n}=b,{specPath:m,openApiSource:y,ignoreDescriptions:W,ignoreTags:w,ignoreTransport:j}=$;n.info(`Validating specs against OpenAPI: ${y}`);let B=await o6(y,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});n.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 A.stat(m),H=[];if(Y.isDirectory){let O=await A.glob({pattern:"**/*.ts",cwd:m,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});H.push(...O)}else H.push(m);n.info(`Found ${H.length} spec files to validate`);for(let O of H)try{let V=await A.readFile(O),U=V.match(/operationId:\s*['"]([^'"]+)['"]/)||V.match(/name:\s*['"]([^'"]+)['"]/)||V.match(/export\s+const\s+(\w+)Spec\s*=/);if(!U||!U[1]){n.debug(`Could not extract operationId from ${O}`);continue}let K=U[1];Z++;let q;if(q=S.get(K),!q){let _=K.replace(/([A-Z])/g,"_$1").toLowerCase();q=S.get(_)}if(!q){for(let[_,L]of S)if(_.toLowerCase().includes(K.toLowerCase())||K.toLowerCase().includes(_.toLowerCase())){q=L;break}}if(!q){Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${K}`}]}),X++;continue}let G=[];if(q.deprecated&&!V.includes("deprecated"))G.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!j){let _=V.match(/path:\s*['"]([^'"]+)['"]/);if(_&&_[1]!==q.path)G.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${_[1]}", OpenAPI has "${q.path}"`})}if(!j){let _=V.match(/method:\s*['"]([^'"]+)['"]/);if(_?.[1]&&_[1].toLowerCase()!==q.method.toLowerCase())G.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${_[1]}", OpenAPI has "${q.method.toUpperCase()}"`})}let z=G.length===0;if(!z)X++;Q.push({specPath:O,operationId:q.operationId,valid:z,diffs:G})}catch(V){n.error(`Error validating ${O}: ${V}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${V instanceof Error?V.message:String(V)}`}]}),X++}let J=X===0;return n.info(`Validation ${J?"passed":"failed"}: ${Z} specs checked, ${X} with differences`),{valid:J,specsValidated:Z,specsWithDiffs:X,results:Q}}async function yL($,b,A){let{fs:n,logger:m}=$,{source:y,outputDir:W}=b,w=n.resolve(A??process.cwd(),y);if(!await n.exists(w))throw Error(`Source file not found: ${w}`);let B={...await P(n,A),outputDir:W};return m.info(`Extracting contracts from ${w} to ${W}`),xj(B,{source:w,outputDir:W,dryRun:!1},$)}var Ej={};f(Ej,{validateFeatureRefs:()=>t6,getArrayNameForSpecType:()=>Mj,detectFeatureContext:()=>i6,computeAddSpecEdit:()=>l6});function i6($,b){let A=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],n=null;for(let{type:Q,regex:Z,specType:X}of A){let Y;Z.lastIndex=0;while((Y=Z.exec($))!==null)if(!n||Y.index>n.index)n={type:Q,specType:X,index:Y.index}}if(!n)return null;let m=$.slice(n.index)+b,y=n.type;new RegExp(`${y}\\s*:\\s*\\[`).exec(m);let w=$.slice(n.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:n.type,specType:n.specType};return null}function l6($,b){let A=Mj(b.type),m=new RegExp(`${A}\\s*:\\s*\\[`,"g").exec($);if(m){let y=m.index+m[0].length,W=typeof b.version==="string"?`'${b.version}'`:b.version,w=`
|
|
2141
|
+
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function Mj($){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 t6($,b){let A=[],n=(m,y,W)=>{for(let w of m){let j=`${w.key}.v${w.version}`;if(!y.has(j))A.push({key:w.key,version:w.version,type:W,message:`${W} ${w.key}.v${w.version} not found`})}};return n($.operations,b.operations,"Operation"),n($.events,b.events,"Event"),n($.presentations,b.presentations,"Presentation"),n($.experiments,b.experiments,"Experiment"),A}var Fj={};f(Fj,{removeReferenceStrategy:()=>J0,implementSkeletonStrategy:()=>O0,implementAiStrategy:()=>q0,generateFixLinks:()=>p6,FixService:()=>Nj,FIX_STRATEGY_STABILITY:()=>bA,FIX_STRATEGY_LABELS:()=>A7,CiOutputSchema:()=>X7});function p6($,b){let A=[];if(!$.ref||!$.file)return A;if(b.includeCli)A.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let n=$.file.startsWith("/")?$.file:`/${$.file}`,m=$.ref,y=m.line||1,W=m.column||1;A.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${n}:${y}:${W}`})}if(b.includeGithubIssue&&b.repository){let n=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),m=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
2110
2142
|
|
|
2111
2143
|
> ${$.message}
|
|
2112
2144
|
|
|
2113
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
2114
|
-
`)}function
|
|
2145
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);A.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${n}&body=${m}`})}return A}import n7 from"path";function M$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function E$($,b){let A=$.enrichment?.owners?.length?$.enrichment.owners.map((W)=>`'${W}'`).join(", "):"'@team'",n=$.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: [${A}]`),y.push(`tags: [${n}]`),y.push(`description: '${m}'`),y.join(`,
|
|
2146
|
+
`)}function ab($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"Spec",n=E$($,{kind:"'api'"});return`/**
|
|
2115
2147
|
* Capability: ${$.key}
|
|
2116
2148
|
*
|
|
2117
2149
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2122,9 +2154,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",labe
|
|
|
2122
2154
|
|
|
2123
2155
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
2124
2156
|
|
|
2125
|
-
export const ${
|
|
2157
|
+
export const ${A} = defineCapability({
|
|
2126
2158
|
meta: {
|
|
2127
|
-
${
|
|
2159
|
+
${n}
|
|
2128
2160
|
},
|
|
2129
2161
|
|
|
2130
2162
|
provides: [
|
|
@@ -2148,7 +2180,7 @@ export const ${n} = defineCapability({
|
|
|
2148
2180
|
// }
|
|
2149
2181
|
],
|
|
2150
2182
|
});
|
|
2151
|
-
`}function
|
|
2183
|
+
`}function eb($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"EventSpec",n=A.replace("Spec","Payload"),m=E$($);return`/**
|
|
2152
2184
|
* Event: ${$.key}
|
|
2153
2185
|
*
|
|
2154
2186
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2161,8 +2193,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
2161
2193
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2162
2194
|
|
|
2163
2195
|
// TODO: Define event payload schema
|
|
2164
|
-
export const ${
|
|
2165
|
-
name: '${
|
|
2196
|
+
export const ${n} = new SchemaModel({
|
|
2197
|
+
name: '${n}',
|
|
2166
2198
|
description: 'Payload for ${$.key} event',
|
|
2167
2199
|
fields: {
|
|
2168
2200
|
// Add your payload fields here
|
|
@@ -2172,12 +2204,12 @@ export const ${A} = new SchemaModel({
|
|
|
2172
2204
|
},
|
|
2173
2205
|
});
|
|
2174
2206
|
|
|
2175
|
-
export const ${
|
|
2207
|
+
export const ${A} = defineEvent({
|
|
2176
2208
|
meta: {
|
|
2177
2209
|
${m}
|
|
2178
2210
|
},
|
|
2179
2211
|
|
|
2180
|
-
payload: ${
|
|
2212
|
+
payload: ${n},
|
|
2181
2213
|
|
|
2182
2214
|
// TODO: Specify PII fields if any
|
|
2183
2215
|
// piiFields: ['user.email'],
|
|
@@ -2188,7 +2220,7 @@ export const ${n} = defineEvent({
|
|
|
2188
2220
|
// policy: 'archive',
|
|
2189
2221
|
// },
|
|
2190
2222
|
});
|
|
2191
|
-
`}function
|
|
2223
|
+
`}function a6($){let b=$.toLowerCase(),A=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let n of A)if(b.includes(n))return"query";return"command"}function sb($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"Spec",n=A.replace("Spec","Input"),m=A.replace("Spec","Output"),y=a6($.key),W=y==="query"?"defineQuery":"defineCommand",w=$.enrichment?.goal||"TODO: Define the business goal",j=$.enrichment?.context||"TODO: Provide context",B=E$($,{goal:`'${w}'`,context:`'${j}'`});return`/**
|
|
2192
2224
|
* Operation: ${$.key}
|
|
2193
2225
|
*
|
|
2194
2226
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2201,8 +2233,8 @@ import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
|
2201
2233
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2202
2234
|
|
|
2203
2235
|
// TODO: Define input schema
|
|
2204
|
-
export const ${
|
|
2205
|
-
name: '${
|
|
2236
|
+
export const ${n} = new SchemaModel({
|
|
2237
|
+
name: '${n}',
|
|
2206
2238
|
description: 'Input for ${$.key}',
|
|
2207
2239
|
fields: {
|
|
2208
2240
|
// Add your input fields here
|
|
@@ -2220,13 +2252,13 @@ export const ${m} = new SchemaModel({
|
|
|
2220
2252
|
},
|
|
2221
2253
|
});
|
|
2222
2254
|
|
|
2223
|
-
export const ${
|
|
2255
|
+
export const ${A} = ${W}({
|
|
2224
2256
|
meta: {
|
|
2225
2257
|
${B}
|
|
2226
2258
|
},
|
|
2227
2259
|
|
|
2228
2260
|
io: {
|
|
2229
|
-
input: ${
|
|
2261
|
+
input: ${n},
|
|
2230
2262
|
output: ${m},
|
|
2231
2263
|
errors: {
|
|
2232
2264
|
// TODO: Define possible errors
|
|
@@ -2266,7 +2298,7 @@ export const ${n} = ${W}({
|
|
|
2266
2298
|
examples: [],
|
|
2267
2299
|
},
|
|
2268
2300
|
});
|
|
2269
|
-
`}function
|
|
2301
|
+
`}function e6($){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 $A($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"PresentationSpec",n=e6($.key),m=E$($);return`/**
|
|
2270
2302
|
* Presentation: ${$.key}
|
|
2271
2303
|
*
|
|
2272
2304
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2277,12 +2309,12 @@ export const ${n} = ${W}({
|
|
|
2277
2309
|
|
|
2278
2310
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
2279
2311
|
|
|
2280
|
-
export const ${
|
|
2312
|
+
export const ${A} = definePresentation({
|
|
2281
2313
|
meta: {
|
|
2282
2314
|
${m}
|
|
2283
2315
|
},
|
|
2284
2316
|
|
|
2285
|
-
kind: '${
|
|
2317
|
+
kind: '${n}',
|
|
2286
2318
|
|
|
2287
2319
|
// TODO: Define content structure
|
|
2288
2320
|
content: {
|
|
@@ -2306,7 +2338,7 @@ export const ${n} = definePresentation({
|
|
|
2306
2338
|
// focusable: true,
|
|
2307
2339
|
// },
|
|
2308
2340
|
});
|
|
2309
|
-
`}import H$ from"path";function OA($,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)"},$n={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function qA($,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:$n["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=OA($,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 eb($);case"event":return ab($);case"presentation":return sb($);case"capability":return pb($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import e6 from"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:$n["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=OA($,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 eb($);case"event":return ab($);case"presentation":return sb($);case"capability":return pb($);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)=>qA(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"child_process";import{promisify as y7}from"util";var W7=y7(m7),Mj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function rL($,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 dL($,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"child_process";import{promisify as j7}from"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(`\u2713 ${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(`\u2717 ${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?`\u2713 All ${j.length} command(s) passed`:`\u2717 ${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 O7($,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:q7(),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),q=X7(G),K=[...G,...V,q];if(!b.dryRun)for(let U of K){let H=vm(X,U.path),O=H7(H);if(!await m.exists(O))await m.mkdir(O);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 q7(){return`# Import Report
|
|
2341
|
+
`}import G$ from"path";function G0($,b){if(b.outputDir)return vm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=s6($.featureFile);if(A)return vm(A,$.ref.key,$.specType)}return vm(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function s6($){let b=G$.dirname($),A=G$.parse($).root,n=0;while(b!==A&&n<50){if(G$.basename(b)==="src")return b;b=G$.dirname(b),n++}b=G$.dirname($),n=0;while(b!==A&&n<50)b=G$.dirname(b),n++;let m=$.lastIndexOf(`${G$.sep}src${G$.sep}`);if(m!==-1)return $.substring(0,m+5);return null}function vm($,b,A){let n=b.replace(/\./g,"-").toLowerCase(),m=$7(A),y=b7(A);return G$.join($,y,`${n}${m}`)}function $7($){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 b7($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var A7={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},bA={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function q0($,b,A){let{fs:n,logger:m}=A,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:bA["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await m7(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=w7(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=G0($,b),Z=[];if(!b.dryRun){let X=n7.dirname(Q);await n.mkdir(X),await n.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 m7($,b,A){if(A.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:m}=await Promise.resolve().then(() => (H0(),Lj)),y=y7(b),W=new m(y),w=$.specType==="operation"?"command":$.specType,j=`${Tj($.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){A.warn("AIGenerator call failed, falling back to heuristics",{error:m instanceof Error?m.message:String(m)})}let n=W7($.key,$.specType);return{...$,description:n.description,enrichment:{goal:n.goal,context:n.context,owners:["@team"],tags:n.tags}}}function y7($){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 W7($,b){let A=$.split("."),n=A[0]||"unknown",m=A.slice(1).join(" ").replace(/_/g," "),y=[n],W=m.toLowerCase().split(" "),j=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>W.some((S)=>S.includes(B)));return{description:`${Tj(b)} for ${n} ${m}`,goal:`Enable ${m} functionality in the ${n} domain`,context:`Part of the ${n} feature set. Generated by ContractSpec AI fix.`,tags:[...y,...j]}}function w7($){switch($.specType){case"operation":return sb($);case"event":return eb($);case"presentation":return $A($);case"capability":return ab($);default:return}}function Tj($){return $.charAt(0).toUpperCase()+$.slice(1)}import j7 from"path";async function O0($,b,A){let{fs:n}=A,{ref:m,specType:y,featureKey:W}=$;try{let w={key:m.key,version:m.version,specType:y,stability:bA["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=B7(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=G0($,b),S=[];if(!b.dryRun){let Q=j7.dirname(B);await n.mkdir(Q),await n.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 B7($){switch($.specType){case"operation":return sb($);case"event":return eb($);case"presentation":return $A($);case"capability":return ab($);default:return}}async function J0($,b,A){let{fs:n}=A,{ref:m,featureFile:y,specType:W}=$;try{let w=await n.readFile(y),j=w,B=S7(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 n.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 S7($,b,A){if(!Q7(A))return $;let m=Dj(b.key),y=Dj(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=Z7(w),w}function Q7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function Dj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Z7($){return $.replace(/,(\s*)\]/g,"$1]")}class Nj{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)=>O0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,A)=>q0(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,n=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)A++;else n++}catch(y){n++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:A,failed:n,results:b}}async scanAndGetFixables($={}){return(await n0(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:n,select:m}=b;if(A)return Promise.resolve(A);if(n&&$.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 Yb}from"zod";var X7=Yb.union([Yb.array(Yb.unknown()),Yb.object({issues:Yb.array(Yb.unknown())}).transform(($)=>$.issues)]);import{exec as Y7}from"child_process";import{promisify as H7}from"util";var G7=H7(Y7),vj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function mR($,b,A={}){if($.length===0)return;let n=A.cwd??process.cwd(),m=vj[A.type??"biome"]??vj.biome,y=50;for(let W=0;W<$.length;W+=y){let j=$.slice(W,W+y).map((B)=>`"${B}"`).join(" ");try{await G7(`${m} ${j}`,{cwd:n})}catch(B){}}}import T$ from"path";async function jR($,b){let A=T$.join(b,"contracts"),n=T$.join(b,"generated"),m=T$.join(n,"docs"),y=await $.fs.exists(A),W=await $.fs.exists(n);if(!y)return{hasContracts:!1,hasGenerated:W,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let w=await B$($,{pattern:"contracts/**/*.ts"}),j=[];if(W)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts"),H=T$.join(m,`${Y}.md`);if(!await $.fs.exists(H))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(A,"index.ts"),S=T$.join(A,"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 rj={};f(rj,{runHook:()=>gj,getAvailableHooks:()=>Pj});import{exec as q7}from"child_process";import{promisify as O7}from"util";var J7=O7(q7);async function gj($,b){let{fs:A,logger:n}=$,{hookName:m,dryRun:y=!1}=b,W=x(b.workspaceRoot);n.info(`Running hook: ${m}`,{workspaceRoot:W,dryRun:y});let w=await kj(A,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}`};n.info(`Found ${j.length} command(s) for ${m}`);let B=[],S=!0;for(let Z of j){if(y){n.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}n.info(`Executing: ${Z}`);try{let{stdout:X,stderr:Y}=await J7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),n.info(`\u2713 ${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)}),n.error(`\u2717 ${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?`\u2713 All ${j.length} command(s) passed`:`\u2717 ${Q}/${j.length} command(s) passed`}}async function Pj($,b){let A=await kj($.fs,b);return A?Object.keys(A):[]}async function kj($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return null;try{let n=await $.readFile(A);return JSON.parse(n).hooks??null}catch{return null}}import{detectFramework as U7,extractFromProject as V7}from"@contractspec/lib.source-extractors";import{generateOperations as K7,generateRegistry as _7,generateSchemas as z7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as L7}from"@contractspec/lib.source-extractors/extractors";import{dirname as R7,join as gm}from"path";async function I7($,b,A,n){let{fs:m,logger:y}=A,W=n??process.cwd();L7(),y.info(`Scanning source code in ${W}...`);let w={readFile:(K)=>m.readFile(K),glob:(K,q)=>m.glob({pattern:K,cwd:q?.cwd}),exists:(K)=>m.exists(K)},j=await U7(W,{readFile:(K)=>m.readFile(K),glob:(K)=>m.glob({pattern:K})});if(j.frameworks.length===0)return y.warn("No supported frameworks detected"),{success:!1,report:C7(),errors:["No supported frameworks detected in project"]};y.info(`Detected frameworks: ${j.frameworks.map((K)=>K.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let K of B.getAll())if("setFs"in K&&typeof K.setFs==="function")K.setFs(w);let S={scope:b.scope,framework:b.framework},Q=await V7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:x7(Q.errors??[]),errors:Q.errors?.map((K)=>K.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:M7(Z)};let X=b.outputDir??gm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},H=K7(Z,Y),J=z7(Z,Y),O=_7(H),V=[...H,...J,O];if(!b.dryRun)for(let K of V){let q=gm(X,K.path),G=R7(q);if(!await m.exists(G))await m.mkdir(G);await m.writeFile(q,K.content),y.info(`Created: ${q}`)}else for(let K of V)y.info(`[DRY RUN] Would create: ${gm(X,K.path)}`);let U={files:V,operationsGenerated:H.length,schemasGenerated:J.length,warnings:[]};return{success:!0,ir:Z,generation:U,report:E7(Z,U,b)}}function C7(){return`# Import Report
|
|
2310
2342
|
|
|
2311
2343
|
## \u274C No Supported Frameworks Detected
|
|
2312
2344
|
|
|
@@ -2323,13 +2355,13 @@ No supported frameworks were detected in the project.
|
|
|
2323
2355
|
- Next.js API Routes
|
|
2324
2356
|
|
|
2325
2357
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
2326
|
-
`}function
|
|
2358
|
+
`}function x7($){return`# Import Report
|
|
2327
2359
|
|
|
2328
2360
|
## \u274C Extraction Failed
|
|
2329
2361
|
|
|
2330
2362
|
${$.map((b)=>`- ${b.message}`).join(`
|
|
2331
2363
|
`)}
|
|
2332
|
-
`}function
|
|
2364
|
+
`}function M7($){return`# Import Analysis Report
|
|
2333
2365
|
|
|
2334
2366
|
## Summary
|
|
2335
2367
|
|
|
@@ -2361,7 +2393,7 @@ ${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).jo
|
|
|
2361
2393
|
|
|
2362
2394
|
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
2363
2395
|
`):"None"}
|
|
2364
|
-
`}function
|
|
2396
|
+
`}function E7($,b,A){return`# Import Report${A.dryRun?" (Dry Run)":""}
|
|
2365
2397
|
|
|
2366
2398
|
## \u2705 Import Successful
|
|
2367
2399
|
|
|
@@ -2387,42 +2419,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
|
2387
2419
|
|
|
2388
2420
|
### Next Steps
|
|
2389
2421
|
|
|
2390
|
-
1. Review generated contracts in \`${
|
|
2422
|
+
1. Review generated contracts in \`${A.outputDir??"generated/"}\`
|
|
2391
2423
|
2. Fill in TODO placeholders with business context
|
|
2392
2424
|
3. Run \`contractspec validate\` to verify contracts
|
|
2393
2425
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
2394
|
-
`}function
|
|
2395
|
-
`)}function
|
|
2396
|
-
`)}async function
|
|
2397
|
-
`)}function
|
|
2398
|
-
`)}function
|
|
2399
|
-
`)}function
|
|
2400
|
-
`);
|
|
2401
|
-
`)}function
|
|
2402
|
-
`)}async function
|
|
2426
|
+
`}function T7($,b,A={}){let n=[];if(n.push("# Import Report"),n.push(""),n.push(`**Generated**: ${new Date().toISOString()}`),n.push(""),n.push("## Summary"),n.push(""),n.push("| Metric | Count |"),n.push("|--------|-------|"),n.push(`| Files Scanned | ${$.stats.filesScanned} |`),n.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),n.push(`| Schemas Found | ${$.stats.schemasFound} |`),n.push(`| Errors Found | ${$.stats.errorsFound} |`),n.push(`| Events Found | ${$.stats.eventsFound} |`),n.push(""),A.includeStats!==!1)n.push("### Confidence"),n.push(""),n.push("| Level | Count |"),n.push("|-------|-------|"),n.push(`| High | ${$.stats.highConfidence} |`),n.push(`| Medium | ${$.stats.mediumConfidence} |`),n.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),n.push("");n.push("### Frameworks Detected"),n.push("");for(let m of $.project.frameworks)n.push(`- **${m.name}** (${m.confidence})`);if(n.push(""),A.includeEndpoints!==!1&&$.endpoints.length>0){n.push("## Endpoints"),n.push(""),n.push("| Method | Path | Kind | Confidence |"),n.push("|--------|------|------|------------|");for(let m of $.endpoints)n.push(`| ${m.method} | \`${m.path}\` | ${m.kind} | ${m.confidence.level} |`);n.push("")}if(A.includeSchemas!==!1&&$.schemas.length>0){n.push("## Schemas"),n.push(""),n.push("| Name | Type | Confidence |"),n.push("|------|------|------------|");for(let m of $.schemas)n.push(`| ${m.name} | ${m.schemaType} | ${m.confidence.level} |`);n.push("")}if(b&&A.includeIssues!==!1){n.push("## Verification"),n.push(""),n.push("| Status | Count |"),n.push("|--------|-------|"),n.push(`| Valid | ${b.summary.validEndpoints} |`),n.push(`| Warnings | ${b.summary.warningEndpoints} |`),n.push(`| Errors | ${b.summary.errorEndpoints} |`),n.push("");let m=b.endpointResults.filter((y)=>y.issues.length>0);if(m.length>0){n.push("### Issues"),n.push("");for(let y of m){n.push(`#### ${y.endpoint.method} ${y.endpoint.path}`);for(let W of y.issues){let w=W.severity==="error"?"\u274C":W.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(n.push(`- ${w} **${W.code}**: ${W.message}`),W.suggestion)n.push(` - *Suggestion*: ${W.suggestion}`)}n.push("")}}}if(A.includeAmbiguities!==!1&&$.ambiguities.length>0){n.push("## Ambiguities (Require Review)"),n.push("");for(let m of $.ambiguities)if(n.push(`- **${m.type}** (${m.itemId}): ${m.description}`),m.suggestion)n.push(` - *Suggestion*: ${m.suggestion}`);n.push("")}return n.push("## Next Steps"),n.push(""),n.push("1. Review generated contracts in the output directory"),n.push("2. Fill in TODO placeholders with business context"),n.push("3. Run `contractspec validate` to verify contracts"),n.push("4. Move stable contracts from `generated/` to `curated/`"),n.push(""),n.join(`
|
|
2427
|
+
`)}function D7($,b){let A=[];A.push(""),A.push("\uD83D\uDCCA Summary"),A.push(` Files scanned: ${$.stats.filesScanned}`),A.push(` Endpoints: ${$.stats.endpointsFound}`),A.push(` Schemas: ${$.stats.schemasFound}`),A.push(""),A.push("\uD83D\uDCC8 Confidence"),A.push(` High: ${$.stats.highConfidence}`),A.push(` Medium: ${$.stats.mediumConfidence}`),A.push(` Low: ${$.stats.lowConfidence}`),A.push(""),A.push("\uD83D\uDD27 Frameworks");for(let n of $.project.frameworks)A.push(` \u2022 ${n.name}`);if(A.push(""),b)A.push("\u2705 Verification"),A.push(` Valid: ${b.summary.validEndpoints}`),A.push(` Warnings: ${b.summary.warningEndpoints}`),A.push(` Errors: ${b.summary.errorEndpoints}`),A.push("");return A.join(`
|
|
2428
|
+
`)}async function N7($,b,A){let{logger:n}=A,m=[],y=[...$.ambiguities];n.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=F7(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 n.info(`Verification complete: ${W.validEndpoints} valid, ${W.warningEndpoints} warnings, ${W.errorEndpoints} errors`),{valid:W.errorEndpoints===0,endpointResults:m,ambiguities:y,summary:W}}function F7($,b){let A=[],n=$.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!==n.length)continue;let W=!0;for(let w=0;w<n.length;w++){let j=n[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)A.push(m)}return A}function ER($,b="feature-map",A={}){switch(b){case"feature-map":return rm($,A);case"orphans":return v7($,A);case"dependencies":return g7($,A);case"full":return P7($,A);default:return rm($,A)}}function rm($,b){let{direction:A="LR",showVersions:n=!0,maxNodes:m=50}=b,y=[`flowchart ${A}`],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}["${S$(Y)}"]`),w++}y.push(" end")}let B=Pm(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=n?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}let S=Pm(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=n?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}let Q=Pm(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=n?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}for(let Z of W){let X=v(`F_${Z.key}`);for(let Y of Z.operations){let H=v(`O_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${H}`)}for(let Y of Z.events){let H=v(`E_${Y.key}_v${Y.version}`);y.push(` ${X} -.-> ${H}`)}for(let Y of Z.presentations){let H=v(`P_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${H}`)}}if(j)y.push(` note["... and more (truncated at ${m} nodes)"]`);return y.join(`
|
|
2429
|
+
`)}function v7($,b){let{direction:A="TB",showVersions:n=!0,maxNodes:m=50}=b,y=[`flowchart ${A}`],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}["${S$(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=n?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${S$(X)}"]`),B++}y.push(" end")}let S=[];for(let Q of W){let[Z,X]=km(Q);if(Z&&X)S.push({type:"operation",key:Z,version:X})}for(let Q of w){let[Z,X]=km(Q);if(Z&&X)S.push({type:"event",key:Z,version:X})}for(let Q of j){let[Z,X]=km(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=n?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${S$(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(`
|
|
2430
|
+
`)}function g7($,b){let{direction:A="TB",showVersions:n=!0,maxNodes:m=50}=b,y=[`flowchart ${A}`],W=0;for(let w of $.features){if(W>=m)break;let j=v(`F_${w.key}`);y.push(` ${j}["${S$(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=n?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${S$(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=n?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${S$(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=n?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${S$(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(`
|
|
2431
|
+
`)}function P7($,b){let A=rm($,b);if($.orphanedSpecs.length===0)return A;let n=A.split(`
|
|
2432
|
+
`);n.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}`;n.push(` ${y}["${S$(W)}"]:::orphan`)}return n.push(" end"),n.push(" classDef orphan stroke-dasharray: 5 5"),n.join(`
|
|
2433
|
+
`)}function Pm($,b,A){let n=new Set,m=[];for(let y of $)for(let W of y[b]){let w=`${W.key}.v${W.version}`;if(!n.has(w))n.add(w),m.push(W)}return m}function km($){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 S$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as k7,specToMarkdown as D$}from"@contractspec/module.workspace";function DR($,b,A){let n=[];if(A.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))n.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))n.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(A.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))n.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))n.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))n.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return n}function NR($,b){let A=[];A.push(`# Verification Report: ${$.meta.key}`),A.push("");let n=b.filter((W)=>W.severity==="error"),m=b.filter((W)=>W.severity==="warning"),y=b.filter((W)=>W.severity==="info");if(A.push("## Summary"),A.push(""),A.push(`- Errors: ${n.length}`),A.push(`- Warnings: ${m.length}`),A.push(`- Info: ${y.length}`),A.push(""),n.length>0){A.push("## Errors"),A.push("");for(let W of n)A.push(`- \u274C **${W.category}**: ${W.message}`);A.push("")}if(m.length>0){A.push("## Warnings"),A.push("");for(let W of m)A.push(`- \u26A0\uFE0F **${W.category}**: ${W.message}`);A.push("")}if(y.length>0){A.push("## Info"),A.push("");for(let W of y)A.push(`- \u2139\uFE0F **${W.category}**: ${W.message}`);A.push("")}return A.join(`
|
|
2434
|
+
`)}async function PR($,b){let A=[];A.push(D$($,"context"));let n=await B$(b),m=async(y)=>{let W=n.find((j)=>j.key===y.name&&j.version===y.version);if(!W)return null;return(await k7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){A.push(`
|
|
2403
2435
|
## Operations (${$.operations.length})
|
|
2404
|
-
`);for(let y of $.operations){let W=await m(y);if(W)
|
|
2436
|
+
`);for(let y of $.operations){let W=await m(y);if(W)A.push(D$(W,"full"));else A.push(`### ${y.name} (v${y.version})
|
|
2405
2437
|
|
|
2406
|
-
*Spec not found*`);
|
|
2438
|
+
*Spec not found*`);A.push("---")}}if($.events?.length){A.push(`
|
|
2407
2439
|
## Events (${$.events.length})
|
|
2408
|
-
`);for(let y of $.events){let W=await m(y);if(W)
|
|
2440
|
+
`);for(let y of $.events){let W=await m(y);if(W)A.push(D$(W,"full"));else A.push(`### ${y.name} (v${y.version})
|
|
2409
2441
|
|
|
2410
|
-
*Spec not found*`);
|
|
2442
|
+
*Spec not found*`);A.push("---")}}if($.presentations?.length){A.push(`
|
|
2411
2443
|
## Presentations (${$.presentations.length})
|
|
2412
|
-
`);for(let y of $.presentations){let W=await m(y);if(W)
|
|
2413
|
-
|
|
2414
|
-
*Spec not found*`);
|
|
2415
|
-
`)}function
|
|
2416
|
-
`)}function
|
|
2417
|
-
`)}function
|
|
2418
|
-
`)}function
|
|
2419
|
-
`)}function
|
|
2420
|
-
`)}import{RegeneratorService as
|
|
2444
|
+
`);for(let y of $.presentations){let W=await m(y);if(W)A.push(D$(W,"full"));else A.push(`### ${y.name} (v${y.version})
|
|
2445
|
+
|
|
2446
|
+
*Spec not found*`);A.push("---")}}return A.join(`
|
|
2447
|
+
`)}function r7($,b){let A=[];if(A.push(`# Implementation Guide: ${$.meta.key}`),A.push(""),A.push(`**Target Agent**: ${b}`),A.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),A.push(""),$.meta.description)A.push("## Overview"),A.push(""),A.push($.meta.description),A.push("");if($.meta.goal)A.push("## Goal"),A.push(""),A.push($.meta.goal),A.push("");if($.meta.context)A.push("## Context"),A.push(""),A.push($.meta.context),A.push("");if(A.push("## Implementation Steps"),A.push(""),$.specType==="operation"){if(A.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)A.push("2. Implement input validation according to the schema"),A.push("3. Implement the core business logic"),A.push("4. Return output matching the expected schema");if($.hasPolicy)A.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){A.push("6. Emit events on success:");for(let n of $.emittedEvents)A.push(` - \`${n.name}\` (v${n.version})`)}A.push("7. Add error handling for expected failure cases"),A.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(A.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){A.push("2. Implement operations:");for(let n of $.operations)A.push(` - \`${n.name}\` (v${n.version})`)}if($.presentations&&$.presentations.length>0){A.push("3. Implement presentations:");for(let n of $.presentations)A.push(` - \`${n.name}\` (v${n.version})`)}A.push("4. Wire up feature exports"),A.push("5. Add integration tests")}else A.push("1. Review the spec requirements"),A.push("2. Implement the core logic"),A.push("3. Add tests"),A.push("4. Document the implementation");if(A.push(""),A.push("## Constraints"),A.push(""),A.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)A.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)A.push(`- Tags: ${$.meta.tags.join(", ")}`);if(A.push(""),b==="cursor-cli")A.push("## Cursor Notes"),A.push(""),A.push("- Use Composer mode for multi-file changes"),A.push("- Reference this guide in your cursor rules"),A.push("- Break implementation into small, focused commits");else if(b==="claude-code")A.push("## Claude Code Notes"),A.push(""),A.push("- Use extended thinking for complex logic"),A.push("- Ask for clarification on ambiguous requirements"),A.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")A.push("## General Notes"),A.push(""),A.push("- Use inline comments to guide generation"),A.push("- Review generated code carefully");return A.push(""),A.push("## Spec Definition"),A.push(""),A.push(D$($,"full")),A.join(`
|
|
2448
|
+
`)}function f7($){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(`
|
|
2449
|
+
`)}function kR($,b,A="generic-mcp"){switch(b){case"guide":return r7($,A);case"rules":return f7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as c7}from"fs/promises";import{createRequire as h7}from"module";import{dirname as d7,resolve as cj}from"path";import{pathToFileURL as u7}from"url";import fj from"vm";import fm from"typescript";async function W$($,b={}){let A=cj(process.cwd(),$),n=b.runtime??l7();try{let m=n==="bun"?await o7(A):await i7(A);return{modulePath:A,exports:m}}catch(m){throw Error(dj(A,m))}}async function lR($,b){let A=cj(process.cwd(),$);if(!await b.exists(A))return null;return W$(A)}async function U0($,b={}){return(await W$($,b)).exports}async function hj($,b){let A=await U0($);return uj(A,$,b)}function dj($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function uj($,b,A){if(A.isValue($))return $;for(let n of A.instanceKeys??[])if(A.isValue($[n]))return $[n];for(let n of A.factoryKeys??[]){let m=$[n];if(typeof m!=="function")continue;let y=await m();if(A.isValue(y))return y}throw Error(`${A.description} module ${b} must export a supported instance or factory.`)}async function o7($){return await import(u7($).href)}async function i7($){return await t7($)??{}}function l7(){return typeof globalThis.Bun<"u"?"bun":"node"}var tR={formatModuleLoadError:dj,resolveAuthoredModuleValue:uj};async function t7($){let b=await c7($,"utf-8"),A=fm.transpileModule(b,{compilerOptions:{module:fm.ModuleKind.CommonJS,target:fm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),n={},m={exports:n},y=h7($),W=fj.createContext({module:m,exports:n,require:y,__dirname:d7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new fj.Script(A.outputText,{filename:$}).runInContext(W),m.exports}var aj={};f(aj,{renderOnboardingGuides:()=>dm,listOnboardingTracks:()=>V0,getOnboardingTrack:()=>hm,createOnboardingConnectArtifacts:()=>WZ,buildOnboardingPlan:()=>yZ,ONBOARDING_TRACKS:()=>cm});var cm=[{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 V0(){return cm}function hm($){return cm.find((b)=>b.id===$)}function dm($){return{agentGuide:p7($),humanGuide:e7($)}}function p7($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let A of $.recommendations)b.push(...a7(A.track,A.reason));return b.join(`
|
|
2450
|
+
`)}function a7($,b){let A=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let n of $.recommendedCommands)A.push(`- \`${n}\``);return[...A,""]}function e7($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((A,n)=>`${n+1}. \`${A}\``),"","## Track Guide",""];for(let A of $.recommendations)b.push(...s7(A.track,A.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let A of $.builderNextSteps)b.push(`- \`${A}\``);b.push("")}return b.join(`
|
|
2451
|
+
`)}function s7($,b){let A=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)A.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(A.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)A.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);A.push("","Commands:");for(let n of $.recommendedCommands)A.push(`- \`${n}\``);return A.push("",`Packages: ${$.packages.map((n)=>`\`${n}\``).join(", ")}`,""),A}import{buildContext as $Z}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as bZ}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as AZ}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function oj($,b,A,n){let m=$Z({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:A,workspaceId:n}),y=await bZ(AZ(nZ(b)),m);return{journeyContext:m,journeyPlan:y}}function ij($){if(!$||$.length===0)return[...V0()];return $.map((b)=>{let A=hm(b);if(!A)throw Error(`Unknown onboarding track: ${b}`);return A})}function lj($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function tj($){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 pj($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let A of V0()){if(A.starterExample.key===b)return A.starterExample;if(A.advancedExample?.key===b)return A.advancedExample}return}function um($,b){return mZ($,b.flatMap((A)=>A.track.connectSurfaces))}function nZ($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((A)=>({defaultSurface:A.id,path:`/onboard/${A.id}`,routeId:`onboard-${A.id}`})),surfaces:Object.fromEntries($.map((A)=>[A.id,{commands:A.recommendedCommands.map((n,m)=>({commandId:`${A.id}-${m}`,intent:`Run ${n}`,title:n})),data:[{hydrateInto:"track",recipeId:`track-${A.id}`,source:{entityType:`onboarding.${A.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${A.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:A.id,title:A.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function mZ($,b){return[...new Set([...$,...b])].sort()}async function yZ($,b={}){let A=await $b($.fs,b),n=ij(b.selectedTracks),m=lj(A.config),W=[...await Promise.all(n.map(async(Y)=>{let H=await Vb($,{config:A.config,cwd:A.cwd,family:Y.reuseFamily,packageRoot:A.packageRoot,platform:Y.adoptionPlatform,query:Y.adoptionQuery,workspaceRoot:A.workspaceRoot});return{reason:H.reason,resolution:H,score:H.selected?.score??0,selected:!1,track:Y}}))].sort((Y,H)=>H.score-Y.score).map((Y,H)=>({...Y,selected:H===0})),w=W[0]?.track;if(!w)throw Error("No onboarding tracks are available.");let{journeyContext:j,journeyPlan:B}=await oj(w,n,A.workspaceRoot,A.packageRoot),S=pj(w,b.forcedExampleKey)??w.starterExample,Q=wZ(["contractspec onboard",...w.recommendedCommands,"contractspec doctor"]),Z=tj(m),X={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:m,builderNextSteps:Z,config:A.config,cwd:A.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:j,journeyPlan:B,nextCommands:Q,packageRoot:A.packageRoot,primaryTrack:w,recommendations:W,selectedExample:S,workspaceRoot:A.workspaceRoot};return{...X,guides:dm(X)}}async function WZ($,b){if(!b.config.connect?.enabled)return;let A=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,n=[b.agentGuidePath,b.humanGuidePath],m=await hb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:n,taskId:A,workspaceRoot:b.workspaceRoot}),y=await lb($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((W)=>W.track.id).join(", ")}`,steps:b.recommendations.map((W)=>({commands:W.track.recommendedCommands,paths:n,summary:`Adopt ${W.track.title}`})),touchedPaths:n},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:n,taskId:A,workspaceRoot:b.workspaceRoot});return{contextPack:{...m,affectedSurfaces:um(m.affectedSurfaces,b.recommendations)},planPacket:{...y.planPacket,affectedSurfaces:um(y.planPacket.affectedSurfaces,b.recommendations)}}}function wZ($){return[...new Set($)]}var ej=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],jZ=[...ej,{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 om($){return $==="minimal"?ej:jZ}function im($){return $.filter((b)=>!b.dev)}function lm($){return $.filter((b)=>b.dev)}import{exec as BZ}from"child_process";import{promisify as SZ}from"util";var QZ=SZ(BZ),ZZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function OI($,b,A=ZZ){let n=om(b.mode),m=im(n),y=lm(n),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=e$(b.workspaceRoot),H=m.filter((U)=>{if(X.has(U.name)&&!b.force)return w.push({name:U.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),J=y.filter((U)=>{if(X.has(U.name)&&!b.force)return w.push({name:U.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let U=[...H,...J];return{success:!0,installed:U.map((K)=>({name:K.name,action:"installed",message:`Would install: ${K.description}`,dev:K.dev})),skipped:w,errors:[],summary:`Dry run: would install ${U.length} package(s), skip ${w.length}.`}}if(!b.skipPrompts&&(H.length>0||J.length>0)){let U=H.length+J.length;if(!await A.confirm(`Install ${U} package(s) using ${Y}?`))return{success:!0,installed:[],skipped:[...w,...H.map((q)=>({name:q.name,action:"skipped",message:"User cancelled"})),...J.map((q)=>({name:q.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(H.length>0){let U=await sj(H,Y,b.workspaceRoot,!1);for(let K of U)if(K.action==="installed")W.push(K);else j.push(K)}if(J.length>0){let U=await sj(J,Y,b.workspaceRoot,!0);for(let K of U)if(K.action==="installed")W.push(K);else j.push(K)}let O=j.length===0,V=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:V}}async function sj($,b,A,n){let m=[],y=$.map((W)=>W.version?`${W.name}@${W.version}`:W.name);try{let w=`${dy(b,n)} ${y.join(" ")}`;await QZ(w,{cwd:A,timeout:120000});for(let j of $)m.push({name:j.name,action:"installed",message:j.description,dev:n})}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:n})}return m}async function JI($,b){let A=$.join(b,"package.json");try{let n=await $.readFile(A),m=JSON.parse(n);return"@contractspec/lib.contracts-spec"in{...m.dependencies,...m.devDependencies}}catch{return!1}}function UI($){let b=om($),A=[];A.push(`ContractSpec ${$} installation:`),A.push("");let n=im(b);if(n.length>0){A.push("Dependencies:");for(let y of n)A.push(` \u2022 ${y.name} - ${y.description}`)}let m=lm(b);if(m.length>0){A.push(""),A.push("Dev Dependencies:");for(let y of m)A.push(` \u2022 ${y.name} - ${y.description}`)}return A.join(`
|
|
2452
|
+
`)}import{RegeneratorService as XZ}from"@contractspec/lib.contracts-spec/regenerator";function II($){return new XZ({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class K0{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,A;try{A=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(n){throw Error(`Registry request failed: ${b} (${n instanceof Error?n.message:String(n)})`)}if(!A.ok){let n=await A.text().catch(()=>"");throw Error(`Registry request failed: ${A.status} ${A.statusText} ${n}`)}return await A.json()}}function tm($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function xI($,b,A){let{logger:n}=A,m=tm(b.registryUrl);n.info(`Adding spec to registry: ${$}`,{registryUrl:m}),await new K0({registryUrl:m}).getJson(`/specs/add?path=${encodeURIComponent($)}`),n.info("Spec added to registry successfully")}async function MI($,b){let{logger:A}=b,n=tm($.registryUrl);A.info("Listing specs from registry",{registryUrl:n});let m=new K0({registryUrl:n}),y=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",W=await m.getJson(`/specs${y}`);return A.info(`Found ${W.length} specs`),W}async function EI($,b,A){let{logger:n}=A,m=tm(b.registryUrl);n.info(`Searching registry: ${$}`,{registryUrl:m});let W=await new K0({registryUrl:m}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return n.info(`Found ${W.length} results`),W}class YZ{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:A}=$,n=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${n.join(", ")}...`);try{let m=this.fs.join(A,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 n){let B=this.getTargetFileName(j);if(B){let S=this.fs.join(A,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}=$,A={rules:(b.rules??[]).map((n)=>this.fs.join(b.rulesDir??".rules",n)),targets:$.targets||b.targets};return JSON.stringify(A,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}function _0($,b,A,n){let m=AA(b,A),y=HZ(A);if(y.test($))return $.replace(y,m);if(n&&pm($)===pm(n))return m;return`${m}${$}`}function AA($,b){let A=pm($);return`${b.startMarker}
|
|
2421
2453
|
${b.note}
|
|
2422
|
-
${
|
|
2454
|
+
${A}
|
|
2423
2455
|
${b.endMarker}
|
|
2424
|
-
`}function
|
|
2425
|
-
`).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,bn(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=Tb();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,bn(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 $x($,b,n=YZ,A={}){let m=[],y=b.targets.length>0?b.targets:Ib,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??Mb(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",q=Q!==S;if(Z&&b.interactive&&q)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:",Ib.map((g)=>({value:g,label:sW[g],selected:H.includes(g)})));let O=U.projectName;if(b.interactive&&!O){let g=V==="package"&&X?X:K.split("/").pop()??"my-project";O=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:O,targets:H,builderApiBaseUrl:_,builderLocalRuntimeId:z,builderLocalGrantedTo:L};for(let g of H){let iA=await OZ($,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 OZ($,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 qZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as VZ}from"path";async function Gx($,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=qZ(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 nn}from"path";async function Vx($,b,n,A,m){let{fs:y}=m,W=A.implementationPath;if(!W){let S=my($),Q=KZ($,".ts"),Z=[nn(S,Q.replace(".contracts",".handler")+".ts"),nn(S,Q.replace(".presentation","")+".tsx"),nn(S,Q.replace(".form",".form")+".tsx"),nn(my(S),"handlers",Q.replace(".contracts",".handler")+".ts"),nn(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 Vn(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 Lx($,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 Dx($,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 Nx($,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 rx($,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 ax($,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=`
|
|
2456
|
+
`}function pm($){return $.replace(/\r\n/g,`
|
|
2457
|
+
`).trimEnd()}function HZ($){return new RegExp(`${$1($.startMarker)}[\\s\\S]*?${$1($.endMarker)}(?:\\r?\\n)?`)}function $1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var GZ="<!-- contractspec:init:agents:start -->",qZ="<!-- contractspec:init:agents:end -->",OZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",b1={endMarker:qZ,note:OZ,startMarker:GZ};async function am($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,"AGENTS.md");try{let y=await $.exists(m),W=Yw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await A.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,_0(w,W,b1,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,AA(W,b1)),{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 JZ,generateBiomePreset as UZ}from"@contractspec/biome-config";async function em($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,"biome.jsonc"),y=$.join(n,".contractspec","biome"),W=$.join(y,"plugins"),w=$.join(y,"ai"),j=JZ("consumer");try{let B=await $.exists(m);if(B&&b.interactive){if(!await A.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,UZ("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 sm($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,".contractsrc.json");try{let y=await $.exists(m),W=jb(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 A.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=A$(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,F(Dn(B,S)))}else await $.writeFile(m,F(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,F(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 $y($,b,A){let n=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(n,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(n))await $.mkdir(n);let W=await $.exists(m),w=Xw(b);if(W)if(b.interactive){if(!await A.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 by($,b,A){let n=lA();try{let m=await $.exists(n),y=Zw();if(b.interactive){if(!await A.confirm(`Configure Claude Desktop at ${n}?`))return{target:"mcp-claude",filePath:n,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(n),B=a(j);if(!B)return{target:"mcp-claude",filePath:n,action:"error",message:"Existing file is not valid JSON"};let S=A$(B,y);return await $.writeFile(n,F(S)),{target:"mcp-claude",filePath:n,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=n.substring(0,n.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(n,F(y)),{target:"mcp-claude",filePath:n,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:n,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function Ay($,b,A){let n=$.join(b.workspaceRoot,".cursor"),m=$.join(n,"mcp.json");try{if(!await $.exists(n))await $.mkdir(n);let W=await $.exists(m),w=Db();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 A.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=A$(B,w);return await $.writeFile(m,F(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,F(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 VZ="<!-- contractspec:init:usage:start -->",KZ="<!-- contractspec:init:usage:end -->",_Z="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",A1={endMarker:KZ,note:_Z,startMarker:VZ};async function ny($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,"USAGE.md");try{let y=await $.exists(m),W=Hw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await A.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,_0(w,W,A1,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,AA(W,A1)),{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 my($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=iA(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 A.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=A$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,F(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,F(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 zZ={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??""},LZ={"agents-md":am,"biome-config":em,"cli-config":sm,"cursor-rules":$y,"mcp-claude":by,"mcp-cursor":Ay,"usage-md":ny,"vscode-settings":my},RZ={findWorkspaceRoot:x,findPackageRoot:c,isMonorepo:Ub,getPackageName:P$};async function OC($,b,A=zZ,n={}){let m=[],y=b.targets.length>0?b.targets:Mb,W={...RZ,...n.workspace},w={...LZ,...n.targets},j=n.setupGitignore??Q0,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 n1($,[Q,S]),H=b.preset??Tb(Y);if(b.interactive&&!b.preset)H=await A.select("Select initialization preset:",yw.map((g)=>({value:g,label:Ww[g],description:ww[g],selected:g===H})));let J=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)J=await A.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 V=Z&&J==="package"?Q:S,U=await n1($,[V]),K={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:J,packageName:X,preset:H,builderApiBaseUrl:b.builderApiBaseUrl??U?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??U?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??U?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??U?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??U?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??U?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??U?.connect?.studio?.queue},q=jw(H,y);if(b.interactive)q=await A.multiSelect("Select components to configure:",Mb.map((g)=>({value:g,label:mw[g],selected:q.includes(g)})));let G=K.projectName;if(b.interactive&&!G){let g=J==="package"&&X?X:V.split("/").pop()??"my-project";G=await A.input("Project name:",g)}let z=K.builderApiBaseUrl;if(b.interactive&&H.startsWith("builder-"))z=await A.input("Builder API base URL:",z??"https://api.contractspec.io");let{builderLocalRuntimeId:_,builderLocalGrantedTo:L}=K;if(b.interactive&&(H==="builder-local"||H==="builder-hybrid"))_=await A.input("Default local runtime target id:",_??"rt_local_daemon"),L=await A.input("Default local runtime grant target:",L??"local:operator");let I={...K,projectName:G,targets:q,builderApiBaseUrl:z,builderLocalRuntimeId:_,builderLocalGrantedTo:L};for(let g of q){let o0=await IZ($,g,I,A,w);m.push(o0)}let E=await j($,{behavior:I.gitignoreBehavior,interactive:I.interactive,patterns:Qw({preset:H}),prompts:A,root:S});if(I.gitignoreBehavior!=="skip"||E.action!=="skipped")m.push(E);let N=m.filter((g)=>g.action!=="error").length,M=m.filter((g)=>g.action==="error").length,r=Z?` (${J} level)`:"";return{success:M===0,preset:H,files:m,summary:`Setup complete${r}: ${N} configured, ${M} failed.`,nextSteps:Sw(I)}}async function IZ($,b,A,n,m){let y=m[b];if(y)return y($,A,n);return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}async function n1($,b){for(let A of b){let n=$.join(A,".contractsrc.json");if(!await $.exists(n))continue;let m=a(await $.readFile(n));if(m)return m}return null}import{validateBlueprint as CZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as xZ}from"path";async function DC($,b){let{fs:A}=b,n=xZ(process.cwd(),$);if(!await A.exists(n))return{valid:!1,errors:[`Blueprint file not found: ${n}`]};try{let m=await W$(n),y=MZ(m.exports),W=CZ(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 MZ($){let b=Object.values($).filter(EZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function EZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as TZ,dirname as yy,join as nA}from"path";async function gC($,b,A,n,m){let{fs:y}=m,W=n.implementationPath;if(!W){let S=yy($),Q=TZ($,".ts"),Z=[nA(S,Q.replace(".contracts",".handler")+".ts"),nA(S,Q.replace(".presentation","")+".tsx"),nA(S,Q.replace(".form",".form")+".tsx"),nA(yy(S),"handlers",Q.replace(".contracts",".handler")+".ts"),nA(yy(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 UA(A).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as DZ,validateBuilderReadinessReport as NZ,validateBuilderWorkspace as FZ,validateBuilderWorkspaceSnapshot as vZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as gZ,validateExternalPatchProposal as PZ,validateProviderRoutingPolicy as kZ,validateRuntimeTarget as rZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as fZ,validateLayoutSlots as cZ}from"@contractspec/lib.surface-runtime/spec";async function hC($,b){if(!iZ($.specType))return{valid:!0,errors:[],warnings:[]};let A=n2($.filePath),n=[`${A}/package.json`,`${A}/README.md`,`${A}/src/index.ts`,$.filePath],m=[];for(let w of n)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 W$($.filePath)).exports}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)],warnings:[]}}let W=$.specType==="module-bundle"?hZ(y):$.specType==="builder-spec"?dZ(y):uZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function hZ($){let b=[],A=[],n=oZ($,lZ);if(n.length===0)return A.push(Wy("module-bundle","bundle")),{errors:b,warnings:A};for(let m of n){let y=Object.values(m.value.surfaces);for(let W of y){try{cZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of fZ(W).warnings)A.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:A}}function dZ($){let b=[],A=[],n=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(tZ(y)){n+=1,b.push(...z0(m,FZ(y)));continue}if(pZ(y)){n+=1,b.push(...z0(m,DZ(y)));continue}if(aZ(y)){n+=1,b.push(...z0(m,NZ(y)));continue}if(eZ(y))n+=1,b.push(...z0(m,vZ(y)))}if(n===0)A.push(Wy("builder-spec","builder"));return{errors:b,warnings:A}}function uZ($){let b=[],A=[],n=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(sZ(y)){n+=1,b.push(...L0(m,rZ(y)));continue}if($2(y)){n+=1,b.push(...L0(m,kZ(y)));continue}if(b2(y)){n+=1,b.push(...L0(m,gZ(y)));continue}if(A2(y))n+=1,b.push(...L0(m,PZ(y)))}if(n===0)A.push(Wy("provider-spec","provider"));return{errors:b,warnings:A}}function oZ($,b){return Object.entries($).filter(([A,n])=>A!=="__esModule"&&b(n)).map(([A,n])=>({exportName:A,value:n}))}function z0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function L0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function iZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function lZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function tZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function pZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function aZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function eZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function sZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function $2($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function b2($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function A2($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function n2($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Wy($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as m2}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as y2}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as W2}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as w2}from"@contractspec/module.workspace";async function y1($,b={}){let A=[],n=[],m;if(!b.skipStructure){m=w2($),A.push(...m.errors),n.push(...m.warnings);let y=await j2($);A.push(...y.errors),n.push(...y.warnings)}return{valid:A.length===0,structureResult:m,errors:A,warnings:n,code:$.sourceBlock}}async function aC($,b={}){return Promise.all($.map(async(A)=>({spec:A,...await y1(A,b)})))}async function p$($,b,A={}){let{fs:n}=b;if(!await n.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let y=await n.readFile($),W=[],w=[],j=void 0;if(!A.skipStructure){let B=await B$(b,{pattern:$});for(let S of B){let Q=await y1(S,A);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 eC($,b,A={}){let n=new Map;for(let m of $){let y=await p$(m,b,A);n.set(m,y)}return n}async function j2($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await W$($.filePath);if($.specType==="app-config"){let m=B2(b.exports,$),y=m2(m);return{errors:y.errors.map((W)=>m1(W)),warnings:[...y.warnings,...y.info].map((W)=>m1(W))}}if($.specType==="feature"){let m=S2(b.exports,$),y=y2(m);return{errors:y.issues.filter((W)=>W.level==="error").map((W)=>R0(W)),warnings:y.issues.filter((W)=>W.level!=="error").map((W)=>R0(W))}}let A=Q2(b.exports,$),n=W2(A);return{errors:n.issues.filter((m)=>m.level==="error").map((m)=>R0(m)),warnings:n.issues.filter((m)=>m.level!=="error").map((m)=>R0(m))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function B2($,b){return wy($,b.exportName,Z2)}function S2($,b){return wy($,b.exportName,X2)}function Q2($,b){return wy($,b.exportName,Y2)}function wy($,b,A){if(b&&A($[b]))return $[b];let n=Object.values($).find(A);if(!n)throw Error("Expected authored module to export a compatible spec value.");return n}function Z2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function X2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function Y2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function m1($){let b=$.code?`[${$.code}] `:"",A=$.path?`${$.path}: `:"";return`${b}${A}${$.message}`}function R0($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as H2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as By}from"fs/promises";import{resolve as I0}from"path";async function mx($,b,A,n){let{fs:m}=n,y=I0(process.cwd(),b);if(!await m.exists(y))return{valid:!1,errors:[`Tenant config file not found: ${y}`]};try{let W=await G2(y),w=await q2(A.connections,m),j=await O2(A.translationCatalog,m),B=await J2(A.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=H2($,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 G2($){if($.endsWith(".json")){let n=await By($,"utf-8"),m=JSON.parse(n);if(!W1(m))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return m}let b=await W$($),A=Object.values(b.exports).filter(W1);if(A.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return A[0]}function W1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function S1($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((A)=>A.trim()).filter(Boolean)}async function q2($,b){let A=S1($);if(!A.length)return[];let n=[];for(let m of A){let y=I0(process.cwd(),m);if(!await b.exists(y)){console.warn(`Warning: Connection file not found: ${y}`);continue}if(y.endsWith(".json")){let w=await By(y,"utf-8"),j=JSON.parse(w);n.push(...jy(j));continue}let W=await W$(y);n.push(...jy(W.exports))}return n}function jy($){if(Array.isArray($)){let b=$.filter(w1);if(b.length)return b}if(w1($))return[$];if($&&typeof $==="object"){let A=Object.values($).flatMap((n)=>jy(n));if(A.length)return A}return[]}function w1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function O2($,b){if(!$)return;let A=I0(process.cwd(),$);if(!await b.exists(A))return;if(A.endsWith(".json")){let y=await By(A,"utf-8"),W=JSON.parse(y);if(j1(W))return B1(W);return}let n=await W$(A),m=Object.values(n.exports).filter(j1);if(m.length===0)return;return B1(m[0])}function j1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function B1($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function J2($){let b=S1($);if(!b.length)return;let{IntegrationSpecRegistry:A}=await import("@contractspec/lib.contracts-integrations"),n=new A;for(let m of b){let{modulePath:y,exportName:W}=U2(m);if(!y)continue;let w=I0(process.cwd(),y);try{let j=await W$(w),B=V2(j.exports,W);if(B)await B(n)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return n}function U2($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),n=b?.trim()??null,m=A?.trim();return{modulePath:n,exportName:m}}function V2($,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 Hx($,b,A={},n){let{fs:m,logger:y}=$,W=await m.glob({pattern:A.pattern}),w=A.outputDirs?.length?A.outputDirs:[void 0],j=[],B=n?.validate??((Q)=>p$(Q,{fs:m,logger:y})),S=n?.build??((Q,Z)=>wb(Q,{fs:m,logger:y},Z?{...b,outputDir:Z}:b,{...A.buildOptions??{},outputDir:Z}));for(let Q of W)for(let Z of w){let X={specPath:Q,outputDir:Z};if(A.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(!A.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 K2}from"ai";var _2=`
|
|
2426
2458
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2427
2459
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2428
2460
|
|
|
@@ -2440,7 +2472,7 @@ Generate scenarios covering:
|
|
|
2440
2472
|
- Happy path (valid input, successful execution)
|
|
2441
2473
|
- Edge cases (boundary values, optional fields)
|
|
2442
2474
|
- Error cases (invalid input, business rule violations)
|
|
2443
|
-
`.trim();class
|
|
2475
|
+
`.trim();class z2{logger;defaultModel;generateTextImpl;constructor($,b,A=K2){this.logger=$;this.defaultModel=b;this.generateTextImpl=A}async generateTests($,b={}){let A=b.model??this.defaultModel;if(!A)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let n=`
|
|
2444
2476
|
Generate a TestSpec for the following Operation:
|
|
2445
2477
|
|
|
2446
2478
|
\`\`\`json
|
|
@@ -2449,23 +2481,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2449
2481
|
|
|
2450
2482
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2451
2483
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2452
|
-
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:
|
|
2453
|
-
`)}function
|
|
2454
|
-
`)}function
|
|
2455
|
-
`);for(let
|
|
2456
|
-
`)}function
|
|
2484
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:A,system:_2,prompt:n});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 A={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},n={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:A,target:n,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 Q1}from"@contractspec/lib.contracts-spec";import{TestRunner as Z1}from"@contractspec/lib.contracts-spec/tests";import{resolve as Sy}from"path";async function _x($,b){let A=new Z1({registry:b}),n=[],m=0,y=0;for(let W of $){let w=await A.run(W);n.push(w),m+=w.passed,y+=w.failed}return{results:n,passed:m,failed:y}}async function zx($,b,A){let{logger:n}=A,m;if(b.registry)m=await R2(Sy(b.registry));else m=new Q1,n.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let y=new Z1({registry:m}),W=[],w=!0;for(let j of $)try{let B=Sy(j),S=await U0(B),Q=X1(S);if(Q.length===0){n.warn(`No TestSpec exports found in ${j}`);continue}for(let Z of Q){n.info(`Running ${Z.meta.key}...`);let X=await y.run(Z);if(W.push(X),X.failed>0)w=!1,n.error(`${Z.meta.key} failed (${X.failed}/${X.scenarios.length})`);else n.info(`${Z.meta.key} passed (${X.passed}/${X.scenarios.length})`)}}catch(B){n.error(`Failed to load/run spec ${j}: ${B instanceof Error?B.message:String(B)}`),w=!1}return{results:W,passed:w}}async function Lx($,b){let A=[];for(let n of $)try{let m=Sy(n),y=await U0(m),W=X1(y);A.push(...W)}catch(m){b.logger.warn(`Failed to load tests from ${n}: ${m instanceof Error?m.message:String(m)}`)}return A}function X1($){let b=[];for(let A of Object.values($))if(L2(A))b.push(A);return b}function L2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function R2($){return hj($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof Q1,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as mA}from"@contractspec/module.workspace";import{IndentationText as I2,Node as Hb,Project as C2,QuoteKind as x2,SyntaxKind as M2}from"ts-morph";function E2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Dx($,b,A={}){let{fs:n,logger:m}=b;if(!await n.exists($))return{specPath:$,specInfo:E2($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let W=await n.readFile($),w;if(A.content!==void 0)w=A.content;else if(A.fields?.length)w=T2(W,A.fields);else return{specPath:$,specInfo:mA(W,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!A.skipValidation){await n.writeFile($,w);let j=await p$($,b);if(j.errors.length>0)return await n.writeFile($,W),{specPath:$,specInfo:mA(w,$),updated:!1,errors:j.errors,warnings:j.warnings};if(j.warnings.length>0&&!A.allowWarnings)return await n.writeFile($,W),{specPath:$,specInfo:mA(w,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:j.warnings};return m.info(`Updated spec: ${$}`),{specPath:$,specInfo:mA(w,$),updated:!0,errors:[],warnings:j.warnings}}return await n.writeFile($,w),m.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:mA(w,$),updated:!0,errors:[],warnings:[]}}function T2($,b){let n=new C2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:I2.TwoSpaces,quoteKind:x2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=N2(n);if(!m)return $;for(let y of b)D2(m,y);return n.getFullText()}function D2($,b){let A=b.key.split(".").map((w)=>w.trim()).filter(Boolean);if(A.length===0)return;let n=$;for(let w of A.slice(0,-1)){if(!n.getProperty(w))n.addPropertyAssignment({name:w,initializer:"{}"});let B=n.getPropertyOrThrow(w);if(!Hb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!Hb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(M2.ObjectLiteralExpression);if(!Q)return;n=Q}let m=A[A.length-1];if(!m)return;let y=F2(b.value),W=n.getProperty(m);if(W&&Hb.isPropertyAssignment(W)){W.setInitializer(y);return}n.addPropertyAssignment({name:m,initializer:y})}function N2($){for(let b of $.getVariableDeclarations()){let A=b.getInitializer();if(!A)continue;if(Hb.isObjectLiteralExpression(A))return A;if(Hb.isCallExpression(A)){let n=A.getArguments()[0];if(n&&Hb.isObjectLiteralExpression(n))return n}}return}function F2($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var x1={};f(x1,{getPackageUpgradeCommand:()=>_1,getDefaultVersioningConfig:()=>x0,getDefaultHooksConfig:()=>M0,applyGuidedUpgrade:()=>C1,applyConfigUpgrades:()=>K1,analyzeUpgrades:()=>C0,analyzeGuidedUpgrade:()=>Yy});import{GeneratedReleaseManifestSchema as R1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as d2,DEFAULT_CONTRACTSRC as u2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function Y1($){return $.packages.map((b)=>{let A=b.version?`@${b.version}`:"";return`- ${b.name}${A} (${b.releaseType})`})}function H1($){return $.map((b)=>` - ${b}`)}function Qy($,b){return $.audiences.filter((A)=>b.includes(A.kind)).map((A)=>`- ${v2(A.kind)}: ${A.summary}`)}function G1($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...Y1($),...Qy($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));return b.join(`
|
|
2485
|
+
`)}function q1($){let b=[`### ${$.summary}`,...Y1($),...Qy($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`);return b.join(`
|
|
2486
|
+
`)}function O1($){let b=[`### ${$.summary}`,...Qy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2487
|
+
`);for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`),b.push(...H1(A.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let A of $.upgradeSteps)b.push(` - [${A.level}] ${A.title}: ${A.summary}`),b.push(...A.instructions.map((n)=>` - ${n}`))}return b.join(`
|
|
2488
|
+
`)}function Zy($){return["# Patch Notes","",...$.releases.map(G1)].join(`
|
|
2457
2489
|
|
|
2458
|
-
`)}function
|
|
2490
|
+
`)}function Xy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[q1(b),"",O1(b)])].join(`
|
|
2459
2491
|
|
|
2460
|
-
`)}function
|
|
2492
|
+
`)}function J1($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...H1(b.instructions)].join(`
|
|
2461
2493
|
`)).join(`
|
|
2462
|
-
`)}function
|
|
2463
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2464
|
-
`)}function
|
|
2465
|
-
`),
|
|
2466
|
-
`),!0}async function
|
|
2467
|
-
`),!0}async function
|
|
2468
|
-
`),m="info";for(let j of
|
|
2494
|
+
`)}function Gb($,b){let A=b.targetPackages.map((n)=>`${n.name}: ${n.currentVersion??"unknown"} -> ${n.targetVersion??"latest"}`).join(`
|
|
2495
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",A||"- No package version targets were inferred.","","Required steps:",J1(b)].join(`
|
|
2496
|
+
`)}function v2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as V1,countUpgradePlanStepLevels as g2,createAgentPromptBundles as P2,dedupeUpgradePlanSteps as k2,sortReleaseManifest as U1}from"@contractspec/lib.contracts-spec";function r2($,b){if(b.length===0)return U1($);let A=new Map(b.map((n)=>[n.name,n.currentVersion??"0.0.0"]));return U1({...$,releases:$.releases.filter((n)=>n.packages.some((m)=>{let y=A.get(m.name);if(!y||!m.version)return!1;return V1(m.version,y)===1}))})}function yA($,b,A,n){let m=r2($,b),y=f2(m,b),W=k2(m.flatMap((S)=>S.upgradeSteps)),w=g2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=P2(j,A,n);return{...j,agentPrompts:B}}function f2($,b){let A=new Map(b.map((m)=>[m.name,m.currentVersion])),n=new Map;for(let m of $)for(let y of m.packages){let W=A.get(y.name),w=n.get(y.name);if(!w){n.set(y.name,{name:y.name,currentVersion:W,targetVersion:y.version});continue}if(y.version&&w.targetVersion&&V1(y.version,w.targetVersion)===1)w.targetVersion=y.version}return Array.from(n.values()).sort((m,y)=>m.name.localeCompare(y.name))}async function C0($,b){let{fs:A,logger:n}=$,m=c(b.workspaceRoot),y=x(b.workspaceRoot),W=e$(y);n.info("Analyzing available upgrades...",{workspaceRoot:y,packageRoot:m,packageManager:W});let w=await c2(A,m),j=await h2(A,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function c2($,b){let A=$.join(b,"package.json");if(!await $.exists(A))return[];try{let n=await $.readFile(A),m=JSON.parse(n),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 h2($,b,A){let n=$.join(b,".contractsrc.json"),m=xb({configRoot:b,workspaceRoot:A});if(!await $.exists(n))return[];try{let y=await $.readFile(n),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:x0(),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:M0(),isNew:!0});if(!W.release)w.push({key:"release",currentValue:void 0,suggestedValue:z1(),isNew:!0});if(!W.upgrade)w.push({key:"upgrade",currentValue:void 0,suggestedValue:L1(),isNew:!0});return w}catch{return[]}}async function K1($,b){let{fs:A,logger:n}=$,m=c(b.workspaceRoot),y=x(b.workspaceRoot),W=xb({configRoot:m,workspaceRoot:y});if(b.dryRun)n.info("Dry run - no changes will be made");let w=A.join(m,".contractsrc.json");if(!await A.exists(w))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let j=await A.readFile(w),B=JSON.parse(j),S=0,Q=B.$schema;if(!Q||Q!==W)B.$schema=W,S++;if(!B.versioning)B.versioning=x0(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=M0(),S++;if(!B.release)B.release=z1(),S++;if(!B.upgrade)B.upgrade=L1(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await A.writeFile(w,JSON.stringify(B,null,2)+`
|
|
2497
|
+
`),n.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 _1($,b,A){let n=A?b.map((m)=>`${m.name}@latest`).join(" "):b.map((m)=>m.name).join(" ");switch($){case"bun":return`bun add ${n}`;case"pnpm":return`pnpm add ${n}`;case"yarn":return`yarn add ${n}`;default:return`npm install ${n}`}}function x0(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function M0(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function z1(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function L1(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var o2="**/*.{ts,tsx,js,jsx,mjs,cjs}",I1=u2.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Yy($,b){let{fs:A}=$,n=c(b.workspaceRoot),m=x(b.workspaceRoot),y=await l2(A,n,m),W=await i2(A,n,m,b.manifestPaths??y.manifestPaths),w=await C0($,{workspaceRoot:n,dryRun:b.dryRun}),j=[b.agentTarget??y.defaultAgentTarget??"codex"],B=yA(W.manifest,w.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),j,Gb),S=t2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:p2(S)}}async function C1($,b){let{fs:A,logger:n}=$,m=c(b.workspaceRoot),y=await Yy($,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 a2(A,m,B))W.push(B.id)}n.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 i2($,b,A,n){let m=n??["generated/releases/upgrade-manifest.json"],y=Array.from(new Set([b,A]));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=R1.parse(JSON.parse(await $.readFile(j)));return{path:j,manifest:B}}}return{manifest:R1.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function l2($,b,A){for(let n of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(A,".contractsrc.json")]))){if(!await $.exists(n))continue;try{let m=JSON.parse(await $.readFile(n)),y=d2.safeParse(m);if(y.success)return{...I1,...y.data.upgrade}}catch{continue}}return I1}function t2($,b,A){let n=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;n.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=A.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),y=[];if(n.length>0)y.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:n.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:n.map((S)=>S.packageName??""),autofixes:n});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:yA({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),Gb).agentPrompts}}function p2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function a2($,b,A){switch(A.kind){case"package-json":return e2($,b,A);case"contractsrc":return s2($,b,A);case"import-rewrite":return $X($,b,A);case"codemod":return!1}}async function e2($,b,A){let n=$.join(b,"package.json");if(!await $.exists(n))return!1;let m=JSON.parse(await $.readFile(n)),y=A.dependencyType??"dependencies",W=m[y]??{};if(!A.packageName||!A.to||!W[A.packageName])return!1;return W[A.packageName]=A.to,m[y]=W,await $.writeFile(n,JSON.stringify(m,null,2)+`
|
|
2498
|
+
`),!0}async function s2($,b,A){let n=$.join(b,".contractsrc.json"),m=await $.exists(n)?JSON.parse(await $.readFile(n)):{};if(!A.configPath)return!1;return bX(m,A.configPath,A.value),await $.writeFile(n,JSON.stringify(m,null,2)+`
|
|
2499
|
+
`),!0}async function $X($,b,A){if(!A.from||!A.to)return!1;let n=await $.glob({pattern:A.path??o2,cwd:b,absolute:!0}),m=!1;for(let y of n){let W=await $.readFile(y);if(!W.includes(A.from))continue;await $.writeFile(y,W.split(A.from).join(A.to)),m=!0}return m}function bX($,b,A){let n=b.split("."),m=$;for(let W of n.slice(0,-1)){let w=m[W];if(!w||typeof w!=="object"||Array.isArray(w))m[W]={};m=m[W]}let y=n.at(-1);if(y)m[y]=A}import{existsSync as Hy,mkdirSync as AX,readFileSync as nX,renameSync as mX,statSync as yX,writeFileSync as WX}from"fs";import{dirname as wX,join as jX}from"path";var BX=".contractspec/verification-cache.json",M1=1;class E1{filePath;cache;isDirty=!1;constructor($,b){let A=b??process.cwd();this.filePath=$??jX(A,BX),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Hy(this.filePath))return;let $=nX(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==M1)return;for(let[A,n]of Object.entries(b.entries))this.cache.set(A,n)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=wX(this.filePath);if(!Hy($))AX($,{recursive:!0});let b={version:M1,entries:Object.fromEntries(this.cache.entries())},A=`${this.filePath}.tmp`;WX(A,JSON.stringify(b,null,2),"utf-8"),mX(A,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(Hy(this.filePath))$=yX(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function sx($,b){return new E1($,b)}class T1{cache=new Map;async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[b,A]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(A).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function bM(){return new T1}class D1{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let b=this.getStorageKey($);return this.store.get(b)??null}async set($,b){let A=this.getStorageKey($);if(await this.store.update(A,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),A=this.keyIndex.has($);if(A)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return A}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function nM($){return new D1($)}import{createHash as SX}from"crypto";var N1={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function F1($){return SX("sha256").update($).digest("hex")}function v1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function QX($){try{let b=$.split("|"),A=new Map;for(let W of b){let[w,j]=W.split(":");if(w&&j)A.set(w,j)}let n=A.get("spec"),m=A.get("impl"),y=A.get("tier");if(!n||!m||!y)return null;return{specHash:n,implHash:m,tier:y,aiModelVersion:A.get("model")}}catch{return null}}function ZX($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class g1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...N1,...b},this.stats={hits:0,misses:0}}createKey($,b,A,n){return{specHash:F1($),implHash:F1(b),tier:A,aiModelVersion:A==="ai_review"?n:void 0}}async lookup($){let b=v1($),A=await this.storage.get(b);if(!A)return this.stats.misses++,{hit:!1,reason:"not_found"};if(A.meta.expiresAt){let n=new Date(A.meta.expiresAt).getTime();if(Date.now()>n)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(A.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(A.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&A.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:A}}async store($,b,A={}){let n=v1($),m=ZX($.tier,this.config),y={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+m).toISOString(),dependencies:A.dependencies??[],specName:A.specName,implPath:A.implPath}};await this.storage.set(n,y),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),A=0;for(let n of b){let m=await this.storage.get(n);if(!m)continue;if(m.meta.dependencies.includes($))await this.storage.delete(n),A++;if(m.meta.specName===$||m.meta.implPath===$)await this.storage.delete(n),A++}return A}async invalidateForSpec($){let b=await this.storage.keys(),A=0;for(let n of b){let m=QX(n);if(m&&m.specHash.startsWith($.substring(0,16)))await this.storage.delete(n),A++}return A}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let b=[];for(let n of $){let m=await this.storage.get(n);if(m)b.push({key:n,createdAt:new Date(m.meta.createdAt).getTime()})}b.sort((n,m)=>n.createdAt-m.createdAt);let A=b.length-this.config.maxEntries;for(let n=0;n<A;n++){let m=b[n];if(m)await this.storage.delete(m.key)}}}function ZM($,b){return new g1($,b)}import{generateVerificationPrompt as XX}from"@contractspec/lib.contracts-spec/llm";function YX($){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 A=[],n=$.split(`
|
|
2500
|
+
`),m="info";for(let j of n){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(/^[-*\u2022]\s*(.+)$/),Q=j.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)A.push({category:"semantic",severity:m,message:Z})}}let y=A.some((j)=>j.severity==="error"),W=!y,w=y?0.3:A.length===0?0.9:0.7;return{compliant:W,confidence:w,findings:A,rawResponse:$}}async function P1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2469
2501
|
{
|
|
2470
2502
|
"passed": true,
|
|
2471
2503
|
"score": 50,
|
|
@@ -2482,16 +2514,16 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2482
2514
|
],
|
|
2483
2515
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2484
2516
|
}
|
|
2485
|
-
\`\`\``;try{let
|
|
2517
|
+
\`\`\``;try{let A=b.aiProvider??"anthropic";if(A==="anthropic"){let{anthropic:n}=await import("@ai-sdk/anthropic"),{generateText:m}=await import("ai");return(await m({model:n("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(A==="openai"){let{openai:n}=await import("@ai-sdk/openai"),{generateText:m}=await import("ai");return(await m({model:n("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${A}`)}catch(A){return`\`\`\`json
|
|
2486
2518
|
{
|
|
2487
2519
|
"passed": false,
|
|
2488
2520
|
"score": 0,
|
|
2489
2521
|
"issues": [
|
|
2490
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2522
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${A instanceof Error?A.message:"Unknown error"}" }
|
|
2491
2523
|
],
|
|
2492
2524
|
"summary": "AI verification encountered an error"
|
|
2493
2525
|
}
|
|
2494
|
-
\`\`\``}}async function
|
|
2526
|
+
\`\`\``}}async function WA($,b={}){let{spec:A,implementationCode:n,implementationPath:m}=$,y=Date.now(),W=XX(A,n),w=await P1(W.taskPrompt,b),j=YX(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:A.meta.key,specVersion:A.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-y}}}function E0($){let{spec:b,implementationCode:A,implementationPath:n}=$,m=Date.now(),y=[];if(A.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(A.includes("// TODO")||A.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"&&!A.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:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}function HX($,b){return`You are analyzing a code implementation against its specification.
|
|
2495
2527
|
|
|
2496
2528
|
## Spec Schema Fields
|
|
2497
2529
|
${$}
|
|
@@ -2538,43 +2570,43 @@ Match types:
|
|
|
2538
2570
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2539
2571
|
- "mismatch": Different meaning despite similar naming
|
|
2540
2572
|
- "missing": Spec field not found in implementation
|
|
2541
|
-
`}function
|
|
2542
|
-
`)}function
|
|
2543
|
-
`),
|
|
2544
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let
|
|
2545
|
-
`)}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
|
|
2546
|
-
`)}function
|
|
2547
|
-
`)}function
|
|
2548
|
-
`),
|
|
2549
|
-
`).trim()||void 0,B=j?.match(
|
|
2550
|
-
${b.map((
|
|
2573
|
+
`}function GX($){let b=[],A=(n,m)=>{try{let W=n?._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)A($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))A($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2574
|
+
`)}function qX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let A=JSON.parse(b[1]);return{fieldMappings:(A.fieldMappings??[]).map((n)=>({specField:String(n.specField??""),specType:String(n.specType??"unknown"),implementationField:n.implementationField?String(n.implementationField):void 0,implementationType:n.implementationType?String(n.implementationType):void 0,match:n.match??"missing",aiConfidence:typeof n.aiConfidence==="number"?n.aiConfidence:0.5,suggestion:n.suggestion?String(n.suggestion):void 0})),intentAlignment:{score:typeof A.intentAlignment?.score==="number"?A.intentAlignment.score:50,issues:Array.isArray(A.intentAlignment?.issues)?A.intentAlignment.issues:[],suggestions:Array.isArray(A.intentAlignment?.suggestions)?A.intentAlignment.suggestions:[]},semanticIssues:(A.semanticIssues??[]).map((n)=>({category:String(n.category??"semantic"),severity:n.severity??"warning",message:String(n.message??""),suggestion:n.suggestion?String(n.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function k1($,b={}){let{spec:A,implementationCode:n}=$,m=GX(A),y=HX(m,n),W=await P1(y,b);return qX(W)}async function OX($,b={}){let{spec:A,implementationCode:n,implementationPath:m}=$,y=Date.now(),W=await WA($,b),w;if(b.aiApiKey)try{w=await k1($,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 JX}from"@contractspec/lib.contracts-spec/operations";function UX($,b){let A=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),n=$.toLowerCase(),m=A.filter((B)=>n.includes(B)),y=A.length>0?m.length/A.length:0,W=b.key.toLowerCase().replace(/\s+/g,""),w=n.includes(W)||n.includes(`test('${b.key.toLowerCase()}'`)||n.includes(`it('${b.key.toLowerCase()}'`)||n.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 VX($,b){let A=JSON.stringify(b.input),n=JSON.stringify(b.output),m=r1(b.input),y=r1(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: ${A.slice(0,100)}...; Output: ${n.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function r1($){let b=[];function A(n){if(typeof n==="string"&&n.length>2)b.push(n);else if(Array.isArray(n))n.forEach(A);else if(n&&typeof n==="object")Object.values(n).forEach(A)}return A($),b}function KX($,b,A){let n=$.includes(b),m=A.http?$.includes(String(A.http)):!0,y=A.when??A.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=n&&(m||B>=0.3);return{name:`Error: ${b}`,type:"error",passed:S,expected:`When: ${y}; Return: ${b} (HTTP ${A.http??400})`,details:S?void 0:!n?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function _X($,b){let A=b.sideEffects?.emits??[],n=[];for(let m of A){let y=JX(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;n.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 n}function zX($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let A=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],n=$.toLowerCase(),m=A.some((y)=>n.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 T0($){let{spec:b,implementationCode:A,implementationPath:n}=$,m=Date.now(),y=[];for(let Y of b.acceptance?.scenarios??[])y.push(UX(A,Y));for(let Y of b.acceptance?.examples??[])y.push(VX(A,Y));for(let[Y,H]of Object.entries(b.io.errors??{}))y.push(KX(A,Y,H));y.push(..._X(A,b));let W=zX(A,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:n?{file:n}: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:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}import{isEmitDeclRef as LX}from"@contractspec/lib.contracts-spec/operations";function RX($){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 IX($){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 CX($,b){if(IX(b))return{name:"contracts_import",passed:!0};let A=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function xX($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let n=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:n,details:n?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function MX($){let b=/:\s*any\b|as\s+any\b|<any>/,A=$.split(`
|
|
2575
|
+
`),n=[];for(let m=0;m<A.length;m++){let y=A[m]??"";if(y.trim().startsWith("//")||y.trim().startsWith("*"))continue;if(b.test(y))n.push(m+1)}return{name:"no_any_type",passed:n.length===0,details:n.length>0?`Found 'any' type on lines: ${n.slice(0,5).join(", ")}${n.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function EX($,b){let A=b.io.errors;if(!A||Object.keys(A).length===0)return{name:"error_handling",passed:!0};let n=Object.keys(A),m=[];for(let y of n)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 TX($,b){let A=b.sideEffects?.emits;if(!A||A.length===0)return{name:"event_emission",passed:!0};let n=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),m=A.map((W)=>{if(LX(W))return W.ref.key;return W.key}),y=m.filter((W)=>$.includes(W));return{name:"event_emission",passed:n&&y.length>0,details:!n?"No event emission pattern found":y.length===0?`Events not referenced: ${m.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function DX($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let A=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:A,details:A?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function NX($,b){let A=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:A,details:A?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function wA($){let{spec:b,implementationCode:A,implementationPath:n}=$,m=Date.now(),y=[RX(A),CX(A,n),xX(A,b),MX(A),EX(A,b),TX(A,b),DX(A,b),NX(A,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:n?{file:n}: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:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}var FX={verbose:!1},vX=["structure","behavior","ai_review"];class D0{config;constructor($={}){this.config={...FX,...$}}async verify($,b,A={}){let n=Date.now(),m=new Map,y=[],W={spec:$,implementationCode:b},w=A.tiers??["structure","behavior"];for(let Z of vX){if(!w.includes(Z))continue;let X;switch(Z){case"structure":X=wA(W);break;case"behavior":X=T0(W);break;case"ai_review":if(this.config.aiApiKey)X=await WA(W,this.config);else X=E0(W);break;default:continue}if(m.set(Z,X),y.push(...X.issues),A.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()-n}}verifyStructure($,b,A){return wA({spec:$,implementationCode:b,implementationPath:A})}verifyBehavior($,b,A){return T0({spec:$,implementationCode:b,implementationPath:A})}async verifyAI($,b,A){let n={spec:$,implementationCode:b,implementationPath:A};if(this.config.aiApiKey)return WA(n,this.config);return E0(n)}quickVerify($,b){return wA({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[n,m]of $.reports){if(b.push(`## ${this.formatTierName(n)}`),b.push(""),b.push(`**Status:** ${m.passed?"\u2713 Passed":"\u2717 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"?"\u274C":y.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";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 A=Array.from($.reports.values()).flatMap((n)=>n.suggestions);if(A.length>0){b.push("## Suggestions"),b.push("");for(let n of A.slice(0,10))b.push(`- ${n}`);if(A.length>10)b.push(`- ... and ${A.length-10} more`);b.push("")}return b.join(`
|
|
2576
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let A=[],n=$.every((j)=>j.passed),m=$.length>0?Math.round($.reduce((j,B)=>j+B.score,0)/$.length):100;A.push(n?"\u2713 Verification passed":"\u2717 Verification failed"),A.push(`Score: ${m}/100`),A.push("");for(let j of $){let B=j.passed?"\u2713":"\u2717";A.push(`${B} ${j.tier}: ${j.score}/100`)}A.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)A.push(`Errors: ${y.length}`);if(W.length>0)A.push(`Warnings: ${W.length}`);if(w.length>0)A.push(`Info: ${w.length}`);return A.join(`
|
|
2577
|
+
`)}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 gX($){return new D0($)}var PX=new D0;var SB={};f(SB,{saveReleaseDraft:()=>s1,renderUpgradePrompt:()=>Gb,renderUpgradeChecklist:()=>J1,renderPatchNotes:()=>Zy,renderMigrationGuide:()=>O1,renderMaintainerSummary:()=>G1,renderCustomerPatchNote:()=>q1,renderCustomerGuide:()=>Xy,prepareReleaseAuthoring:()=>e1,parseConventionalCommit:()=>v0,isConventionalCommit:()=>uX,initReleaseArtifacts:()=>mB,getHighestBumpType:()=>qy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>a1,formatKeepAChangelog:()=>jA,formatConventionalChangelog:()=>c1,formatChangelogJson:()=>N0,filterCommitsByScope:()=>oX,filterBumpableCommits:()=>iX,commitsToChangeEntries:()=>Oy,commitToChangeEntry:()=>d1,checkReleaseArtifacts:()=>WB,buildReleaseArtifacts:()=>yB,applyVersionBump:()=>p1,analyzeVersionsFromCommits:()=>qb,analyzeVersions:()=>XA,DEFAULT_COMMIT_TYPE_MAP:()=>F0});import{basename as kX,dirname as rX}from"path";function jA($){let b=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],A=[...$].sort((n,m)=>h1(n.version,m.version));for(let n of A){b.push(`## [${n.version}] - ${n.date}`),b.push("");let m=n.changes.filter((Q)=>Q.type==="added"),y=n.changes.filter((Q)=>Q.type==="changed"),W=n.changes.filter((Q)=>Q.type==="deprecated"),w=n.changes.filter((Q)=>Q.type==="removed"),j=n.changes.filter((Q)=>Q.type==="fixed"),B=n.changes.filter((Q)=>Q.type==="security"),S=n.breakingChanges??n.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### \u26A0\uFE0F Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(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(`
|
|
2578
|
+
`)}function c1($){let b=["# Changelog",""],A=[...$].sort((n,m)=>h1(n.version,m.version));for(let n of A){let m=n.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":n.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${n.version} (${n.date}) - ${m}`),b.push("");let y={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let W of n.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(`
|
|
2579
|
+
`)}function N0($,b){let A=$.analyses.filter((y)=>y.needsBump),n=new Date().toISOString(),m=n.split("T")[0]??"";return{generatedAt:n,baseline:b,specs:A.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:cX(A,m)}}function fX($){let b=$.split("/"),A=b.lastIndexOf("packages");if(A>=0&&A+2<b.length)return b.slice(0,A+3).join("/");return rX($)}var f1={major:3,minor:2,patch:1};function cX($,b){let A=new Map;for(let n of $){let m=fX(n.specPath),y=A.get(m);if(y)y.push(n);else A.set(m,[n])}return Array.from(A.entries()).flatMap(([n,m])=>{let y=m[0];if(!y)return[];let W=m.reduce((w,j)=>{return(f1[j.bumpType]??0)>(f1[w.bumpType]??0)?j:w},y);return[{name:kX(n),path:n,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 h1($,b){let A=(y)=>{return y.split(".").map((w)=>parseInt(w,10)||0)},n=A($),m=A(b);for(let y=0;y<3;y++){let W=n[y]??0,w=m[y]??0;if(W!==w)return w-W}return 0}var F0={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},hX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,dX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function v0($){let b=$.split(`
|
|
2580
|
+
`),A=b[0]?.trim();if(!A)return null;let n=A.match(hX);if(!n)return null;let[,m,y,W,w]=n;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2581
|
+
`).trim()||void 0,B=j?.match(dX),S=B?.[1];return{type:m.toLowerCase(),scope:y?.toLowerCase(),breaking:!!W||!!B,description:w.trim(),body:j,breakingDescription:S,raw:$}}function uX($){return v0($)!==null}function Gy($,b=F0){if($.breaking)return"major";return b[$.type]??null}function qy($,b=F0){let A=["major","minor","patch"],n=null;for(let m of $){let y=Gy(m,b);if(!y)continue;if(!n){n=y;continue}let W=A.indexOf(n);if(A.indexOf(y)<W)n=y}return n}function d1($){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 Oy($){return $.map(d1)}function oX($,b){return $.filter((A)=>A.scope?.toLowerCase()===b.toLowerCase())}function iX($,b=F0){return $.filter((A)=>Gy(A,b)!==null)}import{z as T}from"zod";import{ReleaseCapsuleSchema as u1}from"@contractspec/lib.contracts-spec";import{dump as lX,load as tX}from"js-yaml";var pX=".changeset/*.md",aX=".changeset/*.release.yaml",eX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,sX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function $Y($,b){return(await $.glob({pattern:pX,cwd:b,absolute:!0})).filter((n)=>$.basename(n)!=="README.md")}async function BA($,b){let A=await $Y($,b),n=[];for(let m of A){let y=await $.readFile(m);n.push(bY($.basename(m),y))}return n}async function SA($,b,A,n){let m=await $.glob({pattern:aX,cwd:b,absolute:!0}),y=new Map(A.map((j)=>[j.slug,j.packages])),W=new Map,w=[];for(let j of m){let B=$.basename(j).replace(/\.release\.yaml$/,"");if(n&&!n.has(B))continue;try{let S=tX(await $.readFile(j)),Q=AY(S,B,y.get(B)??[]);W.set(B,Q)}catch(S){w.push(nY(j,B,S))}}return{capsules:W,issues:w}}async function QA($,b){let A=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),n=[];for(let m of A){let y=JSON.parse(await $.readFile(m));if(!y.name||!y.version||y.private===!0)continue;let W=$.relative(b,$.dirname(m))||".";n.push({name:y.name,dir:W,version:y.version})}return n.sort((m,y)=>m.dir.localeCompare(y.dir))}function g0($,b){let A=new Set;for(let n of $){let m=b.find((y)=>y.dir==="."?!n.startsWith("packages/"):n===y.dir||n.startsWith(`${y.dir}/`));if(m)A.add(m.name)}return Array.from(A).sort((n,m)=>n.localeCompare(m))}function P0($,b){return`---
|
|
2582
|
+
${b.map((n)=>`"${n.name}": ${n.releaseType}`).join(`
|
|
2551
2583
|
`)}
|
|
2552
2584
|
---
|
|
2553
2585
|
|
|
2554
2586
|
${$}
|
|
2555
|
-
`}function
|
|
2556
|
-
`)}function
|
|
2557
|
-
`)){let j=w.trim().match(
|
|
2558
|
-
`)}function
|
|
2587
|
+
`}function k0($){return lX(u1.parse($),{noRefs:!0,lineWidth:100})}function ZA($){return $.map((b)=>{let A=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",n=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${A} ${b.message}.${n}`.trim()}).join(`
|
|
2588
|
+
`)}function bY($,b){let A=$.replace(/\.md$/,""),n=b.match(eX);if(!n)return{slug:A,summary:b.trim(),packages:[]};let m=n[1]??"",y=(n[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2589
|
+
`)){let j=w.trim().match(sX);if(!j)continue;let B=j[1],S=j[2];if(!B||S==="none")continue;W.push({name:B,releaseType:S})}return{slug:A,summary:y,packages:W}}function AY($,b,A){let n=typeof $==="object"&&$!==null?$:{},m=Array.isArray(n.packageNames)?n.packageNames.filter((y)=>typeof y==="string").map((y)=>({name:y,releaseType:n.releaseType??"patch"})):[];return u1.parse({...n,slug:b,packages:Array.isArray(n.packages)&&n.packages.length>0?n.packages:m.length>0?m:A})}function nY($,b,A){let n=typeof A==="object"&&A!==null?A:null,m=Array.isArray(n?.issues)?n.issues.map((W)=>W.message).filter((W)=>typeof W==="string"):[],y=m.length>0?`Release capsule validation failed: ${m.join("; ")}`:typeof n?.reason==="string"?`Release capsule YAML parse failed: ${n.reason}`:`Release capsule parse failed: ${A instanceof Error?A.message:String(A)}`;return{slug:b,filePath:$,message:y,line:typeof n?.mark?.line==="number"?n.mark.line+1:void 0,column:typeof n?.mark?.column==="number"?n.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as t1,determineBumpType as mY}from"@contractspec/lib.contracts-spec";async function XA($,b={}){let{fs:A,git:n,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 A.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 A.readFile(X),H=r0(Y);if(!H)continue;let J=null;if(b.baseline)try{J=await n.showFile(b.baseline,X)}catch{J=null}let O=yY(Y,J),V=O.some((z)=>z.type==="breaking"),U=O.length>0&&!V,K=O.length>0;if(V)S++;if(U)Q++;let q=mY(V,U),G=K?t1(H.version,q):H.version;B.push({specPath:X,specKey:H.key,currentVersion:H.version,suggestedVersion:G,bumpType:q,changes:O,hasBreaking:V,needsBump:K})}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 qb($,b={}){let{git:A,logger:n}=$,m=b.baseline??"HEAD~10";n.info("Analyzing commits for version bump...",{baseline:m});try{let y=await A.log(m),W=[],w=[];for(let Q of y){let Z=v0(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=qy(w),B=Oy(w),S=W.filter((Q)=>Q.breaking).length;return n.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 n.warn("Failed to analyze commits",{error:y instanceof Error?y.message:String(y)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function p1($,b){let{fs:A,logger:n}=$,{specPath:m,dryRun:y=!1,config:W}=b;n.info("Applying version bump...",{specPath:m,bumpType:b.bumpType});try{let w=await A.readFile(m),j=r0(w);if(!j)return{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:i1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=t1(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=wY(w,j.version,S);await A.writeFile(m,X)}if(n.info("Version bump applied",{specPath:m,previousVersion:j.version,newVersion:S}),W?.integrateWithChangesets)await SY($,{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 n.error("Version bump failed",{specPath:m,error:j}),{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:i1(),error:j}}}async function a1($,b={}){let{logger:A}=$,n=b.tiers??["spec","library","monorepo"],m=b.format??"keep-a-changelog";A.info("Generating changelogs...",{tiers:n,format:m});let y=await XA($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),W=[],w=new Map,j="",B=0;if(n.includes("spec"))for(let Q of y.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:jY(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(n.includes("library")){let Q=BY(y.analyses);for(let[Z,X]of Q){let Y=X.filter((H)=>H.needsBump);if(Y.length>0)w.set(Z,jA(Y.map(l1))),B+=Y.length}}if(n.includes("monorepo")){let Q=y.analyses.filter((Z)=>Z.needsBump).map(l1);j=jA(Q)}let S=N0(y,b.baseline);return A.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:W,libraryMarkdown:w,monorepoMarkdown:j,json:S,totalEntries:B}}function r0($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),A=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!A)return null;let n=b[1],m=A[1];if(!n||!m)return null;return{key:n,version:m}}function yY($,b){let A=[];if(!b)return A.push({type:"added",description:"New spec added"}),A;let n=r0($),m=r0(b);if(!n||!m)return A;if(n.version!==m.version)A.push({type:"changed",description:`Version updated from ${m.version} to ${n.version}`,path:"meta.version"});let y=WY($,b);if(y.breaking)A.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(y.nonBreaking)A.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return A}function WY($,b){let A=/io:\s*\{[\s\S]*?\}/,n=$.match(A)?.[0]??"",m=b.match(A)?.[0]??"";if(n===m)return{breaking:!1,nonBreaking:!1};let y=o1(n),W=o1(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 o1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((n)=>n[1]).filter((n)=>!!n)}function wY($,b,A){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${A}'`)}function i1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function jY($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],A=$.changes.filter((y)=>y.type==="breaking"),n=$.changes.filter((y)=>y.type==="changed"),m=$.changes.filter((y)=>y.type==="added");if(A.length>0)b.push("### Breaking Changes"),A.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(n.length>0)b.push("### Changed"),n.forEach((y)=>b.push(`- ${y.description}`)),b.push("");return b.join(`
|
|
2590
|
+
`)}function BY($){let b=new Map;for(let A of $){let y=A.specPath.match(/(.+?\/src\/)/)?.[1]??A.specPath,W=b.get(y)??[];W.push(A),b.set(y,W)}return b}function l1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function SY($,b){let{fs:A,logger:n}=$,{specPath:m,bumpType:y,summary:W,dryRun:w}=b;try{let j=c(m),B=P$(j);if(!B){n.warn("Could not determine package name for changeset",{specPath:m});return}let S=j,Q=null;while(!0){let H=A.join(S,".changeset");if(await A.exists(H)){Q=H;break}let J=A.dirname(S);if(J===S)break;S=J}if(!Q){n.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${QY()}.md`,X=A.join(Q,Z),Y=`---
|
|
2559
2591
|
"${B}": ${y}
|
|
2560
2592
|
---
|
|
2561
2593
|
|
|
2562
2594
|
${W}
|
|
2563
|
-
`;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 Sn(n,W),j=b.baseline?await A.diffFiles(b.baseline):[],B=await jn(n,W),S=await Bn(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,q=Y?B.find((O)=>O.slug===Y):void 0,K=Y?S.capsules.get(Y):void 0,J=b.releaseType??K?.packages[0]?.releaseType??q?.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:q,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((O)=>O.message):[],parseIssues:S.issues.map((O)=>O.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. ${Qn(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:n}=$,A=I(b.workspaceRoot),m=Xn(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 Xn({...$.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 Xn({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 qy(n,"maintainer",b.maintainerSummary),qy(n,"customer",b.customerSummary),qy(n,"integrator",b.integratorSummary),Xn({...$,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 Xn($){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}=Xn($);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 qy($,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 Sn(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((O)=>O.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:[]}},q=n.join(y,".changeset",`${Y}.md`),K=n.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await n.exists(q))throw Error(`Changeset already exists: ${q}`);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(q,J),await n.writeFile(K,U);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:q,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 jn(n,m),j=await Bn(n,m,w);if(j.issues.length>0)throw Error(Qn(j.issues));let B=j.capsules,S=await Sn(n,m),Q=await Promise.all(Array.from(B.entries()).map(async([U,H])=>{let O=n.join(m,".changeset",`${U}.release.yaml`),_=await n.stat(O);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=mn(Z,[],X,Yb),G=n.join(W,"manifest.json"),V=n.join(W,"upgrade-manifest.json"),q=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(q,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:q,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 jn(n,A),S=await Bn(n,A,B),Q=S.capsules,Z=B.length>0,X=!Z&&Q.size>0;j.push(...S.issues.map((Y)=>Qn([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 Zn($,{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"fs";import{readFile as OY}from"fs/promises";import{join as Vy}from"path";import qY 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 OY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=qY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...dA,...m}}import{existsSync as VY}from"fs";import{copyFile as JY,mkdir as AB,readFile as UY,writeFile as KY}from"fs/promises";import{dirname as _Y,join as Ob}from"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=Ob(n,".contractspec","context"),y=Ob(m,"files"),W=[...LY],w=Ob(n,".gitignore");if(VY(w)){let G=(await UY(w,"utf-8")).split(`
|
|
2564
|
-
`).map((
|
|
2595
|
+
`;if(!w)await A.writeFile(X,Y),n.info("Generated changeset",{filePath:X});else n.info("Would generate changeset",{filePath:X,content:Y})}catch(j){n.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function QY(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],A=["run","fly","hop","eat","nap","cry","sing"],n=$[Math.floor(Math.random()*$.length)],m=b[Math.floor(Math.random()*b.length)],y=A[Math.floor(Math.random()*A.length)],W=Math.floor(Math.random()*1000);return`${n}-${m}-${y}-${W}`}var ZY=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 e1($,b={}){let{fs:A,git:n,logger:m,ai:y}=$,W=x(b.workspaceRoot),w=await QA(A,W),j=b.baseline?await n.diffFiles(b.baseline):[],B=await BA(A,W),S=await SA(A,W,B),Q=b.packages&&b.packages.length>0?b.packages:g0(j,w),Z=b.baseline?await qb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??qY(B,S.capsules,Q),H=Y?A.join(W,".changeset",`${Y}.md`):void 0,J=Y?A.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((G)=>G.slug===Y):void 0,V=Y?S.capsules.get(Y):void 0,U=b.releaseType??V?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??OY(Q)),K=(H?await A.exists(H):!1)||(J?await A.exists(J):!1),q=await YY(y,XY({existingCapsule:V,existingChangeset:O,packageNames:Q,releaseType:U,summary:b.summary,workspacePackages:w,isBreaking:U==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await n.log(b.baseline)).map((G)=>G.message):[],parseIssues:S.issues.map((G)=>G.message)},m);return{workspaceRoot:W,source:K?"existing":"created",changesetPath:H??A.join(W,".changeset",`${q.slug}.md`),capsulePath:J??A.join(W,".changeset",`${q.slug}.release.yaml`),draft:q,warnings:S.issues.length?[`Some release capsules could not be parsed. ${ZA(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function s1($,b){let{fs:A}=$,n=x(b.workspaceRoot),m=YA(b.draft),y=A.join(n,".changeset",`${m.slug}.md`),W=A.join(n,".changeset",`${m.slug}.release.yaml`),w=await A.exists(y)||await A.exists(W)?"updated":"created",j=P0(m.summary,m.packages),B=k0(GY(m));return await A.writeFile(y,j),await A.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function XY($){if($.existingCapsule)return YA({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((n)=>({...n,version:$.workspacePackages.find((m)=>m.name===n.name)?.version??n.version})):$.packageNames.map((n)=>({name:n,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===n)?.version})),A=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return YA({slug:$.selectedSlug??JY(A),summary:A,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:$B(A),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function YY($,b,A,n){if(!$)return b;try{let m=await $.generateStructured({schema:ZY,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 HY(b,m.object)}catch(m){return n.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:m instanceof Error?m.message:String(m)}),b}}function HY($,b){let A=[...$.audiences];return Jy(A,"maintainer",b.maintainerSummary),Jy(A,"customer",b.customerSummary),Jy(A,"integrator",b.integratorSummary),YA({...$,summary:bB($.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 YA($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:$B($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function GY($){let{releaseType:b,...A}=YA($);return{schemaVersion:"1",...A}}function $B($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Jy($,b,A){let n=$.find((m)=>m.kind===b);if(n&&!bB(n.summary))return;if(n){n.summary=A;return}$.push({kind:b,summary:A})}function qY($,b,A){let n=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(n.size===1)return Array.from(n)[0];if(A.length===0)return;let m=Array.from(n).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)=>A.includes(B))});return m.length===1?m[0]:void 0}function OY($){return $.length>0?"minor":"patch"}function bB($){return $.trim().startsWith("Describe the ")}function JY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as AB}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as UY,DEFAULT_CONTRACTSRC as VY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var nB="generated/releases",KY="1970-01-01T00:00:00.000Z",f0=VY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function mB($,b={}){let{fs:A,git:n,logger:m}=$,y=x(b.workspaceRoot),W=await QA(A,y),w=b.baseline?await n.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:g0(w,W),B=b.baseline?await qb($,{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??RY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??MY(X),H=j.map((q)=>({name:q,releaseType:Z,version:W.find((G)=>G.name===q)?.version})),J={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:H,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=A.join(y,".changeset",`${Y}.md`),V=A.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await A.exists(O))throw Error(`Changeset already exists: ${O}`);if(await A.exists(V))throw Error(`Release capsule already exists: ${V}`)}let U=P0(X,H),K=k0(J);if(!b.dryRun)await A.writeFile(O,U),await A.writeFile(V,K);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:V,changesetContent:U,capsuleContent:K,packages:H,releaseType:Z,isBreaking:J.isBreaking}}async function yB($,b={}){let{fs:A,logger:n}=$,m=x(b.workspaceRoot),y=await wB(A,m),W=A.join(m,b.outputDir??nB),w=A.join(W,"manifest.json"),j=await LY(A,w),B=await BA(A,m),S=await jB($,{workspaceRoot:m,changesets:B,scope:b.scope??"current",baseline:b.baseline}),Q=await SA(A,m,B,S);if(Q.issues.length>0)throw Error(ZA(Q.issues));let Z=Q.capsules,X=await QA(A,m),Y=new Map((j?.releases??[]).map((_)=>[_.slug,_])),H=(b.scope??"current")!=="all",J=Array.from(Z.entries()).map(([_,L])=>{let I=Y.get(_),E=L.packages.map((N)=>({...N,version:BB(N,X,I,H)}));return{slug:_,version:IY(L,X,I,H),summary:L.summary,date:I?.date??xY(),isBreaking:L.isBreaking,packages:E,affectedRuntimes:[...L.affectedRuntimes],affectedFrameworks:[...L.affectedFrameworks],audiences:[...L.audiences],deprecations:[...L.deprecations],migrationInstructions:[...L.migrationInstructions],upgradeSteps:[...L.upgradeSteps],validation:L.validation}}),O=AB.parse({generatedAt:CY(J),releases:J}),V=b.agentTargets??y.agentTargets??["codex"],U=yA(O,[],V,Gb),K=A.join(W,"upgrade-manifest.json"),q=A.join(W,"patch-notes.md"),G=A.join(W,"customer-guide.md"),z=Object.fromEntries(U.agentPrompts.map((_)=>[_.agent,A.join(W,"prompts",`${_.agent}.md`)]));if(!b.dryRun){await A.writeFile(w,JSON.stringify(O,null,2)),await A.writeFile(K,JSON.stringify(O,null,2)),await A.writeFile(q,Zy(O)),await A.writeFile(G,Xy(O));for(let _ of U.agentPrompts)await A.writeFile(z[_.agent]??"",_.prompt)}return n.info("Built release artifacts",{outputDir:W,releasesBuilt:O.releases.length}),{outputDir:W,manifestPath:w,upgradeManifestPath:K,patchNotesPath:q,customerGuidePath:G,promptPaths:z,manifest:O,upgradePlan:U,releasesBuilt:O.releases.length}}async function WB($,b={}){let{fs:A}=$,n=x(b.workspaceRoot),m=await wB(A,n),y=A.join(n,b.outputDir??nB),W=[],w=[],j=[],B=await BA(A,n),S=await jB($,{workspaceRoot:n,changesets:B,scope:b.scope??"current",baseline:b.baseline}),Q=await SA(A,n,B,S),Z=Q.capsules,X=B.length>0,Y=!X&&Z.size>0;j.push(...Q.issues.map((H)=>ZA([H]))),Ob(W,X||Y,"changesets",X?`Found ${B.length} release changeset(s).`:Y?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let H of B)if(!Z.has(H.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${H.slug}.`);for(let[H,J]of Z){if(J.isBreaking&&J.migrationInstructions.length===0)j.push(`Breaking release ${H} is missing migration instructions.`);if(J.validation.commands.length===0)j.push(`Release capsule ${H} is missing validation commands.`);if(J.validation.evidence.length===0)j.push(`Release capsule ${H} is missing validation evidence.`)}if(b.baseline){try{let H=await K$($,{baseline:b.baseline,workspaceRoot:n});if(Ob(W,!0,"impact",`Impact status: ${H.status}`),H.summary.breaking>0&&!Array.from(Z.values()).some((J)=>J.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(H){Ob(W,!1,"impact",c0(H)),j.push(`Impact detection failed: ${c0(H)}`)}try{let H=await XA($,{baseline:b.baseline,workspaceRoot:n});Ob(W,!0,"versioning",`${H.specsNeedingBump} spec(s) need version review.`)}catch(H){Ob(W,!1,"versioning",c0(H)),j.push(`Version analysis failed: ${c0(H)}`)}}if(b.strict)for(let H of m.publishArtifacts??[]){let J=A.join(y,H);if(!await A.exists(J))j.push(`Missing generated release artifact: ${J}`)}if(Ob(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!X&&!Y)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function wB($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return f0;try{let n=JSON.parse(await $.readFile(A)),m=UY.safeParse(n);return m.success?{...f0,...m.data.release}:f0}catch{return f0}}async function jB($,b){if(b.scope==="all")return;if(b.changesets.length>0)return new Set(b.changesets.map((m)=>m.slug));let A=await _Y($.git,b.baseline),n=new Set;for(let m of A){let y=zY(m.path);if(!y)continue;if(m.path.endsWith(".release.yaml")||m.path.endsWith(".md"))n.add(y)}return n.size>0?n:void 0}async function _Y($,b){if(b&&b!=="HEAD"&&$.diffNameStatus)return $.diffNameStatus(b,[".changeset"]);if($.statusFiles)return $.statusFiles([".changeset"]);if(b)return(await $.diffFiles(b,[".changeset"])).map((n)=>({status:"M",path:n}));return[]}function zY($){let A=$.replace(/\\/g,"/").split("/").pop();if(!A||A==="README.md")return;if(A.endsWith(".release.yaml"))return A.replace(/\.release\.yaml$/,"");if(A.endsWith(".md"))return A.replace(/\.md$/,"");return}async function LY($,b){if(!await $.exists(b))return;try{return AB.parse(JSON.parse(await $.readFile(b)))}catch{return}}function RY($){return $.length>0?"minor":"patch"}function IY($,b,A,n){return $.packages.map((y)=>BB(y,b,A,n)).find((y)=>typeof y==="string")??"0.0.0"}function BB($,b,A,n){let m=b.find((W)=>W.name===$.name)?.version,y=A?.packages.find((W)=>W.name===$.name)?.version;return n?m??$.version??y:$.version??y??m}function CY($){let A=$.map((n)=>n.date).filter(Boolean).sort().at(-1);return A?`${A}T00:00:00.000Z`:KY}function xY(){return new Date().toISOString().split("T")[0]??"1970-01-01"}function MY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Ob($,b,A,n){$.push({name:A,ok:b,message:n})}function c0($){return $ instanceof Error?$.message:String($)}var VB={};f(VB,{silentLogger:()=>XB,runWorkflow:()=>YB,loadWorkflows:()=>Ky,loadVibeConfig:()=>d0,installPack:()=>UB,getWorkflow:()=>GB,exportContext:()=>ZB,consoleLogger:()=>Vy,builtinWorkflows:()=>u0,DEFAULT_VIBE_CONFIG:()=>h0});import{existsSync as EY}from"fs";import{readFile as TY}from"fs/promises";import{join as Uy}from"path";import DY from"js-yaml";var h0={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function d0($){let b=$??process.cwd(),A=x(b)??b,n=[Uy(A,".contractspec","vibe","config.json"),Uy(A,".contractspec","vibe","config.yaml"),Uy(A,".contractspec","vibe","config.yml")],m={};for(let y of n)if(EY(y))try{let W=await TY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=DY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...h0,...m}}import{existsSync as NY}from"fs";import{copyFile as FY,mkdir as QB,readFile as vY,writeFile as gY}from"fs/promises";import{dirname as PY,join as Jb}from"path";import{glob as kY}from"glob";var rY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function ZB($){let b=$??process.cwd(),A=x(b)??b,n=await d0(b),m=Jb(A,".contractspec","context"),y=Jb(m,"files"),W=[...rY],w=Jb(A,".gitignore");if(NY(w)){let H=(await vY(w,"utf-8")).split(`
|
|
2596
|
+
`).map((J)=>J.trim()).filter((J)=>J&&!J.startsWith("#"));W=[...W,...H]}let j=n.contextExportAllowlist.length>0?n.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let Y of j){let H=await kY(Y,{cwd:A,ignore:W,nodir:!0,dot:!0});B.push(...H)}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 QB(y,{recursive:!0});let Q=[];for(let Y of S){let H=Jb(A,Y),J=Jb(y,Y);await QB(PY(J),{recursive:!0}),await FY(H,J),Q.push({path:Y,size:0})}let Z=Jb(m,"index.json"),X={generatedAt:new Date().toISOString(),files:Q.map((Y)=>Y.path),config:{allowlist:n.contextExportAllowlist,ignores:W.length}};return await gY(Z,JSON.stringify(X,null,2)),{success:!0,files:S,indexPath:Z}}var u0=[{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.
|
|
2565
2597
|
Please review them and move selected files to contracts/ directory.
|
|
2566
|
-
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
|
|
2567
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2568
|
-
`);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(
|
|
2569
|
-
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)
|
|
2598
|
+
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 fY}from"child_process";var XB={log:()=>{},warn:()=>{},error:()=>{}},Vy={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function YB($,b,A){let n=A?.logger??Vy,m=A?.prompter;if(n.log(`
|
|
2599
|
+
Running Workflow: ${$.name}`),$.description)n.log($.description);if(n.log(`Track: ${b.track}`),b.dryRun)n.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2600
|
+
`);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(n.log(`
|
|
2601
|
+
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)n.log(` Command: ${W.command}`);if(W.manualCheckpoint){if(b.dryRun)n.warn(" [Manual Checkpoint] Would pause here for user input.");else if(m){if(W.manualMessage)n.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 n.warn("Workflow aborted by user."),y.success=!1,y.steps.push({...w,status:"skip",error:"Aborted by user"}),y;if(j==="skip"){n.warn(" \u2192 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),n.log(" \u2713 Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return n.error(` \u274C 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 A=$.split(" "),n=A[0],m=A.slice(1);if(!n)throw Error("Invalid command");return new Promise((y,W)=>{let w=fY(n,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 hY}from"fs";import{readdir as dY,readFile as uY}from"fs/promises";import{join as HB}from"path";import oY from"js-yaml";async function Ky($){let b=[...u0],A=$??process.cwd(),n=x(A)??A,m=HB(n,".contractspec","vibe","workflows");if(hY(m))try{let y=await dY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await uY(HB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=oY.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 GB($,b){return(await Ky(b)).find((n)=>n.id===$)}import{existsSync as _y}from"fs";import{copyFile as qB,mkdir as OB,readdir as JB,stat as iY}from"fs/promises";import{join as N$,resolve as lY}from"path";async function UB($,b){let A=b??process.cwd(),n=x(A)??A;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let m=lY(A,$);if(!_y(m))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${m}`};let y=0,W=0,w=N$(m,"workflows");if(_y(w)){let B=N$(n,".contractspec","vibe","workflows");await OB(B,{recursive:!0});let S=await JB(w);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await qB(N$(w,Q),N$(B,Q)),y++}let j=N$(m,"templates");if(_y(j)){let B=N$(n,".contractspec","vibe","templates");await OB(B,{recursive:!0});let S=await JB(j);for(let Q of S){let Z=N$(j,Q),X=N$(B,Q);if((await iY(Z)).isFile())await qB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as tY}from"@contractspec/module.workspace";var KB=["product","eng","qa"];function pY($){return KB.includes($)}async function eE($,b){if(!pY(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${KB.join(", ")}`);let A,n,m;if(b.specFiles&&b.specFiles.length>0)A=b.specFiles;else{let W=await aY($,{baseline:b.baseline});if(n=W.totalSpecs,m=W.changedFilesCount,b.baseline){if(W.changedFilesCount===0)return{views:[],totalSpecs:n,changedFilesCount:0,status:"no_changes"};if(W.specFiles.length===0)return{views:[],totalSpecs:n,changedFilesCount:m,status:"no_changed_specs"}}A=W.specFiles}if(A.length===0)return{views:[],totalSpecs:n,changedFilesCount:m,status:"no_specs"};let y=[];for(let W of A){let w=await eY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:n,changedFilesCount:m,status:"success"}}async function aY($,b={}){let n=(await B$({fs:$.fs})).map((w)=>w.filePath),m=n.length;if(!b.baseline)return{specFiles:n,totalSpecs:m};let y=await $.git.diffFiles(b.baseline);if(y.length===0)return{specFiles:[],totalSpecs:m,changedFilesCount:0,hasChanges:!1};let W=n.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 eY($,b,A){if(!await A.fs.exists($))throw Error(`File not found: ${$}`);let n=await tY($);if(n.length===0)return`No specs found in ${$} (Parse result empty)`;return n.map((m)=>sY(m,b)).join(`
|
|
2570
2602
|
|
|
2571
2603
|
---
|
|
2572
2604
|
|
|
2573
|
-
`)}function
|
|
2574
|
-
`)}function
|
|
2605
|
+
`)}function sY($,b){let A=[];switch(b){case"product":$3($,A);break;case"eng":b3($,A);break;case"qa":A3($,A);break}return A.join(`
|
|
2606
|
+
`)}function $3($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2575
2607
|
${$.meta.goal}
|
|
2576
2608
|
`);if($.meta.context)b.push(`### Context
|
|
2577
2609
|
${$.meta.context}
|
|
2578
|
-
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((
|
|
2579
|
-
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((
|
|
2580
|
-
`)}export{
|
|
2610
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- \u2705 Enforces Business Policies");if($.hasIo)b.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((A)=>b.push(`- **${A.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function b3($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function A3($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2611
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((A)=>b.push(`- \uD83E\uDDEA \`${A.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((A)=>b.push(`- [ ] Verify event \`${A.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((A)=>b.push(`- [ ] Test Operation flow: \`${A.name}\``));if($.presentations?.length)$.presentations.forEach((A)=>b.push(`- [ ] Test UI Component: \`${A.name}\``))}}function AT($,b,A,n){let{watcher:m,fs:y,logger:W}=$,w=m.watch(A),j=n?.validate??(async(S)=>{await p$(S,{fs:y,logger:W})}),B=n?.build??(async(S)=>{await wb(S,{fs:y,logger:W},b)});return w.on(async(S)=>{if(S.type!=="change")return;if(W.info("watchSpecs.changed",{path:S.path}),A.runValidate)await j(S.path);if(A.runBuild)if(A.dryRun)W.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),w}async function yT($,b,A={}){let n=(A.getWorkspaceInfo??hy)(b),m=$.join(n.workspaceRoot,".contractsrc.json"),y=$.join(n.packageRoot,".contractsrc.json"),W=await $.exists(m),w=n.workspaceRoot!==n.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{...n,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?y:void 0}}async function WT($,b){let A=[],n=$.join(b,".contractsrc.json");if(await $.exists(n))A.push(n);let m=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let y of m)if(y!==n)A.push(y);return A}async function wT($,b,A){let n={};if(b&&await $.exists(b))try{let m=await $.readFile(b);n=JSON.parse(m)}catch{}if(A&&await $.exists(A))try{let m=await $.readFile(A),y=JSON.parse(m);n=_B(n,y)}catch{}return n}function _B($,b){let A={...$};for(let n of Object.keys(b)){let m=$[n],y=b[n];if(typeof m==="object"&&m!==null&&!Array.isArray(m)&&typeof y==="object"&&y!==null&&!Array.isArray(y))A[n]=_B(m,y);else A[n]=y}return A}function jT($){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(`
|
|
2612
|
+
`)}export{AT as watchSpecs,VB as vibe,SB as versioning,OX as verifyWithAIEnhanced,WA as verifyWithAI,wA as verifyStructure,PX as verifyService,k1 as verifySemanticFields,N7 as verifyImportedContracts,DR as verifyImplementationAgainstParsedSpec,T0 as verifyBehavior,mx as validateTenantConfig,eC as validateSpecs,p$ as validateSpec,y1 as validateScannedSpec,hC as validatePackageScaffold,gC as validateImplementationWithAgent,b0 as validateImplementationFiles,aC as validateDiscoveredSpecs,DC as validateBlueprint,pY as validateAudience,tz as validateAgainstOpenApiService,Aw as utils,x1 as upgrade,Dx as updateSpec,KQ as toKebabCase,tW as templates,oz as syncWithOpenApiService,Hx as syncSpecs,QX as stringToCacheKey,ny as setupUsageMd,Q0 as setupGitignore,am as setupAgentsMd,EI as searchRegistry,a as safeParseJson,_x as runTests,zx as runTestSpecs,OC as runSetup,OI as runQuickstart,Lw as runDoctor,OK as runCIChecks,jw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,CQ as resolveImplementations,Un as resolveDefaultBuildTargets,uj as resolveAuthoredModuleValue,gw as resolveAllImplementations,AA as renderManagedMarkdownBlock,sy as prompts,fy as parseGitModules,Nw as parseExplicitImplementations,iw as packageDeclarations,bG as operationRegistry,aj as onboarding,pm as normalizeMarkdownContent,$D as module,wT as mergeMonorepoConfigs,_0 as mergeManagedMarkdown,h4 as mergeGitignoreContent,P as loadWorkspaceConfig,BU as loadPackageAuthoredDocBlocks,hj as loadAuthoredModuleValue,lR as loadAuthoredModuleIfExists,U0 as loadAuthoredModuleExports,W$ as loadAuthoredModule,jU as loadAuthoredDocBlocksFromSourceFiles,Lx as listTests,aY as listSpecsForView,B$ as listSpecs,MI as listFromRegistry,Yn as listAgentTypes,Ub as isMonorepo,JI as isContractSpecInstalled,mJ as isConnectPreset,nJ as isBuilderPreset,Tb as inferSetupPresetFromConfig,VQ as inferImplementationType,I7 as importFromSourceService,xj as importFromOpenApiService,mj as impact,rj as hooks,OV as groupSpecsByType,Q5 as getWorkspacePackages,hy as getWorkspaceInfo,f3 as getRunCommand,im as getProductionDependencies,P$ as getPackageName,X5 as getMetaRepoInfo,dy as getInstallCommand,kU as getImplementationSummary,rO as getGraphStats,yT as getExtendedWorkspaceInfo,c3 as getExecCommand,lm as getDevDependencies,om as getDependencies,Dw as getConventionPaths,PO as getContractNode,lA as getClaudeDesktopConfigPath,Tn as getBuilderRuntimeModeForPreset,Bw as getBuilderBootstrapPresetForSetupPreset,sW as getApiKey,WV as getAllSpecs,KJ as getAllLayerLocations,Kb as getAgentAdapter,nn as getAIProvider,xA as genericMCPAdapter,MW as generateWorkspaceEnvExample,lW as generateWorkflowSpec,kA as generateWorkflowRunnerTemplate,NA as generateWorkflowDevkitWorkflowTemplate,gA as generateWorkflowDevkitStreamRouteTemplate,FA as generateWorkflowDevkitStartRouteTemplate,PA as generateWorkflowDevkitGenericTemplate,vA as generateWorkflowDevkitFollowUpRouteTemplate,iA as generateVscodeSettings,qW as generateVisualizationSpec,eE as generateViews,eY as generateView,Hw as generateUsageGuide,HW as generateTranslationSpec,iW as generateThemeSpec,PW as generateTestTemplate,YW as generateTestSpec,oW as generateTelemetrySpec,EW as generateTargetEnvExample,KW as generatePwaAppManifestSpec,JW as generateProductIntentSpec,uW as generatePresentationSpec,XW as generatePolicySpec,dW as generateOperationSpec,hW as generateMigrationSpec,ER as generateMermaidDiagram,T7 as generateMarkdownReport,fW as generateKnowledgeSpaceSpec,GW as generateJobSpec,rW as generateIntegrationSpec,VW as generateHarnessSuiteSpec,UW as generateHarnessScenarioSpec,vW as generateHandlerTemplate,r7 as generateGuideFromParsedSpec,FW as generateFormSpec,NW as generateFeatureSpec,PR as generateFeatureContextMarkdown,DW as generateExperimentSpec,EA as generateExampleSpec,TW as generateEventSpec,Cw as generateDocsFromSpecs,IW as generateDataViewSpec,TA as generateDataViewRendererTemplate,f7 as generateCursorRulesFromParsedSpec,Xw as generateCursorRules,Db as generateCursorMcpConfig,jb as generateContractsrcConfig,gW as generateComponentTemplate,D7 as generateCliReport,Zw as generateClaudeMcpConfig,ZW as generateCapabilitySpec,Mw as generateArtifacts,RW as generateAppBlueprintSpec,Yw as generateAgentsGuide,OW as generateAgentSpec,AW as formatters,jT as formatWorkspaceInfo,NR as formatVerificationReport,UI as formatQuickstartPreview,dj as formatModuleLoadError,F as formatJson,mR as formatFiles,aJ as formatDoctorSummary,eJ as formatCheckResult,Fj as fix,x as findWorkspaceRoot,c as findPackageRoot,cy as findMetaRepoRoot,WT as findAllConfigFiles,wV as filterIssuesByType,jV as filterIssuesBySeverity,Ej as features,Ew as extractSpecReferences,yL as extractContracts,kR as exportSpecForLLM,g6 as exportOpenApi,kO as exportGraphAsDot,aW as ensurePackageScaffold,cA as discoverSpecs,h$ as discoverSpecFiles,pA as discoverLayers,A0 as discoverImplementationsForSpec,NU as discoverAllImplementations,Fw as determineStatus,Y5 as detectRepositoryType,e$ as detectPackageManager,Mz as deleteSpec,A$ as deepMergePreserve,Dn as deepMergeOverwrite,IA as cursorCLIAdapter,nM as createWorkspaceStateCacheStorage,P5 as createWorkspaceRegistry,gX as createVerifyService,ZM as createVerificationCacheService,zz as createSpecCreator,Sw as createSetupNextSteps,Qw as createSetupGitignorePatterns,II as createRegeneratorService,E0 as createQuickAIReview,rA as createPackageTargetSpecSource,vy as createNoopLoggerAdapter,gy as createNodeWatcherAdapter,Ny as createNodeGitAdapter,Ey as createNodeFsAdapter,Iy as createNodeAiAdapter,M3 as createNodeAdapters,bM as createInMemoryCacheStorage,sx as createFileSystemCacheStorage,x9 as createEmptyLayerInventory,Fy as createConsoleLoggerAdapter,v3 as createBunFsAdapter,w9 as createBuilderWorkspaceId,G8 as createAgentGuideService,zj as connect,F1 as computeContentHash,Dz as compareSpecs,RK as cleanArtifacts,LA as claudeCodeAdapter,v1 as cacheKeyToString,wb as buildSpec,dA as analyzeWorkspaceDocBlocks,n0 as analyzeIntegrity,jR as analyzeGap,nw as analyzeDeps,q8 as agentGuideService,Xn as agentAdapters,Zn as adoption,xI as addToRegistry,tR as __moduleLoaderInternals,D1 as WorkspaceStateCacheStorage,kH as WorkspaceBundle,D0 as VerifyService,g1 as VerificationCacheService,KB as VALID_AUDIENCES,z2 as TestGeneratorService,Rj as SpecCreatorService,JA as SimpleAgent,mw as SETUP_TARGET_LABELS,Ww as SETUP_PRESET_LABELS,ww as SETUP_PRESET_DESCRIPTIONS,Eb as SETUP_GITIGNORE_PATTERNS,YZ as RuleSyncService,K0 as RegistryClient,f5 as PrActionService,OA as OpenAICodexAgent,ej as MINIMAL_DEPENDENCIES,T1 as InMemoryCacheStorage,CA as GenericMCPAdapter,E1 as FileSystemCacheStorage,jZ as FULL_DEPENDENCIES,k5 as DriftActionService,q$ as DEFAULT_SPEC_PATTERNS,v$ as DEFAULT_FS_IGNORES,N1 as DEFAULT_CACHE_CONFIG,RA as CursorCLIAdapter,qA as CursorAgent,GA as ClaudeCodeAgent,zA as ClaudeCodeAdapter,VZ as CONTRACTSPEC_USAGE_BLOCK_START,KZ as CONTRACTSPEC_USAGE_BLOCK_END,GZ as CONTRACTSPEC_AGENTS_BLOCK_START,qZ as CONTRACTSPEC_AGENTS_BLOCK_END,VK as CI_CHECK_CATEGORY_LABELS,zw as CHECK_CATEGORY_LABELS,UA as AgentOrchestrator,MA as AgentGuideService,Mb as ALL_SETUP_TARGETS,yw as ALL_SETUP_PRESETS,UK as ALL_CI_CHECK_CATEGORIES,_w as ALL_CHECK_CATEGORIES,Y0 as AIGenerator};
|