@contractspec/bundle.workspace 4.5.0 → 4.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundles/WorkspaceBundle.d.ts +34 -0
- package/dist/contracts/operations/init.operation.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +634 -539
- package/dist/node/index.js +634 -539
- package/dist/services/index.d.ts +1 -0
- package/dist/services/package-declarations/helpers.d.ts +13 -0
- package/dist/services/package-declarations/index.d.ts +5 -0
- package/dist/services/package-declarations/inventory.d.ts +4 -0
- package/dist/services/package-declarations/render.d.ts +41 -0
- package/dist/services/package-declarations/sync.d.ts +8 -0
- package/dist/services/package-declarations/sync.test.d.ts +1 -0
- package/dist/services/package-declarations/types.d.ts +48 -0
- package/dist/services/setup/setup-service.d.ts +17 -2
- package/dist/services/test/test-generator-service.d.ts +5 -1
- package/dist/services/workspace-info.d.ts +4 -1
- package/package.json +13 -13
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)){if(!
|
|
4
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
5
|
-
`).map((
|
|
2
|
+
var HB=Object.defineProperty;var qB=($)=>$;function OB($,b){this[$]=qB.bind(null,b)}var f=($,b)=>{for(var n in b)HB($,n,{get:b[n],enumerable:!0,configurable:!0,set:OB.bind(b,n)})};var _y=($,b)=>()=>($&&(b=$($=0)),b);var F$=import.meta.require;import{ContractsrcSchema as H8,DEFAULT_CONTRACTSRC as fn}from"@contractspec/lib.contracts-spec/workspace-config";async function P($,b){let n=$.join(b??".",".contractsrc.json");if(!await $.exists(n))return fn;try{let m=await $.readFile(n),y=JSON.parse(m),W=H8.safeParse(y);return{...fn,...W.data,conventions:{...fn.conventions,...W.data?.conventions||{}}}}catch{return fn}}function tW($){switch($){case"claude":return process.env.ANTHROPIC_API_KEY;case"openai":return process.env.OPENAI_API_KEY;case"custom":return process.env.CONTRACTSPEC_LLM_API_KEY;case"ollama":return;default:return}}var $$=()=>{};var Jj={};f(Jj,{AIGenerator:()=>GA});import{createProvider as Y6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as G6,buildEventSpecPrompt as H6,buildFormPrompt as q6,buildHandlerPrompt as O6,buildOperationSpecPrompt as V6,buildPresentationSpecPrompt as J6,buildTestPrompt as U6,getCodeGenSystemPrompt as tb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Mm,generateText as YA,streamText as K6}from"ai";import*as R from"zod";class GA{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||tW(this.config.aiProvider),n={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return Y6(n).getModel()}async generateOperationSpec($,b){let n=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.operation"'),version:R.number().int().positive().default(1),description:R.string().describe("Clear, concise summary"),goal:R.string().describe("Business purpose"),context:R.string().describe("Background and constraints"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).describe("Team/person owners with @ prefix"),tags:R.array(R.string()).describe("Categorization tags"),auth:R.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:R.string().describe("Description of input structure"),outputShape:R.string().describe("Description of output structure"),flags:R.array(R.string()).describe("Feature flags").default([]),possibleEvents:R.array(R.string()).describe("Events this may emit").default([]),analytics:R.array(R.string()).describe("Analytics events to track").default([])}),m=V6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateEventSpec($){let b=this.getModel(),n=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),A=H6($);return(await Mm({model:b,schema:n,prompt:A,system:Em()})).object}async generatePresentationSpec($,b){let n=this.getModel(),A=R.object({name:R.string(),version:R.number().int().positive().default(1),description:R.string(),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),componentKey:R.string().optional(),propsShape:R.string().optional(),content:R.string().optional(),mimeType:R.string().optional(),dataShape:R.string().optional()}),m=J6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateHandler($){let b=this.getModel();return(await YA({model:b,prompt:O6($),system:tb()})).text}async generateComponent($){let b=this.getModel();return(await YA({model:b,prompt:G6($),system:tb()})).text}async generateForm($){let b=this.getModel();return(await YA({model:b,prompt:q6($),system:tb()})).text}async generateTests($,b,n){let A=this.getModel();return(await YA({model:A,prompt:U6($,b,n),system:tb()})).text}async streamCodeGeneration($,b){let n=this.getModel(),A=await K6({model:n,prompt:$,system:tb()}),m="";for await(let y of A.textStream)m+=y,b(y);return m}}var HA=_y(()=>{$$()});import*as FT from"@contractspec/module.workspace";import{anthropic as VB}from"@ai-sdk/anthropic";import{openai as zy}from"@ai-sdk/openai";import{DEFAULT_MODELS as Ly}from"@contractspec/lib.ai-providers/models";import{generateObject as JB,generateText as UB,streamText as KB}from"ai";import{ollama as _B}from"ollama-ai-provider";function Ry($){return{async validateProvider(b){try{let{aiProvider:n}=b;if(n==="ollama")return{success:!0};if(n==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(n==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}},async generateText(b){let n=tA($);return{text:(await UB({model:n,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let A={model:tA($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await JB(A)).object}},async streamText(b,n){let A=tA($),m=await KB({model:A,prompt:b.prompt,system:b.systemPrompt}),y="";for await(let W of m.textStream)y+=W,n(W);return y}}}function tA($){let{aiProvider:b,aiModel:n,customEndpoint:A}=$;switch(b){case"claude":{let m=n??Ly.anthropic;return VB(m)}case"openai":{let m=n??Ly.openai;return zy(m)}case"ollama":return _B(n??"codellama");case"custom":{if(!A)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return zy(n??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as cB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as zB,stat as LB,mkdir as Cy,readFile as RB,rm as CB,writeFile as xB}from"fs/promises";import{basename as IB,dirname as xy,isAbsolute as EB,join as MB,relative as TB,resolve as Iy}from"path";import{glob as DB}from"glob";var q$=["**/*.command.ts","**/*.query.ts","**/*.operation.ts","**/*.operations.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts","**/*.capability.ts","**/*.workflow.ts","**/*.data-view.ts","**/*.form.ts","**/*.migration.ts","**/*.telemetry.ts","**/*.experiment.ts","**/*.app-config.ts","**/*.integration.ts","**/*.knowledge.ts","**/*.policy.ts","**/*.test-spec.ts","**/blueprint.ts","**/integration.ts","**/example.ts","**/bundles/*Bundle.ts","**/contracts/*.ts","**/contracts/index.ts","**/commands/*.ts","**/commands/index.ts","**/queries/*.ts","**/queries/index.ts","**/operations/*.ts","**/operations/index.ts","**/operations.ts","**/events.ts","**/presentations.ts","**/events/index.ts","**/presentations/index.ts","**/tests/*.ts","**/tests/*.test-spec.ts"],v$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function Ey($){let b=$??process.cwd();return{async exists(A){try{return await zB(n(A)),!0}catch{return!1}},async readFile(A){return RB(n(A),"utf-8")},async writeFile(A,m){let y=n(A),W=xy(y);await Cy(W,{recursive:!0}),await xB(y,m,"utf-8")},async remove(A){await CB(n(A),{recursive:!0,force:!0})},async stat(A){let m=await LB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await Cy(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return(await DB(m,{cwd:W,ignore:y,absolute:w})).sort((B,S)=>B.localeCompare(S))},resolve(...A){let[m,...y]=A;if(!m)return b;return Iy(b,m,...y)},dirname(A){return xy(A)},basename(A){return IB(A)},join(...A){return MB(...A)},relative(A,m){return TB(A,m)}};function n(A){return EB(A)?A:Iy(b,A)}}import{spawnSync as NB}from"child_process";import{existsSync as My,readFileSync as Ty}from"fs";import{access as FB}from"fs/promises";import{resolve as Xn}from"path";function Dy($){let b=$??process.cwd();return{async currentBranch(){try{let n=Ob(["rev-parse","--abbrev-ref","HEAD"],b).trim()||vB(b);return n.length>0?n:void 0}catch{return}},async showFile(n,A){try{let m=Ob(["show",`${n}:${A}`],b);if(m.length>0||n!=="HEAD")return m;return gB(b,A)??m}catch(m){throw Error(`Could not load ${A} at ref ${n}: ${m instanceof Error?m.message:String(m)}`)}},async clean(n){let A=[];if(n?.force)A.push("-f");if(n?.directories)A.push("-d");if(n?.ignored)A.push("-x");if(n?.dryRun)A.push("--dry-run");Ob(["clean",...A],b,{inherit:!0})},async isGitRepo(n){let A=n?Xn(b,n):b;try{return await FB(Xn(A,".git")),!0}catch{return!1}},async log(n){let A=n??"HEAD~10",m="--format=%H|||%s|||%an|||%aI";try{let y=Ob(["log",`${A}..HEAD`,"--format=%H|||%s|||%an|||%aI"],b),W=[];for(let w of y.trim().split(`
|
|
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,A){try{let m=A&&A.length>0?["--",...A]:[];return Ob(["diff","--name-only",`${n}...HEAD`,...m],b).trim().split(`
|
|
4
|
+
`).filter(Boolean)}catch{return[]}}}}function vB($){let b=Xn($,".git","HEAD");if(!My(b))return"";let n=Ty(b,"utf8").trim(),A="ref: refs/heads/";return n.startsWith(A)?n.slice(A.length):n}function gB($,b){let n=Xn($,b);if(!My(n))return;return Ty(n,"utf8")}function Ob($,b,n={}){let A=NB("git",$,{cwd:b,encoding:"utf-8",stdio:n.inherit?"inherit":["ignore","pipe","pipe"]});if(A.error)throw A.error;if(A.status!==0)throw Error(typeof A.stderr==="string"&&A.stderr.length>0?A.stderr:`git ${$.join(" ")} failed with status ${A.status??"unknown"}`);return typeof A.stdout==="string"?A.stdout:""}function Ny(){return{debug($,b){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,b??"")},info($,b){console.info(`[INFO] ${$}`,b??"")},warn($,b){console.warn(`[WARN] ${$}`,b??"")},error($,b){console.error(`[ERROR] ${$}`,b??"")},createProgress(){return PB()}}}function Fy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:kB}}function PB(){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 kB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import rB from"chokidar";var fB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function vy($){let b=$??process.cwd();return{watch(n){let A=[],m,y=rB.watch(n.pattern,{cwd:b,ignored:n.ignore??fB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),W=(w)=>{if(n.debounceMs&&n.debounceMs>0)clearTimeout(m),m=setTimeout(()=>{A.forEach((j)=>j(w))},n.debounceMs);else A.forEach((j)=>j(w))};return y.on("add",(w)=>{W({type:"add",path:w})}),y.on("change",(w)=>{W({type:"change",path:w})}),y.on("unlink",(w)=>{W({type:"unlink",path:w})}),{on(w){A.push(w)},async close(){clearTimeout(m),await y.close()}}}}}function YG($={}){let{cwd:b,config:n,silent:A}=$,m=n??cB;return{fs:Ey(b),git:Dy(b),watcher:vy(b),ai:Ry(m),logger:A?Fy():Ny()}}import{stat as hB,mkdir as dB}from"fs/promises";import{basename as uB,dirname as oB,isAbsolute as iB,join as tB,relative as lB,resolve as gy}from"path";import{glob as pB}from"glob";function JG($){let b=$??process.cwd();return{async exists(A){let m=Bun.file(n(A));try{return await m.exists(),!0}catch{return!1}},async readFile(A){return Bun.file(n(A)).text()},async writeFile(A,m){let y=n(A);await Bun.write(y,m)},async remove(A){await Bun.file(n(A)).delete()},async stat(A){let m=await hB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await dB(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return await pB(m,{cwd:W,ignore:y,absolute:w})},resolve(...A){let[m,...y]=A;if(!m)return b;return gy(b,m,...y)},dirname(A){return oB(A)},basename(A){return uB(A)},join(...A){return tB(...A)},relative(A,m){return lB(A,m)}};function n(A){return iB(A)?A:gy(b,A)}}import{existsSync as u,readFileSync as z$}from"fs";import{tmpdir as aB}from"os";import{dirname as lA,isAbsolute as eB,join as d,relative as sB,resolve as p$}from"path";var Py={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},ky=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function $S($,b){let n=sB(b,$);return n===""||!n.startsWith("..")&&!eB(n)}function pA($){let b=p$($),n=p$(aB());return $S(b,n)?n:void 0}function c($=process.cwd()){let b=p$($),n=pA($);while(!0){if(u(d(b,"package.json")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return $}function I($=process.cwd()){let b=p$($),n=null,A=pA($);while(!0){for(let W of ky)if(u(d(b,W)))return b;let m=d(b,"package.json");if(u(m)){n=b;try{if(JSON.parse(z$(m,"utf-8")).workspaces)return b}catch{}}for(let W of Object.keys(Py))if(u(d(b,W)))return b;let y=lA(b);if(y===b||b===A)break;b=y}return n??$}function a$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let A of b){let m=Object.entries(Py).filter(([,y])=>y===A);for(let[y]of m)if(u(d($,y)))return A}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(A.packageManager){let m=A.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(m)return m[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Vb($=process.cwd()){for(let n of ky)if(u(d($,n)))return!0;let b=d($,"package.json");if(u(b))try{if(JSON.parse(z$(b,"utf-8")).workspaces)return!0}catch{}return!1}function bS($){let b=d($,"pnpm-workspace.yaml");if(u(b))try{let m=z$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(m?.[1])return m[1].split(`
|
|
5
|
+
`).map((W)=>W.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(Array.isArray(A.workspaces))return A.workspaces;if(A.workspaces?.packages&&Array.isArray(A.workspaces.packages))return A.workspaces.packages}catch{}return}function g$($){let b=d($,"package.json");if(u(b))try{return JSON.parse(z$(b,"utf-8")).name}catch{}return}function ry($){let b=d($,".gitmodules");if(!u(b))return[];try{let n=z$(b,"utf-8"),A=[],m=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,y;while((y=m.exec(n))!==null){let[,W,w,j]=y;if(W&&w&&j){let B=d($,w),S=u(d(B,"package.json"))&&nS(B);A.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return A}catch{return[]}}function nS($){let b=d($,"package.json");if(u(b))try{let n=JSON.parse(z$(b,"utf-8"));return Boolean(n.workspaces)}catch{}return u(d($,"pnpm-workspace.yaml"))}function fy($){let b=p$($),n=pA($);while(!0){if(u(d(b,".gitmodules")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return}function AS($){let b=fy($);if(!b)return;let n=ry(b);if(n.length===0)return;let A=p$($),m=n.find((y)=>A.startsWith(y.absolutePath));return{root:b,submodules:n,activeSubmodule:m}}function mS($,b){let n=fy($);if(n){if(ry(n).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function cy($=process.cwd()){let b=c($),n=I($),A=a$(n),m=Vb(n),y=m?bS(n):void 0,W=g$(b),w=mS($,m),j=w==="meta-repo"?AS($):void 0;return{packageManager:A,workspaceRoot:n,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function LG($,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 RG($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function hy($,b=!1){let n=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${n}`.trim();case"pnpm":return`pnpm add ${n}`.trim();case"yarn":return`yarn add ${n}`.trim();case"npm":return`npm install ${n}`.trim()}}import{anthropic as dy}from"@ai-sdk/anthropic";import{generateText as uy}from"ai";class Yn{name="claude-code";apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set. Claude Code agent requires API access."]};try{let b=dy("claude-3-7-sonnet-20250219"),n=this.buildSystemPrompt($),A=this.buildUserPrompt($),m=await uy({model:b,prompt:A,system:n,temperature:0.2});return{success:!0,code:this.extractCode(m.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:m.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let b=dy("claude-3-7-sonnet-20250219"),n=`
|
|
6
6
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
7
7
|
|
|
8
8
|
SPECIFICATION:
|
|
@@ -31,7 +31,7 @@ Provide a structured validation report:
|
|
|
31
31
|
- Are there any missing edge cases?
|
|
32
32
|
|
|
33
33
|
Be thorough and precise. Use a critical but constructive tone.
|
|
34
|
-
`,
|
|
34
|
+
`,A=await uy({model:b,prompt:n,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),suggestions:this.extractSuggestions(A.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
35
35
|
|
|
36
36
|
Your code is:
|
|
37
37
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -74,10 +74,10 @@ Spec:
|
|
|
74
74
|
${$.specCode}
|
|
75
75
|
|
|
76
76
|
Code:
|
|
77
|
-
${$.existingCode}`};return 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
|
|
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"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
78
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("error")||m.includes("bug")||m.includes("incorrect")||m.includes("missing"))b.push(A.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],n=$.split(`
|
|
79
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("warning")||m.includes("should")||m.includes("consider"))b.push(A.trim())}return b}extractSuggestions($){let b=[],n=$.split(`
|
|
80
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("suggest")||m.includes("recommend")||m.includes("could")||m.includes("improvement"))b.push(A.trim())}return b}}import{spawn as yS}from"child_process";import{existsSync as oy}from"fs";import{mkdir as iy,readFile as WS,rm as wS,writeFile as Y$}from"fs/promises";import{homedir as aA,tmpdir as ty}from"os";import{join as o}from"path";class Gn{name="cursor";cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||"3000",this.detectEnvironment()}canHandle($){return this.isCursorAvailable()}async generate($){try{let b=o(ty(),`cursor-agent-${Date.now()}`);await iy(b,{recursive:!0});let n=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=o(ty(),`cursor-validate-${Date.now()}`);await iy(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let n=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",o(aA(),".cursor","cursor"),o(aA(),"AppData","Local","Programs","cursor","Cursor.exe"),o(aA(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let b of $)if(b.includes("cursor")||b.includes("Cursor")||b.includes("windsurf")||b.includes("Windsurf"))try{if(oy(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let n=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let A of n)try{let m=await A.fn();if(m.success)return m}catch(m){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,b){if(!this.cursorPath)throw Error("Cursor executable not found");let n=o(b,"spec.ts"),A=o(b,"output.ts"),m=o(b,"INSTRUCTIONS.md");if(await Y$(n,$.specCode),await Y$(m,this.buildDetailedPrompt($)),$.existingCode)await Y$(o(b,"existing.ts"),$.existingCode);return new Promise((y,W)=>{let w=["--wait","--new-window",b],j=yS(this.cursorPath,w,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";j.stdout?.on("data",(Q)=>{B+=Q.toString()}),j.stderr?.on("data",(Q)=>{S+=Q.toString()}),j.on("error",(Q)=>{W(Q)}),j.on("close",async(Q)=>{if(oy(A))try{let Z=await WS(A,"utf-8");y({success:!0,code:Z,metadata:{agentMode:"cursor",method:"cli",exitCode:Q}})}catch(Z){W(Error("Failed to read generated output"))}else W(Error(`Cursor CLI exited with code ${Q}. No output generated.`))}),setTimeout(()=>{j.kill(),W(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let n=o(b,"SPECIFICATION.ts"),A=o(b,"INSTRUCTIONS.md"),m=o(b,"template.ts");return await Y$(n,$.specCode),await Y$(A,this.buildDetailedPrompt($)),await Y$(m,this.generateTemplate($)),await Y$(o(b,"README.md"),`# Cursor Agent Workspace
|
|
81
81
|
|
|
82
82
|
This workspace was prepared for Cursor AI code generation.
|
|
83
83
|
|
|
@@ -93,18 +93,18 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
93
93
|
4. Save the result as output.ts
|
|
94
94
|
|
|
95
95
|
Workspace path: ${b}
|
|
96
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await
|
|
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$(o(b,"specification.ts"),$.specCode),await Y$(o(b,"implementation.ts"),$.existingCode||"// No implementation"),await Y$(o(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let n=[{path:"spec.ts",content:$.specCode}];if($.existingCode)n.push({path:"existing.ts",content:$.existingCode});return n}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
97
97
|
|
|
98
98
|
**Task Type:** ${$.type}
|
|
99
99
|
**Generated:** ${new Date().toISOString()}
|
|
100
100
|
|
|
101
|
-
`,
|
|
101
|
+
`,n=`## Specification
|
|
102
102
|
|
|
103
103
|
\`\`\`typescript
|
|
104
104
|
${$.specCode}
|
|
105
105
|
\`\`\`
|
|
106
106
|
|
|
107
|
-
`,
|
|
107
|
+
`,A={generate:`## Task: Generate Implementation
|
|
108
108
|
|
|
109
109
|
### Requirements:
|
|
110
110
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -197,7 +197,7 @@ ${$.existingCode||""}
|
|
|
197
197
|
- Enhance error messages
|
|
198
198
|
|
|
199
199
|
### Output Format:
|
|
200
|
-
Refactored code that maintains functionality while improving quality.`};return b+
|
|
200
|
+
Refactored code that maintains functionality while improving quality.`};return b+n+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
201
201
|
|
|
202
202
|
## Specification
|
|
203
203
|
\`\`\`typescript
|
|
@@ -255,7 +255,7 @@ export function implementation() {
|
|
|
255
255
|
// Implementation goes here
|
|
256
256
|
throw new Error('Not implemented');
|
|
257
257
|
}
|
|
258
|
-
`}async cleanupWorkDir($){try{await
|
|
258
|
+
`}async cleanupWorkDir($){try{await wS($,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}}import{openai as ly}from"@ai-sdk/openai";import{generateText as py}from"ai";class Hn{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let n=this.isComplexTask($)?"o1":"gpt-5.4",A=ly(n),m=this.buildSystemPrompt($),y=this.buildUserPrompt($),W=await py({model:A,prompt:y,system:m,temperature:0.2});return{success:!0,code:this.extractCode(W.text),metadata:{model:n,agentMode:"openai-codex",usage:W.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=ly("gpt-5.4"),n=`
|
|
259
259
|
Review this code implementation against its specification.
|
|
260
260
|
|
|
261
261
|
SPECIFICATION:
|
|
@@ -275,7 +275,7 @@ Provide a detailed validation report including:
|
|
|
275
275
|
4. Recommendations for improvement
|
|
276
276
|
|
|
277
277
|
Format as a structured report.
|
|
278
|
-
`,
|
|
278
|
+
`,A=await py({model:b,prompt:n,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],n=($.specCode+($.existingCode||"")).toLowerCase();return b.some((A)=>n.includes(A))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
279
279
|
|
|
280
280
|
Generate production-quality code that is:
|
|
281
281
|
- Type-safe and well-typed
|
|
@@ -312,9 +312,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
312
312
|
${$.existingCode}
|
|
313
313
|
|
|
314
314
|
Spec:
|
|
315
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let 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
|
|
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"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
316
|
+
`);for(let A of n)if(A.toLowerCase().includes("error")||A.toLowerCase().includes("bug")||A.toLowerCase().includes("fails"))b.push(A.trim());return b}extractWarnings($){let b=[],n=$.split(`
|
|
317
|
+
`);for(let A of n)if(A.toLowerCase().includes("warning")||A.toLowerCase().includes("should")||A.toLowerCase().includes("consider"))b.push(A.trim());return b}}import P$ from"chalk";import SS from"ora";import{generateText as ay}from"ai";var A0={};f(A0,{getCodeGenSystemPrompt:()=>n0,buildTestPrompt:()=>b0,buildHandlerPrompt:()=>eA,buildFormPrompt:()=>$0,buildComponentPrompt:()=>sA});function eA($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
318
318
|
|
|
319
319
|
Here is the contract spec:
|
|
320
320
|
|
|
@@ -333,7 +333,7 @@ Generate a complete handler implementation that:
|
|
|
333
333
|
|
|
334
334
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
335
335
|
|
|
336
|
-
Return only the TypeScript code for the handler function.`}function
|
|
336
|
+
Return only the TypeScript code for the handler function.`}function sA($){return`You are a senior React developer creating a component for a presentation specification.
|
|
337
337
|
|
|
338
338
|
Here is the presentation spec:
|
|
339
339
|
|
|
@@ -352,7 +352,7 @@ Generate a complete React component that:
|
|
|
352
352
|
|
|
353
353
|
The component should follow Atomic Design principles and be reusable.
|
|
354
354
|
|
|
355
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
355
|
+
Return only the TypeScript/TSX code for the component.`}function $0($){return`You are a senior React developer creating a form component from a form specification.
|
|
356
356
|
|
|
357
357
|
Here is the form spec:
|
|
358
358
|
|
|
@@ -372,7 +372,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
372
372
|
|
|
373
373
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
374
374
|
|
|
375
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
375
|
+
Return only the TypeScript/TSX code for the form component.`}function b0($,b,n){return`You are a senior developer writing comprehensive tests.
|
|
376
376
|
|
|
377
377
|
Spec:
|
|
378
378
|
\`\`\`typescript
|
|
@@ -385,7 +385,7 @@ ${b}
|
|
|
385
385
|
\`\`\`
|
|
386
386
|
|
|
387
387
|
Generate complete test suite using Vitest that:
|
|
388
|
-
${
|
|
388
|
+
${n==="handler"?`
|
|
389
389
|
- Test all acceptance scenarios from the spec
|
|
390
390
|
- Test error cases defined in spec.io.errors
|
|
391
391
|
- Verify events are emitted correctly
|
|
@@ -399,7 +399,7 @@ ${A==="handler"?`
|
|
|
399
399
|
|
|
400
400
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
401
401
|
|
|
402
|
-
Return only the TypeScript test code.`}function
|
|
402
|
+
Return only the TypeScript test code.`}function n0(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
403
403
|
- Type-safe API design
|
|
404
404
|
- React and modern hooks
|
|
405
405
|
- Test-driven development
|
|
@@ -413,7 +413,7 @@ Generate production-ready code that is:
|
|
|
413
413
|
- Defensive and error-safe
|
|
414
414
|
- Easy to maintain and extend
|
|
415
415
|
|
|
416
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
416
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as jS}from"@contractspec/lib.ai-providers";function m0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return jS(b)}class qn{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=m0(this.config),n=this.buildPrompt($),A=await ay({model:b,prompt:n,system:n0()});return{success:!0,code:A.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=m0(this.config),n=`
|
|
417
417
|
Review the following implementation against its specification.
|
|
418
418
|
|
|
419
419
|
Specification:
|
|
@@ -427,15 +427,15 @@ Provide a detailed validation report:
|
|
|
427
427
|
2. Are there any missing features?
|
|
428
428
|
3. Are there any bugs or issues?
|
|
429
429
|
4. Suggestions for improvement
|
|
430
|
-
`,
|
|
431
|
-
${$.specCode}`;case"test":return
|
|
432
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
430
|
+
`,A=await ay({model:b,prompt:n,system:"You are a code review expert. Provide thorough, constructive feedback."}),m=A.text.toLowerCase().includes("error")||A.text.toLowerCase().includes("missing")||A.text.toLowerCase().includes("incorrect");return{success:!m,code:A.text,warnings:m?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return eA($.specCode);else if($.specCode.includes(".presentation."))return sA($.specCode);else if($.specCode.includes(".form."))return $0($.specCode);return`Generate implementation for:
|
|
431
|
+
${$.specCode}`;case"test":return b0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
432
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as BS}from"@contractspec/lib.ai-agent/agent/unified-agent";class y0{name;agent;constructor($,b,n={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=BS(n,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),n=await this.agent.run(b);return{success:!0,code:n.text,metadata:{finishReason:n.finishReason,usage:n.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
433
433
|
${$.specCode}
|
|
434
434
|
|
|
435
435
|
`;if($.existingCode)b+=`Existing Code:
|
|
436
436
|
${$.existingCode}
|
|
437
437
|
|
|
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
|
|
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 On{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new qn($),n=new Gn,A=new Yn,m=new Hn;this.agents.set("simple",b),this.agents.set("cursor",n),this.agents.set("claude-code",A),this.agents.set("openai-codex",m),this.defaultAgent=b,this.agents.set("opencode-sdk",new y0("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),n=this.agents.get(b);if(!n)return console.log(P$.yellow(`\u26A0\uFE0F Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!n.canHandle($))return console.log(P$.yellow(`\u26A0\uFE0F Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let A=SS(`Executing with ${b} agent...`).start();try{let m=$.type==="validate"?await n.validate($):await n.generate($);if(m.success)return A.succeed(P$.green(`${b} agent completed successfully`)),m;A.warn(P$.yellow(`${b} agent failed, trying fallback...`));let y=this.getFallbackMode(b);if(y&&y!==b){let W=this.agents.get(y);if(W&&W.canHandle($))return $.type==="validate"?await W.validate($):await W.generate($)}return A.info(P$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(m){return A.fail(P$.red("Agent execution failed")),console.log(P$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,n]of this.agents){let A={type:"generate",specCode:"test"},m=n.canHandle(A);$.push({mode:b,available:m,reason:m?void 0:"Not configured or dependencies missing"})}return $}getAgentMode(){return this.config.agentMode||"simple"}getFallbackMode($){return{cursor:"claude-code","claude-agent-sdk":"claude-code","claude-code":"openai-codex","openai-codex":"simple",opencode:"opencode-sdk","opencode-sdk":"claude-code",simple:"simple"}[$]}}var ey={};f(ey,{specCreation:()=>W0,codeGeneration:()=>A0});var W0={};f(W0,{getSystemPrompt:()=>YS,buildPresentationSpecPrompt:()=>XS,buildOperationSpecPrompt:()=>QS,buildEventSpecPrompt:()=>ZS,addExampleContext:()=>GS});function QS($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
439
439
|
|
|
440
440
|
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
441
441
|
|
|
@@ -453,7 +453,7 @@ Create a complete contract specification following these guidelines:
|
|
|
453
453
|
8. **Feature Flags**: Any flags that gate this operation
|
|
454
454
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
455
455
|
|
|
456
|
-
Respond with a structured spec.`}function
|
|
456
|
+
Respond with a structured spec.`}function ZS($){return`You are a senior software architect creating an event specification.
|
|
457
457
|
|
|
458
458
|
User description: ${$}
|
|
459
459
|
|
|
@@ -467,7 +467,7 @@ Create a complete event specification following these guidelines:
|
|
|
467
467
|
|
|
468
468
|
Events represent things that have already happened and should use past tense.
|
|
469
469
|
|
|
470
|
-
Respond with a structured spec.`}function
|
|
470
|
+
Respond with a structured spec.`}function XS($,b){return`You are a senior software architect creating a presentation specification.
|
|
471
471
|
|
|
472
472
|
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
473
473
|
|
|
@@ -485,7 +485,7 @@ Create a complete presentation specification following these guidelines:
|
|
|
485
485
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
486
486
|
- Data structure description`}
|
|
487
487
|
|
|
488
|
-
Respond with a structured spec.`}function
|
|
488
|
+
Respond with a structured spec.`}function YS(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
489
489
|
|
|
490
490
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
491
491
|
|
|
@@ -495,7 +495,7 @@ Your specs are:
|
|
|
495
495
|
- Business-oriented (capturing the "why" not just "what")
|
|
496
496
|
- Designed for both humans and AI agents to understand
|
|
497
497
|
|
|
498
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
498
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function GS($,b){if(b.length===0)return $;return`${$}
|
|
499
499
|
|
|
500
500
|
Here are some good examples for reference:
|
|
501
501
|
|
|
@@ -503,29 +503,29 @@ ${b.join(`
|
|
|
503
503
|
|
|
504
504
|
`)}
|
|
505
505
|
|
|
506
|
-
Follow this structure and quality level.`}var
|
|
507
|
-
`)}function
|
|
506
|
+
Follow this structure and quality level.`}import{defineModuleBundle as HS}from"@contractspec/lib.surface-runtime/spec";var _3=HS({meta:{key:"bundles.workspace",version:"1.0.0",title:"Workspace",description:"Workspace utilities for monorepo development"},routes:[{routeId:"default",path:"/",defaultSurface:"main"}],surfaces:{main:{surfaceId:"main",kind:"workbench",title:"Workspace",slots:[],layouts:[],data:[],verification:{dimensions:{guidance:"Scaffolded guidance profile for Workspace.",density:"Scaffolded density profile for Workspace.",dataDepth:"Scaffolded data-depth profile for Workspace.",control:"Scaffolded control profile for Workspace.",media:"Scaffolded media profile for Workspace.",pace:"Scaffolded pace profile for Workspace.",narrative:"Scaffolded narrative profile for Workspace."}}}}});var bW={};f(bW,{sarifToJson:()=>KS,formatAsTextLines:()=>$W,formatAsText:()=>_S,formatAsSarif:()=>VS,formatAsJson:()=>qS});function qS($,b={}){let{pretty:n=!0,driftResult:A}=b,m=$.issues.map((S)=>({name:S.ruleId,status:S.severity==="error"?"fail":S.severity==="warning"?"warn":"pass",category:S.category,message:S.message,file:S.file,line:S.line,details:S.context})),y=$.categories.filter((S)=>S.passed).length,W=$.totalErrors,w=$.totalWarnings,j=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:m,categories:$.categories.map((S)=>({category:S.category,label:S.label,passed:S.passed,errors:S.errors,warnings:S.warnings,notes:S.notes,durationMs:S.durationMs})),drift:{status:A?.hasDrift?"detected":"none",files:A?.files??[]},summary:{pass:y,fail:W,warn:w,note:j,total:y+W+w+j,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return n?JSON.stringify(B,null,2):JSON.stringify(B)}var OS={"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 VS($,b={}){let{toolName:n="ContractSpec",toolVersion:A="1.0.0",toolUri:m="https://contractspec.io",repositoryUri:y,workingDirectory:W}=b,w=new Map,j=new Map,B=$.issues.filter((X)=>X.file);for(let X of B)if(!w.has(X.ruleId)){let Y=OS[X.ruleId]??{name:X.ruleId,description:`Rule: ${X.ruleId}`},G={id:X.ruleId,name:Y.name,shortDescription:{text:Y.description},defaultConfiguration:{level:sy(X.severity)}};if(Y.helpUri)G.helpUri=Y.helpUri;j.set(X.ruleId,w.size),w.set(X.ruleId,G)}let S=B.map((X)=>{let Y={ruleId:X.ruleId,ruleIndex:j.get(X.ruleId)??0,level:sy(X.severity),message:{text:X.message}},G={physicalLocation:{artifactLocation:{uri:JS(X.file),uriBaseId:"%SRCROOT%"}}};if(X.line!==void 0)G.physicalLocation.region={startLine:X.line,startColumn:X.column??1,endLine:X.endLine??X.line,endColumn:X.endColumn};return Y.locations=[G],Y.partialFingerprints={primaryLocationLineHash:US(X)},Y}),Q=[];if(y)Q.push({repositoryUri:y,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:n,version:A,informationUri:m,rules:Array.from(w.values())}},results:S,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...W&&{workingDirectory:{uri:W}}}]};if(Q.length>0)Z.versionControlProvenance=Q;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[Z]}}function sy($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function JS($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function US($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function KS($){return JSON.stringify($,null,2)}function $W($,b={}){let n=[],{verbose:A=!1,showTiming:m=!0,groupByFile:y=!1}=b;if(n.push({text:"",style:"normal"}),n.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),n.push({text:"",style:"normal"}),$.commitSha||$.branch){let w=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");n.push({text:`Git: ${w}`,style:"muted"})}n.push({text:"",style:"normal"}),n.push({text:"Check Results:",style:"bold"});for(let w of $.categories){let j=w.passed?"\u2713":"\u2717",B=w.passed?"success":"error",S=zS(w),Q=m?` (${w.durationMs}ms)`:"";n.push({text:` ${j} ${w.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(n.push({text:"",style:"normal"}),n.push({text:"Issues:",style:"bold"}),y){let w=LS($.issues);for(let[j,B]of w){n.push({text:"",style:"normal"}),n.push({text:` ${j||"(no file)"}`,style:"bold",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}else{let w=$.issues.filter((S)=>S.severity==="error"),j=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(w.length>0){n.push({text:"",style:"normal"}),n.push({text:" Errors:",style:"error",indent:1});for(let S of w)n.push(...Vn(S,A,2))}if(j.length>0){n.push({text:"",style:"normal"}),n.push({text:" Warnings:",style:"warning",indent:1});for(let S of j)n.push(...Vn(S,A,2))}if(B.length>0&&A){n.push({text:"",style:"normal"}),n.push({text:" Notes:",style:"muted",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}n.push({text:"",style:"normal"}),n.push({text:"\u2500".repeat(50),style:"muted"});let W=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&A?`${$.totalNotes} note(s)`:null].filter(Boolean);if(W.length>0)n.push({text:`Found: ${W.join(", ")}`,style:$.success?"warning":"error"});if(m)n.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(n.push({text:"",style:"normal"}),$.success)n.push({text:"\u2705 All CI checks passed!",style:"success"});else n.push({text:"\u274C CI checks failed",style:"error"});return n.push({text:"",style:"normal"}),n}function _S($,b={}){return $W($,b).map((A)=>" ".repeat(A.indent??0)+A.text).join(`
|
|
507
|
+
`)}function zS($){let b=[];if($.errors>0)b.push(`${$.errors} error(s)`);if($.warnings>0)b.push(`${$.warnings} warning(s)`);if(b.length===0)return"passed";return b.join(", ")}function Vn($,b,n){let A=[],m=$.severity==="error"?"\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(A.push({text:W,style:y,indent:n}),b&&$.context){let w=JSON.stringify($.context);if(w!=="{}")A.push({text:`Context: ${w}`,style:"muted",indent:n+1})}return A}function LS($){let b=new Map;for(let n of $){let A=n.file??"";if(!b.has(A))b.set(A,[]);let m=b.get(A);if(m)m.push(n)}return new Map([...b.entries()].sort(([n],[A])=>n.localeCompare(A)))}import{OperationSpecRegistry as RS}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as CS}from"@contractspec/lib.contracts-spec/operations/report";function xS(){let $=new RS;return CS($),$}var k3=xS();class IS{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let n=$.drift?.status==="fail",A=!1;if(n&&b==="fail")A=!0;return{driftDetected:n,shouldFail:A}}}function ES($){if(!$)return"\u2014";let b=new Date($),A=new Date().getTime()-b.getTime(),m=Math.floor(A/86400000);if(m<1)return"today";if(m===1)return"yesterday";return`${m} days ago`}class MS{collectChanges($,b,n){if($){let A=$.endsWith("/")?$:`${$}/`;return n.filter((m)=>m.startsWith(A))}if(b){let A=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return n.filter((m)=>A.test(m))}return n}detectDrift($){let b=$.map((n)=>n.slice(3)).filter((n)=>n&&n.trim().length>0).filter((n)=>n!==".contractspec-ci"&&!n.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},n=b.breaking||0,A=b.nonBreaking||0,m=b.total;if(m===void 0)m=n+A;let y=$?.breaking||!1,W="unknown";if($){if(y||n>0)W="breaking",y=!0;else if(A>0)W="non-breaking";else if(m===0)W="no-impact"}return{status:W,breaking:y,breakingCount:n,nonBreakingCount:A,total:m||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,n=this.deriveImpactStatus($.impactJson),A={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:n.status,breaking:n.breakingCount,nonBreaking:n.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(A.validation?.status==="fail")A.nextSteps?.push("Fix validation errors and rerun the workflow.");if(A.risk?.status==="breaking")A.nextSteps?.push("Review breaking changes and plan a migration.");if(A.risk?.status==="unknown")A.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(A.drift?.status==="fail")A.nextSteps?.push("Run the generate command locally and commit drift fixes.");let m=this.finalizeResults(A,$.failOn);if(m.shouldFail)A.nextSteps?.unshift(`CI failed: ${m.failReasons.join(", ")} (fail_on=${$.failOn}).`);return A}finalizeResults($,b){let n=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,A=$.drift?.status==="fail",m=$.validation?.status==="fail",y=$.risk?.status==="unknown",W=[],w=!1;if(b!=="never"){if(b==="breaking"){if(n)W.push("breaking changes detected");if(y)W.push("impact status unknown")}else if(b==="drift"){if(A)W.push("drift detected");if(y)W.push("impact status unknown")}else if(b==="any"){if(n)W.push("breaking changes detected");if(A)W.push("drift detected");if(m)W.push("validation failed");if(y)W.push("impact status unknown")}else W.push(`invalid fail_on value (${b})`);if(W.length>0)w=!0}return{driftDetected:A,breakingChangeDetected:n,validationFailed:m,shouldFail:w,failReasons:W}}generateReportMarkdown($,b){let n=(j,B=60000)=>{if(j.length<=B)return j;return`${j.slice(0,B)}
|
|
508
508
|
|
|
509
|
-
*(output truncated)*`},
|
|
510
|
-
`)},n
|
|
509
|
+
*(output truncated)*`},A=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
510
|
+
`)},m=n($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),y=n($.validation?.outputPath?b($.validation.outputPath):""),W=$.drift?.files??[],w=[];if(w.push("## ContractSpec Report"),w.push(""),$.contracts&&$.contracts.length>0){w.push("### Overall verification status"),w.push(""),w.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),w.push("| --- | --- | --- | --- | --- |");for(let j of $.contracts){let B=j.lastVerifiedSha??"\u2014",S=ES(j.lastVerifiedDate),Q=j.surfaces.join(", ");w.push(`| ${j.name} | ${S} | ${j.driftMismatches} | ${Q} | ${B} |`)}w.push("")}if(w.push("### 1) What changed"),$.whatChanged?.summary)w.push($.whatChanged.summary);else w.push("No contract changes detected.");if(m.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Contract view (product)</summary>"),w.push(""),w.push(m),w.push(""),w.push("</details>");if(w.push(""),w.push("### 2) Risk classification"),$.risk?.status){let j=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);w.push(j.join(" | "))}else w.push("Impact analysis unavailable.");if(w.push(""),w.push("### 3) Validation results"),$.validation?.status){if(w.push(`Status: ${$.validation.status}`),y.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Validation output</summary>"),w.push(""),w.push(y),w.push(""),w.push("</details>")}else w.push("Validation step not run.");if(w.push(""),w.push("### 4) Drift results"),$.drift?.status){if(w.push(`Status: ${$.drift.status}`),W.length>0)w.push(""),w.push("<details>"),w.push("<summary>Drifted files</summary>"),w.push(""),w.push(A(W)),w.push(""),w.push("</details>")}else w.push("Drift check not run.");if(w.push(""),w.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)w.push(A($.nextSteps));else w.push("- No action required.");return`${w.join(`
|
|
511
511
|
`)}
|
|
512
|
-
`}}var s0={};P(s0,{uniqueTokens:()=>N$,tokenize:()=>i$,syncAdoptionCatalog:()=>J5,scanWorkspaceAdoptionCandidates:()=>p0,resolveAdoptionWorkspace:()=>l$,resolveAdoption:()=>Xb,overlap:()=>ZA,normalizeText:()=>gW,inferFamilyFromPath:()=>e0,hasLocalShadcnRegistry:()=>a0,getContractSpecAdoptionCatalog:()=>QA,createAdoptionCatalogDocument:()=>i0,candidateTokens:()=>l0});function E($,b,A,m,n,W,w,j,y={}){return{id:$,source:"contractspec",packageRef:b,family:A,packageKind:m,title:y.title??b,description:j,capabilityTags:W,preferredUseCases:w,avoidWhen:y.avoidWhen,platforms:y.platforms,replacementImportHints:y.replacementImportHints,resolutionPriority:n,runtimes:y.runtimes}}var TW=[E("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),E("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),E("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),E("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),E("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var DW=[E("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),E("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),E("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),E("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),E("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),E("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),E("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),E("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var NW=[E("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),E("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),E("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),E("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),E("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),E("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),E("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),E("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),E("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var FW=[E("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),E("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),E("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),E("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),E("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),E("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var vW=[E("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),E("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),E("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var sB=[...vW,...TW,...DW,...NW,...FW];function QA(){return[...sB].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function i0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:QA()}}import{DEFAULT_CONTRACTSRC as y5}from"@contractspec/lib.contracts-spec/workspace-config";function gW($){return $.toLowerCase().trim()}function i$($){return gW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function N$($){return[...new Set($.flatMap((b)=>i$(b)))]}function l0($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return N$(b)}function ZA($,b){let A=new Set(b);return $.filter((m)=>A.has(m)).length}import{resolve as $5}from"path";import{ContractsrcSchema as b5,DEFAULT_CONTRACTSRC as t0}from"@contractspec/lib.contracts-spec/workspace-config";async function l$($,b={}){let A=$5(b.cwd??process.cwd()),m=b.workspaceRoot??M(A),n=b.packageRoot??r(A),W=b.config?PW(t0,b.config):await A5($,m,n);return{adoption:W.connect?.adoption??t0.connect.adoption,config:W,cwd:A,packageRoot:n,workspaceRoot:m}}async function A5($,b,A){let m=t0;if(b!==A)m=await kW($,m,$.join(b,".contractsrc.json"));return kW($,m,$.join(A,".contractsrc.json"))}async function kW($,b,A){if(!await $.exists(A))return b;try{let m=JSON.parse(await $.readFile(A)),n=b5.safeParse(m);if(!n.success)return b;return PW(b,n.data)}catch{return b}}function PW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var m5=["package.json","packages/*/package.json"];async function p0($,b){let[A,m]=await Promise.all([n5($,b),W5($,b)]);return{fileCandidates:m,packageCandidates:A}}async function a0($,b){let A=$.join(b.workspaceRoot,"components.json");if(await $.exists(A))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function n5($,b){let A=await $.glob({patterns:m5,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),m=[];for(let n of A)try{let W=JSON.parse(await $.readFile($.join(b.workspaceRoot,n))),w=e0(n);if(!w)continue;let j=W.name??$.dirname(n);m.push({id:`workspace.package.${j}`,source:"workspace",family:w,title:j,description:W.description??`Local reusable package at ${n}.`,packageKind:j5(n),packageRef:j,capabilityTags:N$([j,n]),preferredUseCases:[n],resolutionPriority:120})}catch{continue}return m}async function W5($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((m)=>{let n=e0(m);if(!n)return[];let W=m.split("/").pop()?.replace(/\.[^.]+$/,"")??m;return[{id:`workspace.file.${m}`,source:"workspace",family:n,title:W,description:`Local reusable source at ${m}.`,filePath:m,capabilityTags:i$(m),preferredUseCases:[m],resolutionPriority:w5(n,m)}]})}function e0($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function w5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function j5($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Xb($,b){let A=await l$($.fs,b),m=q5(b),n=N$([m,b.symbol??"",...b.paths??[]]),W=await p0($.fs,A),w=await O5($,A),j=await a0($.fs,A),y=B5(A,n,b,[...W.packageCandidates,...W.fileCandidates,...w,...V5(b.family,b.platform,j)]),B=y[0]??null,S=y.length>1&&B!=null&&B.candidate.source===y[1].candidate.source&&Math.abs(B.score-y[1].score)<=40,Q=X5(A,B,S,b.currentTarget);return{ambiguous:S,candidates:y,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:m,reason:H5(B,S),selected:B,verdict:Q}}function B5($,b,A,m){return m.filter((n)=>n.family===A.family&&Z5($,n.family)).filter((n)=>G5(n,A.platform)).map((n)=>S5(n,b,A.paths)).filter((n)=>n.score>40).sort((n,W)=>W.score-n.score).slice(0,8)}function S5($,b,A){let m=l0($),n=N$(A??[]),W=[],w=ZA(b,m)*25,j=ZA(n,m)*10;if(w>0)W.push("query overlap");if(j>0)W.push("path overlap");return{candidate:$,matchReasons:W,score:Q5($.source)+($.resolutionPriority??0)+w+j}}function Q5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function Z5($,b){return $.adoption.families?.[b]??!0}function G5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function X5($,b,A,m){let n=$.adoption.thresholds??y5.connect.adoption.thresholds;if(A)return n.ambiguous??"require_review";if(!b)return n.newImplementation??"require_review";if(b.candidate.source==="workspace")return Y5(b.candidate,m)?"permit":n.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return n.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return n.newImplementation??"require_review";return n.newExternalDependency??"require_review"}function Y5($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function H5($,b){if(b)return"Multiple similarly strong adoption candidates were found.";if(!$)return"No reusable workspace or ContractSpec candidate matched the request.";return`Selected ${$.candidate.source} candidate ${$.candidate.title}.`}function q5($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function O5($,b){let A=QA(),m=b.adoption.catalog?.overrideManifestPath;if(!m||!await $.fs.exists($.fs.join(b.workspaceRoot,m)))return A;try{let n=await $.fs.readFile($.fs.join(b.workspaceRoot,m)),W=JSON.parse(n);return[...A,...Array.isArray(W)?W:W.entries??[]]}catch{return A}}function V5($,b,A){if($==="ui"&&b==="web"&&A)return[t$("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[t$("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[t$("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[t$("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[t$("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[t$("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function t$($,b,A,m,n){return{id:$,source:"ecosystem",packageRef:A,family:b,packageKind:"primitive",title:m,description:m,capabilityTags:i$(m),preferredUseCases:[m],resolutionPriority:n}}async function J5($,b={}){let A=await l$($.fs,b),m=i0(),n=$.fs.join(A.workspaceRoot,A.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(n,`${JSON.stringify(m,null,2)}
|
|
513
|
-
`),{catalog:
|
|
512
|
+
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>sS,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>Un,normalizeText:()=>wW,inferFamilyFromPath:()=>Z0,hasLocalShadcnRegistry:()=>Q0,getContractSpecAdoptionCatalog:()=>Jn,createAdoptionCatalogDocument:()=>w0,candidateTokens:()=>j0});function x($,b,n,A,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:n,packageKind:A,title:j.title??b,description:w,capabilityTags:y,preferredUseCases:W,avoidWhen:j.avoidWhen,platforms:j.platforms,replacementImportHints:j.replacementImportHints,resolutionPriority:m,runtimes:j.runtimes}}var nW=[x("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),x("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),x("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),x("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),x("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var AW=[x("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),x("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),x("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),x("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),x("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),x("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),x("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),x("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var mW=[x("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),x("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),x("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),x("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),x("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),x("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),x("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),x("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),x("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var yW=[x("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),x("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),x("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),x("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),x("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),x("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var WW=[x("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),x("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),x("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var TS=[...WW,...nW,...AW,...mW,...yW];function Jn(){return[...TS].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function w0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:Jn()}}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 Un($,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=Un(b,A)*25,w=Un(m,A)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score: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=Jn(),A=b.adoption.catalog?.overrideManifestPath;if(!A||!await $.fs.exists($.fs.join(b.workspaceRoot,A)))return n;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,A)),y=JSON.parse(m);return[...n,...Array.isArray(y)?y:y.entries??[]]}catch{return n}}function 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:A,catalogPath:m}}import{AGENT_SYSTEM_PROMPTS as $5}from"@contractspec/lib.contracts-spec/llm";class Kn{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let n of $.fileStructure){let A=n.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";b.push(`${A} \`${n.path}\``),b.push(` ${n.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let n of $.steps){b.push(`### ${n.order}. ${n.title}`),b.push(""),b.push(n.description),b.push(""),b.push("**Acceptance Criteria:**");for(let A of n.acceptanceCriteria)b.push(`- [ ] ${A}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let n of $.constraints.security)b.push(`- \u26A0\uFE0F ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:$5["claude-code"],taskPrompt:b.join(`
|
|
514
514
|
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
515
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let
|
|
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
|
|
515
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let n=[],A=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let m of A){let y=$.matchAll(m);for(let W of y)if(W[1])n.push(W[1])}if(n.length>0)return{errors:n};return{code:$}}}var _n=new Kn;import{AGENT_SYSTEM_PROMPTS as b5}from"@contractspec/lib.contracts-spec/llm";class zn{agentType="cursor-cli";formatPlan($){let b=[];if(b.push(`# ${$.target.key}.v${$.target.version}`),b.push(""),b.push(`> ${$.context.goal}`),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push("");for(let A of $.fileStructure)b.push(`- ${A.type}: \`${A.path}\` - ${A.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let A of $.steps)b.push(`${A.order}. **${A.title}**: ${A.description}`);b.push("");let n=[...$.constraints.policy,...$.constraints.security.map((A)=>`\u26A0\uFE0F ${A}`)];if(n.length>0){b.push("## Constraints"),b.push("");for(let A of n)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((A)=>`\`${A}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:b5["cursor-cli"],taskPrompt:b.join(`
|
|
516
|
+
`)}}generateConfig($){let b=$.meta,n=[];if(n.push("---"),n.push(`description: Implementation rules for ${b.key}.v${b.version}`),n.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),n.push("alwaysApply: false"),n.push("---"),n.push(""),n.push(`# ${b.key} Implementation Rules`),n.push(""),n.push(`This ${b.kind} operation must follow the ContractSpec specification.`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Requirements"),n.push(""),n.push("1. Input/output types MUST match the spec schema exactly"),n.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)n.push("3. Events MUST be emitted as specified");if(n.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)n.push(`5. Idempotency: ${$.policy.idempotent}`);if(n.push(""),$.io.errors&&Object.keys($.io.errors).length>0){n.push("## Error Cases"),n.push("");for(let[A,m]of Object.entries($.io.errors))n.push(`- \`${A}\` (HTTP ${m.http??400}): ${m.when}`);n.push("")}if($.sideEffects?.emits?.length){n.push("## Events to Emit"),n.push("");for(let A of $.sideEffects.emits)if("ref"in A)n.push(`- \`${A.ref.key}.v${A.ref.version}\`: ${A.when}`);else n.push(`- \`${A.key}.v${A.version}\`: ${A.when}`);n.push("")}if($.policy.pii?.length){n.push("## PII Handling"),n.push(""),n.push("These fields contain PII and must be handled with care:");for(let A of $.policy.pii)n.push(`- \`${A}\``);n.push("")}if($.acceptance?.scenarios?.length){n.push("## Acceptance Scenarios"),n.push("");for(let A of $.acceptance.scenarios)n.push(`### ${A.key}`),n.push(`- Given: ${A.given.join("; ")}`),n.push(`- When: ${A.when.join("; ")}`),n.push(`- Then: ${A.then.join("; ")}`),n.push("")}return n.join(`
|
|
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 Ln=new zn;import{AGENT_SYSTEM_PROMPTS as n5}from"@contractspec/lib.contracts-spec/llm";class Rn{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let n of $.fileStructure)b.push(`| \`${n.path}\` | ${n.type} | ${n.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let n of $.steps)if(b.push(`### Step ${n.order}: ${n.title}`),b.push(""),b.push(n.description),b.push(""),n.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let A of n.acceptanceCriteria)b.push(`- ${A}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let n of $.constraints.security)b.push(`- ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),{agent:"generic-mcp",systemPrompt:n5["generic-mcp"],taskPrompt:b.join(`
|
|
518
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,n=[];return n.push(`# ${b.key} v${b.version}`),n.push(""),n.push(`**Type:** ${b.kind}`),n.push(`**Stability:** ${b.stability}`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Description"),n.push(""),n.push(b.description),n.push(""),n.join(`
|
|
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 n=JSON.parse($);if(typeof n.code==="string")return{code:n.code};if(typeof n.errors==="object")return{errors:Array.isArray(n.errors)?n.errors:[String(n.errors)]}}catch{}return{code:$}}}var Cn=new Rn;var Y0={"claude-code":_n,"cursor-cli":Ln,"generic-mcp":Cn};function Ub($){let b=Y0[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function G0(){return Object.keys(Y0)}import{featureToMarkdown as H0,generateImplementationPlan as SW,operationSpecToAgentPrompt as A5,operationSpecToFullMarkdown as m5}from"@contractspec/lib.contracts-spec/llm";var y5={defaultAgent:"generic-mcp",verbose:!1};class xn{config;constructor($={}){this.config={...y5,...$}}generateGuide($,b={}){let n=b.agent??this.config.defaultAgent,A=Ub(n),m=SW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),y=A.formatPlan(m),W=m5($);return{plan:m,prompt:y,markdown:W}}generateFeatureGuide($,b,n={}){let A=n.agent??this.config.defaultAgent,m=Ub(A),y=$.operations?.[0],W=y?b.specs?.get(y.key,y.version):void 0,w;if(W)w=SW(W,{projectRoot:this.config.projectRoot}),w.target={type:"feature",key:$.meta.key,version:"1.0.0"},w.context.goal=$.meta.description??w.context.goal;else w={target:{type:"feature",key:$.meta.key,version:"1.0.0"},context:{goal:$.meta.description??`Implement feature ${$.meta.key}`,description:$.meta.title??$.meta.key,background:""},specMarkdown:H0($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(w.specMarkdown=H0($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)w.steps=$.operations.map((S,Q)=>({order:Q+1,title:`Implement ${S.key}`,description:`Implement operation ${S.key}.v${S.version}`,acceptanceCriteria:[`Operation ${S.key} works as specified`]}));let j=m.formatPlan(w),B=H0($,b);return{plan:w,prompt:j,markdown:B}}generateAgentConfig($,b){return Ub(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,n="implement",A){return A5($,{taskType:n,existingCode:A})}listAgentTypes(){return G0()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function W5($){return new xn($)}var w5=new xn;import{detectAuthoringTarget as s5,generateComponentTemplate as $8,generateHandlerTemplate as b8,generateTestTemplate as n8,getAuthoringTargetDefinition as A8,inferSpecTypeFromFilePath as m8,scanSpecSource as y8}from"@contractspec/module.workspace";var dW={};f(dW,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});function QW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
520
520
|
|
|
521
|
-
export const ${
|
|
521
|
+
export const ${nb($.key)}Capability = defineCapability({
|
|
522
522
|
meta: {
|
|
523
523
|
key: '${$.key}',
|
|
524
524
|
version: '${$.version}',
|
|
525
525
|
kind: '${$.kind??"api"}',
|
|
526
|
-
title: '${k(
|
|
526
|
+
title: '${k(bb($))}',
|
|
527
527
|
description: '${k($.description)}',
|
|
528
|
-
domain: '${k(
|
|
528
|
+
domain: '${k(r$($))}',
|
|
529
529
|
owners: [${W$($.owners)}],
|
|
530
530
|
tags: [${W$($.tags)}],
|
|
531
531
|
stability: '${$.stability}',
|
|
@@ -533,15 +533,15 @@ export const ${a$($.key)}Capability = defineCapability({
|
|
|
533
533
|
provides: [],
|
|
534
534
|
requires: [],
|
|
535
535
|
});
|
|
536
|
-
`}function
|
|
536
|
+
`}function ZW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
537
537
|
|
|
538
|
-
export const ${
|
|
538
|
+
export const ${nb($.key)}Policy = definePolicy({
|
|
539
539
|
meta: {
|
|
540
540
|
key: '${$.key}',
|
|
541
541
|
version: '${$.version}',
|
|
542
|
-
title: '${k(
|
|
542
|
+
title: '${k(bb($))}',
|
|
543
543
|
description: '${k($.description)}',
|
|
544
|
-
domain: '${k(
|
|
544
|
+
domain: '${k(r$($))}',
|
|
545
545
|
owners: [${W$($.owners)}],
|
|
546
546
|
tags: [${W$($.tags)}],
|
|
547
547
|
stability: '${$.stability}',
|
|
@@ -551,27 +551,27 @@ export const ${a$($.key)}Policy = definePolicy({
|
|
|
551
551
|
{
|
|
552
552
|
effect: 'allow',
|
|
553
553
|
actions: ['read'],
|
|
554
|
-
resource: { type: '${k(
|
|
554
|
+
resource: { type: '${k(r$($))}' },
|
|
555
555
|
reason: 'TODO: replace with real access rules',
|
|
556
556
|
},
|
|
557
557
|
],
|
|
558
558
|
});
|
|
559
|
-
`}function
|
|
559
|
+
`}function XW($){let b=$.targetVersion??"1.0.0",n=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
560
560
|
|
|
561
|
-
export const ${
|
|
561
|
+
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
562
562
|
meta: {
|
|
563
563
|
key: '${$.key}',
|
|
564
564
|
version: '${$.version}',
|
|
565
|
-
title: '${k(
|
|
565
|
+
title: '${k(bb($))}',
|
|
566
566
|
description: '${k($.description)}',
|
|
567
|
-
domain: '${k(
|
|
567
|
+
domain: '${k(r$($))}',
|
|
568
568
|
owners: [${W$($.owners)}],
|
|
569
569
|
tags: [${W$($.tags)}],
|
|
570
570
|
stability: '${$.stability}',
|
|
571
571
|
},
|
|
572
572
|
target: {
|
|
573
573
|
type: '${$.targetType}',
|
|
574
|
-
${$.targetType}: ${
|
|
574
|
+
${$.targetType}: ${n},
|
|
575
575
|
},
|
|
576
576
|
scenarios: [
|
|
577
577
|
{
|
|
@@ -581,13 +581,13 @@ export const ${a$($.key)}TestSpec = defineTestSpec({
|
|
|
581
581
|
},
|
|
582
582
|
],
|
|
583
583
|
});
|
|
584
|
-
`}function
|
|
584
|
+
`}function YW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
585
585
|
|
|
586
|
-
export const ${
|
|
586
|
+
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
587
587
|
meta: {
|
|
588
588
|
key: '${$.key}',
|
|
589
589
|
version: '${$.version}',
|
|
590
|
-
domain: '${k(
|
|
590
|
+
domain: '${k(r$($))}',
|
|
591
591
|
description: '${k($.description)}',
|
|
592
592
|
owners: [${W$($.owners)}],
|
|
593
593
|
tags: [${W$($.tags)}],
|
|
@@ -597,20 +597,20 @@ export const ${a$(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
|
597
597
|
fallback: '${$.fallback??$.locale}',
|
|
598
598
|
messages: {
|
|
599
599
|
'${$.key}.title': {
|
|
600
|
-
value: '${k(
|
|
600
|
+
value: '${k(bb($))}',
|
|
601
601
|
description: 'TODO: replace with a real localized message',
|
|
602
602
|
},
|
|
603
603
|
},
|
|
604
604
|
});
|
|
605
|
-
`}function
|
|
605
|
+
`}function GW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
|
|
606
606
|
|
|
607
|
-
export const ${
|
|
607
|
+
export const ${nb($.key)}Job = defineJob({
|
|
608
608
|
meta: {
|
|
609
609
|
key: '${$.key}',
|
|
610
610
|
version: '${$.version}',
|
|
611
|
-
title: '${k(
|
|
611
|
+
title: '${k(bb($))}',
|
|
612
612
|
description: '${k($.description)}',
|
|
613
|
-
domain: '${k(
|
|
613
|
+
domain: '${k(r$($))}',
|
|
614
614
|
owners: [${W$($.owners)}],
|
|
615
615
|
tags: [${W$($.tags)}],
|
|
616
616
|
stability: '${$.stability}',
|
|
@@ -618,17 +618,17 @@ export const ${a$($.key)}Job = defineJob({
|
|
|
618
618
|
payload: { schema: {} },
|
|
619
619
|
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
620
620
|
});
|
|
621
|
-
`}function
|
|
621
|
+
`}function HW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
622
622
|
|
|
623
|
-
export const ${
|
|
623
|
+
export const ${nb($.key)}Visualization = defineVisualization({
|
|
624
624
|
meta: {
|
|
625
625
|
key: '${$.key}',
|
|
626
626
|
version: '${$.version}',
|
|
627
|
-
title: '${k(
|
|
627
|
+
title: '${k(bb($))}',
|
|
628
628
|
description: '${k($.description)}',
|
|
629
629
|
goal: 'TODO: describe the decision this visualization supports',
|
|
630
630
|
context: 'TODO: describe where this visualization appears',
|
|
631
|
-
domain: '${k(
|
|
631
|
+
domain: '${k(r$($))}',
|
|
632
632
|
owners: [${W$($.owners)}],
|
|
633
633
|
tags: [${W$($.tags)}],
|
|
634
634
|
stability: '${$.stability}',
|
|
@@ -646,19 +646,19 @@ export const ${a$($.key)}Visualization = defineVisualization({
|
|
|
646
646
|
measure: 'value',
|
|
647
647
|
},
|
|
648
648
|
});
|
|
649
|
-
`}function
|
|
649
|
+
`}function bb($){return $.title??j5($.key.split(".").at(-1)??$.key)}function r$($){return $.domain??$.key.split(".")[0]??"contractspec"}function W$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function nb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function j5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function In($){let b=$.packageName??`@contractspec/example.${S5($.key.split(".").at(-1)??$.key)}`,n=`${Kb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
650
650
|
|
|
651
|
-
|
|
651
|
+
const ${n} = defineExample({
|
|
652
652
|
meta: {
|
|
653
653
|
key: '${$.key}',
|
|
654
654
|
version: '${$.version}',
|
|
655
|
-
title: '${
|
|
656
|
-
description: '${
|
|
655
|
+
title: '${t(En($))}',
|
|
656
|
+
description: '${t($.description)}',
|
|
657
657
|
kind: 'template',
|
|
658
658
|
visibility: 'experimental',
|
|
659
659
|
stability: '${$.stability}',
|
|
660
|
-
owners: [${
|
|
661
|
-
tags: [${
|
|
660
|
+
owners: [${S$($.owners)}],
|
|
661
|
+
tags: [${S$($.tags)}],
|
|
662
662
|
},
|
|
663
663
|
surfaces: {
|
|
664
664
|
templates: true,
|
|
@@ -670,49 +670,52 @@ export const ${Hb($.key)}Example = defineExample({
|
|
|
670
670
|
packageName: '${b}',
|
|
671
671
|
},
|
|
672
672
|
});
|
|
673
|
-
`}function lW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
674
673
|
|
|
675
|
-
export
|
|
674
|
+
export default ${n};
|
|
675
|
+
export { ${n} };
|
|
676
|
+
`}function qW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
677
|
+
|
|
678
|
+
export const ${Kb($.key)}Agent = defineAgent({
|
|
676
679
|
meta: {
|
|
677
680
|
key: '${$.key}',
|
|
678
681
|
version: '${$.version}',
|
|
679
|
-
description: '${
|
|
680
|
-
owners: [${
|
|
681
|
-
tags: [${
|
|
682
|
+
description: '${t($.description)}',
|
|
683
|
+
owners: [${S$($.owners)}],
|
|
684
|
+
tags: [${S$($.tags)}],
|
|
682
685
|
stability: '${$.stability}',
|
|
683
686
|
},
|
|
684
|
-
instructions: '${
|
|
687
|
+
instructions: '${t($.instructions)}',
|
|
685
688
|
tools: [{ name: 'todo' }],
|
|
686
689
|
});
|
|
687
|
-
`}function
|
|
690
|
+
`}function OW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
688
691
|
|
|
689
|
-
export const ${
|
|
692
|
+
export const ${Kb($.key)}ProductIntent = defineProductIntentSpec({
|
|
690
693
|
id: '${$.id??`${$.key}-run`}',
|
|
691
694
|
meta: {
|
|
692
695
|
key: '${$.key}',
|
|
693
696
|
version: '${$.version}',
|
|
694
|
-
title: '${
|
|
695
|
-
description: '${
|
|
697
|
+
title: '${t(En($))}',
|
|
698
|
+
description: '${t($.description)}',
|
|
696
699
|
goal: 'TODO: capture the desired product outcome',
|
|
697
700
|
context: 'TODO: capture the decision context',
|
|
698
701
|
stability: '${$.stability}',
|
|
699
|
-
owners: [${
|
|
700
|
-
tags: [${
|
|
702
|
+
owners: [${S$($.owners)}],
|
|
703
|
+
tags: [${S$($.tags)}],
|
|
701
704
|
},
|
|
702
|
-
question: '${
|
|
705
|
+
question: '${t($.question)}',
|
|
703
706
|
insights: { insights: [] },
|
|
704
707
|
});
|
|
705
|
-
`}function
|
|
708
|
+
`}function VW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
706
709
|
|
|
707
|
-
export const ${
|
|
710
|
+
export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
708
711
|
meta: {
|
|
709
712
|
key: '${$.key}',
|
|
710
713
|
version: '${$.version}',
|
|
711
|
-
title: '${
|
|
712
|
-
description: '${
|
|
713
|
-
domain: '${
|
|
714
|
-
owners: [${
|
|
715
|
-
tags: [${
|
|
714
|
+
title: '${t(En($))}',
|
|
715
|
+
description: '${t($.description)}',
|
|
716
|
+
domain: '${t(UW($))}',
|
|
717
|
+
owners: [${S$($.owners)}],
|
|
718
|
+
tags: [${S$($.tags)}],
|
|
716
719
|
stability: '${$.stability}',
|
|
717
720
|
},
|
|
718
721
|
target: {
|
|
@@ -737,17 +740,17 @@ export const ${Hb($.key)}HarnessScenario = defineHarnessScenario({
|
|
|
737
740
|
},
|
|
738
741
|
],
|
|
739
742
|
});
|
|
740
|
-
`}function
|
|
743
|
+
`}function JW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
741
744
|
|
|
742
|
-
export const ${
|
|
745
|
+
export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
743
746
|
meta: {
|
|
744
747
|
key: '${$.key}',
|
|
745
748
|
version: '${$.version}',
|
|
746
|
-
title: '${
|
|
747
|
-
description: '${
|
|
748
|
-
domain: '${
|
|
749
|
-
owners: [${
|
|
750
|
-
tags: [${
|
|
749
|
+
title: '${t(En($))}',
|
|
750
|
+
description: '${t($.description)}',
|
|
751
|
+
domain: '${t(UW($))}',
|
|
752
|
+
owners: [${S$($.owners)}],
|
|
753
|
+
tags: [${S$($.tags)}],
|
|
751
754
|
stability: '${$.stability}',
|
|
752
755
|
},
|
|
753
756
|
scenarios: [
|
|
@@ -760,94 +763,94 @@ export const ${Hb($.key)}HarnessSuite = defineHarnessSuite({
|
|
|
760
763
|
weight: 1,
|
|
761
764
|
},
|
|
762
765
|
],
|
|
763
|
-
summary: '${
|
|
764
|
-
tags: [${
|
|
766
|
+
summary: '${t($.description)}',
|
|
767
|
+
tags: [${S$($.tags)}],
|
|
765
768
|
});
|
|
766
|
-
`}function
|
|
767
|
-
`:"";return`import
|
|
769
|
+
`}function En($){return $.title??B5($.key.split(".").at(-1)??$.key)}function UW($){return $.domain??$.key.split(".")[0]??"contractspec"}function S$($){return $.map((b)=>`'${t(b)}'`).join(", ")}function Kb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function B5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function S5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function LW($){let b=V5($.key.split(".").pop()??"App")+"AppConfig",n=Q5($),A=Z5($),m=KW("dataViews",$.dataViews),y=KW("workflows",$.workflows),W=X5($),w=Y5($),j=G5($),B=H5($),S=q5($),Q=O5($),Z=$.notes?` notes: '${T($.notes)}',
|
|
770
|
+
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
768
771
|
|
|
769
|
-
export const ${b}
|
|
772
|
+
export const ${b} = defineAppConfig({
|
|
770
773
|
meta: {
|
|
771
|
-
key: '${
|
|
774
|
+
key: '${T($.key)}',
|
|
772
775
|
version: '${$.version}',
|
|
773
|
-
title: '${
|
|
774
|
-
description: '${
|
|
775
|
-
domain: '${
|
|
776
|
-
owners: [${$.owners.map((
|
|
777
|
-
tags: [${$.tags.map((
|
|
776
|
+
title: '${T($.title)}',
|
|
777
|
+
description: '${T($.description)}',
|
|
778
|
+
domain: '${T($.domain)}',
|
|
779
|
+
owners: [${$.owners.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
780
|
+
tags: [${$.tags.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
778
781
|
stability: '${$.stability}',
|
|
779
|
-
appId: '${
|
|
782
|
+
appId: '${T($.appId)}',
|
|
780
783
|
},
|
|
781
|
-
${A}${m}${
|
|
782
|
-
`}function
|
|
783
|
-
`:"",
|
|
784
|
+
${n}${A}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
785
|
+
`}function Q5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((A)=>_W(A)).join(", ")}],
|
|
786
|
+
`:"",n=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((A)=>_W(A)).join(", ")}],
|
|
784
787
|
`:"";return` capabilities: {
|
|
785
|
-
${b}${
|
|
786
|
-
`}function
|
|
787
|
-
`:"",
|
|
788
|
+
${b}${n} },
|
|
789
|
+
`}function Z5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
790
|
+
`:"",n=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
788
791
|
`:"";return` features: {
|
|
789
|
-
${b}${
|
|
790
|
-
`}function
|
|
791
|
-
key: '${
|
|
792
|
-
version: '${
|
|
792
|
+
${b}${n} },
|
|
793
|
+
`}function KW($,b){if(b.length===0)return"";let n=b.map((A)=>` ${A.slot}: {
|
|
794
|
+
key: '${T(A.key)}'${A.version?`,
|
|
795
|
+
version: '${A.version}'`:""}
|
|
793
796
|
}`).join(`,
|
|
794
797
|
`);return` ${$}: {
|
|
795
|
-
${
|
|
798
|
+
${n}
|
|
796
799
|
},
|
|
797
|
-
`}function
|
|
798
|
-
${$.policyRefs.map((
|
|
799
|
-
key: '${
|
|
800
|
-
version: '${
|
|
800
|
+
`}function X5($){if($.policyRefs.length===0)return"";return` policies: [
|
|
801
|
+
${$.policyRefs.map((n)=>` {
|
|
802
|
+
key: '${T(n.key)}'${n.version?`,
|
|
803
|
+
version: '${n.version}'`:""}
|
|
801
804
|
}`).join(`,
|
|
802
805
|
`)}
|
|
803
806
|
],
|
|
804
|
-
`}function
|
|
805
|
-
`,
|
|
807
|
+
`}function Y5($){if(!$.theme)return"";let b=` primary: { key: '${T($.theme.key)}', version: '${$.theme.version}' },
|
|
808
|
+
`,n=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((A)=>`{ key: '${T(A.key)}', version: '${A.version}' }`).join(", ")}],
|
|
806
809
|
`:"";return` theme: {
|
|
807
|
-
${b}${
|
|
808
|
-
`}function
|
|
810
|
+
${b}${n} },
|
|
811
|
+
`}function G5($){if(!$.telemetry)return"";return` telemetry: {
|
|
809
812
|
spec: {
|
|
810
|
-
key: '${
|
|
813
|
+
key: '${T($.telemetry.key)}'${$.telemetry.version?`,
|
|
811
814
|
version: '${$.telemetry.version}'`:""}
|
|
812
815
|
},
|
|
813
816
|
},
|
|
814
|
-
`}function
|
|
815
|
-
`:"",
|
|
817
|
+
`}function H5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((A)=>zW(A)).join(", ")}],
|
|
818
|
+
`:"",n=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((A)=>zW(A)).join(", ")}],
|
|
816
819
|
`:"";return` experiments: {
|
|
817
|
-
${b}${
|
|
818
|
-
`}function
|
|
819
|
-
${$.featureFlags.map((
|
|
820
|
-
key: '${
|
|
821
|
-
enabled: ${
|
|
822
|
-
${
|
|
823
|
-
${
|
|
820
|
+
${b}${n} },
|
|
821
|
+
`}function q5($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
822
|
+
${$.featureFlags.map((n)=>` {
|
|
823
|
+
key: '${T(n.key)}',
|
|
824
|
+
enabled: ${n.enabled},
|
|
825
|
+
${n.variant?`variant: '${T(n.variant)}',`:""}
|
|
826
|
+
${n.description?`description: '${T(n.description)}',`:""}
|
|
824
827
|
}`).join(`,
|
|
825
828
|
`)}
|
|
826
829
|
],
|
|
827
|
-
`}function
|
|
828
|
-
${$.routes.map((
|
|
830
|
+
`}function O5($){if($.routes.length===0)return"";return` routes: [
|
|
831
|
+
${$.routes.map((n)=>{return` { ${[`path: '${T(n.path)}'`,n.label?`label: '${T(n.label)}'`:null,n.dataView?`dataView: '${T(n.dataView)}'`:null,n.workflow?`workflow: '${T(n.workflow)}'`:null,n.guardKey?`guard: { key: '${T(n.guardKey)}'${n.guardVersion?`, version: '${n.guardVersion}'`:""} }`:null,n.featureFlag?`featureFlag: '${T(n.featureFlag)}'`:null,n.experimentKey?`experiment: { key: '${T(n.experimentKey)}'${n.experimentVersion?`, version: '${n.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
829
832
|
`)}
|
|
830
833
|
],
|
|
831
|
-
`}function
|
|
832
|
-
key: '${
|
|
833
|
-
label: '${
|
|
834
|
-
dataPath: '${
|
|
835
|
-
${
|
|
836
|
-
${
|
|
837
|
-
${
|
|
834
|
+
`}function _W($){return`{ key: '${T($)}' }`}function zW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${T($.key)}'${b} }`}function V5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=J5($.name.split(".").pop()??"DataView")+"DataView",n=$.fields.map((y)=>` {
|
|
835
|
+
key: '${y.key}',
|
|
836
|
+
label: '${Mn(y.label)}',
|
|
837
|
+
dataPath: '${y.dataPath}',
|
|
838
|
+
${y.format?`format: '${y.format}',`:""}
|
|
839
|
+
${y.sortable?"sortable: true,":""}
|
|
840
|
+
${y.filterable?"filterable: true,":""}
|
|
838
841
|
}`).join(`,
|
|
839
|
-
`),
|
|
842
|
+
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((y)=>`'${y}'`).join(", ")}],`:"",m=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
840
843
|
|
|
841
844
|
export const ${b}: DataViewSpec = {
|
|
842
845
|
meta: {
|
|
843
846
|
key: '${$.name}',
|
|
844
847
|
version: ${$.version},
|
|
845
848
|
entity: '${$.entity}',
|
|
846
|
-
title: '${
|
|
847
|
-
description: '${
|
|
848
|
-
domain: '${
|
|
849
|
-
owners: [${$.owners.map((
|
|
850
|
-
tags: [${$.tags.map((
|
|
849
|
+
title: '${Mn($.title)}',
|
|
850
|
+
description: '${Mn($.description||"Describe the purpose of this data view.")}',
|
|
851
|
+
domain: '${Mn($.domain||$.entity)}',
|
|
852
|
+
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
853
|
+
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
851
854
|
stability: '${$.stability}',
|
|
852
855
|
},
|
|
853
856
|
source: {
|
|
@@ -855,7 +858,7 @@ export const ${b}: DataViewSpec = {
|
|
|
855
858
|
name: '${$.primaryOperation.name}',
|
|
856
859
|
version: ${$.primaryOperation.version},
|
|
857
860
|
},
|
|
858
|
-
${
|
|
861
|
+
${m}
|
|
859
862
|
refreshEvents: [
|
|
860
863
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
861
864
|
],
|
|
@@ -863,10 +866,10 @@ export const ${b}: DataViewSpec = {
|
|
|
863
866
|
view: {
|
|
864
867
|
kind: '${$.kind}',
|
|
865
868
|
fields: [
|
|
866
|
-
${
|
|
869
|
+
${n}
|
|
867
870
|
],
|
|
868
871
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
869
|
-
${
|
|
872
|
+
${A}
|
|
870
873
|
filters: [
|
|
871
874
|
// Example filter:
|
|
872
875
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -881,13 +884,13 @@ ${A}
|
|
|
881
884
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
882
885
|
},
|
|
883
886
|
};
|
|
884
|
-
`}function
|
|
887
|
+
`}function J5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Mn($){return $.replace(/'/g,"\\'")}function Tn({exportName:$,specImportPath:b,rendererName:n,viewKind:A}){return`'use client';
|
|
885
888
|
|
|
886
889
|
import * as React from 'react';
|
|
887
890
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
888
891
|
import { ${$} } from '${b}';
|
|
889
892
|
|
|
890
|
-
export interface ${
|
|
893
|
+
export interface ${n}Props {
|
|
891
894
|
items?: Record<string, unknown>[];
|
|
892
895
|
item?: Record<string, unknown> | null;
|
|
893
896
|
className?: string;
|
|
@@ -897,17 +900,17 @@ export interface ${A}Props {
|
|
|
897
900
|
}
|
|
898
901
|
|
|
899
902
|
/**
|
|
900
|
-
* Auto-generated renderer for the "${
|
|
903
|
+
* Auto-generated renderer for the "${A}" data view.
|
|
901
904
|
* Customize as needed for app-specific behaviour.
|
|
902
905
|
*/
|
|
903
|
-
export function ${
|
|
906
|
+
export function ${n}({
|
|
904
907
|
items = [],
|
|
905
908
|
item = null,
|
|
906
909
|
className,
|
|
907
910
|
renderActions,
|
|
908
911
|
onSelect,
|
|
909
912
|
onRowClick,
|
|
910
|
-
}: ${
|
|
913
|
+
}: ${n}Props) {
|
|
911
914
|
return (
|
|
912
915
|
<DataViewRenderer
|
|
913
916
|
spec={${$}}
|
|
@@ -920,7 +923,7 @@ export function ${A}({
|
|
|
920
923
|
/>
|
|
921
924
|
);
|
|
922
925
|
}
|
|
923
|
-
`}function
|
|
926
|
+
`}function CW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,piiFields:w}=$,j=U5(b.replace(/\./g,"_"))+"V"+n,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
924
927
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
925
928
|
|
|
926
929
|
// TODO: Define event payload schema
|
|
@@ -933,80 +936,80 @@ export const ${B} = new SchemaModel({
|
|
|
933
936
|
},
|
|
934
937
|
});
|
|
935
938
|
|
|
936
|
-
export const ${
|
|
939
|
+
export const ${j} = defineEvent({
|
|
937
940
|
name: '${b}',
|
|
938
941
|
name: '${b}',
|
|
939
|
-
version: '${
|
|
940
|
-
description: '${
|
|
941
|
-
description: '${
|
|
942
|
-
stability: '${
|
|
943
|
-
owners: [${
|
|
944
|
-
tags: [${
|
|
945
|
-
${
|
|
942
|
+
version: '${n}',
|
|
943
|
+
description: '${A}',
|
|
944
|
+
description: '${A}',
|
|
945
|
+
stability: '${m}',
|
|
946
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
947
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
948
|
+
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
946
949
|
payload: ${B},
|
|
947
950
|
});
|
|
948
|
-
`}function
|
|
949
|
-
${
|
|
950
|
-
type: '${
|
|
951
|
-
target: '${
|
|
952
|
-
${typeof
|
|
951
|
+
`}function U5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function xW($){let b=_5($.name.split(".").pop()??"Experiment")+"Experiment",n=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
952
|
+
${y.overrides.map((w)=>` {
|
|
953
|
+
type: '${w.type}',
|
|
954
|
+
target: '${h(w.target)}',
|
|
955
|
+
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
953
956
|
}`).join(`,
|
|
954
957
|
`)}
|
|
955
958
|
],`:"";return` {
|
|
956
|
-
id: '${
|
|
957
|
-
name: '${
|
|
958
|
-
${
|
|
959
|
-
${typeof
|
|
960
|
-
${
|
|
959
|
+
id: '${h(y.id)}',
|
|
960
|
+
name: '${h(y.name)}',
|
|
961
|
+
${y.description?`description: '${h(y.description)}',`:""}
|
|
962
|
+
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
963
|
+
${W}
|
|
961
964
|
}`}).join(`,
|
|
962
|
-
`),
|
|
963
|
-
${$.successMetrics.map((
|
|
964
|
-
name: '${
|
|
965
|
-
telemetryEvent: { name: '${
|
|
966
|
-
aggregation: '${
|
|
967
|
-
${typeof
|
|
965
|
+
`),A=K5($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
966
|
+
${$.successMetrics.map((y)=>` {
|
|
967
|
+
name: '${h(y.name)}',
|
|
968
|
+
telemetryEvent: { name: '${h(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
969
|
+
aggregation: '${y.aggregation}',
|
|
970
|
+
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
968
971
|
}`).join(`,
|
|
969
972
|
`)}
|
|
970
973
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
971
974
|
|
|
972
975
|
export const ${b}: ExperimentSpec = {
|
|
973
976
|
meta: {
|
|
974
|
-
key: '${
|
|
977
|
+
key: '${h($.name)}',
|
|
975
978
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
976
|
-
title: '${
|
|
977
|
-
description: '${
|
|
978
|
-
domain: '${
|
|
979
|
-
owners: [${$.owners.map((
|
|
980
|
-
tags: [${$.tags.map((
|
|
979
|
+
title: '${h($.name)} experiment',
|
|
980
|
+
description: '${h($.description||"Describe the experiment goal.")}',
|
|
981
|
+
domain: '${h($.domain)}',
|
|
982
|
+
owners: [${$.owners.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
983
|
+
tags: [${$.tags.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
981
984
|
stability: '${$.stability}',
|
|
982
985
|
},
|
|
983
|
-
controlVariant: '${
|
|
986
|
+
controlVariant: '${h($.controlVariant)}',
|
|
984
987
|
variants: [
|
|
985
|
-
${A}
|
|
986
|
-
],
|
|
987
|
-
allocation: ${m},
|
|
988
988
|
${n}
|
|
989
|
+
],
|
|
990
|
+
allocation: ${A},
|
|
991
|
+
${m}
|
|
989
992
|
};
|
|
990
|
-
`}function
|
|
993
|
+
`}function K5($){switch($.type){case"random":return`{
|
|
991
994
|
type: 'random',
|
|
992
|
-
${$.salt?`salt: '${
|
|
995
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
993
996
|
}`;case"sticky":return`{
|
|
994
997
|
type: 'sticky',
|
|
995
998
|
attribute: '${$.attribute}',
|
|
996
|
-
${$.salt?`salt: '${
|
|
999
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
997
1000
|
}`;case"targeted":return`{
|
|
998
1001
|
type: 'targeted',
|
|
999
1002
|
rules: [
|
|
1000
1003
|
${$.rules.map((b)=>` {
|
|
1001
|
-
variantId: '${
|
|
1004
|
+
variantId: '${h(b.variantId)}',
|
|
1002
1005
|
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1003
|
-
${b.policy?`policy: { name: '${
|
|
1004
|
-
${b.expression?`expression: '${
|
|
1006
|
+
${b.policy?`policy: { name: '${h(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1007
|
+
${b.expression?`expression: '${h(b.expression)}',`:""}
|
|
1005
1008
|
}`).join(`,
|
|
1006
1009
|
`)}
|
|
1007
1010
|
],
|
|
1008
1011
|
fallback: '${$.fallback??"control"}',
|
|
1009
|
-
}`;default:return
|
|
1012
|
+
}`;default:return z5($)}}function _5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function z5($){throw Error(`Unsupported allocation type ${$}`)}function L5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function IW($){let b=(n)=>n.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
1010
1013
|
`);return`/**
|
|
1011
1014
|
* ${$.title} Feature
|
|
1012
1015
|
*
|
|
@@ -1015,15 +1018,15 @@ ${$.rules.map((b)=>` {
|
|
|
1015
1018
|
|
|
1016
1019
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
1017
1020
|
|
|
1018
|
-
export const ${
|
|
1021
|
+
export const ${L5($.key)}Feature = defineFeature({
|
|
1019
1022
|
meta: {
|
|
1020
1023
|
key: '${$.key}',
|
|
1021
1024
|
version: '${$.version}',
|
|
1022
1025
|
title: '${$.title}',
|
|
1023
1026
|
description: '${$.description||"TODO: Add description"}',
|
|
1024
1027
|
domain: '${$.domain}',
|
|
1025
|
-
owners: [${$.owners.map((
|
|
1026
|
-
tags: [${$.tags.map((
|
|
1028
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1029
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
1027
1030
|
stability: '${$.stability||"beta"}',
|
|
1028
1031
|
},
|
|
1029
1032
|
|
|
@@ -1043,7 +1046,7 @@ ${b($.presentations)||" // Add presentations here"}
|
|
|
1043
1046
|
${b($.experiments)||" // Add experiments here"}
|
|
1044
1047
|
],
|
|
1045
1048
|
});
|
|
1046
|
-
`}function
|
|
1049
|
+
`}function R5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function EW($){let b=R5($.key),n=`${b}FormModel`,A=`${b}Form`;return`/**
|
|
1047
1050
|
* ${$.title} Form
|
|
1048
1051
|
*
|
|
1049
1052
|
* Auto-generated form spec.
|
|
@@ -1052,8 +1055,8 @@ ${b($.experiments)||" // Add experiments here"}
|
|
|
1052
1055
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
1053
1056
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
1054
1057
|
|
|
1055
|
-
const ${
|
|
1056
|
-
name: '${
|
|
1058
|
+
const ${n} = defineSchemaModel({
|
|
1059
|
+
name: '${n}',
|
|
1057
1060
|
description: '${$.description||"TODO: Add form model description"}',
|
|
1058
1061
|
fields: {
|
|
1059
1062
|
${$.primaryFieldKey}: {
|
|
@@ -1063,18 +1066,18 @@ const ${A} = defineSchemaModel({
|
|
|
1063
1066
|
},
|
|
1064
1067
|
});
|
|
1065
1068
|
|
|
1066
|
-
export const ${
|
|
1069
|
+
export const ${A} = defineFormSpec({
|
|
1067
1070
|
meta: {
|
|
1068
1071
|
key: '${$.key}',
|
|
1069
1072
|
version: '${$.version}',
|
|
1070
1073
|
title: '${$.title}',
|
|
1071
1074
|
description: '${$.description||"TODO: Add description"}',
|
|
1072
1075
|
domain: '${$.domain}',
|
|
1073
|
-
owners: [${$.owners.map((
|
|
1074
|
-
tags: [${$.tags.map((
|
|
1076
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1077
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1075
1078
|
stability: '${$.stability||"beta"}',
|
|
1076
1079
|
},
|
|
1077
|
-
model: ${
|
|
1080
|
+
model: ${n},
|
|
1078
1081
|
fields: [
|
|
1079
1082
|
{
|
|
1080
1083
|
kind: 'text',
|
|
@@ -1099,13 +1102,13 @@ export const ${m} = defineFormSpec({
|
|
|
1099
1102
|
form: 'react-hook-form',
|
|
1100
1103
|
},
|
|
1101
1104
|
});
|
|
1102
|
-
`}function
|
|
1103
|
-
import { ${
|
|
1105
|
+
`}function MW($,b){let n=C5($.split(".").pop()||"unknown")+"Handler",A=Dn($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1106
|
+
import { ${A} } from '../contracts/${NW($)}.contracts';
|
|
1104
1107
|
|
|
1105
1108
|
/**
|
|
1106
1109
|
* Handler for ${$}
|
|
1107
1110
|
*/
|
|
1108
|
-
export const ${
|
|
1111
|
+
export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
1109
1112
|
input,
|
|
1110
1113
|
context
|
|
1111
1114
|
) => {
|
|
@@ -1125,27 +1128,27 @@ export const ${A}: ContractHandler<typeof ${m}> = async (
|
|
|
1125
1128
|
throw error;
|
|
1126
1129
|
}
|
|
1127
1130
|
};
|
|
1128
|
-
`}function
|
|
1131
|
+
`}function TW($,b){let n=Dn($);return`import React from 'react';
|
|
1129
1132
|
|
|
1130
|
-
interface ${
|
|
1133
|
+
interface ${n}Props {
|
|
1131
1134
|
// TODO: Define props based on presentation spec
|
|
1132
1135
|
}
|
|
1133
1136
|
|
|
1134
1137
|
/**
|
|
1135
1138
|
* ${b}
|
|
1136
1139
|
*/
|
|
1137
|
-
export const ${
|
|
1140
|
+
export const ${n}: React.FC<${n}Props> = (props) => {
|
|
1138
1141
|
return (
|
|
1139
1142
|
<div>
|
|
1140
1143
|
{/* TODO: Implement component UI */}
|
|
1141
|
-
<p>Component: ${
|
|
1144
|
+
<p>Component: ${n}</p>
|
|
1142
1145
|
</div>
|
|
1143
1146
|
);
|
|
1144
1147
|
};
|
|
1145
|
-
`}function
|
|
1146
|
-
import { ${
|
|
1148
|
+
`}function DW($,b){let n=b==="handler"?"../handlers":"../components",A=Dn($);return`import { describe, it, expect } from 'bun:test';
|
|
1149
|
+
import { ${A} } from '${n}/${NW($)}';
|
|
1147
1150
|
|
|
1148
|
-
describe('${
|
|
1151
|
+
describe('${A}', () => {
|
|
1149
1152
|
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
1150
1153
|
// TODO: Implement test
|
|
1151
1154
|
expect(true).toBe(true);
|
|
@@ -1161,16 +1164,16 @@ describe('${m}', () => {
|
|
|
1161
1164
|
// TODO: Test accessibility
|
|
1162
1165
|
});`}
|
|
1163
1166
|
});
|
|
1164
|
-
`}function
|
|
1165
|
-
`),
|
|
1166
|
-
${$.capabilitiesRequired.map((
|
|
1167
|
+
`}function C5($){let b=Dn($);return b.charAt(0).toLowerCase()+b.slice(1)}function Dn($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function NW($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function FW($){let b=v5($.name.split(".").pop()??"Integration"),n=`${b}IntegrationSpec`,A=`register${b}Integration`,m=$.supportedModes.length?$.supportedModes:["managed"],y=m.map((G)=>`'${G}'`).join(", "),W=$.capabilitiesProvided.map((G)=>` { key: '${G.key}', version: '${G.version}' }`).join(`,
|
|
1168
|
+
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1169
|
+
${$.capabilitiesRequired.map((G)=>{let V=G.version!==void 0?`, version: '${G.version}'`:"",O=G.optional?", optional: true":"",K=G.reason?`, reason: '${w$(G.reason)}'`:"";return` { key: '${G.key}'${V}${O}${K} }`}).join(`,
|
|
1167
1170
|
`)}
|
|
1168
|
-
],`:"",
|
|
1169
|
-
`:"",
|
|
1171
|
+
],`:"",j=x5($.configFields),B=E5($.configFields),S=I5($.secretFields),Q=M5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
|
|
1172
|
+
`:"",X=T5($.rateLimitRpm,$.rateLimitRph),Y=D5(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1170
1173
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
1171
1174
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
1172
1175
|
|
|
1173
|
-
export const ${
|
|
1176
|
+
export const ${n}: IntegrationSpec = {
|
|
1174
1177
|
meta: {
|
|
1175
1178
|
key: '${$.name}',
|
|
1176
1179
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
@@ -1179,145 +1182,145 @@ export const ${A}: IntegrationSpec = {
|
|
|
1179
1182
|
title: '${w$($.title)}',
|
|
1180
1183
|
description: '${w$($.description)}',
|
|
1181
1184
|
domain: '${w$($.domain)}',
|
|
1182
|
-
owners: [${$.owners.map((
|
|
1183
|
-
tags: [${$.tags.map((
|
|
1184
|
-
stability: StabilityEnum.${
|
|
1185
|
+
owners: [${$.owners.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1186
|
+
tags: [${$.tags.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1187
|
+
stability: StabilityEnum.${F5($.stability)},
|
|
1185
1188
|
},
|
|
1186
|
-
supportedModes: [${
|
|
1189
|
+
supportedModes: [${y}],
|
|
1187
1190
|
capabilities: {
|
|
1188
1191
|
provides: [
|
|
1189
|
-
${
|
|
1192
|
+
${W}
|
|
1190
1193
|
],
|
|
1191
|
-
${
|
|
1194
|
+
${w.length>0?`${w}
|
|
1192
1195
|
`:""} },
|
|
1193
1196
|
configSchema: {
|
|
1194
|
-
${
|
|
1197
|
+
${j}
|
|
1195
1198
|
example: ${B},
|
|
1196
1199
|
},
|
|
1197
1200
|
secretSchema: {
|
|
1198
1201
|
${S}
|
|
1199
1202
|
example: ${Q},
|
|
1200
1203
|
},
|
|
1201
|
-
${Z}${
|
|
1204
|
+
${Z}${X}${Y} healthCheck: {
|
|
1202
1205
|
method: '${$.healthCheckMethod}',
|
|
1203
1206
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
1204
1207
|
},
|
|
1205
1208
|
};
|
|
1206
1209
|
|
|
1207
|
-
export function ${
|
|
1210
|
+
export function ${A}(
|
|
1208
1211
|
registry: IntegrationSpecRegistry
|
|
1209
1212
|
): IntegrationSpecRegistry {
|
|
1210
|
-
return registry.register(${
|
|
1213
|
+
return registry.register(${n});
|
|
1211
1214
|
}
|
|
1212
|
-
`}function
|
|
1213
|
-
`:"",
|
|
1215
|
+
`}function x5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1216
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: '${N5(m.type)}'${y} }`}).join(`,
|
|
1214
1217
|
`):"";return` schema: {
|
|
1215
1218
|
type: 'object',
|
|
1216
|
-
${
|
|
1217
|
-
${
|
|
1219
|
+
${n} properties: {
|
|
1220
|
+
${A||" "}
|
|
1218
1221
|
},
|
|
1219
1222
|
},
|
|
1220
|
-
`}function
|
|
1221
|
-
`:"",
|
|
1223
|
+
`}function I5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1224
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
1222
1225
|
`):"";return` schema: {
|
|
1223
1226
|
type: 'object',
|
|
1224
|
-
${
|
|
1225
|
-
${
|
|
1227
|
+
${n} properties: {
|
|
1228
|
+
${A||" "}
|
|
1226
1229
|
},
|
|
1227
1230
|
},
|
|
1228
|
-
`}function
|
|
1229
|
-
${$.map((
|
|
1231
|
+
`}function E5($){if($.length===0)return"{}";return`{
|
|
1232
|
+
${$.map((n)=>{switch(n.type){case"number":return` ${n.key}: 0`;case"boolean":return` ${n.key}: true`;case"string":default:return` ${n.key}: '${n.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
1230
1233
|
`)}
|
|
1231
|
-
}`}function
|
|
1232
|
-
${$.map((
|
|
1234
|
+
}`}function M5($){if($.length===0)return"{}";return`{
|
|
1235
|
+
${$.map((n)=>` ${n.key}: '${n.key.toUpperCase()}_SECRET'`).join(`,
|
|
1233
1236
|
`)}
|
|
1234
|
-
}`}function
|
|
1237
|
+
}`}function T5($,b){if($==null&&b==null)return"";let n=[];if($!=null)n.push(` rpm: ${$}`);if(b!=null)n.push(` rph: ${b}`);return` constraints: {
|
|
1235
1238
|
rateLimit: {
|
|
1236
|
-
${
|
|
1239
|
+
${n.join(`,
|
|
1237
1240
|
`)}
|
|
1238
1241
|
},
|
|
1239
1242
|
},
|
|
1240
|
-
`}function
|
|
1241
|
-
`:"",n
|
|
1242
|
-
`:"";if(!m
|
|
1243
|
-
${
|
|
1244
|
-
`}function
|
|
1243
|
+
`}function D5($,b,n){if(!$.includes("byok"))return"";let A=b?` setupInstructions: '${w$(b)}',
|
|
1244
|
+
`:"",m=n&&n.length?` requiredScopes: [${n.map((y)=>`'${w$(y)}'`).join(", ")}],
|
|
1245
|
+
`:"";if(!A&&!m)return"";return` byokSetup: {
|
|
1246
|
+
${A}${m} },
|
|
1247
|
+
`}function N5($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function F5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function v5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function w$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function vW($){let b=f5($.name.split(".").pop()??"KnowledgeSpace"),n=`${b}KnowledgeSpace`,A=`register${b}KnowledgeSpace`,m=g5($),y=P5($),W=k5($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1245
1248
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1246
1249
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1247
1250
|
|
|
1248
|
-
export const ${
|
|
1251
|
+
export const ${n}: KnowledgeSpaceSpec = {
|
|
1249
1252
|
meta: {
|
|
1250
1253
|
key: '${$.name}',
|
|
1251
1254
|
version: ${$.version},
|
|
1252
1255
|
category: '${$.category}',
|
|
1253
|
-
displayName: '${
|
|
1254
|
-
title: '${
|
|
1255
|
-
description: '${
|
|
1256
|
-
domain: '${
|
|
1257
|
-
owners: [${$.owners.map((
|
|
1258
|
-
tags: [${$.tags.map((
|
|
1259
|
-
stability: StabilityEnum.${
|
|
1260
|
-
},
|
|
1261
|
-
retention: ${
|
|
1256
|
+
displayName: '${O$($.displayName)}',
|
|
1257
|
+
title: '${O$($.title)}',
|
|
1258
|
+
description: '${O$($.description)}',
|
|
1259
|
+
domain: '${O$($.domain)}',
|
|
1260
|
+
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1261
|
+
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1262
|
+
stability: StabilityEnum.${r5($.stability)},
|
|
1263
|
+
},
|
|
1264
|
+
retention: ${m},
|
|
1262
1265
|
access: {
|
|
1263
|
-
${
|
|
1266
|
+
${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${w}
|
|
1264
1267
|
`:""} },
|
|
1265
|
-
${
|
|
1268
|
+
${W} description: '${O$($.description||$.displayName)}',
|
|
1266
1269
|
};
|
|
1267
1270
|
|
|
1268
|
-
export function ${
|
|
1271
|
+
export function ${A}(
|
|
1269
1272
|
registry: KnowledgeSpaceRegistry
|
|
1270
1273
|
): KnowledgeSpaceRegistry {
|
|
1271
|
-
return registry.register(${
|
|
1274
|
+
return registry.register(${n});
|
|
1272
1275
|
}
|
|
1273
|
-
`}function
|
|
1274
|
-
`,
|
|
1275
|
-
`;return`${b}${
|
|
1276
|
+
`}function g5($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",n=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${n} }`}function P5($){let b=` trustLevel: '${$.trustLevel}',
|
|
1277
|
+
`,n=` automationWritable: ${$.automationWritable},
|
|
1278
|
+
`;return`${b}${n}`}function k5($){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: {
|
|
1276
1279
|
${b.join(`,
|
|
1277
1280
|
`)}
|
|
1278
1281
|
},
|
|
1279
|
-
`}function
|
|
1282
|
+
`}function r5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function f5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function O$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function PW($){let n=`${c5($.name.split(".").pop()??"Migration")}Migration`,A=$.dependencies.length>0?`dependencies: [${$.dependencies.map((m)=>`'${m}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1280
1283
|
|
|
1281
|
-
export const ${
|
|
1284
|
+
export const ${n}: MigrationSpec = {
|
|
1282
1285
|
meta: {
|
|
1283
1286
|
key: '${$.name}',
|
|
1284
1287
|
version: ${$.version},
|
|
1285
|
-
title: '${
|
|
1286
|
-
description: '${
|
|
1287
|
-
domain: '${
|
|
1288
|
-
owners: [${$.owners.map((
|
|
1289
|
-
tags: [${$.tags.map((
|
|
1288
|
+
title: '${f$($.title)}',
|
|
1289
|
+
description: '${f$($.description??"")}',
|
|
1290
|
+
domain: '${f$($.domain)}',
|
|
1291
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1292
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1290
1293
|
stability: '${$.stability}',
|
|
1291
1294
|
},
|
|
1292
1295
|
plan: {
|
|
1293
1296
|
up: [
|
|
1294
|
-
${
|
|
1297
|
+
${gW($.up)}
|
|
1295
1298
|
],${$.down&&$.down.length?`
|
|
1296
1299
|
down: [
|
|
1297
|
-
${
|
|
1300
|
+
${gW($.down)}
|
|
1298
1301
|
],`:""}
|
|
1299
1302
|
},
|
|
1300
|
-
${
|
|
1303
|
+
${A}
|
|
1301
1304
|
};
|
|
1302
|
-
`}function
|
|
1305
|
+
`}function gW($){return $.map((b)=>{let n=b.description?`description: '${f$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1303
1306
|
kind: 'schema',
|
|
1304
|
-
${
|
|
1305
|
-
sql: \`${
|
|
1307
|
+
${n}
|
|
1308
|
+
sql: \`${f$(b.sql??"")}\`,
|
|
1306
1309
|
}`;case"data":return` {
|
|
1307
1310
|
kind: 'data',
|
|
1308
|
-
${
|
|
1309
|
-
script: \`${
|
|
1311
|
+
${n}
|
|
1312
|
+
script: \`${f$(b.script??"")}\`,
|
|
1310
1313
|
}`;case"validation":default:return` {
|
|
1311
1314
|
kind: 'validation',
|
|
1312
|
-
${
|
|
1313
|
-
assertion: \`${
|
|
1315
|
+
${n}
|
|
1316
|
+
assertion: \`${f$(b.assertion??"")}\`,
|
|
1314
1317
|
}`}}).join(`,
|
|
1315
|
-
`)}function
|
|
1318
|
+
`)}function c5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function kW($){let{name:b,version:n,kind:A,description:m,goal:y,context:W,stability:w,owners:j,tags:B,auth:S,flags:Q}=$,Z=h5(b.split(".").pop()||"Unknown")+"Spec",X=Z.replace("Spec","Input"),Y=Z.replace("Spec","Output");return`import { define${q0(A)} } from '@contractspec/lib.contracts-spec';
|
|
1316
1319
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1317
1320
|
|
|
1318
1321
|
// TODO: Define input schema
|
|
1319
|
-
export const ${
|
|
1320
|
-
name: '${
|
|
1322
|
+
export const ${X} = new SchemaModel({
|
|
1323
|
+
name: '${X}',
|
|
1321
1324
|
description: 'Input for ${b}',
|
|
1322
1325
|
fields: {
|
|
1323
1326
|
// Add your fields here
|
|
@@ -1326,8 +1329,8 @@ export const ${G} = new SchemaModel({
|
|
|
1326
1329
|
});
|
|
1327
1330
|
|
|
1328
1331
|
// TODO: Define output schema
|
|
1329
|
-
export const ${
|
|
1330
|
-
name: '${
|
|
1332
|
+
export const ${Y} = new SchemaModel({
|
|
1333
|
+
name: '${Y}',
|
|
1331
1334
|
description: 'Output for ${b}',
|
|
1332
1335
|
fields: {
|
|
1333
1336
|
// Add your fields here
|
|
@@ -1335,23 +1338,23 @@ export const ${X} = new SchemaModel({
|
|
|
1335
1338
|
},
|
|
1336
1339
|
});
|
|
1337
1340
|
|
|
1338
|
-
export const ${Z} = define${
|
|
1341
|
+
export const ${Z} = define${q0(A)}({
|
|
1339
1342
|
meta: {
|
|
1340
1343
|
key: '${b}',
|
|
1341
1344
|
key: '${b}',
|
|
1342
|
-
version: '${
|
|
1343
|
-
stability: '${
|
|
1344
|
-
stability: '${
|
|
1345
|
-
owners: [${
|
|
1346
|
-
tags: [${B.map((
|
|
1347
|
-
description: '${
|
|
1348
|
-
goal: '${
|
|
1349
|
-
context: '${
|
|
1345
|
+
version: '${n}',
|
|
1346
|
+
stability: '${w}',
|
|
1347
|
+
stability: '${w}',
|
|
1348
|
+
owners: [${j.map((G)=>`'${G}'`).join(", ")}],
|
|
1349
|
+
tags: [${B.map((G)=>`'${G}'`).join(", ")}],
|
|
1350
|
+
description: '${m}',
|
|
1351
|
+
goal: '${y}',
|
|
1352
|
+
context: '${W}',
|
|
1350
1353
|
},
|
|
1351
1354
|
|
|
1352
1355
|
io: {
|
|
1353
|
-
input: ${
|
|
1354
|
-
output: ${
|
|
1356
|
+
input: ${X},
|
|
1357
|
+
output: ${Y},
|
|
1355
1358
|
errors: {
|
|
1356
1359
|
// Define possible errors
|
|
1357
1360
|
// EXAMPLE_ERROR: {
|
|
@@ -1364,7 +1367,7 @@ export const ${Z} = define${mm(m)}({
|
|
|
1364
1367
|
|
|
1365
1368
|
policy: {
|
|
1366
1369
|
auth: '${S}',
|
|
1367
|
-
${Q.length>0?`flags: [${Q.map((
|
|
1370
|
+
${Q.length>0?`flags: [${Q.map((G)=>`'${G}'`).join(", ")}],`:"// flags: [],"}
|
|
1368
1371
|
},
|
|
1369
1372
|
|
|
1370
1373
|
sideEffects: {
|
|
@@ -1378,9 +1381,9 @@ export const ${Z} = define${mm(m)}({
|
|
|
1378
1381
|
},
|
|
1379
1382
|
|
|
1380
1383
|
transport: {
|
|
1381
|
-
rest: { method: '${
|
|
1384
|
+
rest: { method: '${A==="command"?"POST":"GET"}' },
|
|
1382
1385
|
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1383
|
-
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(
|
|
1386
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(n).replace(/\./g,"_")}' },
|
|
1384
1387
|
},
|
|
1385
1388
|
|
|
1386
1389
|
acceptance: {
|
|
@@ -1401,12 +1404,12 @@ export const ${Z} = define${mm(m)}({
|
|
|
1401
1404
|
],
|
|
1402
1405
|
},
|
|
1403
1406
|
});
|
|
1404
|
-
`}function
|
|
1407
|
+
`}function q0($){return $.charAt(0).toUpperCase()+$.slice(1)}function h5($){return $.split(/[-_.]/).map(q0).join("")}function rW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,presentationKind:w}=$,j=d5(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1405
1408
|
kind: 'web_component',
|
|
1406
1409
|
framework: 'react',
|
|
1407
1410
|
componentKey: '${b.replace(/\./g,"_")}',
|
|
1408
1411
|
props: new SchemaModel({
|
|
1409
|
-
name: '${
|
|
1412
|
+
name: '${j}Props',
|
|
1410
1413
|
description: 'Props for ${b}',
|
|
1411
1414
|
fields: {
|
|
1412
1415
|
// TODO: Define component props
|
|
@@ -1418,7 +1421,7 @@ export const ${Z} = define${mm(m)}({
|
|
|
1418
1421
|
},`;break;case"markdown":B=` content: {
|
|
1419
1422
|
kind: 'markdown',
|
|
1420
1423
|
content: \`
|
|
1421
|
-
# ${
|
|
1424
|
+
# ${A}
|
|
1422
1425
|
|
|
1423
1426
|
TODO: Add markdown content here
|
|
1424
1427
|
\`,
|
|
@@ -1427,7 +1430,7 @@ TODO: Add markdown content here
|
|
|
1427
1430
|
kind: 'data',
|
|
1428
1431
|
mimeType: 'application/json',
|
|
1429
1432
|
model: new SchemaModel({
|
|
1430
|
-
name: '${
|
|
1433
|
+
name: '${j}Data',
|
|
1431
1434
|
description: 'Data structure for ${b}',
|
|
1432
1435
|
fields: {
|
|
1433
1436
|
// TODO: Define data structure
|
|
@@ -1436,14 +1439,14 @@ TODO: Add markdown content here
|
|
|
1436
1439
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1437
1440
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1438
1441
|
|
|
1439
|
-
export const ${
|
|
1442
|
+
export const ${j}: PresentationSpec = {
|
|
1440
1443
|
meta: {
|
|
1441
1444
|
key: '${b}',
|
|
1442
|
-
version: ${
|
|
1443
|
-
stability: '${
|
|
1444
|
-
owners: [${
|
|
1445
|
-
tags: [${
|
|
1446
|
-
description: '${
|
|
1445
|
+
version: ${n},
|
|
1446
|
+
stability: '${m}',
|
|
1447
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1448
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1449
|
+
description: '${A}',
|
|
1447
1450
|
},
|
|
1448
1451
|
|
|
1449
1452
|
policy: {
|
|
@@ -1453,50 +1456,50 @@ export const ${y}: PresentationSpec = {
|
|
|
1453
1456
|
|
|
1454
1457
|
${B}
|
|
1455
1458
|
};
|
|
1456
|
-
`}function
|
|
1457
|
-
${$.providers.map((
|
|
1458
|
-
type: '${
|
|
1459
|
-
config: ${
|
|
1459
|
+
`}function d5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function fW($){let b=u5($.name.split(".").pop()??"Telemetry")+"Telemetry",n=$.providers?.length?`providers: [
|
|
1460
|
+
${$.providers.map((m)=>` {
|
|
1461
|
+
type: '${m.type}',
|
|
1462
|
+
config: ${o5(m.config)},
|
|
1460
1463
|
}`).join(`,
|
|
1461
1464
|
`)}
|
|
1462
|
-
],`:"",
|
|
1463
|
-
type: '${
|
|
1464
|
-
${
|
|
1465
|
-
${
|
|
1466
|
-
${
|
|
1467
|
-
${
|
|
1465
|
+
],`:"",A=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1466
|
+
type: '${w.type}',
|
|
1467
|
+
${w.required?"required: true,":""}
|
|
1468
|
+
${w.pii?"pii: true,":""}
|
|
1469
|
+
${w.redact?"redact: true,":""}
|
|
1470
|
+
${w.description?`description: '${l(w.description)}',`:""}
|
|
1468
1471
|
}`).join(`,
|
|
1469
|
-
`),
|
|
1472
|
+
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1470
1473
|
enabled: true,
|
|
1471
|
-
${typeof
|
|
1474
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1472
1475
|
thresholds: [
|
|
1473
|
-
${
|
|
1474
|
-
metric: '${l(
|
|
1475
|
-
${typeof
|
|
1476
|
-
${typeof
|
|
1476
|
+
${m.anomalyRules.map((w)=>` {
|
|
1477
|
+
metric: '${l(w.metric)}',
|
|
1478
|
+
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1479
|
+
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1477
1480
|
}`).join(`,
|
|
1478
1481
|
`)}
|
|
1479
1482
|
],
|
|
1480
|
-
actions: [${(
|
|
1481
|
-
},`:
|
|
1483
|
+
actions: [${(m.anomalyActions??[]).map((w)=>`'${w}'`).join(", ")}],
|
|
1484
|
+
},`:m.anomalyEnabled?` anomalyDetection: {
|
|
1482
1485
|
enabled: true,
|
|
1483
|
-
${typeof
|
|
1486
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1484
1487
|
},`:"";return` {
|
|
1485
|
-
name: '${l(
|
|
1486
|
-
version: ${
|
|
1488
|
+
name: '${l(m.name)}',
|
|
1489
|
+
version: ${m.version},
|
|
1487
1490
|
semantics: {
|
|
1488
|
-
what: '${l(
|
|
1489
|
-
${
|
|
1490
|
-
${
|
|
1491
|
+
what: '${l(m.what)}',
|
|
1492
|
+
${m.who?`who: '${l(m.who)}',`:""}
|
|
1493
|
+
${m.why?`why: '${l(m.why)}',`:""}
|
|
1491
1494
|
},
|
|
1492
|
-
privacy: '${
|
|
1495
|
+
privacy: '${m.privacy}',
|
|
1493
1496
|
properties: {
|
|
1494
|
-
${
|
|
1497
|
+
${y}
|
|
1495
1498
|
},
|
|
1496
|
-
${typeof
|
|
1497
|
-
${typeof
|
|
1498
|
-
${
|
|
1499
|
-
${
|
|
1499
|
+
${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: ['${l(m.samplingConditions)}']`:""} },`:""}
|
|
1501
|
+
${W}
|
|
1502
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${l(w)}'`).join(", ")}],`:""}
|
|
1500
1503
|
}`}).join(`,
|
|
1501
1504
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1502
1505
|
|
|
@@ -1507,21 +1510,21 @@ export const ${b}: TelemetrySpec = {
|
|
|
1507
1510
|
title: '${l($.name)} telemetry',
|
|
1508
1511
|
description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1509
1512
|
domain: '${l($.domain)}',
|
|
1510
|
-
owners: [${$.owners.map((
|
|
1511
|
-
tags: [${$.tags.map((
|
|
1513
|
+
owners: [${$.owners.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1514
|
+
tags: [${$.tags.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1512
1515
|
stability: '${$.stability}',
|
|
1513
1516
|
},
|
|
1514
1517
|
config: {
|
|
1515
1518
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1516
1519
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1517
1520
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1518
|
-
${
|
|
1521
|
+
${n}
|
|
1519
1522
|
},
|
|
1520
1523
|
events: [
|
|
1521
|
-
${
|
|
1524
|
+
${A}
|
|
1522
1525
|
],
|
|
1523
1526
|
};
|
|
1524
|
-
`}function
|
|
1527
|
+
`}function u5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function o5($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function i5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function cW($){return`/**
|
|
1525
1528
|
* ${$.title} Theme
|
|
1526
1529
|
*
|
|
1527
1530
|
* Auto-generated theme spec.
|
|
@@ -1529,7 +1532,7 @@ ${m}
|
|
|
1529
1532
|
|
|
1530
1533
|
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1531
1534
|
|
|
1532
|
-
export const ${
|
|
1535
|
+
export const ${i5($.key)}Theme = defineTheme({
|
|
1533
1536
|
meta: {
|
|
1534
1537
|
key: '${$.key}',
|
|
1535
1538
|
version: '${$.version}',
|
|
@@ -1549,11 +1552,11 @@ export const ${X8($.key)}Theme = defineTheme({
|
|
|
1549
1552
|
},
|
|
1550
1553
|
},
|
|
1551
1554
|
});
|
|
1552
|
-
`}function
|
|
1553
|
-
`),
|
|
1554
|
-
from: '${
|
|
1555
|
-
to: '${
|
|
1556
|
-
${
|
|
1555
|
+
`}function hW($){let b=l5($.name.split(".").pop()??"Workflow")+"Workflow",n=$.steps.map((m)=>t5(m)).join(`,
|
|
1556
|
+
`),A=$.transitions.map((m)=>` {
|
|
1557
|
+
from: '${m.from}',
|
|
1558
|
+
to: '${m.to}',
|
|
1559
|
+
${m.condition?` condition: '${Ab(m.condition)}',`:""}
|
|
1557
1560
|
}`).join(`,
|
|
1558
1561
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1559
1562
|
|
|
@@ -1569,32 +1572,32 @@ export const ${b}: WorkflowSpec = {
|
|
|
1569
1572
|
meta: {
|
|
1570
1573
|
key: '${$.name}',
|
|
1571
1574
|
version: ${$.version},
|
|
1572
|
-
title: '${
|
|
1573
|
-
description: '${
|
|
1574
|
-
domain: '${
|
|
1575
|
+
title: '${Ab($.title)}',
|
|
1576
|
+
description: '${Ab($.description)}',
|
|
1577
|
+
domain: '${Ab($.domain)}',
|
|
1575
1578
|
stability: '${$.stability}',
|
|
1576
|
-
owners: [${$.owners.map((
|
|
1577
|
-
tags: [${$.tags.map((
|
|
1579
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1580
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1578
1581
|
},
|
|
1579
1582
|
definition: {
|
|
1580
1583
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1581
1584
|
`:""} steps: [
|
|
1582
|
-
${
|
|
1585
|
+
${n}
|
|
1583
1586
|
],
|
|
1584
1587
|
transitions: [
|
|
1585
|
-
${
|
|
1588
|
+
${A}
|
|
1586
1589
|
],
|
|
1587
1590
|
},
|
|
1588
1591
|
${$.policyFlags.length>0?`policy: {
|
|
1589
|
-
flags: [${$.policyFlags.map((
|
|
1592
|
+
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1590
1593
|
},`:"// policy: { flags: [] },"}
|
|
1591
1594
|
};
|
|
1592
|
-
`}function
|
|
1593
|
-
`)}function
|
|
1595
|
+
`}function t5($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${Ab($.label)}',`];if($.description)b.push(` description: '${Ab($.description)}',`);let n=[];if($.operation)n.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)n.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(n.length)b.push(` action: { ${n.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1596
|
+
`)}function l5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ab($){return $.replace(/'/g,"\\'")}function Nn({exportName:$,specImportPath:b,workflowFunctionName:n}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1594
1597
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1595
1598
|
import { ${$} } from '${b}';
|
|
1596
1599
|
|
|
1597
|
-
export async function ${
|
|
1600
|
+
export async function ${n}(input = {}, bridge = {}) {
|
|
1598
1601
|
"use workflow";
|
|
1599
1602
|
|
|
1600
1603
|
// Keep the workflow function deterministic.
|
|
@@ -1611,7 +1614,7 @@ export async function ${A}(input = {}, bridge = {}) {
|
|
|
1611
1614
|
},
|
|
1612
1615
|
});
|
|
1613
1616
|
}
|
|
1614
|
-
`}function
|
|
1617
|
+
`}function Fn($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1615
1618
|
import { ${b} } from '${$}';
|
|
1616
1619
|
|
|
1617
1620
|
export const POST = createWorkflowDevkitStartRoute({
|
|
@@ -1620,17 +1623,17 @@ export const POST = createWorkflowDevkitStartRoute({
|
|
|
1620
1623
|
return [body];
|
|
1621
1624
|
},
|
|
1622
1625
|
});
|
|
1623
|
-
`}function
|
|
1626
|
+
`}function vn(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1624
1627
|
|
|
1625
1628
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1626
1629
|
resolveToken({ runId }) {
|
|
1627
1630
|
return \`workflow-session:\${runId}\`;
|
|
1628
1631
|
},
|
|
1629
1632
|
});
|
|
1630
|
-
`}function
|
|
1633
|
+
`}function gn(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1631
1634
|
|
|
1632
1635
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1633
|
-
`}function
|
|
1636
|
+
`}function Pn($,b){return`import { ${b} } from '${$}';
|
|
1634
1637
|
|
|
1635
1638
|
export const workflowDevkitBootstrap = {
|
|
1636
1639
|
workflow: ${b},
|
|
@@ -1642,13 +1645,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1642
1645
|
};
|
|
1643
1646
|
},
|
|
1644
1647
|
};
|
|
1645
|
-
`}function
|
|
1648
|
+
`}function kn({exportName:$,specImportPath:b,runnerName:n,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1646
1649
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1647
1650
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1648
1651
|
import { ${$} } from '${b}';
|
|
1649
1652
|
|
|
1650
1653
|
/**
|
|
1651
|
-
* Runner wiring for ${
|
|
1654
|
+
* Runner wiring for ${A}.
|
|
1652
1655
|
*
|
|
1653
1656
|
* TODO:
|
|
1654
1657
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1660,7 +1663,7 @@ registry.register(${$});
|
|
|
1660
1663
|
|
|
1661
1664
|
const stateStore = new InMemoryStateStore();
|
|
1662
1665
|
|
|
1663
|
-
export const ${
|
|
1666
|
+
export const ${n} = new WorkflowRunner({
|
|
1664
1667
|
registry,
|
|
1665
1668
|
stateStore,
|
|
1666
1669
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1682,12 +1685,12 @@ export const ${A} = new WorkflowRunner({
|
|
|
1682
1685
|
// console.log(event, payload);
|
|
1683
1686
|
},
|
|
1684
1687
|
});
|
|
1685
|
-
`}import{getAuthoringTargetDefinition as
|
|
1686
|
-
`],[
|
|
1688
|
+
`}import{getAuthoringTargetDefinition as p5}from"@contractspec/module.workspace";var uW={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function oW($,b){let n=a5($,b.specPath),A=e5($,b.target,n),m=$.join(n,"package.json"),y=$.join(n,"README.md"),W=$.join(n,"src"),w=$.join(W,"index.ts"),j=O0($.relative(W,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(W);let B=[[m,JSON.stringify({name:A,version:"0.1.0",description:uW[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1689
|
+
`],[y,`# ${A}
|
|
1687
1690
|
|
|
1688
|
-
${
|
|
1689
|
-
`],[
|
|
1690
|
-
`],[b.specPath,b.specCode]],S={packageRoot:
|
|
1691
|
+
${uW[b.target]}.
|
|
1692
|
+
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1693
|
+
`],[b.specPath,b.specCode]],S={packageRoot:n,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function rn($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1691
1694
|
|
|
1692
1695
|
export const ${$.exportName} = defineModuleBundle({
|
|
1693
1696
|
meta: {
|
|
@@ -1712,7 +1715,15 @@ export const ${$.exportName} = defineModuleBundle({
|
|
|
1712
1715
|
layouts: [],
|
|
1713
1716
|
data: [],
|
|
1714
1717
|
verification: {
|
|
1715
|
-
|
|
1718
|
+
dimensions: {
|
|
1719
|
+
guidance: "Scaffolded guidance profile for ${$.title}.",
|
|
1720
|
+
density: "Scaffolded density profile for ${$.title}.",
|
|
1721
|
+
dataDepth: "Scaffolded data-depth profile for ${$.title}.",
|
|
1722
|
+
control: "Scaffolded control profile for ${$.title}.",
|
|
1723
|
+
media: "Scaffolded media profile for ${$.title}.",
|
|
1724
|
+
pace: "Scaffolded pace profile for ${$.title}.",
|
|
1725
|
+
narrative: "Scaffolded narrative profile for ${$.title}.",
|
|
1726
|
+
},
|
|
1716
1727
|
},
|
|
1717
1728
|
},
|
|
1718
1729
|
},
|
|
@@ -1748,22 +1759,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1748
1759
|
supportedArtifactTypes: ["patch"],
|
|
1749
1760
|
knownConstraints: [],
|
|
1750
1761
|
};
|
|
1751
|
-
`}}function
|
|
1762
|
+
`}}function a5($,b){let n=O0(b),A="/src/",m=n.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return n.slice(0,m)}function e5($,b,n){let A=p5(b),m=O0($.basename(n));return`${A.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${m}`}function O0($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function yb($,b,n,A={}){let{fs:m,logger:y,workspace:W}=b,w=W?.scanSpecSource??y8,j=W?.inferSpecTypeFromFilePath??m8,B=W?.generateHandlerTemplate??b8,S=W?.generateComponentTemplate??$8,Q=W?.generateTestTemplate??n8,{targets:Z=void 0,outputDir:X=n.outputDir,overwrite:Y=!1,dryRun:G=!1,includeTests:V=!1,runtimeGeneration:O}=A,K=await m.readFile($),J=w(K,$),U=s5(K,$),H=U==="unknown"?j($):U,q=Z??J0(H,{includeTests:V});y.info(`Building from spec: ${$}`,{targetId:H});let _=[],z={};for(let L of q)try{let C=await W8(L,$,K,J,H,{fs:m,logger:y},X,Y,G,O,z,{genHandler:B,genComponent:S,genTest:Q});if(_.push(C),C.success&&C.generatedCode)z[L]=C.generatedCode}catch(C){_.push({target:L,outputPath:"",success:!1,error:C instanceof Error?C.message:String(C),skipped:!1})}return{specPath:$,specInfo:J,targetId:H,results:_}}async function W8($,b,n,A,m,y,W,w,j,B,S,Q){let{fs:Z,logger:X}=y,{genHandler:Y,genComponent:G,genTest:V}=Q,O,K,J=[];switch($){case"handler":{if(m!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${m})`};let q=A.kind==="command"||A.kind==="query"?A.kind:"command",_=Y(s(n,A,b),q);K=mb(b,W,"handlers",s(n,A,b),".handler.ts",y.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:n,outputPath:K,fallbackCode:_})??_;break}case"component":{if(m!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${m})`};let q=G(s(n,A,b),A.description??"");K=mb(b,W,"components",s(n,A,b),".tsx",y.fs),O=await B?.generateArtifact?.({kind:"component",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"test":{let q=m==="operation"?"handler":"component",_=m==="operation"?S.handler??"":m==="presentation"?S.component??"":m==="form"?S.form??"":"",z=V(s(n,A,b),q);K=mb(b,W,"__tests__",s(n,A,b),".test.ts",y.fs),O=await B?.generateTest?.({kind:q,specCode:n,outputPath:K,existingCode:_,fallbackCode:z})??z;break}case"form":{if(m!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${m})`};let q=`import * as React from "react";
|
|
1752
1763
|
|
|
1753
|
-
export interface ${
|
|
1764
|
+
export interface ${V$(s(n,A,b))}Props {
|
|
1754
1765
|
className?: string;
|
|
1755
1766
|
}
|
|
1756
1767
|
|
|
1757
|
-
export function ${
|
|
1768
|
+
export function ${V$(s(n,A,b))}Form({
|
|
1758
1769
|
className,
|
|
1759
|
-
}: ${
|
|
1760
|
-
return <form className={className}>TODO: implement ${
|
|
1770
|
+
}: ${V$(s(n,A,b))}Props) {
|
|
1771
|
+
return <form className={className}>TODO: implement ${s(n,A,b)}</form>;
|
|
1761
1772
|
}
|
|
1762
|
-
`;K=
|
|
1773
|
+
`;K=mb(b,W,"forms",s(n,A,b),".form.tsx",y.fs),O=await B?.generateArtifact?.({kind:"form",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"workflow-runner":{if(m!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${m})`};let q=s(n,A,b),_=S8(n)??`${V$(q)}Workflow`,z=`${V$(q)}Runner`,L=U0(q);if(K=mb(b,W,"workflows",q,".runner.ts",y.fs),O=kn({exportName:_,specImportPath:V0(y.fs,K,b),runnerName:z,workflowName:q}),X8(n)){let C=`${V$(q)}WorkflowDevkit`,D=_b(y.fs,K,`${L}.workflow-devkit.ts`),F=_b(y.fs,K,`${L}.workflow-devkit.start.route.ts`),E=_b(y.fs,K,`${L}.workflow-devkit.follow-up.route.ts`),r=_b(y.fs,K,`${L}.workflow-devkit.stream.route.ts`),g=_b(y.fs,K,`${L}.workflow-devkit.generic.ts`);J=[{path:D,code:Nn({exportName:_,specImportPath:V0(y.fs,D,b),workflowFunctionName:C})},{path:F,code:Fn(iW(y.fs,F,D),C)},{path:E,code:vn()},{path:r,code:gn()},{path:g,code:Pn(iW(y.fs,g,D),C)}]}break}case"data-view-renderer":{if(m!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${m})`};let q=s(n,A,b),_=Q8(n)??`${V$(q)}DataView`,z=`${V$(q)}Renderer`;K=mb(b,W,"data-views",q,".renderer.tsx",y.fs),O=Tn({exportName:_,specImportPath:V0(y.fs,K,b),rendererName:z,viewKind:Z8(n)??"table"});break}case"package-scaffold":{if(m!=="module-bundle"&&m!=="builder-spec"&&m!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${m})`};if(j){let z=j8(b);return X.info(`[dry-run] Would scaffold package: ${z}`),{target:$,outputPath:z,success:!0}}let q=n.trim().length>0?n:rn({target:m,key:A.key??y.fs.basename(b),title:A.key??y.fs.basename(b),description:A.description??A8(m).title,exportName:V$(A.key??y.fs.basename(b))});return K=(await oW(y.fs,{target:m,specPath:b,specCode:q,overwrite:w})).packageRoot,X.info(`Generated package scaffold: ${K}`),{target:$,outputPath:K,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let U=[{path:K,code:O},...J],H=w?void 0:await w8(U,Z);if(H)return{target:$,outputPath:H,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(j){for(let q of U)X.info(`[dry-run] Would write: ${q.path}`);return{target:$,outputPath:K,success:!0,generatedCode:U[0]?.code}}for(let q of U)await Z.mkdir(Z.dirname(q.path)),await Z.writeFile(q.path,Y8(q.code)),X.info(`Generated: ${q.path}`);return{target:$,outputPath:K,success:!0}}function J0($,b){switch($){case"operation":return b.includeTests?["handler","test"]:["handler"];case"presentation":return b.includeTests?["component","test"]:["component"];case"form":return b.includeTests?["form","test"]:["form"];case"workflow":return["workflow-runner"];case"data-view":return["data-view-renderer"];case"module-bundle":case"builder-spec":case"provider-spec":return["package-scaffold"];default:return[]}}function mb($,b,n,A,m,y){let W=U0(A.split(".").pop()??"unknown"),w;if(b.startsWith("."))w=y.resolve(y.dirname($),"..",b,n);else w=y.resolve(b,n);return y.join(w,`${W}${m}`)}async function w8($,b){for(let n of $)if(await b.exists(n.path))return n.path;return}function U0($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function V$($){return U0($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function K0($){return $.replace(/\.[^.]+$/,"")}function j8($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function V0($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function iW($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function _b($,b,n){return $.join($.dirname(b),n)}function s($,b,n){return B8($,"name")??b.key??K0(G8(n))}function B8($,b){let n=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(n)?.[1]??null}function S8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function Q8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function Z8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function X8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function Y8($){return $.endsWith(`
|
|
1763
1774
|
`)?$:`${$}
|
|
1764
|
-
`}function v8($){return $.replaceAll("\\","/").split("/").pop()??$}s();import{scanAllSpecsFromSource as h8,scanSpecSource as c8}from"@contractspec/module.workspace";import d8 from"micromatch";var Ew={};P(Ew,{validators:()=>f8,urlSchema:()=>r8,isValidVersion:()=>k8,isValidIdentifier:()=>Cw,isValidDotName:()=>Iw,isTestFile:()=>Ob,isLibraryDefinitionFile:()=>Vb,emailSchema:()=>P8});import Bm from"micromatch";function Ob($,b){let A=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return Bm.isMatch($,A)}function Vb($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(Bm.isMatch($,b))return!1;let A=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return Bm.isMatch($,A)}import*as q$ from"zod";function Cw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function Iw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function k8($){return Number.isInteger($)&&$>0}var P8=q$.string().email(),r8=q$.string().url(),f8={specName:q$.string().refine(Iw,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:q$.number().int().positive(),identifier:q$.string().refine(Cw,{message:"Must be a valid TypeScript identifier"}),owner:q$.string().startsWith("@"),tag:q$.string().min(1)};function Jb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function u8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],A=[...Jb($?.conventions.models),...Jb($?.conventions.operations),...Jb($?.conventions.events),...Jb($?.conventions.presentations),...Jb($?.conventions.forms)];return[...new Set(b.flatMap((m)=>{let n=m==="**"?"":`${m}/`,W=X$.map((j)=>`${n}${j}`),w=A.map((j)=>`${n}${j}/**/*.ts`);return[...W,...w]}))]}function o8($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function i8($,b){let A=$.filePath.localeCompare(b.filePath);if(A!==0)return A;let m=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(m!==0)return m;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function g$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((A,m)=>A.localeCompare(m));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:u8(b.config)})}async function xA($,b={}){let A=await g$($.fs,b),m=b.type?Array.isArray(b.type)?b.type:[b.type]:[],n=[];for(let W of A){if(b.config?.excludePackages&&d8.isMatch(W,b.config.excludePackages,{contains:!0}))continue;if(W.includes("node_modules")||W.includes("/dist/")||Ob(W,b.config)||Vb(W))continue;try{let w=await $.fs.readFile(W),j=h8(w,W),y=j.length>0?j:[c8(w,W)];for(let B of y)if(o8(B,b,m))n.push(B)}catch{}}return n.sort(i8)}function _$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function TA($){let b=JSON.parse($),A=new Map,m=0,n=0,W=0,w=0,j=0,y=0,B=0,S=0;for(let[Z,G]of Object.entries(b)){let X=l8(Z,G);A.set(Z,X),m+=X.statements.total,n+=X.statements.covered,W+=X.branches.total,w+=X.branches.covered,j+=X.functions.total,y+=X.functions.covered,B+=X.lines.total,S+=X.lines.covered}let Q={statements:{covered:n,total:m,pct:_$(n,m)},branches:{covered:w,total:W,pct:_$(w,W)},functions:{covered:y,total:j,pct:_$(y,j)},lines:{covered:S,total:B,pct:_$(S,B)}};return{files:A,total:Q}}function l8($,b){let A=Object.keys(b.statementMap).length,m=Object.values(b.s).filter((S)=>S>0).length,n=Object.keys(b.fnMap).length,W=Object.values(b.f).filter((S)=>S>0).length,w=0,j=0;for(let S of Object.values(b.b))w+=S.length,j+=S.filter((Q)=>Q>0).length;let y=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(y.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:m,total:A,pct:_$(m,A)},branches:{covered:j,total:w,pct:_$(j,w)},functions:{covered:W,total:n,pct:_$(W,n)},lines:{covered:B.size,total:y.size,pct:_$(B.size,y.size)}}}function Sm($){switch($){case"istanbul":return{parse:TA};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function Qm($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function Zm($,b,A,m){let n=[];if(A.statements!==void 0&&m.statements.pct<A.statements)n.push({metric:"statements",required:A.statements,actual:m.statements.pct,message:`Statement coverage ${m.statements.pct}% is below required ${A.statements}%`});if(A.branches!==void 0&&m.branches.pct<A.branches)n.push({metric:"branches",required:A.branches,actual:m.branches.pct,message:`Branch coverage ${m.branches.pct}% is below required ${A.branches}%`});if(A.functions!==void 0&&m.functions.pct<A.functions)n.push({metric:"functions",required:A.functions,actual:m.functions.pct,message:`Function coverage ${m.functions.pct}% is below required ${A.functions}%`});if(A.lines!==void 0&&m.lines.pct<A.lines)n.push({metric:"lines",required:A.lines,actual:m.lines.pct,message:`Line coverage ${m.lines.pct}% is below required ${A.lines}%`});if(A.mutations!==void 0)n.push({metric:"mutations",required:A.mutations,actual:0,message:`Mutation coverage required (${A.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:A,actual:m,passed:n.length===0,failures:n}}async function Gm($,b,A){let{fs:m,logger:n}=$,W=[],w=A.workspaceRoot?`${A.workspaceRoot}/coverage`:"./coverage",j=[`${w}/coverage-final.json`,`${w}/coverage.json`,`${w}/coverage-summary.json`],y,B;for(let G of j)if(await m.exists(G)){y=await m.readFile(G),B=G;break}if(!y)return n.info("No coverage report found, skipping coverage checks"),W;let S=Qm(B??"coverage.json"),Z=Sm(S).parse(y);for(let G of b){if(G.specType!=="test-spec"||!G.key||!G.version||!G.sourceBlock)continue;let X=G.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!X||!X[1])continue;let Y=X[1],V={},O=Y.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=Y.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=Y.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let _=Y.match(/lines\s*:\s*(\d+)/);if(_&&_[1])V.lines=parseInt(_[1],10);if(Object.keys(V).length===0)continue;let H=Zm(G.key,G.version,V,Z.total);for(let q of H.failures)W.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:G.filePath,context:{specKey:G.key,specVersion:G.version,metric:q.metric,required:q.required,actual:q.actual}})}return W}s();import{addContractNode as t8,buildReverseEdges as p8,createContractGraph as a8,detectCycles as e8,findMissingDependencies as s8,parseImportedSpecNames as $9,toDot as b9}from"@contractspec/module.workspace";async function Mw($,b={}){let{fs:A}=$,m=await g$(A,{config:b.config,pattern:b.pattern}),n=a8();for(let j of m){let y=await A.readFile(j),B=A.relative(".",j),S=A.basename(j).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=$9(y,j);t8(n,S,B,Q)}p8(n);let W=e8(n),w=s8(n);return{graph:n,total:n.size,cycles:W,missing:w}}function Hq($,b){return $.get(b)}function qq($){return b9($)}function Oq($){let b=Array.from($.values()),A=b.filter((w)=>w.dependencies.length>0),m=b.filter((w)=>w.dependencies.length===0),n=b.filter((w)=>w.dependents.length>0),W=b.filter((w)=>w.dependents.length===0);return{total:$.size,withDeps:A.length,withoutDeps:m.length,used:n.length,unused:W.length}}async function Xm($,b){let A=[],m=await g($.fs),n=await Mw($,{config:m,pattern:b.pattern});for(let W of n.cycles)A.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${W.join(" \u2192 ")}`,category:"deps",context:{cycle:W}});for(let W of n.missing)for(let w of W.missing)A.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${W.contract} requires ${w}`,category:"deps",context:{contract:W.contract,missing:w}});return A}import{analyzePackageDocBlocks as A9}from"@contractspec/module.workspace";var m9=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function n9($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:m9}),m=new Map;for(let w of A){let j=$.dirname(w),y=$.join(j,"src");if(!await $.exists(y))continue;try{let B=JSON.parse(await $.readFile(w));m.set(j,{packageName:B.name??$.relative(b,j),packageRoot:j,srcRoot:y})}catch{continue}}let n=$.join(b,"package.json"),W=$.join(b,"src");if(await $.exists(n)&&await $.exists(W))try{let w=JSON.parse(await $.readFile(n));m.set(b,{packageName:w.name??b,packageRoot:b,srcRoot:W})}catch{}return[...m.values()].sort((w,j)=>w.packageRoot.localeCompare(j.packageRoot))}async function DA($,b){let A=[],m=await n9($,b);for(let n of m){let W=A9({packageName:n.packageName,srcRoot:n.srcRoot});for(let w of W.diagnostics)A.push({...w,packageName:n.packageName,packageRoot:n.packageRoot,srcRoot:n.srcRoot})}return A}async function Ym($,b){let A=b.workspaceRoot??process.cwd();return(await DA($.fs,A)).map((n)=>({ruleId:n.ruleId,severity:n.severity==="warning"?"warning":"error",message:n.message,category:"docs",file:n.file,line:n.line,column:n.column,context:{packageName:n.packageName,packageRoot:n.packageRoot,...n.context}}))}async function Hm($,b,A){let m=[],n=await W9($,b);if(m.push(n),n.status==="pass")m.push(await w9($,b,A));return m}async function W9($,b){let A=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(A))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let n=await $.readFile(A),W=JSON.parse(n),w=W.aiProvider??"claude",j=W.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${w}, Model: ${j}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function w9($,b,A){let m=$.join(b.workspaceRoot,".contractsrc.json");try{let n=await $.readFile(m),w=JSON.parse(n).aiProvider??"claude",y={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[w];if(!y)return{category:"ai",name:"API Key",status:"pass",message:`${w} does not require an API key`};if(!!process.env[y])return{category:"ai",name:"API Key",status:"pass",message:`${y} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${y} not set`,details:`Set ${y} in your environment to use AI features`,fix:A?{description:`Set ${y} environment variable`,apply:async()=>{let S=await A.input(`Enter your ${w} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${y}=`))return{success:!1,message:`${y} already in .env, update manually`};Z+=`
|
|
1765
|
-
`}return Z+=`${
|
|
1766
|
-
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${
|
|
1775
|
+
`}function G8($){return $.replaceAll("\\","/").split("/").pop()??$}$$();import{scanAllSpecsFromSource as U8,scanSpecSource as K8}from"@contractspec/module.workspace";import _8 from"micromatch";var aW={};f(aW,{validators:()=>J8,urlSchema:()=>V8,isValidVersion:()=>q8,isValidIdentifier:()=>lW,isValidDotName:()=>pW,isTestFile:()=>zb,isLibraryDefinitionFile:()=>Lb,emailSchema:()=>O8});import _0 from"micromatch";function zb($,b){let n=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _0.isMatch($,n)}function Lb($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(_0.isMatch($,b))return!1;let n=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return _0.isMatch($,n)}import*as J$ from"zod";function lW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function pW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function q8($){return Number.isInteger($)&&$>0}var O8=J$.string().email(),V8=J$.string().url(),J8={specName:J$.string().refine(pW,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:J$.number().int().positive(),identifier:J$.string().refine(lW,{message:"Must be a valid TypeScript identifier"}),owner:J$.string().startsWith("@"),tag:J$.string().min(1)};function Rb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function z8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],n=[...Rb($?.conventions.models),...Rb($?.conventions.operations),...Rb($?.conventions.events),...Rb($?.conventions.presentations),...Rb($?.conventions.forms)];return[...new Set(b.flatMap((A)=>{let m=A==="**"?"":`${A}/`,y=q$.map((w)=>`${m}${w}`),W=n.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function L8($,b,n){if($.specType==="unknown")return!1;if(b.type&&!n.includes($.specType))return!1;return!0}function R8($,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:z8(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&&_8.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||zb(y,b.config)||Lb(y))continue;try{let W=await $.fs.readFile(y),w=U8(W,y),j=w.length>0?w:[K8(W,y)];for(let B of j)if(L8(B,b,A))m.push(B)}catch{}}return m.sort(R8)}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=C8(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 C8($,b){let n=Object.keys(b.statementMap).length,A=Object.values(b.s).filter((S)=>S>0).length,m=Object.keys(b.fnMap).length,y=Object.values(b.f).filter((S)=>S>0).length,W=0,w=0;for(let S of Object.values(b.b))W+=S.length,w+=S.filter((Q)=>Q>0).length;let j=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(j.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:A,total:n,pct:L$(A,n)},branches:{covered:w,total:W,pct:L$(w,W)},functions:{covered:y,total:m,pct:L$(y,m)},lines:{covered:B.size,total:j.size,pct:L$(B.size,j.size)}}}function z0($){switch($){case"istanbul":return{parse:hn};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function L0($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function R0($,b,n,A){let m=[];if(n.statements!==void 0&&A.statements.pct<n.statements)m.push({metric:"statements",required:n.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${n.statements}%`});if(n.branches!==void 0&&A.branches.pct<n.branches)m.push({metric:"branches",required:n.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${n.branches}%`});if(n.functions!==void 0&&A.functions.pct<n.functions)m.push({metric:"functions",required:n.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${n.functions}%`});if(n.lines!==void 0&&A.lines.pct<n.lines)m.push({metric:"lines",required:n.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${n.lines}%`});if(n.mutations!==void 0)m.push({metric:"mutations",required:n.mutations,actual:0,message:`Mutation coverage required (${n.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:n,actual:A,passed:m.length===0,failures:m}}async function C0($,b,n){let{fs:A,logger:m}=$,y=[],W=n.workspaceRoot?`${n.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await A.exists(X)){j=await A.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=L0(B??"coverage.json"),Z=z0(S).parse(j);for(let X of b){if(X.specType!=="test-spec"||!X.key||!X.version||!X.sourceBlock)continue;let Y=X.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!Y||!Y[1])continue;let G=Y[1],V={},O=G.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=G.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=G.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let U=G.match(/lines\s*:\s*(\d+)/);if(U&&U[1])V.lines=parseInt(U[1],10);if(Object.keys(V).length===0)continue;let H=R0(X.key,X.version,V,Z.total);for(let q of H.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:q.metric,required:q.required,actual:q.actual}})}return y}$$();import{addContractNode as x8,buildReverseEdges as I8,createContractGraph as E8,detectCycles as M8,findMissingDependencies as T8,parseImportedSpecNames as D8,toDot as N8}from"@contractspec/module.workspace";async function eW($,b={}){let{fs:n}=$,A=await c$(n,{config:b.config,pattern:b.pattern}),m=E8();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=D8(j,w);x8(m,S,B,Q)}I8(m);let y=M8(m),W=T8(m);return{graph:m,total:m.size,cycles:y,missing:W}}function VO($,b){return $.get(b)}function JO($){return N8($)}function UO($){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 F8}from"@contractspec/module.workspace";var v8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function g8($,b){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:v8}),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 g8($,b);for(let m of A){let y=F8({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 P8($,b);if(A.push(m),m.status==="pass")A.push(await k8($,b,n));return A}async function P8($,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 k8($,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+=`
|
|
1776
|
+
`}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 r8}from"child_process";import{promisify as f8}from"util";var un=f8(r8);async function M0($,b){let n=[];return n.push(await c8(b)),n.push(await h8(b)),n.push(await d8($,b)),n}async function c8($){try{return await un("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4}),{category:"cli",name:"CLI Accessible",status:"pass",message:"ContractSpec CLI is accessible"}}catch{return{category:"cli",name:"CLI Accessible",status:"fail",message:"ContractSpec CLI is not accessible",details:'Could not run "bunx contractspec --version"',fix:{description:"Install ContractSpec CLI globally",apply:async()=>{try{return await un("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(b){return{success:!1,message:`Failed to install: ${b instanceof Error?b.message:String(b)}`}}}}}}}async function h8($){try{let{stdout:b}=await un("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${b.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function d8($,b){let n=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(n))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let w=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(w))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let m=await $.readFile(n),y=JSON.parse(m);if(y.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||y.devDependencies?.["@contractspec/app.cli-contractspec"]!==void 0)return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is installed as a project dependency"};return{category:"cli",name:"Local Installation",status:"warn",message:"CLI is not installed as a project dependency",details:"Consider adding @contractspec/app.cli-contractspec to devDependencies",fix:{description:"Add CLI as a dev dependency",apply:async()=>{try{return await un("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(w){return{success:!1,message:`Failed to install: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}$$();import{DEFAULT_CONTRACTSRC as on}from"@contractspec/lib.contracts-spec/workspace-config";import{join as u8,relative as o8}from"path";var i8="contractspec",t8="contractsrc.schema.json";function l8($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Cb($){return l8(o8($.configRoot,u8($.workspaceRoot,"node_modules",i8,t8)))}var xb=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],sW={"cli-config":"CLI Configuration (.contractsrc.json)","biome-config":"Biome Configuration (biome.jsonc + plugins)","vscode-settings":"VS Code Settings (.vscode/settings.json)","mcp-cursor":"MCP for Cursor (.cursor/mcp.json)","mcp-claude":"MCP for Claude Desktop","cursor-rules":"Cursor AI Rules (.cursor/rules/)","agents-md":"AI Agent Guide (AGENTS.md)","usage-md":"Usage Guide (USAGE.md)"},$w=["core","connect","builder-managed","builder-local","builder-hybrid"],bw={core:"Core workspace setup",connect:"Connect-enabled setup","builder-managed":"Builder setup (managed runtime)","builder-local":"Builder setup (local runtime)","builder-hybrid":"Builder setup (hybrid runtime)"},nw={core:"Generic ContractSpec workspace files and editor wiring.",connect:"Core workspace setup plus Connect config, artifact storage, and adapter defaults.","builder-managed":"Core workspace setup plus Builder config for managed runtime and API-based next steps.","builder-local":"Core workspace setup plus Builder config for local runtime registration and control-plane-backed next steps.","builder-hybrid":"Core workspace setup plus Builder config for hybrid runtime with API and local defaults."};var Ib={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function Eb($){if($?.builder?.enabled)switch($.builder.runtimeMode){case"local":return"builder-local";case"hybrid":return"builder-hybrid";default:return"builder-managed"}if($?.connect?.enabled)return"connect";return"core"}function R$($){return $.preset??"core"}function Aw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return xb}}function T0($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function mw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function PO($){return $.startsWith("builder-")}function kO($){return $==="connect"}function yw($){let b=R$($),n=p8($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset managed-mvp`,`contractspec builder status --workspace-id ${n}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function p8($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function Ww($){let b=R$($),n=[Ib.verificationCache];if(b==="connect")n.unshift(Ib.connect);return n}function Wb($){let b=$.isMonorepo&&$.scope==="package",n=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,A=a8($),m=e8($);return{$schema:Cb({configRoot:n,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...A?{connect:A}:{},...m?{builder:m}:{},...b&&$.packageName?{package:$.packageName}:{}}}function tn($){let b=R$($),n={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(T0(b))n["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return n}function Mb(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function ww(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function jw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1767
1778
|
|
|
1768
1779
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1769
1780
|
|
|
@@ -1784,10 +1795,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1784
1795
|
## Contract Locations
|
|
1785
1796
|
|
|
1786
1797
|
Contracts are located in:
|
|
1787
|
-
- \`${
|
|
1788
|
-
- \`${
|
|
1789
|
-
- \`${
|
|
1790
|
-
- \`${
|
|
1798
|
+
- \`${A}/operations/\` - Command and query specs
|
|
1799
|
+
- \`${A}/events/\` - Event specs
|
|
1800
|
+
- \`${A}/presentations/\` - UI presentation specs
|
|
1801
|
+
- \`${A}/features/\` - Feature module specs
|
|
1791
1802
|
|
|
1792
1803
|
## When Making Changes
|
|
1793
1804
|
|
|
@@ -1829,7 +1840,7 @@ defineCommand({
|
|
|
1829
1840
|
- Events must be declared in contracts before being emitted.
|
|
1830
1841
|
- UI components should reference presentation contracts.
|
|
1831
1842
|
- Feature flags should be defined in feature modules.
|
|
1832
|
-
`}function
|
|
1843
|
+
`}function Bw($){let b=$.projectName??"this project",n=$.isMonorepo&&$.scope==="package",A=R$($),m=n&&$.packageName?`${$.packageName} package`:b,y="src/contracts",W=$.isMonorepo?n?`
|
|
1833
1844
|
## Monorepo Scope
|
|
1834
1845
|
|
|
1835
1846
|
This guide is scoped to the current package.
|
|
@@ -1843,7 +1854,7 @@ This guide is scoped to the workspace root.
|
|
|
1843
1854
|
- Prefer the nearest package guide when working inside a specific package.
|
|
1844
1855
|
`:"";return`# ContractSpec AI Guide
|
|
1845
1856
|
|
|
1846
|
-
Scope: \`${
|
|
1857
|
+
Scope: \`${m}\`
|
|
1847
1858
|
|
|
1848
1859
|
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1849
1860
|
|
|
@@ -1853,7 +1864,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
|
|
|
1853
1864
|
- Validate contracts after changes with \`contractspec validate\`.
|
|
1854
1865
|
- Regenerate derived artifacts before considering the work complete.
|
|
1855
1866
|
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1856
|
-
${
|
|
1867
|
+
${W}
|
|
1857
1868
|
## Contract Locations
|
|
1858
1869
|
|
|
1859
1870
|
- \`src/contracts/operations/\` - command and query specs
|
|
@@ -1889,8 +1900,8 @@ ${w}
|
|
|
1889
1900
|
|
|
1890
1901
|
## Initialization Preset
|
|
1891
1902
|
|
|
1892
|
-
- This workspace was initialized with the \`${
|
|
1893
|
-
`}function
|
|
1903
|
+
- This workspace was initialized with the \`${A}\` setup preset.
|
|
1904
|
+
`}function Sw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1894
1905
|
|
|
1895
1906
|
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1896
1907
|
|
|
@@ -1919,16 +1930,100 @@ This workspace uses ContractSpec to keep contracts, generated artifacts, and AI
|
|
|
1919
1930
|
|
|
1920
1931
|
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1921
1932
|
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1922
|
-
`}function
|
|
1923
|
-
`}async function Jm($,b){let A=[];return A.push(await J9($,b)),A.push(await K9($,b)),A.push(await _9($,b)),A.push(await U9($,b)),A.push(await z9($,b)),A.push(await L9($,b)),A.push(await R9($,b)),A}async function k$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function J9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(await $.exists(A))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let n=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,N(n)),{success:!0,message:"Created .contractsrc.json"}}catch(n){return{success:!1,message:`Failed to create: ${n instanceof Error?n.message:String(n)}`}}}}}}async function K9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A);return JSON.parse(n),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(n){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:n instanceof Error?n.message:String(n),fix:{description:"Replace with valid default config",apply:async()=>{try{let w=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,N(w)),{success:!0,message:"Replaced with valid config"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}}async function _9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n),w=[];if(!W.outputDir)w.push("outputDir");if(!W.conventions)w.push("conventions");if(w.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${w.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let j=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let y of w)if(j[y]!==void 0)W[y]=j[y];return await $.writeFile(A,N(W)),{success:!0,message:"Added missing fields"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function U9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:W.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return W.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(A,N(W)),{success:!0,message:"Added versioning configuration"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function z9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.hooks){let y=W.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(y).length} git hook(s) configured`}}let w=$.join(b.workspaceRoot,".husky");if(await $.exists(w))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return W.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(A,N(W)),{success:!0,message:"Added hooks configuration"}}catch(y){return{success:!1,message:`Failed: ${y instanceof Error?y.message:String(y)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function L9($,b){let A=await k$($,b),m=await g($,A),n=zb(m);if(n==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(n==="connect"){let j=[m.connect?.storage?.root?null:"storage.root",m.connect?.storage?.contextPack?null:"storage.contextPack",m.connect?.storage?.planPacket?null:"storage.planPacket",m.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),y=m.connect?.studio?.enabled&&m.connect?.studio?.mode==="review-bridge"&&!m.connect?.studio?.endpoint;if(j.length===0&&!y)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...j,...y?["connect.studio.endpoint"]:[]].join(", ")}`}}let W=[],w=m.builder?.api?.controlPlaneTokenEnvVar;if(n.startsWith("builder-")&&!m.builder?.api?.baseUrl)W.push("builder.api.baseUrl");if(n.startsWith("builder-")&&!w)W.push("builder.api.controlPlaneTokenEnvVar");if(n.startsWith("builder-")&&w&&!process.env[w])W.push(`env:${w}`);if((n==="builder-local"||n==="builder-hybrid")&&!m.builder?.localRuntime?.runtimeId)W.push("builder.localRuntime.runtimeId");if((n==="builder-local"||n==="builder-hybrid")&&!m.builder?.localRuntime?.grantedTo)W.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:W.length===0?"pass":"warn",message:W.length===0?`Builder preset inferred (${n}) and required config is present`:`Builder preset inferred (${n}) but setup is missing ${W.join(", ")}`}}async function R9($,b){let A=await k$($,b),m=await g($,A),n=zb(m);if(!n.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let W=$.join(A,".vscode","settings.json"),w=m.builder?.api?.baseUrl;if(!w)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let j=await $.readFile(W).catch(()=>""),y=j?p(j):void 0;if(y?.["contractspec.api.baseUrl"]===w)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(A,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...y??{},...vA({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:n,targets:[],builderApiBaseUrl:w})};return await $.writeFile(W,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as C9}from"child_process";import{promisify as I9}from"util";var P$=I9(C9);async function Km($,b){let A=[];return A.push(await E9(b)),A.push(await M9(b)),A.push(await x9($,b)),A.push(await T9($,b)),A.push(await D9($,b)),A}async function E9($){try{let{stdout:b}=await P$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function M9($){try{let{stdout:b}=await P$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function x9($,b){let A=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],m=null;for(let{file:n,name:W}of A){let w=$.join(b.workspaceRoot,n);if(await $.exists(w)){m=W;break}}if(!m){let n=$.join(b.workspaceRoot,".."),W=$.join(b.workspaceRoot,"../.."),w=[n,W];for(let j of w){for(let{file:y,name:B}of A){let S=$.join(j,y);if(await $.exists(S)){m=B;break}}if(m)break}}if(!m)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await P$(`${m} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${m}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${m} detected but not available`,details:`Install ${m} or use a different package manager`}}}async function T9($,b){let A=$.join(b.workspaceRoot,"node_modules");if(await $.exists(A))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await P$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await P$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(n){return{success:!1,message:`Failed: ${n instanceof Error?n.message:String(n)}`}}}}}}async function D9($,b){let A=$.join(b.workspaceRoot,"package.json");try{let m=await $.readFile(A),n=JSON.parse(m),W={...n.dependencies,...n.devDependencies};if("@contractspec/lib.contracts-spec"in W)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${W["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await P$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await P$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function _m($,b){let A=await DA($,b.workspaceRoot);if(A.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return A.map((m)=>({category:"docs",name:`Same-File DocBlocks (${m.packageName})`,status:m.severity==="warning"?"warn":"fail",message:m.message,details:$.relative(b.workspaceRoot,m.file),context:{ruleId:m.ruleId,file:m.file,line:m.line,column:m.column,packageName:m.packageName}}))}import{isExampleFile as N9,isFeatureFile as F9,scanAllSpecsFromSource as v9,scanExampleSource as g9,scanFeatureSource as k9}from"@contractspec/module.workspace";function P9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function PA($,b={}){let{fs:A,logger:m}=$,n=P9(),W=b.pattern??"**/*.{ts,tsx}";m.info("Scanning for contract layer files...");let w=await A.glob({pattern:W});for(let y of w){if(y.includes("node_modules")||y.includes("/dist/"))continue;try{let B=await A.readFile(y);if(F9(y)){let S=k9(B,y);n.features.set(S.key,S);continue}if(N9(y)){let S=g9(B,y);n.examples.set(S.key,S);continue}if(y.includes(".app-config.")||y.includes(".blueprint.")){let S=v9(B,y);for(let Q of S)if(Q.specType==="app-config"&&Q.key)n.appConfigs.set(Q.key,Q)}}catch{}}try{let y=await A.glob({pattern:"**/.contractsrc.json"});for(let B of y){if(B.includes("node_modules"))continue;try{let S=await A.readFile(B),Q=JSON.parse(S);n.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){n.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let j={features:n.features.size,examples:n.examples.size,appConfigs:n.appConfigs.size,workspaceConfigs:n.workspaceConfigs.size,total:n.features.size+n.examples.size+n.appConfigs.size+n.workspaceConfigs.size};return m.info(`Discovered ${j.features} features, ${j.examples} examples, ${j.appConfigs} app configs, ${j.workspaceConfigs} workspace configs`),{inventory:n,stats:j}}function $O($){let b=[];for(let[A,m]of $.features)b.push({key:A,file:m.filePath,type:"feature"});for(let[A,m]of $.examples)b.push({key:A,version:m.version,file:m.filePath,type:"example"});for(let[A,m]of $.appConfigs)b.push({key:A,version:m.version,file:m.filePath,type:"app-config"});for(let[,A]of $.workspaceConfigs)b.push({key:A.file,file:A.file,type:"workspace-config"});return b}function rA($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function Um($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function fA($,b){let A=$.join(b,"config/stability-policy.json");if(!await $.exists(A))return;try{let m=await $.readFile(A),n=JSON.parse(m);return{version:typeof n.version==="number"&&Number.isFinite(n.version)?n.version:1,criticalPackages:Um(n.criticalPackages).map(rA),criticalFeatureKeys:Um(n.criticalFeatureKeys),smokePackages:Um(n.smokePackages)}}catch{return}}function cw($,b){let A=rA($);if(b?.criticalPackages.includes(A))return"critical";return"non-critical"}function dw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function Ab($){return rA(`${rA($)}/config/stability-policy.json`)}async function zm($,b){let A=[],m=await fA($,b.workspaceRoot),n=await PA({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return A.push(r9(n.stats.features)),A.push(f9(n.stats.examples)),A.push(h9(n.inventory.features,m,b)),A.push(c9(n.inventory.examples)),A.push(d9(n.inventory.workspaceConfigs)),A}function r9($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function f9($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function h9($,b,A){let m=[],n=[];for(let[W,w]of $)if(!(Boolean(w.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(w.sourceBlock??"")))if(dw(W,b))n.push(W);else m.push(W);if(n.length===0&&m.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:b?Ab(A.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:n.length>0?"fail":"warn",message:n.length>0?`${n.length} critical feature(s) missing owners`:`${m.length} feature(s) missing owners`,details:n.length>0?`Critical features: ${n.join(", ")}`:`Features: ${m.slice(0,3).join(", ")}${m.length>3?"...":""}`,context:{policyPath:b?Ab(A.workspaceRoot):void 0,criticalMissingFeatures:n,missingFeatures:m}}}function c9($){let b=[];for(let[A,m]of $)if(!m.entrypoints.packageName)b.push(A);if(b.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function d9($){let b=[];for(let[,A]of $)if(!A.valid)b.push(A.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function Lm($,b){let A=[];return A.push(await u9($,b)),A.push(await o9($,b)),A.push(await i9($,b)),A}async function u9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(A))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let n=$.join(b.workspaceRoot,".cursor");if(!await $.exists(n))await $.mkdir(n);let W=Lb();return await $.writeFile(A,N(W)),{success:!0,message:"Created .cursor/mcp.json"}}catch(n){return{success:!1,message:`Failed: ${n instanceof Error?n.message:String(n)}`}}}}}}async function o9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(A))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let j=Lb(),y=$$(W,j);return await $.writeFile(A,N(y)),{success:!0,message:"Registered MCP server"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function i9($,b){let A=gA();try{if(!await $.exists(A))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let n=await $.readFile(A);if(JSON.parse(n).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var l9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],uw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function t9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,m])=>{if(typeof m==="string")b[A]=m;return b},{})}function p9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function a9($,b,A){let m=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:uw}),n=[];for(let W of m){let w=$.dirname(W),j=$.relative(b,w);try{let y=JSON.parse(await $.readFile(W)),B=t9(y.scripts),S=await $.glob({patterns:l9,cwd:w,ignore:uw});n.push({packageName:y.name??j,packagePath:j.replace(/\\/g,"/"),hasBuildScript:typeof B.build==="string",hasTypecheckScript:typeof B.typecheck==="string",hasLintScript:typeof B.lint==="string"||typeof B["lint:check"]==="string",hasTestScript:typeof B.test==="string",usesPassWithNoTests:p9(B),testFileCount:S.length,tier:cw(j,A)})}catch{continue}}return n}function e9($){let b=[];if(!$.hasBuildScript)b.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)b.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)b.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)b.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)b.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)b.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return b}function s9($){let b=[];if($.testFileCount>0&&!$.hasTestScript)b.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)b.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return b}async function ow($,b,A){let m=await a9($,b,A),n=[];for(let w of m){if(w.tier==="critical")n.push(...e9(w));n.push(...s9(w))}let W=m.filter((w)=>w.tier==="critical").map((w)=>({packageName:w.packageName,packagePath:w.packagePath,hasBuildScript:w.hasBuildScript,hasTypecheckScript:w.hasTypecheckScript,hasLintScript:w.hasLintScript,hasTestScript:w.hasTestScript,usesPassWithNoTests:w.usesPassWithNoTests,testFileCount:w.testFileCount}));return{findings:n,criticalPackages:W}}function lw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function iw($,b,A,m){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:m,context:{findings:[]}};let n=b.filter((W)=>{return W.tier==="critical"||A.has(W.code)});return{category:"workspace",name:$,status:n.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:lw(b),context:{findings:b}}}async function tw($,b){let A=await fA($,b.workspaceRoot);if(!A)return[];let m=await ow($,b.workspaceRoot,A),n=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),W=m.findings.filter((y)=>n.has(y.code)),w=m.findings.filter((y)=>y.code==="tests-without-test-script"),j=m.findings.filter((y)=>y.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:W.length>0?"fail":"pass",message:W.length>0?`${W.length} critical package gate failure(s)`:`All ${m.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:W.length>0?lw(W):b.verbose?`Policy: ${Ab(b.workspaceRoot)}`:void 0,context:{policyPath:Ab(b.workspaceRoot),criticalPackages:m.criticalPackages,findings:W}},iw("Package Test Scripts",w,new Set,"All tested packages expose a test script"),iw("Buildable Packages Without Tests",j,new Set,"All buildable packages have tests or explicit test scripts")]}var $S=["src/contracts","contracts","src/specs","specs"];async function Rm($,b){let A=[];return A.push(bS(b)),A.push(await AS($,b)),A.push(await mS($,b)),A.push(await nS($,b)),A.push(await wS($,b)),A.push(...await tw($,b)),A}function bS($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",A=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${A}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function AS($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let m of A){let n=$.join(m,"package.json");if(await $.exists(n))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${m}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function mS($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],m=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let w of A)for(let j of $S){let y=$.join(w,j);if(await $.exists(y)){let B=w===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${j}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let n=b.isMonorepo?"src/contracts":"src/contracts",W=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${n}/${W} to organize your specs`,fix:{description:`Create ${n}/ directory${W}`,apply:async()=>{try{let w=$.join(m,"src","contracts");return await $.mkdir(w),{success:!0,message:`Created ${n}/`}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}async function nS($,b){try{let A=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],m=b.isMonorepo?b.packageRoot:b.workspaceRoot,n=await $.glob({patterns:A,ignore:["node_modules/**","dist/**"],cwd:m});if(n.length>0){let w=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${n.length} contract file(s)${w}`,details:b.verbose?n.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:b.isMonorepo?`No contract files found in package "${b.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function WS($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let m=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(m))return{path:m,root:b.packageRoot,level:"package"}}let A=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.workspaceRoot,level:"workspace"};return null}async function wS($,b){try{let A=await WS($,b);if(!A)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let m=await $.readFile(A.path),n=JSON.parse(m),W=n.outputDir??"./src",w=$.join(A.root,W),j=b.isMonorepo?` (${A.level} level)`:"";if(await $.exists(w))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${W}${j}`,details:b.verbose?`Resolved to: ${w}`:void 0};let B=W==="./src"||W==="src",S=Array.isArray(n.packages)&&n.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||A.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${A.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${W}${j}`,details:b.verbose?`Expected at: ${w}`:void 0,fix:{description:`Create ${W} directory`,apply:async()=>{try{return await $.mkdir(w),{success:!0,message:`Created ${W}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var pw=["cli","config","mcp","deps","docs","workspace","ai","layers"],aw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var jS={checks:{runCliChecks:qm,runConfigChecks:Jm,runMcpChecks:Lm,runDepsChecks:Km,runDocChecks:_m,runWorkspaceChecks:Rm,runAiChecks:Hm,runLayerChecks:zm},workspace:{findWorkspaceRoot:M,findPackageRoot:r,isMonorepo:Gb,getPackageName:T$}},yS={confirm:async()=>!1,input:async()=>""};async function ew($,b,A=yS,m=jS){let{fs:n,logger:W}=$,w=b.categories??pw,{checks:j,workspace:y}=m,B=y.findWorkspaceRoot(b.workspaceRoot),S=y.findPackageRoot(b.workspaceRoot),Q=y.isMonorepo(B),Z=Q?y.getPackageName(S):void 0,G={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";W.info(`Detected monorepo${J}`)}let X=[];for(let J of w){if(b.skipAi&&J==="ai")continue;W.info(`Checking ${aw[J]}...`);let _=await BS(J,n,G,A,j);for(let H of _){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await A.confirm(`Fix "${H.name}"? ${H.fix.description}`)){W.info(`Applying fix: ${H.fix.description}`);let U=await H.fix.apply();if(U.success)W.info(`\u2713 ${U.message}`),H.status="pass",H.message=`Fixed: ${U.message}`,H.fix=void 0;else W.warn(`\u2717 ${U.message}`)}}X.push(H)}}let Y=X.filter((J)=>J.status==="pass").length,V=X.filter((J)=>J.status==="warn").length,O=X.filter((J)=>J.status==="fail").length,K=X.filter((J)=>J.status==="skip").length;return{checks:X,passed:Y,warnings:V,failures:O,skipped:K,healthy:O===0}}async function BS($,b,A,m,n){switch($){case"cli":return n.runCliChecks(b,A);case"config":return n.runConfigChecks(b,A);case"mcp":return n.runMcpChecks(b,A);case"deps":return n.runDepsChecks(b,A);case"docs":return n.runDocChecks(b,A);case"workspace":return n.runWorkspaceChecks(b,A);case"ai":return n.runAiChecks(b,A,m);case"layers":return n.runLayerChecks(b,A);default:return[]}}function EO($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1924
|
-
`)}function
|
|
1925
|
-
${$.details}`;if($.fix)
|
|
1926
|
-
Fix available: ${$.fix.description}`;return
|
|
1927
|
-
|
|
1928
|
-
${$.body}`;await
|
|
1929
|
-
`).length},w,j=new RegExp(Cb.contractHandler);while((w=j.exec($))!==null)if(w[1])n(w[1],"handler",W(w.index));let y=new RegExp(Cb.typeofSpec);while((w=y.exec($))!==null)if(w[1])n(w[1],"typeof",W(w.index));let B=new RegExp(Cb.namedImport);while((w=B.exec($))!==null){let G=w[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(G)for(let X of G)n(X,"import",W(w.index))}let S=new RegExp(Cb.defaultImport);while((w=S.exec($))!==null)if(w[1])n(w[1],"import",W(w.index));let Q=new RegExp(Cb.specAssignment);while((w=Q.exec($))!==null)if(w[1])n(w[1],"unknown",W(w.index));return A}var Wj=["**/*.ts(x)"];async function uA($,b,A={}){let{fs:m}=b,n=A.includePatterns??Wj,W=A.excludePatterns??[...new Set([...x$,...X$])],w=[];for(let j of n){let y=await m.glob({pattern:j,ignore:W});for(let B of y)try{let S=await m.readFile(B),Z=nj(S,B).filter((G)=>G.specKey===$);w.push(...Z)}catch{}}return w}async function ZV($,b={}){let{fs:A}=$,m=b.includePatterns??Wj,n=b.excludePatterns??[...new Set([...x$,...X$])],W=new Map;for(let w of m){let j=await A.glob({pattern:w,ignore:n});for(let y of j)try{let B=await A.readFile(y),S=nj(B,y);for(let Q of S){let Z=W.get(Q.specKey)??[];Z.push(Q),W.set(Q.specKey,Z)}}catch{}}return W}function TS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function wj($,b,A){let m=TS(b),n=[];if($==="operation")n.push({path:`${A}/handlers/${m}.handler.ts`,type:"handler"}),n.push({path:`${A}/handlers/${m}.handler.test.ts`,type:"test"});if($==="presentation")n.push({path:`${A}/components/${m}.tsx`,type:"component"}),n.push({path:`${A}/components/${m}.test.tsx`,type:"test"});if($==="form")n.push({path:`${A}/forms/${m}.form.tsx`,type:"form"}),n.push({path:`${A}/forms/${m}.form.test.tsx`,type:"test"});if($==="event")n.push({path:`${A}/handlers/${m}.handler.ts`,type:"handler"}),n.push({path:`${A}/handlers/${m}.handler.test.ts`,type:"test"});return n}import{Node as t,Project as DS,SyntaxKind as NS}from"ts-morph";function jj($){let b=[],m=new DS({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),n=(y)=>{if(!t.isObjectLiteralExpression(y))return;let B=y.getProperty("implementations");if(B&&t.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&t.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(t.isObjectLiteralExpression(Q)){let Z,G,X,Y=Q.getProperty("path");if(Y&&t.isPropertyAssignment(Y)){let K=Y.getInitializer();if(t.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&t.isPropertyAssignment(V)){let K=V.getInitializer();if(t.isStringLiteral(K))G=K.getLiteralText()}let O=Q.getProperty("description");if(O&&t.isPropertyAssignment(O)){let K=O.getInitializer();if(t.isStringLiteral(K))X=K.getLiteralText()}if(Z&&G)b.push({path:Z,type:G,description:X})}}}},W=m.getDescendantsOfKind(NS.CallExpression);for(let y of W){let B=y.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=y.getArguments();if(S.length>0&&t.isObjectLiteralExpression(S[0]))return n(S[0]),b}}let w=m.getVariableStatements();for(let y of w)if(y.isExported())for(let B of y.getDeclarations()){let S=B.getInitializer();if(S&&t.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return n(S),b}}let j=m.getExportAssignment((y)=>!y.isExportEquals());if(j){let y=j.getExpression();if(t.isObjectLiteralExpression(y))n(y);else if(t.isAsExpression(y)&&t.isObjectLiteralExpression(y.getExpression()))n(y.getExpression())}return b}function yj($){if($.length===0)return"missing";let b=$.filter((n)=>n.exists),A=$.filter((n)=>n.type!=="test");if(b.filter((n)=>n.type!=="test").length===0)return"missing";if($.every((n)=>n.exists))return"implemented";return"partial"}function qV($){let b=$.filter((n)=>n.status==="implemented").length,A=$.filter((n)=>n.status==="partial").length,m=$.filter((n)=>n.status==="missing").length;return{total:$.length,implemented:b,partial:A,missing:m,coverage:$.length>0?Math.round(b/$.length*100):100}}var gS={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Bj($){return FS("sha256").update($).digest("hex")}async function kS($,b,A,m={},n){let W={...gS,...m},w=W.computeHashes?Bj($.sourceBlock||""):void 0,j=$.key??vS.basename($.filePath).replace(/\.[jt]s$/,""),y=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(X,Y,V,O)=>{if(Q.has(X))return;Q.add(X);let K=await B.exists(X),J=void 0,_=void 0;if(K&&W.computeHashes)try{J=await B.readFile(X),_=Bj(J)}catch{}S.push({path:X,type:Y,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:_,description:O})};if(W.includeExplicit&&$.sourceBlock){if(n)n.suffixText="Discover explicit implementations";let X=jj($.sourceBlock);for(let Y of X)await Z(Y.path,Y.type,"explicit",Y.description)}if(W.includeDiscovered){if(n)n.suffixText="Discover implementations";let X=await uA(j,b,W);for(let Y of X){if(Y.filePath===$.filePath)continue;await Z(Y.filePath,Y.inferredType,"discovered")}}if(W.includeConvention){if(n)n.suffixText="Discover implementations based on conventions";let X=W.outputDir??A.outputDir??"./src",Y=wj($.specType,j,X);for(let{path:V,type:O}of Y)await Z(V,O,"convention")}if(n)n.suffixText="Determine implementation status";let G=yj(S);return{specKey:j,specVersion:y,specPath:$.filePath,specType:$.specType,implementations:S,status:G,specHash:w}}async function Sj($,b,A,m={},n){let W=[];for(let w of $){if(n)n.text=`Resolving implementation... (${W.length}/${$.length})`;try{let j=await kS(w,b,A,m,n);W.push(j)}catch(j){console.error(`Failed to resolve implementations for ${w}:`,j)}}return W}async function Dm($,b,A){let{fs:m}=$,n=[],W=await g(m),w=A.implementation??{},j=b.filter((B)=>B.specType==="operation"),y=await Sj(j,{fs:m},W,{computeHashes:w.useCache??!0});for(let B of y){if(w.requireImplemented&&B.status==="missing")n.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")n.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!w.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);n.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)n.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return n}s();import{isFeatureFile as fS,scanAllSpecsFromSource as hS,scanFeatureSource as cS}from"@contractspec/module.workspace";function PS($,b){return`${$}.v${b}`}function Nm($,b,A,m,n,W={}){let{treatMissingAsError:w=!0}=W;if(!m||m.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let j=[],y=[],B=[];for(let S of m){let Q=PS(S.key,S.version);if(n.has(Q))j.push(S);else if(y.push(S),w)B.push(`Spec ${b}.v${A} references test ${S.key}.v${S.version} which does not exist`)}return{valid:y.length===0,foundTests:j,missingTests:y,errors:B,specFile:$}}function Qj($,b){return`${$}.v${b}`}function Zj($,b){let A=new Map,m=new Map,n=[],W=[];for(let w of $){if(!w.key||!w.version)continue;let j=Qj(w.key,w.version);if(!w.testTarget){W.push(j);continue}let{type:y,key:B,version:S}=w.testTarget,Q=S??w.version,Z=Qj(B,Q),G=rS(b,y);if(!G||!G.has(Z)){n.push(j);continue}if(m.set(j,Z),!A.has(Z))A.set(Z,new Set);A.get(Z)?.add(j)}return{targetToTests:A,testToTarget:m,orphanedTests:n,testsWithoutTarget:W}}function rS($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function b$($,b){return`${$}.v${b}`}function dS(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function Fm($,b){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[b]}async function oA($,b={}){let{fs:A,logger:m}=$;m.info("Starting integrity analysis...",{options:b});let n=await g$(A,{config:b.config,cwd:b.cwd,pattern:b.pattern}),W=dS(),w=[],j=[];for(let H of n){if((await A.stat(H)).isDirectory)continue;let U=await A.readFile(H);if(fS(H)){let z=cS(U,H);w.push(z)}else{let z=hS(U,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let I=Fm(W,L.specType);if(I&&L.key&&L.version!==void 0){let C=b$(L.key,L.version);I.set(C,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let y=b.featureKey?w.filter((H)=>H.key===b.featureKey):w,B=new Set;for(let H of y){for(let q of H.operations){let U=b$(q.key,q.version);if(B.add(`operation:${U}`),!W.operations.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let U=b$(q.key,q.version);if(B.add(`event:${U}`),!W.events.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let U=b$(q.key,q.version);if(B.add(`presentation:${U}`),!W.presentations.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let U=b$(q.key,q.version);if(B.add(`experiment:${U}`),!W.experiments.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let U=b$(q.key,q.version);if(B.add(`capability:${U}`),!W.capabilities.has(U))j.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let U=b$(q.key,q.version);B.add(`capability:${U}`)}for(let q of H.opToPresentationLinks){let U=b$(q.op.key,q.op.version),z=b$(q.pres.key,q.pres.version);if(!W.operations.has(U))j.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!W.presentations.has(z))j.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let U=b$(q.key,q.version);if(!W.presentations.has(U))j.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=Fm(W,H);if(!q)continue;for(let[U,z]of q)if(!B.has(`${H}:${U}`))S.push(z),j.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of W.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let G=Zj(Z,W);for(let H of y)for(let q of H.opToPresentationLinks){let U=b$(q.op.key,q.op.version),z=G.targetToTests.get(U),L=!1,I=!1;if(z)for(let C of z){let F=W.testSpecs.get(C);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)I=!0}}if(!z||!L||!I){let C=[];if(!L)C.push("success scenario");if(!I)C.push("error scenario");j.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${C.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let X={},Y=0;for(let H of Q){let q=Fm(W,H);if(!q)continue;let U=q.size,z=0,L=0,I=b.requireTestsFor?.includes(H);for(let[C,F]of q){if(B.has(`${H}:${C}`))z++;if(I){let x=b$(F.key,F.version),h=G.targetToTests.has(x),nA=`${F.key}.test`,r1=W.testSpecs.has(b$(nA,F.version));if(!h&&!r1)L++,Y++,j.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}X[H]={total:U,covered:z,orphaned:U-z,missingTest:I?L:0}}let V=Object.values(X).reduce((H,q)=>H+q.total,0),O=Object.values(X).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:Y,byType:X},_=!j.some((H)=>H.severity==="error");return m.info("Integrity analysis complete",{features:w.length,totalSpecs:V,orphaned:S.length,issues:j.length,healthy:_}),{inventory:W,features:y,coverage:K,issues:j,orphanedSpecs:S,healthy:_}}function kV($){let b=[];for(let A of Object.values($))for(let m of A.values())b.push(m);return b}function PV($,b){return $.filter((A)=>A.type===b)}function rV($,b){return $.filter((A)=>A.severity===b)}async function vm($,b){let A=[],m=await g($.fs),n=await oA($,{config:m,pattern:b.pattern,all:!0});for(let W of n.issues)A.push({ruleId:`integrity-${W.type}`,severity:W.severity==="error"?"error":"warning",message:W.message,category:"integrity",file:W.file,context:{specKey:W.specKey,specType:W.specType,featureKey:W.featureKey,ref:W.ref}});return A}async function gm($,b){let A=[],m=await PA($,{});for(let[n,W]of m.inventory.features){if(!W.key)A.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:W.filePath,context:{key:n}});if(!W.owners?.length)A.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${n}' missing 'owners' field`,category:"layers",file:W.filePath,context:{key:n}});if(W.operations.length===0&&W.events.length===0&&W.presentations.length===0)A.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${n}' has no operations, events, or presentations`,category:"layers",file:W.filePath,context:{key:n}})}for(let[n,W]of m.inventory.examples){if(!W.entrypoints.packageName)A.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${n}' missing 'packageName' in entrypoints`,category:"layers",file:W.filePath,context:{key:n}});if(!W.surfaces.templates&&!W.surfaces.sandbox.enabled&&!W.surfaces.studio.enabled&&!W.surfaces.mcp.enabled)A.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${n}' has no enabled surfaces`,category:"layers",file:W.filePath,context:{key:n}})}for(let n of m.inventory.workspaceConfigs.values())if(!n.valid)for(let W of n.errors)A.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${W}`,category:"layers",file:n.file});return A}s();import{ContractsrcSchema as oS,DEFAULT_CONTRACTSRC as iA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as uS}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:A,scan:m=uS}=$,n=await g$(A,b),W=[],w=Array.isArray(b.type)?b.type:[b.type];for(let j of n){if(Ob(j,b.config))continue;if(Vb(j))continue;try{let y=await A.readFile(j),B=m(y,j);if(B.specType==="unknown")continue;if(b.type&&!w.includes(B.specType))continue;W.push(B)}catch{}}return W}function pV($){let b=new Map;for(let A of $){let m=b.get(A.specType)??[];m.push(A),b.set(A.specType,m)}return b}var iS=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,lS=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,tS=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,pS=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,aS=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,eS=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,sS=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function lA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function $Q($,b){let A=$.replaceAll("\\","/"),m=new Set(["contracts","features",...lA(b?.conventions?.operations),...lA(b?.conventions?.events),...lA(b?.conventions?.presentations),...lA(b?.conventions?.forms)]);return A.split("/").some((n)=>m.has(n))}function bQ($,b,A){let m=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(m))return!1;if(m.includes("/node_modules/")||m.includes("/dist/")||aS.test(m)||pS.test(m)||m.endsWith(".d.ts")||m.endsWith(".test.ts")||m.endsWith(".spec.ts"))return!1;if(b.has(m))return!1;if($Q(m,A))return!1;return iS.test(m)}function Gj($){return $.replaceAll("\\","/").match(eS)?.[1]??null}function AQ($){let b=$.split(`
|
|
1930
|
-
`).map((A)=>A.trim()).filter((A)=>A.length>0&&!A.startsWith("//")&&!A.startsWith("/*")&&!A.startsWith("*")&&!A.startsWith("*/"));return b.length>0&&b.every((A)=>A.startsWith("import ")||A.startsWith("export *")||A.startsWith("export {")||A.startsWith("export type {")||A==="'use client';"||A==='"use client";'||A==="'use server';"||A==='"use server";')}function mQ($){if(!$)return iA;let b=oS.safeParse($),A=b.success?b.data:{};return{...iA,...A,conventions:{...iA.conventions,...A.conventions??{}},ci:{...iA.ci,...A.ci??{}}}}async function km($,b){let{fs:A,logger:m}=$,n=[],W=b.config?mQ(b.config):await g(A),w=await j$({fs:A},{config:W}),j=new Set(w.map((S)=>S.filePath.replaceAll("\\","/"))),y=new Set(w.map((S)=>Gj(S.filePath)).filter((S)=>Boolean(S))),B=await A.glob({pattern:"**/*.{ts,tsx}"});for(let S of B){if(!bQ(S,j,W))continue;try{let Q=await A.readFile(S);if(AQ(Q))continue;let Z=Gj(S);if(!(Z!==null&&sS.test(Z)&&y.has(Z))&&!tS.test(Q))continue;if(lS.test(Q))continue;n.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:S})}catch(Q){m.warn("Policy scan failed for file",{file:S,error:Q instanceof Error?Q.message:String(Q)})}}return n}import{validateSpecStructure as nQ}from"@contractspec/module.workspace";async function Pm($){let b=[];for(let A of $){let m=nQ(A);for(let n of m.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:n,category:"structure",file:A.filePath});for(let n of m.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:n,category:"structure",file:A.filePath})}return b}async function rm($){let b=[],A=new Map,m=new Map;for(let n of $){if(!n.key||!n.version)continue;if(n.specType==="test-spec"){let W=`${n.key}.v${n.version}`;A.set(W,{key:n.key,version:n.version,file:n.filePath,type:"test-spec"})}if(n.testRefs&&n.testRefs.length>0){if(!m.has(n.filePath))m.set(n.filePath,[]);m.get(n.filePath)?.push({key:n.key,version:n.version,testRefs:n.testRefs})}}for(let[n,W]of m)for(let w of W){if(!w.testRefs)continue;let j=Nm(n,w.key,w.version,w.testRefs,A,{treatMissingAsError:!0});for(let y of j.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:y,category:"test-refs",file:n,context:{specKey:w.key,specVersion:w.version,missingTests:j.missingTests}})}return b}s();async function fm($,b){let{fs:A}=$,m=[],n=await g(A);for(let W of b){if(W.specType!=="operation")continue;let w=await dA(W,{fs:A},n,{checkTests:!0,outputDir:n.outputDir});for(let j of w.errors)m.push({ruleId:"test-missing",severity:"warning",message:j,category:"tests",file:W.filePath});for(let j of w.warnings)m.push({ruleId:"test-warning",severity:"warning",message:j,category:"tests",file:W.filePath})}return m}function a($,b,A){let m={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},n=b.filter((j)=>j.severity==="error").length,W=b.filter((j)=>j.severity==="warning").length,w=b.filter((j)=>j.severity==="note").length;return{category:$,label:m[$],errors:n,warnings:W,notes:w,passed:n===0,durationMs:A}}async function Xj($){try{if(!await $.exists(".git/HEAD"))return{};let A=await $.readFile(".git/HEAD"),m=A.match(/^ref: (.+)$/m);if(m){let W=m[1]?.replace("refs/heads/",""),w=`.git/${m[1]}`;if(await $.exists(w))return{commitSha:(await $.readFile(w)).trim(),branch:W};return{branch:W}}return{commitSha:A.trim()}}catch{return{}}}function Yj($){let b=$.config?.ci?.checks,A=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)A.push("handlers");if($.checkTests)A.push("tests");if($.implementation)A.push("implementation");if($.checkDrift)A.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return A.filter((m)=>!$.skip?.includes(m));return A}async function IJ($,b={}){let A=Date.now(),{fs:m,logger:n}=$,W=[],w=[],j=Yj(b);n.info("Starting CI checks...",{checks:j});let y=await g(m),B=await xA($,{config:y,pattern:b.pattern});if(j.includes("structure")){let V=Date.now(),O=await Pm(B);W.push(...O),w.push(a("structure",O,Date.now()-V))}if(j.includes("integrity")){let V=Date.now(),O=await vm($,b);W.push(...O),w.push(a("integrity",O,Date.now()-V))}if(j.includes("deps")){let V=Date.now(),O=await Xm($,b);W.push(...O),w.push(a("deps",O,Date.now()-V))}if(j.includes("doctor")){let V=Date.now(),O=await Cm($,b);W.push(...O),w.push(a("doctor",O,Date.now()-V))}if(j.includes("docs")){let V=Date.now(),O=await Ym($,b);W.push(...O),w.push(a("docs",O,Date.now()-V))}if(j.includes("policy")){let V=Date.now(),O=await km($,b);W.push(...O),w.push(a("policy",O,Date.now()-V))}if(j.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await Tm($,B);W.push(...O),w.push(a("handlers",O,Date.now()-V))}if(j.includes("tests")||b.checkTests){let V=Date.now(),O=await fm($,B);W.push(...O),w.push(a("tests",O,Date.now()-V))}if(j.includes("test-refs")){let V=Date.now(),O=await rm(B);W.push(...O),w.push(a("test-refs",O,Date.now()-V))}if(j.includes("coverage")){let V=Date.now(),O=await Gm($,B,b);W.push(...O),w.push(a("coverage",O,Date.now()-V))}if(j.includes("implementation")){let V=Date.now(),O=await Dm($,B,b);W.push(...O),w.push(a("implementation",O,Date.now()-V))}if(j.includes("layers")){let V=Date.now(),O=await gm($,b);W.push(...O),w.push(a("layers",O,Date.now()-V))}if(j.includes("drift")){let V=Date.now(),O=await xm($,b);W.push(...O),w.push(a("drift",O,Date.now()-V))}let S=W.filter((V)=>V.severity==="error").length,Q=W.filter((V)=>V.severity==="warning").length,Z=W.filter((V)=>V.severity==="note").length,G=b.failOnWarnings?S===0&&Q===0:S===0,X=await Xj(m),Y={success:G,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:W,categories:w,durationMs:Date.now()-A,timestamp:new Date().toISOString(),...X};return n.info("CI checks complete",{success:G,errors:S,warnings:Q,durationMs:Y.durationMs}),Y}var MJ=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],xJ={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function vJ($,b={}){let{fs:A,logger:m}=$,n=(b.outputDir??"./src").replace(/\\/g,"/"),W=["generated/**","dist/**",".turbo/**"],w=[`${n}/handlers/**/*.handler.ts`,`${n}/handlers/**/*.handler.test.ts`,`${n}/components/**/*.tsx`,`${n}/components/**/*.test.tsx`,`${n}/forms/**/*.form.tsx`,`${n}/forms/**/*.form.test.tsx`,`${n}/**/*.runner.ts`,`${n}/**/*.renderer.tsx`],j=b.generatedOnly?[...W,...w]:[...W,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...w],y=await A.glob({patterns:j,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of y)try{let Z=await A.stat(Q),G=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&G<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)m.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await A.remove(Q),m.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}s();var cj={};P(cj,{writeReviewPacket:()=>An,writeDecisionEnvelope:()=>Fb,withBranch:()=>f$,verifyConnectMutation:()=>Q4,resolveWorkspace:()=>o,resolveStoragePaths:()=>Q$,replayConnectDecision:()=>cQ,persistLatestArtifacts:()=>$n,persistDecisionArtifacts:()=>Nb,normalizeEvalInput:()=>NQ,matchConfiguredPath:()=>Ib,loadStoredDecision:()=>vb,listStoredReviewPackets:()=>mn,listConnectReviewPackets:()=>dQ,isReviewCommand:()=>hm,isDeniedCommand:()=>cm,isAllowedCommand:()=>tA,initConnectWorkspace:()=>PQ,inferSurfaces:()=>xb,evaluateConnectDecision:()=>TQ,ensureStorage:()=>Db,defaultActor:()=>Mb,decisionArtifactRefs:()=>nb,createConnectControlPlaneRuntime:()=>$4,connectVerdictToPolicy:()=>z$,configuredThreshold:()=>r$,compileConnectPlanPacket:()=>gb,buildConnectContextPack:()=>Tb,assessConnectPolicy:()=>Eb,assertConnectEnabled:()=>A$,artifactRef:()=>J$,appendAuditRecord:()=>bn,analyzeConnectImpact:()=>h$,CONTROL_PLANE_TRACE_GET_REF:()=>pA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>aA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>im,CONTROL_PLANE_PLAN_COMPILE_REF:()=>om,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>um,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>O$,AGENT_APPROVALS_REF:()=>eA,ACP_TERMINAL_EXEC_REF:()=>yQ,ACP_FS_ACCESS_REF:()=>jQ});import WQ from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function Ib($,b,A){if(!A||A.length===0)return!1;let m=b.replaceAll("\\","/");return WQ.isMatch(m,A,{contains:!0})}function r$($,b,A){return $.config.connect?.policy?.reviewThresholds?.[b]??A}function tA($,b){return dm($.config.connect?.commands?.allow,b)}function hm($,b){return dm($.config.connect?.commands?.review,b)}function cm($,b){return dm($.config.connect?.commands?.deny,b)}function dm($,b){if(!$||$.length===0)return!1;return $.some((A)=>b===A||b.startsWith(`${A} `))}function qj($,b){if(b.length===0)return{state:"none"};for(let m of b)if(cm($,m))return{commandMatch:m,state:"deny"};for(let m of b)if(hm($,m))return{commandMatch:m,state:"review"};if(b.every((m)=>tA($,m)))return{state:"allow"};let A=b.find(wQ);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((m)=>!tA($,m)),state:"unknown"}}function wQ($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return Hj(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return Hj(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function Hj($,b){return b.every((A)=>$.includes(A)||$.includes(A.replace("-","")))}var um={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},om={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},im={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},pA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},aA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},O$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},jQ={key:"acp.fs.access",version:"1.0.0",kind:"command"},yQ={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},eA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Eb($,b){let A=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.immutablePaths)),m=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.protectedPaths)),n=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:W,state:w}=qj($,b.commands??[]),j=b.impactAnalysis.unknownPaths.length>0,y=b.impactAnalysis.driftFiles.length>0,B=BQ({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:w==="destructive",commandState:w,contractDrift:y,generatedPath:Boolean(n),immutable:Boolean(A),protectedPath:Boolean(m),smokeFailed:b.smokeFailed===!0,unknownImpact:j,workspace:$}),S=SQ({breakingChange:b.impactAnalysis.breakingChange,commandMatch:W,commandState:w,contractDrift:y,protectedPath:m,unknownPaths:b.impactAnalysis.unknownPaths}),Q=z$(B);return{commandMatch:W,commandState:w,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:n,immutablePath:A,protectedPath:m,requiredApprovals:Q.requiresApproval?[{capability:O$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function z$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function BQ($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(r$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(r$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(r$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(r$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(r$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(QQ)[0]??"permit"}function SQ($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function QQ($,b){return Oj($)-Oj(b)}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as MQ}from"crypto";var Uj={};P(Uj,{formatPrComment:()=>Vj,formatMinimalComment:()=>lm,formatJson:()=>Kj,formatCheckRun:()=>Jj,detectImpact:()=>V$,ImpactDetectionOverviewDocBlock:()=>qQ});function Vj($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)A.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else A.push("\u2705 **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| \u2796 Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let m=$.deltas.filter((W)=>W.severity==="breaking"),n=$.deltas.filter((W)=>W.severity==="non_breaking");if(m.length>0){A.push("#### \uD83D\uDD34 Breaking Changes"),A.push("");for(let W of m)A.push(`- **${W.specKey}**: ${W.description}`);A.push("")}if(n.length>0){A.push("#### \uD83D\uDFE1 Non-breaking Changes"),A.push("");for(let W of n)A.push(`- **${W.specKey}**: ${W.description}`);A.push("")}}if($.addedSpecs.length>0){A.push("### Added Specs"),A.push("");for(let m of $.addedSpecs)A.push(`- \`${m.key}\` v${m.version} (${m.type})`);A.push("")}if($.removedSpecs.length>0){A.push("### Removed Specs"),A.push("");for(let m of $.removedSpecs)A.push(`- \`${m.key}\` v${m.version} (${m.type})`);A.push("")}if(b.drift)if(b.drift.hasDrift){A.push("### \u26A0\uFE0F Drift Detected"),A.push(""),A.push("The following generated files are out of sync with their specs:"),A.push("");for(let m of b.drift.files)A.push(`- \`${m}\``);A.push(""),A.push("Run `contractspec generate` to regenerate artifacts."),A.push("")}else A.push("### \u2705 No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
1931
|
-
|
|
1933
|
+
`}function a8($){if(R$($)!=="connect")return;return{...on.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin",packageRef:"contractspec-adoption"},codex:{enabled:!0,mode:"wrapper",packageRef:"contractspec-adoption"},"claude-code":{enabled:!0,mode:"rule",packageRef:"contractspec-adoption"}},adoption:{...on.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:on.connect?.studio}}function e8($){let b=T0(R$($)),n=mw(R$($));if(!b||!n)return;let A=!0,m=b==="local"||b==="hybrid";return{...on.builder,enabled:!0,runtimeMode:b,bootstrapPreset:n,api:A?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:m?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function ln(){let $=process.platform,b=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${b}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??b}/Claude/claude_desktop_config.json`;default:return`${b}/.config/claude/claude_desktop_config.json`}}function b$($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(m===void 0)n[A]=y;else if(pn(m)&&pn(y))n[A]=b$(m,y)}return n}function D0($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(y===void 0)continue;if(pn(m)&&pn(y))n[A]=D0(m,y);else n[A]=y}return n}function pn($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function a($){try{return JSON.parse($)}catch{return null}}function N($){return JSON.stringify($,null,2)+`
|
|
1934
|
+
`}async function N0($,b){let n=[];return n.push(await s8($,b)),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}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 s8($,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 $9($,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 b9($,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 n9($,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 A9($,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 m9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),j=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(w.length===0&&!j)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...w,...j?["connect.studio.endpoint"]:[]].join(", ")}`}}let y=[],W=A.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!A.builder?.api?.baseUrl)y.push("builder.api.baseUrl");if(m.startsWith("builder-")&&!W)y.push("builder.api.controlPlaneTokenEnvVar");if(m.startsWith("builder-")&&W&&!process.env[W])y.push(`env:${W}`);if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)y.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:y.length===0?"pass":"warn",message:y.length===0?`Builder preset inferred (${m}) and required config is present`:`Builder preset inferred (${m}) but setup is missing ${y.join(", ")}`}}async function y9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(n,".vscode","settings.json"),W=A.builder?.api?.baseUrl;if(!W)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let w=await $.readFile(y).catch(()=>""),j=w?a(w):void 0;if(j?.["contractspec.api.baseUrl"]===W)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(n,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...tn({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as W9}from"child_process";import{promisify as w9}from"util";var d$=w9(W9);async function F0($,b){let n=[];return n.push(await j9(b)),n.push(await B9(b)),n.push(await S9($,b)),n.push(await Q9($,b)),n.push(await Z9($,b)),n}async function j9($){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 B9($){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 S9($,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 Q9($,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 Z9($,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 X9,isFeatureFile as Y9,scanAllSpecsFromSource as G9,scanExampleSource as H9,scanFeatureSource as q9}from"@contractspec/module.workspace";function O9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function an($,b={}){let{fs:n,logger:A}=$,m=O9(),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(Y9(j)){let S=q9(B,j);m.features.set(S.key,S);continue}if(X9(j)){let S=H9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=G9(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 AV($){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(V9(m.stats.features)),n.push(J9(m.stats.examples)),n.push(U9(m.inventory.features,A,b)),n.push(K9(m.inventory.examples)),n.push(_9(m.inventory.workspaceConfigs)),n}function V9($){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 J9($){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 U9($,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 K9($){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 _9($){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 z9($,b)),n.push(await L9($,b)),n.push(await R9($,b)),n}async function z9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(n))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Mb();return await $.writeFile(n,N(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function L9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(n))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let w=Mb(),j=b$(y,w);return await $.writeFile(n,N(j)),{success:!0,message:"Registered MCP server"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function R9($,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 C9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Xw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function x9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[n,A])=>{if(typeof A==="string")b[n]=A;return b},{})}function I9($){return Object.entries($).some(([b,n])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(n)})}async function E9($,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=x9(j.scripts),S=await $.glob({patterns:C9,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:I9(B),testFileCount:S.length,tier:Qw(w,n)})}catch{continue}}return m}function M9($){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 T9($){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 E9($,b,n),m=[];for(let W of A){if(W.tier==="critical")m.push(...M9(W));m.push(...T9(W))}let y=A.filter((W)=>W.tier==="critical").map((W)=>({packageName:W.packageName,packagePath:W.packagePath,hasBuildScript:W.hasBuildScript,hasTypecheckScript:W.hasTypecheckScript,hasLintScript:W.hasLintScript,hasTestScript:W.hasTestScript,usesPassWithNoTests:W.usesPassWithNoTests,testFileCount:W.testFileCount}));return{findings:m,criticalPackages:y}}function Hw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Gw($,b,n,A){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||n.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:Hw(b),context:{findings:b}}}async function qw($,b){let n=await sn($,b.workspaceRoot);if(!n)return[];let A=await Yw($,b.workspaceRoot,n),m=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),y=A.findings.filter((j)=>m.has(j.code)),W=A.findings.filter((j)=>j.code==="tests-without-test-script"),w=A.findings.filter((j)=>j.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:y.length>0?"fail":"pass",message:y.length>0?`${y.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?Hw(y):b.verbose?`Policy: ${wb(b.workspaceRoot)}`:void 0,context:{policyPath:wb(b.workspaceRoot),criticalPackages:A.criticalPackages,findings:y}},Gw("Package Test Scripts",W,new Set,"All tested packages expose a test script"),Gw("Buildable Packages Without Tests",w,new Set,"All buildable packages have tests or explicit test scripts")]}var D9=["src/contracts","contracts","src/specs","specs"];async function r0($,b){let n=[];return n.push(N9(b)),n.push(await F9($,b)),n.push(await v9($,b)),n.push(await g9($,b)),n.push(await k9($,b)),n.push(...await qw($,b)),n}function N9($){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 F9($,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 v9($,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 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(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 g9($,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 P9($,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 k9($,b){try{let n=await P9($,b);if(!n)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(n.path),m=JSON.parse(A),y=m.outputDir??"./src",W=$.join(n.root,y),w=b.isMonorepo?` (${n.level} level)`:"";if(await $.exists(W))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${y}${w}`,details:b.verbose?`Resolved to: ${W}`:void 0};let B=y==="./src"||y==="src",S=Array.isArray(m.packages)&&m.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||n.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${n.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${y}${w}`,details:b.verbose?`Expected at: ${W}`:void 0,fix:{description:`Create ${y} directory`,apply:async()=>{try{return await $.mkdir(W),{success:!0,message:`Created ${y}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var Ow=["cli","config","mcp","deps","docs","workspace","ai","layers"],Vw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var r9={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$}},f9={confirm:async()=>!1,input:async()=>""};async function Jw($,b,n=f9,A=r9){let{fs:m,logger:y}=$,W=b.categories??Ow,{checks:w,workspace:j}=A,B=j.findWorkspaceRoot(b.workspaceRoot),S=j.findPackageRoot(b.workspaceRoot),Q=j.isMonorepo(B),Z=Q?j.getPackageName(S):void 0,X={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${J}`)}let Y=[];for(let J of W){if(b.skipAi&&J==="ai")continue;y.info(`Checking ${Vw[J]}...`);let U=await c9(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,O=Y.filter((J)=>J.status==="fail").length,K=Y.filter((J)=>J.status==="skip").length;return{checks:Y,passed:G,warnings:V,failures:O,skipped:K,healthy:O===0}}async function c9($,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 TV($){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 DV($){let n=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)n+=`
|
|
1936
|
+
${$.details}`;if($.fix)n+=`
|
|
1937
|
+
Fix available: ${$.fix.description}`;return n}async function f0($,b){let n=[],A=b.workspaceRoot??process.cwd(),m=await Jw($,{workspaceRoot:A,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let y of m.checks)if(y.status==="fail")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});else if(y.status==="warn")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});return n}$$();import{mkdtemp as mQ,rm as yQ}from"fs/promises";import{tmpdir as WQ}from"os";import Tb from"path";import{DEFAULT_CONTRACTSRC as p9}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as a9}from"@contractspec/module.workspace";import e9 from"path";import{packageDocBlocks as h9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as d9,convertSpecToDocBlock as u9,extractModuleDocData as o9,loadSpecFromSource as i9,scanAllSpecsFromSource as t9,scanSpecSource as l9}from"@contractspec/module.workspace";import h0 from"path";import{dirname as Uw,sep as $A}from"path";class c0{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let n;if(b.specType==="app-config")n="app-config";else if(b.specType==="example")n="example";else if(b.specType==="feature")n="feature";if(n&&b.key){let A=Uw(b.filePath);this.modules.push({type:n,key:b.key,dirPath:A})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=Uw($),n=this.modules.filter((A)=>{let m=A.dirPath.endsWith($A)?A.dirPath:A.dirPath+$A;return(b.endsWith($A)?b:b+$A).startsWith(m)||b===A.dirPath});if(n.length===0)return;return n.sort((A,m)=>{let y={"app-config":3,example:2,feature:1},W=y[A.type],w=y[m.type];if(W!==w)return w-W;return m.dirPath.length-A.dirPath.length}),n[0]}}async function _w($,b,n){let{fs:A,logger:m}=n,y=[];if(m.info(`Generating docs for ${$.length} files...`),b.outputDir)await A.mkdir(b.outputDir);let W=new c0(n),w=[];for(let B of $)try{let S=await A.readFile(B),Q=t9(S,B);if(Q.length>0)w.push(...Q);else{let Z=l9(S,B);if(Z.specType!=="unknown")w.push(Z)}}catch(S){}W.initialize(w);let j=await zw($,n);for(let B of j)if(y.push(B.entry.block),m.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await Kw(B.entry.block,B.filePath,b.outputDir,W,A);for(let B of $)try{let S=await i9(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=u9(Q,{rootPath:b.rootPath});if(y.push(Z),m.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await Kw(Z,B,b.outputDir,W,A)}}catch(S){m.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)m.info(`Wrote ${y.length} doc files to ${b.outputDir}`);return{blocks:y,count:y.length}}async function hV($,b){return(await zw($,b)).map(({entry:A})=>A.block)}function dV($,b){return h9(d9({packageName:$,srcRoot:b}))}async function zw($,b){let n=[...new Set($)].sort((m,y)=>m.localeCompare(y)),A=[];for(let m of n){let y=await b.fs.readFile(m),W=m.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),w=o9(y,m,W);for(let j of w.entries)A.push({entry:j,filePath:m})}return A}async function Kw($,b,n,A,m){let y=A.resolve(b),W=y?h0.join(n,y.key):h0.join(n,"_common");await m.mkdir(W);let w=h0.join(W,`${$.id}.md`),j=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1938
|
+
|
|
1939
|
+
${$.body}`;await m.writeFile(w,j)}async function Lw($,b,n,A,m={}){let y=m.config,W=await cn($,{cwd:m.specSearchRoot,config:y,pattern:m.specPattern??$Q(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=e9.join(bQ(n,y),"docs"),j=await _w(W.map((S)=>S.filePath),{outputDir:w,format:"markdown",rootPath:A},$),B=0;for(let S of W){let Q=s9(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await yb(S.filePath,$,y??p9,{targets:J0(S.specType,{includeTests:Boolean(m.includeRuntimeTests)}),outputDir:y?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((X)=>X.success).length}return{specsCount:W.length,docsCount:j.count,materializedCount:B}}function s9($){return a9($.specType)}function $Q($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${d0($)}/**/*.ts`:void 0}function bQ($,b){let n=(b?.connect?.policy?.generatedPaths??[]).map(AQ).filter(Boolean);if(n.length>0)return n[0];if(b?.outputDir&&b.outputDir!=="./src")return d0(b.outputDir);return $}function nQ($){return d0($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function AQ($){let b=nQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function d0($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function bA($,b,n,A={}){let m=await mQ(Tb.join(WQ(),"contractspec-drift-"));try{await Lw($,b,m,A.rootPath,A.generation);let y=[],W=await import("fs/promises");async function w(Z){let X=await W.readdir(Z,{withFileTypes:!0}),Y=[];for(let G of X){let V=Tb.resolve(Z,G.name);if(G.isDirectory())Y.push(...await w(V));else Y.push(V)}return Y}let j=async(Z)=>{if(!await W.stat(Z).catch(()=>!1))return[];return(await w(Z)).map((Y)=>Tb.relative(Z,Y)).sort()},B=await j(m),S=await j(n),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){y.push(Z);continue}if(!B.includes(Z)){y.push(Z);continue}let X=await W.readFile(Tb.join(m,Z)),Y=await W.readFile(Tb.join(n,Z));if(!X.equals(Y))y.push(Z)}return{hasDrift:y.length>0,files:y}}finally{await yQ(m,{recursive:!0,force:!0})}}async function u0($,b){let{fs:n,logger:A}=$,m=[],y=await P(n);if(!y.outputDir)return A.info("No outputDir configured, skipping drift checks"),m;let W="./contracts",w=y.outputDir;if(!await n.exists(w))return A.info("Generated directory does not exist, skipping drift checks"),m;try{let j=await bA($,W,w);if(j.hasDrift)for(let B of j.files)m.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${w}/${B}`,context:{file:B}})}catch(j){A.warn("Drift detection failed",{error:j instanceof Error?j.message:String(j)})}return m}$$();function wQ($){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 nA($,b,n,A={}){let{fs:m}=b,y=[],W=[],w=$.key??m.basename($.filePath).replace(/\.[jt]s$/,""),j=A.outputDir??n.outputDir??"./src",B=wQ(w),S={};if($.specType==="operation")S.handlerPath=m.join(j,"handlers",`${B}.handler.ts`),S.handlerTestPath=m.join(j,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=m.join(j,"components",`${B}.tsx`),S.componentTestPath=m.join(j,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=m.join(j,"forms",`${B}.form.tsx`),S.formTestPath=m.join(j,"forms",`${B}.form.test.tsx`);if(A.checkHandlers&&S.handlerPath)if(!await m.exists(S.handlerPath))y.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await m.readFile(S.handlerPath),X=`${jQ(w.split(".").pop()??w)}Spec`,Y=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),G=new RegExp(`typeof\\s+${X}\\b`).test(Z);if(!Y)W.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!G)W.push(`Handler ContractHandler typing does not reference expected spec var (${X}): ${S.handlerPath}`)}if(A.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await m.exists(Z))y.push(`Missing test file: ${Z}`)}return{valid:y.length===0,errors:y,warnings:W,expected:S}}async function o0($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkHandlers:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"handler-missing",severity:"warning",message:w,category:"handlers",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"handler-warning",severity:"warning",message:w,category:"handlers",file:y.filePath})}return A}$$();import{createHash as YQ}from"crypto";import GQ from"path";var Db={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},BQ={".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 SQ($){let b=$.toLowerCase();for(let[n,A]of Object.entries(BQ))if(b.endsWith(n))return A;if(b.includes("/handlers/"))return"handler";if(b.includes("/services/"))return"service";if(b.includes("/components/"))return"component";if(b.includes("/forms/"))return"form";if(b.includes("/hooks/"))return"hook";if(b.includes("/__tests__/"))return"test";return"other"}function Rw($,b){let n=[],A=new Set,m=(Z,X,Y)=>{let G=`${Z}:${X}`;if(A.has(G))return;A.add(G),n.push({filePath:b,specKey:Z,referenceType:X,lineNumber:Y,inferredType:SQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1940
|
+
`).length},W,w=new RegExp(Db.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Db.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Db.namedImport);while((W=B.exec($))!==null){let X=W[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(X)for(let Y of X)m(Y,"import",y(W.index))}let S=new RegExp(Db.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Db.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return n}var Cw=["**/*.ts(x)"];async function AA($,b,n={}){let{fs:A}=b,m=n.includePatterns??Cw,y=n.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await A.glob({pattern:w,ignore:y});for(let B of j)try{let S=await A.readFile(B),Z=Rw(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function GJ($,b={}){let{fs:n}=$,A=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of A){let w=await n.glob({pattern:W,ignore:m});for(let j of w)try{let B=await n.readFile(j),S=Rw(B,j);for(let Q of S){let Z=y.get(Q.specKey)??[];Z.push(Q),y.set(Q.specKey,Z)}}catch{}}return y}function QQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,n){let A=QQ(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 ZQ,SyntaxKind as XQ}from"ts-morph";function Iw($){let b=[],A=new ZQ({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),m=(j)=>{if(!p.isObjectLiteralExpression(j))return;let B=j.getProperty("implementations");if(B&&p.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&p.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(p.isObjectLiteralExpression(Q)){let Z,X,Y,G=Q.getProperty("path");if(G&&p.isPropertyAssignment(G)){let K=G.getInitializer();if(p.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&p.isPropertyAssignment(V)){let K=V.getInitializer();if(p.isStringLiteral(K))X=K.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let K=O.getInitializer();if(p.isStringLiteral(K))Y=K.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=A.getDescendantsOfKind(XQ.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 JJ($){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 HQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Mw($){return YQ("sha256").update($).digest("hex")}async function qQ($,b,n,A={},m){let y={...HQ,...A},W=y.computeHashes?Mw($.sourceBlock||""):void 0,w=$.key??GQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,G,V,O)=>{if(Q.has(Y))return;Q.add(Y);let K=await B.exists(Y),J=void 0,U=void 0;if(K&&y.computeHashes)try{J=await B.readFile(Y),U=Mw(J)}catch{}S.push({path:Y,type:G,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:U,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Iw($.sourceBlock);for(let G of Y)await Z(G.path,G.type,"explicit",G.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await AA(w,b,y);for(let G of Y){if(G.filePath===$.filePath)continue;await Z(G.filePath,G.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??n.outputDir??"./src",G=xw($.specType,w,Y);for(let{path:V,type:O}of G)await Z(V,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Ew(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function Tw($,b,n,A={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await 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 JQ,scanAllSpecsFromSource as UQ,scanFeatureSource as KQ}from"@contractspec/module.workspace";function OQ($,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=OQ(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=VQ(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 VQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function _Q(){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=_Q(),W=[],w=[];for(let H of m){if((await n.stat(H)).isDirectory)continue;let _=await n.readFile(H);if(JQ(H)){let z=KQ(_,H);W.push(z)}else{let z=UQ(_,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let C=l0(y,L.specType);if(C&&L.key&&L.version!==void 0){let D=n$(L.key,L.version);C.set(D,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let j=b.featureKey?W.filter((H)=>H.key===b.featureKey):W,B=new Set;for(let H of j){for(let q of H.operations){let _=n$(q.key,q.version);if(B.add(`operation:${_}`),!y.operations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let _=n$(q.key,q.version);if(B.add(`event:${_}`),!y.events.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let _=n$(q.key,q.version);if(B.add(`presentation:${_}`),!y.presentations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let _=n$(q.key,q.version);if(B.add(`experiment:${_}`),!y.experiments.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let _=n$(q.key,q.version);if(B.add(`capability:${_}`),!y.capabilities.has(_))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let _=n$(q.key,q.version);B.add(`capability:${_}`)}for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=n$(q.pres.key,q.pres.version);if(!y.operations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let _=n$(q.key,q.version);if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=l0(y,H);if(!q)continue;for(let[_,z]of q)if(!B.has(`${H}:${_}`))S.push(z),w.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of y.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let X=Nw(Z,y);for(let H of j)for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=X.targetToTests.get(_),L=!1,C=!1;if(z)for(let D of z){let F=y.testSpecs.get(D);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)C=!0}}if(!z||!L||!C){let D=[];if(!L)D.push("success scenario");if(!C)D.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${D.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let Y={},G=0;for(let H of Q){let q=l0(y,H);if(!q)continue;let _=q.size,z=0,L=0,C=b.requireTestsFor?.includes(H);for(let[D,F]of q){if(B.has(`${H}:${D}`))z++;if(C){let E=n$(F.key,F.version),r=X.targetToTests.has(E),g=`${F.key}.test`,iA=y.testSpecs.has(n$(g,F.version));if(!r&&!iA)L++,G++,w.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}Y[H]={total:_,covered:z,orphaned:_-z,missingTest:C?L:0}}let V=Object.values(Y).reduce((H,q)=>H+q.total,0),O=Object.values(Y).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:G,byType:Y},U=!w.some((H)=>H.severity==="error");return A.info("Integrity analysis complete",{features:W.length,totalSpecs:V,orphaned:S.length,issues:w.length,healthy:U}),{inventory:y,features:j,coverage:K,issues:w,orphanedSpecs:S,healthy:U}}function fJ($){let b=[];for(let n of Object.values($))for(let A of n.values())b.push(A);return b}function cJ($,b){return $.filter((n)=>n.type===b)}function hJ($,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 hQ,DEFAULT_CONTRACTSRC as WA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as zQ}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:n,scan:A=zQ}=$,m=await c$(n,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(zb(w,b.config))continue;if(Lb(w))continue;try{let j=await n.readFile(w),B=A(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function sJ($){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:()=>kQ,resolvePackageDeclarationConfig:()=>Nb,renderPackageDeclaration:()=>Wm,normalizePath:()=>C$,matchesAllowMissing:()=>ym,inferWorkspacePackageKind:()=>s0,getIndexExportPath:()=>bm,getCanonicalDeclarationRelativePath:()=>$m,discoverWorkspacePackages:()=>gw,createPackageDeclarationIssue:()=>wm,buildPackageTitle:()=>Fb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>G$,buildDomain:()=>Am,buildDeclarationTags:()=>mm,auditPackageDeclarations:()=>vb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>e0,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>Fw});var Fw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},e0={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function Nb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...Fw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function s0($){let b=C$($);for(let[n,A]of Object.entries(e0))if(b.startsWith(n))return A;return null}function $m($,b){switch($){case"libs":case"modules":return`src/${b}.feature.ts`;case"integrations":return"src/integration.ts";case"apps":case"appsRegistry":return"src/blueprint.ts";case"bundles":return`src/bundles/${yA(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function bm($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${yA(b)}Bundle`;case"examples":return"./example"}}function nm($){return C$($).replace(/^packages\//,"").replace(/\//g,".")}function Fb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Am($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function mm($,b,n){return[...new Set([...n,"package",b,$])]}function ym($,b,n){return $.some((A)=>{let m=C$(A);return m===C$(b)||m===n})}function C$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function yA($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function G$($,b){let n=yA(b);switch($){case"feature":return`${n}Feature`;case"integration":return`${n}IntegrationSpec`;case"app-config":return`${n}Blueprint`;case"module-bundle":return`${n}Bundle`;case"example":return`${n}Example`}}import{scanAllSpecsFromSource as LQ,scanSpecSource as RQ}from"@contractspec/module.workspace";var CQ=["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 xQ($,n,b.config),m=await $.glob({cwd:n,patterns:A,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=Nb(b.config),W=[];for(let w of m){let j=C$($.dirname(w)),B=s0(j);if(!B)continue;let S=await Pw($,$.join(n,w)),Q=$.basename(j),Z=$.join(n,j),X=y.requiredByKind?.[EQ(B)];if(!X)continue;let Y=$m(B,Q);W.push({workspaceRoot:n,relativePackageRoot:j,packageRoot:Z,packageName:typeof S.name==="string"?S.name:j,packageDirName:Q,description:typeof S.description==="string"?S.description:void 0,kind:B,target:X,canonicalDeclarationRelativePath:Y,canonicalDeclarationPath:$.join(Z,Y),indexPath:$.join(Z,"src/index.ts"),indexExportPath:bm(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function vb($,b={}){let n=await gw($,b),A=[];for(let m of n){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=LQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[RQ(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 xQ($,b,n){let A=$.join(b,"package.json");if(await $.exists(A)){let m=await Pw($,A),y=IQ(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 CQ}function IQ($){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 EQ($){return $==="appsRegistry"?"appsRegistry":$}function vw($){return $.replace(/\/+$/,"")}async function Pw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function Wm($){let{pkg:b,refs:n,owners:A,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:Fb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:Am(b.packageDirName),owners:A,tags:mm(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return MQ(b,n,y);case"integration":return TQ(b,n,y);case"app-config":return DQ(b,n,y);case"module-bundle":return rn({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:G$("module-bundle",b.packageDirName)});case"example":return In({key:y.key,version:y.version,description:y.description,title:y.title,domain:y.domain,owners:y.owners,tags:y.tags,stability:y.stability,packageName:b.packageName})}}function MQ($,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 ${G$("feature",$.packageDirName)} = defineFeature({
|
|
1943
|
+
meta: ${NQ(n)},
|
|
1944
|
+
${A.length>0?`${A.join(`
|
|
1945
|
+
`)}
|
|
1946
|
+
`:""}});
|
|
1947
|
+
`}function TQ($,b,n){let A=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1948
|
+
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1949
|
+
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1950
|
+
|
|
1951
|
+
const ${G$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1952
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1953
|
+
description: 'Managed configuration for ${$.packageName}.',
|
|
1954
|
+
fields: {},
|
|
1955
|
+
});
|
|
1956
|
+
|
|
1957
|
+
const ${G$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1958
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1959
|
+
description: 'Secret material for ${$.packageName}.',
|
|
1960
|
+
fields: {},
|
|
1961
|
+
});
|
|
1962
|
+
|
|
1963
|
+
export const ${G$("integration",$.packageDirName)} = defineIntegration({
|
|
1964
|
+
meta: {
|
|
1965
|
+
...${rw(n)},
|
|
1966
|
+
category: 'custom',
|
|
1967
|
+
},
|
|
1968
|
+
supportedModes: ['managed'],
|
|
1969
|
+
capabilities: {
|
|
1970
|
+
provides: [
|
|
1971
|
+
${A||" // Add capability refs here"}
|
|
1972
|
+
],
|
|
1973
|
+
},
|
|
1974
|
+
configSchema: { schema: ${G$("integration",$.packageDirName)}Config, example: {} },
|
|
1975
|
+
secretSchema: { schema: ${G$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1976
|
+
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1977
|
+
});
|
|
1978
|
+
`}function DQ($,b,n){let A=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
1979
|
+
`),m=kw(b.workflows),y=kw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1980
|
+
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1981
|
+
|
|
1982
|
+
export const ${G$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1983
|
+
meta: {
|
|
1984
|
+
...${rw(n)},
|
|
1985
|
+
appId: '${Q$($.packageDirName)}',
|
|
1986
|
+
},
|
|
1987
|
+
capabilities: {
|
|
1988
|
+
enabled: [
|
|
1989
|
+
${W||" // Add capability refs here"}
|
|
1990
|
+
],
|
|
1991
|
+
},${A?`
|
|
1992
|
+
features: {
|
|
1993
|
+
include: [
|
|
1994
|
+
${A}
|
|
1995
|
+
],
|
|
1996
|
+
},`:""}${y?`
|
|
1997
|
+
dataViews: {
|
|
1998
|
+
${y}
|
|
1999
|
+
},`:""}${m?`
|
|
2000
|
+
workflows: {
|
|
2001
|
+
${m}
|
|
2002
|
+
},`:""}
|
|
2003
|
+
});
|
|
2004
|
+
`}function jb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2005
|
+
${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
2006
|
+
`)}
|
|
2007
|
+
],`}function kw($){return $.map((b,n)=>` ${n===0?"primary":`item${n+1}`}: {
|
|
2008
|
+
key: '${b.key}',
|
|
2009
|
+
version: '${b.version}',
|
|
2010
|
+
},`).join(`
|
|
2011
|
+
`)}function NQ($){return`{
|
|
2012
|
+
key: '${$.key}',
|
|
2013
|
+
version: '${$.version}',
|
|
2014
|
+
title: '${Q$($.title)}',
|
|
2015
|
+
description: '${Q$($.description)}',
|
|
2016
|
+
domain: '${Q$($.domain)}',
|
|
2017
|
+
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
|
+
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2019
|
+
stability: '${$.stability}',
|
|
2020
|
+
}`}function rw($){return`{ key: '${$.key}', version: '${$.version}', title: '${Q$($.title)}', description: '${Q$($.description)}', domain: '${Q$($.domain)}', owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}], tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}], stability: '${$.stability}' }`}function Q$($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{scanAllSpecsFromSource as FQ}from"@contractspec/module.workspace";var vQ={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 gQ($){return $.packageName!=="@contractspec/lib.schema"}function PQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function kQ($,b={}){let n=await vb($,b),A=[],m=[],y=[];for(let W of n){if(!b.force&&W.exists&&W.matchesExpectedTarget){y.push({...W,action:"skipped",declarationCreated:!1,indexUpdated:!1,packageJsonUpdated:!1,dependenciesUpdated:[]});continue}let w=await rQ($,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()}
|
|
2021
|
+
`);let B=await fQ($,W,b.dryRun,gQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await cQ($,W,b.dryRun);if(W.exists)m.push(W.canonicalDeclarationPath);else A.push(W.canonicalDeclarationPath);if(B)m.push(W.indexPath);if(Q)m.push($.join(W.packageRoot,"package.json"));y.push({...W,action:W.exists?"updated":"created",declarationCreated:!W.exists,indexUpdated:B,packageJsonUpdated:Q,dependenciesUpdated:S})}return{packages:y,createdFiles:A,updatedFiles:m}}function wm($,b){return{allowlisted:ym(b,$.relativePackageRoot,$.packageName),message:$.exists?`Package declaration at ${$.canonicalDeclarationRelativePath} must be a ${$.target} spec.`:`Package ${$.relativePackageRoot} is missing its canonical ${$.target} declaration at ${$.canonicalDeclarationRelativePath}.`}}async function rQ($,b){let n=await $.glob({cwd:b.packageRoot,patterns:["src/**/*.{ts,tsx}"],absolute:!1,ignore:["**/dist/**","**/*.test.*","**/*.spec.*","**/*.stories.*"]}),A={operations:[],events:[],presentations:[],experiments:[],workflows:[],dataViews:[],capabilities:[],features:[]};for(let m of n){if(m===b.canonicalDeclarationRelativePath)continue;let y=await $.readFile($.join(b.packageRoot,m)),W=FQ(y,m);for(let w of W){if(!w.key||!w.version)continue;let j={key:w.key,version:w.version};switch(w.specType){case"operation":x$(A.operations,j);break;case"event":x$(A.events,j);break;case"presentation":x$(A.presentations,j);break;case"experiment":x$(A.experiments,j);break;case"workflow":x$(A.workflows,j);break;case"data-view":x$(A.dataViews,j);break;case"capability":x$(A.capabilities,j);break;case"feature":x$(A.features,j);break}}}return A}function x$($,b){if(!$.some((n)=>n.key===b.key&&n.version===b.version))$.push(b)}async function fQ($,b,n=!1,A=!0){if(!A)return!1;let m=`export * from "${b.indexExportPath}";`,y=new RegExp(`export \\* from ['"]${b.indexExportPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"];`),W=await $.exists(b.indexPath)?await $.readFile(b.indexPath):"";if(y.test(W))return!1;if(W=`${W.trimEnd()}
|
|
2022
|
+
${m}
|
|
2023
|
+
`.trimStart(),!n)await $.writeFile(b.indexPath,W);return!0}async function cQ($,b,n=!1){let A=$.join(b.packageRoot,"package.json"),m=JSON.parse(await $.readFile(A)),y=fw(m,"dependencies"),W=[],w=!1;for(let B of vQ[b.target]){if(!PQ(b,B)){if(B in y)delete y[B],w=!0;continue}if(typeof y[B]!=="string")y[B]="workspace:*",W.push(B)}let j=fw(m,"exports");if(w=w||W.length>0,typeof j["."]!=="string")j["."]="./src/index.ts",w=!0;if(w&&!n)await $.writeFile(A,`${JSON.stringify(m,null,"\t")}
|
|
2024
|
+
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function fw($,b){let n=$[b];if(typeof n==="object"&&n!==null&&!Array.isArray(n))return n;let A={};return $[b]=A,A}var dQ=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,uQ=/@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?)?['"]/,oQ=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,iQ=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,tQ=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,lQ=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,pQ=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function wA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function aQ($,b){let n=$.replaceAll("\\","/"),A=new Set(["contracts","features",...wA(b?.conventions?.operations),...wA(b?.conventions?.events),...wA(b?.conventions?.presentations),...wA(b?.conventions?.forms)]);return n.split("/").some((m)=>A.has(m))}function eQ($,b,n){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||tQ.test(A)||iQ.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(b.has(A))return!1;if(aQ(A,n))return!1;return dQ.test(A)}function hw($){return $.replaceAll("\\","/").match(lQ)?.[1]??null}function sQ($){let b=$.split(`
|
|
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 $4($){if(!$)return WA;let b=hQ.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?$4(b.config):await P(n),W=Nb(y),w=await j$({fs:n},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>hw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await n.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!eQ(Q,j,y))continue;try{let Z=await n.readFile(Q);if(sQ(Z))continue;let X=hw(Q);if(!(X!==null&&pQ.test(X)&&B.has(X))&&!oQ.test(Z))continue;if(uQ.test(Z))continue;m.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:Q})}catch(Z){A.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await vb(n,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=wm(Z,W.allowMissing??[]);m.push({ruleId:"policy-package-declaration",severity:X.allowlisted||W.severity==="warning"?"warning":"error",message:X.message,category:"policy",file:Z.canonicalDeclarationPath,context:{allowlisted:X.allowlisted,expectedTarget:Z.target,packageName:Z.packageName,packageRoot:Z.relativePackageRoot}})}}return m}import{validateSpecStructure as b4}from"@contractspec/module.workspace";async function Bm($){let b=[];for(let n of $){let A=b4(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 sU($,b={}){let n=Date.now(),{fs:A,logger:m}=$,y=[],W=[],w=uw(b);m.info("Starting CI checks...",{checks:w});let j=await P(A),B=await cn($,{config:j,pattern:b.pattern});if(w.includes("structure")){let V=Date.now(),O=await Bm(B);y.push(...O),W.push(e("structure",O,Date.now()-V))}if(w.includes("integrity")){let V=Date.now(),O=await p0($,b);y.push(...O),W.push(e("integrity",O,Date.now()-V))}if(w.includes("deps")){let V=Date.now(),O=await x0($,b);y.push(...O),W.push(e("deps",O,Date.now()-V))}if(w.includes("doctor")){let V=Date.now(),O=await f0($,b);y.push(...O),W.push(e("doctor",O,Date.now()-V))}if(w.includes("docs")){let V=Date.now(),O=await I0($,b);y.push(...O),W.push(e("docs",O,Date.now()-V))}if(w.includes("policy")){let V=Date.now(),O=await jm($,b);y.push(...O),W.push(e("policy",O,Date.now()-V))}if(w.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await o0($,B);y.push(...O),W.push(e("handlers",O,Date.now()-V))}if(w.includes("tests")||b.checkTests){let V=Date.now(),O=await Qm($,B);y.push(...O),W.push(e("tests",O,Date.now()-V))}if(w.includes("test-refs")){let V=Date.now(),O=await Sm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-V))}if(w.includes("coverage")){let V=Date.now(),O=await C0($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-V))}if(w.includes("implementation")){let V=Date.now(),O=await i0($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-V))}if(w.includes("layers")){let V=Date.now(),O=await a0($,b);y.push(...O),W.push(e("layers",O,Date.now()-V))}if(w.includes("drift")){let V=Date.now(),O=await u0($,b);y.push(...O),W.push(e("drift",O,Date.now()-V))}let S=y.filter((V)=>V.severity==="error").length,Q=y.filter((V)=>V.severity==="warning").length,Z=y.filter((V)=>V.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await dw(A),G={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:G.durationMs}),G}var bK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],nK={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 wK($,b={}){let{fs:n,logger:A}=$,m=(b.outputDir??"./src").replace(/\\/g,"/"),y=["generated/**","dist/**",".turbo/**"],W=[`${m}/handlers/**/*.handler.ts`,`${m}/handlers/**/*.handler.test.ts`,`${m}/components/**/*.tsx`,`${m}/components/**/*.test.tsx`,`${m}/forms/**/*.form.tsx`,`${m}/forms/**/*.form.test.tsx`,`${m}/**/*.runner.ts`,`${m}/**/*.renderer.tsx`],w=b.generatedOnly?[...y,...W]:[...y,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...W],j=await n.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await n.stat(Q),X=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&X<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)A.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await n.remove(Q),A.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}$$();var Vj={};f(Vj,{writeReviewPacket:()=>Rm,writeDecisionEnvelope:()=>db,withBranch:()=>o$,verifyConnectMutation:()=>j6,resolveWorkspace:()=>i,resolveStoragePaths:()=>X$,replayConnectDecision:()=>r4,persistLatestArtifacts:()=>zm,persistDecisionArtifacts:()=>hb,normalizeEvalInput:()=>M4,matchConfiguredPath:()=>gb,loadStoredDecision:()=>ub,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>f4,isReviewCommand:()=>Zm,isDeniedCommand:()=>Xm,isAllowedCommand:()=>jA,initConnectWorkspace:()=>v4,inferSurfaces:()=>rb,evaluateConnectDecision:()=>I4,ensureStorage:()=>cb,defaultActor:()=>kb,decisionArtifactRefs:()=>Sb,createConnectControlPlaneRuntime:()=>a4,connectVerdictToPolicy:()=>I$,configuredThreshold:()=>u$,compileConnectPlanPacket:()=>ob,buildConnectContextPack:()=>fb,assessConnectPolicy:()=>Pb,assertConnectEnabled:()=>A$,artifactRef:()=>_$,appendAuditRecord:()=>Lm,analyzeConnectImpact:()=>i$,CONTROL_PLANE_TRACE_GET_REF:()=>BA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>SA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>qm,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Hm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>U$,AGENT_APPROVALS_REF:()=>QA,ACP_TERMINAL_EXEC_REF:()=>y4,ACP_FS_ACCESS_REF:()=>m4});import n4 from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function gb($,b,n){if(!n||n.length===0)return!1;let A=b.replaceAll("\\","/");return n4.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(A4);if(n)return{commandMatch:n,state:"destructive"};return{commandMatch:b.find((A)=>!jA($,A)),state:"unknown"}}function A4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return ow(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return ow(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function ow($,b){return b.every((n)=>$.includes(n)||$.includes(n.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Hm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},BA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},SA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},U$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},m4={key:"acp.fs.access",version:"1.0.0",kind:"command"},y4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},QA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Pb($,b){let n=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.immutablePaths)),A=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=iw($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=W4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(n),protectedPath:Boolean(A),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=w4({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(j4)[0]??"permit"}function w4($){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 tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as C4}from"crypto";var sw={};f(sw,{formatPrComment:()=>lw,formatMinimalComment:()=>Om,formatJson:()=>aw,formatCheckRun:()=>pw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>Y4});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 Om($){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 pw($,b,n={}){let A=n.key??"ContractSpec Impact",m=n.failOnBreaking??!0,y,W;if($.hasBreaking)y=m?"failure":"neutral",W=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)y="success",W=`Non-breaking changes (${$.summary.nonBreaking})`;else y="success",W="No contract impact";let w=Om($);return{name:A,headSha:b,conclusion:y,title:W,summary:w,annotations:$.deltas.filter((j)=>j.severity==="breaking").slice(0,50).map((j)=>({path:j.path,startLine:1,endLine:1,annotationLevel:"failure",message:j.description,title:`Breaking: ${j.rule}`}))}}function aw($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((n)=>({type:n.rule,path:n.specKey,summary:n.description,severity:n.severity==="breaking"?"breaking":n.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as B4,computeIoDiff as S4,generateSnapshot as ew}from"@contractspec/module.workspace";async function K$($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting impact detection...",{baseline:b.baseline});let w=(await n.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${w.length} spec files`);let j=await Q4(n,w,y),B=ew(j),S;if(b.baseline){let X=await Z4(n,A,w,b.baseline,y);S=ew(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=X4(S.specs,B.specs),Z=B4(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 Q4($,b,n){let A=[];for(let m of b){let y=await $.readFile(m);A.push({path:m,content:y})}return A}async function Z4($,b,n,A,m){let y=[];for(let W of n)try{let w=await b.showFile(A,W);y.push({path:W,content:w})}catch{}return y}function X4($,b){let n=[],A=new Map($.map((y)=>[`${y.key}@${y.version}`,y])),m=new Map(b.map((y)=>[`${y.key}@${y.version}`,y]));for(let[y,W]of m){let w=A.get(y);if(w&&W.type==="operation"&&w.type==="operation"){let j=S4(w.io,W.io);n.push(...j)}}return n}var Y4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1932
2027
|
# Contract Impact Detection
|
|
1933
2028
|
|
|
1934
2029
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -1974,49 +2069,49 @@ The system consists of three layers:
|
|
|
1974
2069
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1975
2070
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1976
2071
|
3. **Integrations**: CLI command + GitHub Action
|
|
1977
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
1978
|
-
`;await $.writeFile(b.auditFile,`${
|
|
1979
|
-
`)}async function
|
|
1980
|
-
`);if(
|
|
1981
|
-
`)?
|
|
2072
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as bj,readFileSync as nj}from"fs";import{basename as G4,join as Vm,resolve as H4}from"path";import{ContractsrcSchema as q4,DEFAULT_CONTRACTSRC as O4}from"@contractspec/lib.contracts-spec/workspace-config";function i($={}){let b=H4($.cwd??process.cwd()),n=$.workspaceRoot??I(b),A=$.packageRoot??c(b),m=$.config??V4(n,A),y=J4(A,n);return{cwd:b,workspaceRoot:n,packageRoot:A,config:m,repoId:y,branch:"unknown"}}function o$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function kb($,b){return b??{id:`cli:${$}`,type:"human"}}function rb($){let b=new Set;for(let n of $){if(n.includes("/cli-")||n.includes("/apps/cli-"))b.add("cli");if(n.includes("/contracts-spec/")||n.includes("/specs/"))b.add("contract");if(n.includes("/components/")||n.includes("/ui/")||n.endsWith(".tsx")||n.endsWith(".jsx"))b.add("ui");if(n.includes("/integrations/")||n.includes("/provider"))b.add("integration");if(n.includes("/libs/")||n.includes("/shared/")||n.includes("/utils/"))b.add("library");if(n.includes("/modules/")||n.includes("/bundles/")||n.includes("/examples/"))b.add("solution");if(n.includes("/runtime/"))b.add("runtime");if(n.includes("/harness"))b.add("harness");if(n.includes("/ai-agent/"))b.add("agent");if(n.includes("/knowledge/"))b.add("knowledge");if(n.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function V4($,b){let n={...O4};if($!==b)n=$j(n,Vm($,".contractsrc.json"));return $j(n,Vm(b,".contractsrc.json"))}function $j($,b){if(!bj(b))return $;try{let n=nj(b,"utf-8"),A=JSON.parse(n),m=q4.safeParse(A);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function J4($,b){let n=Vm($,"package.json");if(bj(n))try{let A=JSON.parse(nj(n,"utf-8"));if(A.name)return A.name}catch{}return G4(b)}async function i$($,b){let n=await j$({fs:$.fs},{config:b.workspace.config}),A=new Map(n.filter((j)=>typeof j.key==="string").map((j)=>[j.key,j])),m=b.touchedPaths.map((j)=>U4($.fs,b.workspace,j,n,A)),y=b.baseline!=null?await K$({...$,logger:$.logger??mj},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,W=await K4($,b.workspace,b.touchedPaths),w=_m([...m.flatMap((j)=>j.contracts),...(y?.deltas??[]).map((j)=>({key:j.specKey,version:j.specVersion,kind:j.specType==="event"?"event":"command"}))]);return{breakingChange:y?.hasBreaking===!0,driftFiles:W,impactResult:y,impactedContracts:w,pathImpacts:m,unknownPaths:m.filter((j)=>j.contracts.length===0).map((j)=>j.path)}}function U4($,b,n,A,m){let y=$.resolve(b.workspaceRoot,n),W=Km(n),w=A.map((Y)=>{let G=m$($.relative(b.workspaceRoot,Y.filePath));return{score:L4(n,W,G,Y.key),spec:Y}}).filter((Y)=>Y.score>=45).sort((Y,G)=>G.score-Y.score).slice(0,3),j=A.find((Y)=>Y.filePath===y),B=j?[{score:100,spec:j}]:w,S=B.filter((Y)=>typeof Y.spec.key==="string").map((Y)=>Um(Y.spec.key,Y.spec.version,Y.spec.kind)),Q=B.flatMap((Y)=>[...Y.spec.emittedEvents??[],...Y.spec.policyRefs??[],...Y.spec.testRefs??[]].map((G)=>m.get(G.key)).filter(Boolean).map((G)=>Um(G.key,G.version,G.kind))),Z=_m([...S,...Q]),X=_m([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((Y)=>Y.spec.policyRefs??[]).map((Y)=>Um(Y.key,Y.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:n,policies:X,reasons:B.map((Y)=>`${Y.spec.key??Y.spec.filePath} matched with score ${Y.score}`),surfaces:rb([n])}}async function K4($,b,n){let A=_4($.fs,b,n),m=await Promise.all(A.map(async(y)=>{let W=$.fs.resolve(b.packageRoot,y.comparisonRoot),w=await bA({...$,logger:$.logger??mj},b.workspaceRoot,W,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),j=y.filterPrefix&&y.filterPrefix!==y.comparisonRoot?m$($.fs.relative(y.comparisonRoot,y.filterPrefix)):void 0;return w.files.filter((B)=>j?m$(B)===j||m$(B).startsWith(`${j}/`):!0).map((B)=>m$($.fs.join(y.comparisonRoot,B)))}));return[...new Set(m.flat())].sort()}function _4($,b,n){let A=(b.config.connect?.policy?.generatedPaths??[]).map(R4).filter(Boolean),m=b.config.outputDir&&b.config.outputDir!=="./src"?m$(b.config.outputDir):void 0,y=new Map;for(let W of n){let w=m$(W);if(m&&w.startsWith(m))y.set(m,{comparisonRoot:m});for(let j of A)if(w.startsWith(j)){let B=z4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function z4($,b,n){if(b&&n.startsWith(b))return b;return $.basename(n)==="docs"?m$($.dirname(n)):n}function L4($,b,n,A){if(m$($)===m$(n))return 100;let m=Km(n),y=Km(A??""),W=Aj($)===Aj(n)?40:0,w=Jm($.split("/"),n.split("/"),5),j=Jm(b,m,5),B=Jm(b,y,4);return W+w+j+B}function Jm($,b,n){let A=new Set(b);return $.filter((m)=>A.has(m)).length*n}function Km($){return m$($).split(/[\/._-]+/).filter(Boolean)}function Aj($){return m$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function R4($){return m$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function m$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Um($,b,n){return{key:$,version:String(b??"1.0.0"),kind:n==="query"||n==="event"||n==="policy"||n==="capability"?n:"command"}}function _m($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var mj={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function fb($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let A=kb(b.taskId,b.actor),m=await x4($,n.workspaceRoot,b),y=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),W=n.config.connect?.canonPacks??[];return{id:`connect.ctx_${C4()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:A,knowledge:W.map((w)=>({spaceKey:w.ref,category:"canonical",trustLevel:w.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:y.impactedContracts,affectedSurfaces:y.pathImpacts.length>0?[...new Set(y.pathImpacts.flatMap((w)=>w.surfaces))].sort():rb(m),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...W.map((w)=>({key:w.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...W.map((w)=>({kind:"canon-pack",ref:w.ref}))],acceptanceChecks:n.config.connect?.policy?.smokeChecks??[]}}async function x4($,b,n){let A=n.paths??[];if(A.length>0)return A.map((y)=>yj($.fs,b,y));if(!n.baseline)return[];return(await $.git.diffFiles(n.baseline)).map((y)=>yj($.fs,b,y))}function yj($,b,n){let A=$.resolve(b,n);return $.relative(b,A).replaceAll("\\","/")}import{resolve as t$}from"path";function X$($){let b=$.config.connect?.storage,n=t$($.packageRoot,b?.root??".contractspec/connect");return{root:n,contextPack:t$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:t$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:t$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:t$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:t$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:t$(n,"decisions")}}async function cb($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function zm($,b,n){if(n.contextPack)await Z$($,b.contextPack,n.contextPack);if(n.planPacket)await Z$($,b.planPacket,n.planPacket);if(n.patchVerdict)await Z$($,b.patchVerdict,n.patchVerdict)}async function hb($,b,n,A){let m=$.join(b.decisionsDir,n);if(await $.mkdir(m),A.contextPack)await Z$($,$.join(m,"context-pack.json"),A.contextPack);if(A.planPacket)await Z$($,$.join(m,"plan-packet.json"),A.planPacket);if(A.patchVerdict)await Z$($,$.join(m,"patch-verdict.json"),A.patchVerdict);if(A.reviewPacket)await Z$($,$.join(m,"review-packet.json"),A.reviewPacket);if(A.evaluationResult!==void 0)await Z$($,$.join(m,"evaluation-result.json"),A.evaluationResult);if(A.replayBundle!==void 0)await Z$($,$.join(m,"replay-bundle.json"),A.replayBundle);return m}async function db($,b,n,A){let m=$.join(b.decisionsDir,n,"decision-envelope.json");return await Z$($,m,A),m}async function Lm($,b,n){let A=await Wj($,b.auditFile)??"",m=`${JSON.stringify(n)}
|
|
2073
|
+
`;await $.writeFile(b.auditFile,`${A}${m}`)}async function Rm($,b,n){let A=$.join(b.reviewPacketsDir,`${n.id}.json`);return await Z$($,A,n),A}async function ub($,b,n){let A=$.join(b.decisionsDir,n);return{historyDir:A,contextPack:await Bb($,$.join(A,"context-pack.json")),planPacket:await Bb($,$.join(A,"plan-packet.json")),patchVerdict:await Bb($,$.join(A,"patch-verdict.json")),reviewPacket:await Bb($,$.join(A,"review-packet.json")),envelope:await Bb($,$.join(A,"decision-envelope.json"))}}async function Cm($,b){let n=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),A=[];for(let m of n){let y=await Bb($,m);if(y)A.push({filePath:m,packet:y})}return A.sort((m,y)=>m.packet.id.localeCompare(y.packet.id))}function _$($,b,n){return $.relative(b.packageRoot,$.resolve(n)).replaceAll("\\","/")}function Sb($,b,n,A,m){let y=$.join(n.decisionsDir,A);return{contextPack:_$($,b,$.join(y,"context-pack.json")),planPacket:_$($,b,$.join(y,"plan-packet.json")),patchVerdict:_$($,b,$.join(y,"patch-verdict.json")),reviewPacket:m.reviewPacket?_$($,b,$.join(y,"review-packet.json")):void 0,evaluationResult:m.evaluationResult?_$($,b,$.join(y,"evaluation-result.json")):void 0,replayBundle:m.replayBundle?_$($,b,$.join(y,"replay-bundle.json")):void 0}}async function Z$($,b,n){await $.writeFile(b,`${JSON.stringify(n,null,2)}
|
|
2074
|
+
`)}async function Bb($,b){let n=await Wj($,b);if(!n)return;try{return JSON.parse(n)}catch{return}}async function Wj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function I4($,b,n){let A=i(b);if(A$(A),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let m=X$(A),y=await ub($.fs,m,b.decisionId),W=E4(A,y),w=b.scenarioKey?await n.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:W}):await n.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:W}),j=await hb($.fs,m,b.decisionId,{evaluationResult:w}),B=await $.fs.exists($.fs.join(j,"replay-bundle.json")),S={artifacts:Sb($.fs,A,m,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(y.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:y.envelope?.createdAt??new Date().toISOString(),runtimeLink:y.envelope?.runtimeLink,taskId:y.contextPack?.taskId??b.decisionId,verdict:y.patchVerdict?.verdict??"permit"};return await db($.fs,m,b.decisionId,S),{historyDir:j,evaluation:w,context:W}}function E4($,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 M4($){return $}import{DEFAULT_CONTRACTSRC as F4}from"@contractspec/lib.contracts-spec/workspace-config";async function ZA($,b){let n=$.join(b.root,".gitignore"),A=b.behavior??"auto",m=Bj(b.patterns);if(m.length===0||A==="skip")return{target:"gitignore",filePath:n,action:"skipped",message:A==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(A==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${n}?`,!0))return{target:"gitignore",filePath:n,action:"skipped",message:"User skipped ContractSpec gitignore update"};let y=await $.exists(n),W=y?await $.readFile(n):"",w=T4(W,m);if(jj(W)===jj(w))return{target:"gitignore",filePath:n,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(n,w),{target:"gitignore",filePath:n,action:y?"merged":"created",message:y?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(y){return{target:"gitignore",filePath:n,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}function T4($,b){let n=D4(b),A=N4(),m=$.replace(/\r\n/g,`
|
|
2075
|
+
`);if(A.test(m))return m.replace(A,n);if(m.trim().length===0)return n;return`${m.endsWith(`
|
|
2076
|
+
`)?m:`${m}
|
|
1982
2077
|
`}
|
|
1983
|
-
${
|
|
2078
|
+
${n}`}function D4($){return`# contractspec:init:gitignore:start
|
|
1984
2079
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1985
|
-
${
|
|
2080
|
+
${Bj($).join(`
|
|
1986
2081
|
`)}
|
|
1987
2082
|
# contractspec:init:gitignore:end
|
|
1988
|
-
`}function
|
|
1989
|
-
`).trimEnd()}function Dj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function PQ($,b={}){let A=o(b),m=b.scope==="package"?A.packageRoot:A.workspaceRoot,n=$.join(m,".contractsrc.json"),W={connect:{...kQ.connect,enabled:!0}},w="created";if(await $.exists(n)){let B=p(await $.readFile(n)),S=$$(B??{},W);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(n,N(S)),w="merged"}else await $.writeFile(n,N(W));let j=Q$(o({...b,workspaceRoot:m,packageRoot:m}));await Db($,j);let y=await sA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ub.connect,Ub.verificationCache],prompts:b.prompts,root:A.workspaceRoot});return{configPath:n,targetRoot:m,action:w,gitignore:y}}import{randomUUID as $0}from"crypto";async function gb($,b){let A=o(b);A$(A),A=f$(A,await $.git.currentBranch());let{commands:m,touchedPaths:n}=rQ(b.candidate),W=await Tb($,{...b,paths:n}),w=Mb(b.taskId,b.actor),j=fQ(b.candidate.steps,b.candidate),y=await h$($,{baseline:b.baseline,touchedPaths:n,workspace:A}),B=Eb(A,{commands:m,impactAnalysis:y,touchedPaths:n}),S={id:`connect.plan_${$0()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:w,objective:b.candidate.objective,steps:j,impactedContracts:W.impactedContracts,affectedSurfaces:W.affectedSurfaces,requiredChecks:A.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:hQ(n.length,m.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:um,planCompile:om,planVerify:im,traceId:w.traceId},acpActions:[...n.length>0?["acp.fs.access"]:[],...m.length>0?["acp.terminal.exec"]:[]]};return{contextPack:W,planPacket:S}}function rQ($){let b=new Set($.touchedPaths??[]),A=new Set($.commands??[]);for(let m of $.steps??[]){if(typeof m==="string")continue;for(let n of m.paths??[])b.add(n);for(let n of m.commands??[])A.add(n)}return{commands:[...A],touchedPaths:[...b]}}function fQ($,b){if(!$||$.length===0)return[{id:`step_${$0()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((A)=>typeof A==="string"?{id:`step_${$0()}`,summary:A}:{id:`step_${$0()}`,summary:A.summary,paths:A.paths,commands:A.commands,contractRefs:A.contractRefs})}function hQ($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function cQ($,b,A){let m=o(b);A$(m);let n=Q$(m),W=await vb($.fs,n,b.decisionId),w={decisionId:W.envelope?.runtimeLink?.decisionId,traceId:W.envelope?.runtimeLink?.traceId},j=A&&(w.decisionId||w.traceId)?await A.getExecutionTrace(w):null,y=A&&j?await A.replayExecutionTrace(w):null;return{decisionId:b.decisionId,historyDir:W.historyDir,contextPack:W.contextPack,planPacket:W.planPacket,patchVerdict:W.patchVerdict,reviewPacket:W.reviewPacket,trace:j??void 0,replay:y??void 0,source:j?"local+control-plane":"local"}}async function dQ($,b={}){let A=o(b);return A$(A),mn($.fs,Q$(A))}import{buildChannelPlanTrace as uQ,compileChannelPlan as oQ,finalizeChannelPlan as iQ,replayExecutionTrace as lQ,resolveChannelExecutionActor as tQ}from"@contractspec/integration.runtime/channel";import{createHash as pQ}from"crypto";var kb="connect.local",aQ="connect.runtime-link.v1",eQ="connect.adapter.v1",sQ="connect-control-plane-bridge";function $4($){return{linkDecision:async({connectDecisionId:b,createdAt:A,input:m,patchVerdict:n,planPacket:W,workspace:w})=>{let j=new Date(A),y=JSON.stringify({connectDecisionId:b,objective:W.objective,taskId:W.taskId,tool:m.tool,verdict:n.verdict}),B={workspaceId:w.repoId,providerKey:kb,externalEventId:b,eventType:m.tool==="acp.fs.access"?`connect.fs.${m.operation}`:"connect.terminal.exec",occurredAt:j,signatureValid:!0,traceId:n.controlPlane.traceId,thread:{externalThreadId:`connect:${W.taskId}`,externalUserId:W.actor.id},message:{text:n4(W.objective,m)},metadata:Fj({connectDecisionId:b,connectVerdict:n.verdict,sessionId:W.actor.sessionId,workflowId:`connect:${W.taskId}`}),rawPayload:y},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:W4(y),traceId:B.traceId});if(S.duplicate)return b4($.store,w.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:j}),Z=tQ(B,{actorId:W.actor.id,actorType:W.actor.type,capabilityGrants:m4(n.verdict),capabilitySource:"connect",sessionId:W.actor.sessionId}),G=oQ({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:j}),X=iQ({plan:G,decision:A4(n),approvalTimeoutMs:900000,now:j}),Y=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:X.policy?.verdict??"blocked",riskTier:X.policy?.riskTier??"blocked",confidence:X.policy?.confidence??0.5,modelName:sQ,promptVersion:aQ,policyVersion:eQ,toolTrace:uQ(X),actionPlan:X,requiresApproval:X.approval.required,approvalStatus:X.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:X.approval.required?"pending":"processed",decisionId:Y.id,receiptId:S.receiptId,traceId:X.traceId,workspaceId:w.repoId,providerKey:kb,sessionId:W.actor.sessionId,workflowId:`connect:${W.taskId}`,metadata:Fj({connectDecisionId:b,connectVerdict:n.verdict,tool:m.tool})}),{approvalStatus:Y.approvalStatus,decisionId:Y.id,planId:X.id,providerKey:kb,receiptId:S.receiptId,threadId:Q.id,traceId:X.traceId,workspaceId:w.repoId}},getExecutionTrace:(b)=>Nj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let A=await Nj($.traceService,b);return A?lQ(A):null}}}async function b4($,b,A){let n=(await $.listDecisions({externalEventId:A,limit:1,providerKey:kb,workspaceId:b}))[0];return n?{approvalStatus:n.approvalStatus,decisionId:n.id,planId:n.actionPlan.id,providerKey:kb,receiptId:n.receiptId,threadId:n.threadId,traceId:n.actionPlan.traceId,workspaceId:b}:null}async function Nj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function A4($){let b=z$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((A)=>`${A.status}:${A.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function m4($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function n4($,b){return`${$} [${b.tool}]`}function W4($){return pQ("sha256").update($).digest("hex")}function Fj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as S4}from"crypto";async function vj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=w4(b);if(!A)return{};let m=await Xb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:A,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:A==="ui"?j4(b):void 0,query:nn(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:m.verdict==="permit"?"pass":m.verdict==="rewrite"?"warn":"fail",detail:m.reason},reason:m.reason,remediation:m.selected!=null?[`Prefer ${m.selected.candidate.source} candidate ${m.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:m,verdict:m.verdict}}function w4($){let b=nn($).toLowerCase();if(/\b(contract|operation|event|spec|presentation|form)\b/.test(b))return"contracts";if(/\b(integration|provider|sdk|adapter|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render)\b/.test(b))return"runtime";if(/\b(component|ui|screen|view|page|tsx|jsx)\b/.test(b))return"ui";if(/\b(module|bundle|example|template)\b/.test(b))return"solutions";if(/\b(logger|schema|testing|observability|identity|utility|shared|lib)\b/.test(b))return"sharedLibs";return null}function nn($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function j4($){let b=nn($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function gj($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as y4}from"crypto";function kj($,b,A){let m=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:A?`Generated path: ${A}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||A?"warn":"pass",detail:m}}function Pj($,b){let A=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",m=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:A,detail:m}}function rj($,b,A){return{id:"impact-analysis",status:$?"fail":b||A?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":A?"Impact could not be resolved.":"Impact resolved."}}function fj($,b,A,m,n,W){let w=W.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${W.runtimeLink.decisionId}`:W.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${W.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${y4()}`,sourceDecisionId:b,objective:m.objective,reason:W.reason,summary:{paths:n,impactedContracts:A.impactedContracts,affectedSurfaces:A.affectedSurfaces,requiredChecks:m.requiredChecks},evidence:[{type:"context-pack",ref:W.artifactRefs.contextPack},{type:"plan-packet",ref:W.artifactRefs.planPacket},{type:"patch-verdict",ref:W.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:w}],requiredApprovals:[{capability:O$.key,reason:W.reason}],controlPlane:{traceQuery:pA,policyExplain:aA,approvalStatus:W.runtimeLink?.approvalStatus,decisionId:W.runtimeLink?.decisionId,traceId:W.runtimeLink?.traceId??A.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Wn($,b,A,m,n,W,w,j,y){let B=z$(w);return{decisionId:$,summary:m.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:n,checks:W,verdict:w,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:y?.approvalStatus,decisionId:y?.decisionId,traceId:y?.traceId??A.actor.traceId},approvalOperationRefs:w==="require_review"?[`${O$.key}@${O$.version}`,`${eA.key}@${eA.version}`]:void 0,remediation:B4(w),reviewPacketRef:j,replay:{traceQuery:pA,policyExplain:aA}}}function B4($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function Q4($,b,A={}){let m=o(b);A$(m),m=f$(m,await $.git.currentBranch());let n=`connect.dec_${S4()}`,W=(A.now??(()=>new Date))().toISOString(),w=Q$(m);await Db($.fs,w);let{contextPack:j,planPacket:y}=await gb($,{...b,candidate:X4(b)}),B=Y4(b),S=await h$($,{baseline:b.baseline,touchedPaths:B,workspace:m}),Q=await H4(A,m.config.connect?.policy?.smokeChecks??[],m.workspaceRoot),Z=Q.some((h)=>h.id.startsWith("smoke:")&&h.status==="fail"),G=Eb(m,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),X=await vj($,b),Y=[kj(G.immutablePath,G.protectedPath,G.generatedPath),Pj(G.commandState,G.commandMatch),rj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...X.check?[X.check]:[],...Q],V=Z4(G,X.verdict),O=z$(V),K=X.reason??G.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?G.requiredApprovals.length>0?G.requiredApprovals:[{capability:O$.key,reason:K}]:[],_={...y,requiredApprovals:J,verificationStatus:O.verificationStatus},H=nb($.fs,m,w,n,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((h)=>({file:h.path,contracts:h.contracts,policies:h.policies,surfaces:h.surfaces})):B.map((h)=>({file:h,contracts:j.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:j.affectedSurfaces})),U=Wn(n,b,j,_,q,Y,V,void 0),z=A.controlPlane?await A.controlPlane.linkDecision({connectDecisionId:n,createdAt:W,input:b,patchVerdict:U,planPacket:_,workspace:m}):null,L=z?{...y,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...y.controlPlane,decisionId:z.decisionId,traceId:z.traceId??y.controlPlane.traceId}}:_,I=V==="require_review"?fj(m,n,j,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,C=Wn(n,b,j,L,q,Y,V,I?J$($.fs,m,$.fs.join(w.reviewPacketsDir,`${I.id}.json`)):void 0,z);if(X.remediation?.length)C.remediation=X.remediation;if(await $n($.fs,w,{contextPack:j,planPacket:L,patchVerdict:C}),I)await An($.fs,w,I);let F=await Nb($.fs,w,n,{contextPack:j,planPacket:L,patchVerdict:C,reviewPacket:I}),x={artifacts:nb($.fs,m,w,n,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:n,createdAt:W,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await Fb($.fs,w,n,x),await bn($.fs,w,gj({contextPack:j,createdAt:W,envelope:x,reviewPacket:I,verifyInput:b,workspace:m})),{contextPack:j,planPacket:L,patchVerdict:C,reviewPacket:I,historyDir:F}}function Z4($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return G4($.verdict,b)}function G4($,b){if(!b)return $;return hj($)<=hj(b)?$:b}function hj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function X4($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function Y4($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function H4($,b,A){if(!$.runCommand)return[];let m=[];for(let n of b){let W=await $.runCommand(n,{cwd:A});m.push({id:`smoke:${n}`,status:W.exitCode===0?"pass":"fail",detail:W.exitCode===0?`Passed: ${n}`:`Failed (${W.exitCode}): ${n}`})}return m}m0();var yn={};P(yn,{generateWorkflowSpec:()=>Jw,generateWorkflowRunnerTemplate:()=>EA,generateWorkflowDevkitWorkflowTemplate:()=>zA,generateWorkflowDevkitStreamRouteTemplate:()=>CA,generateWorkflowDevkitStartRouteTemplate:()=>LA,generateWorkflowDevkitGenericTemplate:()=>IA,generateWorkflowDevkitFollowUpRouteTemplate:()=>RA,generateVisualizationSpec:()=>oW,generateTranslationSpec:()=>dW,generateThemeSpec:()=>Vw,generateTestTemplate:()=>Sw,generateTestSpec:()=>cW,generateTelemetrySpec:()=>Ow,generateProductIntentSpec:()=>tW,generatePresentationSpec:()=>qw,generatePolicySpec:()=>hW,generateOperationSpec:()=>Hw,generateMigrationSpec:()=>Yw,generateKnowledgeSpaceSpec:()=>Gw,generateJobSpec:()=>uW,generateIntegrationSpec:()=>Zw,generateHarnessSuiteSpec:()=>aW,generateHarnessScenarioSpec:()=>pW,generateHandlerTemplate:()=>yw,generateFormSpec:()=>jw,generateFeatureSpec:()=>ww,generateExperimentSpec:()=>Ww,generateExampleSpec:()=>iW,generateEventSpec:()=>nw,generateDataViewSpec:()=>mw,generateDataViewRendererTemplate:()=>_A,generateComponentTemplate:()=>Bw,generateCapabilitySpec:()=>fW,generateAppBlueprintSpec:()=>Aw,generateAgentSpec:()=>lW});m0();class uj{ai;templates=yn;constructor($){this.ai=new A0($)}}function N_($){return new uj($)}import{scanSpecSource as R4}from"@contractspec/module.workspace";function oj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function r_($,b,A={}){let{fs:m,logger:n}=b,W=await m.exists($);if(!W&&!A.force)return{specPath:$,specInfo:oj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let w=oj($),j;if(W)try{let B=await m.readFile($);w=R4(B,$),j=w.key}catch{}let y=[];if(A.clean&&j)try{let B=await uA(j,{fs:m});for(let S of B)try{await m.remove(S.filePath),y.push(S.filePath),n.info(`Removed artifact: ${S.filePath}`)}catch{n.warn(`Could not remove artifact: ${S.filePath}`)}}catch{n.warn("Could not discover implementations for cleanup")}if(W)await m.remove($),n.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:w,deleted:!0,cleanedFiles:y,errors:[]}}import{computeSemanticDiff as C4}from"@contractspec/module.workspace";async function c_($,b,A,m={}){let{fs:n,git:W}=A;if(!await n.exists($))throw Error(`Spec file not found: ${$}`);let j=await n.readFile($),y,B;if(m.baseline)y=await W.showFile(m.baseline,$),B=`${m.baseline}:${$}`;else{if(!await n.exists(b))throw Error(`Spec file not found: ${b}`);y=await n.readFile(b),B=b}let S=C4(j,$,y,B,{breakingOnly:m.breakingOnly});return{spec1:$,spec2:B,differences:S}}s();import{openApiForRegistry as I4}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Bn}from"@contractspec/lib.contracts-spec/operations";async function E4($,b){let{fs:A,logger:m}=b,{registryPath:n,outputPath:W="./openapi.json"}=$;m.info("Loading registry...",{registryPath:n});let w=await M4(n,A);m.info("Generating OpenAPI document...");let j=I4(w,{title:$.title,version:$.version,description:$.description,servers:$.servers}),y=JSON.stringify(j,null,2)+`
|
|
1990
|
-
`,B=
|
|
2083
|
+
`}function N4(){return new RegExp(`${wj("# contractspec:init:gitignore:start")}[\\s\\S]*?${wj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function wj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jj($){return $.replace(/\r\n/g,`
|
|
2084
|
+
`).trimEnd()}function Bj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function v4($,b={}){let n=i(b),A=b.scope==="package"?n.packageRoot:n.workspaceRoot,m=$.join(A,".contractsrc.json"),y={connect:{...F4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=b$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,N(S)),W="merged"}else await $.writeFile(m,N(y));let w=X$(i({...b,workspaceRoot:A,packageRoot:A}));await cb($,w);let j=await ZA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ib.connect,Ib.verificationCache],prompts:b.prompts,root:n.workspaceRoot});return{configPath:m,targetRoot:A,action:W,gitignore:j}}import{randomUUID as XA}from"crypto";async function ob($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let{commands:A,touchedPaths:m}=g4(b.candidate),y=await fb($,{...b,paths:m}),W=kb(b.taskId,b.actor),w=P4(b.candidate.steps,b.candidate),j=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),B=Pb(n,{commands:A,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${XA()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:n.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:k4(m.length,A.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:Hm,planVerify:qm,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function g4($){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 P4($,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 k4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function r4($,b,n){let A=i(b);A$(A);let m=X$(A),y=await ub($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=n&&(W.decisionId||W.traceId)?await n.getExecutionTrace(W):null,j=n&&w?await n.replayExecutionTrace(W):null;return{decisionId:b.decisionId,historyDir:y.historyDir,contextPack:y.contextPack,planPacket:y.planPacket,patchVerdict:y.patchVerdict,reviewPacket:y.reviewPacket,trace:w??void 0,replay:j??void 0,source:w?"local+control-plane":"local"}}async function f4($,b={}){let n=i(b);return A$(n),Cm($.fs,X$(n))}import{buildChannelPlanTrace as c4,compileChannelPlan as h4,finalizeChannelPlan as d4,replayExecutionTrace as u4,resolveChannelExecutionActor as o4}from"@contractspec/integration.runtime/channel";import{createHash as i4}from"crypto";var ib="connect.local",t4="connect.runtime-link.v1",l4="connect.adapter.v1",p4="connect-control-plane-bridge";function a4($){return{linkDecision:async({connectDecisionId:b,createdAt:n,input:A,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(n),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:A.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:ib,externalEventId:b,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:b6(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:n6(j),traceId:B.traceId});if(S.duplicate)return e4($.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=o4(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:$6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=h4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=d4({plan:X,decision:s4(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:p4,promptVersion:t4,policyVersion:l4,toolTrace:c4(Y),actionPlan:Y,requiresApproval:Y.approval.required,approvalStatus:Y.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:Y.approval.required?"pending":"processed",decisionId:G.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:ib,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,tool:A.tool})}),{approvalStatus:G.approvalStatus,decisionId:G.id,planId:Y.id,providerKey:ib,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Sj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let n=await Sj($.traceService,b);return n?u4(n):null}}}async function e4($,b,n){let m=(await $.listDecisions({externalEventId:n,limit:1,providerKey:ib,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:ib,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Sj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function s4($){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 $6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function b6($,b){return`${$} [${b.tool}]`}function n6($){return i4("sha256").update($).digest("hex")}function Qj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as w6}from"crypto";async function Zj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let n=A6(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"?m6(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 A6($){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 m6($){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 y6}from"crypto";function Yj($,b,n){let A=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:n?`Generated path: ${n}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||n?"warn":"pass",detail:A}}function Gj($,b){let n=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:n,detail:A}}function Hj($,b,n){return{id:"impact-analysis",status:$?"fail":b||n?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":n?"Impact could not be resolved.":"Impact resolved."}}function qj($,b,n,A,m,y){let W=y.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${y.runtimeLink.decisionId}`:y.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${y.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${y6()}`,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 j6($,b,n={}){let A=i(b);A$(A),A=o$(A,await $.git.currentBranch());let m=`connect.dec_${w6()}`,y=(n.now??(()=>new Date))().toISOString(),W=X$(A);await cb($.fs,W);let{contextPack:w,planPacket:j}=await ob($,{...b,candidate:Q6(b)}),B=Z6(b),S=await i$($,{baseline:b.baseline,touchedPaths:B,workspace:A}),Q=await X6(n,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=Pb(A,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await Zj($,b),G=[Yj(X.immutablePath,X.protectedPath,X.generatedPath),Gj(X.commandState,X.commandMatch),Hj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],V=B6(X,Y.verdict),O=I$(V),K=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:U$.key,reason:K}]:[],U={...j,requiredApprovals:J,verificationStatus:O.verificationStatus},H=Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((r)=>({file:r.path,contracts:r.contracts,policies:r.policies,surfaces:r.surfaces})):B.map((r)=>({file:r,contracts:w.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:w.affectedSurfaces})),_=Im(m,b,w,U,q,G,V,void 0),z=n.controlPlane?await n.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:_,planPacket:U,workspace:A}):null,L=z?{...j,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:z.decisionId,traceId:z.traceId??j.controlPlane.traceId}}:U,C=V==="require_review"?qj(A,m,w,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,D=Im(m,b,w,L,q,G,V,C?_$($.fs,A,$.fs.join(W.reviewPacketsDir,`${C.id}.json`)):void 0,z);if(Y.remediation?.length)D.remediation=Y.remediation;if(await zm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:D}),C)await Rm($.fs,W,C);let F=await hb($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C}),E={artifacts:Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(C)}),connectDecisionId:m,createdAt:y,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await db($.fs,W,m,E),await Lm($.fs,W,Xj({contextPack:w,createdAt:y,envelope:E,reviewPacket:C,verifyInput:b,workspace:A})),{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C,historyDir:F}}function B6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return S6($.verdict,b)}function S6($,b){if(!b)return $;return Oj($)<=Oj(b)?$:b}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Q6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function Z6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function X6($,b,n){if(!$.runCommand)return[];let A=[];for(let m of b){let y=await $.runCommand(m,{cwd:n});A.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return A}HA();var Tm={};f(Tm,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});HA();class Uj{ai;templates=Tm;constructor($){this.ai=new GA($)}}function yz($){return new Uj($)}import{scanSpecSource as _6}from"@contractspec/module.workspace";function Kj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Qz($,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=_6(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 z6}from"@contractspec/module.workspace";async function Yz($,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=z6(w,$,j,B,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:B,differences:S}}$$();import{openApiForRegistry as L6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Dm}from"@contractspec/lib.contracts-spec/operations";async function R6($,b){let{fs:n,logger:A}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;A.info("Loading registry...",{registryPath:m});let W=await C6(m,n);A.info("Generating OpenAPI document...");let w=L6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2085
|
+
`,B=n.resolve(y);return await n.mkdir(n.dirname(B)),await n.writeFile(B,j),A.info(`OpenAPI document written to ${B}`),{document:w,outputPath:B,json:j}}async function C6($,b){let A=await import(b.resolve($));if(A instanceof Dm)return A;if(A.registry instanceof Dm)return A.registry;let m=typeof A.createRegistry==="function"?A.createRegistry:typeof A.default==="function"?A.default:void 0;if(m){let y=await m();if(y instanceof Dm)return y}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as x6,parseOpenApi as I6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Nm,dirname as _j,join as Qb}from"path";function E6($,b,n){if(b.outputDir)return b.outputDir;let{outputDir:A,conventions:m}=n;switch($){case"operation":return Qb(A,m.operations.split("|")[0]??"operations");case"event":return Qb(A,m.events);case"model":return Qb(A,"models");default:return A}}async function zj($,b,n){let{fs:A,logger:m}=n,{source:y,prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;m.info(`Importing from OpenAPI: ${y}`);let X=await I6(y,{fetch:globalThis.fetch,readFile:(J)=>A.readFile(J)});if(X.warnings.length>0)for(let J of X.warnings)m.warn(`Parse warning: ${J}`);m.info(`Parsed ${X.operations.length} operations from ${X.info.title} v${X.info.version}`);let Y=x6(X,$,{prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q});m.info(`Import result: ${Y.summary.imported} imported, ${Y.summary.skipped} skipped, ${Y.summary.errors} errors`);let G=[],V=[],O=[],K=new Map;for(let J of Y.operationSpecs){let U="operation",H=null;if(J.code.includes("defineEvent("))U="event",H=J.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((J.code.includes("defineSchemaModel(")||J.code.includes("new EnumType(")||J.code.includes("ScalarTypeEnum.")||J.code.includes("new ZodSchemaType(")||J.code.includes("z.enum(")||J.code.includes("new JsonSchemaType(")||J.code.includes("new GraphQLSchemaType("))&&!J.code.includes("defineCommand(")&&!J.code.includes("defineQuery("))U="model";else U="operation",H=J.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let q=E6(U,b,$),_=Qb(q,J.fileName);if(!H&&U==="model"){if(J.code.includes("new ZodSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(J.code.includes("new JsonSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(J.code.includes("new GraphQLSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!H)H=J.code.match(/export const (\w+)\s*=/)}if(Z)m.info(`[DRY RUN] Would create: ${_}`);else{let z=_j(_);if(!await A.exists(z))await A.mkdir(z);await A.writeFile(_,J.code),m.info(`Created: ${_}`)}if(G.push({path:_,operationId:J.source.sourceId,specName:J.fileName.replace(".ts","")}),H){let z=_j(_),L=K.get(z)||[];L.push({file:Nm(_),name:H[1],type:U}),K.set(z,L)}}if(!Z&&G.length>0)for(let[J,U]of K.entries()){if(U.length===0)continue;let H=U.map((E)=>E.type),q=H.every((E)=>E==="operation"),_=H.every((E)=>E==="event"),z=H.every((E)=>E==="model"),L=`/**
|
|
1991
2086
|
* Auto-generated registry file.
|
|
1992
2087
|
*/
|
|
1993
|
-
`;
|
|
2088
|
+
`;U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;L+=`import { ${E.name} } from '${r}';
|
|
1994
2089
|
`}),L+=`
|
|
1995
|
-
`;let
|
|
2090
|
+
`;let C=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1996
2091
|
|
|
1997
2092
|
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
1998
|
-
`,
|
|
1999
|
-
`}),
|
|
2093
|
+
`,U.forEach((E)=>{L+=`operationRegistry.register(${E.name});
|
|
2094
|
+
`}),C=!0;else if(_)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
2000
2095
|
|
|
2001
2096
|
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2002
|
-
`,
|
|
2003
|
-
`}),
|
|
2097
|
+
`,U.forEach((E)=>{L+=`eventRegistry.register(${E.name});
|
|
2098
|
+
`}),C=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
2004
2099
|
|
|
2005
2100
|
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2006
|
-
`,
|
|
2007
|
-
`}),
|
|
2101
|
+
`,U.forEach((E)=>{L+=`modelRegistry.register(${E.name});
|
|
2102
|
+
`}),C=!0;if(C){let E=Qb(J,"registry.ts");await A.writeFile(E,L),m.info(`Created/Updated registry: ${E}`)}let D=`/**
|
|
2008
2103
|
* Auto-generated barrel file.
|
|
2009
2104
|
*/
|
|
2010
2105
|
|
|
2011
|
-
`;if(
|
|
2012
|
-
`}),
|
|
2013
|
-
`;let F=
|
|
2014
|
-
{ key: '${b.key}', version: ${
|
|
2106
|
+
`;if(U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;D+=`export * from '${r}';
|
|
2107
|
+
`}),C)D+=`export * from './registry';
|
|
2108
|
+
`;let F=Qb(J,"index.ts");await A.writeFile(F,D),m.info(`Created/Updated index: ${F}`)}for(let J of Y.skipped)V.push({operationId:J.sourceId,reason:J.reason}),m.debug(`Skipped: ${J.sourceId} - ${J.reason}`);for(let J of Y.errors)O.push({operationId:J.sourceId,error:J.error}),m.error(`Error: ${J.sourceId} - ${J.error}`);return{imported:Y.summary.imported,skipped:Y.summary.skipped,errors:Y.summary.errors,files:G,skippedOperations:V,errorMessages:O}}import{importFromOpenApi as M6,parseOpenApi as T6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as D6,join as N6}from"path";async function Cz($,b,n){let{fs:A,logger:m}=n,{sources:y,sourceName:W,interactive:w,force:j,dryRun:B}=$,{outputDir:S}=b,Q=y??b.openapi?.sources??[];if(W){if(Q=Q.filter((X)=>X.name===W),Q.length===0)throw Error(`Source not found: ${W}`)}if(Q.length===0)return m.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let Z={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let X of Q){m.info(`Syncing with source: ${X.name}`);let Y=X.url??X.file;if(!Y){m.warn(`Source ${X.name} has no url or file configured`);continue}let G=await T6(Y,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});m.info(`Parsed ${G.operations.length} operations from ${X.name}`);let V=M6(G,b,{prefix:X.prefix,tags:X.tags,exclude:X.exclude,defaultStability:X.defaultStability,defaultAuth:X.defaultAuth});for(let O of V.operationSpecs){let K=N6(S,O.fileName);if(!await A.exists(K)){if(!B){let U=D6(K);await A.mkdir(U),await A.writeFile(K,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:K}),m.info(`Added: ${O.source.sourceId}`)}else if(await A.readFile(K)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K});else if(j==="openapi"){if(!B)await A.writeFile(K,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:K}),m.info(`Updated: ${O.source.sourceId}`)}else if(j==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K}),m.info(`Kept: ${O.source.sourceId}`);else if(w)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId}`)}}return m.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as F6}from"@contractspec/lib.contracts-transformers/openapi";async function Ez($,b){let{fs:n,logger:A}=b,{specPath:m,openApiSource:y,ignoreDescriptions:W,ignoreTags:w,ignoreTransport:j}=$;A.info(`Validating specs against OpenAPI: ${y}`);let B=await F6(y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});A.info(`Parsed ${B.operations.length} operations from ${B.info.title}`);let S=new Map;for(let O of B.operations)S.set(O.operationId,O);let Q=[],Z=0,X=0,Y=await n.stat(m),G=[];if(Y.isDirectory){let O=await n.glob({pattern:"**/*.ts",cwd:m,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});G.push(...O)}else G.push(m);A.info(`Found ${G.length} spec files to validate`);for(let O of G)try{let K=await n.readFile(O),J=K.match(/operationId:\s*['"]([^'"]+)['"]/)||K.match(/name:\s*['"]([^'"]+)['"]/)||K.match(/export\s+const\s+(\w+)Spec\s*=/);if(!J||!J[1]){A.debug(`Could not extract operationId from ${O}`);continue}let U=J[1];Z++;let H;if(H=S.get(U),!H){let z=U.replace(/([A-Z])/g,"_$1").toLowerCase();H=S.get(z)}if(!H){for(let[z,L]of S)if(z.toLowerCase().includes(U.toLowerCase())||U.toLowerCase().includes(z.toLowerCase())){H=L;break}}if(!H){Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${U}`}]}),X++;continue}let q=[];if(H.deprecated&&!K.includes("deprecated"))q.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!j){let z=K.match(/path:\s*['"]([^'"]+)['"]/);if(z&&z[1]!==H.path)q.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${z[1]}", OpenAPI has "${H.path}"`})}if(!j){let z=K.match(/method:\s*['"]([^'"]+)['"]/);if(z?.[1]&&z[1].toLowerCase()!==H.method.toLowerCase())q.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${z[1]}", OpenAPI has "${H.method.toUpperCase()}"`})}let _=q.length===0;if(!_)X++;Q.push({specPath:O,operationId:H.operationId,valid:_,diffs:q})}catch(K){A.error(`Error validating ${O}: ${K}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${K instanceof Error?K.message:String(K)}`}]}),X++}let V=X===0;return A.info(`Validation ${V?"passed":"failed"}: ${Z} specs checked, ${X} with differences`),{valid:V,specsValidated:Z,specsWithDiffs:X,results:Q}}async function rz($,b,n){let{fs:A,logger:m}=$,{source:y,outputDir:W}=b,w=A.resolve(n??process.cwd(),y);if(!await A.exists(w))throw Error(`Source file not found: ${w}`);let B={...await P(A,n),outputDir:W};return m.info(`Extracting contracts from ${w} to ${W}`),zj(B,{source:w,outputDir:W,dryRun:!1},$)}var Rj={};f(Rj,{validateFeatureRefs:()=>P6,getArrayNameForSpecType:()=>Lj,detectFeatureContext:()=>v6,computeAddSpecEdit:()=>g6});function v6($,b){let n=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],A=null;for(let{type:Q,regex:Z,specType:X}of n){let Y;Z.lastIndex=0;while((Y=Z.exec($))!==null)if(!A||Y.index>A.index)A={type:Q,specType:X,index:Y.index}}if(!A)return null;let m=$.slice(A.index)+b,y=A.type;new RegExp(`${y}\\s*:\\s*\\[`).exec(m);let w=$.slice(A.index),j=0,B=!1,S="";for(let Q=0;Q<w.length;Q++){let Z=w[Q],X=Q>0?w[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&X!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")j++;else if(Z==="]"){if(j--,j===0)return null}}if(j>0)return{type:A.type,specType:A.specType};return null}function g6($,b){let n=Lj(b.type),m=new RegExp(`${n}\\s*:\\s*\\[`,"g").exec($);if(m){let y=m.index+m[0].length,W=typeof b.version==="string"?`'${b.version}'`:b.version,w=`
|
|
2109
|
+
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function Lj($){switch($){case"operation":case"command":case"query":return"operations";case"event":return"events";case"presentation":return"presentations";case"experiment":return"experiments";case"workflow":return"workflows";default:return"operations"}}function P6($,b){let n=[],A=(m,y,W)=>{for(let w of m){let j=`${w.key}.v${w.version}`;if(!y.has(j))n.push({key:w.key,version:w.version,type:W,message:`${W} ${w.key}.v${w.version} not found`})}};return A($.operations,b.operations,"Operation"),A($.events,b.events,"Event"),A($.presentations,b.presentations,"Presentation"),A($.experiments,b.experiments,"Experiment"),n}var Ej={};f(Ej,{removeReferenceStrategy:()=>JA,implementSkeletonStrategy:()=>VA,implementAiStrategy:()=>OA,generateFixLinks:()=>k6,FixService:()=>Ij,FIX_STRATEGY_STABILITY:()=>sb,FIX_STRATEGY_LABELS:()=>u6,CiOutputSchema:()=>n7});function k6($,b){let n=[];if(!$.ref||!$.file)return n;if(b.includeCli)n.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let A=$.file.startsWith("/")?$.file:`/${$.file}`,m=$.ref,y=m.line||1,W=m.column||1;n.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${A}:${y}:${W}`})}if(b.includeGithubIssue&&b.repository){let A=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),m=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
2015
2110
|
|
|
2016
2111
|
> ${$.message}
|
|
2017
2112
|
|
|
2018
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
2019
|
-
`)}function
|
|
2113
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${A}&body=${m}`})}return n}import o6 from"path";function E$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function M$($,b){let n=$.enrichment?.owners?.length?$.enrichment.owners.map((W)=>`'${W}'`).join(", "):"'@team'",A=$.enrichment?.tags?.length?$.enrichment.tags.map((W)=>`'${W}'`).join(", "):"",m=$.description||`TODO: Add description for ${$.key}`,y=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([W,w])=>{if(w!==void 0)y.push(`${W}: ${w}`)});return y.push(`owners: [${n}]`),y.push(`tags: [${A}]`),y.push(`description: '${m}'`),y.join(`,
|
|
2114
|
+
`)}function lb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=M$($,{kind:"'api'"});return`/**
|
|
2020
2115
|
* Capability: ${$.key}
|
|
2021
2116
|
*
|
|
2022
2117
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2027,9 +2122,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);A.push({type:"github-issue",labe
|
|
|
2027
2122
|
|
|
2028
2123
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
2029
2124
|
|
|
2030
|
-
export const ${
|
|
2125
|
+
export const ${n} = defineCapability({
|
|
2031
2126
|
meta: {
|
|
2032
|
-
${
|
|
2127
|
+
${A}
|
|
2033
2128
|
},
|
|
2034
2129
|
|
|
2035
2130
|
provides: [
|
|
@@ -2053,7 +2148,7 @@ export const ${A} = defineCapability({
|
|
|
2053
2148
|
// }
|
|
2054
2149
|
],
|
|
2055
2150
|
});
|
|
2056
|
-
`}function
|
|
2151
|
+
`}function pb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"EventSpec",A=n.replace("Spec","Payload"),m=M$($);return`/**
|
|
2057
2152
|
* Event: ${$.key}
|
|
2058
2153
|
*
|
|
2059
2154
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2066,8 +2161,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
2066
2161
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2067
2162
|
|
|
2068
2163
|
// TODO: Define event payload schema
|
|
2069
|
-
export const ${
|
|
2070
|
-
name: '${
|
|
2164
|
+
export const ${A} = new SchemaModel({
|
|
2165
|
+
name: '${A}',
|
|
2071
2166
|
description: 'Payload for ${$.key} event',
|
|
2072
2167
|
fields: {
|
|
2073
2168
|
// Add your payload fields here
|
|
@@ -2077,12 +2172,12 @@ export const ${m} = new SchemaModel({
|
|
|
2077
2172
|
},
|
|
2078
2173
|
});
|
|
2079
2174
|
|
|
2080
|
-
export const ${
|
|
2175
|
+
export const ${n} = defineEvent({
|
|
2081
2176
|
meta: {
|
|
2082
|
-
${
|
|
2177
|
+
${m}
|
|
2083
2178
|
},
|
|
2084
2179
|
|
|
2085
|
-
payload: ${
|
|
2180
|
+
payload: ${A},
|
|
2086
2181
|
|
|
2087
2182
|
// TODO: Specify PII fields if any
|
|
2088
2183
|
// piiFields: ['user.email'],
|
|
@@ -2093,7 +2188,7 @@ export const ${A} = defineEvent({
|
|
|
2093
2188
|
// policy: 'archive',
|
|
2094
2189
|
// },
|
|
2095
2190
|
});
|
|
2096
|
-
`}function
|
|
2191
|
+
`}function r6($){let b=$.toLowerCase(),n=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let A of n)if(b.includes(A))return"query";return"command"}function ab($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=n.replace("Spec","Input"),m=n.replace("Spec","Output"),y=r6($.key),W=y==="query"?"defineQuery":"defineCommand",w=$.enrichment?.goal||"TODO: Define the business goal",j=$.enrichment?.context||"TODO: Provide context",B=M$($,{goal:`'${w}'`,context:`'${j}'`});return`/**
|
|
2097
2192
|
* Operation: ${$.key}
|
|
2098
2193
|
*
|
|
2099
2194
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2102,12 +2197,12 @@ export const ${A} = defineEvent({
|
|
|
2102
2197
|
* Referenced by feature: ${$.featureKey||"unknown"}
|
|
2103
2198
|
*/
|
|
2104
2199
|
|
|
2105
|
-
import { ${
|
|
2200
|
+
import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
2106
2201
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2107
2202
|
|
|
2108
2203
|
// TODO: Define input schema
|
|
2109
|
-
export const ${
|
|
2110
|
-
name: '${
|
|
2204
|
+
export const ${A} = new SchemaModel({
|
|
2205
|
+
name: '${A}',
|
|
2111
2206
|
description: 'Input for ${$.key}',
|
|
2112
2207
|
fields: {
|
|
2113
2208
|
// Add your input fields here
|
|
@@ -2116,8 +2211,8 @@ export const ${m} = new SchemaModel({
|
|
|
2116
2211
|
});
|
|
2117
2212
|
|
|
2118
2213
|
// TODO: Define output schema
|
|
2119
|
-
export const ${
|
|
2120
|
-
name: '${
|
|
2214
|
+
export const ${m} = new SchemaModel({
|
|
2215
|
+
name: '${m}',
|
|
2121
2216
|
description: 'Output for ${$.key}',
|
|
2122
2217
|
fields: {
|
|
2123
2218
|
// Add your output fields here
|
|
@@ -2125,14 +2220,14 @@ export const ${n} = new SchemaModel({
|
|
|
2125
2220
|
},
|
|
2126
2221
|
});
|
|
2127
2222
|
|
|
2128
|
-
export const ${
|
|
2223
|
+
export const ${n} = ${W}({
|
|
2129
2224
|
meta: {
|
|
2130
2225
|
${B}
|
|
2131
2226
|
},
|
|
2132
2227
|
|
|
2133
2228
|
io: {
|
|
2134
|
-
input: ${
|
|
2135
|
-
output: ${
|
|
2229
|
+
input: ${A},
|
|
2230
|
+
output: ${m},
|
|
2136
2231
|
errors: {
|
|
2137
2232
|
// TODO: Define possible errors
|
|
2138
2233
|
// EXAMPLE_ERROR: {
|
|
@@ -2154,7 +2249,7 @@ export const ${A} = ${w}({
|
|
|
2154
2249
|
},
|
|
2155
2250
|
|
|
2156
2251
|
transport: {
|
|
2157
|
-
rest: { method: '${
|
|
2252
|
+
rest: { method: '${y==="command"?"POST":"GET"}' },
|
|
2158
2253
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
2159
2254
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
2160
2255
|
},
|
|
@@ -2171,7 +2266,7 @@ export const ${A} = ${w}({
|
|
|
2171
2266
|
examples: [],
|
|
2172
2267
|
},
|
|
2173
2268
|
});
|
|
2174
|
-
`}function
|
|
2269
|
+
`}function f6($){let b=$.toLowerCase();if(b.includes("doc")||b.includes("guide")||b.includes("readme"))return"markdown";if(b.includes("data")||b.includes("api")||b.includes("export"))return"data";return"web_component"}function eb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"PresentationSpec",A=f6($.key),m=M$($);return`/**
|
|
2175
2270
|
* Presentation: ${$.key}
|
|
2176
2271
|
*
|
|
2177
2272
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2182,12 +2277,12 @@ export const ${A} = ${w}({
|
|
|
2182
2277
|
|
|
2183
2278
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
2184
2279
|
|
|
2185
|
-
export const ${
|
|
2280
|
+
export const ${n} = definePresentation({
|
|
2186
2281
|
meta: {
|
|
2187
|
-
${
|
|
2282
|
+
${m}
|
|
2188
2283
|
},
|
|
2189
2284
|
|
|
2190
|
-
kind: '${
|
|
2285
|
+
kind: '${A}',
|
|
2191
2286
|
|
|
2192
2287
|
// TODO: Define content structure
|
|
2193
2288
|
content: {
|
|
@@ -2211,7 +2306,7 @@ export const ${A} = definePresentation({
|
|
|
2211
2306
|
// focusable: true,
|
|
2212
2307
|
// },
|
|
2213
2308
|
});
|
|
2214
|
-
`}import G$ from"path";function n0($,b){if(b.outputDir)return Qn(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=u4($.featureFile);if(A)return Qn(A,$.ref.key,$.specType)}return Qn(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function u4($){let b=G$.dirname($),A=G$.parse($).root,m=0;while(b!==A&&m<50){if(G$.basename(b)==="src")return b;b=G$.dirname(b),m++}b=G$.dirname($),m=0;while(b!==A&&m<50)b=G$.dirname(b),m++;let n=$.lastIndexOf(`${G$.sep}src${G$.sep}`);if(n!==-1)return $.substring(0,n+5);return null}function Qn($,b,A){let m=b.replace(/\./g,"-").toLowerCase(),n=o4(A),W=i4(A);return G$.join($,W,`${m}${n}`)}function o4($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function i4($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var l4={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},db={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function W0($,b,A){let{fs:m,logger:n}=A,{ref:W,specType:w,featureKey:j}=$;try{let y={key:W.key,version:W.version,specType:w,stability:db["implement-ai"],featureKey:j},B=y;if(b.aiConfig)try{B=await p4(y,b,n)}catch(G){n.warn("AI enrichment failed, falling back to skeleton",{error:G instanceof Error?G.message:String(G)})}else n.info("No AI config provided, using skeleton with experimental stability");let S=s4(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${w}`};let Q=n0($,b),Z=[];if(!b.dryRun){let G=t4.dirname(Q);await m.mkdir(G),await m.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(y){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:y instanceof Error?y.message:String(y)}}}async function p4($,b,A){if(A.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:n}=await Promise.resolve().then(() => (m0(),dj)),W=a4(b),w=new n(W),j=$.specType==="operation"?"command":$.specType,y=`${aj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await w.generateOperationSpec(y,j);return{...$,description:B.description,enrichment:{goal:B.goal,context:B.context,owners:B.owners,tags:B.tags}}}if($.specType==="event"){let B=await w.generateEventSpec(y);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(n){A.warn("AIGenerator call failed, falling back to heuristics",{error:n instanceof Error?n.message:String(n)})}let m=e4($.key,$.specType);return{...$,description:m.description,enrichment:{goal:m.goal,context:m.context,owners:["@team"],tags:m.tags}}}function a4($){let b=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[b?.provider??"openai"]??"openai",aiModel:b?.model??"gpt-4-turbo",customApiKey:b?.apiKey??"",customEndpoint:b?.endpoint??""}}function e4($,b){let A=$.split("."),m=A[0]||"unknown",n=A.slice(1).join(" ").replace(/_/g," "),W=[m],w=n.toLowerCase().split(" "),y=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>w.some((S)=>S.includes(B)));return{description:`${aj(b)} for ${m} ${n}`,goal:`Enable ${n} functionality in the ${m} domain`,context:`Part of the ${m} feature set. Generated by ContractSpec AI fix.`,tags:[...W,...y]}}function s4($){switch($.specType){case"operation":return hb($);case"event":return fb($);case"presentation":return cb($);case"capability":return rb($);default:return}}function aj($){return $.charAt(0).toUpperCase()+$.slice(1)}import $6 from"path";async function w0($,b,A){let{fs:m}=A,{ref:n,specType:W,featureKey:w}=$;try{let j={key:n.key,version:n.version,specType:W,stability:db["implement-skeleton"],description:`Skeleton spec for ${n.key}`,featureKey:w},y=b6(j);if(!y)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let B=n0($,b),S=[];if(!b.dryRun){let Q=$6.dirname(B);await m.mkdir(Q),await m.writeFile(B,y),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(j){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}function b6($){switch($.specType){case"operation":return hb($);case"event":return fb($);case"presentation":return cb($);case"capability":return rb($);default:return}}async function j0($,b,A){let{fs:m}=A,{ref:n,featureFile:W,specType:w}=$;try{let j=await m.readFile(W),y=j,B=A6(j,n,w);if(B===j)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${n.key}.v${n.version} in ${W}`};let S=[];if(!b.dryRun)await m.writeFile(W,B),S.push({path:W,action:"modified",previousContent:y});else S.push({path:W,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(j){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}function A6($,b,A){if(!m6(A))return $;let n=ej(b.key),W=ej(b.version),w=[new RegExp(`\\{\\s*key:\\s*['"]${n}['"],\\s*version:\\s*['"]${W}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${W}['"],\\s*key:\\s*['"]${n}['"]\\s*\\},?\\s*`,"g")],j=$;for(let y of w)j=j.replace(y,"");return j=n6(j),j}function m6($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function ej($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n6($){return $.replace(/,(\s*)\]/g,"$1]")}class sj{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,A)=>j0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,A)=>w0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,A)=>W0(b,A,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let A=this.strategies.get(b.strategy);if(!A)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),A.fix($,b)}async batchFix($){let b=[],A=0,m=0;for(let n of $.issues)try{let W=await this.fixIssue(n,$.options);if(b.push(W),W.success)A++;else m++}catch(W){m++,b.push({success:!1,strategy:$.options.strategy,issue:n,filesChanged:[],error:W instanceof Error?W.message:String(W)})}return{total:$.issues.length,succeeded:A,failed:m,results:b}}async scanAndGetFixables($={}){return(await oA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((A)=>this.getToFix(A)).filter((A)=>A!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let A=this.parseFixableIssue($);if(!A)return null;return{...A,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:A,preferAi:m,select:n}=b;if(A)return Promise.resolve(A);if(m&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof n==="function")return n($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as wb}from"zod";var W6=wb.union([wb.array(wb.unknown()),wb.object({issues:wb.array(wb.unknown())}).transform(($)=>$.issues)]);import{exec as w6}from"child_process";import{promisify as j6}from"util";var y6=j6(w6),by={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function Xz($,b,A={}){if($.length===0)return;let m=A.cwd??process.cwd(),n=by[A.type??"biome"]??by.biome,W=50;for(let w=0;w<$.length;w+=W){let y=$.slice(w,w+W).map((B)=>`"${B}"`).join(" ");try{await y6(`${n} ${y}`,{cwd:m})}catch(B){}}}import C$ from"path";async function Oz($,b){let A=C$.join(b,"contracts"),m=C$.join(b,"generated"),n=C$.join(m,"docs"),W=await $.fs.exists(A),w=await $.fs.exists(m);if(!W)return{hasContracts:!1,hasGenerated:w,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let j=await j$($,{pattern:"contracts/**/*.ts"}),y=[];if(w)for(let G of j){let X=G.key||C$.basename(G.filePath,".ts"),Y=C$.join(n,`${X}.md`);if(!await $.fs.exists(Y))y.push(X)}else if(j.length>0)for(let G of j){let X=G.key||C$.basename(G.filePath,".ts");y.push(X)}let B=C$.join(A,"index.ts"),S=C$.join(A,"registry.ts"),Q=j.length>0&&!await $.fs.exists(B),Z=j.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:w,missingDocs:y,missingIndex:Q,missingRegistry:Z,totalSpecs:j.length}}var Wy={};P(Wy,{runHook:()=>Ay,getAvailableHooks:()=>my});import{exec as B6}from"child_process";import{promisify as S6}from"util";var Q6=S6(B6);async function Ay($,b){let{fs:A,logger:m}=$,{hookName:n,dryRun:W=!1}=b,w=M(b.workspaceRoot);m.info(`Running hook: ${n}`,{workspaceRoot:w,dryRun:W});let j=await ny(A,w);if(!j)return{hookName:n,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let y=j[n];if(!y||y.length===0)return{hookName:n,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${n}`};m.info(`Found ${y.length} command(s) for ${n}`);let B=[],S=!0;for(let Z of y){if(W){m.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}m.info(`Executing: ${Z}`);try{let{stdout:G,stderr:X}=await Q6(Z,{cwd:w,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:G,stderr:X}),m.info(`\u2713 ${Z}`)}catch(G){S=!1;let X=G;B.push({command:Z,success:!1,exitCode:X.code??1,stdout:X.stdout??"",stderr:X.stderr??X.message??String(G)}),m.error(`\u2717 ${Z}`,{exitCode:X.code,stderr:X.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:n,success:S,commandResults:B,totalCommands:y.length,successfulCommands:Q,summary:S?`\u2713 All ${y.length} command(s) passed`:`\u2717 ${Q}/${y.length} command(s) passed`}}async function my($,b){let A=await ny($.fs,b);return A?Object.keys(A):[]}async function ny($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return null;try{let m=await $.readFile(A);return JSON.parse(m).hooks??null}catch{return null}}import{detectFramework as Z6,extractFromProject as G6}from"@contractspec/lib.source-extractors";import{generateOperations as X6,generateRegistry as Y6,generateSchemas as H6}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as q6}from"@contractspec/lib.source-extractors/extractors";import{dirname as O6,join as Zn}from"path";async function V6($,b,A,m){let{fs:n,logger:W}=A,w=m??process.cwd();q6(),W.info(`Scanning source code in ${w}...`);let j={readFile:(_)=>n.readFile(_),glob:(_,H)=>n.glob({pattern:_,cwd:H?.cwd}),exists:(_)=>n.exists(_)},y=await Z6(w,{readFile:(_)=>n.readFile(_),glob:(_)=>n.glob({pattern:_})});if(y.frameworks.length===0)return W.warn("No supported frameworks detected"),{success:!1,report:J6(),errors:["No supported frameworks detected in project"]};W.info(`Detected frameworks: ${y.frameworks.map((_)=>_.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let _ of B.getAll())if("setFs"in _&&typeof _.setFs==="function")_.setFs(j);let S={scope:b.scope,framework:b.framework},Q=await G6(y,S);if(!Q.success||!Q.ir)return{success:!1,report:K6(Q.errors??[]),errors:Q.errors?.map((_)=>_.message)};let Z=Q.ir;if(W.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:_6(Z)};let G=b.outputDir??Zn($.outputDir,"generated"),X={outputDir:G,defaultAuth:"user"},Y=X6(Z,X),V=H6(Z,X),O=Y6(Y),K=[...Y,...V,O];if(!b.dryRun)for(let _ of K){let H=Zn(G,_.path),q=O6(H);if(!await n.exists(q))await n.mkdir(q);await n.writeFile(H,_.content),W.info(`Created: ${H}`)}else for(let _ of K)W.info(`[DRY RUN] Would create: ${Zn(G,_.path)}`);let J={files:K,operationsGenerated:Y.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:U6(Z,J,b)}}function J6(){return`# Import Report
|
|
2309
|
+
`}import H$ from"path";function qA($,b){if(b.outputDir)return Fm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let n=c6($.featureFile);if(n)return Fm(n,$.ref.key,$.specType)}return Fm(H$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function c6($){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=h6(n),y=d6(n);return H$.join($,y,`${A}${m}`)}function h6($){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 d6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var u6={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},sb={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function OA($,b,n){let{fs:A,logger:m}=n,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:sb["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await i6(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=p6(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=qA($,b),Z=[];if(!b.dryRun){let X=o6.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 i6($,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=t6(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=l6($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function t6($){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 l6($,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 p6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import a6 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:sb["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=e6(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=qA($,b),S=[];if(!b.dryRun){let Q=a6.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 e6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}async function JA($,b,n){let{fs:A}=n,{ref:m,featureFile:y,specType:W}=$;try{let w=await A.readFile(y),j=w,B=s6(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 s6($,b,n){if(!$7(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=b7(w),w}function $7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b7($){return $.replace(/,(\s*)\]/g,"$1]")}class Ij{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,n)=>JA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,n)=>VA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,n)=>OA(b,n,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let n=this.strategies.get(b.strategy);if(!n)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),n.fix($,b)}async batchFix($){let b=[],n=0,A=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)n++;else A++}catch(y){A++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:n,failed:A,results:b}}async scanAndGetFixables($={}){return(await mA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((n)=>this.getToFix(n)).filter((n)=>n!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let n=this.parseFixableIssue($);if(!n)return null;return{...n,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:n,preferAi:A,select:m}=b;if(n)return Promise.resolve(n);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof m==="function")return m($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as Zb}from"zod";var n7=Zb.union([Zb.array(Zb.unknown()),Zb.object({issues:Zb.array(Zb.unknown())}).transform(($)=>$.issues)]);import{exec as A7}from"child_process";import{promisify as m7}from"util";var y7=m7(A7),Mj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function kL($,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 y7(`${m} ${j}`,{cwd:A})}catch(B){}}}import T$ from"path";async function hL($,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 w7}from"util";var j7=w7(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 j7(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 B7,extractFromProject as S7}from"@contractspec/lib.source-extractors";import{generateOperations as Q7,generateRegistry as Z7,generateSchemas as X7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as Y7}from"@contractspec/lib.source-extractors/extractors";import{dirname as G7,join as vm}from"path";async function H7($,b,n,A){let{fs:m,logger:y}=n,W=A??process.cwd();Y7(),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 B7(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 S7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:O7(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:V7(Z)};let X=b.outputDir??vm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},G=Q7(Z,Y),V=X7(Z,Y),O=Z7(G),K=[...G,...V,O];if(!b.dryRun)for(let U of K){let H=vm(X,U.path),q=G7(H);if(!await m.exists(q))await m.mkdir(q);await m.writeFile(H,U.content),y.info(`Created: ${H}`)}else for(let U of K)y.info(`[DRY RUN] Would create: ${vm(X,U.path)}`);let J={files:K,operationsGenerated:G.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:J7(Z,J,b)}}function q7(){return`# Import Report
|
|
2215
2310
|
|
|
2216
2311
|
## \u274C No Supported Frameworks Detected
|
|
2217
2312
|
|
|
@@ -2228,13 +2323,13 @@ No supported frameworks were detected in the project.
|
|
|
2228
2323
|
- Next.js API Routes
|
|
2229
2324
|
|
|
2230
2325
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
2231
|
-
`}function
|
|
2326
|
+
`}function O7($){return`# Import Report
|
|
2232
2327
|
|
|
2233
2328
|
## \u274C Extraction Failed
|
|
2234
2329
|
|
|
2235
2330
|
${$.map((b)=>`- ${b.message}`).join(`
|
|
2236
2331
|
`)}
|
|
2237
|
-
`}function
|
|
2332
|
+
`}function V7($){return`# Import Analysis Report
|
|
2238
2333
|
|
|
2239
2334
|
## Summary
|
|
2240
2335
|
|
|
@@ -2266,7 +2361,7 @@ ${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).jo
|
|
|
2266
2361
|
|
|
2267
2362
|
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
2268
2363
|
`):"None"}
|
|
2269
|
-
`}function
|
|
2364
|
+
`}function J7($,b,n){return`# Import Report${n.dryRun?" (Dry Run)":""}
|
|
2270
2365
|
|
|
2271
2366
|
## \u2705 Import Successful
|
|
2272
2367
|
|
|
@@ -2292,42 +2387,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
|
2292
2387
|
|
|
2293
2388
|
### Next Steps
|
|
2294
2389
|
|
|
2295
|
-
1. Review generated contracts in \`${
|
|
2390
|
+
1. Review generated contracts in \`${n.outputDir??"generated/"}\`
|
|
2296
2391
|
2. Fill in TODO placeholders with business context
|
|
2297
2392
|
3. Run \`contractspec validate\` to verify contracts
|
|
2298
2393
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
2299
|
-
`}function
|
|
2300
|
-
`)}function
|
|
2301
|
-
`)}async function
|
|
2302
|
-
`)}function
|
|
2303
|
-
`)}function
|
|
2304
|
-
`)}function
|
|
2305
|
-
`);
|
|
2306
|
-
`)}function
|
|
2307
|
-
`)}async function
|
|
2394
|
+
`}function U7($,b,n={}){let A=[];if(A.push("# Import Report"),A.push(""),A.push(`**Generated**: ${new Date().toISOString()}`),A.push(""),A.push("## Summary"),A.push(""),A.push("| Metric | Count |"),A.push("|--------|-------|"),A.push(`| Files Scanned | ${$.stats.filesScanned} |`),A.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),A.push(`| Schemas Found | ${$.stats.schemasFound} |`),A.push(`| Errors Found | ${$.stats.errorsFound} |`),A.push(`| Events Found | ${$.stats.eventsFound} |`),A.push(""),n.includeStats!==!1)A.push("### Confidence"),A.push(""),A.push("| Level | Count |"),A.push("|-------|-------|"),A.push(`| High | ${$.stats.highConfidence} |`),A.push(`| Medium | ${$.stats.mediumConfidence} |`),A.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),A.push("");A.push("### Frameworks Detected"),A.push("");for(let m of $.project.frameworks)A.push(`- **${m.name}** (${m.confidence})`);if(A.push(""),n.includeEndpoints!==!1&&$.endpoints.length>0){A.push("## Endpoints"),A.push(""),A.push("| Method | Path | Kind | Confidence |"),A.push("|--------|------|------|------------|");for(let m of $.endpoints)A.push(`| ${m.method} | \`${m.path}\` | ${m.kind} | ${m.confidence.level} |`);A.push("")}if(n.includeSchemas!==!1&&$.schemas.length>0){A.push("## Schemas"),A.push(""),A.push("| Name | Type | Confidence |"),A.push("|------|------|------------|");for(let m of $.schemas)A.push(`| ${m.name} | ${m.schemaType} | ${m.confidence.level} |`);A.push("")}if(b&&n.includeIssues!==!1){A.push("## Verification"),A.push(""),A.push("| Status | Count |"),A.push("|--------|-------|"),A.push(`| Valid | ${b.summary.validEndpoints} |`),A.push(`| Warnings | ${b.summary.warningEndpoints} |`),A.push(`| Errors | ${b.summary.errorEndpoints} |`),A.push("");let m=b.endpointResults.filter((y)=>y.issues.length>0);if(m.length>0){A.push("### Issues"),A.push("");for(let y of m){A.push(`#### ${y.endpoint.method} ${y.endpoint.path}`);for(let W of y.issues){let w=W.severity==="error"?"\u274C":W.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(A.push(`- ${w} **${W.code}**: ${W.message}`),W.suggestion)A.push(` - *Suggestion*: ${W.suggestion}`)}A.push("")}}}if(n.includeAmbiguities!==!1&&$.ambiguities.length>0){A.push("## Ambiguities (Require Review)"),A.push("");for(let m of $.ambiguities)if(A.push(`- **${m.type}** (${m.itemId}): ${m.description}`),m.suggestion)A.push(` - *Suggestion*: ${m.suggestion}`);A.push("")}return A.push("## Next Steps"),A.push(""),A.push("1. Review generated contracts in the output directory"),A.push("2. Fill in TODO placeholders with business context"),A.push("3. Run `contractspec validate` to verify contracts"),A.push("4. Move stable contracts from `generated/` to `curated/`"),A.push(""),A.join(`
|
|
2395
|
+
`)}function K7($,b){let n=[];n.push(""),n.push("\uD83D\uDCCA Summary"),n.push(` Files scanned: ${$.stats.filesScanned}`),n.push(` Endpoints: ${$.stats.endpointsFound}`),n.push(` Schemas: ${$.stats.schemasFound}`),n.push(""),n.push("\uD83D\uDCC8 Confidence"),n.push(` High: ${$.stats.highConfidence}`),n.push(` Medium: ${$.stats.mediumConfidence}`),n.push(` Low: ${$.stats.lowConfidence}`),n.push(""),n.push("\uD83D\uDD27 Frameworks");for(let A of $.project.frameworks)n.push(` \u2022 ${A.name}`);if(n.push(""),b)n.push("\u2705 Verification"),n.push(` Valid: ${b.summary.validEndpoints}`),n.push(` Warnings: ${b.summary.warningEndpoints}`),n.push(` Errors: ${b.summary.errorEndpoints}`),n.push("");return n.join(`
|
|
2396
|
+
`)}async function _7($,b,n){let{logger:A}=n,m=[],y=[...$.ambiguities];A.info(`Verifying ${$.endpoints.length} endpoints...`);for(let w of $.endpoints){let j=[];if(w.confidence.level==="low"||w.confidence.level==="ambiguous")j.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${w.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!w.input&&(w.method==="POST"||w.method==="PUT"||w.method==="PATCH"))j.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!w.output)j.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(b.checkDuplicates){if($.endpoints.filter((Q)=>Q.id!==w.id&&Q.path===w.path&&Q.method===w.method).length>0)j.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${w.method} ${w.path} found`,severity:"error"})}if(b.checkConflicts){let S=z7(w,$.endpoints);for(let Q of S)j.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=j.some((S)=>S.severity==="error")?"error":j.some((S)=>S.severity==="warning")?"warning":"valid";m.push({endpoint:w,status:B,issues:j})}if(b.validateSchemas){for(let w of $.schemas)if(!w.fields||w.fields.length===0)y.push({type:"schema",itemId:w.id,description:`Schema ${w.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:w.source})}let W={totalEndpoints:m.length,validEndpoints:m.filter((w)=>w.status==="valid").length,warningEndpoints:m.filter((w)=>w.status==="warning").length,errorEndpoints:m.filter((w)=>w.status==="error").length,totalIssues:m.reduce((w,j)=>w+j.issues.length,0)};return A.info(`Verification complete: ${W.validEndpoints} valid, ${W.warningEndpoints} warnings, ${W.errorEndpoints} errors`),{valid:W.errorEndpoints===0,endpointResults:m,ambiguities:y,summary:W}}function z7($,b){let n=[],A=$.path.split("/").filter(Boolean);for(let m of b){if(m.id===$.id)continue;if(m.method!==$.method)continue;let y=m.path.split("/").filter(Boolean);if(y.length!==A.length)continue;let W=!0;for(let w=0;w<A.length;w++){let j=A[w]??"",B=y[w]??"",S=j.startsWith(":")||j.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&j!==B){W=!1;break}}if(W&&$.path!==m.path)n.push(m)}return n}function ZR($,b="feature-map",n={}){switch(b){case"feature-map":return km($,n);case"orphans":return L7($,n);case"dependencies":return R7($,n);case"full":return C7($,n);default:return km($,n)}}function km($,b){let{direction:n="LR",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=$.features;if(b.featureKeys&&b.featureKeys.length>0)W=W.filter((Z)=>b.featureKeys?.includes(Z.key));let w=0,j=!1;if(W.length>0){y.push(" subgraph features [Features]");for(let Z of W){if(w>=m)break;let X=v(`F_${Z.key}`),Y=Z.title??Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let B=gm(W,"operations",$.inventory);if(B.length>0&&w<m){y.push(" subgraph ops [Operations]");for(let Z of B){if(w>=m)break;let X=v(`O_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let S=gm(W,"events",$.inventory);if(S.length>0&&w<m){y.push(" subgraph events [Events]");for(let Z of S){if(w>=m)break;let X=v(`E_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let Q=gm(W,"presentations",$.inventory);if(Q.length>0&&w<m){y.push(" subgraph presentations [Presentations]");for(let Z of Q){if(w>=m)break;let X=v(`P_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}for(let Z of W){let X=v(`F_${Z.key}`);for(let Y of Z.operations){let G=v(`O_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}for(let Y of Z.events){let G=v(`E_${Y.key}_v${Y.version}`);y.push(` ${X} -.-> ${G}`)}for(let Y of Z.presentations){let G=v(`P_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}}if(j)y.push(` note["... and more (truncated at ${m} nodes)"]`);return y.join(`
|
|
2397
|
+
`)}function L7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=new Set,w=new Set,j=new Set;for(let Q of $.features){for(let Z of Q.operations)W.add(`${Z.key}.v${Z.version}`);for(let Z of Q.events)w.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)j.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){y.push(" subgraph features [Features]");for(let Q of $.features){if(B>=m)break;let Z=v(`F_${Q.key}`);y.push(` ${Z}["${B$(Q.title??Q.key)}"]`),B++}y.push(" end")}if($.orphanedSpecs.length>0){y.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=m)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}let S=[];for(let Q of W){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"operation",key:Z,version:X})}for(let Q of w){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"event",key:Z,version:X})}for(let Q of j){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"presentation",key:Z,version:X})}if(S.length>0&&B<m){y.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=m)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let X of Q.operations){let Y=v(`operation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}for(let X of Q.events){let Y=v(`event_${X.key}_v${X.version}`);y.push(` ${Z} -.-> ${Y}`)}for(let X of Q.presentations){let Y=v(`presentation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}}return y.join(`
|
|
2398
|
+
`)}function R7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=0;for(let w of $.features){if(W>=m)break;let j=v(`F_${w.key}`);y.push(` ${j}["${B$(w.title??w.key)}"]`),W++;for(let B of w.operations){if(W>=m)break;let S=v(`O_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.events){if(W>=m)break;let S=v(`E_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} -.-> ${S}`),W++}for(let B of w.presentations){if(W>=m)break;let S=v(`P_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);y.push(` ${S} --> ${Q}`)}}return y.join(`
|
|
2399
|
+
`)}function C7($,b){let n=km($,b);if($.orphanedSpecs.length===0)return n;let A=n.split(`
|
|
2400
|
+
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let m of $.orphanedSpecs.slice(0,20)){let y=v(`orphan_${m.type}_${m.key}_v${m.version}`),W=`${m.key}.v${m.version}`;A.push(` ${y}["${B$(W)}"]:::orphan`)}return A.push(" end"),A.push(" classDef orphan stroke-dasharray: 5 5"),A.join(`
|
|
2401
|
+
`)}function gm($,b,n){let A=new Set,m=[];for(let y of $)for(let W of y[b]){let w=`${W.key}.v${W.version}`;if(!A.has(w))A.add(w),m.push(W)}return m}function Pm($){let b=$.match(/^(.+)\.v(\d+)$/);if(!b)return[void 0,void 0];return[b[1],b[2]]}function v($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function B$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as x7,specToMarkdown as D$}from"@contractspec/module.workspace";function YR($,b,n){let A=[];if(n.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))A.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))A.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(n.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))A.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))A.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(b))A.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return A}function GR($,b){let n=[];n.push(`# Verification Report: ${$.meta.key}`),n.push("");let A=b.filter((W)=>W.severity==="error"),m=b.filter((W)=>W.severity==="warning"),y=b.filter((W)=>W.severity==="info");if(n.push("## Summary"),n.push(""),n.push(`- Errors: ${A.length}`),n.push(`- Warnings: ${m.length}`),n.push(`- Info: ${y.length}`),n.push(""),A.length>0){n.push("## Errors"),n.push("");for(let W of A)n.push(`- \u274C **${W.category}**: ${W.message}`);n.push("")}if(m.length>0){n.push("## Warnings"),n.push("");for(let W of m)n.push(`- \u26A0\uFE0F **${W.category}**: ${W.message}`);n.push("")}if(y.length>0){n.push("## Info"),n.push("");for(let W of y)n.push(`- \u2139\uFE0F **${W.category}**: ${W.message}`);n.push("")}return n.join(`
|
|
2402
|
+
`)}async function VR($,b){let n=[];n.push(D$($,"context"));let A=await j$(b),m=async(y)=>{let W=A.find((j)=>j.key===y.name&&j.version===y.version);if(!W)return null;return(await x7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){n.push(`
|
|
2308
2403
|
## Operations (${$.operations.length})
|
|
2309
|
-
`);for(let
|
|
2404
|
+
`);for(let y of $.operations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2310
2405
|
|
|
2311
|
-
*Spec not found*`);
|
|
2406
|
+
*Spec not found*`);n.push("---")}}if($.events?.length){n.push(`
|
|
2312
2407
|
## Events (${$.events.length})
|
|
2313
|
-
`);for(let
|
|
2408
|
+
`);for(let y of $.events){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2314
2409
|
|
|
2315
|
-
*Spec not found*`);
|
|
2410
|
+
*Spec not found*`);n.push("---")}}if($.presentations?.length){n.push(`
|
|
2316
2411
|
## Presentations (${$.presentations.length})
|
|
2317
|
-
`);for(let
|
|
2318
|
-
|
|
2319
|
-
*Spec not found*`);
|
|
2320
|
-
`)}function
|
|
2321
|
-
`)}function
|
|
2322
|
-
`)}function
|
|
2323
|
-
`)}function
|
|
2324
|
-
`)}function
|
|
2325
|
-
`)}import{RegeneratorService as
|
|
2412
|
+
`);for(let y of $.presentations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2413
|
+
|
|
2414
|
+
*Spec not found*`);n.push("---")}}return n.join(`
|
|
2415
|
+
`)}function I7($,b){let n=[];if(n.push(`# Implementation Guide: ${$.meta.key}`),n.push(""),n.push(`**Target Agent**: ${b}`),n.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),n.push(""),$.meta.description)n.push("## Overview"),n.push(""),n.push($.meta.description),n.push("");if($.meta.goal)n.push("## Goal"),n.push(""),n.push($.meta.goal),n.push("");if($.meta.context)n.push("## Context"),n.push(""),n.push($.meta.context),n.push("");if(n.push("## Implementation Steps"),n.push(""),$.specType==="operation"){if(n.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)n.push("2. Implement input validation according to the schema"),n.push("3. Implement the core business logic"),n.push("4. Return output matching the expected schema");if($.hasPolicy)n.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){n.push("6. Emit events on success:");for(let A of $.emittedEvents)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("7. Add error handling for expected failure cases"),n.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(n.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){n.push("2. Implement operations:");for(let A of $.operations)n.push(` - \`${A.name}\` (v${A.version})`)}if($.presentations&&$.presentations.length>0){n.push("3. Implement presentations:");for(let A of $.presentations)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("4. Wire up feature exports"),n.push("5. Add integration tests")}else n.push("1. Review the spec requirements"),n.push("2. Implement the core logic"),n.push("3. Add tests"),n.push("4. Document the implementation");if(n.push(""),n.push("## Constraints"),n.push(""),n.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)n.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)n.push(`- Tags: ${$.meta.tags.join(", ")}`);if(n.push(""),b==="cursor-cli")n.push("## Cursor Notes"),n.push(""),n.push("- Use Composer mode for multi-file changes"),n.push("- Reference this guide in your cursor rules"),n.push("- Break implementation into small, focused commits");else if(b==="claude-code")n.push("## Claude Code Notes"),n.push(""),n.push("- Use extended thinking for complex logic"),n.push("- Ask for clarification on ambiguous requirements"),n.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")n.push("## General Notes"),n.push(""),n.push("- Use inline comments to guide generation"),n.push("- Review generated code carefully");return n.push(""),n.push("## Spec Definition"),n.push(""),n.push(D$($,"full")),n.join(`
|
|
2416
|
+
`)}function E7($){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(`
|
|
2417
|
+
`)}function JR($,b,n="generic-mcp"){switch(b){case"guide":return I7($,n);case"rules":return E7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as M7}from"fs/promises";import{createRequire as T7}from"module";import{dirname as D7,resolve as gj}from"path";import{pathToFileURL as N7}from"url";import vj from"vm";import rm from"typescript";async function y$($,b={}){let n=gj(process.cwd(),$),A=b.runtime??g7();try{let m=A==="bun"?await F7(n):await v7(n);return{modulePath:n,exports:m}}catch(m){throw Error(kj(n,m))}}async function IR($,b){let n=gj(process.cwd(),$);if(!await b.exists(n))return null;return y$(n)}async function UA($,b={}){return(await y$($,b)).exports}async function Pj($,b){let n=await UA($);return rj(n,$,b)}function kj($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function rj($,b,n){if(n.isValue($))return $;for(let A of n.instanceKeys??[])if(n.isValue($[A]))return $[A];for(let A of n.factoryKeys??[]){let m=$[A];if(typeof m!=="function")continue;let y=await m();if(n.isValue(y))return y}throw Error(`${n.description} module ${b} must export a supported instance or factory.`)}async function F7($){return await import(N7($).href)}async function v7($){return await P7($)??{}}function g7(){return typeof globalThis.Bun<"u"?"bun":"node"}var ER={formatModuleLoadError:kj,resolveAuthoredModuleValue:rj};async function P7($){let b=await M7($,"utf-8"),n=rm.transpileModule(b,{compilerOptions:{module:rm.ModuleKind.CommonJS,target:rm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),A={},m={exports:A},y=T7($),W=vj.createContext({module:m,exports:A,require:y,__dirname:D7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new vj.Script(n.outputText,{filename:$}).runInContext(W),m.exports}var oj={};f(oj,{renderOnboardingGuides:()=>hm,listOnboardingTracks:()=>KA,getOnboardingTrack:()=>cm,createOnboardingConnectArtifacts:()=>l7,buildOnboardingPlan:()=>t7,ONBOARDING_TRACKS:()=>fm});var fm=[{id:"contracts",title:"Contracts",summary:"Author and validate spec-first contracts before implementation.",description:"Use ContractSpec contracts as the durable source of truth for operations, events, presentations, and validation.",reuseFamily:"contracts",adoptionQuery:"contract operation event policy presentation spec-first contracts",primaryDocsRoute:"/docs/getting-started/start-here",secondaryDocsRoutes:["/docs/guides/spec-validation-and-typing","/docs/guides/generate-docs-clients-schemas"],packages:["@contractspec/lib.contracts-spec","@contractspec/lib.schema"],recommendedCommands:["contractspec create --type operation","contractspec generate","contractspec validate","contractspec ci"],starterExample:{key:"minimal",packageRef:"@contractspec/example.minimal",title:"Minimal",summary:"Smallest reference implementation for baseline ContractSpec usage."},connectSurfaces:["cli","contract","runtime"]},{id:"ui-design",title:"UI Design",summary:"Adopt the design system and contract-backed theming flow.",description:"Use ThemeSpec, the design system, and composed UI surfaces instead of ad-hoc theme files or raw primitives.",reuseFamily:"ui",adoptionQuery:"ui design system theme tokens composed controls themes",adoptionPlatform:"web",primaryDocsRoute:"/docs/tech/contracts/themes",secondaryDocsRoutes:["/docs/guides/first-module-bundle","/docs/getting-started/installation"],packages:["@contractspec/lib.design-system","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec create --type theme","contractspec generate","contractspec validate"],starterExample:{key:"data-grid-showcase",packageRef:"@contractspec/example.data-grid-showcase",title:"Data Grid Showcase",summary:"Reference app for composed design-system tables and contract-backed UI rendering."},connectSurfaces:["cli","runtime","ui"]},{id:"knowledge",title:"Knowledge",summary:"Model trusted knowledge spaces, sources, and retrieval flows.",description:"Use knowledge spaces, bindings, and governed retrieval instead of prompt-only context injection.",reuseFamily:"sharedLibs",adoptionQuery:"knowledge spaces sources bindings retrieval canon ingestion assistant",primaryDocsRoute:"/docs/knowledge",secondaryDocsRoutes:["/docs/knowledge/spaces","/docs/knowledge/examples"],packages:["@contractspec/lib.knowledge","@contractspec/lib.ai-agent"],recommendedCommands:["contractspec create --type knowledge","contractspec validate","contractspec connect adoption resolve --family sharedLibs --stdin"],starterExample:{key:"knowledge-canon",packageRef:"@contractspec/example.knowledge-canon",title:"Knowledge Canon",summary:"Minimal contract-first knowledge space example with bindings and source samples."},advancedExample:{key:"policy-safe-knowledge-assistant",packageRef:"@contractspec/example.policy-safe-knowledge-assistant",title:"Policy-Safe Knowledge Assistant",summary:"End-to-end governed knowledge assistant with policy, locale, and learning flows."},connectSurfaces:["cli","knowledge","mcp","runtime"]},{id:"ai-agents",title:"AI Agents",summary:"Define agents, tools, approvals, and MCP-aware execution.",description:"Use the ContractSpec agent runtime and agent specs instead of ad-hoc prompt wrappers.",reuseFamily:"sharedLibs",adoptionQuery:"ai agent tools approvals mcp orchestration unified agent runtime",primaryDocsRoute:"/docs/libraries/ai-agent",secondaryDocsRoutes:["/docs/advanced/mcp","/docs/getting-started/cli"],packages:["@contractspec/lib.ai-agent","@contractspec/lib.contracts-spec"],recommendedCommands:["contractspec create --type agent","contractspec agent export --spec <path> --format opencode","contractspec validate"],starterExample:{key:"agent-console",packageRef:"@contractspec/example.agent-console",title:"Agent Console",summary:"Reference autonomous-agent workspace with runs, tools, metrics, and replay."},connectSurfaces:["agent","cli","mcp","runtime"]},{id:"learning-journey",title:"Learning Journey",summary:"Guide users through milestones, progression, and adaptive journeys.",description:"Use the learning-journey module and example family for structured onboarding and progression flows.",reuseFamily:"solutions",adoptionQuery:"learning journey onboarding progression coaching drills guided wizard",primaryDocsRoute:"/docs/guides/first-module-bundle",secondaryDocsRoutes:["/docs/getting-started/start-here"],packages:["@contractspec/module.learning-journey","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec examples list --query learning-journey","contractspec validate","contractspec doctor"],starterExample:{key:"learning-journey-ui-onboarding",packageRef:"@contractspec/example.learning-journey-ui-onboarding",title:"Learning Journey UI Onboarding",summary:"Checklist- and journey-map-based onboarding mini app."},advancedExample:{key:"learning-journey-registry",packageRef:"@contractspec/example.learning-journey-registry",title:"Learning Journey Registry",summary:"Registry and template aggregation surface for broader learning-journey compositions."},connectSurfaces:["cli","runtime","solution"]}];function KA(){return fm}function cm($){return fm.find((b)=>b.id===$)}function hm($){return{agentGuide:k7($),humanGuide:f7($)}}function k7($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let n of $.recommendations)b.push(...r7(n.track,n.reason));return b.join(`
|
|
2418
|
+
`)}function r7($,b){let n=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return[...n,""]}function f7($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((n,A)=>`${A+1}. \`${n}\``),"","## Track Guide",""];for(let n of $.recommendations)b.push(...c7(n.track,n.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let n of $.builderNextSteps)b.push(`- \`${n}\``);b.push("")}return b.join(`
|
|
2419
|
+
`)}function c7($,b){let n=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)n.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(n.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)n.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);n.push("","Commands:");for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return n.push("",`Packages: ${$.packages.map((A)=>`\`${A}\``).join(", ")}`,""),n}import{buildContext as h7}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as d7}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as u7}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function fj($,b,n,A){let m=h7({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:n,workspaceId:A}),y=await d7(u7(o7(b)),m);return{journeyContext:m,journeyPlan:y}}function cj($){if(!$||$.length===0)return[...KA()];return $.map((b)=>{let n=cm(b);if(!n)throw Error(`Unknown onboarding track: ${b}`);return n})}function hj($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function dj($){switch($){case"managed":return["contractspec builder status"];case"local":case"hybrid":return["contractspec builder status","contractspec builder local status"];case"none":default:return["contractspec init --preset builder-managed","contractspec init --preset builder-local","contractspec init --preset builder-hybrid"]}}function uj($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let n of KA()){if(n.starterExample.key===b)return n.starterExample;if(n.advancedExample?.key===b)return n.advancedExample}return}function dm($,b){return i7($,b.flatMap((n)=>n.track.connectSurfaces))}function o7($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((n)=>({defaultSurface:n.id,path:`/onboard/${n.id}`,routeId:`onboard-${n.id}`})),surfaces:Object.fromEntries($.map((n)=>[n.id,{commands:n.recommendedCommands.map((A,m)=>({commandId:`${n.id}-${m}`,intent:`Run ${A}`,title:A})),data:[{hydrateInto:"track",recipeId:`track-${n.id}`,source:{entityType:`onboarding.${n.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${n.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:n.id,title:n.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function i7($,b){return[...new Set([...$,...b])].sort()}async function t7($,b={}){let n=await s$($.fs,b),A=cj(b.selectedTracks),m=hj(n.config),W=[...await Promise.all(A.map(async(Y)=>{let G=await Jb($,{config:n.config,cwd:n.cwd,family:Y.reuseFamily,packageRoot:n.packageRoot,platform:Y.adoptionPlatform,query:Y.adoptionQuery,workspaceRoot:n.workspaceRoot});return{reason:G.reason,resolution:G,score:G.selected?.score??0,selected:!1,track:Y}}))].sort((Y,G)=>G.score-Y.score).map((Y,G)=>({...Y,selected:G===0})),w=W[0]?.track;if(!w)throw Error("No onboarding tracks are available.");let{journeyContext:j,journeyPlan:B}=await fj(w,A,n.workspaceRoot,n.packageRoot),S=uj(w,b.forcedExampleKey)??w.starterExample,Q=p7(["contractspec onboard",...w.recommendedCommands,"contractspec doctor"]),Z=dj(m),X={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:m,builderNextSteps:Z,config:n.config,cwd:n.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:j,journeyPlan:B,nextCommands:Q,packageRoot:n.packageRoot,primaryTrack:w,recommendations:W,selectedExample:S,workspaceRoot:n.workspaceRoot};return{...X,guides:hm(X)}}async function l7($,b){if(!b.config.connect?.enabled)return;let n=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,A=[b.agentGuidePath,b.humanGuidePath],m=await fb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot}),y=await ob($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((W)=>W.track.id).join(", ")}`,steps:b.recommendations.map((W)=>({commands:W.track.recommendedCommands,paths:A,summary:`Adopt ${W.track.title}`})),touchedPaths:A},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot});return{contextPack:{...m,affectedSurfaces:dm(m.affectedSurfaces,b.recommendations)},planPacket:{...y.planPacket,affectedSurfaces:dm(y.planPacket.affectedSurfaces,b.recommendations)}}}function p7($){return[...new Set($)]}var ij=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],a7=[...ij,{name:"@contractspec/lib.schema",description:"Extended schema utilities and common types"},{name:"@contractspec/app.cli-contractspec",dev:!0,description:"ContractSpec CLI for validation, scaffolding, and code generation"},{name:"typescript",dev:!0,description:"TypeScript compiler for type checking"}];function um($){return $==="minimal"?ij:a7}function om($){return $.filter((b)=>!b.dev)}function im($){return $.filter((b)=>b.dev)}import{exec as e7}from"child_process";import{promisify as s7}from"util";var $Z=s7(e7),bZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function sR($,b,n=bZ){let A=um(b.mode),m=om(A),y=im(A),W=[],w=[],j=[],B=$.join(b.workspaceRoot,"package.json");if(!await $.exists(B))return{success:!1,installed:[],skipped:[],errors:[{name:"package.json",action:"error",message:"No package.json found. Run `npm init` first."}],summary:"No package.json found in workspace root."};let Q=await $.readFile(B),Z=JSON.parse(Q),X=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),Y=a$(b.workspaceRoot),G=m.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),V=y.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let J=[...G,...V];return{success:!0,installed:J.map((U)=>({name:U.name,action:"installed",message:`Would install: ${U.description}`,dev:U.dev})),skipped:w,errors:[],summary:`Dry run: would install ${J.length} package(s), skip ${w.length}.`}}if(!b.skipPrompts&&(G.length>0||V.length>0)){let J=G.length+V.length;if(!await n.confirm(`Install ${J} package(s) using ${Y}?`))return{success:!0,installed:[],skipped:[...w,...G.map((H)=>({name:H.name,action:"skipped",message:"User cancelled"})),...V.map((H)=>({name:H.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(G.length>0){let J=await tj(G,Y,b.workspaceRoot,!1);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}if(V.length>0){let J=await tj(V,Y,b.workspaceRoot,!0);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}let O=j.length===0,K=O?`Successfully installed ${W.length} package(s), skipped ${w.length}.`:`Installed ${W.length}, skipped ${w.length}, failed ${j.length}.`;return{success:O,installed:W,skipped:w,errors:j,summary:K}}async function tj($,b,n,A){let m=[],y=$.map((W)=>W.version?`${W.name}@${W.version}`:W.name);try{let w=`${hy(b,A)} ${y.join(" ")}`;await $Z(w,{cwd:n,timeout:120000});for(let j of $)m.push({name:j.name,action:"installed",message:j.description,dev:A})}catch(W){let w=W instanceof Error?W.message:String(W);for(let j of $)m.push({name:j.name,action:"error",message:`Failed to install: ${w}`,dev:A})}return m}async function $C($,b){let n=$.join(b,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A);return"@contractspec/lib.contracts-spec"in{...m.dependencies,...m.devDependencies}}catch{return!1}}function bC($){let b=um($),n=[];n.push(`ContractSpec ${$} installation:`),n.push("");let A=om(b);if(A.length>0){n.push("Dependencies:");for(let y of A)n.push(` \u2022 ${y.name} - ${y.description}`)}let m=im(b);if(m.length>0){n.push(""),n.push("Dev Dependencies:");for(let y of m)n.push(` \u2022 ${y.name} - ${y.description}`)}return n.join(`
|
|
2420
|
+
`)}import{RegeneratorService as nZ}from"@contractspec/lib.contracts-spec/regenerator";function jC($){return new nZ({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class _A{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,n;try{n=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(A){throw Error(`Registry request failed: ${b} (${A instanceof Error?A.message:String(A)})`)}if(!n.ok){let A=await n.text().catch(()=>"");throw Error(`Registry request failed: ${n.status} ${n.statusText} ${A}`)}return await n.json()}}function tm($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function SC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Adding spec to registry: ${$}`,{registryUrl:m}),await new _A({registryUrl:m}).getJson(`/specs/add?path=${encodeURIComponent($)}`),A.info("Spec added to registry successfully")}async function QC($,b){let{logger:n}=b,A=tm($.registryUrl);n.info("Listing specs from registry",{registryUrl:A});let m=new _A({registryUrl:A}),y=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",W=await m.getJson(`/specs${y}`);return n.info(`Found ${W.length} specs`),W}async function ZC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Searching registry: ${$}`,{registryUrl:m});let W=await new _A({registryUrl:m}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return A.info(`Found ${W.length} results`),W}class AZ{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:n}=$,A=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${A.join(", ")}...`);try{let m=this.fs.join(n,b.rulesDir??".rules");if(!await this.fs.exists(m))return{success:!1,files:[],errors:[`Rules directory not found: ${m}`]};let W=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${W}`);let w=[];for(let j of A){let B=this.getTargetFileName(j);if(B){let S=this.fs.join(n,B);w.push(S)}}return{success:!0,files:w,logs:[`Successfully synchronized rules to ${w.length} targets.`]}}catch(m){let y=m instanceof Error?m.message:String(m);return this.logger.error(`Rule synchronization failed: ${y}`),{success:!1,files:[],errors:[y]}}}async generateConfig($){let{config:b}=$,n={rules:(b.rules??[]).map((A)=>this.fs.join(b.rulesDir??".rules",A)),targets:$.targets||b.targets};return JSON.stringify(n,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}function zA($,b,n,A){let m=$n(b,n),y=mZ(n);if(y.test($))return $.replace(y,m);if(A&&lm($)===lm(A))return m;return`${m}${$}`}function $n($,b){let n=lm($);return`${b.startMarker}
|
|
2326
2421
|
${b.note}
|
|
2327
|
-
${
|
|
2422
|
+
${n}
|
|
2328
2423
|
${b.endMarker}
|
|
2329
|
-
`}function
|
|
2330
|
-
`).trimEnd()}function j7($){return new RegExp(`${Vy($.startMarker)}[\\s\\S]*?${Vy($.endMarker)}(?:\\r?\\n)?`)}function Vy($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var y7="<!-- contractspec:init:agents:start -->",B7="<!-- contractspec:init:agents:end -->",S7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Jy={endMarker:B7,note:S7,startMarker:y7};async function Rn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"AGENTS.md");try{let W=await $.exists(n),w=fw(b);if(W){let j=await $.readFile(n);if(b.interactive){if(!await A.confirm(`${n} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:n,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(n,Q0(j,w,Jy,w)),{target:"agents-md",filePath:n,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(n,ub(w,Jy)),{target:"agents-md",filePath:n,action:"created",message:"Created AI agent guide"}}catch(W){return{target:"agents-md",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}import{generateArtifactsForAudience as Q7,generateBiomePreset as Z7}from"@contractspec/biome-config";async function Cn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"biome.jsonc"),W=$.join(m,".contractspec","biome"),w=$.join(W,"plugins"),j=$.join(W,"ai"),y=Q7("consumer");try{let B=await $.exists(n);if(B&&b.interactive){if(!await A.confirm(`${n} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:n,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(w),await $.mkdir(j),await $.writeFile(n,Z7("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(y.plugins))await $.writeFile($.join(w,S),Q);return await $.writeFile($.join(j,"consumer.md"),y.aiRules),{target:"biome-config",filePath:n,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:n,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function In($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,".contractsrc.json");try{let W=await $.exists(n),w=bb(b);if(W){let j=await $.readFile(n),y=p(j);if(!y)return{target:"cli-config",filePath:n,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${n} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:n,action:"skipped",message:"User skipped merge"}}let B=$$(y,w);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof w==="object"&&w!==null){let S={};if("connect"in w)S.connect=w.connect;if("builder"in w)S.builder=w.builder;await $.writeFile(n,N(Vm(B,S)))}else await $.writeFile(n,N(B));return{target:"cli-config",filePath:n,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(n,N(w)),{target:"cli-config",filePath:n,action:"created",message:"Created CLI configuration"}}catch(W){return{target:"cli-config",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function En($,b,A){let m=$.join(b.workspaceRoot,".cursor","rules"),n=$.join(m,"contractspec.mdc");try{let W=$.join(b.workspaceRoot,".cursor");if(!await $.exists(W))await $.mkdir(W);if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(n),j=rw(b);if(w)if(b.interactive){if(!await A.confirm(`${n} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:n,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:n,action:"skipped",message:"File already exists"};return await $.writeFile(n,j),{target:"cursor-rules",filePath:n,action:w?"merged":"created",message:w?"Updated Cursor rules":"Created Cursor rules"}}catch(W){return{target:"cursor-rules",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function Mn($,b,A){let m=gA();try{let n=await $.exists(m),W=Pw();if(b.interactive){if(!await A.confirm(`Configure Claude Desktop at ${m}?`))return{target:"mcp-claude",filePath:m,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(n){let y=await $.readFile(m),B=p(y);if(!B)return{target:"mcp-claude",filePath:m,action:"error",message:"Existing file is not valid JSON"};let S=$$(B,W);return await $.writeFile(m,N(S)),{target:"mcp-claude",filePath:m,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let w=m.substring(0,m.lastIndexOf("/"));if(!await $.exists(w))await $.mkdir(w);return await $.writeFile(m,N(W)),{target:"mcp-claude",filePath:m,action:"created",message:"Created Claude Desktop configuration"}}catch(n){return{target:"mcp-claude",filePath:m,action:"error",message:n instanceof Error?n.message:"Unknown error"}}}async function xn($,b,A){let m=$.join(b.workspaceRoot,".cursor"),n=$.join(m,"mcp.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(n),j=Lb();if(w){let y=await $.readFile(n),B=p(y);if(!B)return{target:"mcp-cursor",filePath:n,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${n} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:n,action:"skipped",message:"User skipped merge"}}let S=$$(B,j);return await $.writeFile(n,N(S)),{target:"mcp-cursor",filePath:n,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(n,N(j)),{target:"mcp-cursor",filePath:n,action:"created",message:"Created Cursor MCP configuration"}}catch(W){return{target:"mcp-cursor",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var G7="<!-- contractspec:init:usage:start -->",X7="<!-- contractspec:init:usage:end -->",Y7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Ky={endMarker:X7,note:Y7,startMarker:G7};async function Tn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"USAGE.md");try{let W=await $.exists(n),w=hw(b);if(W){let j=await $.readFile(n);if(b.interactive){if(!await A.confirm(`${n} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:n,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(n,Q0(j,w,Ky,w)),{target:"usage-md",filePath:n,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(n,ub(w,Ky)),{target:"usage-md",filePath:n,action:"created",message:"Created usage guide"}}catch(W){return{target:"usage-md",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function Dn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,".vscode"),W=$.join(n,"settings.json");try{if(!await $.exists(n))await $.mkdir(n);let j=await $.exists(W),y=vA(b);if(j){let B=await $.readFile(W),S=p(B);if(!S)return{target:"vscode-settings",filePath:W,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${W} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:W,action:"skipped",message:"User skipped merge"}}let Q=$$(S,y);if("contractspec.api.baseUrl"in y)Q["contractspec.api.baseUrl"]=y["contractspec.api.baseUrl"];return await $.writeFile(W,N(Q)),{target:"vscode-settings",filePath:W,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(W,N(y)),{target:"vscode-settings",filePath:W,action:"created",message:"Created VS Code settings"}}catch(w){return{target:"vscode-settings",filePath:W,action:"error",message:w instanceof Error?w.message:"Unknown error"}}}var H7={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((A)=>A.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((A)=>A.selected!==!1).map((A)=>A.value),input:async($,b)=>b??""};async function IR($,b,A=H7){let m=[],n=b.targets.length>0?b.targets:_b,W=b.workspaceRoot,w=M(W),j=b.packageRoot??r(W),y=b.isMonorepo??Gb(w),B=b.packageName??(y?T$(j):void 0),S=await _y($,[j,w]),Q=b.preset??zb(S);if(b.interactive&&!b.preset)Q=await A.select("Select initialization preset:",Tw.map((C)=>({value:C,label:Dw[C],description:Nw[C],selected:C===Q})));let Z=b.scope??"workspace",G=j!==w;if(y&&b.interactive&&G)Z=await A.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${B??j})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${w})`,description:"Create config files at the workspace root"}]);let X=y&&Z==="package"?j:w,Y=await _y($,[X]),V={...b,workspaceRoot:w,packageRoot:j,isMonorepo:y,scope:Z,packageName:B,preset:Q,builderApiBaseUrl:b.builderApiBaseUrl??Y?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??Y?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??Y?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??Y?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??Y?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??Y?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??Y?.connect?.studio?.queue},O=Fw(Q,n);if(b.interactive)O=await A.multiSelect("Select components to configure:",_b.map((C)=>({value:C,label:xw[C],selected:O.includes(C)})));let K=V.projectName;if(b.interactive&&!K){let C=Z==="package"&&B?B:X.split("/").pop()??"my-project";K=await A.input("Project name:",C)}let J=V.builderApiBaseUrl;if(b.interactive&&Q.startsWith("builder-"))J=await A.input("Builder API base URL:",J??"https://api.contractspec.io");let{builderLocalRuntimeId:_,builderLocalGrantedTo:H}=V;if(b.interactive&&(Q==="builder-local"||Q==="builder-hybrid"))_=await A.input("Default local runtime target id:",_??"rt_local_daemon"),H=await A.input("Default local runtime grant target:",H??"local:operator");let q={...V,projectName:K,targets:O,builderApiBaseUrl:J,builderLocalRuntimeId:_,builderLocalGrantedTo:H};for(let C of O){let F=await q7($,C,q,A);m.push(F)}let U=await sA($,{behavior:q.gitignoreBehavior,interactive:q.interactive,patterns:kw({preset:Q}),prompts:A,root:w});if(q.gitignoreBehavior!=="skip"||U.action!=="skipped")m.push(U);let z=m.filter((C)=>C.action!=="error").length,L=m.filter((C)=>C.action==="error").length,I=y?` (${Z} level)`:"";return{success:L===0,preset:Q,files:m,summary:`Setup complete${I}: ${z} configured, ${L} failed.`,nextSteps:gw(q)}}async function q7($,b,A,m){switch(b){case"agents-md":return Rn($,A,m);case"cli-config":return In($,A,m);case"biome-config":return Cn($,A,m);case"vscode-settings":return Dn($,A,m);case"mcp-cursor":return xn($,A,m);case"mcp-claude":return Mn($,A,m);case"cursor-rules":return En($,A,m);case"usage-md":return Tn($,A,m);default:return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}}async function _y($,b){for(let A of b){let m=$.join(A,".contractsrc.json");if(!await $.exists(m))continue;let n=p(await $.readFile(m));if(n)return n}return null}import{validateBlueprint as O7}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as V7}from"path";async function cR($,b){let{fs:A}=b,m=V7(process.cwd(),$);if(!await A.exists(m))return{valid:!1,errors:[`Blueprint file not found: ${m}`]};try{let n=await n$(m),W=J7(n.exports),w=O7(W);return{spec:W,report:w,valid:w.valid,errors:w.errors.map((j)=>`[${j.code}] ${j.path}: ${j.message}`)}}catch(n){return{valid:!1,errors:[n instanceof Error?n.message:String(n)]}}}function J7($){let b=Object.values($).filter(K7);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function K7($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as _7,dirname as Nn,join as ob}from"path";async function iR($,b,A,m,n){let{fs:W}=n,w=m.implementationPath;if(!w){let S=Nn($),Q=_7($,".ts"),Z=[ob(S,Q.replace(".contracts",".handler")+".ts"),ob(S,Q.replace(".presentation","")+".tsx"),ob(S,Q.replace(".form",".form")+".tsx"),ob(Nn(S),"handlers",Q.replace(".contracts",".handler")+".ts"),ob(Nn(S),"components",Q.replace(".presentation","")+".tsx")];for(let G of Z)if(await W.exists(G)){w=G;break}}if(!w||!await W.exists(w))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let j=await W.readFile(w),B=await new BA(A).validate(b,j);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as U7,validateBuilderReadinessReport as z7,validateBuilderWorkspace as L7,validateBuilderWorkspaceSnapshot as R7}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as C7,validateExternalPatchProposal as I7,validateProviderRoutingPolicy as E7,validateRuntimeTarget as M7}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as x7,validateLayoutSlots as T7}from"@contractspec/lib.surface-runtime/spec";async function sR($,b){if(!g7($.specType))return{valid:!0,errors:[],warnings:[]};let A=i7($.filePath),m=[`${A}/package.json`,`${A}/README.md`,`${A}/src/index.ts`,$.filePath],n=[];for(let j of m)if(!await b.exists(j))n.push(`Missing package scaffold file: ${j}`);if(n.length>0)return{valid:!1,errors:n,warnings:[]};let W;try{W=(await n$($.filePath)).exports}catch(j){return{valid:!1,errors:[j instanceof Error?j.message:String(j)],warnings:[]}}let w=$.specType==="module-bundle"?D7(W):$.specType==="builder-spec"?N7(W):F7(W);return{valid:n.length===0&&w.errors.length===0,errors:[...n,...w.errors],warnings:w.warnings.map((j)=>`[${$.filePath}] ${j}`)}}function D7($){let b=[],A=[],m=v7($,k7);if(m.length===0)return A.push(Fn("module-bundle","bundle")),{errors:b,warnings:A};for(let n of m){let W=Object.values(n.value.surfaces);for(let w of W){try{T7(w)}catch(j){b.push(`[${n.exportName}] ${j instanceof Error?j.message:String(j)}`)}for(let j of x7(w).warnings)A.push(`[${n.exportName}] ${j}`)}}return{errors:b,warnings:A}}function N7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(P7(W)){m+=1,b.push(...Z0(n,L7(W)));continue}if(r7(W)){m+=1,b.push(...Z0(n,U7(W)));continue}if(f7(W)){m+=1,b.push(...Z0(n,z7(W)));continue}if(h7(W))m+=1,b.push(...Z0(n,R7(W)))}if(m===0)A.push(Fn("builder-spec","builder"));return{errors:b,warnings:A}}function F7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(c7(W)){m+=1,b.push(...G0(n,M7(W)));continue}if(d7(W)){m+=1,b.push(...G0(n,E7(W)));continue}if(u7(W)){m+=1,b.push(...G0(n,C7(W)));continue}if(o7(W))m+=1,b.push(...G0(n,I7(W)))}if(m===0)A.push(Fn("provider-spec","provider"));return{errors:b,warnings:A}}function v7($,b){return Object.entries($).filter(([A,m])=>A!=="__esModule"&&b(m)).map(([A,m])=>({exportName:A,value:m}))}function Z0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function G0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function g7($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function k7($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function P7($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function r7($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function f7($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function h7($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function c7($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function d7($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function u7($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function o7($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function i7($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Fn($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as l7}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as t7}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as p7}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as a7}from"@contractspec/module.workspace";async function zy($,b={}){let A=[],m=[],n;if(!b.skipStructure){n=a7($),A.push(...n.errors),m.push(...n.warnings);let W=await e7($);A.push(...W.errors),m.push(...W.warnings)}return{valid:A.length===0,structureResult:n,errors:A,warnings:m,code:$.sourceBlock}}async function jC($,b={}){return Promise.all($.map(async(A)=>({spec:A,...await zy(A,b)})))}async function d$($,b,A={}){let{fs:m}=b;if(!await m.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let W=await m.readFile($),w=[],j=[],y=void 0;if(!A.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await zy(S,A);y=Q.structureResult,w.push(...Q.errors),j.push(...Q.warnings)}}return{valid:w.length===0,structureResult:y,errors:w,warnings:j,code:W}}async function yC($,b,A={}){let m=new Map;for(let n of $){let W=await d$(n,b,A);m.set(n,W)}return m}async function e7($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await n$($.filePath);if($.specType==="app-config"){let n=s7(b.exports,$),W=l7(n);return{errors:W.errors.map((w)=>Uy(w)),warnings:[...W.warnings,...W.info].map((w)=>Uy(w))}}if($.specType==="feature"){let n=$Z(b.exports,$),W=t7(n);return{errors:W.issues.filter((w)=>w.level==="error").map((w)=>X0(w)),warnings:W.issues.filter((w)=>w.level!=="error").map((w)=>X0(w))}}let A=bZ(b.exports,$),m=p7(A);return{errors:m.issues.filter((n)=>n.level==="error").map((n)=>X0(n)),warnings:m.issues.filter((n)=>n.level!=="error").map((n)=>X0(n))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function s7($,b){return vn($,b.exportName,AZ)}function $Z($,b){return vn($,b.exportName,mZ)}function bZ($,b){return vn($,b.exportName,nZ)}function vn($,b,A){if(b&&A($[b]))return $[b];let m=Object.values($).find(A);if(!m)throw Error("Expected authored module to export a compatible spec value.");return m}function AZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function mZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function nZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function Uy($){let b=$.code?`[${$.code}] `:"",A=$.path?`${$.path}: `:"";return`${b}${A}${$.message}`}function X0($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as WZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as kn}from"fs/promises";import{resolve as Y0}from"path";async function XC($,b,A,m){let{fs:n}=m,W=Y0(process.cwd(),b);if(!await n.exists(W))return{valid:!1,errors:[`Tenant config file not found: ${W}`]};try{let w=await wZ(W),j=await jZ(A.connections,n),y=await yZ(A.translationCatalog,n),B=await BZ(A.integrationRegistrars),S={};if(j.length>0)S.tenantConnections=j;if(y)S.translationCatalogs={blueprint:[y],platform:[]};if(B)S.integrationSpecs=B;let Q=WZ($,w,S);return{config:w,report:Q,valid:Q.valid,errors:Q.errors.map((Z)=>`[${Z.code}] ${Z.path}: ${Z.message}`)}}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)]}}}async function wZ($){if($.endsWith(".json")){let m=await kn($,"utf-8"),n=JSON.parse(m);if(!Ly(n))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return n}let b=await n$($),A=Object.values(b.exports).filter(Ly);if(A.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return A[0]}function Ly($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function Ey($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((A)=>A.trim()).filter(Boolean)}async function jZ($,b){let A=Ey($);if(!A.length)return[];let m=[];for(let n of A){let W=Y0(process.cwd(),n);if(!await b.exists(W)){console.warn(`Warning: Connection file not found: ${W}`);continue}if(W.endsWith(".json")){let j=await kn(W,"utf-8"),y=JSON.parse(j);m.push(...gn(y));continue}let w=await n$(W);m.push(...gn(w.exports))}return m}function gn($){if(Array.isArray($)){let b=$.filter(Ry);if(b.length)return b}if(Ry($))return[$];if($&&typeof $==="object"){let A=Object.values($).flatMap((m)=>gn(m));if(A.length)return A}return[]}function Ry($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function yZ($,b){if(!$)return;let A=Y0(process.cwd(),$);if(!await b.exists(A))return;if(A.endsWith(".json")){let W=await kn(A,"utf-8"),w=JSON.parse(W);if(Cy(w))return Iy(w);return}let m=await n$(A),n=Object.values(m.exports).filter(Cy);if(n.length===0)return;return Iy(n[0])}function Cy($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function Iy($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function BZ($){let b=Ey($);if(!b.length)return;let{IntegrationSpecRegistry:A}=await import("@contractspec/lib.contracts-integrations"),m=new A;for(let n of b){let{modulePath:W,exportName:w}=SZ(n);if(!W)continue;let j=Y0(process.cwd(),W);try{let y=await n$(j),B=QZ(y.exports,w);if(B)await B(m)}catch(y){console.warn(`Failed to load registrar from ${j}: ${y}`)}}return m}function SZ($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),m=b?.trim()??null,n=A?.trim();return{modulePath:m,exportName:n}}function QZ($,b){if(b){let A=$[b];if(typeof A==="function")return A;return}if(typeof $.default==="function")return $.default;for(let A of Object.values($))if(typeof A==="function")return A;return}async function LC($,b,A={},m){let{fs:n,logger:W}=$,w=await n.glob({pattern:A.pattern}),j=A.outputDirs?.length?A.outputDirs:[void 0],y=[],B=m?.validate??((Q)=>d$(Q,{fs:n,logger:W})),S=m?.build??((Q,Z)=>$b(Q,{fs:n,logger:W},Z?{...b,outputDir:Z}:b,{...A.buildOptions??{},outputDir:Z}));for(let Q of w)for(let Z of j){let G={specPath:Q,outputDir:Z};if(A.validate)try{G.validation=await B(Q)}catch(X){G.error={phase:"validate",message:X instanceof Error?X.message:String(X)},y.push(G);continue}if(!A.dryRun)try{G.build=await S(Q,Z)}catch(X){G.error={phase:"build",message:X instanceof Error?X.message:String(X)},y.push(G);continue}else W.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});y.push(G)}return{specs:w,runs:y}}import{generateText as ZZ}from"ai";var GZ=`
|
|
2424
|
+
`}function lm($){return $.replace(/\r\n/g,`
|
|
2425
|
+
`).trimEnd()}function mZ($){return new RegExp(`${lj($.startMarker)}[\\s\\S]*?${lj($.endMarker)}(?:\\r?\\n)?`)}function lj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yZ="<!-- contractspec:init:agents:start -->",WZ="<!-- contractspec:init:agents:end -->",wZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",pj={endMarker:WZ,note:wZ,startMarker:yZ};async function pm($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"AGENTS.md");try{let y=await $.exists(m),W=Bw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:m,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(m,zA(w,W,pj,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,$n(W,pj)),{target:"agents-md",filePath:m,action:"created",message:"Created AI agent guide"}}catch(y){return{target:"agents-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}import{generateArtifactsForAudience as jZ,generateBiomePreset as BZ}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=jZ("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,BZ("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(j.plugins))await $.writeFile($.join(W,S),Q);return await $.writeFile($.join(w,"consumer.md"),j.aiRules),{target:"biome-config",filePath:m,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:m,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function em($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".contractsrc.json");try{let y=await $.exists(m),W=Wb(b);if(y){let w=await $.readFile(m),j=a(w);if(!j)return{target:"cli-config",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=b$(j,W);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof W==="object"&&W!==null){let S={};if("connect"in W)S.connect=W.connect;if("builder"in W)S.builder=W.builder;await $.writeFile(m,N(D0(B,S)))}else await $.writeFile(m,N(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,N(W)),{target:"cli-config",filePath:m,action:"created",message:"Created CLI configuration"}}catch(y){return{target:"cli-config",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function sm($,b,n){let A=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(A,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=jw(b);if(W)if(b.interactive){if(!await n.confirm(`${m} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:m,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:m,action:"skipped",message:"File already exists"};return await $.writeFile(m,w),{target:"cursor-rules",filePath:m,action:W?"merged":"created",message:W?"Updated Cursor rules":"Created Cursor rules"}}catch(y){return{target:"cursor-rules",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function $y($,b,n){let A=ln();try{let m=await $.exists(A),y=ww();if(b.interactive){if(!await n.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(A),B=a(j);if(!B)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let S=b$(B,y);return await $.writeFile(A,N(S)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(A,N(y)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:A,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function by($,b,n){let A=$.join(b.workspaceRoot,".cursor"),m=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=Mb();if(W){let j=await $.readFile(m),B=a(j);if(!B)return{target:"mcp-cursor",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=b$(B,w);return await $.writeFile(m,N(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,N(w)),{target:"mcp-cursor",filePath:m,action:"created",message:"Created Cursor MCP configuration"}}catch(y){return{target:"mcp-cursor",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}var SZ="<!-- contractspec:init:usage:start -->",QZ="<!-- contractspec:init:usage:end -->",ZZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:QZ,note:ZZ,startMarker:SZ};async function ny($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"USAGE.md");try{let y=await $.exists(m),W=Sw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:m,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(m,zA(w,W,aj,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,$n(W,aj)),{target:"usage-md",filePath:m,action:"created",message:"Created usage guide"}}catch(y){return{target:"usage-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function Ay($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=tn(b);if(w){let B=await $.readFile(y),S=a(B);if(!S)return{target:"vscode-settings",filePath:y,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=b$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,N(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,N(j)),{target:"vscode-settings",filePath:y,action:"created",message:"Created VS Code settings"}}catch(W){return{target:"vscode-settings",filePath:y,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var XZ={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??""},YZ={"agents-md":pm,"biome-config":am,"cli-config":em,"cursor-rules":sm,"mcp-claude":$y,"mcp-cursor":by,"usage-md":ny,"vscode-settings":Ay},GZ={findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$};async function sC($,b,n=XZ,A={}){let m=[],y=b.targets.length>0?b.targets:xb,W={...GZ,...A.workspace},w={...YZ,...A.targets},j=A.setupGitignore??ZA,B=b.workspaceRoot,S=W.findWorkspaceRoot(B),Q=b.packageRoot??W.findPackageRoot(B),Z=b.isMonorepo??W.isMonorepo(S),X=b.packageName??(Z?W.getPackageName(Q):void 0),Y=await ej($,[Q,S]),G=b.preset??Eb(Y);if(b.interactive&&!b.preset)G=await n.select("Select initialization preset:",$w.map((g)=>({value:g,label:bw[g],description:nw[g],selected:g===G})));let V=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)V=await n.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${X??Q})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${S})`,description:"Create config files at the workspace root"}]);let K=Z&&V==="package"?Q:S,J=await ej($,[K]),U={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:V,packageName:X,preset:G,builderApiBaseUrl:b.builderApiBaseUrl??J?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??J?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??J?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??J?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??J?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??J?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??J?.connect?.studio?.queue},H=Aw(G,y);if(b.interactive)H=await n.multiSelect("Select components to configure:",xb.map((g)=>({value:g,label:sW[g],selected:H.includes(g)})));let q=U.projectName;if(b.interactive&&!q){let g=V==="package"&&X?X:K.split("/").pop()??"my-project";q=await n.input("Project name:",g)}let _=U.builderApiBaseUrl;if(b.interactive&&G.startsWith("builder-"))_=await n.input("Builder API base URL:",_??"https://api.contractspec.io");let{builderLocalRuntimeId:z,builderLocalGrantedTo:L}=U;if(b.interactive&&(G==="builder-local"||G==="builder-hybrid"))z=await n.input("Default local runtime target id:",z??"rt_local_daemon"),L=await n.input("Default local runtime grant target:",L??"local:operator");let C={...U,projectName:q,targets:H,builderApiBaseUrl:_,builderLocalRuntimeId:z,builderLocalGrantedTo:L};for(let g of H){let iA=await HZ($,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 HZ($,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 OZ}from"path";async function Yx($,b){let{fs:n}=b,A=OZ(process.cwd(),$);if(!await n.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let m=await y$(A),y=VZ(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 VZ($){let b=Object.values($).filter(JZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function JZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as UZ,dirname as my,join as bn}from"path";async function Ox($,b,n,A,m){let{fs:y}=m,W=A.implementationPath;if(!W){let S=my($),Q=UZ($,".ts"),Z=[bn(S,Q.replace(".contracts",".handler")+".ts"),bn(S,Q.replace(".presentation","")+".tsx"),bn(S,Q.replace(".form",".form")+".tsx"),bn(my(S),"handlers",Q.replace(".contracts",".handler")+".ts"),bn(my(S),"components",Q.replace(".presentation","")+".tsx")];for(let X of Z)if(await y.exists(X)){W=X;break}}if(!W||!await y.exists(W))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let w=await y.readFile(W),B=await new On(n).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as KZ,validateBuilderReadinessReport as _Z,validateBuilderWorkspace as zZ,validateBuilderWorkspaceSnapshot as LZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as RZ,validateExternalPatchProposal as CZ,validateProviderRoutingPolicy as xZ,validateRuntimeTarget as IZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as EZ,validateLayoutSlots as MZ}from"@contractspec/lib.surface-runtime/spec";async function zx($,b){if(!vZ($.specType))return{valid:!0,errors:[],warnings:[]};let n=oZ($.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"?TZ(y):$.specType==="builder-spec"?DZ(y):NZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function TZ($){let b=[],n=[],A=FZ($,gZ);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{MZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of EZ(W).warnings)n.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:n}}function DZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(PZ(y)){A+=1,b.push(...LA(m,zZ(y)));continue}if(kZ(y)){A+=1,b.push(...LA(m,KZ(y)));continue}if(rZ(y)){A+=1,b.push(...LA(m,_Z(y)));continue}if(fZ(y))A+=1,b.push(...LA(m,LZ(y)))}if(A===0)n.push(yy("builder-spec","builder"));return{errors:b,warnings:n}}function NZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(cZ(y)){A+=1,b.push(...RA(m,IZ(y)));continue}if(hZ(y)){A+=1,b.push(...RA(m,xZ(y)));continue}if(dZ(y)){A+=1,b.push(...RA(m,RZ(y)));continue}if(uZ(y))A+=1,b.push(...RA(m,CZ(y)))}if(A===0)n.push(yy("provider-spec","provider"));return{errors:b,warnings:n}}function FZ($,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 vZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function gZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function PZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function kZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function rZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function fZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function cZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function hZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function dZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function uZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function oZ($){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 iZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as tZ}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as lZ}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as pZ}from"@contractspec/module.workspace";async function $1($,b={}){let n=[],A=[],m;if(!b.skipStructure){m=pZ($),n.push(...m.errors),A.push(...m.warnings);let y=await aZ($);n.push(...y.errors),A.push(...y.warnings)}return{valid:n.length===0,structureResult:m,errors:n,warnings:A,code:$.sourceBlock}}async function Tx($,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 Dx($,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 aZ($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await y$($.filePath);if($.specType==="app-config"){let m=eZ(b.exports,$),y=iZ(m);return{errors:y.errors.map((W)=>sj(W)),warnings:[...y.warnings,...y.info].map((W)=>sj(W))}}if($.specType==="feature"){let m=sZ(b.exports,$),y=tZ(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=$2(b.exports,$),A=lZ(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 eZ($,b){return Wy($,b.exportName,b2)}function sZ($,b){return Wy($,b.exportName,n2)}function $2($,b){return Wy($,b.exportName,A2)}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 b2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function n2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function A2($){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 m2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as jy}from"fs/promises";import{resolve as xA}from"path";async function kx($,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 y2(y),w=await W2(n.connections,m),j=await w2(n.translationCatalog,m),B=await j2(n.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=m2($,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 y2($){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 w2($,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 j2($){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}=B2(m);if(!y)continue;let w=xA(process.cwd(),y);try{let j=await y$(w),B=S2(j.exports,W);if(B)await B(A)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return A}function B2($){if(!$)return{modulePath:null};let[b,n]=$.split("#"),A=b?.trim()??null,m=n?.trim();return{modulePath:A,exportName:m}}function S2($,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 px($,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 Q2}from"ai";var Z2=`
|
|
2331
2426
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2332
2427
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2333
2428
|
|
|
@@ -2345,7 +2440,7 @@ Generate scenarios covering:
|
|
|
2345
2440
|
- Happy path (valid input, successful execution)
|
|
2346
2441
|
- Edge cases (boundary values, optional fields)
|
|
2347
2442
|
- Error cases (invalid input, business rule violations)
|
|
2348
|
-
`.trim();class
|
|
2443
|
+
`.trim();class X2{logger;defaultModel;generateTextImpl;constructor($,b,n=Q2){this.logger=$;this.defaultModel=b;this.generateTextImpl=n}async generateTests($,b={}){let n=b.model??this.defaultModel;if(!n)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let A=`
|
|
2349
2444
|
Generate a TestSpec for the following Operation:
|
|
2350
2445
|
|
|
2351
2446
|
\`\`\`json
|
|
@@ -2354,23 +2449,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2354
2449
|
|
|
2355
2450
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2356
2451
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2357
|
-
`.trim();try{let{text:
|
|
2358
|
-
`)}function
|
|
2359
|
-
`)}function
|
|
2360
|
-
`);for(let
|
|
2361
|
-
`)}function
|
|
2452
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:n,system:Z2,prompt:A});this.logUsage(y);let W=this.parseResponse(m);return this.enrichSpec(W,$)}catch(m){throw this.logger.error("Failed to generate tests",{error:m}),m}}parseResponse($){try{let b=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(b)}catch(b){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,b){let n={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},A={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:n,target:A,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let b=$;this.logger.debug(`AI Usage: ${b.promptTokens} prompt + ${b.completionTokens} completion = ${b.totalTokens} total tokens`)}}import{OperationSpecRegistry as W1}from"@contractspec/lib.contracts-spec";import{TestRunner as w1}from"@contractspec/lib.contracts-spec/tests";import{resolve as By}from"path";async function mI($,b){let n=new w1({registry:b}),A=[],m=0,y=0;for(let W of $){let w=await n.run(W);A.push(w),m+=w.passed,y+=w.failed}return{results:A,passed:m,failed:y}}async function yI($,b,n){let{logger:A}=n,m;if(b.registry)m=await G2(By(b.registry));else m=new W1,A.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let y=new w1({registry:m}),W=[],w=!0;for(let j of $)try{let B=By(j),S=await UA(B),Q=j1(S);if(Q.length===0){A.warn(`No TestSpec exports found in ${j}`);continue}for(let Z of Q){A.info(`Running ${Z.meta.key}...`);let X=await y.run(Z);if(W.push(X),X.failed>0)w=!1,A.error(`${Z.meta.key} failed (${X.failed}/${X.scenarios.length})`);else A.info(`${Z.meta.key} passed (${X.passed}/${X.scenarios.length})`)}}catch(B){A.error(`Failed to load/run spec ${j}: ${B instanceof Error?B.message:String(B)}`),w=!1}return{results:W,passed:w}}async function WI($,b){let n=[];for(let A of $)try{let m=By(A),y=await UA(m),W=j1(y);n.push(...W)}catch(m){b.logger.warn(`Failed to load tests from ${A}: ${m instanceof Error?m.message:String(m)}`)}return n}function j1($){let b=[];for(let n of Object.values($))if(Y2(n))b.push(n);return b}function Y2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function G2($){return Pj($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof W1,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as nn}from"@contractspec/module.workspace";import{IndentationText as H2,Node as Xb,Project as q2,QuoteKind as O2,SyntaxKind as V2}from"ts-morph";function J2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function YI($,b,n={}){let{fs:A,logger:m}=b;if(!await A.exists($))return{specPath:$,specInfo:J2($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let W=await A.readFile($),w;if(n.content!==void 0)w=n.content;else if(n.fields?.length)w=U2(W,n.fields);else return{specPath:$,specInfo:nn(W,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!n.skipValidation){await A.writeFile($,w);let j=await l$($,b);if(j.errors.length>0)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:j.errors,warnings:j.warnings};if(j.warnings.length>0&&!n.allowWarnings)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:j.warnings};return m.info(`Updated spec: ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:j.warnings}}return await A.writeFile($,w),m.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:[]}}function U2($,b){let A=new q2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:H2.TwoSpaces,quoteKind:O2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=_2(A);if(!m)return $;for(let y of b)K2(m,y);return A.getFullText()}function K2($,b){let n=b.key.split(".").map((w)=>w.trim()).filter(Boolean);if(n.length===0)return;let A=$;for(let w of n.slice(0,-1)){if(!A.getProperty(w))A.addPropertyAssignment({name:w,initializer:"{}"});let B=A.getPropertyOrThrow(w);if(!Xb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!Xb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(V2.ObjectLiteralExpression);if(!Q)return;A=Q}let m=n[n.length-1];if(!m)return;let y=z2(b.value),W=A.getProperty(m);if(W&&Xb.isPropertyAssignment(W)){W.setInitializer(y);return}A.addPropertyAssignment({name:m,initializer:y})}function _2($){for(let b of $.getVariableDeclarations()){let n=b.getInitializer();if(!n)continue;if(Xb.isObjectLiteralExpression(n))return n;if(Xb.isCallExpression(n)){let A=n.getArguments()[0];if(A&&Xb.isObjectLiteralExpression(A))return A}}return}function z2($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var z1={};f(z1,{getPackageUpgradeCommand:()=>O1,getDefaultVersioningConfig:()=>EA,getDefaultHooksConfig:()=>MA,applyGuidedUpgrade:()=>_1,applyConfigUpgrades:()=>q1,analyzeUpgrades:()=>IA,analyzeGuidedUpgrade:()=>Xy});import{GeneratedReleaseManifestSchema as U1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as D2,DEFAULT_CONTRACTSRC as N2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function B1($){return $.packages.map((b)=>{let n=b.version?`@${b.version}`:"";return`- ${b.name}${n} (${b.releaseType})`})}function S1($){return $.map((b)=>` - ${b}`)}function Sy($,b){return $.audiences.filter((n)=>b.includes(n.kind)).map((n)=>`- ${L2(n.kind)}: ${n.summary}`)}function Q1($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...B1($),...Sy($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));return b.join(`
|
|
2453
|
+
`)}function Z1($){let b=[`### ${$.summary}`,...B1($),...Sy($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`);return b.join(`
|
|
2454
|
+
`)}function X1($){let b=[`### ${$.summary}`,...Sy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2455
|
+
`);for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`),b.push(...S1(n.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let n of $.upgradeSteps)b.push(` - [${n.level}] ${n.title}: ${n.summary}`),b.push(...n.instructions.map((A)=>` - ${A}`))}return b.join(`
|
|
2456
|
+
`)}function Qy($){return["# Patch Notes","",...$.releases.map(Q1)].join(`
|
|
2362
2457
|
|
|
2363
|
-
`)}function
|
|
2458
|
+
`)}function Zy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[Z1(b),"",X1(b)])].join(`
|
|
2364
2459
|
|
|
2365
|
-
`)}function
|
|
2460
|
+
`)}function Y1($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...S1(b.instructions)].join(`
|
|
2366
2461
|
`)).join(`
|
|
2367
|
-
`)}function
|
|
2368
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2369
|
-
`)}function
|
|
2370
|
-
`),
|
|
2371
|
-
`),!0}async function
|
|
2372
|
-
`),!0}async function
|
|
2373
|
-
`),
|
|
2462
|
+
`)}function Yb($,b){let n=b.targetPackages.map((A)=>`${A.name}: ${A.currentVersion??"unknown"} -> ${A.targetVersion??"latest"}`).join(`
|
|
2463
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",n||"- No package version targets were inferred.","","Required steps:",Y1(b)].join(`
|
|
2464
|
+
`)}function L2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as H1,countUpgradePlanStepLevels as R2,createAgentPromptBundles as C2,dedupeUpgradePlanSteps as x2,sortReleaseManifest as G1}from"@contractspec/lib.contracts-spec";function I2($,b){if(b.length===0)return G1($);let n=new Map(b.map((A)=>[A.name,A.currentVersion??"0.0.0"]));return G1({...$,releases:$.releases.filter((A)=>A.packages.some((m)=>{let y=n.get(m.name);if(!y||!m.version)return!1;return H1(m.version,y)===1}))})}function An($,b,n,A){let m=I2($,b),y=E2(m,b),W=x2(m.flatMap((S)=>S.upgradeSteps)),w=R2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=C2(j,n,A);return{...j,agentPrompts:B}}function E2($,b){let n=new Map(b.map((m)=>[m.name,m.currentVersion])),A=new Map;for(let m of $)for(let y of m.packages){let W=n.get(y.name),w=A.get(y.name);if(!w){A.set(y.name,{name:y.name,currentVersion:W,targetVersion:y.version});continue}if(y.version&&w.targetVersion&&H1(y.version,w.targetVersion)===1)w.targetVersion=y.version}return Array.from(A.values()).sort((m,y)=>m.name.localeCompare(y.name))}async function IA($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=a$(y);A.info("Analyzing available upgrades...",{workspaceRoot:y,packageRoot:m,packageManager:W});let w=await M2(n,m),j=await T2(n,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function M2($,b){let n=$.join(b,"package.json");if(!await $.exists(n))return[];try{let A=await $.readFile(n),m=JSON.parse(A),y=m.dependencies??{},W=m.devDependencies??{},w=[],j={...y,...W};for(let[B,S]of Object.entries(j))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))w.push({name:B,currentVersion:S,isDevDependency:!!W[B]});return w}catch{return[]}}async function T2($,b,n){let A=$.join(b,".contractsrc.json"),m=Cb({configRoot:b,workspaceRoot:n});if(!await $.exists(A))return[];try{let y=await $.readFile(A),W=JSON.parse(y),w=[],j=W.$schema;if(!j||j!==m)w.push({key:"$schema",currentValue:j,suggestedValue:m,isNew:!j});if(!W.versioning)w.push({key:"versioning",currentValue:void 0,suggestedValue:EA(),isNew:!0});else if(W.versioning.integrateWithChangesets===void 0)w.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!W.hooks)w.push({key:"hooks",currentValue:void 0,suggestedValue:MA(),isNew:!0});if(!W.release)w.push({key:"release",currentValue:void 0,suggestedValue:V1(),isNew:!0});if(!W.upgrade)w.push({key:"upgrade",currentValue:void 0,suggestedValue:J1(),isNew:!0});return w}catch{return[]}}async function q1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=Cb({configRoot:m,workspaceRoot:y});if(b.dryRun)A.info("Dry run - no changes will be made");let w=n.join(m,".contractsrc.json");if(!await n.exists(w))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let j=await n.readFile(w),B=JSON.parse(j),S=0,Q=B.$schema;if(!Q||Q!==W)B.$schema=W,S++;if(!B.versioning)B.versioning=EA(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=MA(),S++;if(!B.release)B.release=V1(),S++;if(!B.upgrade)B.upgrade=J1(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await n.writeFile(w,JSON.stringify(B,null,2)+`
|
|
2465
|
+
`),A.info("Configuration upgraded",{sectionsUpgraded:S});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:S,summary:b.dryRun?`Would upgrade ${S} config section(s)`:`Upgraded ${S} config section(s)`}}catch(j){let B=j instanceof Error?j.message:String(j);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function O1($,b,n){let A=n?b.map((m)=>`${m.name}@latest`).join(" "):b.map((m)=>m.name).join(" ");switch($){case"bun":return`bun add ${A}`;case"pnpm":return`pnpm add ${A}`;case"yarn":return`yarn add ${A}`;default:return`npm install ${A}`}}function EA(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function MA(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function V1(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function J1(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var F2="**/*.{ts,tsx,js,jsx,mjs,cjs}",K1=N2.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Xy($,b){let{fs:n}=$,A=c(b.workspaceRoot),m=I(b.workspaceRoot),y=await g2(n,A,m),W=await v2(n,A,m,b.manifestPaths??y.manifestPaths),w=await IA($,{workspaceRoot:A,dryRun:b.dryRun}),j=[b.agentTarget??y.defaultAgentTarget??"codex"],B=An(W.manifest,w.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),j,Yb),S=P2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:k2(S)}}async function _1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=await Xy($,b),W=[];if(!b.dryRun){for(let j of y.plan.steps){if(j.level!=="auto")continue;for(let B of j.autofixes??[])if(await r2(n,m,B))W.push(B.id)}A.info("Applied guided upgrade autofixes",{count:W.length,workspaceRoot:m})}let w=y.plan.steps.filter((j)=>j.level!=="auto");return{success:!0,packagesUpgraded:W.filter((j)=>j.startsWith("pkg:")).length,configSectionsUpgraded:W.filter((j)=>j.startsWith("config:")).length,summary:b.dryRun?`Would apply ${y.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${W.length} deterministic upgrade autofix(es)`,appliedAutofixes:W,remainingSteps:w,humanChecklist:y.humanChecklist,promptBundle:y.plan.agentPrompts[0],plan:y.plan,manifestPath:y.manifestPath}}async function v2($,b,n,A){let m=A??["generated/releases/upgrade-manifest.json"],y=Array.from(new Set([b,n]));for(let W of m){let w=W.startsWith("/")?[W]:y.map((j)=>$.join(j,W));for(let j of w){if(!await $.exists(j))continue;let B=U1.parse(JSON.parse(await $.readFile(j)));return{path:j,manifest:B}}}return{manifest:U1.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function g2($,b,n){for(let A of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(n,".contractsrc.json")]))){if(!await $.exists(A))continue;try{let m=JSON.parse(await $.readFile(A)),y=D2.safeParse(m);if(y.success)return{...K1,...y.data.upgrade}}catch{continue}}return K1}function P2($,b,n){let A=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;A.push({id:`pkg:${S.name}`,kind:"package-json",title:`Update ${S.name}`,summary:`Update ${S.name} to ${Q.targetVersion}`,packageName:S.name,dependencyType:S.isDevDependency?"devDependencies":"dependencies",from:S.currentVersion,to:Q.targetVersion})}let m=n.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),y=[];if(A.length>0)y.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:A.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:A.map((S)=>S.packageName??""),autofixes:A});if(m.length>0)y.push({id:"upgrade-contractsrc-config",title:"Refresh .contractsrc.json defaults",summary:"Bring workspace release and upgrade config in line with current defaults.",level:"auto",instructions:m.map((S)=>`${S.configPath} -> updated`),autofixes:m});let W=[...y,...$.steps],w=W.filter((S)=>S.level==="auto").length,j=W.filter((S)=>S.level==="assisted").length,B=W.filter((S)=>S.level==="manual").length;return{...$,steps:W,autofixCount:w,assistedCount:j,manualCount:B,agentPrompts:An({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),Yb).agentPrompts}}function k2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function r2($,b,n){switch(n.kind){case"package-json":return f2($,b,n);case"contractsrc":return c2($,b,n);case"import-rewrite":return h2($,b,n);case"codemod":return!1}}async function f2($,b,n){let A=$.join(b,"package.json");if(!await $.exists(A))return!1;let m=JSON.parse(await $.readFile(A)),y=n.dependencyType??"dependencies",W=m[y]??{};if(!n.packageName||!n.to||!W[n.packageName])return!1;return W[n.packageName]=n.to,m[y]=W,await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2466
|
+
`),!0}async function c2($,b,n){let A=$.join(b,".contractsrc.json"),m=await $.exists(A)?JSON.parse(await $.readFile(A)):{};if(!n.configPath)return!1;return d2(m,n.configPath,n.value),await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2467
|
+
`),!0}async function h2($,b,n){if(!n.from||!n.to)return!1;let A=await $.glob({pattern:n.path??F2,cwd:b,absolute:!0}),m=!1;for(let y of A){let W=await $.readFile(y);if(!W.includes(n.from))continue;await $.writeFile(y,W.split(n.from).join(n.to)),m=!0}return m}function d2($,b,n){let A=b.split("."),m=$;for(let W of A.slice(0,-1)){let w=m[W];if(!w||typeof w!=="object"||Array.isArray(w))m[W]={};m=m[W]}let y=A.at(-1);if(y)m[y]=n}import{existsSync as Yy,mkdirSync as u2,readFileSync as o2,renameSync as i2,statSync as t2,writeFileSync as l2}from"fs";import{dirname as p2,join as a2}from"path";var e2=".contractspec/verification-cache.json",L1=1;class R1{filePath;cache;isDirty=!1;constructor($,b){let n=b??process.cwd();this.filePath=$??a2(n,e2),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Yy(this.filePath))return;let $=o2(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==L1)return;for(let[n,A]of Object.entries(b.entries))this.cache.set(n,A)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=p2(this.filePath);if(!Yy($))u2($,{recursive:!0});let b={version:L1,entries:Object.fromEntries(this.cache.entries())},n=`${this.filePath}.tmp`;l2(n,JSON.stringify(b,null,2),"utf-8"),i2(n,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(Yy(this.filePath))$=t2(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function NI($,b){return new R1($,b)}class C1{cache=new Map;async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[b,n]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(n).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function vI(){return new C1}class x1{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let b=this.getStorageKey($);return this.store.get(b)??null}async set($,b){let n=this.getStorageKey($);if(await this.store.update(n,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),n=this.keyIndex.has($);if(n)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return n}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function PI($){return new x1($)}import{createHash as s2}from"crypto";var I1={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function E1($){return s2("sha256").update($).digest("hex")}function M1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function $X($){try{let b=$.split("|"),n=new Map;for(let W of b){let[w,j]=W.split(":");if(w&&j)n.set(w,j)}let A=n.get("spec"),m=n.get("impl"),y=n.get("tier");if(!A||!m||!y)return null;return{specHash:A,implHash:m,tier:y,aiModelVersion:n.get("model")}}catch{return null}}function bX($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class T1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...I1,...b},this.stats={hits:0,misses:0}}createKey($,b,n,A){return{specHash:E1($),implHash:E1(b),tier:n,aiModelVersion:n==="ai_review"?A:void 0}}async lookup($){let b=M1($),n=await this.storage.get(b);if(!n)return this.stats.misses++,{hit:!1,reason:"not_found"};if(n.meta.expiresAt){let A=new Date(n.meta.expiresAt).getTime();if(Date.now()>A)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(n.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(n.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&n.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:n}}async store($,b,n={}){let A=M1($),m=bX($.tier,this.config),y={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+m).toISOString(),dependencies:n.dependencies??[],specName:n.specName,implPath:n.implPath}};await this.storage.set(A,y),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),n=0;for(let A of b){let m=await this.storage.get(A);if(!m)continue;if(m.meta.dependencies.includes($))await this.storage.delete(A),n++;if(m.meta.specName===$||m.meta.implPath===$)await this.storage.delete(A),n++}return n}async invalidateForSpec($){let b=await this.storage.keys(),n=0;for(let A of b){let m=$X(A);if(m&&m.specHash.startsWith($.substring(0,16)))await this.storage.delete(A),n++}return n}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let b=[];for(let A of $){let m=await this.storage.get(A);if(m)b.push({key:A,createdAt:new Date(m.meta.createdAt).getTime()})}b.sort((A,m)=>A.createdAt-m.createdAt);let n=b.length-this.config.maxEntries;for(let A=0;A<n;A++){let m=b[A];if(m)await this.storage.delete(m.key)}}}function iI($,b){return new T1($,b)}import{generateVerificationPrompt as nX}from"@contractspec/lib.contracts-spec/llm";function AX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let j=JSON.parse(b[1]);return{compliant:j.passed??!1,confidence:(j.score??0)/100,findings:(j.issues??[]).map((B)=>({category:String(B.category??"semantic"),severity:String(B.severity??"warning"),message:String(B.message??""),location:B.location?String(B.location):void 0,suggestion:B.suggestion?String(B.suggestion):void 0})),rawResponse:$}}catch{}let n=[],A=$.split(`
|
|
2468
|
+
`),m="info";for(let j of A){let B=j.toLowerCase();if(B.includes("error")||B.includes("critical"))m="error";else if(B.includes("warning")||B.includes("should"))m="warning";else if(B.includes("info")||B.includes("note"))m="info";let S=j.match(/^[-*\u2022]\s*(.+)$/),Q=j.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)n.push({category:"semantic",severity:m,message:Z})}}let y=n.some((j)=>j.severity==="error"),W=!y,w=y?0.3:n.length===0?0.9:0.7;return{compliant:W,confidence:w,findings:n,rawResponse:$}}async function D1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2374
2469
|
{
|
|
2375
2470
|
"passed": true,
|
|
2376
2471
|
"score": 50,
|
|
@@ -2387,16 +2482,16 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2387
2482
|
],
|
|
2388
2483
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2389
2484
|
}
|
|
2390
|
-
\`\`\``;try{let
|
|
2485
|
+
\`\`\``;try{let n=b.aiProvider??"anthropic";if(n==="anthropic"){let{anthropic:A}=await import("@ai-sdk/anthropic"),{generateText:m}=await import("ai");return(await m({model:A("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(n==="openai"){let{openai:A}=await import("@ai-sdk/openai"),{generateText:m}=await import("ai");return(await m({model:A("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${n}`)}catch(n){return`\`\`\`json
|
|
2391
2486
|
{
|
|
2392
2487
|
"passed": false,
|
|
2393
2488
|
"score": 0,
|
|
2394
2489
|
"issues": [
|
|
2395
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2490
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${n instanceof Error?n.message:"Unknown error"}" }
|
|
2396
2491
|
],
|
|
2397
2492
|
"summary": "AI verification encountered an error"
|
|
2398
2493
|
}
|
|
2399
|
-
\`\`\``}}async function
|
|
2494
|
+
\`\`\``}}async function mn($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=nX(n,A),w=await D1(W.taskPrompt,b),j=AX(w),B=j.findings.map((X)=>({severity:X.severity,category:"semantic",message:X.message,location:X.location?{file:X.location}:m?{file:m}:void 0,suggestion:X.suggestion})),S=Math.round(j.confidence*100),Q=j.compliant,Z=j.findings.filter((X)=>X.suggestion).map((X)=>X.suggestion);return{tier:"ai_review",passed:Q,score:S,issues:B,suggestions:Z,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Q?1:0}},meta:{specName:n.meta.key,specVersion:n.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-y}}}function TA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];if(n.includes("console.log"))y.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(n.includes("// TODO")||n.includes("// FIXME"))y.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(b.policy.auth!=="anonymous"&&!n.includes("auth"))y.push({severity:"warning",category:"semantic",message:`Spec requires ${b.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let W=y.filter((j)=>j.severity==="error").length===0?80:40,w=y.filter((j)=>j.severity==="error").length===0;return{tier:"ai_review",passed:w,score:W,issues:y,suggestions:y.filter((j)=>j.suggestion).map((j)=>j.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:w?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}function mX($,b){return`You are analyzing a code implementation against its specification.
|
|
2400
2495
|
|
|
2401
2496
|
## Spec Schema Fields
|
|
2402
2497
|
${$}
|
|
@@ -2443,43 +2538,43 @@ Match types:
|
|
|
2443
2538
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2444
2539
|
- "mismatch": Different meaning despite similar naming
|
|
2445
2540
|
- "missing": Spec field not found in implementation
|
|
2446
|
-
`}function
|
|
2447
|
-
`)}function
|
|
2448
|
-
`),
|
|
2449
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let
|
|
2450
|
-
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function
|
|
2451
|
-
`)}function
|
|
2452
|
-
`)}function
|
|
2453
|
-
`),
|
|
2454
|
-
`).trim()||void 0,B=
|
|
2455
|
-
${b.map((
|
|
2541
|
+
`}function yX($){let b=[],n=(A,m)=>{try{let W=A?._def?.shape;if(W&&typeof W==="function"){let w=W();for(let[j,B]of Object.entries(w)){let Q=B?._def?.typeName??"unknown";b.push(`- ${j}: ${String(Q).replace("Zod","").toLowerCase()} (${m})`)}}}catch{b.push(`- [unable to extract ${m} fields]`)}};if($.io.input)n($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))n($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2542
|
+
`)}function WX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let n=JSON.parse(b[1]);return{fieldMappings:(n.fieldMappings??[]).map((A)=>({specField:String(A.specField??""),specType:String(A.specType??"unknown"),implementationField:A.implementationField?String(A.implementationField):void 0,implementationType:A.implementationType?String(A.implementationType):void 0,match:A.match??"missing",aiConfidence:typeof A.aiConfidence==="number"?A.aiConfidence:0.5,suggestion:A.suggestion?String(A.suggestion):void 0})),intentAlignment:{score:typeof n.intentAlignment?.score==="number"?n.intentAlignment.score:50,issues:Array.isArray(n.intentAlignment?.issues)?n.intentAlignment.issues:[],suggestions:Array.isArray(n.intentAlignment?.suggestions)?n.intentAlignment.suggestions:[]},semanticIssues:(n.semanticIssues??[]).map((A)=>({category:String(A.category??"semantic"),severity:A.severity??"warning",message:String(A.message??""),suggestion:A.suggestion?String(A.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function N1($,b={}){let{spec:n,implementationCode:A}=$,m=yX(n),y=mX(m,A),W=await D1(y,b);return WX(W)}async function wX($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=await mn($,b),w;if(b.aiApiKey)try{w=await N1($,b)}catch{}if(w){let j=[];for(let Z of w.fieldMappings)if(Z.match==="missing")j.push({severity:"error",category:"semantic",message:`Missing field: '${Z.specField}' (${Z.specType}) not found in implementation`,suggestion:Z.suggestion??`Add field '${Z.specField}' to implementation`});else if(Z.match==="mismatch")j.push({severity:"warning",category:"semantic",message:`Field mismatch: '${Z.specField}' has incorrect implementation as '${Z.implementationField}'`,suggestion:Z.suggestion});else if(Z.match==="compatible"&&Z.aiConfidence<0.8)j.push({severity:"info",category:"semantic",message:`Field naming: '${Z.specField}' implemented as '${Z.implementationField}' (compatible but not exact)`,suggestion:Z.suggestion});for(let Z of w.intentAlignment.issues)j.push({severity:"warning",category:"semantic",message:Z});for(let Z of w.semanticIssues)j.push({severity:Z.severity,category:"semantic",message:Z.message,suggestion:Z.suggestion});W.issues=[...W.issues,...j];let B=w.fieldMappings.length,S=w.fieldMappings.filter((Z)=>Z.match==="exact"||Z.match==="compatible").length;if(B>0){let Z=Math.round(S/B*100);W.score=Math.round((W.score+Z)/2),W.coverage.fields={total:B,implemented:S}}if(j.some((Z)=>Z.severity==="error"))W.passed=!1;W.suggestions=[...W.suggestions,...w.intentAlignment.suggestions]}return W.meta={...W.meta,duration:Date.now()-y},W}import{isEmitDeclRef as jX}from"@contractspec/lib.contracts-spec/operations";function BX($,b){let n=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),A=$.toLowerCase(),m=n.filter((B)=>A.includes(B)),y=n.length>0?m.length/n.length:0,W=b.key.toLowerCase().replace(/\s+/g,""),w=A.includes(W)||A.includes(`test('${b.key.toLowerCase()}'`)||A.includes(`it('${b.key.toLowerCase()}'`)||A.includes(`describe('${b.key.toLowerCase()}'`),j=y>=0.3||w;return{name:b.key,type:"scenario",passed:j,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:j?void 0:`Scenario keywords not found in implementation (${Math.round(y*100)}% coverage)`}}function SX($,b){let n=JSON.stringify(b.input),A=JSON.stringify(b.output),m=F1(b.input),y=F1(b.output),W=$.toLowerCase(),w=m.filter((X)=>W.includes(X.toLowerCase())),j=y.filter((X)=>W.includes(X.toLowerCase())),B=m.length>0?w.length/m.length:1,S=y.length>0?j.length/y.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${n.slice(0,100)}...; Output: ${A.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function F1($){let b=[];function n(A){if(typeof A==="string"&&A.length>2)b.push(A);else if(Array.isArray(A))A.forEach(n);else if(A&&typeof A==="object")Object.values(A).forEach(n)}return n($),b}function QX($,b,n){let A=$.includes(b),m=n.http?$.includes(String(n.http)):!0,y=n.when??n.description,W=y.toLowerCase().split(/\s+/).filter((Q)=>Q.length>3),w=$.toLowerCase(),j=W.filter((Q)=>w.includes(Q)),B=W.length>0?j.length/W.length:1,S=A&&(m||B>=0.3);return{name:`Error: ${b}`,type:"error",passed:S,expected:`When: ${y}; Return: ${b} (HTTP ${n.http??400})`,details:S?void 0:!A?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function ZX($,b){let n=b.sideEffects?.emits??[],A=[];for(let m of n){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;A.push({name:`Event: ${y}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${y} when: ${W}`,details:!B?`Event '${y}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return A}function XX($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let n=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],A=$.toLowerCase(),m=n.some((y)=>A.includes(y));return{name:"Idempotency",type:"scenario",passed:m,expected:"Operation should be idempotent (safe to retry)",details:m?void 0:"No idempotency pattern found for idempotent operation"}}function DA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];for(let Y of b.acceptance?.scenarios??[])y.push(BX(n,Y));for(let Y of b.acceptance?.examples??[])y.push(SX(n,Y));for(let[Y,G]of Object.entries(b.io.errors??{}))y.push(QX(n,Y,G));y.push(...ZX(n,b));let W=XX(n,b);if(W)y.push(W);let w=y.filter((Y)=>!Y.passed).map((Y)=>({severity:Y.type==="error"?"error":"warning",category:Y.type==="scenario"?"scenario":Y.type==="example"?"scenario":"error_handling",message:Y.details??`${Y.type} not covered: ${Y.name}`,location:A?{file:A}:void 0,suggestion:Y.expected?`Expected: ${Y.expected}`:void 0})),j=y.filter((Y)=>Y.type==="scenario"),B=y.filter((Y)=>Y.type==="error"),S=y.filter((Y)=>Y.passed).length,Q=y.length>0?Math.round(S/y.length*100):100,Z=w.filter((Y)=>Y.severity==="error").length===0,X=y.filter((Y)=>!Y.passed&&Y.expected).map((Y)=>`${Y.name}: ${Y.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:w,suggestions:X,coverage:{scenarios:{total:j.length,covered:j.filter((Y)=>Y.passed).length},errors:{total:B.length,handled:B.filter((Y)=>Y.passed).length},fields:{total:y.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}import{isEmitDeclRef as YX}from"@contractspec/lib.contracts-spec/operations";function GX($){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 HX($){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 qX($,b){if(HX(b))return{name:"contracts_import",passed:!0};let n=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:n,details:n?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function OX($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let A=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function VX($){let b=/:\s*any\b|as\s+any\b|<any>/,n=$.split(`
|
|
2543
|
+
`),A=[];for(let m=0;m<n.length;m++){let y=n[m]??"";if(y.trim().startsWith("//")||y.trim().startsWith("*"))continue;if(b.test(y))A.push(m+1)}return{name:"no_any_type",passed:A.length===0,details:A.length>0?`Found 'any' type on lines: ${A.slice(0,5).join(", ")}${A.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function JX($,b){let n=b.io.errors;if(!n||Object.keys(n).length===0)return{name:"error_handling",passed:!0};let A=Object.keys(n),m=[];for(let y of A)if(!$.includes(y))m.push(y);return{name:"error_handling",passed:m.length===0,details:m.length>0?`Missing error handling for: ${m.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function UX($,b){let n=b.sideEffects?.emits;if(!n||n.length===0)return{name:"event_emission",passed:!0};let A=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),m=n.map((W)=>{if(YX(W))return W.ref.key;return W.key}),y=m.filter((W)=>$.includes(W));return{name:"event_emission",passed:A&&y.length>0,details:!A?"No event emission pattern found":y.length===0?`Events not referenced: ${m.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function KX($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let n=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:n,details:n?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function _X($,b){let n=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:n,details:n?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function yn($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[GX(n),qX(n,A),OX(n,b),VX(n),JX(n,b),UX(n,b),KX(n,b),_X(n,b)],W=y.filter((X)=>!X.passed).map((X)=>({severity:X.name==="no_any_type"?"warning":"error",category:X.name.includes("import")?"import":X.name.includes("export")?"export":"type",message:X.details??`Check failed: ${X.name}`,location:A?{file:A}:void 0,suggestion:X.suggestion})),w=y.filter((X)=>X.passed).length,j=Math.round(w/y.length*100),B=W.filter((X)=>X.severity==="error").length===0,S=y.filter((X)=>!X.passed&&X.suggestion).map((X)=>X.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=y.find((X)=>X.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:j,issues:W,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:y.length,implemented:w}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}var zX={verbose:!1},LX=["structure","behavior","ai_review"];class NA{config;constructor($={}){this.config={...zX,...$}}async verify($,b,n={}){let A=Date.now(),m=new Map,y=[],W={spec:$,implementationCode:b},w=n.tiers??["structure","behavior"];for(let Z of LX){if(!w.includes(Z))continue;let X;switch(Z){case"structure":X=yn(W);break;case"behavior":X=DA(W);break;case"ai_review":if(this.config.aiApiKey)X=await mn(W,this.config);else X=TA(W);break;default:continue}if(m.set(Z,X),y.push(...X.issues),n.failFast&&!X.passed)break}let j=Array.from(m.values()),B=j.every((Z)=>Z.passed),S=j.length>0?Math.round(j.reduce((Z,X)=>Z+X.score,0)/j.length):100,Q=this.generateSummary(j,y);return{passed:B,score:S,reports:m,allIssues:y,summary:Q,duration:Date.now()-A}}verifyStructure($,b,n){return yn({spec:$,implementationCode:b,implementationPath:n})}verifyBehavior($,b,n){return DA({spec:$,implementationCode:b,implementationPath:n})}async verifyAI($,b,n){let A={spec:$,implementationCode:b,implementationPath:n};if(this.config.aiApiKey)return mn(A,this.config);return TA(A)}quickVerify($,b){return yn({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[A,m]of $.reports){if(b.push(`## ${this.formatTierName(A)}`),b.push(""),b.push(`**Status:** ${m.passed?"\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 n=Array.from($.reports.values()).flatMap((A)=>A.suggestions);if(n.length>0){b.push("## Suggestions"),b.push("");for(let A of n.slice(0,10))b.push(`- ${A}`);if(n.length>10)b.push(`- ... and ${n.length-10} more`);b.push("")}return b.join(`
|
|
2544
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let n=[],A=$.every((j)=>j.passed),m=$.length>0?Math.round($.reduce((j,B)=>j+B.score,0)/$.length):100;n.push(A?"\u2713 Verification passed":"\u2717 Verification failed"),n.push(`Score: ${m}/100`),n.push("");for(let j of $){let B=j.passed?"\u2713":"\u2717";n.push(`${B} ${j.tier}: ${j.score}/100`)}n.push("");let y=b.filter((j)=>j.severity==="error"),W=b.filter((j)=>j.severity==="warning"),w=b.filter((j)=>j.severity==="info");if(y.length>0)n.push(`Errors: ${y.length}`);if(W.length>0)n.push(`Warnings: ${W.length}`);if(w.length>0)n.push(`Info: ${w.length}`);return n.join(`
|
|
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 RX($){return new NA($)}var CX=new NA;var nB={};f(nB,{saveReleaseDraft:()=>t1,renderUpgradePrompt:()=>Yb,renderUpgradeChecklist:()=>Y1,renderPatchNotes:()=>Qy,renderMigrationGuide:()=>X1,renderMaintainerSummary:()=>Q1,renderCustomerPatchNote:()=>Z1,renderCustomerGuide:()=>Zy,prepareReleaseAuthoring:()=>i1,parseConventionalCommit:()=>gA,isConventionalCommit:()=>NX,initReleaseArtifacts:()=>e1,getHighestBumpType:()=>Hy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>o1,formatKeepAChangelog:()=>Wn,formatConventionalChangelog:()=>g1,formatChangelogJson:()=>FA,filterCommitsByScope:()=>FX,filterBumpableCommits:()=>vX,commitsToChangeEntries:()=>qy,commitToChangeEntry:()=>k1,checkReleaseArtifacts:()=>$B,buildReleaseArtifacts:()=>s1,applyVersionBump:()=>u1,analyzeVersionsFromCommits:()=>Gb,analyzeVersions:()=>Qn,DEFAULT_COMMIT_TYPE_MAP:()=>vA});import{basename as xX,dirname as IX}from"path";function Wn($){let b=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){b.push(`## [${A.version}] - ${A.date}`),b.push("");let m=A.changes.filter((Q)=>Q.type==="added"),y=A.changes.filter((Q)=>Q.type==="changed"),W=A.changes.filter((Q)=>Q.type==="deprecated"),w=A.changes.filter((Q)=>Q.type==="removed"),j=A.changes.filter((Q)=>Q.type==="fixed"),B=A.changes.filter((Q)=>Q.type==="security"),S=A.breakingChanges??A.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### \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(`
|
|
2546
|
+
`)}function g1($){let b=["# Changelog",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){let m=A.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":A.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${A.version} (${A.date}) - ${m}`),b.push("");let y={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let W of A.changes){let w=y[W.type]??"chore",j=W.path?`(${W.path})`:"",B=W.type==="breaking"?"!":"";b.push(`- **${w}${j}${B}**: ${W.description}`)}b.push("")}return b.join(`
|
|
2547
|
+
`)}function FA($,b){let n=$.analyses.filter((y)=>y.needsBump),A=new Date().toISOString(),m=A.split("T")[0]??"";return{generatedAt:A,baseline:b,specs:n.map((y)=>({key:y.specKey,version:y.suggestedVersion,path:y.specPath,entries:[{version:y.suggestedVersion,date:m,bumpType:y.bumpType,changes:y.changes,breakingChanges:y.changes.filter((W)=>W.type==="breaking")}]})),libraries:MX(n,m)}}function EX($){let b=$.split("/"),n=b.lastIndexOf("packages");if(n>=0&&n+2<b.length)return b.slice(0,n+3).join("/");return IX($)}var v1={major:3,minor:2,patch:1};function MX($,b){let n=new Map;for(let A of $){let m=EX(A.specPath),y=n.get(m);if(y)y.push(A);else n.set(m,[A])}return Array.from(n.entries()).flatMap(([A,m])=>{let y=m[0];if(!y)return[];let W=m.reduce((w,j)=>{return(v1[j.bumpType]??0)>(v1[w.bumpType]??0)?j:w},y);return[{name:xX(A),path:A,version:W.suggestedVersion,entries:[{version:W.suggestedVersion,date:b,bumpType:W.bumpType,changes:m.flatMap((w)=>w.changes),breakingChanges:m.flatMap((w)=>w.changes).filter((w)=>w.type==="breaking")}]}]})}function P1($,b){let n=(y)=>{return y.split(".").map((w)=>parseInt(w,10)||0)},A=n($),m=n(b);for(let y=0;y<3;y++){let W=A[y]??0,w=m[y]??0;if(W!==w)return w-W}return 0}var vA={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},TX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,DX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function gA($){let b=$.split(`
|
|
2548
|
+
`),n=b[0]?.trim();if(!n)return null;let A=n.match(TX);if(!A)return null;let[,m,y,W,w]=A;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2549
|
+
`).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 NX($){return gA($)!==null}function Gy($,b=vA){if($.breaking)return"major";return b[$.type]??null}function Hy($,b=vA){let n=["major","minor","patch"],A=null;for(let m of $){let y=Gy(m,b);if(!y)continue;if(!A){A=y;continue}let W=n.indexOf(A);if(n.indexOf(y)<W)A=y}return A}function k1($){if($.breaking)return{type:"breaking",description:$.breakingDescription??$.description,path:$.scope};switch($.type){case"feat":return{type:"added",description:$.description,path:$.scope};case"fix":return{type:"fixed",description:$.description,path:$.scope};case"deprecate":return{type:"deprecated",description:$.description,path:$.scope};case"remove":return{type:"removed",description:$.description,path:$.scope};case"security":return{type:"security",description:$.description,path:$.scope};default:return{type:"changed",description:$.description,path:$.scope}}}function qy($){return $.map(k1)}function FX($,b){return $.filter((n)=>n.scope?.toLowerCase()===b.toLowerCase())}function vX($,b=vA){return $.filter((n)=>Gy(n,b)!==null)}import{z as M}from"zod";import{ReleaseCapsuleSchema as r1}from"@contractspec/lib.contracts-spec";import{dump as gX,load as PX}from"js-yaml";var kX=".changeset/*.md",rX=".changeset/*.release.yaml",fX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,cX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function hX($,b){return(await $.glob({pattern:kX,cwd:b,absolute:!0})).filter((A)=>$.basename(A)!=="README.md")}async function wn($,b){let n=await hX($,b),A=[];for(let m of n){let y=await $.readFile(m);A.push(dX($.basename(m),y))}return A}async function jn($,b,n){let A=await $.glob({pattern:rX,cwd:b,absolute:!0}),m=new Map(n.map((w)=>[w.slug,w.packages])),y=new Map,W=[];for(let w of A){let j=$.basename(w).replace(/\.release\.yaml$/,"");try{let B=PX(await $.readFile(w)),S=uX(B,j,m.get(j)??[]);y.set(j,S)}catch(B){W.push(oX(w,j,B))}}return{capsules:y,issues:W}}async function Bn($,b){let n=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),A=[];for(let m of n){let y=JSON.parse(await $.readFile(m));if(!y.name||!y.version||y.private===!0)continue;let W=$.relative(b,$.dirname(m))||".";A.push({name:y.name,dir:W,version:y.version})}return A.sort((m,y)=>m.dir.localeCompare(y.dir))}function PA($,b){let n=new Set;for(let A of $){let m=b.find((y)=>y.dir==="."?!A.startsWith("packages/"):A===y.dir||A.startsWith(`${y.dir}/`));if(m)n.add(m.name)}return Array.from(n).sort((A,m)=>A.localeCompare(m))}function kA($,b){return`---
|
|
2550
|
+
${b.map((A)=>`"${A.name}": ${A.releaseType}`).join(`
|
|
2456
2551
|
`)}
|
|
2457
2552
|
---
|
|
2458
2553
|
|
|
2459
2554
|
${$}
|
|
2460
|
-
`}function
|
|
2461
|
-
`)}function
|
|
2462
|
-
`)){let
|
|
2463
|
-
`)}function
|
|
2464
|
-
"${B}": ${
|
|
2555
|
+
`}function rA($){return gX(r1.parse($),{noRefs:!0,lineWidth:100})}function Sn($){return $.map((b)=>{let n=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",A=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${n} ${b.message}.${A}`.trim()}).join(`
|
|
2556
|
+
`)}function dX($,b){let n=$.replace(/\.md$/,""),A=b.match(fX);if(!A)return{slug:n,summary:b.trim(),packages:[]};let m=A[1]??"",y=(A[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2557
|
+
`)){let j=w.trim().match(cX);if(!j)continue;let B=j[1],S=j[2];if(!B||S==="none")continue;W.push({name:B,releaseType:S})}return{slug:n,summary:y,packages:W}}function uX($,b,n){let A=typeof $==="object"&&$!==null?$:{},m=Array.isArray(A.packageNames)?A.packageNames.filter((y)=>typeof y==="string").map((y)=>({name:y,releaseType:A.releaseType??"patch"})):[];return r1.parse({...A,slug:b,packages:Array.isArray(A.packages)&&A.packages.length>0?A.packages:m.length>0?m:n})}function oX($,b,n){let A=typeof n==="object"&&n!==null?n:null,m=Array.isArray(A?.issues)?A.issues.map((W)=>W.message).filter((W)=>typeof W==="string"):[],y=m.length>0?`Release capsule validation failed: ${m.join("; ")}`:typeof A?.reason==="string"?`Release capsule YAML parse failed: ${A.reason}`:`Release capsule parse failed: ${n instanceof Error?n.message:String(n)}`;return{slug:b,filePath:$,message:y,line:typeof A?.mark?.line==="number"?A.mark.line+1:void 0,column:typeof A?.mark?.column==="number"?A.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as d1,determineBumpType as iX}from"@contractspec/lib.contracts-spec";async function Qn($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting version analysis...",{baseline:b.baseline});let W=b.pattern??"**/*.{operation,event,presentation}.ts",j=(await n.glob({pattern:W,cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${j.length} spec files`);let B=[],S=0,Q=0;for(let X of j)try{let Y=await n.readFile(X),G=fA(Y);if(!G)continue;let V=null;if(b.baseline)try{V=await A.showFile(b.baseline,X)}catch{V=null}let O=tX(Y,V),K=O.some((_)=>_.type==="breaking"),J=O.length>0&&!K,U=O.length>0;if(K)S++;if(J)Q++;let H=iX(K,J),q=U?d1(G.version,H):G.version;B.push({specPath:X,specKey:G.key,currentVersion:G.version,suggestedVersion:q,bumpType:H,changes:O,hasBreaking:K,needsBump:U})}catch(Y){m.warn(`Failed to analyze ${X}:`,{error:Y instanceof Error?Y.message:String(Y)})}let Z=B.filter((X)=>X.needsBump).length;return m.info("Version analysis complete",{totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q}),{analyses:B,totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q,baseline:b.baseline}}async function Gb($,b={}){let{git:n,logger:A}=$,m=b.baseline??"HEAD~10";A.info("Analyzing commits for version bump...",{baseline:m});try{let y=await n.log(m),W=[],w=[];for(let Q of y){let Z=gA(Q.message);if(Z)W.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),w.push(Z)}let j=Hy(w),B=qy(w),S=W.filter((Q)=>Q.breaking).length;return A.info("Commit analysis complete",{totalCommits:W.length,breakingCommits:S,suggestedBumpType:j}),{suggestedBumpType:j,commits:W,changes:B,totalCommits:W.length,breakingCommits:S}}catch(y){return A.warn("Failed to analyze commits",{error:y instanceof Error?y.message:String(y)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function u1($,b){let{fs:n,logger:A}=$,{specPath:m,dryRun:y=!1,config:W}=b;A.info("Applying version bump...",{specPath:m,bumpType:b.bumpType});try{let w=await n.readFile(m),j=fA(w);if(!j)return{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:c1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=d1(j.version,B),Q=b.changes??[];if(b.changeDescription)Q.push({type:B==="major"?"breaking":"changed",description:b.changeDescription});let Z={version:S,date:new Date().toISOString().split("T")[0]??"",bumpType:B,changes:Q,breakingChanges:Q.filter((X)=>X.type==="breaking")};if(!y){let X=pX(w,j.version,S);await n.writeFile(m,X)}if(A.info("Version bump applied",{specPath:m,previousVersion:j.version,newVersion:S}),W?.integrateWithChangesets)await sX($,{specPath:m,bumpType:B,summary:b.changeDescription??`Bump ${j.key} to ${S}`,dryRun:y});return{success:!0,specPath:m,specKey:j.key,previousVersion:j.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(w){let j=w instanceof Error?w.message:String(w);return A.error("Version bump failed",{specPath:m,error:j}),{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:c1(),error:j}}}async function o1($,b={}){let{logger:n}=$,A=b.tiers??["spec","library","monorepo"],m=b.format??"keep-a-changelog";n.info("Generating changelogs...",{tiers:A,format:m});let y=await Qn($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),W=[],w=new Map,j="",B=0;if(A.includes("spec"))for(let Q of y.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:aX(Q),kind:"changelog",specKey:Q.specKey,specVersion:Q.suggestedVersion,entries:[{version:Q.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:Q.bumpType,changes:Q.changes,breakingChanges:Q.changes.filter((X)=>X.type==="breaking")}]};W.push(Z),B++}if(A.includes("library")){let Q=eX(y.analyses);for(let[Z,X]of Q){let Y=X.filter((G)=>G.needsBump);if(Y.length>0)w.set(Z,Wn(Y.map(h1))),B+=Y.length}}if(A.includes("monorepo")){let Q=y.analyses.filter((Z)=>Z.needsBump).map(h1);j=Wn(Q)}let S=FA(y,b.baseline);return n.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:W,libraryMarkdown:w,monorepoMarkdown:j,json:S,totalEntries:B}}function fA($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),n=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!n)return null;let A=b[1],m=n[1];if(!A||!m)return null;return{key:A,version:m}}function tX($,b){let n=[];if(!b)return n.push({type:"added",description:"New spec added"}),n;let A=fA($),m=fA(b);if(!A||!m)return n;if(A.version!==m.version)n.push({type:"changed",description:`Version updated from ${m.version} to ${A.version}`,path:"meta.version"});let y=lX($,b);if(y.breaking)n.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(y.nonBreaking)n.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return n}function lX($,b){let n=/io:\s*\{[\s\S]*?\}/,A=$.match(n)?.[0]??"",m=b.match(n)?.[0]??"";if(A===m)return{breaking:!1,nonBreaking:!1};let y=f1(A),W=f1(m),w=W.filter((B)=>!y.includes(B)),j=y.filter((B)=>!W.includes(B));return{breaking:w.length>0,nonBreaking:j.length>0&&w.length===0}}function f1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((A)=>A[1]).filter((A)=>!!A)}function pX($,b,n){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${n}'`)}function c1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function aX($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],n=$.changes.filter((y)=>y.type==="breaking"),A=$.changes.filter((y)=>y.type==="changed"),m=$.changes.filter((y)=>y.type==="added");if(n.length>0)b.push("### Breaking Changes"),n.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(m.length>0)b.push("### Added"),m.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(A.length>0)b.push("### Changed"),A.forEach((y)=>b.push(`- ${y.description}`)),b.push("");return b.join(`
|
|
2558
|
+
`)}function eX($){let b=new Map;for(let n of $){let y=n.specPath.match(/(.+?\/src\/)/)?.[1]??n.specPath,W=b.get(y)??[];W.push(n),b.set(y,W)}return b}function h1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function sX($,b){let{fs:n,logger:A}=$,{specPath:m,bumpType:y,summary:W,dryRun:w}=b;try{let j=c(m),B=g$(j);if(!B){A.warn("Could not determine package name for changeset",{specPath:m});return}let S=j,Q=null;while(!0){let G=n.join(S,".changeset");if(await n.exists(G)){Q=G;break}let V=n.dirname(S);if(V===S)break;S=V}if(!Q){A.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${$Y()}.md`,X=n.join(Q,Z),Y=`---
|
|
2559
|
+
"${B}": ${y}
|
|
2465
2560
|
---
|
|
2466
2561
|
|
|
2467
|
-
${
|
|
2468
|
-
`;if(!j)await A.writeFile(G,X),m.info("Generated changeset",{filePath:G});else m.info("Would generate changeset",{filePath:G,content:X})}catch(y){m.error("Failed to generate changeset",{error:y instanceof Error?y.message:String(y)})}}function b2(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],A=["run","fly","hop","eat","nap","cry","sing"],m=$[Math.floor(Math.random()*$.length)],n=b[Math.floor(Math.random()*b.length)],W=A[Math.floor(Math.random()*A.length)],w=Math.floor(Math.random()*1000);return`${m}-${n}-${W}-${w}`}var A2=T.object({summary:T.string(),maintainerSummary:T.string(),customerSummary:T.string(),integratorSummary:T.string(),deprecations:T.array(T.string()).default([]),migrationInstructions:T.array(T.object({id:T.string(),title:T.string(),summary:T.string(),required:T.boolean().default(!1),when:T.string().optional(),steps:T.array(T.string()).default([])})).default([]),upgradeSteps:T.array(T.object({id:T.string(),title:T.string(),summary:T.string(),level:T.enum(["auto","assisted","manual"]).default("manual"),instructions:T.array(T.string()).default([])})).default([]),validationCommands:T.array(T.string()).default([]),validationEvidence:T.array(T.string()).default([])});async function q1($,b={}){let{fs:A,git:m,logger:n,ai:W}=$,w=M(b.workspaceRoot),j=await $A(A,w),y=b.baseline?await m.diffFiles(b.baseline):[],B=await eb(A,w),S=await sb(A,w,B),Q=b.packages&&b.packages.length>0?b.packages:L0(y,j),Z=b.baseline?await Bb($,{baseline:b.baseline,workspaceRoot:w}):null,G=b.baseline?await V$($,{baseline:b.baseline,workspaceRoot:w}):null,X=b.slug??j2(B,S.capsules,Q),Y=X?A.join(w,".changeset",`${X}.md`):void 0,V=X?A.join(w,".changeset",`${X}.release.yaml`):void 0,O=X?B.find((q)=>q.slug===X):void 0,K=X?S.capsules.get(X):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((G?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??y2(Q)),_=(Y?await A.exists(Y):!1)||(V?await A.exists(V):!1),H=await n2(W,m2({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:j,isBreaking:J==="major"||(G?.summary.breaking??0)>0,selectedSlug:X}),{changedFiles:y,commitMessages:b.baseline?(await m.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},n);return{workspaceRoot:w,source:_?"existing":"created",changesetPath:Y??A.join(w,".changeset",`${H.slug}.md`),capsulePath:V??A.join(w,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${bA(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:W!==void 0}}async function O1($,b){let{fs:A}=$,m=M(b.workspaceRoot),n=mA(b.draft),W=A.join(m,".changeset",`${n.slug}.md`),w=A.join(m,".changeset",`${n.slug}.release.yaml`),j=await A.exists(W)||await A.exists(w)?"updated":"created",y=R0(n.summary,n.packages),B=C0(w2(n));return await A.writeFile(W,y),await A.writeFile(w,B),{source:j,changesetPath:W,capsulePath:w,changesetContent:y,capsuleContent:B}}function m2($){if($.existingCapsule)return mA({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((m)=>({...m,version:$.workspacePackages.find((n)=>n.name===m.name)?.version??m.version})):$.packageNames.map((m)=>({name:m,releaseType:$.releaseType,version:$.workspacePackages.find((n)=>n.name===m)?.version})),A=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return mA({slug:$.selectedSlug??B2(A),summary:A,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:V1(A),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function n2($,b,A,m){if(!$)return b;try{let n=await $.generateStructured({schema:A2,systemPrompt:"You write structured release metadata for a TypeScript monorepo. Be concise, concrete, and safe for public release notes.",prompt:JSON.stringify({draft:b,changedFiles:A.changedFiles.slice(0,40),commitMessages:A.commitMessages.slice(0,20),parseIssues:A.parseIssues})});return W2(b,n.object)}catch(n){return m.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:n instanceof Error?n.message:String(n)}),b}}function W2($,b){let A=[...$.audiences];return tn(A,"maintainer",b.maintainerSummary),tn(A,"customer",b.customerSummary),tn(A,"integrator",b.integratorSummary),mA({...$,summary:J1($.summary)?b.summary:$.summary,audiences:A,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function mA($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:V1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function w2($){let{releaseType:b,...A}=mA($);return{schemaVersion:"1",...A}}function V1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function tn($,b,A){let m=$.find((n)=>n.kind===b);if(m&&!J1(m.summary))return;if(m){m.summary=A;return}$.push({kind:b,summary:A})}function j2($,b,A){let m=new Set([...$.map((W)=>W.slug),...b.keys()].filter((W)=>W!=="auto-dependent-bumps"));if(m.size===1)return Array.from(m)[0];if(A.length===0)return;let n=Array.from(m).filter((W)=>{let w=b.get(W),j=$.find((B)=>B.slug===W);return(w?.packages.map((B)=>B.name)??j?.packages.map((B)=>B.name)??[]).some((B)=>A.includes(B))});return n.length===1?n[0]:void 0}function y2($){return $.length>0?"minor":"patch"}function J1($){return $.trim().startsWith("Describe the ")}function B2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as S2}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as Q2,DEFAULT_CONTRACTSRC as Z2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var K1="generated/releases",E0=Z2.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function _1($,b={}){let{fs:A,git:m,logger:n}=$,W=M(b.workspaceRoot),w=await $A(A,W),j=b.baseline?await m.diffFiles(b.baseline):[],y=b.packages&&b.packages.length>0?b.packages:L0(j,w),B=b.baseline?await Bb($,{baseline:b.baseline,workspaceRoot:W}):null,S=b.baseline?await V$($,{baseline:b.baseline,workspaceRoot:W}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??G2(y),Z=b.releaseType??Q,G=b.summary??`Describe the ${Z} release for ${y[0]??"the workspace"}`,X=b.slug??Y2(G),Y=y.map((H)=>({name:H,releaseType:Z,version:w.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:X,summary:G,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:Y,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:G},{kind:"customer",summary:G}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=A.join(W,".changeset",`${X}.md`),K=A.join(W,".changeset",`${X}.release.yaml`);if(!b.force){if(await A.exists(O))throw Error(`Changeset already exists: ${O}`);if(await A.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=R0(G,Y),_=C0(V);if(!b.dryRun)await A.writeFile(O,J),await A.writeFile(K,_);return n.info("Initialized release artifacts",{slug:X,workspaceRoot:W}),{slug:X,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:_,packages:Y,releaseType:Z,isBreaking:V.isBreaking}}async function U1($,b={}){let{fs:A,logger:m}=$,n=M(b.workspaceRoot),W=await L1(A,n),w=A.join(n,b.outputDir??K1),j=await eb(A,n),y=await sb(A,n,j);if(y.issues.length>0)throw Error(bA(y.issues));let B=y.capsules,S=await $A(A,n),Q=await Promise.all(Array.from(B.entries()).map(async([_,H])=>{let q=A.join(n,".changeset",`${_}.release.yaml`),U=await A.stat(q);return{slug:_,version:X2(H,S),summary:H.summary,date:U.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:H.isBreaking,packages:H.packages.map((z)=>({...z,version:S.find((L)=>L.name===z.name)?.version??z.version})),affectedRuntimes:[...H.affectedRuntimes],affectedFrameworks:[...H.affectedFrameworks],audiences:[...H.audiences],deprecations:[...H.deprecations],migrationInstructions:[...H.migrationInstructions],upgradeSteps:[...H.upgradeSteps],validation:H.validation}})),Z=S2.parse({generatedAt:new Date().toISOString(),releases:Q}),G=b.agentTargets??W.agentTargets??["codex"],X=lb(Z,[],G,yb),Y=A.join(w,"manifest.json"),V=A.join(w,"upgrade-manifest.json"),O=A.join(w,"patch-notes.md"),K=A.join(w,"customer-guide.md"),J=Object.fromEntries(X.agentPrompts.map((_)=>[_.agent,A.join(w,"prompts",`${_.agent}.md`)]));if(!b.dryRun){await A.writeFile(Y,JSON.stringify(Z,null,2)),await A.writeFile(V,JSON.stringify(Z,null,2)),await A.writeFile(O,fn(Z)),await A.writeFile(K,hn(Z));for(let _ of X.agentPrompts)await A.writeFile(J[_.agent]??"",_.prompt)}return m.info("Built release artifacts",{outputDir:w,releasesBuilt:Z.releases.length}),{outputDir:w,manifestPath:Y,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:X,releasesBuilt:Z.releases.length}}async function z1($,b={}){let{fs:A}=$,m=M(b.workspaceRoot),n=await L1(A,m),W=A.join(m,b.outputDir??K1),w=[],j=[],y=[],B=await eb(A,m),S=await sb(A,m,B),Q=S.capsules,Z=B.length>0,G=!Z&&Q.size>0;y.push(...S.issues.map((X)=>bA([X]))),Sb(w,Z||G,"changesets",Z?`Found ${B.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let X of B)if(!Q.has(X.slug)&&n.requireReleaseCapsule)y.push(`Missing release capsule for changeset ${X.slug}.`);for(let[X,Y]of Q){if(Y.isBreaking&&Y.migrationInstructions.length===0)y.push(`Breaking release ${X} is missing migration instructions.`);if(Y.validation.commands.length===0)y.push(`Release capsule ${X} is missing validation commands.`);if(Y.validation.evidence.length===0)y.push(`Release capsule ${X} is missing validation evidence.`)}if(b.baseline){try{let X=await V$($,{baseline:b.baseline,workspaceRoot:m});if(Sb(w,!0,"impact",`Impact status: ${X.status}`),X.summary.breaking>0&&!Array.from(Q.values()).some((Y)=>Y.isBreaking))y.push("Breaking impact detected without a breaking release capsule.")}catch(X){Sb(w,!1,"impact",M0(X)),y.push(`Impact detection failed: ${M0(X)}`)}try{let X=await AA($,{baseline:b.baseline,workspaceRoot:m});Sb(w,!0,"versioning",`${X.specsNeedingBump} spec(s) need version review.`)}catch(X){Sb(w,!1,"versioning",M0(X)),y.push(`Version analysis failed: ${M0(X)}`)}}if(b.strict)for(let X of n.publishArtifacts??[]){let Y=A.join(W,X);if(!await A.exists(Y))y.push(`Missing generated release artifact: ${Y}`)}if(Sb(w,y.length===0,"capsules",y.length===0?"All release capsules are complete.":y[0]??""),!Z&&!G)j.push("No pending release changesets were found.");return{success:y.length===0,errors:y,warnings:j,checks:w}}async function L1($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return E0;try{let m=JSON.parse(await $.readFile(A)),n=Q2.safeParse(m);return n.success?{...E0,...n.data.release}:E0}catch{return E0}}function G2($){return $.length>0?"minor":"patch"}function X2($,b){return $.packages.map((m)=>b.find((n)=>n.name===m.name)?.version??m.version).find((m)=>typeof m==="string")??"0.0.0"}function Y2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Sb($,b,A,m){$.push({name:A,ok:b,message:m})}function M0($){return $ instanceof Error?$.message:String($)}var g1={};P(g1,{silentLogger:()=>E1,runWorkflow:()=>M1,loadWorkflows:()=>en,loadVibeConfig:()=>T0,installPack:()=>v1,getWorkflow:()=>T1,exportContext:()=>I1,consoleLogger:()=>an,builtinWorkflows:()=>D0,DEFAULT_VIBE_CONFIG:()=>x0});import{existsSync as H2}from"fs";import{readFile as q2}from"fs/promises";import{join as pn}from"path";import O2 from"js-yaml";var x0={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function T0($){let b=$??process.cwd(),A=M(b)??b,m=[pn(A,".contractspec","vibe","config.json"),pn(A,".contractspec","vibe","config.yaml"),pn(A,".contractspec","vibe","config.yml")],n={};for(let W of m)if(H2(W))try{let w=await q2(W,"utf-8");if(W.endsWith(".json"))n=JSON.parse(w);else n=O2.load(w);break}catch(w){console.warn(`Warning: Failed to parse ${W}`,w)}return{...x0,...n}}import{existsSync as V2}from"fs";import{copyFile as J2,mkdir as C1,readFile as K2,writeFile as _2}from"fs/promises";import{dirname as U2,join as Qb}from"path";import{glob as z2}from"glob";var L2=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function I1($){let b=$??process.cwd(),A=M(b)??b,m=await T0(b),n=Qb(A,".contractspec","context"),W=Qb(n,"files"),w=[...L2],j=Qb(A,".gitignore");if(V2(j)){let Y=(await K2(j,"utf-8")).split(`
|
|
2469
|
-
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));
|
|
2562
|
+
${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 $Y(){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 bY=M.object({summary:M.string(),maintainerSummary:M.string(),customerSummary:M.string(),integratorSummary:M.string(),deprecations:M.array(M.string()).default([]),migrationInstructions:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),required:M.boolean().default(!1),when:M.string().optional(),steps:M.array(M.string()).default([])})).default([]),upgradeSteps:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),level:M.enum(["auto","assisted","manual"]).default("manual"),instructions:M.array(M.string()).default([])})).default([]),validationCommands:M.array(M.string()).default([]),validationEvidence:M.array(M.string()).default([])});async function i1($,b={}){let{fs:n,git:A,logger:m,ai:y}=$,W=I(b.workspaceRoot),w=await Bn(n,W),j=b.baseline?await A.diffFiles(b.baseline):[],B=await wn(n,W),S=await jn(n,W,B),Q=b.packages&&b.packages.length>0?b.packages:PA(j,w),Z=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??WY(B,S.capsules,Q),G=Y?n.join(W,".changeset",`${Y}.md`):void 0,V=Y?n.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((q)=>q.slug===Y):void 0,K=Y?S.capsules.get(Y):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??wY(Q)),U=(G?await n.exists(G):!1)||(V?await n.exists(V):!1),H=await AY(y,nY({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:w,isBreaking:J==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await A.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},m);return{workspaceRoot:W,source:U?"existing":"created",changesetPath:G??n.join(W,".changeset",`${H.slug}.md`),capsulePath:V??n.join(W,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${Sn(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:n}=$,A=I(b.workspaceRoot),m=Zn(b.draft),y=n.join(A,".changeset",`${m.slug}.md`),W=n.join(A,".changeset",`${m.slug}.release.yaml`),w=await n.exists(y)||await n.exists(W)?"updated":"created",j=kA(m.summary,m.packages),B=rA(yY(m));return await n.writeFile(y,j),await n.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function nY($){if($.existingCapsule)return Zn({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((A)=>({...A,version:$.workspacePackages.find((m)=>m.name===A.name)?.version??A.version})):$.packageNames.map((A)=>({name:A,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===A)?.version})),n=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return Zn({slug:$.selectedSlug??jY(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 AY($,b,n,A){if(!$)return b;try{let m=await $.generateStructured({schema:bY,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 mY(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 mY($,b){let n=[...$.audiences];return Oy(n,"maintainer",b.maintainerSummary),Oy(n,"customer",b.customerSummary),Oy(n,"integrator",b.integratorSummary),Zn({...$,summary:p1($.summary)?b.summary:$.summary,audiences:n,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function Zn($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:l1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function yY($){let{releaseType:b,...n}=Zn($);return{schemaVersion:"1",...n}}function l1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Oy($,b,n){let A=$.find((m)=>m.kind===b);if(A&&!p1(A.summary))return;if(A){A.summary=n;return}$.push({kind:b,summary:n})}function WY($,b,n){let A=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(A.size===1)return Array.from(A)[0];if(n.length===0)return;let m=Array.from(A).filter((y)=>{let W=b.get(y),w=$.find((B)=>B.slug===y);return(W?.packages.map((B)=>B.name)??w?.packages.map((B)=>B.name)??[]).some((B)=>n.includes(B))});return m.length===1?m[0]:void 0}function wY($){return $.length>0?"minor":"patch"}function p1($){return $.trim().startsWith("Describe the ")}function jY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as BY}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as SY,DEFAULT_CONTRACTSRC as QY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var a1="generated/releases",cA=QY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function e1($,b={}){let{fs:n,git:A,logger:m}=$,y=I(b.workspaceRoot),W=await Bn(n,y),w=b.baseline?await A.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:PA(w,W),B=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:y}):null,S=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:y}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??ZY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??YY(X),G=j.map((H)=>({name:H,releaseType:Z,version:W.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:G,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:X},{kind:"customer",summary:X}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=n.join(y,".changeset",`${Y}.md`),K=n.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await n.exists(O))throw Error(`Changeset already exists: ${O}`);if(await n.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=kA(X,G),U=rA(V);if(!b.dryRun)await n.writeFile(O,J),await n.writeFile(K,U);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:U,packages:G,releaseType:Z,isBreaking:V.isBreaking}}async function s1($,b={}){let{fs:n,logger:A}=$,m=I(b.workspaceRoot),y=await bB(n,m),W=n.join(m,b.outputDir??a1),w=await wn(n,m),j=await jn(n,m,w);if(j.issues.length>0)throw Error(Sn(j.issues));let B=j.capsules,S=await Bn(n,m),Q=await Promise.all(Array.from(B.entries()).map(async([U,H])=>{let q=n.join(m,".changeset",`${U}.release.yaml`),_=await n.stat(q);return{slug:U,version:XY(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=BY.parse({generatedAt:new Date().toISOString(),releases:Q}),X=b.agentTargets??y.agentTargets??["codex"],Y=An(Z,[],X,Yb),G=n.join(W,"manifest.json"),V=n.join(W,"upgrade-manifest.json"),O=n.join(W,"patch-notes.md"),K=n.join(W,"customer-guide.md"),J=Object.fromEntries(Y.agentPrompts.map((U)=>[U.agent,n.join(W,"prompts",`${U.agent}.md`)]));if(!b.dryRun){await n.writeFile(G,JSON.stringify(Z,null,2)),await n.writeFile(V,JSON.stringify(Z,null,2)),await n.writeFile(O,Qy(Z)),await n.writeFile(K,Zy(Z));for(let U of Y.agentPrompts)await n.writeFile(J[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:W,releasesBuilt:Z.releases.length}),{outputDir:W,manifestPath:G,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:Y,releasesBuilt:Z.releases.length}}async function $B($,b={}){let{fs:n}=$,A=I(b.workspaceRoot),m=await bB(n,A),y=n.join(A,b.outputDir??a1),W=[],w=[],j=[],B=await wn(n,A),S=await jn(n,A,B),Q=S.capsules,Z=B.length>0,X=!Z&&Q.size>0;j.push(...S.issues.map((Y)=>Sn([Y]))),Hb(W,Z||X,"changesets",Z?`Found ${B.length} release changeset(s).`:X?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let Y of B)if(!Q.has(Y.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${Y.slug}.`);for(let[Y,G]of Q){if(G.isBreaking&&G.migrationInstructions.length===0)j.push(`Breaking release ${Y} is missing migration instructions.`);if(G.validation.commands.length===0)j.push(`Release capsule ${Y} is missing validation commands.`);if(G.validation.evidence.length===0)j.push(`Release capsule ${Y} is missing validation evidence.`)}if(b.baseline){try{let Y=await K$($,{baseline:b.baseline,workspaceRoot:A});if(Hb(W,!0,"impact",`Impact status: ${Y.status}`),Y.summary.breaking>0&&!Array.from(Q.values()).some((G)=>G.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(Y){Hb(W,!1,"impact",hA(Y)),j.push(`Impact detection failed: ${hA(Y)}`)}try{let Y=await Qn($,{baseline:b.baseline,workspaceRoot:A});Hb(W,!0,"versioning",`${Y.specsNeedingBump} spec(s) need version review.`)}catch(Y){Hb(W,!1,"versioning",hA(Y)),j.push(`Version analysis failed: ${hA(Y)}`)}}if(b.strict)for(let Y of m.publishArtifacts??[]){let G=n.join(y,Y);if(!await n.exists(G))j.push(`Missing generated release artifact: ${G}`)}if(Hb(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!Z&&!X)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function bB($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return cA;try{let A=JSON.parse(await $.readFile(n)),m=SY.safeParse(A);return m.success?{...cA,...m.data.release}:cA}catch{return cA}}function ZY($){return $.length>0?"minor":"patch"}function XY($,b){return $.packages.map((A)=>b.find((m)=>m.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function YY($){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 GY}from"fs";import{readFile as HY}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(GY(y))try{let W=await HY(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 OY}from"fs";import{copyFile as VY,mkdir as AB,readFile as JY,writeFile as UY}from"fs/promises";import{dirname as KY,join as qb}from"path";import{glob as _Y}from"glob";var zY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function mB($){let b=$??process.cwd(),n=I(b)??b,A=await uA(b),m=qb(n,".contractspec","context"),y=qb(m,"files"),W=[...zY],w=qb(n,".gitignore");if(OY(w)){let G=(await JY(w,"utf-8")).split(`
|
|
2564
|
+
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));W=[...W,...G]}let j=A.contextExportAllowlist.length>0?A.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let Y of j){let G=await _Y(Y,{cwd:n,ignore:W,nodir:!0,dot:!0});B.push(...G)}let S=Array.from(new Set(B)).sort();if(S.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await AB(y,{recursive:!0});let Q=[];for(let Y of S){let G=qb(n,Y),V=qb(y,Y);await AB(KY(V),{recursive:!0}),await VY(G,V),Q.push({path:Y,size:0})}let Z=qb(m,"index.json"),X={generatedAt:new Date().toISOString(),files:Q.map((Y)=>Y.path),config:{allowlist:A.contextExportAllowlist,ignores:W.length}};return await UY(Z,JSON.stringify(X,null,2)),{success:!0,files:S,indexPath:Z}}var oA=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and generate artifacts.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
|
|
2470
2565
|
Please review them and move selected files to contracts/ directory.
|
|
2471
|
-
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"release",label:"Prepare Release",command:"contractspec release prepare"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as
|
|
2472
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2473
|
-
`);let
|
|
2474
|
-
\uD83D\uDC49 Step: ${
|
|
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 LY}from"child_process";var yB={log:()=>{},warn:()=>{},error:()=>{}},Jy={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function WB($,b,n){let A=n?.logger??Jy,m=n?.prompter;if(A.log(`
|
|
2567
|
+
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${b.track}`),b.dryRun)A.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
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(A.log(`
|
|
2569
|
+
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)A.log(` Command: ${W.command}`);if(W.manualCheckpoint){if(b.dryRun)A.warn(" [Manual Checkpoint] Would pause here for user input.");else if(m){if(W.manualMessage)A.log(W.manualMessage);let j=await m.select({message:"Checkpoint action:",choices:[{name:"Proceed",value:"proceed",description:"Run this step"},{name:"Skip Step",value:"skip",description:"Skip this step and continue"},{name:"Abort Workflow",value:"abort",description:"Exit workflow"}]});if(j==="abort")return A.warn("Workflow aborted by user."),y.success=!1,y.steps.push({...w,status:"skip",error:"Aborted by user"}),y;if(j==="skip"){A.warn(" \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 RY(W.command,b.root);w.status="pass",y.stepsExecuted.push(W.id),y.steps.push(w),A.log(" \u2713 Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return A.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 RY($,b){let n=$.split(" "),A=n[0],m=n.slice(1);if(!A)throw Error("Invalid command");return new Promise((y,W)=>{let w=LY(A,m,{cwd:b,stdio:"inherit",shell:!0});w.on("error",W),w.on("exit",(j)=>{if(j===0)y();else W(Error(`Command exited with code ${j}`))})})}import{existsSync as CY}from"fs";import{readdir as xY,readFile as IY}from"fs/promises";import{join as wB}from"path";import EY from"js-yaml";async function Uy($){let b=[...oA],n=$??process.cwd(),A=I(n)??n,m=wB(A,".contractspec","vibe","workflows");if(CY(m))try{let y=await xY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await IY(wB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=EY.load(w);if(j.id&&j.steps)b.push(j)}catch(j){console.warn(`Failed to parse workflow ${W}:`,j)}}}catch(y){console.warn("Error loading user workflows:",y)}return b}async function jB($,b){return(await Uy(b)).find((A)=>A.id===$)}import{existsSync as Ky}from"fs";import{copyFile as BB,mkdir as SB,readdir as QB,stat as MY}from"fs/promises";import{join as N$,resolve as TY}from"path";async function ZB($,b){let n=b??process.cwd(),A=I(n)??n;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let m=TY(n,$);if(!Ky(m))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${m}`};let y=0,W=0,w=N$(m,"workflows");if(Ky(w)){let B=N$(A,".contractspec","vibe","workflows");await SB(B,{recursive:!0});let S=await QB(w);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await BB(N$(w,Q),N$(B,Q)),y++}let j=N$(m,"templates");if(Ky(j)){let B=N$(A,".contractspec","vibe","templates");await SB(B,{recursive:!0});let S=await QB(j);for(let Q of S){let Z=N$(j,Q),X=N$(B,Q);if((await MY(Z)).isFile())await BB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as DY}from"@contractspec/module.workspace";var YB=["product","eng","qa"];function NY($){return YB.includes($)}async function DM($,b){if(!NY(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${YB.join(", ")}`);let n,A,m;if(b.specFiles&&b.specFiles.length>0)n=b.specFiles;else{let W=await FY($,{baseline:b.baseline});if(A=W.totalSpecs,m=W.changedFilesCount,b.baseline){if(W.changedFilesCount===0)return{views:[],totalSpecs:A,changedFilesCount:0,status:"no_changes"};if(W.specFiles.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_changed_specs"}}n=W.specFiles}if(n.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_specs"};let y=[];for(let W of n){let w=await vY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:A,changedFilesCount:m,status:"success"}}async function FY($,b={}){let A=(await j$({fs:$.fs})).map((w)=>w.filePath),m=A.length;if(!b.baseline)return{specFiles:A,totalSpecs:m};let y=await $.git.diffFiles(b.baseline);if(y.length===0)return{specFiles:[],totalSpecs:m,changedFilesCount:0,hasChanges:!1};let W=A.filter((w)=>y.some((j)=>w.endsWith(j)||j.endsWith(w)||w.includes(j)||j.includes(w)));return{specFiles:W,totalSpecs:m,changedFilesCount:y.length,hasChanges:W.length>0}}async function vY($,b,n){if(!await n.fs.exists($))throw Error(`File not found: ${$}`);let A=await DY($);if(A.length===0)return`No specs found in ${$} (Parse result empty)`;return A.map((m)=>gY(m,b)).join(`
|
|
2475
2570
|
|
|
2476
2571
|
---
|
|
2477
2572
|
|
|
2478
|
-
`)}function
|
|
2479
|
-
`)}function
|
|
2573
|
+
`)}function gY($,b){let n=[];switch(b){case"product":PY($,n);break;case"eng":kY($,n);break;case"qa":rY($,n);break}return n.join(`
|
|
2574
|
+
`)}function PY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2480
2575
|
${$.meta.goal}
|
|
2481
2576
|
`);if($.meta.context)b.push(`### Context
|
|
2482
2577
|
${$.meta.context}
|
|
2483
|
-
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((
|
|
2484
|
-
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((
|
|
2485
|
-
`)}export{
|
|
2578
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- \u2705 Enforces Business Policies");if($.hasIo)b.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((n)=>b.push(`- **${n.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function kY($,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((n)=>b.push(`- \`${n.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function rY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2579
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((n)=>b.push(`- \uD83E\uDDEA \`${n.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((n)=>b.push(`- [ ] Verify event \`${n.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((n)=>b.push(`- [ ] Test Operation flow: \`${n.name}\``));if($.presentations?.length)$.presentations.forEach((n)=>b.push(`- [ ] Test UI Component: \`${n.name}\``))}}function gM($,b,n,A){let{watcher:m,fs:y,logger:W}=$,w=m.watch(n),j=A?.validate??(async(S)=>{await l$(S,{fs:y,logger:W})}),B=A?.build??(async(S)=>{await yb(S,{fs:y,logger:W},b)});return w.on(async(S)=>{if(S.type!=="change")return;if(W.info("watchSpecs.changed",{path:S.path}),n.runValidate)await j(S.path);if(n.runBuild)if(n.dryRun)W.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),w}async function rM($,b,n={}){let A=(n.getWorkspaceInfo??cy)(b),m=$.join(A.workspaceRoot,".contractsrc.json"),y=$.join(A.packageRoot,".contractsrc.json"),W=await $.exists(m),w=A.workspaceRoot!==A.packageRoot?await $.exists(y):!1,j;if(W)try{let B=await $.readFile(m),S=JSON.parse(B);if(S.packages||S.excludePackages||S.recursive)j={packages:S.packages,excludePackages:S.excludePackages,recursive:S.recursive}}catch{}return{...A,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?y:void 0}}async function fM($,b){let n=[],A=$.join(b,".contractsrc.json");if(await $.exists(A))n.push(A);let m=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let y of m)if(y!==A)n.push(y);return n}async function cM($,b,n){let A={};if(b&&await $.exists(b))try{let m=await $.readFile(b);A=JSON.parse(m)}catch{}if(n&&await $.exists(n))try{let m=await $.readFile(n),y=JSON.parse(m);A=GB(A,y)}catch{}return A}function GB($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(typeof m==="object"&&m!==null&&!Array.isArray(m)&&typeof y==="object"&&y!==null&&!Array.isArray(y))n[A]=GB(m,y);else n[A]=y}return n}function hM($){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(`
|
|
2580
|
+
`)}export{gM as watchSpecs,XB as vibe,nB as versioning,wX as verifyWithAIEnhanced,mn as verifyWithAI,yn as verifyStructure,CX as verifyService,N1 as verifySemanticFields,_7 as verifyImportedContracts,YR as verifyImplementationAgainstParsedSpec,DA as verifyBehavior,kx as validateTenantConfig,Dx as validateSpecs,l$ as validateSpec,$1 as validateScannedSpec,zx as validatePackageScaffold,Ox as validateImplementationWithAgent,nA as validateImplementationFiles,Tx as validateDiscoveredSpecs,Yx as validateBlueprint,NY as validateAudience,Ez as validateAgainstOpenApiService,aW as utils,z1 as upgrade,YI as updateSpec,QQ as toKebabCase,dW as templates,Cz as syncWithOpenApiService,px as syncSpecs,$X as stringToCacheKey,ny as setupUsageMd,ZA as setupGitignore,pm as setupAgentsMd,ZC as searchRegistry,a as safeParseJson,mI as runTests,yI as runTestSpecs,sC as runSetup,sR as runQuickstart,Jw as runDoctor,sU as runCIChecks,Aw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,qQ as resolveImplementations,J0 as resolveDefaultBuildTargets,rj as resolveAuthoredModuleValue,Tw as resolveAllImplementations,$n as renderManagedMarkdownBlock,ey as prompts,ry as parseGitModules,Iw as parseExplicitImplementations,cw as packageDeclarations,k3 as operationRegistry,oj as onboarding,lm as normalizeMarkdownContent,FT as module,cM as mergeMonorepoConfigs,zA as mergeManagedMarkdown,T4 as mergeGitignoreContent,P as loadWorkspaceConfig,dV as loadPackageAuthoredDocBlocks,Pj as loadAuthoredModuleValue,IR as loadAuthoredModuleIfExists,UA as loadAuthoredModuleExports,y$ as loadAuthoredModule,hV as loadAuthoredDocBlocksFromSourceFiles,WI as listTests,FY as listSpecsForView,j$ as listSpecs,QC as listFromRegistry,G0 as listAgentTypes,Vb as isMonorepo,$C as isContractSpecInstalled,kO as isConnectPreset,PO as isBuilderPreset,Eb as inferSetupPresetFromConfig,SQ as inferImplementationType,H7 as importFromSourceService,zj as importFromOpenApiService,sw as impact,Fj as hooks,sJ as groupSpecsByType,bS as getWorkspacePackages,cy as getWorkspaceInfo,LG as getRunCommand,om as getProductionDependencies,g$ as getPackageName,AS as getMetaRepoInfo,hy as getInstallCommand,JJ as getImplementationSummary,UO as getGraphStats,rM as getExtendedWorkspaceInfo,RG as getExecCommand,im as getDevDependencies,um as getDependencies,xw as getConventionPaths,VO as getContractNode,ln as getClaudeDesktopConfigPath,T0 as getBuilderRuntimeModeForPreset,mw as getBuilderBootstrapPresetForSetupPreset,tW as getApiKey,fJ as getAllSpecs,AV as getAllLayerLocations,Ub as getAgentAdapter,m0 as getAIProvider,Cn as genericMCPAdapter,hW as generateWorkflowSpec,kn as generateWorkflowRunnerTemplate,Nn as generateWorkflowDevkitWorkflowTemplate,gn as generateWorkflowDevkitStreamRouteTemplate,Fn as generateWorkflowDevkitStartRouteTemplate,Pn as generateWorkflowDevkitGenericTemplate,vn as generateWorkflowDevkitFollowUpRouteTemplate,tn as generateVscodeSettings,HW as generateVisualizationSpec,DM as generateViews,vY as generateView,Sw as generateUsageGuide,YW as generateTranslationSpec,cW as generateThemeSpec,DW as generateTestTemplate,XW as generateTestSpec,fW as generateTelemetrySpec,OW as generateProductIntentSpec,rW as generatePresentationSpec,ZW as generatePolicySpec,kW as generateOperationSpec,PW as generateMigrationSpec,ZR as generateMermaidDiagram,U7 as generateMarkdownReport,vW as generateKnowledgeSpaceSpec,GW as generateJobSpec,FW as generateIntegrationSpec,JW as generateHarnessSuiteSpec,VW as generateHarnessScenarioSpec,MW as generateHandlerTemplate,I7 as generateGuideFromParsedSpec,EW as generateFormSpec,IW as generateFeatureSpec,VR as generateFeatureContextMarkdown,xW as generateExperimentSpec,In as generateExampleSpec,CW as generateEventSpec,_w as generateDocsFromSpecs,RW as generateDataViewSpec,Tn as generateDataViewRendererTemplate,E7 as generateCursorRulesFromParsedSpec,jw as generateCursorRules,Mb as generateCursorMcpConfig,Wb as generateContractsrcConfig,TW as generateComponentTemplate,K7 as generateCliReport,ww as generateClaudeMcpConfig,QW as generateCapabilitySpec,Lw as generateArtifacts,LW as generateAppBlueprintSpec,Bw as generateAgentsGuide,qW as generateAgentSpec,bW as formatters,hM as formatWorkspaceInfo,GR as formatVerificationReport,bC as formatQuickstartPreview,kj as formatModuleLoadError,N as formatJson,kL as formatFiles,TV as formatDoctorSummary,DV as formatCheckResult,Ej as fix,I as findWorkspaceRoot,c as findPackageRoot,fy as findMetaRepoRoot,fM as findAllConfigFiles,cJ as filterIssuesByType,hJ as filterIssuesBySeverity,Rj as features,Rw as extractSpecReferences,rz as extractContracts,JR as exportSpecForLLM,R6 as exportOpenApi,JO as exportGraphAsDot,oW as ensurePackageScaffold,cn as discoverSpecs,c$ as discoverSpecFiles,an as discoverLayers,AA as discoverImplementationsForSpec,GJ as discoverAllImplementations,Ew as determineStatus,mS as detectRepositoryType,a$ as detectPackageManager,Qz as deleteSpec,b$ as deepMergePreserve,D0 as deepMergeOverwrite,Ln as cursorCLIAdapter,PI as createWorkspaceStateCacheStorage,xS as createWorkspaceRegistry,RX as createVerifyService,iI as createVerificationCacheService,yz as createSpecCreator,yw as createSetupNextSteps,Ww as createSetupGitignorePatterns,jC as createRegeneratorService,TA as createQuickAIReview,rn as createPackageTargetSpecSource,Fy as createNoopLoggerAdapter,vy as createNodeWatcherAdapter,Dy as createNodeGitAdapter,Ey as createNodeFsAdapter,Ry as createNodeAiAdapter,YG as createNodeAdapters,vI as createInMemoryCacheStorage,NI as createFileSystemCacheStorage,O9 as createEmptyLayerInventory,Ny as createConsoleLoggerAdapter,JG as createBunFsAdapter,p8 as createBuilderWorkspaceId,W5 as createAgentGuideService,Vj as connect,E1 as computeContentHash,Yz as compareSpecs,wK as cleanArtifacts,_n as claudeCodeAdapter,M1 as cacheKeyToString,yb as buildSpec,dn as analyzeWorkspaceDocBlocks,mA as analyzeIntegrity,hL as analyzeGap,eW as analyzeDeps,w5 as agentGuideService,Y0 as agentAdapters,X0 as adoption,SC as addToRegistry,ER as __moduleLoaderInternals,x1 as WorkspaceStateCacheStorage,_3 as WorkspaceBundle,NA as VerifyService,T1 as VerificationCacheService,YB as VALID_AUDIENCES,X2 as TestGeneratorService,Uj as SpecCreatorService,qn as SimpleAgent,sW as SETUP_TARGET_LABELS,bw as SETUP_PRESET_LABELS,nw as SETUP_PRESET_DESCRIPTIONS,Ib as SETUP_GITIGNORE_PATTERNS,AZ as RuleSyncService,_A as RegistryClient,MS as PrActionService,Hn as OpenAICodexAgent,ij as MINIMAL_DEPENDENCIES,C1 as InMemoryCacheStorage,Rn as GenericMCPAdapter,R1 as FileSystemCacheStorage,a7 as FULL_DEPENDENCIES,IS as DriftActionService,q$ as DEFAULT_SPEC_PATTERNS,v$ as DEFAULT_FS_IGNORES,I1 as DEFAULT_CACHE_CONFIG,zn as CursorCLIAdapter,Gn as CursorAgent,Yn as ClaudeCodeAgent,Kn as ClaudeCodeAdapter,SZ as CONTRACTSPEC_USAGE_BLOCK_START,QZ as CONTRACTSPEC_USAGE_BLOCK_END,yZ as CONTRACTSPEC_AGENTS_BLOCK_START,WZ as CONTRACTSPEC_AGENTS_BLOCK_END,nK as CI_CHECK_CATEGORY_LABELS,Vw as CHECK_CATEGORY_LABELS,On as AgentOrchestrator,xn as AgentGuideService,xb as ALL_SETUP_TARGETS,$w as ALL_SETUP_PRESETS,bK as ALL_CI_CHECK_CATEGORIES,Ow as ALL_CHECK_CATEGORIES,GA as AIGenerator};
|