@contractspec/bundle.workspace 4.5.5 → 4.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +518 -486
- package/dist/node/index.js +518 -486
- package/dist/ports/git.d.ts +16 -0
- package/dist/services/versioning/release-files.d.ts +1 -1
- package/dist/services/versioning/release-service.types.d.ts +4 -0
- package/dist/templates/advanced-contracts.template.d.ts +5 -0
- package/dist/templates/advanced-contracts.template.test.d.ts +1 -0
- package/dist/types.d.ts +2 -1
- package/package.json +13 -11
package/dist/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(n
|
|
4
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
5
|
-
`).map((
|
|
2
|
+
var UB=Object.defineProperty;var VB=($)=>$;function KB($,b){this[$]=VB.bind(null,b)}var f=($,b)=>{for(var A in b)UB($,A,{get:b[A],enumerable:!0,configurable:!0,set:KB.bind(b,A)})};var zy=($,b)=>()=>($&&(b=$($=0)),b);var F$=import.meta.require;import{ContractsrcSchema as _S,DEFAULT_CONTRACTSRC as fA}from"@contractspec/lib.contracts-spec/workspace-config";async function P($,b){let A=$.join(b??".",".contractsrc.json");if(!await $.exists(A))return fA;try{let m=await $.readFile(A),y=JSON.parse(m),W=_S.safeParse(y);return{...fA,...W.data,conventions:{...fA.conventions,...W.data?.conventions||{}}}}catch{return fA}}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 b$=()=>{};var Vj={};f(Vj,{AIGenerator:()=>Y0});import{createProvider as V6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as K6,buildEventSpecPrompt as _6,buildFormPrompt as z6,buildHandlerPrompt as L6,buildOperationSpecPrompt as R6,buildPresentationSpecPrompt as I6,buildTestPrompt as C6,getCodeGenSystemPrompt as pb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Tm,generateText as X0,streamText as x6}from"ai";import*as R from"zod";class Y0{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||tW(this.config.aiProvider),A={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return V6(A).getModel()}async generateOperationSpec($,b){let A=this.getModel(),n=R.object({name:R.string().describe('Dot notation name like "domain.operation"'),version:R.number().int().positive().default(1),description:R.string().describe("Clear, concise summary"),goal:R.string().describe("Business purpose"),context:R.string().describe("Background and constraints"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).describe("Team/person owners with @ prefix"),tags:R.array(R.string()).describe("Categorization tags"),auth:R.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:R.string().describe("Description of input structure"),outputShape:R.string().describe("Description of output structure"),flags:R.array(R.string()).describe("Feature flags").default([]),possibleEvents:R.array(R.string()).describe("Events this may emit").default([]),analytics:R.array(R.string()).describe("Analytics events to track").default([])}),m=R6($,b);return(await Tm({model:A,schema:n,prompt:m,system:Em()})).object}async generateEventSpec($){let b=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),n=_6($);return(await Tm({model:b,schema:A,prompt:n,system:Em()})).object}async generatePresentationSpec($,b){let A=this.getModel(),n=R.object({name:R.string(),version:R.number().int().positive().default(1),description:R.string(),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),componentKey:R.string().optional(),propsShape:R.string().optional(),content:R.string().optional(),mimeType:R.string().optional(),dataShape:R.string().optional()}),m=I6($,b);return(await Tm({model:A,schema:n,prompt:m,system:Em()})).object}async generateHandler($){let b=this.getModel();return(await X0({model:b,prompt:L6($),system:pb()})).text}async generateComponent($){let b=this.getModel();return(await X0({model:b,prompt:K6($),system:pb()})).text}async generateForm($){let b=this.getModel();return(await X0({model:b,prompt:z6($),system:pb()})).text}async generateTests($,b,A){let n=this.getModel();return(await X0({model:n,prompt:C6($,b,A),system:pb()})).text}async streamCodeGeneration($,b){let A=this.getModel(),n=await x6({model:A,prompt:$,system:pb()}),m="";for await(let y of n.textStream)m+=y,b(y);return m}}var H0=zy(()=>{b$()});import*as iT from"@contractspec/module.workspace";import{anthropic as _B}from"@ai-sdk/anthropic";import{openai as Ly}from"@ai-sdk/openai";import{DEFAULT_MODELS as Ry}from"@contractspec/lib.ai-providers/models";import{generateObject as zB,generateText as LB,streamText as RB}from"ai";import{ollama as IB}from"ollama-ai-provider";function Iy($){return{async validateProvider(b){try{let{aiProvider:A}=b;if(A==="ollama")return{success:!0};if(A==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(A==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(A){return{success:!1,error:A instanceof Error?A.message:String(A)}}},async generateText(b){let A=i0($);return{text:(await LB({model:A,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let n={model:i0($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await zB(n)).object}},async streamText(b,A){let n=i0($),m=await RB({model:n,prompt:b.prompt,system:b.systemPrompt}),y="";for await(let W of m.textStream)y+=W,A(W);return y}}}function i0($){let{aiProvider:b,aiModel:A,customEndpoint:n}=$;switch(b){case"claude":{let m=A??Ry.anthropic;return _B(m)}case"openai":{let m=A??Ry.openai;return Ly(m)}case"ollama":return IB(A??"codellama");case"custom":{if(!n)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return Ly(A??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as lB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as CB,stat as xB,mkdir as Cy,readFile as MB,rm as EB,writeFile as TB}from"fs/promises";import{basename as DB,dirname as xy,isAbsolute as NB,join as FB,relative as vB,resolve as My}from"path";import{glob as gB}from"glob";var q$=["**/*.command.ts","**/*.query.ts","**/*.operation.ts","**/*.operations.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts","**/*.capability.ts","**/*.workflow.ts","**/*.data-view.ts","**/*.form.ts","**/*.migration.ts","**/*.telemetry.ts","**/*.experiment.ts","**/*.app-config.ts","**/*.integration.ts","**/*.knowledge.ts","**/*.policy.ts","**/*.test-spec.ts","**/blueprint.ts","**/integration.ts","**/example.ts","**/bundles/*Bundle.ts","**/contracts/*.ts","**/contracts/index.ts","**/commands/*.ts","**/commands/index.ts","**/queries/*.ts","**/queries/index.ts","**/operations/*.ts","**/operations/index.ts","**/operations.ts","**/events.ts","**/presentations.ts","**/events/index.ts","**/presentations/index.ts","**/tests/*.ts","**/tests/*.test-spec.ts"],v$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function Ey($){let b=$??process.cwd();return{async exists(n){try{return await CB(A(n)),!0}catch{return!1}},async readFile(n){return MB(A(n),"utf-8")},async writeFile(n,m){let y=A(n),W=xy(y);await Cy(W,{recursive:!0}),await TB(y,m,"utf-8")},async remove(n){await EB(A(n),{recursive:!0,force:!0})},async stat(n){let m=await xB(A(n));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(n){await Cy(A(n),{recursive:!0})},async glob(n){let m=n.patterns??(n.pattern?[n.pattern]:q$),y=n.ignore??v$,W=n.cwd??b,w=n.absolute??!0;return(await gB(m,{cwd:W,ignore:y,absolute:w})).sort((B,S)=>B.localeCompare(S))},resolve(...n){let[m,...y]=n;if(!m)return b;return My(b,m,...y)},dirname(n){return xy(n)},basename(n){return DB(n)},join(...n){return FB(...n)},relative(n,m){return vB(n,m)}};function A(n){return NB(n)?n:My(b,n)}}import{spawnSync as PB}from"child_process";import{existsSync as Ty,readFileSync as Dy}from"fs";import{access as kB}from"fs/promises";import{resolve as HA}from"path";function Ny($){let b=$??process.cwd();return{async currentBranch(){try{let A=g$(["rev-parse","--abbrev-ref","HEAD"],b).trim()||rB(b);return A.length>0?A:void 0}catch{return}},async showFile(A,n){try{let m=g$(["show",`${A}:${n}`],b);if(m.length>0||A!=="HEAD")return m;return fB(b,n)??m}catch(m){throw Error(`Could not load ${n} at ref ${A}: ${m instanceof Error?m.message:String(m)}`)}},async clean(A){let n=[];if(A?.force)n.push("-f");if(A?.directories)n.push("-d");if(A?.ignored)n.push("-x");if(A?.dryRun)n.push("--dry-run");g$(["clean",...n],b,{inherit:!0})},async isGitRepo(A){let n=A?HA(b,A):b;try{return await kB(HA(n,".git")),!0}catch{return!1}},async log(A){let n=A??"HEAD~10",m="--format=%H|||%s|||%an|||%aI";try{let y=g$(["log",`${n}..HEAD`,"--format=%H|||%s|||%an|||%aI"],b),W=[];for(let w of y.trim().split(`
|
|
3
|
+
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(A,n){try{let m=n&&n.length>0?["--",...n]:[];return g$(["diff","--name-only",`${A}...HEAD`,...m],b).trim().split(`
|
|
4
|
+
`).filter(Boolean)}catch{return[]}},async statusFiles(A){try{let n=A&&A.length>0?["--",...A]:[],m=g$(["status","--short","--untracked-files=all",...n],b);return cB(m)}catch{return[]}},async diffNameStatus(A,n){try{let m=n&&n.length>0?["--",...n]:[],y=g$(["diff","--name-status",`${A}..HEAD`,...m],b);return hB(y)}catch{return[]}}}}function rB($){let b=HA($,".git","HEAD");if(!Ty(b))return"";let A=Dy(b,"utf8").trim(),n="ref: refs/heads/";return A.startsWith(n)?A.slice(n.length):A}function fB($,b){let A=HA($,b);if(!Ty(A))return;return Dy(A,"utf8")}function g$($,b,A={}){let n=PB("git",$,{cwd:b,encoding:"utf-8",stdio:A.inherit?"inherit":["ignore","pipe","pipe"]});if(n.error)throw n.error;if(n.status!==0)throw Error(typeof n.stderr==="string"&&n.stderr.length>0?n.stderr:`git ${$.join(" ")} failed with status ${n.status??"unknown"}`);return typeof n.stdout==="string"?n.stdout:""}function cB($){return $.split(`
|
|
5
|
+
`).map((b)=>b.trimEnd()).filter(Boolean).map((b)=>{let A=b.slice(0,2).trim()||b.slice(0,1),n=b.slice(3),[m,y]=n.includes(" -> ")?n.split(" -> "):[void 0,n];return{status:A,path:y??n,previousPath:m}})}function hB($){return $.split(`
|
|
6
|
+
`).map((b)=>b.trim()).filter(Boolean).map((b)=>{let[A="",n="",m]=b.split("\t");return{status:A,path:m??n,previousPath:m?n:void 0}})}function Fy(){return{debug($,b){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,b??"")},info($,b){console.info(`[INFO] ${$}`,b??"")},warn($,b){console.warn(`[WARN] ${$}`,b??"")},error($,b){console.error(`[ERROR] ${$}`,b??"")},createProgress(){return dB()}}}function vy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:uB}}function dB(){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 uB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import oB from"chokidar";var iB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function gy($){let b=$??process.cwd();return{watch(A){let n=[],m,y=oB.watch(A.pattern,{cwd:b,ignored:A.ignore??iB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),W=(w)=>{if(A.debounceMs&&A.debounceMs>0)clearTimeout(m),m=setTimeout(()=>{n.forEach((j)=>j(w))},A.debounceMs);else n.forEach((j)=>j(w))};return y.on("add",(w)=>{W({type:"add",path:w})}),y.on("change",(w)=>{W({type:"change",path:w})}),y.on("unlink",(w)=>{W({type:"unlink",path:w})}),{on(w){n.push(w)},async close(){clearTimeout(m),await y.close()}}}}}function R3($={}){let{cwd:b,config:A,silent:n}=$,m=A??lB;return{fs:Ey(b),git:Ny(b),watcher:gy(b),ai:Iy(m),logger:n?vy():Fy()}}import{stat as tB,mkdir as pB}from"fs/promises";import{basename as aB,dirname as eB,isAbsolute as sB,join as $5,relative as b5,resolve as Py}from"path";import{glob as A5}from"glob";function T3($){let b=$??process.cwd();return{async exists(n){let m=Bun.file(A(n));try{return await m.exists(),!0}catch{return!1}},async readFile(n){return Bun.file(A(n)).text()},async writeFile(n,m){let y=A(n);await Bun.write(y,m)},async remove(n){await Bun.file(A(n)).delete()},async stat(n){let m=await tB(A(n));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(n){await pB(A(n),{recursive:!0})},async glob(n){let m=n.patterns??(n.pattern?[n.pattern]:q$),y=n.ignore??v$,W=n.cwd??b,w=n.absolute??!0;return await A5(m,{cwd:W,ignore:y,absolute:w})},resolve(...n){let[m,...y]=n;if(!m)return b;return Py(b,m,...y)},dirname(n){return eB(n)},basename(n){return aB(n)},join(...n){return $5(...n)},relative(n,m){return b5(n,m)}};function A(n){return sB(n)?n:Py(b,n)}}import{existsSync as o,readFileSync as z$}from"fs";import{tmpdir as n5}from"os";import{dirname as l0,isAbsolute as m5,join as u,relative as y5,resolve as a$}from"path";var ky={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},ry=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function W5($,b){let A=y5(b,$);return A===""||!A.startsWith("..")&&!m5(A)}function t0($){let b=a$($),A=a$(n5());return W5(b,A)?A:void 0}function c($=process.cwd()){let b=a$($),A=t0($);while(!0){if(o(u(b,"package.json")))return b;let n=l0(b);if(n===b||b===A)break;b=n}return $}function x($=process.cwd()){let b=a$($),A=null,n=t0($);while(!0){for(let W of ry)if(o(u(b,W)))return b;let m=u(b,"package.json");if(o(m)){A=b;try{if(JSON.parse(z$(m,"utf-8")).workspaces)return b}catch{}}for(let W of Object.keys(ky))if(o(u(b,W)))return b;let y=l0(b);if(y===b||b===n)break;b=y}return A??$}function e$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let n of b){let m=Object.entries(ky).filter(([,y])=>y===n);for(let[y]of m)if(o(u($,y)))return n}let A=u($,"package.json");if(o(A))try{let n=JSON.parse(z$(A,"utf-8"));if(n.packageManager){let m=n.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(m)return m[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Ub($=process.cwd()){for(let A of ry)if(o(u($,A)))return!0;let b=u($,"package.json");if(o(b))try{if(JSON.parse(z$(b,"utf-8")).workspaces)return!0}catch{}return!1}function w5($){let b=u($,"pnpm-workspace.yaml");if(o(b))try{let m=z$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(m?.[1])return m[1].split(`
|
|
7
|
+
`).map((W)=>W.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let A=u($,"package.json");if(o(A))try{let n=JSON.parse(z$(A,"utf-8"));if(Array.isArray(n.workspaces))return n.workspaces;if(n.workspaces?.packages&&Array.isArray(n.workspaces.packages))return n.workspaces.packages}catch{}return}function P$($){let b=u($,"package.json");if(o(b))try{return JSON.parse(z$(b,"utf-8")).name}catch{}return}function fy($){let b=u($,".gitmodules");if(!o(b))return[];try{let A=z$(b,"utf-8"),n=[],m=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,y;while((y=m.exec(A))!==null){let[,W,w,j]=y;if(W&&w&&j){let B=u($,w),S=o(u(B,"package.json"))&&j5(B);n.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return n}catch{return[]}}function j5($){let b=u($,"package.json");if(o(b))try{let A=JSON.parse(z$(b,"utf-8"));return Boolean(A.workspaces)}catch{}return o(u($,"pnpm-workspace.yaml"))}function cy($){let b=a$($),A=t0($);while(!0){if(o(u(b,".gitmodules")))return b;let n=l0(b);if(n===b||b===A)break;b=n}return}function B5($){let b=cy($);if(!b)return;let A=fy(b);if(A.length===0)return;let n=a$($),m=A.find((y)=>n.startsWith(y.absolutePath));return{root:b,submodules:A,activeSubmodule:m}}function S5($,b){let A=cy($);if(A){if(fy(A).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function hy($=process.cwd()){let b=c($),A=x($),n=e$(A),m=Ub(A),y=m?w5(A):void 0,W=P$(b),w=S5($,m),j=w==="meta-repo"?B5($):void 0;return{packageManager:n,workspaceRoot:A,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function g3($,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 P3($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function dy($,b=!1){let A=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${A}`.trim();case"pnpm":return`pnpm add ${A}`.trim();case"yarn":return`yarn add ${A}`.trim();case"npm":return`npm install ${A}`.trim()}}import{anthropic as uy}from"@ai-sdk/anthropic";import{generateText as oy}from"ai";class GA{name="claude-code";apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set. Claude Code agent requires API access."]};try{let b=uy("claude-3-7-sonnet-20250219"),A=this.buildSystemPrompt($),n=this.buildUserPrompt($),m=await oy({model:b,prompt:n,system:A,temperature:0.2});return{success:!0,code:this.extractCode(m.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:m.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let b=uy("claude-3-7-sonnet-20250219"),A=`
|
|
6
8
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
7
9
|
|
|
8
10
|
SPECIFICATION:
|
|
@@ -31,7 +33,7 @@ Provide a structured validation report:
|
|
|
31
33
|
- Are there any missing edge cases?
|
|
32
34
|
|
|
33
35
|
Be thorough and precise. Use a critical but constructive tone.
|
|
34
|
-
`,
|
|
36
|
+
`,n=await oy({model:b,prompt:A,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),m=this.detectIssues(n.text);return{success:!m,code:n.text,errors:m?this.extractErrors(n.text):[],warnings:this.extractWarnings(n.text),suggestions:this.extractSuggestions(n.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
35
37
|
|
|
36
38
|
Your code is:
|
|
37
39
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -74,10 +76,10 @@ Spec:
|
|
|
74
76
|
${$.specCode}
|
|
75
77
|
|
|
76
78
|
Code:
|
|
77
|
-
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
80
|
-
`);for(let
|
|
79
|
+
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],A=$.toLowerCase();return b.some((n)=>A.includes(n))}extractErrors($){let b=[],A=$.split(`
|
|
80
|
+
`);for(let n of A){let m=n.toLowerCase();if(m.includes("error")||m.includes("bug")||m.includes("incorrect")||m.includes("missing"))b.push(n.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],A=$.split(`
|
|
81
|
+
`);for(let n of A){let m=n.toLowerCase();if(m.includes("warning")||m.includes("should")||m.includes("consider"))b.push(n.trim())}return b}extractSuggestions($){let b=[],A=$.split(`
|
|
82
|
+
`);for(let n of A){let m=n.toLowerCase();if(m.includes("suggest")||m.includes("recommend")||m.includes("could")||m.includes("improvement"))b.push(n.trim())}return b}}import{spawn as Q5}from"child_process";import{existsSync as iy}from"fs";import{mkdir as ly,readFile as Z5,rm as X5,writeFile as Y$}from"fs/promises";import{homedir as p0,tmpdir as ty}from"os";import{join as i}from"path";class qA{name="cursor";cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||"3000",this.detectEnvironment()}canHandle($){return this.isCursorAvailable()}async generate($){try{let b=i(ty(),`cursor-agent-${Date.now()}`);await ly(b,{recursive:!0});let A=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=i(ty(),`cursor-validate-${Date.now()}`);await ly(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let A=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",i(p0(),".cursor","cursor"),i(p0(),"AppData","Local","Programs","cursor","Cursor.exe"),i(p0(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let b of $)if(b.includes("cursor")||b.includes("Cursor")||b.includes("windsurf")||b.includes("Windsurf"))try{if(iy(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let A=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let n of A)try{let m=await n.fn();if(m.success)return m}catch(m){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,b){if(!this.cursorPath)throw Error("Cursor executable not found");let A=i(b,"spec.ts"),n=i(b,"output.ts"),m=i(b,"INSTRUCTIONS.md");if(await Y$(A,$.specCode),await Y$(m,this.buildDetailedPrompt($)),$.existingCode)await Y$(i(b,"existing.ts"),$.existingCode);return new Promise((y,W)=>{let w=["--wait","--new-window",b],j=Q5(this.cursorPath,w,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";j.stdout?.on("data",(Q)=>{B+=Q.toString()}),j.stderr?.on("data",(Q)=>{S+=Q.toString()}),j.on("error",(Q)=>{W(Q)}),j.on("close",async(Q)=>{if(iy(n))try{let Z=await Z5(n,"utf-8");y({success:!0,code:Z,metadata:{agentMode:"cursor",method:"cli",exitCode:Q}})}catch(Z){W(Error("Failed to read generated output"))}else W(Error(`Cursor CLI exited with code ${Q}. No output generated.`))}),setTimeout(()=>{j.kill(),W(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let A=i(b,"SPECIFICATION.ts"),n=i(b,"INSTRUCTIONS.md"),m=i(b,"template.ts");return await Y$(A,$.specCode),await Y$(n,this.buildDetailedPrompt($)),await Y$(m,this.generateTemplate($)),await Y$(i(b,"README.md"),`# Cursor Agent Workspace
|
|
81
83
|
|
|
82
84
|
This workspace was prepared for Cursor AI code generation.
|
|
83
85
|
|
|
@@ -93,18 +95,18 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
93
95
|
4. Save the result as output.ts
|
|
94
96
|
|
|
95
97
|
Workspace path: ${b}
|
|
96
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Y$(
|
|
98
|
+
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Y$(i(b,"specification.ts"),$.specCode),await Y$(i(b,"implementation.ts"),$.existingCode||"// No implementation"),await Y$(i(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let A=[{path:"spec.ts",content:$.specCode}];if($.existingCode)A.push({path:"existing.ts",content:$.existingCode});return A}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
97
99
|
|
|
98
100
|
**Task Type:** ${$.type}
|
|
99
101
|
**Generated:** ${new Date().toISOString()}
|
|
100
102
|
|
|
101
|
-
`,
|
|
103
|
+
`,A=`## Specification
|
|
102
104
|
|
|
103
105
|
\`\`\`typescript
|
|
104
106
|
${$.specCode}
|
|
105
107
|
\`\`\`
|
|
106
108
|
|
|
107
|
-
`,
|
|
109
|
+
`,n={generate:`## Task: Generate Implementation
|
|
108
110
|
|
|
109
111
|
### Requirements:
|
|
110
112
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -197,7 +199,7 @@ ${$.existingCode||""}
|
|
|
197
199
|
- Enhance error messages
|
|
198
200
|
|
|
199
201
|
### Output Format:
|
|
200
|
-
Refactored code that maintains functionality while improving quality.`};return b+
|
|
202
|
+
Refactored code that maintains functionality while improving quality.`};return b+A+(n[$.type]||n.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
201
203
|
|
|
202
204
|
## Specification
|
|
203
205
|
\`\`\`typescript
|
|
@@ -255,7 +257,7 @@ export function implementation() {
|
|
|
255
257
|
// Implementation goes here
|
|
256
258
|
throw new Error('Not implemented');
|
|
257
259
|
}
|
|
258
|
-
`}async cleanupWorkDir($){try{await
|
|
260
|
+
`}async cleanupWorkDir($){try{await X5($,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}}import{openai as py}from"@ai-sdk/openai";import{generateText as ay}from"ai";class OA{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let A=this.isComplexTask($)?"o1":"gpt-5.4",n=py(A),m=this.buildSystemPrompt($),y=this.buildUserPrompt($),W=await ay({model:n,prompt:y,system:m,temperature:0.2});return{success:!0,code:this.extractCode(W.text),metadata:{model:A,agentMode:"openai-codex",usage:W.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=py("gpt-5.4"),A=`
|
|
259
261
|
Review this code implementation against its specification.
|
|
260
262
|
|
|
261
263
|
SPECIFICATION:
|
|
@@ -275,7 +277,7 @@ Provide a detailed validation report including:
|
|
|
275
277
|
4. Recommendations for improvement
|
|
276
278
|
|
|
277
279
|
Format as a structured report.
|
|
278
|
-
`,
|
|
280
|
+
`,n=await ay({model:b,prompt:A,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),m=this.detectIssues(n.text);return{success:!m,code:n.text,errors:m?this.extractErrors(n.text):[],warnings:this.extractWarnings(n.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],A=($.specCode+($.existingCode||"")).toLowerCase();return b.some((n)=>A.includes(n))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
279
281
|
|
|
280
282
|
Generate production-quality code that is:
|
|
281
283
|
- Type-safe and well-typed
|
|
@@ -312,9 +314,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
312
314
|
${$.existingCode}
|
|
313
315
|
|
|
314
316
|
Spec:
|
|
315
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],
|
|
316
|
-
`);for(let
|
|
317
|
-
`);for(let
|
|
317
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],A=$.toLowerCase();return b.some((n)=>A.includes(n))}extractErrors($){let b=[],A=$.split(`
|
|
318
|
+
`);for(let n of A)if(n.toLowerCase().includes("error")||n.toLowerCase().includes("bug")||n.toLowerCase().includes("fails"))b.push(n.trim());return b}extractWarnings($){let b=[],A=$.split(`
|
|
319
|
+
`);for(let n of A)if(n.toLowerCase().includes("warning")||n.toLowerCase().includes("should")||n.toLowerCase().includes("consider"))b.push(n.trim());return b}}import k$ from"chalk";import G5 from"ora";import{generateText as ey}from"ai";var An={};f(An,{getCodeGenSystemPrompt:()=>bn,buildTestPrompt:()=>$n,buildHandlerPrompt:()=>a0,buildFormPrompt:()=>s0,buildComponentPrompt:()=>e0});function a0($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
318
320
|
|
|
319
321
|
Here is the contract spec:
|
|
320
322
|
|
|
@@ -333,7 +335,7 @@ Generate a complete handler implementation that:
|
|
|
333
335
|
|
|
334
336
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
335
337
|
|
|
336
|
-
Return only the TypeScript code for the handler function.`}function
|
|
338
|
+
Return only the TypeScript code for the handler function.`}function e0($){return`You are a senior React developer creating a component for a presentation specification.
|
|
337
339
|
|
|
338
340
|
Here is the presentation spec:
|
|
339
341
|
|
|
@@ -352,7 +354,7 @@ Generate a complete React component that:
|
|
|
352
354
|
|
|
353
355
|
The component should follow Atomic Design principles and be reusable.
|
|
354
356
|
|
|
355
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
357
|
+
Return only the TypeScript/TSX code for the component.`}function s0($){return`You are a senior React developer creating a form component from a form specification.
|
|
356
358
|
|
|
357
359
|
Here is the form spec:
|
|
358
360
|
|
|
@@ -372,7 +374,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
372
374
|
|
|
373
375
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
374
376
|
|
|
375
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
377
|
+
Return only the TypeScript/TSX code for the form component.`}function $n($,b,A){return`You are a senior developer writing comprehensive tests.
|
|
376
378
|
|
|
377
379
|
Spec:
|
|
378
380
|
\`\`\`typescript
|
|
@@ -385,7 +387,7 @@ ${b}
|
|
|
385
387
|
\`\`\`
|
|
386
388
|
|
|
387
389
|
Generate complete test suite using Vitest that:
|
|
388
|
-
${
|
|
390
|
+
${A==="handler"?`
|
|
389
391
|
- Test all acceptance scenarios from the spec
|
|
390
392
|
- Test error cases defined in spec.io.errors
|
|
391
393
|
- Verify events are emitted correctly
|
|
@@ -399,7 +401,7 @@ ${n==="handler"?`
|
|
|
399
401
|
|
|
400
402
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
401
403
|
|
|
402
|
-
Return only the TypeScript test code.`}function
|
|
404
|
+
Return only the TypeScript test code.`}function bn(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
403
405
|
- Type-safe API design
|
|
404
406
|
- React and modern hooks
|
|
405
407
|
- Test-driven development
|
|
@@ -413,7 +415,7 @@ Generate production-ready code that is:
|
|
|
413
415
|
- Defensive and error-safe
|
|
414
416
|
- Easy to maintain and extend
|
|
415
417
|
|
|
416
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
418
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as Y5}from"@contractspec/lib.ai-providers";function nn($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return Y5(b)}class JA{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=nn(this.config),A=this.buildPrompt($),n=await ey({model:b,prompt:A,system:bn()});return{success:!0,code:n.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:n.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=nn(this.config),A=`
|
|
417
419
|
Review the following implementation against its specification.
|
|
418
420
|
|
|
419
421
|
Specification:
|
|
@@ -427,15 +429,15 @@ Provide a detailed validation report:
|
|
|
427
429
|
2. Are there any missing features?
|
|
428
430
|
3. Are there any bugs or issues?
|
|
429
431
|
4. Suggestions for improvement
|
|
430
|
-
`,
|
|
431
|
-
${$.specCode}`;case"test":return
|
|
432
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
432
|
+
`,n=await ey({model:b,prompt:A,system:"You are a code review expert. Provide thorough, constructive feedback."}),m=n.text.toLowerCase().includes("error")||n.text.toLowerCase().includes("missing")||n.text.toLowerCase().includes("incorrect");return{success:!m,code:n.text,warnings:m?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return a0($.specCode);else if($.specCode.includes(".presentation."))return e0($.specCode);else if($.specCode.includes(".form."))return s0($.specCode);return`Generate implementation for:
|
|
433
|
+
${$.specCode}`;case"test":return $n($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
434
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as H5}from"@contractspec/lib.ai-agent/agent/unified-agent";class mn{name;agent;constructor($,b,A={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=H5(A,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),A=await this.agent.run(b);return{success:!0,code:A.text,metadata:{finishReason:A.finishReason,usage:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
433
435
|
${$.specCode}
|
|
434
436
|
|
|
435
437
|
`;if($.existingCode)b+=`Existing Code:
|
|
436
438
|
${$.existingCode}
|
|
437
439
|
|
|
438
|
-
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class
|
|
440
|
+
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class UA{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new JA($),A=new qA,n=new GA,m=new OA;this.agents.set("simple",b),this.agents.set("cursor",A),this.agents.set("claude-code",n),this.agents.set("openai-codex",m),this.defaultAgent=b,this.agents.set("opencode-sdk",new mn("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),A=this.agents.get(b);if(!A)return console.log(k$.yellow(`\u26A0\uFE0F Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!A.canHandle($))return console.log(k$.yellow(`\u26A0\uFE0F Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let n=G5(`Executing with ${b} agent...`).start();try{let m=$.type==="validate"?await A.validate($):await A.generate($);if(m.success)return n.succeed(k$.green(`${b} agent completed successfully`)),m;n.warn(k$.yellow(`${b} agent failed, trying fallback...`));let y=this.getFallbackMode(b);if(y&&y!==b){let W=this.agents.get(y);if(W&&W.canHandle($))return $.type==="validate"?await W.validate($):await W.generate($)}return n.info(k$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(m){return n.fail(k$.red("Agent execution failed")),console.log(k$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,A]of this.agents){let n={type:"generate",specCode:"test"},m=A.canHandle(n);$.push({mode:b,available:m,reason:m?void 0:"Not configured or dependencies missing"})}return $}getAgentMode(){return this.config.agentMode||"simple"}getFallbackMode($){return{cursor:"claude-code","claude-agent-sdk":"claude-code","claude-code":"openai-codex","openai-codex":"simple",opencode:"opencode-sdk","opencode-sdk":"claude-code",simple:"simple"}[$]}}var sy={};f(sy,{specCreation:()=>yn,codeGeneration:()=>An});var yn={};f(yn,{getSystemPrompt:()=>U5,buildPresentationSpecPrompt:()=>J5,buildOperationSpecPrompt:()=>q5,buildEventSpecPrompt:()=>O5,addExampleContext:()=>V5});function q5($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
439
441
|
|
|
440
442
|
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
441
443
|
|
|
@@ -453,7 +455,7 @@ Create a complete contract specification following these guidelines:
|
|
|
453
455
|
8. **Feature Flags**: Any flags that gate this operation
|
|
454
456
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
455
457
|
|
|
456
|
-
Respond with a structured spec.`}function
|
|
458
|
+
Respond with a structured spec.`}function O5($){return`You are a senior software architect creating an event specification.
|
|
457
459
|
|
|
458
460
|
User description: ${$}
|
|
459
461
|
|
|
@@ -467,7 +469,7 @@ Create a complete event specification following these guidelines:
|
|
|
467
469
|
|
|
468
470
|
Events represent things that have already happened and should use past tense.
|
|
469
471
|
|
|
470
|
-
Respond with a structured spec.`}function
|
|
472
|
+
Respond with a structured spec.`}function J5($,b){return`You are a senior software architect creating a presentation specification.
|
|
471
473
|
|
|
472
474
|
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
473
475
|
|
|
@@ -485,7 +487,7 @@ Create a complete presentation specification following these guidelines:
|
|
|
485
487
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
486
488
|
- Data structure description`}
|
|
487
489
|
|
|
488
|
-
Respond with a structured spec.`}function
|
|
490
|
+
Respond with a structured spec.`}function U5(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
489
491
|
|
|
490
492
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
491
493
|
|
|
@@ -495,7 +497,7 @@ Your specs are:
|
|
|
495
497
|
- Business-oriented (capturing the "why" not just "what")
|
|
496
498
|
- Designed for both humans and AI agents to understand
|
|
497
499
|
|
|
498
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
500
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function V5($,b){if(b.length===0)return $;return`${$}
|
|
499
501
|
|
|
500
502
|
Here are some good examples for reference:
|
|
501
503
|
|
|
@@ -503,47 +505,47 @@ ${b.join(`
|
|
|
503
505
|
|
|
504
506
|
`)}
|
|
505
507
|
|
|
506
|
-
Follow this structure and quality level.`}import{defineModuleBundle as
|
|
507
|
-
`)}function
|
|
508
|
+
Follow this structure and quality level.`}import{defineModuleBundle as K5}from"@contractspec/lib.surface-runtime/spec";var FH=K5({meta:{key:"bundles.workspace",version:"1.0.0",title:"Workspace",description:"Workspace utilities for monorepo development"},routes:[{routeId:"default",path:"/",defaultSurface:"main"}],surfaces:{main:{surfaceId:"main",kind:"workbench",title:"Workspace",slots:[],layouts:[],data:[],verification:{dimensions:{guidance:"Scaffolded guidance profile for Workspace.",density:"Scaffolded density profile for Workspace.",dataDepth:"Scaffolded data-depth profile for Workspace.",control:"Scaffolded control profile for Workspace.",media:"Scaffolded media profile for Workspace.",pace:"Scaffolded pace profile for Workspace.",narrative:"Scaffolded narrative profile for Workspace."}}}}});var AW={};f(AW,{sarifToJson:()=>C5,formatAsTextLines:()=>bW,formatAsText:()=>x5,formatAsSarif:()=>L5,formatAsJson:()=>_5});function _5($,b={}){let{pretty:A=!0,driftResult:n}=b,m=$.issues.map((S)=>({name:S.ruleId,status:S.severity==="error"?"fail":S.severity==="warning"?"warn":"pass",category:S.category,message:S.message,file:S.file,line:S.line,details:S.context})),y=$.categories.filter((S)=>S.passed).length,W=$.totalErrors,w=$.totalWarnings,j=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:m,categories:$.categories.map((S)=>({category:S.category,label:S.label,passed:S.passed,errors:S.errors,warnings:S.warnings,notes:S.notes,durationMs:S.durationMs})),drift:{status:n?.hasDrift?"detected":"none",files:n?.files??[]},summary:{pass:y,fail:W,warn:w,note:j,total:y+W+w+j,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return A?JSON.stringify(B,null,2):JSON.stringify(B)}var z5={"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 L5($,b={}){let{toolName:A="ContractSpec",toolVersion:n="1.0.0",toolUri:m="https://contractspec.io",repositoryUri:y,workingDirectory:W}=b,w=new Map,j=new Map,B=$.issues.filter((X)=>X.file);for(let X of B)if(!w.has(X.ruleId)){let Y=z5[X.ruleId]??{name:X.ruleId,description:`Rule: ${X.ruleId}`},H={id:X.ruleId,name:Y.name,shortDescription:{text:Y.description},defaultConfiguration:{level:$W(X.severity)}};if(Y.helpUri)H.helpUri=Y.helpUri;j.set(X.ruleId,w.size),w.set(X.ruleId,H)}let S=B.map((X)=>{let Y={ruleId:X.ruleId,ruleIndex:j.get(X.ruleId)??0,level:$W(X.severity),message:{text:X.message}},H={physicalLocation:{artifactLocation:{uri:R5(X.file),uriBaseId:"%SRCROOT%"}}};if(X.line!==void 0)H.physicalLocation.region={startLine:X.line,startColumn:X.column??1,endLine:X.endLine??X.line,endColumn:X.endColumn};return Y.locations=[H],Y.partialFingerprints={primaryLocationLineHash:I5(X)},Y}),Q=[];if(y)Q.push({repositoryUri:y,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:A,version:n,informationUri:m,rules:Array.from(w.values())}},results:S,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...W&&{workingDirectory:{uri:W}}}]};if(Q.length>0)Z.versionControlProvenance=Q;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[Z]}}function $W($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function R5($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function I5($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function C5($){return JSON.stringify($,null,2)}function bW($,b={}){let A=[],{verbose:n=!1,showTiming:m=!0,groupByFile:y=!1}=b;if(A.push({text:"",style:"normal"}),A.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),A.push({text:"",style:"normal"}),$.commitSha||$.branch){let w=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");A.push({text:`Git: ${w}`,style:"muted"})}A.push({text:"",style:"normal"}),A.push({text:"Check Results:",style:"bold"});for(let w of $.categories){let j=w.passed?"\u2713":"\u2717",B=w.passed?"success":"error",S=M5(w),Q=m?` (${w.durationMs}ms)`:"";A.push({text:` ${j} ${w.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(A.push({text:"",style:"normal"}),A.push({text:"Issues:",style:"bold"}),y){let w=E5($.issues);for(let[j,B]of w){A.push({text:"",style:"normal"}),A.push({text:` ${j||"(no file)"}`,style:"bold",indent:1});for(let S of B)A.push(...VA(S,n,2))}}else{let w=$.issues.filter((S)=>S.severity==="error"),j=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(w.length>0){A.push({text:"",style:"normal"}),A.push({text:" Errors:",style:"error",indent:1});for(let S of w)A.push(...VA(S,n,2))}if(j.length>0){A.push({text:"",style:"normal"}),A.push({text:" Warnings:",style:"warning",indent:1});for(let S of j)A.push(...VA(S,n,2))}if(B.length>0&&n){A.push({text:"",style:"normal"}),A.push({text:" Notes:",style:"muted",indent:1});for(let S of B)A.push(...VA(S,n,2))}}A.push({text:"",style:"normal"}),A.push({text:"\u2500".repeat(50),style:"muted"});let W=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&n?`${$.totalNotes} note(s)`:null].filter(Boolean);if(W.length>0)A.push({text:`Found: ${W.join(", ")}`,style:$.success?"warning":"error"});if(m)A.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(A.push({text:"",style:"normal"}),$.success)A.push({text:"\u2705 All CI checks passed!",style:"success"});else A.push({text:"\u274C CI checks failed",style:"error"});return A.push({text:"",style:"normal"}),A}function x5($,b={}){return bW($,b).map((n)=>" ".repeat(n.indent??0)+n.text).join(`
|
|
509
|
+
`)}function M5($){let b=[];if($.errors>0)b.push(`${$.errors} error(s)`);if($.warnings>0)b.push(`${$.warnings} warning(s)`);if(b.length===0)return"passed";return b.join(", ")}function VA($,b,A){let n=[],m=$.severity==="error"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",y=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",W=`${m} ${$.message}`;if($.file){let w=$.line?`:${$.line}`:"";W+=` (${$.file}${w})`}if(n.push({text:W,style:y,indent:A}),b&&$.context){let w=JSON.stringify($.context);if(w!=="{}")n.push({text:`Context: ${w}`,style:"muted",indent:A+1})}return n}function E5($){let b=new Map;for(let A of $){let n=A.file??"";if(!b.has(n))b.set(n,[]);let m=b.get(n);if(m)m.push(A)}return new Map([...b.entries()].sort(([A],[n])=>A.localeCompare(n)))}import{OperationSpecRegistry as T5}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as D5}from"@contractspec/lib.contracts-spec/operations/report";function N5(){let $=new T5;return D5($),$}var aH=N5();class F5{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let A=$.drift?.status==="fail",n=!1;if(A&&b==="fail")n=!0;return{driftDetected:A,shouldFail:n}}}function v5($){if(!$)return"\u2014";let b=new Date($),n=new Date().getTime()-b.getTime(),m=Math.floor(n/86400000);if(m<1)return"today";if(m===1)return"yesterday";return`${m} days ago`}class g5{collectChanges($,b,A){if($){let n=$.endsWith("/")?$:`${$}/`;return A.filter((m)=>m.startsWith(n))}if(b){let n=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return A.filter((m)=>n.test(m))}return A}detectDrift($){let b=$.map((A)=>A.slice(3)).filter((A)=>A&&A.trim().length>0).filter((A)=>A!==".contractspec-ci"&&!A.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},A=b.breaking||0,n=b.nonBreaking||0,m=b.total;if(m===void 0)m=A+n;let y=$?.breaking||!1,W="unknown";if($){if(y||A>0)W="breaking",y=!0;else if(n>0)W="non-breaking";else if(m===0)W="no-impact"}return{status:W,breaking:y,breakingCount:A,nonBreakingCount:n,total:m||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,A=this.deriveImpactStatus($.impactJson),n={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:A.status,breaking:A.breakingCount,nonBreaking:A.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(n.validation?.status==="fail")n.nextSteps?.push("Fix validation errors and rerun the workflow.");if(n.risk?.status==="breaking")n.nextSteps?.push("Review breaking changes and plan a migration.");if(n.risk?.status==="unknown")n.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(n.drift?.status==="fail")n.nextSteps?.push("Run the generate command locally and commit drift fixes.");let m=this.finalizeResults(n,$.failOn);if(m.shouldFail)n.nextSteps?.unshift(`CI failed: ${m.failReasons.join(", ")} (fail_on=${$.failOn}).`);return n}finalizeResults($,b){let A=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,n=$.drift?.status==="fail",m=$.validation?.status==="fail",y=$.risk?.status==="unknown",W=[],w=!1;if(b!=="never"){if(b==="breaking"){if(A)W.push("breaking changes detected");if(y)W.push("impact status unknown")}else if(b==="drift"){if(n)W.push("drift detected");if(y)W.push("impact status unknown")}else if(b==="any"){if(A)W.push("breaking changes detected");if(n)W.push("drift detected");if(m)W.push("validation failed");if(y)W.push("impact status unknown")}else W.push(`invalid fail_on value (${b})`);if(W.length>0)w=!0}return{driftDetected:n,breakingChangeDetected:A,validationFailed:m,shouldFail:w,failReasons:W}}generateReportMarkdown($,b){let A=(j,B=60000)=>{if(j.length<=B)return j;return`${j.slice(0,B)}
|
|
508
510
|
|
|
509
|
-
*(output truncated)*`},
|
|
510
|
-
`)},m=
|
|
511
|
+
*(output truncated)*`},n=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
512
|
+
`)},m=A($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),y=A($.validation?.outputPath?b($.validation.outputPath):""),W=$.drift?.files??[],w=[];if(w.push("## ContractSpec Report"),w.push(""),$.contracts&&$.contracts.length>0){w.push("### Overall verification status"),w.push(""),w.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),w.push("| --- | --- | --- | --- | --- |");for(let j of $.contracts){let B=j.lastVerifiedSha??"\u2014",S=v5(j.lastVerifiedDate),Q=j.surfaces.join(", ");w.push(`| ${j.name} | ${S} | ${j.driftMismatches} | ${Q} | ${B} |`)}w.push("")}if(w.push("### 1) What changed"),$.whatChanged?.summary)w.push($.whatChanged.summary);else w.push("No contract changes detected.");if(m.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Contract view (product)</summary>"),w.push(""),w.push(m),w.push(""),w.push("</details>");if(w.push(""),w.push("### 2) Risk classification"),$.risk?.status){let j=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);w.push(j.join(" | "))}else w.push("Impact analysis unavailable.");if(w.push(""),w.push("### 3) Validation results"),$.validation?.status){if(w.push(`Status: ${$.validation.status}`),y.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Validation output</summary>"),w.push(""),w.push(y),w.push(""),w.push("</details>")}else w.push("Validation step not run.");if(w.push(""),w.push("### 4) Drift results"),$.drift?.status){if(w.push(`Status: ${$.drift.status}`),W.length>0)w.push(""),w.push("<details>"),w.push("<summary>Drifted files</summary>"),w.push(""),w.push(n(W)),w.push(""),w.push("</details>")}else w.push("Drift check not run.");if(w.push(""),w.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)w.push(n($.nextSteps));else w.push("- No action required.");return`${w.join(`
|
|
511
513
|
`)}
|
|
512
|
-
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>sS,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>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:
|
|
514
|
+
`}}var Zn={};f(Zn,{uniqueTokens:()=>r$,tokenize:()=>s$,syncAdoptionCatalog:()=>y8,scanWorkspaceAdoptionCandidates:()=>Bn,resolveAdoptionWorkspace:()=>$b,resolveAdoption:()=>Vb,overlap:()=>_A,normalizeText:()=>jW,inferFamilyFromPath:()=>Qn,hasLocalShadcnRegistry:()=>Sn,getContractSpecAdoptionCatalog:()=>KA,createAdoptionCatalogDocument:()=>Wn,candidateTokens:()=>wn});function C($,b,A,n,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:A,packageKind:n,title:j.title??b,description:w,capabilityTags:y,preferredUseCases:W,avoidWhen:j.avoidWhen,platforms:j.platforms,replacementImportHints:j.replacementImportHints,resolutionPriority:m,runtimes:j.runtimes}}var nW=[C("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),C("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),C("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),C("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),C("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var mW=[C("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),C("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),C("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),C("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),C("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),C("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),C("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),C("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var yW=[C("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),C("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),C("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),C("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),C("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),C("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),C("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),C("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),C("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var WW=[C("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),C("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),C("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),C("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),C("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),C("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var wW=[C("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),C("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),C("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var P5=[...wW,...nW,...mW,...yW,...WW];function KA(){return[...P5].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function Wn($=new Date){return{version:1,generatedAt:$.toISOString(),entries:KA()}}import{DEFAULT_CONTRACTSRC as i5}from"@contractspec/lib.contracts-spec/workspace-config";function jW($){return $.toLowerCase().trim()}function s$($){return jW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function r$($){return[...new Set($.flatMap((b)=>s$(b)))]}function wn($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return r$(b)}function _A($,b){let A=new Set(b);return $.filter((n)=>A.has(n)).length}import{resolve as k5}from"path";import{ContractsrcSchema as r5,DEFAULT_CONTRACTSRC as jn}from"@contractspec/lib.contracts-spec/workspace-config";async function $b($,b={}){let A=k5(b.cwd??process.cwd()),n=b.workspaceRoot??x(A),m=b.packageRoot??c(A),y=b.config?SW(jn,b.config):await f5($,n,m);return{adoption:y.connect?.adoption??jn.connect.adoption,config:y,cwd:A,packageRoot:m,workspaceRoot:n}}async function f5($,b,A){let n=jn;if(b!==A)n=await BW($,n,$.join(b,".contractsrc.json"));return BW($,n,$.join(A,".contractsrc.json"))}async function BW($,b,A){if(!await $.exists(A))return b;try{let n=JSON.parse(await $.readFile(A)),m=r5.safeParse(n);if(!m.success)return b;return SW(b,m.data)}catch{return b}}function SW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var c5=["package.json","packages/*/package.json"];async function Bn($,b){let[A,n]=await Promise.all([h5($,b),d5($,b)]);return{fileCandidates:n,packageCandidates:A}}async function Sn($,b){let A=$.join(b.workspaceRoot,"components.json");if(await $.exists(A))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function h5($,b){let A=await $.glob({patterns:c5,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),n=[];for(let m of A)try{let y=JSON.parse(await $.readFile($.join(b.workspaceRoot,m))),W=Qn(m);if(!W)continue;let w=y.name??$.dirname(m);n.push({id:`workspace.package.${w}`,source:"workspace",family:W,title:w,description:y.description??`Local reusable package at ${m}.`,packageKind:o5(m),packageRef:w,capabilityTags:r$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return n}async function d5($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((n)=>{let m=Qn(n);if(!m)return[];let y=n.split("/").pop()?.replace(/\.[^.]+$/,"")??n;return[{id:`workspace.file.${n}`,source:"workspace",family:m,title:y,description:`Local reusable source at ${n}.`,filePath:n,capabilityTags:s$(n),preferredUseCases:[n],resolutionPriority:u5(m,n)}]})}function Qn($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function u5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function o5($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Vb($,b){let A=await $b($.fs,b),n=A8(b),m=r$([n,b.symbol??"",...b.paths??[]]),y=await Bn($.fs,A),W=await n8($,A),w=await Sn($.fs,A),j=l5(A,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...m8(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=s5(A,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:n,reason:b8(B,S),selected:B,verdict:Q}}function l5($,b,A,n){return n.filter((m)=>m.family===A.family&&a5($,m.family)).filter((m)=>e5(m,A.platform)).map((m)=>t5(m,b,A.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function t5($,b,A){let n=wn($),m=r$(A??[]),y=[],W=_A(b,n)*25,w=_A(m,n)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:p5($.source)+($.resolutionPriority??0)+W+w}}function p5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function a5($,b){return $.adoption.families?.[b]??!0}function e5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function s5($,b,A,n){let m=$.adoption.thresholds??i5.connect.adoption.thresholds;if(A)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return $8(b.candidate,n)?"permit":m.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return m.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return m.newImplementation??"require_review";return m.newExternalDependency??"require_review"}function $8($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function b8($,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 A8($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function n8($,b){let A=KA(),n=b.adoption.catalog?.overrideManifestPath;if(!n||!await $.fs.exists($.fs.join(b.workspaceRoot,n)))return A;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,n)),y=JSON.parse(m);return[...A,...Array.isArray(y)?y:y.entries??[]]}catch{return A}}function m8($,b,A){if($==="ui"&&b==="web"&&A)return[bb("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[bb("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[bb("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[bb("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[bb("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[bb("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function bb($,b,A,n,m){return{id:$,source:"ecosystem",packageRef:A,family:b,packageKind:"primitive",title:n,description:n,capabilityTags:s$(n),preferredUseCases:[n],resolutionPriority:m}}async function y8($,b={}){let A=await $b($.fs,b),n=Wn(),m=$.fs.join(A.workspaceRoot,A.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(m,`${JSON.stringify(n,null,2)}
|
|
515
|
+
`),{catalog:n,catalogPath:m}}import{AGENT_SYSTEM_PROMPTS as W8}from"@contractspec/lib.contracts-spec/llm";class zA{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let A of $.fileStructure){let n=A.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";b.push(`${n} \`${A.path}\``),b.push(` ${A.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let A of $.steps){b.push(`### ${A.order}. ${A.title}`),b.push(""),b.push(A.description),b.push(""),b.push("**Acceptance Criteria:**");for(let n of A.acceptanceCriteria)b.push(`- [ ] ${n}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let A of $.constraints.security)b.push(`- \u26A0\uFE0F ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:W8["claude-code"],taskPrompt:b.join(`
|
|
514
516
|
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
515
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let
|
|
516
|
-
`)}}generateConfig($){let b=$.meta,
|
|
517
|
-
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var
|
|
518
|
-
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,
|
|
519
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let
|
|
517
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let A=[],n=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let m of n){let y=$.matchAll(m);for(let W of y)if(W[1])A.push(W[1])}if(A.length>0)return{errors:A};return{code:$}}}var LA=new zA;import{AGENT_SYSTEM_PROMPTS as w8}from"@contractspec/lib.contracts-spec/llm";class RA{agentType="cursor-cli";formatPlan($){let b=[];if(b.push(`# ${$.target.key}.v${$.target.version}`),b.push(""),b.push(`> ${$.context.goal}`),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push("");for(let n of $.fileStructure)b.push(`- ${n.type}: \`${n.path}\` - ${n.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let n of $.steps)b.push(`${n.order}. **${n.title}**: ${n.description}`);b.push("");let A=[...$.constraints.policy,...$.constraints.security.map((n)=>`\u26A0\uFE0F ${n}`)];if(A.length>0){b.push("## Constraints"),b.push("");for(let n of A)b.push(`- ${n}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((n)=>`\`${n}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:w8["cursor-cli"],taskPrompt:b.join(`
|
|
518
|
+
`)}}generateConfig($){let b=$.meta,A=[];if(A.push("---"),A.push(`description: Implementation rules for ${b.key}.v${b.version}`),A.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),A.push("alwaysApply: false"),A.push("---"),A.push(""),A.push(`# ${b.key} Implementation Rules`),A.push(""),A.push(`This ${b.kind} operation must follow the ContractSpec specification.`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Requirements"),A.push(""),A.push("1. Input/output types MUST match the spec schema exactly"),A.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)A.push("3. Events MUST be emitted as specified");if(A.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)A.push(`5. Idempotency: ${$.policy.idempotent}`);if(A.push(""),$.io.errors&&Object.keys($.io.errors).length>0){A.push("## Error Cases"),A.push("");for(let[n,m]of Object.entries($.io.errors))A.push(`- \`${n}\` (HTTP ${m.http??400}): ${m.when}`);A.push("")}if($.sideEffects?.emits?.length){A.push("## Events to Emit"),A.push("");for(let n of $.sideEffects.emits)if("ref"in n)A.push(`- \`${n.ref.key}.v${n.ref.version}\`: ${n.when}`);else A.push(`- \`${n.key}.v${n.version}\`: ${n.when}`);A.push("")}if($.policy.pii?.length){A.push("## PII Handling"),A.push(""),A.push("These fields contain PII and must be handled with care:");for(let n of $.policy.pii)A.push(`- \`${n}\``);A.push("")}if($.acceptance?.scenarios?.length){A.push("## Acceptance Scenarios"),A.push("");for(let n of $.acceptance.scenarios)A.push(`### ${n.key}`),A.push(`- Given: ${n.given.join("; ")}`),A.push(`- When: ${n.when.join("; ")}`),A.push(`- Then: ${n.then.join("; ")}`),A.push("")}return A.join(`
|
|
519
|
+
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var IA=new RA;import{AGENT_SYSTEM_PROMPTS as j8}from"@contractspec/lib.contracts-spec/llm";class CA{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let A of $.fileStructure)b.push(`| \`${A.path}\` | ${A.type} | ${A.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let A of $.steps)if(b.push(`### Step ${A.order}: ${A.title}`),b.push(""),b.push(A.description),b.push(""),A.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let n of A.acceptanceCriteria)b.push(`- ${n}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let A of $.constraints.security)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),{agent:"generic-mcp",systemPrompt:j8["generic-mcp"],taskPrompt:b.join(`
|
|
520
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,A=[];return A.push(`# ${b.key} v${b.version}`),A.push(""),A.push(`**Type:** ${b.kind}`),A.push(`**Stability:** ${b.stability}`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Description"),A.push(""),A.push(b.description),A.push(""),A.join(`
|
|
521
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let A=JSON.parse($);if(typeof A.code==="string")return{code:A.code};if(typeof A.errors==="object")return{errors:Array.isArray(A.errors)?A.errors:[String(A.errors)]}}catch{}return{code:$}}}var xA=new CA;var Xn={"claude-code":LA,"cursor-cli":IA,"generic-mcp":xA};function Kb($){let b=Xn[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function Yn(){return Object.keys(Xn)}import{featureToMarkdown as Hn,generateImplementationPlan as QW,operationSpecToAgentPrompt as B8,operationSpecToFullMarkdown as S8}from"@contractspec/lib.contracts-spec/llm";var Q8={defaultAgent:"generic-mcp",verbose:!1};class MA{config;constructor($={}){this.config={...Q8,...$}}generateGuide($,b={}){let A=b.agent??this.config.defaultAgent,n=Kb(A),m=QW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),y=n.formatPlan(m),W=S8($);return{plan:m,prompt:y,markdown:W}}generateFeatureGuide($,b,A={}){let n=A.agent??this.config.defaultAgent,m=Kb(n),y=$.operations?.[0],W=y?b.specs?.get(y.key,y.version):void 0,w;if(W)w=QW(W,{projectRoot:this.config.projectRoot}),w.target={type:"feature",key:$.meta.key,version:"1.0.0"},w.context.goal=$.meta.description??w.context.goal;else w={target:{type:"feature",key:$.meta.key,version:"1.0.0"},context:{goal:$.meta.description??`Implement feature ${$.meta.key}`,description:$.meta.title??$.meta.key,background:""},specMarkdown:Hn($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(w.specMarkdown=Hn($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)w.steps=$.operations.map((S,Q)=>({order:Q+1,title:`Implement ${S.key}`,description:`Implement operation ${S.key}.v${S.version}`,acceptanceCriteria:[`Operation ${S.key} works as specified`]}));let j=m.formatPlan(w),B=Hn($,b);return{plan:w,prompt:j,markdown:B}}generateAgentConfig($,b){return Kb(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,A="implement",n){return B8($,{taskType:A,existingCode:n})}listAgentTypes(){return Yn()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function Z8($){return new MA($)}var X8=new MA;import{detectAuthoringTarget as WS,generateComponentTemplate as wS,generateHandlerTemplate as jS,generateTestTemplate as BS,getAuthoringTargetDefinition as SS,inferSpecTypeFromFilePath as QS,scanSpecSource as ZS}from"@contractspec/module.workspace";var uW={};f(uW,{generateWorkflowSpec:()=>dW,generateWorkflowRunnerTemplate:()=>kA,generateWorkflowDevkitWorkflowTemplate:()=>NA,generateWorkflowDevkitStreamRouteTemplate:()=>gA,generateWorkflowDevkitStartRouteTemplate:()=>FA,generateWorkflowDevkitGenericTemplate:()=>PA,generateWorkflowDevkitFollowUpRouteTemplate:()=>vA,generateVisualizationSpec:()=>qW,generateTranslationSpec:()=>HW,generateThemeSpec:()=>hW,generateTestTemplate:()=>NW,generateTestSpec:()=>YW,generateTelemetrySpec:()=>cW,generatePwaAppManifestSpec:()=>KW,generateProductIntentSpec:()=>JW,generatePresentationSpec:()=>fW,generatePolicySpec:()=>XW,generateOperationSpec:()=>rW,generateMigrationSpec:()=>kW,generateKnowledgeSpaceSpec:()=>gW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>vW,generateHarnessSuiteSpec:()=>VW,generateHarnessScenarioSpec:()=>UW,generateHandlerTemplate:()=>TW,generateFormSpec:()=>EW,generateFeatureSpec:()=>MW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>EA,generateEventSpec:()=>CW,generateDataViewSpec:()=>IW,generateDataViewRendererTemplate:()=>TA,generateComponentTemplate:()=>DW,generateCapabilitySpec:()=>ZW,generateAppBlueprintSpec:()=>RW,generateAgentSpec:()=>OW});function ZW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
520
522
|
|
|
521
523
|
export const ${nb($.key)}Capability = defineCapability({
|
|
522
524
|
meta: {
|
|
523
525
|
key: '${$.key}',
|
|
524
526
|
version: '${$.version}',
|
|
525
527
|
kind: '${$.kind??"api"}',
|
|
526
|
-
title: '${k(
|
|
528
|
+
title: '${k(Ab($))}',
|
|
527
529
|
description: '${k($.description)}',
|
|
528
|
-
domain: '${k(
|
|
529
|
-
owners: [${
|
|
530
|
-
tags: [${
|
|
530
|
+
domain: '${k(f$($))}',
|
|
531
|
+
owners: [${w$($.owners)}],
|
|
532
|
+
tags: [${w$($.tags)}],
|
|
531
533
|
stability: '${$.stability}',
|
|
532
534
|
},
|
|
533
535
|
provides: [],
|
|
534
536
|
requires: [],
|
|
535
537
|
});
|
|
536
|
-
`}function
|
|
538
|
+
`}function XW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
537
539
|
|
|
538
540
|
export const ${nb($.key)}Policy = definePolicy({
|
|
539
541
|
meta: {
|
|
540
542
|
key: '${$.key}',
|
|
541
543
|
version: '${$.version}',
|
|
542
|
-
title: '${k(
|
|
544
|
+
title: '${k(Ab($))}',
|
|
543
545
|
description: '${k($.description)}',
|
|
544
|
-
domain: '${k(
|
|
545
|
-
owners: [${
|
|
546
|
-
tags: [${
|
|
546
|
+
domain: '${k(f$($))}',
|
|
547
|
+
owners: [${w$($.owners)}],
|
|
548
|
+
tags: [${w$($.tags)}],
|
|
547
549
|
stability: '${$.stability}',
|
|
548
550
|
scope: '${$.scope??"feature"}',
|
|
549
551
|
},
|
|
@@ -551,27 +553,27 @@ export const ${nb($.key)}Policy = definePolicy({
|
|
|
551
553
|
{
|
|
552
554
|
effect: 'allow',
|
|
553
555
|
actions: ['read'],
|
|
554
|
-
resource: { type: '${k(
|
|
556
|
+
resource: { type: '${k(f$($))}' },
|
|
555
557
|
reason: 'TODO: replace with real access rules',
|
|
556
558
|
},
|
|
557
559
|
],
|
|
558
560
|
});
|
|
559
|
-
`}function
|
|
561
|
+
`}function YW($){let b=$.targetVersion??"1.0.0",A=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
560
562
|
|
|
561
563
|
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
562
564
|
meta: {
|
|
563
565
|
key: '${$.key}',
|
|
564
566
|
version: '${$.version}',
|
|
565
|
-
title: '${k(
|
|
567
|
+
title: '${k(Ab($))}',
|
|
566
568
|
description: '${k($.description)}',
|
|
567
|
-
domain: '${k(
|
|
568
|
-
owners: [${
|
|
569
|
-
tags: [${
|
|
569
|
+
domain: '${k(f$($))}',
|
|
570
|
+
owners: [${w$($.owners)}],
|
|
571
|
+
tags: [${w$($.tags)}],
|
|
570
572
|
stability: '${$.stability}',
|
|
571
573
|
},
|
|
572
574
|
target: {
|
|
573
575
|
type: '${$.targetType}',
|
|
574
|
-
${$.targetType}: ${
|
|
576
|
+
${$.targetType}: ${A},
|
|
575
577
|
},
|
|
576
578
|
scenarios: [
|
|
577
579
|
{
|
|
@@ -581,23 +583,23 @@ export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
|
581
583
|
},
|
|
582
584
|
],
|
|
583
585
|
});
|
|
584
|
-
`}function
|
|
586
|
+
`}function HW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
585
587
|
|
|
586
588
|
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
587
589
|
meta: {
|
|
588
590
|
key: '${$.key}',
|
|
589
591
|
version: '${$.version}',
|
|
590
|
-
domain: '${k(
|
|
592
|
+
domain: '${k(f$($))}',
|
|
591
593
|
description: '${k($.description)}',
|
|
592
|
-
owners: [${
|
|
593
|
-
tags: [${
|
|
594
|
+
owners: [${w$($.owners)}],
|
|
595
|
+
tags: [${w$($.tags)}],
|
|
594
596
|
stability: '${$.stability}',
|
|
595
597
|
},
|
|
596
598
|
locale: '${$.locale}',
|
|
597
599
|
fallback: '${$.fallback??$.locale}',
|
|
598
600
|
messages: {
|
|
599
601
|
'${$.key}.title': {
|
|
600
|
-
value: '${k(
|
|
602
|
+
value: '${k(Ab($))}',
|
|
601
603
|
description: 'TODO: replace with a real localized message',
|
|
602
604
|
},
|
|
603
605
|
},
|
|
@@ -608,29 +610,29 @@ export const ${nb($.key)}Job = defineJob({
|
|
|
608
610
|
meta: {
|
|
609
611
|
key: '${$.key}',
|
|
610
612
|
version: '${$.version}',
|
|
611
|
-
title: '${k(
|
|
613
|
+
title: '${k(Ab($))}',
|
|
612
614
|
description: '${k($.description)}',
|
|
613
|
-
domain: '${k(
|
|
614
|
-
owners: [${
|
|
615
|
-
tags: [${
|
|
615
|
+
domain: '${k(f$($))}',
|
|
616
|
+
owners: [${w$($.owners)}],
|
|
617
|
+
tags: [${w$($.tags)}],
|
|
616
618
|
stability: '${$.stability}',
|
|
617
619
|
},
|
|
618
620
|
payload: { schema: {} },
|
|
619
621
|
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
620
622
|
});
|
|
621
|
-
`}function
|
|
623
|
+
`}function qW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
622
624
|
|
|
623
625
|
export const ${nb($.key)}Visualization = defineVisualization({
|
|
624
626
|
meta: {
|
|
625
627
|
key: '${$.key}',
|
|
626
628
|
version: '${$.version}',
|
|
627
|
-
title: '${k(
|
|
629
|
+
title: '${k(Ab($))}',
|
|
628
630
|
description: '${k($.description)}',
|
|
629
631
|
goal: 'TODO: describe the decision this visualization supports',
|
|
630
632
|
context: 'TODO: describe where this visualization appears',
|
|
631
|
-
domain: '${k(
|
|
632
|
-
owners: [${
|
|
633
|
-
tags: [${
|
|
633
|
+
domain: '${k(f$($))}',
|
|
634
|
+
owners: [${w$($.owners)}],
|
|
635
|
+
tags: [${w$($.tags)}],
|
|
634
636
|
stability: '${$.stability}',
|
|
635
637
|
},
|
|
636
638
|
source: {
|
|
@@ -646,19 +648,19 @@ export const ${nb($.key)}Visualization = defineVisualization({
|
|
|
646
648
|
measure: 'value',
|
|
647
649
|
},
|
|
648
650
|
});
|
|
649
|
-
`}function
|
|
651
|
+
`}function Ab($){return $.title??Y8($.key.split(".").at(-1)??$.key)}function f$($){return $.domain??$.key.split(".")[0]??"contractspec"}function w$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function nb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Y8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function EA($){let b=$.packageName??`@contractspec/example.${G8($.key.split(".").at(-1)??$.key)}`,A=`${mb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
650
652
|
|
|
651
|
-
const ${
|
|
653
|
+
const ${A} = defineExample({
|
|
652
654
|
meta: {
|
|
653
655
|
key: '${$.key}',
|
|
654
656
|
version: '${$.version}',
|
|
655
|
-
title: '${
|
|
656
|
-
description: '${
|
|
657
|
+
title: '${h(_b($))}',
|
|
658
|
+
description: '${h($.description)}',
|
|
657
659
|
kind: 'template',
|
|
658
660
|
visibility: 'experimental',
|
|
659
661
|
stability: '${$.stability}',
|
|
660
|
-
owners: [${
|
|
661
|
-
tags: [${
|
|
662
|
+
owners: [${s($.owners)}],
|
|
663
|
+
tags: [${s($.tags)}],
|
|
662
664
|
},
|
|
663
665
|
surfaces: {
|
|
664
666
|
templates: true,
|
|
@@ -671,51 +673,51 @@ const ${n} = defineExample({
|
|
|
671
673
|
},
|
|
672
674
|
});
|
|
673
675
|
|
|
674
|
-
export default ${
|
|
675
|
-
export { ${
|
|
676
|
-
`}function
|
|
676
|
+
export default ${A};
|
|
677
|
+
export { ${A} };
|
|
678
|
+
`}function OW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
677
679
|
|
|
678
|
-
export const ${
|
|
680
|
+
export const ${mb($.key)}Agent = defineAgent({
|
|
679
681
|
meta: {
|
|
680
682
|
key: '${$.key}',
|
|
681
683
|
version: '${$.version}',
|
|
682
|
-
description: '${
|
|
683
|
-
owners: [${
|
|
684
|
-
tags: [${
|
|
684
|
+
description: '${h($.description)}',
|
|
685
|
+
owners: [${s($.owners)}],
|
|
686
|
+
tags: [${s($.tags)}],
|
|
685
687
|
stability: '${$.stability}',
|
|
686
688
|
},
|
|
687
|
-
instructions: '${
|
|
689
|
+
instructions: '${h($.instructions)}',
|
|
688
690
|
tools: [{ name: 'todo' }],
|
|
689
691
|
});
|
|
690
|
-
`}function
|
|
692
|
+
`}function JW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
691
693
|
|
|
692
|
-
export const ${
|
|
694
|
+
export const ${mb($.key)}ProductIntent = defineProductIntentSpec({
|
|
693
695
|
id: '${$.id??`${$.key}-run`}',
|
|
694
696
|
meta: {
|
|
695
697
|
key: '${$.key}',
|
|
696
698
|
version: '${$.version}',
|
|
697
|
-
title: '${
|
|
698
|
-
description: '${
|
|
699
|
+
title: '${h(_b($))}',
|
|
700
|
+
description: '${h($.description)}',
|
|
699
701
|
goal: 'TODO: capture the desired product outcome',
|
|
700
702
|
context: 'TODO: capture the decision context',
|
|
701
703
|
stability: '${$.stability}',
|
|
702
|
-
owners: [${
|
|
703
|
-
tags: [${
|
|
704
|
+
owners: [${s($.owners)}],
|
|
705
|
+
tags: [${s($.tags)}],
|
|
704
706
|
},
|
|
705
|
-
question: '${
|
|
707
|
+
question: '${h($.question)}',
|
|
706
708
|
insights: { insights: [] },
|
|
707
709
|
});
|
|
708
|
-
`}function
|
|
710
|
+
`}function UW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
709
711
|
|
|
710
|
-
export const ${
|
|
712
|
+
export const ${mb($.key)}HarnessScenario = defineHarnessScenario({
|
|
711
713
|
meta: {
|
|
712
714
|
key: '${$.key}',
|
|
713
715
|
version: '${$.version}',
|
|
714
|
-
title: '${
|
|
715
|
-
description: '${
|
|
716
|
-
domain: '${
|
|
717
|
-
owners: [${
|
|
718
|
-
tags: [${
|
|
716
|
+
title: '${h(_b($))}',
|
|
717
|
+
description: '${h($.description)}',
|
|
718
|
+
domain: '${h(Gn($))}',
|
|
719
|
+
owners: [${s($.owners)}],
|
|
720
|
+
tags: [${s($.tags)}],
|
|
719
721
|
stability: '${$.stability}',
|
|
720
722
|
},
|
|
721
723
|
target: {
|
|
@@ -740,17 +742,17 @@ export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
|
740
742
|
},
|
|
741
743
|
],
|
|
742
744
|
});
|
|
743
|
-
`}function
|
|
745
|
+
`}function VW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
744
746
|
|
|
745
|
-
export const ${
|
|
747
|
+
export const ${mb($.key)}HarnessSuite = defineHarnessSuite({
|
|
746
748
|
meta: {
|
|
747
749
|
key: '${$.key}',
|
|
748
750
|
version: '${$.version}',
|
|
749
|
-
title: '${
|
|
750
|
-
description: '${
|
|
751
|
-
domain: '${
|
|
752
|
-
owners: [${
|
|
753
|
-
tags: [${
|
|
751
|
+
title: '${h(_b($))}',
|
|
752
|
+
description: '${h($.description)}',
|
|
753
|
+
domain: '${h(Gn($))}',
|
|
754
|
+
owners: [${s($.owners)}],
|
|
755
|
+
tags: [${s($.tags)}],
|
|
754
756
|
stability: '${$.stability}',
|
|
755
757
|
},
|
|
756
758
|
scenarios: [
|
|
@@ -763,99 +765,129 @@ export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
|
763
765
|
weight: 1,
|
|
764
766
|
},
|
|
765
767
|
],
|
|
766
|
-
summary: '${
|
|
767
|
-
tags: [${
|
|
768
|
+
summary: '${h($.description)}',
|
|
769
|
+
tags: [${s($.tags)}],
|
|
768
770
|
});
|
|
769
|
-
`}function
|
|
771
|
+
`}function KW($){let b=$.currentRelease??$.version;return`import { definePwaAppManifest } from '@contractspec/lib.contracts-spec/pwa';
|
|
772
|
+
|
|
773
|
+
export const ${mb($.key)}PwaApp = definePwaAppManifest({
|
|
774
|
+
meta: {
|
|
775
|
+
key: '${$.key}',
|
|
776
|
+
version: '${$.version}',
|
|
777
|
+
appId: '${$.appId??$.key}',
|
|
778
|
+
title: '${h(_b($))}',
|
|
779
|
+
description: '${h($.description)}',
|
|
780
|
+
domain: '${h(Gn($))}',
|
|
781
|
+
stability: '${$.stability}',
|
|
782
|
+
owners: [${s($.owners)}],
|
|
783
|
+
tags: [${s($.tags)}],
|
|
784
|
+
},
|
|
785
|
+
currentRelease: '${b}',
|
|
786
|
+
defaultUpdatePolicy: {
|
|
787
|
+
mode: 'optional',
|
|
788
|
+
minSupportedVersion: '${b}',
|
|
789
|
+
},
|
|
790
|
+
releases: [
|
|
791
|
+
{
|
|
792
|
+
version: '${b}',
|
|
793
|
+
releasedAt: new Date().toISOString(),
|
|
794
|
+
notes: 'Initial release manifest.',
|
|
795
|
+
},
|
|
796
|
+
],
|
|
797
|
+
offline: {
|
|
798
|
+
supported: true,
|
|
799
|
+
},
|
|
800
|
+
});
|
|
801
|
+
`}function _b($){return $.title??H8($.key.split(".").at(-1)??$.key)}function Gn($){return $.domain??$.key.split(".")[0]??"contractspec"}function s($){return $.map((b)=>`'${h(b)}'`).join(", ")}function mb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function H8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function G8($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=L8($.key.split(".").pop()??"App")+"AppConfig",A=q8($),n=O8($),m=_W("dataViews",$.dataViews),y=_W("workflows",$.workflows),W=J8($),w=U8($),j=V8($),B=K8($),S=_8($),Q=z8($),Z=$.notes?` notes: '${D($.notes)}',
|
|
770
802
|
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
771
803
|
|
|
772
804
|
export const ${b} = defineAppConfig({
|
|
773
805
|
meta: {
|
|
774
|
-
key: '${
|
|
806
|
+
key: '${D($.key)}',
|
|
775
807
|
version: '${$.version}',
|
|
776
|
-
title: '${
|
|
777
|
-
description: '${
|
|
778
|
-
domain: '${
|
|
779
|
-
owners: [${$.owners.map((X)=>`'${
|
|
780
|
-
tags: [${$.tags.map((X)=>`'${
|
|
808
|
+
title: '${D($.title)}',
|
|
809
|
+
description: '${D($.description)}',
|
|
810
|
+
domain: '${D($.domain)}',
|
|
811
|
+
owners: [${$.owners.map((X)=>`'${D(X)}'`).join(", ")}],
|
|
812
|
+
tags: [${$.tags.map((X)=>`'${D(X)}'`).join(", ")}],
|
|
781
813
|
stability: '${$.stability}',
|
|
782
|
-
appId: '${
|
|
814
|
+
appId: '${D($.appId)}',
|
|
783
815
|
},
|
|
784
|
-
${
|
|
785
|
-
`}function
|
|
786
|
-
`:"",
|
|
816
|
+
${A}${n}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
817
|
+
`}function q8($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((n)=>zW(n)).join(", ")}],
|
|
818
|
+
`:"",A=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((n)=>zW(n)).join(", ")}],
|
|
787
819
|
`:"";return` capabilities: {
|
|
788
|
-
${b}${
|
|
789
|
-
`}function
|
|
790
|
-
`:"",
|
|
820
|
+
${b}${A} },
|
|
821
|
+
`}function O8($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((n)=>`{ key: '${D(n)}' }`).join(", ")}],
|
|
822
|
+
`:"",A=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((n)=>`{ key: '${D(n)}' }`).join(", ")}],
|
|
791
823
|
`:"";return` features: {
|
|
792
|
-
${b}${
|
|
793
|
-
`}function
|
|
794
|
-
key: '${
|
|
795
|
-
version: '${
|
|
824
|
+
${b}${A} },
|
|
825
|
+
`}function _W($,b){if(b.length===0)return"";let A=b.map((n)=>` ${n.slot}: {
|
|
826
|
+
key: '${D(n.key)}'${n.version?`,
|
|
827
|
+
version: '${n.version}'`:""}
|
|
796
828
|
}`).join(`,
|
|
797
829
|
`);return` ${$}: {
|
|
798
|
-
${
|
|
830
|
+
${A}
|
|
799
831
|
},
|
|
800
|
-
`}function
|
|
801
|
-
${$.policyRefs.map((
|
|
802
|
-
key: '${
|
|
803
|
-
version: '${
|
|
832
|
+
`}function J8($){if($.policyRefs.length===0)return"";return` policies: [
|
|
833
|
+
${$.policyRefs.map((A)=>` {
|
|
834
|
+
key: '${D(A.key)}'${A.version?`,
|
|
835
|
+
version: '${A.version}'`:""}
|
|
804
836
|
}`).join(`,
|
|
805
837
|
`)}
|
|
806
838
|
],
|
|
807
|
-
`}function
|
|
808
|
-
`,
|
|
839
|
+
`}function U8($){if(!$.theme)return"";let b=` primary: { key: '${D($.theme.key)}', version: '${$.theme.version}' },
|
|
840
|
+
`,A=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((n)=>`{ key: '${D(n.key)}', version: '${n.version}' }`).join(", ")}],
|
|
809
841
|
`:"";return` theme: {
|
|
810
|
-
${b}${
|
|
811
|
-
`}function
|
|
842
|
+
${b}${A} },
|
|
843
|
+
`}function V8($){if(!$.telemetry)return"";return` telemetry: {
|
|
812
844
|
spec: {
|
|
813
|
-
key: '${
|
|
845
|
+
key: '${D($.telemetry.key)}'${$.telemetry.version?`,
|
|
814
846
|
version: '${$.telemetry.version}'`:""}
|
|
815
847
|
},
|
|
816
848
|
},
|
|
817
|
-
`}function
|
|
818
|
-
`:"",
|
|
849
|
+
`}function K8($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((n)=>LW(n)).join(", ")}],
|
|
850
|
+
`:"",A=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((n)=>LW(n)).join(", ")}],
|
|
819
851
|
`:"";return` experiments: {
|
|
820
|
-
${b}${
|
|
821
|
-
`}function
|
|
822
|
-
${$.featureFlags.map((
|
|
823
|
-
key: '${
|
|
824
|
-
enabled: ${
|
|
825
|
-
${
|
|
826
|
-
${
|
|
852
|
+
${b}${A} },
|
|
853
|
+
`}function _8($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
854
|
+
${$.featureFlags.map((A)=>` {
|
|
855
|
+
key: '${D(A.key)}',
|
|
856
|
+
enabled: ${A.enabled},
|
|
857
|
+
${A.variant?`variant: '${D(A.variant)}',`:""}
|
|
858
|
+
${A.description?`description: '${D(A.description)}',`:""}
|
|
827
859
|
}`).join(`,
|
|
828
860
|
`)}
|
|
829
861
|
],
|
|
830
|
-
`}function
|
|
831
|
-
${$.routes.map((
|
|
862
|
+
`}function z8($){if($.routes.length===0)return"";return` routes: [
|
|
863
|
+
${$.routes.map((A)=>{return` { ${[`path: '${D(A.path)}'`,A.label?`label: '${D(A.label)}'`:null,A.dataView?`dataView: '${D(A.dataView)}'`:null,A.workflow?`workflow: '${D(A.workflow)}'`:null,A.guardKey?`guard: { key: '${D(A.guardKey)}'${A.guardVersion?`, version: '${A.guardVersion}'`:""} }`:null,A.featureFlag?`featureFlag: '${D(A.featureFlag)}'`:null,A.experimentKey?`experiment: { key: '${D(A.experimentKey)}'${A.experimentVersion?`, version: '${A.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
832
864
|
`)}
|
|
833
865
|
],
|
|
834
|
-
`}function
|
|
866
|
+
`}function zW($){return`{ key: '${D($)}' }`}function LW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${D($.key)}'${b} }`}function L8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function D($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function IW($){let b=R8($.name.split(".").pop()??"DataView")+"DataView",A=$.fields.map((y)=>` {
|
|
835
867
|
key: '${y.key}',
|
|
836
|
-
label: '${
|
|
868
|
+
label: '${zb(y.label)}',
|
|
837
869
|
dataPath: '${y.dataPath}',
|
|
838
|
-
${y.format?`format:
|
|
870
|
+
${y.format?`format: ${I8(y.format)},`:""}
|
|
839
871
|
${y.sortable?"sortable: true,":""}
|
|
840
872
|
${y.filterable?"filterable: true,":""}
|
|
841
873
|
}`).join(`,
|
|
842
|
-
`),
|
|
874
|
+
`),n=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((y)=>`'${y}'`).join(", ")}],`:"",m=$.itemOperation?`item: { key: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
843
875
|
|
|
844
876
|
export const ${b}: DataViewSpec = {
|
|
845
877
|
meta: {
|
|
846
878
|
key: '${$.name}',
|
|
847
879
|
version: ${$.version},
|
|
848
880
|
entity: '${$.entity}',
|
|
849
|
-
title: '${
|
|
850
|
-
description: '${
|
|
851
|
-
domain: '${
|
|
881
|
+
title: '${zb($.title)}',
|
|
882
|
+
description: '${zb($.description||"Describe the purpose of this data view.")}',
|
|
883
|
+
domain: '${zb($.domain||$.entity)}',
|
|
852
884
|
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
853
885
|
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
854
886
|
stability: '${$.stability}',
|
|
855
887
|
},
|
|
856
888
|
source: {
|
|
857
889
|
primary: {
|
|
858
|
-
|
|
890
|
+
key: '${$.primaryOperation.name}',
|
|
859
891
|
version: ${$.primaryOperation.version},
|
|
860
892
|
},
|
|
861
893
|
${m}
|
|
@@ -866,10 +898,10 @@ export const ${b}: DataViewSpec = {
|
|
|
866
898
|
view: {
|
|
867
899
|
kind: '${$.kind}',
|
|
868
900
|
fields: [
|
|
869
|
-
${
|
|
901
|
+
${A}
|
|
870
902
|
],
|
|
871
903
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
872
|
-
${
|
|
904
|
+
${n}
|
|
873
905
|
filters: [
|
|
874
906
|
// Example filter:
|
|
875
907
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -880,17 +912,17 @@ ${n}
|
|
|
880
912
|
],
|
|
881
913
|
},
|
|
882
914
|
states: {
|
|
883
|
-
// empty: {
|
|
884
|
-
// error: {
|
|
915
|
+
// empty: { key: 'app.data.empty', version: '1.0.0' },
|
|
916
|
+
// error: { key: 'app.data.error', version: '1.0.0' },
|
|
885
917
|
},
|
|
886
918
|
};
|
|
887
|
-
`}function
|
|
919
|
+
`}function R8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function zb($){return $.replace(/'/g,"\\'")}function I8($){if(typeof $==="string")return`'${zb($)}'`;return JSON.stringify($)}function TA({exportName:$,specImportPath:b,rendererName:A,viewKind:n}){return`'use client';
|
|
888
920
|
|
|
889
921
|
import * as React from 'react';
|
|
890
922
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
891
923
|
import { ${$} } from '${b}';
|
|
892
924
|
|
|
893
|
-
export interface ${
|
|
925
|
+
export interface ${A}Props {
|
|
894
926
|
items?: Record<string, unknown>[];
|
|
895
927
|
item?: Record<string, unknown> | null;
|
|
896
928
|
className?: string;
|
|
@@ -900,17 +932,17 @@ export interface ${n}Props {
|
|
|
900
932
|
}
|
|
901
933
|
|
|
902
934
|
/**
|
|
903
|
-
* Auto-generated renderer for the "${
|
|
935
|
+
* Auto-generated renderer for the "${n}" data view.
|
|
904
936
|
* Customize as needed for app-specific behaviour.
|
|
905
937
|
*/
|
|
906
|
-
export function ${
|
|
938
|
+
export function ${A}({
|
|
907
939
|
items = [],
|
|
908
940
|
item = null,
|
|
909
941
|
className,
|
|
910
942
|
renderActions,
|
|
911
943
|
onSelect,
|
|
912
944
|
onRowClick,
|
|
913
|
-
}: ${
|
|
945
|
+
}: ${A}Props) {
|
|
914
946
|
return (
|
|
915
947
|
<DataViewRenderer
|
|
916
948
|
spec={${$}}
|
|
@@ -923,7 +955,7 @@ export function ${n}({
|
|
|
923
955
|
/>
|
|
924
956
|
);
|
|
925
957
|
}
|
|
926
|
-
`}function CW($){let{name:b,version:
|
|
958
|
+
`}function CW($){let{name:b,version:A,description:n,stability:m,owners:y,tags:W,piiFields:w}=$,j=C8(b.replace(/\./g,"_"))+"V"+A,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
927
959
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
928
960
|
|
|
929
961
|
// TODO: Define event payload schema
|
|
@@ -939,33 +971,33 @@ export const ${B} = new SchemaModel({
|
|
|
939
971
|
export const ${j} = defineEvent({
|
|
940
972
|
name: '${b}',
|
|
941
973
|
name: '${b}',
|
|
942
|
-
version: '${
|
|
943
|
-
description: '${
|
|
944
|
-
description: '${
|
|
974
|
+
version: '${A}',
|
|
975
|
+
description: '${n}',
|
|
976
|
+
description: '${n}',
|
|
945
977
|
stability: '${m}',
|
|
946
978
|
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
947
979
|
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
948
980
|
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
949
981
|
payload: ${B},
|
|
950
982
|
});
|
|
951
|
-
`}function
|
|
983
|
+
`}function C8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function xW($){let b=M8($.name.split(".").pop()??"Experiment")+"Experiment",A=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
952
984
|
${y.overrides.map((w)=>` {
|
|
953
985
|
type: '${w.type}',
|
|
954
|
-
target: '${
|
|
986
|
+
target: '${d(w.target)}',
|
|
955
987
|
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
956
988
|
}`).join(`,
|
|
957
989
|
`)}
|
|
958
990
|
],`:"";return` {
|
|
959
|
-
id: '${
|
|
960
|
-
name: '${
|
|
961
|
-
${y.description?`description: '${
|
|
991
|
+
id: '${d(y.id)}',
|
|
992
|
+
name: '${d(y.name)}',
|
|
993
|
+
${y.description?`description: '${d(y.description)}',`:""}
|
|
962
994
|
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
963
995
|
${W}
|
|
964
996
|
}`}).join(`,
|
|
965
|
-
`),
|
|
997
|
+
`),n=x8($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
966
998
|
${$.successMetrics.map((y)=>` {
|
|
967
|
-
name: '${
|
|
968
|
-
telemetryEvent: { name: '${
|
|
999
|
+
name: '${d(y.name)}',
|
|
1000
|
+
telemetryEvent: { name: '${d(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
969
1001
|
aggregation: '${y.aggregation}',
|
|
970
1002
|
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
971
1003
|
}`).join(`,
|
|
@@ -974,42 +1006,42 @@ ${$.successMetrics.map((y)=>` {
|
|
|
974
1006
|
|
|
975
1007
|
export const ${b}: ExperimentSpec = {
|
|
976
1008
|
meta: {
|
|
977
|
-
key: '${
|
|
1009
|
+
key: '${d($.name)}',
|
|
978
1010
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
979
|
-
title: '${
|
|
980
|
-
description: '${
|
|
981
|
-
domain: '${
|
|
982
|
-
owners: [${$.owners.map((y)=>`'${
|
|
983
|
-
tags: [${$.tags.map((y)=>`'${
|
|
1011
|
+
title: '${d($.name)} experiment',
|
|
1012
|
+
description: '${d($.description||"Describe the experiment goal.")}',
|
|
1013
|
+
domain: '${d($.domain)}',
|
|
1014
|
+
owners: [${$.owners.map((y)=>`'${d(y)}'`).join(", ")}],
|
|
1015
|
+
tags: [${$.tags.map((y)=>`'${d(y)}'`).join(", ")}],
|
|
984
1016
|
stability: '${$.stability}',
|
|
985
1017
|
},
|
|
986
|
-
controlVariant: '${
|
|
1018
|
+
controlVariant: '${d($.controlVariant)}',
|
|
987
1019
|
variants: [
|
|
988
|
-
${
|
|
1020
|
+
${A}
|
|
989
1021
|
],
|
|
990
|
-
allocation: ${
|
|
1022
|
+
allocation: ${n},
|
|
991
1023
|
${m}
|
|
992
1024
|
};
|
|
993
|
-
`}function
|
|
1025
|
+
`}function x8($){switch($.type){case"random":return`{
|
|
994
1026
|
type: 'random',
|
|
995
|
-
${$.salt?`salt: '${
|
|
1027
|
+
${$.salt?`salt: '${d($.salt)}',`:""}
|
|
996
1028
|
}`;case"sticky":return`{
|
|
997
1029
|
type: 'sticky',
|
|
998
1030
|
attribute: '${$.attribute}',
|
|
999
|
-
${$.salt?`salt: '${
|
|
1031
|
+
${$.salt?`salt: '${d($.salt)}',`:""}
|
|
1000
1032
|
}`;case"targeted":return`{
|
|
1001
1033
|
type: 'targeted',
|
|
1002
1034
|
rules: [
|
|
1003
1035
|
${$.rules.map((b)=>` {
|
|
1004
|
-
variantId: '${
|
|
1036
|
+
variantId: '${d(b.variantId)}',
|
|
1005
1037
|
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1006
|
-
${b.policy?`policy: { name: '${
|
|
1007
|
-
${b.expression?`expression: '${
|
|
1038
|
+
${b.policy?`policy: { name: '${d(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1039
|
+
${b.expression?`expression: '${d(b.expression)}',`:""}
|
|
1008
1040
|
}`).join(`,
|
|
1009
1041
|
`)}
|
|
1010
1042
|
],
|
|
1011
1043
|
fallback: '${$.fallback??"control"}',
|
|
1012
|
-
}`;default:return
|
|
1044
|
+
}`;default:return E8($)}}function M8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function d($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function E8($){throw Error(`Unsupported allocation type ${$}`)}function T8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function MW($){let b=(A)=>A.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
1013
1045
|
`);return`/**
|
|
1014
1046
|
* ${$.title} Feature
|
|
1015
1047
|
*
|
|
@@ -1018,15 +1050,15 @@ ${$.rules.map((b)=>` {
|
|
|
1018
1050
|
|
|
1019
1051
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
1020
1052
|
|
|
1021
|
-
export const ${
|
|
1053
|
+
export const ${T8($.key)}Feature = defineFeature({
|
|
1022
1054
|
meta: {
|
|
1023
1055
|
key: '${$.key}',
|
|
1024
1056
|
version: '${$.version}',
|
|
1025
1057
|
title: '${$.title}',
|
|
1026
1058
|
description: '${$.description||"TODO: Add description"}',
|
|
1027
1059
|
domain: '${$.domain}',
|
|
1028
|
-
owners: [${$.owners.map((
|
|
1029
|
-
tags: [${$.tags.map((
|
|
1060
|
+
owners: [${$.owners.map((A)=>`'${A}'`).join(", ")}],
|
|
1061
|
+
tags: [${$.tags.map((A)=>`'${A}'`).join(", ")}],
|
|
1030
1062
|
stability: '${$.stability||"beta"}',
|
|
1031
1063
|
},
|
|
1032
1064
|
|
|
@@ -1046,7 +1078,7 @@ ${b($.presentations)||" // Add presentations here"}
|
|
|
1046
1078
|
${b($.experiments)||" // Add experiments here"}
|
|
1047
1079
|
],
|
|
1048
1080
|
});
|
|
1049
|
-
`}function
|
|
1081
|
+
`}function D8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function EW($){let b=D8($.key),A=`${b}FormModel`,n=`${b}Form`;return`/**
|
|
1050
1082
|
* ${$.title} Form
|
|
1051
1083
|
*
|
|
1052
1084
|
* Auto-generated form spec.
|
|
@@ -1055,8 +1087,8 @@ ${b($.experiments)||" // Add experiments here"}
|
|
|
1055
1087
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
1056
1088
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
1057
1089
|
|
|
1058
|
-
const ${
|
|
1059
|
-
name: '${
|
|
1090
|
+
const ${A} = defineSchemaModel({
|
|
1091
|
+
name: '${A}',
|
|
1060
1092
|
description: '${$.description||"TODO: Add form model description"}',
|
|
1061
1093
|
fields: {
|
|
1062
1094
|
${$.primaryFieldKey}: {
|
|
@@ -1066,7 +1098,7 @@ const ${n} = defineSchemaModel({
|
|
|
1066
1098
|
},
|
|
1067
1099
|
});
|
|
1068
1100
|
|
|
1069
|
-
export const ${
|
|
1101
|
+
export const ${n} = defineFormSpec({
|
|
1070
1102
|
meta: {
|
|
1071
1103
|
key: '${$.key}',
|
|
1072
1104
|
version: '${$.version}',
|
|
@@ -1077,7 +1109,7 @@ export const ${A} = defineFormSpec({
|
|
|
1077
1109
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1078
1110
|
stability: '${$.stability||"beta"}',
|
|
1079
1111
|
},
|
|
1080
|
-
model: ${
|
|
1112
|
+
model: ${A},
|
|
1081
1113
|
fields: [
|
|
1082
1114
|
{
|
|
1083
1115
|
kind: 'text',
|
|
@@ -1102,13 +1134,13 @@ export const ${A} = defineFormSpec({
|
|
|
1102
1134
|
form: 'react-hook-form',
|
|
1103
1135
|
},
|
|
1104
1136
|
});
|
|
1105
|
-
`}function
|
|
1106
|
-
import { ${
|
|
1137
|
+
`}function TW($,b){let A=N8($.split(".").pop()||"unknown")+"Handler",n=DA($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1138
|
+
import { ${n} } from '../contracts/${FW($)}.contracts';
|
|
1107
1139
|
|
|
1108
1140
|
/**
|
|
1109
1141
|
* Handler for ${$}
|
|
1110
1142
|
*/
|
|
1111
|
-
export const ${
|
|
1143
|
+
export const ${A}: ContractHandler<typeof ${n}> = async (
|
|
1112
1144
|
input,
|
|
1113
1145
|
context
|
|
1114
1146
|
) => {
|
|
@@ -1128,27 +1160,27 @@ export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
|
1128
1160
|
throw error;
|
|
1129
1161
|
}
|
|
1130
1162
|
};
|
|
1131
|
-
`}function
|
|
1163
|
+
`}function DW($,b){let A=DA($);return`import React from 'react';
|
|
1132
1164
|
|
|
1133
|
-
interface ${
|
|
1165
|
+
interface ${A}Props {
|
|
1134
1166
|
// TODO: Define props based on presentation spec
|
|
1135
1167
|
}
|
|
1136
1168
|
|
|
1137
1169
|
/**
|
|
1138
1170
|
* ${b}
|
|
1139
1171
|
*/
|
|
1140
|
-
export const ${
|
|
1172
|
+
export const ${A}: React.FC<${A}Props> = (props) => {
|
|
1141
1173
|
return (
|
|
1142
1174
|
<div>
|
|
1143
1175
|
{/* TODO: Implement component UI */}
|
|
1144
|
-
<p>Component: ${
|
|
1176
|
+
<p>Component: ${A}</p>
|
|
1145
1177
|
</div>
|
|
1146
1178
|
);
|
|
1147
1179
|
};
|
|
1148
|
-
`}function
|
|
1149
|
-
import { ${
|
|
1180
|
+
`}function NW($,b){let A=b==="handler"?"../handlers":"../components",n=DA($);return`import { describe, it, expect } from 'bun:test';
|
|
1181
|
+
import { ${n} } from '${A}/${FW($)}';
|
|
1150
1182
|
|
|
1151
|
-
describe('${
|
|
1183
|
+
describe('${n}', () => {
|
|
1152
1184
|
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
1153
1185
|
// TODO: Implement test
|
|
1154
1186
|
expect(true).toBe(true);
|
|
@@ -1164,27 +1196,27 @@ describe('${A}', () => {
|
|
|
1164
1196
|
// TODO: Test accessibility
|
|
1165
1197
|
});`}
|
|
1166
1198
|
});
|
|
1167
|
-
`}function
|
|
1199
|
+
`}function N8($){let b=DA($);return b.charAt(0).toLowerCase()+b.slice(1)}function DA($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function FW($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function vW($){let b=h8($.name.split(".").pop()??"Integration"),A=`${b}IntegrationSpec`,n=`register${b}Integration`,m=$.supportedModes.length?$.supportedModes:["managed"],y=m.map((H)=>`'${H}'`).join(", "),W=$.capabilitiesProvided.map((H)=>` { key: '${H.key}', version: '${H.version}' }`).join(`,
|
|
1168
1200
|
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1169
|
-
${$.capabilitiesRequired.map((
|
|
1201
|
+
${$.capabilitiesRequired.map((H)=>{let J=H.version!==void 0?`, version: '${H.version}'`:"",O=H.optional?", optional: true":"",V=H.reason?`, reason: '${j$(H.reason)}'`:"";return` { key: '${H.key}'${J}${O}${V} }`}).join(`,
|
|
1170
1202
|
`)}
|
|
1171
|
-
],`:"",j=
|
|
1172
|
-
`:"",X=
|
|
1203
|
+
],`:"",j=F8($.configFields),B=g8($.configFields),S=v8($.secretFields),Q=P8($.secretFields),Z=$.docsUrl?` docsUrl: '${j$($.docsUrl)}',
|
|
1204
|
+
`:"",X=k8($.rateLimitRpm,$.rateLimitRph),Y=r8(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1173
1205
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
1174
1206
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
1175
1207
|
|
|
1176
|
-
export const ${
|
|
1208
|
+
export const ${A}: IntegrationSpec = {
|
|
1177
1209
|
meta: {
|
|
1178
1210
|
key: '${$.name}',
|
|
1179
1211
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
1180
1212
|
category: '${$.category}',
|
|
1181
|
-
displayName: '${
|
|
1182
|
-
title: '${
|
|
1183
|
-
description: '${
|
|
1184
|
-
domain: '${
|
|
1185
|
-
owners: [${$.owners.map((
|
|
1186
|
-
tags: [${$.tags.map((
|
|
1187
|
-
stability: StabilityEnum.${
|
|
1213
|
+
displayName: '${j$($.displayName)}',
|
|
1214
|
+
title: '${j$($.title)}',
|
|
1215
|
+
description: '${j$($.description)}',
|
|
1216
|
+
domain: '${j$($.domain)}',
|
|
1217
|
+
owners: [${$.owners.map((H)=>`'${j$(H)}'`).join(", ")}],
|
|
1218
|
+
tags: [${$.tags.map((H)=>`'${j$(H)}'`).join(", ")}],
|
|
1219
|
+
stability: StabilityEnum.${c8($.stability)},
|
|
1188
1220
|
},
|
|
1189
1221
|
supportedModes: [${y}],
|
|
1190
1222
|
capabilities: {
|
|
@@ -1207,48 +1239,48 @@ ${Z}${X}${Y} healthCheck: {
|
|
|
1207
1239
|
},
|
|
1208
1240
|
};
|
|
1209
1241
|
|
|
1210
|
-
export function ${
|
|
1242
|
+
export function ${n}(
|
|
1211
1243
|
registry: IntegrationSpecRegistry
|
|
1212
1244
|
): IntegrationSpecRegistry {
|
|
1213
|
-
return registry.register(${
|
|
1245
|
+
return registry.register(${A});
|
|
1214
1246
|
}
|
|
1215
|
-
`}function
|
|
1216
|
-
`:"",
|
|
1247
|
+
`}function F8($){let b=$.filter((m)=>m.required),A=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1248
|
+
`:"",n=$.length?$.map((m)=>{let y=m.description?`, description: '${j$(m.description)}'`:"";return` ${m.key}: { type: '${f8(m.type)}'${y} }`}).join(`,
|
|
1217
1249
|
`):"";return` schema: {
|
|
1218
1250
|
type: 'object',
|
|
1219
|
-
${
|
|
1220
|
-
${
|
|
1251
|
+
${A} properties: {
|
|
1252
|
+
${n||" "}
|
|
1221
1253
|
},
|
|
1222
1254
|
},
|
|
1223
|
-
`}function
|
|
1224
|
-
`:"",
|
|
1255
|
+
`}function v8($){let b=$.filter((m)=>m.required),A=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1256
|
+
`:"",n=$.length?$.map((m)=>{let y=m.description?`, description: '${j$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
1225
1257
|
`):"";return` schema: {
|
|
1226
1258
|
type: 'object',
|
|
1227
|
-
${
|
|
1228
|
-
${
|
|
1259
|
+
${A} properties: {
|
|
1260
|
+
${n||" "}
|
|
1229
1261
|
},
|
|
1230
1262
|
},
|
|
1231
|
-
`}function
|
|
1232
|
-
${$.map((
|
|
1263
|
+
`}function g8($){if($.length===0)return"{}";return`{
|
|
1264
|
+
${$.map((A)=>{switch(A.type){case"number":return` ${A.key}: 0`;case"boolean":return` ${A.key}: true`;case"string":default:return` ${A.key}: '${A.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
1233
1265
|
`)}
|
|
1234
|
-
}`}function
|
|
1235
|
-
${$.map((
|
|
1266
|
+
}`}function P8($){if($.length===0)return"{}";return`{
|
|
1267
|
+
${$.map((A)=>` ${A.key}: '${A.key.toUpperCase()}_SECRET'`).join(`,
|
|
1236
1268
|
`)}
|
|
1237
|
-
}`}function
|
|
1269
|
+
}`}function k8($,b){if($==null&&b==null)return"";let A=[];if($!=null)A.push(` rpm: ${$}`);if(b!=null)A.push(` rph: ${b}`);return` constraints: {
|
|
1238
1270
|
rateLimit: {
|
|
1239
|
-
${
|
|
1271
|
+
${A.join(`,
|
|
1240
1272
|
`)}
|
|
1241
1273
|
},
|
|
1242
1274
|
},
|
|
1243
|
-
`}function
|
|
1244
|
-
`:"",m=
|
|
1245
|
-
`:"";if(!
|
|
1246
|
-
${
|
|
1247
|
-
`}function
|
|
1275
|
+
`}function r8($,b,A){if(!$.includes("byok"))return"";let n=b?` setupInstructions: '${j$(b)}',
|
|
1276
|
+
`:"",m=A&&A.length?` requiredScopes: [${A.map((y)=>`'${j$(y)}'`).join(", ")}],
|
|
1277
|
+
`:"";if(!n&&!m)return"";return` byokSetup: {
|
|
1278
|
+
${n}${m} },
|
|
1279
|
+
`}function f8($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function c8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function h8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function j$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function gW($){let b=l8($.name.split(".").pop()??"KnowledgeSpace"),A=`${b}KnowledgeSpace`,n=`register${b}KnowledgeSpace`,m=d8($),y=u8($),W=o8($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1248
1280
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1249
1281
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1250
1282
|
|
|
1251
|
-
export const ${
|
|
1283
|
+
export const ${A}: KnowledgeSpaceSpec = {
|
|
1252
1284
|
meta: {
|
|
1253
1285
|
key: '${$.name}',
|
|
1254
1286
|
version: ${$.version},
|
|
@@ -1259,7 +1291,7 @@ export const ${n}: KnowledgeSpaceSpec = {
|
|
|
1259
1291
|
domain: '${O$($.domain)}',
|
|
1260
1292
|
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1261
1293
|
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1262
|
-
stability: StabilityEnum.${
|
|
1294
|
+
stability: StabilityEnum.${i8($.stability)},
|
|
1263
1295
|
},
|
|
1264
1296
|
retention: ${m},
|
|
1265
1297
|
access: {
|
|
@@ -1268,54 +1300,54 @@ ${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` ve
|
|
|
1268
1300
|
${W} description: '${O$($.description||$.displayName)}',
|
|
1269
1301
|
};
|
|
1270
1302
|
|
|
1271
|
-
export function ${
|
|
1303
|
+
export function ${n}(
|
|
1272
1304
|
registry: KnowledgeSpaceRegistry
|
|
1273
1305
|
): KnowledgeSpaceRegistry {
|
|
1274
|
-
return registry.register(${
|
|
1306
|
+
return registry.register(${A});
|
|
1275
1307
|
}
|
|
1276
|
-
`}function
|
|
1277
|
-
`,
|
|
1278
|
-
`;return`${b}${
|
|
1308
|
+
`}function d8($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",A=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${A} }`}function u8($){let b=` trustLevel: '${$.trustLevel}',
|
|
1309
|
+
`,A=` automationWritable: ${$.automationWritable},
|
|
1310
|
+
`;return`${b}${A}`}function o8($){let b=[];if($.embeddingModel)b.push(` embeddingModel: '${O$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")b.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)b.push(` vectorDbIntegration: '${O$($.vectorDbIntegration)}'`);if(b.length===0)return"";return` indexing: {
|
|
1279
1311
|
${b.join(`,
|
|
1280
1312
|
`)}
|
|
1281
1313
|
},
|
|
1282
|
-
`}function
|
|
1314
|
+
`}function i8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function l8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function O$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function kW($){let A=`${t8($.name.split(".").pop()??"Migration")}Migration`,n=$.dependencies.length>0?`dependencies: [${$.dependencies.map((m)=>`'${m}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1283
1315
|
|
|
1284
|
-
export const ${
|
|
1316
|
+
export const ${A}: MigrationSpec = {
|
|
1285
1317
|
meta: {
|
|
1286
1318
|
key: '${$.name}',
|
|
1287
1319
|
version: ${$.version},
|
|
1288
|
-
title: '${
|
|
1289
|
-
description: '${
|
|
1290
|
-
domain: '${
|
|
1320
|
+
title: '${c$($.title)}',
|
|
1321
|
+
description: '${c$($.description??"")}',
|
|
1322
|
+
domain: '${c$($.domain)}',
|
|
1291
1323
|
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1292
1324
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1293
1325
|
stability: '${$.stability}',
|
|
1294
1326
|
},
|
|
1295
1327
|
plan: {
|
|
1296
1328
|
up: [
|
|
1297
|
-
${
|
|
1329
|
+
${PW($.up)}
|
|
1298
1330
|
],${$.down&&$.down.length?`
|
|
1299
1331
|
down: [
|
|
1300
|
-
${
|
|
1332
|
+
${PW($.down)}
|
|
1301
1333
|
],`:""}
|
|
1302
1334
|
},
|
|
1303
|
-
${
|
|
1335
|
+
${n}
|
|
1304
1336
|
};
|
|
1305
|
-
`}function
|
|
1337
|
+
`}function PW($){return $.map((b)=>{let A=b.description?`description: '${c$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1306
1338
|
kind: 'schema',
|
|
1307
|
-
${
|
|
1308
|
-
sql: \`${
|
|
1339
|
+
${A}
|
|
1340
|
+
sql: \`${c$(b.sql??"")}\`,
|
|
1309
1341
|
}`;case"data":return` {
|
|
1310
1342
|
kind: 'data',
|
|
1311
|
-
${
|
|
1312
|
-
script: \`${
|
|
1343
|
+
${A}
|
|
1344
|
+
script: \`${c$(b.script??"")}\`,
|
|
1313
1345
|
}`;case"validation":default:return` {
|
|
1314
1346
|
kind: 'validation',
|
|
1315
|
-
${
|
|
1316
|
-
assertion: \`${
|
|
1347
|
+
${A}
|
|
1348
|
+
assertion: \`${c$(b.assertion??"")}\`,
|
|
1317
1349
|
}`}}).join(`,
|
|
1318
|
-
`)}function
|
|
1350
|
+
`)}function t8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function c$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function rW($){let{name:b,version:A,kind:n,description:m,goal:y,context:W,stability:w,owners:j,tags:B,auth:S,flags:Q}=$,Z=p8(b.split(".").pop()||"Unknown")+"Spec",X=Z.replace("Spec","Input"),Y=Z.replace("Spec","Output");return`import { define${qn(n)} } from '@contractspec/lib.contracts-spec';
|
|
1319
1351
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1320
1352
|
|
|
1321
1353
|
// TODO: Define input schema
|
|
@@ -1338,15 +1370,15 @@ export const ${Y} = new SchemaModel({
|
|
|
1338
1370
|
},
|
|
1339
1371
|
});
|
|
1340
1372
|
|
|
1341
|
-
export const ${Z} = define${
|
|
1373
|
+
export const ${Z} = define${qn(n)}({
|
|
1342
1374
|
meta: {
|
|
1343
1375
|
key: '${b}',
|
|
1344
1376
|
key: '${b}',
|
|
1345
|
-
version: '${
|
|
1377
|
+
version: '${A}',
|
|
1346
1378
|
stability: '${w}',
|
|
1347
1379
|
stability: '${w}',
|
|
1348
|
-
owners: [${j.map((
|
|
1349
|
-
tags: [${B.map((
|
|
1380
|
+
owners: [${j.map((H)=>`'${H}'`).join(", ")}],
|
|
1381
|
+
tags: [${B.map((H)=>`'${H}'`).join(", ")}],
|
|
1350
1382
|
description: '${m}',
|
|
1351
1383
|
goal: '${y}',
|
|
1352
1384
|
context: '${W}',
|
|
@@ -1367,7 +1399,7 @@ export const ${Z} = define${q0(A)}({
|
|
|
1367
1399
|
|
|
1368
1400
|
policy: {
|
|
1369
1401
|
auth: '${S}',
|
|
1370
|
-
${Q.length>0?`flags: [${Q.map((
|
|
1402
|
+
${Q.length>0?`flags: [${Q.map((H)=>`'${H}'`).join(", ")}],`:"// flags: [],"}
|
|
1371
1403
|
},
|
|
1372
1404
|
|
|
1373
1405
|
sideEffects: {
|
|
@@ -1381,9 +1413,9 @@ export const ${Z} = define${q0(A)}({
|
|
|
1381
1413
|
},
|
|
1382
1414
|
|
|
1383
1415
|
transport: {
|
|
1384
|
-
rest: { method: '${
|
|
1416
|
+
rest: { method: '${n==="command"?"POST":"GET"}' },
|
|
1385
1417
|
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1386
|
-
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(
|
|
1418
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(A).replace(/\./g,"_")}' },
|
|
1387
1419
|
},
|
|
1388
1420
|
|
|
1389
1421
|
acceptance: {
|
|
@@ -1404,7 +1436,7 @@ export const ${Z} = define${q0(A)}({
|
|
|
1404
1436
|
],
|
|
1405
1437
|
},
|
|
1406
1438
|
});
|
|
1407
|
-
`}function
|
|
1439
|
+
`}function qn($){return $.charAt(0).toUpperCase()+$.slice(1)}function p8($){return $.split(/[-_.]/).map(qn).join("")}function fW($){let{name:b,version:A,description:n,stability:m,owners:y,tags:W,presentationKind:w}=$,j=a8(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1408
1440
|
kind: 'web_component',
|
|
1409
1441
|
framework: 'react',
|
|
1410
1442
|
componentKey: '${b.replace(/\./g,"_")}',
|
|
@@ -1421,7 +1453,7 @@ export const ${Z} = define${q0(A)}({
|
|
|
1421
1453
|
},`;break;case"markdown":B=` content: {
|
|
1422
1454
|
kind: 'markdown',
|
|
1423
1455
|
content: \`
|
|
1424
|
-
# ${
|
|
1456
|
+
# ${n}
|
|
1425
1457
|
|
|
1426
1458
|
TODO: Add markdown content here
|
|
1427
1459
|
\`,
|
|
@@ -1442,11 +1474,11 @@ import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
|
1442
1474
|
export const ${j}: PresentationSpec = {
|
|
1443
1475
|
meta: {
|
|
1444
1476
|
key: '${b}',
|
|
1445
|
-
version: ${
|
|
1477
|
+
version: ${A},
|
|
1446
1478
|
stability: '${m}',
|
|
1447
1479
|
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1448
1480
|
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1449
|
-
description: '${
|
|
1481
|
+
description: '${n}',
|
|
1450
1482
|
},
|
|
1451
1483
|
|
|
1452
1484
|
policy: {
|
|
@@ -1456,25 +1488,25 @@ export const ${j}: PresentationSpec = {
|
|
|
1456
1488
|
|
|
1457
1489
|
${B}
|
|
1458
1490
|
};
|
|
1459
|
-
`}function
|
|
1491
|
+
`}function a8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function cW($){let b=e8($.name.split(".").pop()??"Telemetry")+"Telemetry",A=$.providers?.length?`providers: [
|
|
1460
1492
|
${$.providers.map((m)=>` {
|
|
1461
1493
|
type: '${m.type}',
|
|
1462
|
-
config: ${
|
|
1494
|
+
config: ${s8(m.config)},
|
|
1463
1495
|
}`).join(`,
|
|
1464
1496
|
`)}
|
|
1465
|
-
],`:"",
|
|
1497
|
+
],`:"",n=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1466
1498
|
type: '${w.type}',
|
|
1467
1499
|
${w.required?"required: true,":""}
|
|
1468
1500
|
${w.pii?"pii: true,":""}
|
|
1469
1501
|
${w.redact?"redact: true,":""}
|
|
1470
|
-
${w.description?`description: '${
|
|
1502
|
+
${w.description?`description: '${t(w.description)}',`:""}
|
|
1471
1503
|
}`).join(`,
|
|
1472
1504
|
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1473
1505
|
enabled: true,
|
|
1474
1506
|
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1475
1507
|
thresholds: [
|
|
1476
1508
|
${m.anomalyRules.map((w)=>` {
|
|
1477
|
-
metric: '${
|
|
1509
|
+
metric: '${t(w.metric)}',
|
|
1478
1510
|
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1479
1511
|
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1480
1512
|
}`).join(`,
|
|
@@ -1485,46 +1517,46 @@ ${m.anomalyRules.map((w)=>` {
|
|
|
1485
1517
|
enabled: true,
|
|
1486
1518
|
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1487
1519
|
},`:"";return` {
|
|
1488
|
-
name: '${
|
|
1520
|
+
name: '${t(m.name)}',
|
|
1489
1521
|
version: ${m.version},
|
|
1490
1522
|
semantics: {
|
|
1491
|
-
what: '${
|
|
1492
|
-
${m.who?`who: '${
|
|
1493
|
-
${m.why?`why: '${
|
|
1523
|
+
what: '${t(m.what)}',
|
|
1524
|
+
${m.who?`who: '${t(m.who)}',`:""}
|
|
1525
|
+
${m.why?`why: '${t(m.why)}',`:""}
|
|
1494
1526
|
},
|
|
1495
1527
|
privacy: '${m.privacy}',
|
|
1496
1528
|
properties: {
|
|
1497
1529
|
${y}
|
|
1498
1530
|
},
|
|
1499
1531
|
${typeof m.retentionDays==="number"?`retention: { days: ${m.retentionDays}, ${m.retentionPolicy?`policy: '${m.retentionPolicy}'`:""} },`:""}
|
|
1500
|
-
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${
|
|
1532
|
+
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${t(m.samplingConditions)}']`:""} },`:""}
|
|
1501
1533
|
${W}
|
|
1502
|
-
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${
|
|
1534
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${t(w)}'`).join(", ")}],`:""}
|
|
1503
1535
|
}`}).join(`,
|
|
1504
1536
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1505
1537
|
|
|
1506
1538
|
export const ${b}: TelemetrySpec = {
|
|
1507
1539
|
meta: {
|
|
1508
|
-
key: '${
|
|
1540
|
+
key: '${t($.name)}',
|
|
1509
1541
|
version: ${$.version},
|
|
1510
|
-
title: '${
|
|
1511
|
-
description: '${
|
|
1512
|
-
domain: '${
|
|
1513
|
-
owners: [${$.owners.map((m)=>`'${
|
|
1514
|
-
tags: [${$.tags.map((m)=>`'${
|
|
1542
|
+
title: '${t($.name)} telemetry',
|
|
1543
|
+
description: '${t($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1544
|
+
domain: '${t($.domain)}',
|
|
1545
|
+
owners: [${$.owners.map((m)=>`'${t(m)}'`).join(", ")}],
|
|
1546
|
+
tags: [${$.tags.map((m)=>`'${t(m)}'`).join(", ")}],
|
|
1515
1547
|
stability: '${$.stability}',
|
|
1516
1548
|
},
|
|
1517
1549
|
config: {
|
|
1518
1550
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1519
1551
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1520
1552
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1521
|
-
${
|
|
1553
|
+
${A}
|
|
1522
1554
|
},
|
|
1523
1555
|
events: [
|
|
1524
|
-
${
|
|
1556
|
+
${n}
|
|
1525
1557
|
],
|
|
1526
1558
|
};
|
|
1527
|
-
`}function
|
|
1559
|
+
`}function e8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function s8($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${t(b)}'`}function $S($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function hW($){return`/**
|
|
1528
1560
|
* ${$.title} Theme
|
|
1529
1561
|
*
|
|
1530
1562
|
* Auto-generated theme spec.
|
|
@@ -1532,7 +1564,7 @@ ${A}
|
|
|
1532
1564
|
|
|
1533
1565
|
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1534
1566
|
|
|
1535
|
-
export const ${
|
|
1567
|
+
export const ${$S($.key)}Theme = defineTheme({
|
|
1536
1568
|
meta: {
|
|
1537
1569
|
key: '${$.key}',
|
|
1538
1570
|
version: '${$.version}',
|
|
@@ -1552,11 +1584,11 @@ export const ${i5($.key)}Theme = defineTheme({
|
|
|
1552
1584
|
},
|
|
1553
1585
|
},
|
|
1554
1586
|
});
|
|
1555
|
-
`}function
|
|
1556
|
-
`),
|
|
1587
|
+
`}function dW($){let b=AS($.name.split(".").pop()??"Workflow")+"Workflow",A=$.steps.map((m)=>bS(m)).join(`,
|
|
1588
|
+
`),n=$.transitions.map((m)=>` {
|
|
1557
1589
|
from: '${m.from}',
|
|
1558
1590
|
to: '${m.to}',
|
|
1559
|
-
${m.condition?` condition: '${
|
|
1591
|
+
${m.condition?` condition: '${yb(m.condition)}',`:""}
|
|
1560
1592
|
}`).join(`,
|
|
1561
1593
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1562
1594
|
|
|
@@ -1572,9 +1604,9 @@ export const ${b}: WorkflowSpec = {
|
|
|
1572
1604
|
meta: {
|
|
1573
1605
|
key: '${$.name}',
|
|
1574
1606
|
version: ${$.version},
|
|
1575
|
-
title: '${
|
|
1576
|
-
description: '${
|
|
1577
|
-
domain: '${
|
|
1607
|
+
title: '${yb($.title)}',
|
|
1608
|
+
description: '${yb($.description)}',
|
|
1609
|
+
domain: '${yb($.domain)}',
|
|
1578
1610
|
stability: '${$.stability}',
|
|
1579
1611
|
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1580
1612
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
@@ -1582,22 +1614,22 @@ export const ${b}: WorkflowSpec = {
|
|
|
1582
1614
|
definition: {
|
|
1583
1615
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1584
1616
|
`:""} steps: [
|
|
1585
|
-
${
|
|
1617
|
+
${A}
|
|
1586
1618
|
],
|
|
1587
1619
|
transitions: [
|
|
1588
|
-
${
|
|
1620
|
+
${n}
|
|
1589
1621
|
],
|
|
1590
1622
|
},
|
|
1591
1623
|
${$.policyFlags.length>0?`policy: {
|
|
1592
1624
|
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1593
1625
|
},`:"// policy: { flags: [] },"}
|
|
1594
1626
|
};
|
|
1595
|
-
`}function
|
|
1596
|
-
`)}function
|
|
1627
|
+
`}function bS($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${yb($.label)}',`];if($.description)b.push(` description: '${yb($.description)}',`);let A=[];if($.operation)A.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)A.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(A.length)b.push(` action: { ${A.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1628
|
+
`)}function AS($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function yb($){return $.replace(/'/g,"\\'")}function NA({exportName:$,specImportPath:b,workflowFunctionName:A}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1597
1629
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1598
1630
|
import { ${$} } from '${b}';
|
|
1599
1631
|
|
|
1600
|
-
export async function ${
|
|
1632
|
+
export async function ${A}(input = {}, bridge = {}) {
|
|
1601
1633
|
"use workflow";
|
|
1602
1634
|
|
|
1603
1635
|
// Keep the workflow function deterministic.
|
|
@@ -1614,7 +1646,7 @@ export async function ${n}(input = {}, bridge = {}) {
|
|
|
1614
1646
|
},
|
|
1615
1647
|
});
|
|
1616
1648
|
}
|
|
1617
|
-
`}function
|
|
1649
|
+
`}function FA($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1618
1650
|
import { ${b} } from '${$}';
|
|
1619
1651
|
|
|
1620
1652
|
export const POST = createWorkflowDevkitStartRoute({
|
|
@@ -1623,17 +1655,17 @@ export const POST = createWorkflowDevkitStartRoute({
|
|
|
1623
1655
|
return [body];
|
|
1624
1656
|
},
|
|
1625
1657
|
});
|
|
1626
|
-
`}function
|
|
1658
|
+
`}function vA(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1627
1659
|
|
|
1628
1660
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1629
1661
|
resolveToken({ runId }) {
|
|
1630
1662
|
return \`workflow-session:\${runId}\`;
|
|
1631
1663
|
},
|
|
1632
1664
|
});
|
|
1633
|
-
`}function
|
|
1665
|
+
`}function gA(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1634
1666
|
|
|
1635
1667
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1636
|
-
`}function
|
|
1668
|
+
`}function PA($,b){return`import { ${b} } from '${$}';
|
|
1637
1669
|
|
|
1638
1670
|
export const workflowDevkitBootstrap = {
|
|
1639
1671
|
workflow: ${b},
|
|
@@ -1645,13 +1677,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1645
1677
|
};
|
|
1646
1678
|
},
|
|
1647
1679
|
};
|
|
1648
|
-
`}function
|
|
1680
|
+
`}function kA({exportName:$,specImportPath:b,runnerName:A,workflowName:n}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1649
1681
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1650
1682
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1651
1683
|
import { ${$} } from '${b}';
|
|
1652
1684
|
|
|
1653
1685
|
/**
|
|
1654
|
-
* Runner wiring for ${
|
|
1686
|
+
* Runner wiring for ${n}.
|
|
1655
1687
|
*
|
|
1656
1688
|
* TODO:
|
|
1657
1689
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1663,7 +1695,7 @@ registry.register(${$});
|
|
|
1663
1695
|
|
|
1664
1696
|
const stateStore = new InMemoryStateStore();
|
|
1665
1697
|
|
|
1666
|
-
export const ${
|
|
1698
|
+
export const ${A} = new WorkflowRunner({
|
|
1667
1699
|
registry,
|
|
1668
1700
|
stateStore,
|
|
1669
1701
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1685,12 +1717,12 @@ export const ${n} = new WorkflowRunner({
|
|
|
1685
1717
|
// console.log(event, payload);
|
|
1686
1718
|
},
|
|
1687
1719
|
});
|
|
1688
|
-
`}import{getAuthoringTargetDefinition as
|
|
1689
|
-
`],[y,`# ${
|
|
1720
|
+
`}import{getAuthoringTargetDefinition as nS}from"@contractspec/module.workspace";var oW={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function iW($,b){let A=mS($,b.specPath),n=yS($,b.target,A),m=$.join(A,"package.json"),y=$.join(A,"README.md"),W=$.join(A,"src"),w=$.join(W,"index.ts"),j=On($.relative(W,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(W);let B=[[m,JSON.stringify({name:n,version:"0.1.0",description:oW[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1721
|
+
`],[y,`# ${n}
|
|
1690
1722
|
|
|
1691
|
-
${
|
|
1723
|
+
${oW[b.target]}.
|
|
1692
1724
|
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1693
|
-
`],[b.specPath,b.specCode]],S={packageRoot:
|
|
1725
|
+
`],[b.specPath,b.specCode]],S={packageRoot:A,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function rA($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1694
1726
|
|
|
1695
1727
|
export const ${$.exportName} = defineModuleBundle({
|
|
1696
1728
|
meta: {
|
|
@@ -1759,22 +1791,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1759
1791
|
supportedArtifactTypes: ["patch"],
|
|
1760
1792
|
knownConstraints: [],
|
|
1761
1793
|
};
|
|
1762
|
-
`}}function
|
|
1794
|
+
`}}function mS($,b){let A=On(b),n="/src/",m=A.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return A.slice(0,m)}function yS($,b,A){let n=nS(b),m=On($.basename(A));return`${n.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${m}`}function On($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function wb($,b,A,n={}){let{fs:m,logger:y,workspace:W}=b,w=W?.scanSpecSource??ZS,j=W?.inferSpecTypeFromFilePath??QS,B=W?.generateHandlerTemplate??jS,S=W?.generateComponentTemplate??wS,Q=W?.generateTestTemplate??BS,{targets:Z=void 0,outputDir:X=A.outputDir,overwrite:Y=!1,dryRun:H=!1,includeTests:J=!1,runtimeGeneration:O}=n,V=await m.readFile($),U=w(V,$),K=WS(V,$),q=K==="unknown"?j($):K,G=Z??Un(q,{includeTests:J});y.info(`Building from spec: ${$}`,{targetId:q});let z=[],_={};for(let L of G)try{let I=await XS(L,$,V,U,q,{fs:m,logger:y},X,Y,H,O,_,{genHandler:B,genComponent:S,genTest:Q});if(z.push(I),I.success&&I.generatedCode)_[L]=I.generatedCode}catch(I){z.push({target:L,outputPath:"",success:!1,error:I instanceof Error?I.message:String(I),skipped:!1})}return{specPath:$,specInfo:U,targetId:q,results:z}}async function XS($,b,A,n,m,y,W,w,j,B,S,Q){let{fs:Z,logger:X}=y,{genHandler:Y,genComponent:H,genTest:J}=Q,O,V,U=[];switch($){case"handler":{if(m!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${m})`};let G=n.kind==="command"||n.kind==="query"?n.kind:"command",z=Y($$(A,n,b),G);V=Wb(b,W,"handlers",$$(A,n,b),".handler.ts",y.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:A,outputPath:V,fallbackCode:z})??z;break}case"component":{if(m!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${m})`};let G=H($$(A,n,b),n.description??"");V=Wb(b,W,"components",$$(A,n,b),".tsx",y.fs),O=await B?.generateArtifact?.({kind:"component",specCode:A,outputPath:V,fallbackCode:G})??G;break}case"test":{let G=m==="operation"?"handler":"component",z=m==="operation"?S.handler??"":m==="presentation"?S.component??"":m==="form"?S.form??"":"",_=J($$(A,n,b),G);V=Wb(b,W,"__tests__",$$(A,n,b),".test.ts",y.fs),O=await B?.generateTest?.({kind:G,specCode:A,outputPath:V,existingCode:z,fallbackCode:_})??_;break}case"form":{if(m!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${m})`};let G=`import * as React from "react";
|
|
1763
1795
|
|
|
1764
|
-
export interface ${
|
|
1796
|
+
export interface ${J$($$(A,n,b))}Props {
|
|
1765
1797
|
className?: string;
|
|
1766
1798
|
}
|
|
1767
1799
|
|
|
1768
|
-
export function ${
|
|
1800
|
+
export function ${J$($$(A,n,b))}Form({
|
|
1769
1801
|
className,
|
|
1770
|
-
}: ${
|
|
1771
|
-
return <form className={className}>TODO: implement ${
|
|
1802
|
+
}: ${J$($$(A,n,b))}Props) {
|
|
1803
|
+
return <form className={className}>TODO: implement ${$$(A,n,b)}</form>;
|
|
1772
1804
|
}
|
|
1773
|
-
`;
|
|
1805
|
+
`;V=Wb(b,W,"forms",$$(A,n,b),".form.tsx",y.fs),O=await B?.generateArtifact?.({kind:"form",specCode:A,outputPath:V,fallbackCode:G})??G;break}case"workflow-runner":{if(m!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${m})`};let G=$$(A,n,b),z=qS(A)??`${J$(G)}Workflow`,_=`${J$(G)}Runner`,L=Vn(G);if(V=Wb(b,W,"workflows",G,".runner.ts",y.fs),O=kA({exportName:z,specImportPath:Jn(y.fs,V,b),runnerName:_,workflowName:G}),US(A)){let I=`${J$(G)}WorkflowDevkit`,E=Lb(y.fs,V,`${L}.workflow-devkit.ts`),N=Lb(y.fs,V,`${L}.workflow-devkit.start.route.ts`),M=Lb(y.fs,V,`${L}.workflow-devkit.follow-up.route.ts`),r=Lb(y.fs,V,`${L}.workflow-devkit.stream.route.ts`),g=Lb(y.fs,V,`${L}.workflow-devkit.generic.ts`);U=[{path:E,code:NA({exportName:z,specImportPath:Jn(y.fs,E,b),workflowFunctionName:I})},{path:N,code:FA(lW(y.fs,N,E),I)},{path:M,code:vA()},{path:r,code:gA()},{path:g,code:PA(lW(y.fs,g,E),I)}]}break}case"data-view-renderer":{if(m!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${m})`};let G=$$(A,n,b),z=OS(A)??`${J$(G)}DataView`,_=`${J$(G)}Renderer`;V=Wb(b,W,"data-views",G,".renderer.tsx",y.fs),O=TA({exportName:z,specImportPath:Jn(y.fs,V,b),rendererName:_,viewKind:JS(A)??"table"});break}case"package-scaffold":{if(m!=="module-bundle"&&m!=="builder-spec"&&m!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${m})`};if(j){let _=HS(b);return X.info(`[dry-run] Would scaffold package: ${_}`),{target:$,outputPath:_,success:!0}}let G=A.trim().length>0?A:rA({target:m,key:n.key??y.fs.basename(b),title:n.key??y.fs.basename(b),description:n.description??SS(m).title,exportName:J$(n.key??y.fs.basename(b))});return V=(await iW(y.fs,{target:m,specPath:b,specCode:G,overwrite:w})).packageRoot,X.info(`Generated package scaffold: ${V}`),{target:$,outputPath:V,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let K=[{path:V,code:O},...U],q=w?void 0:await YS(K,Z);if(q)return{target:$,outputPath:q,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(j){for(let G of K)X.info(`[dry-run] Would write: ${G.path}`);return{target:$,outputPath:V,success:!0,generatedCode:K[0]?.code}}for(let G of K)await Z.mkdir(Z.dirname(G.path)),await Z.writeFile(G.path,VS(G.code)),X.info(`Generated: ${G.path}`);return{target:$,outputPath:V,success:!0}}function Un($,b){switch($){case"operation":return b.includeTests?["handler","test"]:["handler"];case"presentation":return b.includeTests?["component","test"]:["component"];case"form":return b.includeTests?["form","test"]:["form"];case"workflow":return["workflow-runner"];case"data-view":return["data-view-renderer"];case"module-bundle":case"builder-spec":case"provider-spec":return["package-scaffold"];default:return[]}}function Wb($,b,A,n,m,y){let W=Vn(n.split(".").pop()??"unknown"),w;if(b.startsWith("."))w=y.resolve(y.dirname($),"..",b,A);else w=y.resolve(b,A);return y.join(w,`${W}${m}`)}async function YS($,b){for(let A of $)if(await b.exists(A.path))return A.path;return}function Vn($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function J$($){return Vn($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Kn($){return $.replace(/\.[^.]+$/,"")}function HS($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Jn($,b,A){let n=Kn($.relative($.dirname(b),A));return n.startsWith(".")?n:`./${n}`}function lW($,b,A){let n=Kn($.relative($.dirname(b),A));return n.startsWith(".")?n:`./${n}`}function Lb($,b,A){return $.join($.dirname(b),A)}function $$($,b,A){return GS($,"name")??b.key??Kn(KS(A))}function GS($,b){let A=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(A)?.[1]??null}function qS($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function OS($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function JS($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function US($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function VS($){return $.endsWith(`
|
|
1774
1806
|
`)?$:`${$}
|
|
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+=`
|
|
1807
|
+
`}function KS($){return $.replaceAll("\\","/").split("/").pop()??$}b$();import{scanAllSpecsFromSource as CS,scanSpecSource as xS}from"@contractspec/module.workspace";import MS from"micromatch";var eW={};f(eW,{validators:()=>IS,urlSchema:()=>RS,isValidVersion:()=>zS,isValidIdentifier:()=>pW,isValidDotName:()=>aW,isTestFile:()=>Rb,isLibraryDefinitionFile:()=>Ib,emailSchema:()=>LS});import _n from"micromatch";function Rb($,b){let A=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _n.isMatch($,A)}function Ib($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(_n.isMatch($,b))return!1;let A=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return _n.isMatch($,A)}import*as U$ from"zod";function pW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function aW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function zS($){return Number.isInteger($)&&$>0}var LS=U$.string().email(),RS=U$.string().url(),IS={specName:U$.string().refine(aW,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:U$.number().int().positive(),identifier:U$.string().refine(pW,{message:"Must be a valid TypeScript identifier"}),owner:U$.string().startsWith("@"),tag:U$.string().min(1)};function Cb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function ES($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],A=[...Cb($?.conventions.models),...Cb($?.conventions.operations),...Cb($?.conventions.events),...Cb($?.conventions.presentations),...Cb($?.conventions.forms)];return[...new Set(b.flatMap((n)=>{let m=n==="**"?"":`${n}/`,y=q$.map((w)=>`${m}${w}`),W=A.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function TS($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function DS($,b){let A=$.filePath.localeCompare(b.filePath);if(A!==0)return A;let n=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(n!==0)return n;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function h$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((A,n)=>A.localeCompare(n));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:ES(b.config)})}async function cA($,b={}){let A=await h$($.fs,b),n=b.type?Array.isArray(b.type)?b.type:[b.type]:[],m=[];for(let y of A){if(b.config?.excludePackages&&MS.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||Rb(y,b.config)||Ib(y))continue;try{let W=await $.fs.readFile(y),w=CS(W,y),j=w.length>0?w:[xS(W,y)];for(let B of j)if(TS(B,b,n))m.push(B)}catch{}}return m.sort(DS)}function L$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function hA($){let b=JSON.parse($),A=new Map,n=0,m=0,y=0,W=0,w=0,j=0,B=0,S=0;for(let[Z,X]of Object.entries(b)){let Y=NS(Z,X);A.set(Z,Y),n+=Y.statements.total,m+=Y.statements.covered,y+=Y.branches.total,W+=Y.branches.covered,w+=Y.functions.total,j+=Y.functions.covered,B+=Y.lines.total,S+=Y.lines.covered}let Q={statements:{covered:m,total:n,pct:L$(m,n)},branches:{covered:W,total:y,pct:L$(W,y)},functions:{covered:j,total:w,pct:L$(j,w)},lines:{covered:S,total:B,pct:L$(S,B)}};return{files:A,total:Q}}function NS($,b){let A=Object.keys(b.statementMap).length,n=Object.values(b.s).filter((S)=>S>0).length,m=Object.keys(b.fnMap).length,y=Object.values(b.f).filter((S)=>S>0).length,W=0,w=0;for(let S of Object.values(b.b))W+=S.length,w+=S.filter((Q)=>Q>0).length;let j=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(j.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:n,total:A,pct:L$(n,A)},branches:{covered:w,total:W,pct:L$(w,W)},functions:{covered:y,total:m,pct:L$(y,m)},lines:{covered:B.size,total:j.size,pct:L$(B.size,j.size)}}}function zn($){switch($){case"istanbul":return{parse:hA};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function Ln($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function Rn($,b,A,n){let m=[];if(A.statements!==void 0&&n.statements.pct<A.statements)m.push({metric:"statements",required:A.statements,actual:n.statements.pct,message:`Statement coverage ${n.statements.pct}% is below required ${A.statements}%`});if(A.branches!==void 0&&n.branches.pct<A.branches)m.push({metric:"branches",required:A.branches,actual:n.branches.pct,message:`Branch coverage ${n.branches.pct}% is below required ${A.branches}%`});if(A.functions!==void 0&&n.functions.pct<A.functions)m.push({metric:"functions",required:A.functions,actual:n.functions.pct,message:`Function coverage ${n.functions.pct}% is below required ${A.functions}%`});if(A.lines!==void 0&&n.lines.pct<A.lines)m.push({metric:"lines",required:A.lines,actual:n.lines.pct,message:`Line coverage ${n.lines.pct}% is below required ${A.lines}%`});if(A.mutations!==void 0)m.push({metric:"mutations",required:A.mutations,actual:0,message:`Mutation coverage required (${A.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:A,actual:n,passed:m.length===0,failures:m}}async function In($,b,A){let{fs:n,logger:m}=$,y=[],W=A.workspaceRoot?`${A.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await n.exists(X)){j=await n.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=Ln(B??"coverage.json"),Z=zn(S).parse(j);for(let X of b){if(X.specType!=="test-spec"||!X.key||!X.version||!X.sourceBlock)continue;let Y=X.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!Y||!Y[1])continue;let H=Y[1],J={},O=H.match(/statements\s*:\s*(\d+)/);if(O&&O[1])J.statements=parseInt(O[1],10);let V=H.match(/branches\s*:\s*(\d+)/);if(V&&V[1])J.branches=parseInt(V[1],10);let U=H.match(/functions\s*:\s*(\d+)/);if(U&&U[1])J.functions=parseInt(U[1],10);let K=H.match(/lines\s*:\s*(\d+)/);if(K&&K[1])J.lines=parseInt(K[1],10);if(Object.keys(J).length===0)continue;let q=Rn(X.key,X.version,J,Z.total);for(let G of q.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:G.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:G.metric,required:G.required,actual:G.actual}})}return y}b$();import{addContractNode as FS,buildReverseEdges as vS,createContractGraph as gS,detectCycles as PS,findMissingDependencies as kS,parseImportedSpecNames as rS,toDot as fS}from"@contractspec/module.workspace";async function sW($,b={}){let{fs:A}=$,n=await h$(A,{config:b.config,pattern:b.pattern}),m=gS();for(let w of n){let j=await A.readFile(w),B=A.relative(".",w),S=A.basename(w).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=rS(j,w);FS(m,S,B,Q)}vS(m);let y=PS(m),W=kS(m);return{graph:m,total:m.size,cycles:y,missing:W}}function EO($,b){return $.get(b)}function TO($){return fS($)}function DO($){let b=Array.from($.values()),A=b.filter((W)=>W.dependencies.length>0),n=b.filter((W)=>W.dependencies.length===0),m=b.filter((W)=>W.dependents.length>0),y=b.filter((W)=>W.dependents.length===0);return{total:$.size,withDeps:A.length,withoutDeps:n.length,used:m.length,unused:y.length}}async function Cn($,b){let A=[],n=await P($.fs),m=await sW($,{config:n,pattern:b.pattern});for(let y of m.cycles)A.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${y.join(" \u2192 ")}`,category:"deps",context:{cycle:y}});for(let y of m.missing)for(let W of y.missing)A.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${y.contract} requires ${W}`,category:"deps",context:{contract:y.contract,missing:W}});return A}import{analyzePackageDocBlocks as cS}from"@contractspec/module.workspace";var hS=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function dS($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:hS}),n=new Map;for(let W of A){let w=$.dirname(W),j=$.join(w,"src");if(!await $.exists(j))continue;try{let B=JSON.parse(await $.readFile(W));n.set(w,{packageName:B.name??$.relative(b,w),packageRoot:w,srcRoot:j})}catch{continue}}let m=$.join(b,"package.json"),y=$.join(b,"src");if(await $.exists(m)&&await $.exists(y))try{let W=JSON.parse(await $.readFile(m));n.set(b,{packageName:W.name??b,packageRoot:b,srcRoot:y})}catch{}return[...n.values()].sort((W,w)=>W.packageRoot.localeCompare(w.packageRoot))}async function dA($,b){let A=[],n=await dS($,b);for(let m of n){let y=cS({packageName:m.packageName,srcRoot:m.srcRoot});for(let W of y.diagnostics)A.push({...W,packageName:m.packageName,packageRoot:m.packageRoot,srcRoot:m.srcRoot})}return A}async function xn($,b){let A=b.workspaceRoot??process.cwd();return(await dA($.fs,A)).map((m)=>({ruleId:m.ruleId,severity:m.severity==="warning"?"warning":"error",message:m.message,category:"docs",file:m.file,line:m.line,column:m.column,context:{packageName:m.packageName,packageRoot:m.packageRoot,...m.context}}))}async function Mn($,b,A){let n=[],m=await uS($,b);if(n.push(m),m.status==="pass")n.push(await oS($,b,A));return n}async function uS($,b){let A=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(A))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let m=await $.readFile(A),y=JSON.parse(m),W=y.aiProvider??"claude",w=y.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${W}, Model: ${w}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function oS($,b,A){let n=$.join(b.workspaceRoot,".contractsrc.json");try{let m=await $.readFile(n),W=JSON.parse(m).aiProvider??"claude",j={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[W];if(!j)return{category:"ai",name:"API Key",status:"pass",message:`${W} does not require an API key`};if(!!process.env[j])return{category:"ai",name:"API Key",status:"pass",message:`${j} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${j} not set`,details:`Set ${j} in your environment to use AI features`,fix:A?{description:`Set ${j} environment variable`,apply:async()=>{let S=await A.input(`Enter your ${W} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${j}=`))return{success:!1,message:`${j} already in .env, update manually`};Z+=`
|
|
1776
1808
|
`}return Z+=`${j}=${S}
|
|
1777
|
-
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${j} to .env (restart required)`}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as
|
|
1809
|
+
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${j} to .env (restart required)`}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as iS}from"child_process";import{promisify as lS}from"util";var uA=lS(iS);async function En($,b){let A=[];return A.push(await tS(b)),A.push(await pS(b)),A.push(await aS($,b)),A}async function tS($){try{return await uA("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4}),{category:"cli",name:"CLI Accessible",status:"pass",message:"ContractSpec CLI is accessible"}}catch{return{category:"cli",name:"CLI Accessible",status:"fail",message:"ContractSpec CLI is not accessible",details:'Could not run "bunx contractspec --version"',fix:{description:"Install ContractSpec CLI globally",apply:async()=>{try{return await uA("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(b){return{success:!1,message:`Failed to install: ${b instanceof Error?b.message:String(b)}`}}}}}}}async function pS($){try{let{stdout:b}=await uA("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${b.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function aS($,b){let A=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(A))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let w=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(w))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let m=await $.readFile(A),y=JSON.parse(m);if(y.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||y.devDependencies?.["@contractspec/app.cli-contractspec"]!==void 0)return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is installed as a project dependency"};return{category:"cli",name:"Local Installation",status:"warn",message:"CLI is not installed as a project dependency",details:"Consider adding @contractspec/app.cli-contractspec to devDependencies",fix:{description:"Add CLI as a dev dependency",apply:async()=>{try{return await uA("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(w){return{success:!1,message:`Failed to install: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}b$();import{DEFAULT_CONTRACTSRC as oA}from"@contractspec/lib.contracts-spec/workspace-config";import{join as eS,relative as sS}from"path";var $9="contractspec",b9="contractsrc.schema.json";function A9($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function xb($){return A9(sS($.configRoot,eS($.workspaceRoot,"node_modules",$9,b9)))}var Mb=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],$w={"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)"},bw=["core","connect","builder-managed","builder-local","builder-hybrid"],Aw={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 Eb={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function Tb($){if($?.builder?.enabled)switch($.builder.runtimeMode){case"local":return"builder-local";case"hybrid":return"builder-hybrid";default:return"builder-managed"}if($?.connect?.enabled)return"connect";return"core"}function R$($){return $.preset??"core"}function mw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return Mb}}function Tn($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function yw($){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 aO($){return $==="connect"}function Ww($){let b=R$($),A=n9($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset managed-mvp`,`contractspec builder status --workspace-id ${A}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function n9($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function ww($){let b=R$($),A=[Eb.verificationCache];if(b==="connect")A.unshift(Eb.connect);return A}function jb($){let b=$.isMonorepo&&$.scope==="package",A=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,n=m9($),m=y9($);return{$schema:xb({configRoot:A,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...n?{connect:n}:{},...m?{builder:m}:{},...b&&$.packageName?{package:$.packageName}:{}}}function iA($){let b=R$($),A={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(Tn(b))A["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return A}function Db(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function jw(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function Bw($){let b=$.projectName??"this project",n=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1778
1810
|
|
|
1779
1811
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1780
1812
|
|
|
@@ -1795,10 +1827,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1795
1827
|
## Contract Locations
|
|
1796
1828
|
|
|
1797
1829
|
Contracts are located in:
|
|
1798
|
-
- \`${
|
|
1799
|
-
- \`${
|
|
1800
|
-
- \`${
|
|
1801
|
-
- \`${
|
|
1830
|
+
- \`${n}/operations/\` - Command and query specs
|
|
1831
|
+
- \`${n}/events/\` - Event specs
|
|
1832
|
+
- \`${n}/presentations/\` - UI presentation specs
|
|
1833
|
+
- \`${n}/features/\` - Feature module specs
|
|
1802
1834
|
|
|
1803
1835
|
## When Making Changes
|
|
1804
1836
|
|
|
@@ -1840,7 +1872,7 @@ defineCommand({
|
|
|
1840
1872
|
- Events must be declared in contracts before being emitted.
|
|
1841
1873
|
- UI components should reference presentation contracts.
|
|
1842
1874
|
- Feature flags should be defined in feature modules.
|
|
1843
|
-
`}function
|
|
1875
|
+
`}function Sw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package",n=R$($),m=A&&$.packageName?`${$.packageName} package`:b,y="src/contracts",W=$.isMonorepo?A?`
|
|
1844
1876
|
## Monorepo Scope
|
|
1845
1877
|
|
|
1846
1878
|
This guide is scoped to the current package.
|
|
@@ -1900,8 +1932,8 @@ ${W}
|
|
|
1900
1932
|
|
|
1901
1933
|
## Initialization Preset
|
|
1902
1934
|
|
|
1903
|
-
- This workspace was initialized with the \`${
|
|
1904
|
-
`}function
|
|
1935
|
+
- This workspace was initialized with the \`${n}\` setup preset.
|
|
1936
|
+
`}function Qw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1905
1937
|
|
|
1906
1938
|
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1907
1939
|
|
|
@@ -1930,68 +1962,68 @@ This workspace uses ContractSpec to keep contracts, generated artifacts, and AI
|
|
|
1930
1962
|
|
|
1931
1963
|
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1932
1964
|
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1933
|
-
`}function
|
|
1934
|
-
`}async function N0($,b){let n=[];return n.push(await 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
|
|
1936
|
-
${$.details}`;if($.fix)
|
|
1937
|
-
Fix available: ${$.fix.description}`;return
|
|
1938
|
-
|
|
1939
|
-
${$.body}`;await m.writeFile(w,j)}async function
|
|
1940
|
-
`).length},W,w=new RegExp(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 ${
|
|
1943
|
-
meta: ${
|
|
1944
|
-
${
|
|
1965
|
+
`}function m9($){if(R$($)!=="connect")return;return{...oA.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin",packageRef:"contractspec-adoption"},codex:{enabled:!0,mode:"wrapper",packageRef:"contractspec-adoption"},"claude-code":{enabled:!0,mode:"rule",packageRef:"contractspec-adoption"}},adoption:{...oA.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:oA.connect?.studio}}function y9($){let b=Tn(R$($)),A=yw(R$($));if(!b||!A)return;let n=!0,m=b==="local"||b==="hybrid";return{...oA.builder,enabled:!0,runtimeMode:b,bootstrapPreset:A,api:n?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:m?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function lA(){let $=process.platform,b=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${b}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??b}/Claude/claude_desktop_config.json`;default:return`${b}/.config/claude/claude_desktop_config.json`}}function A$($,b){let A={...$};for(let n of Object.keys(b)){let m=$[n],y=b[n];if(m===void 0)A[n]=y;else if(tA(m)&&tA(y))A[n]=A$(m,y)}return A}function Dn($,b){let A={...$};for(let n of Object.keys(b)){let m=$[n],y=b[n];if(y===void 0)continue;if(tA(m)&&tA(y))A[n]=Dn(m,y);else A[n]=y}return A}function tA($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function a($){try{return JSON.parse($)}catch{return null}}function F($){return JSON.stringify($,null,2)+`
|
|
1966
|
+
`}async function Nn($,b){let A=[];return A.push(await W9($,b)),A.push(await w9($,b)),A.push(await j9($,b)),A.push(await B9($,b)),A.push(await S9($,b)),A.push(await Q9($,b)),A.push(await Z9($,b)),A}async function d$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function W9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(await $.exists(A))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let m=jb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,F(m)),{success:!0,message:"Created .contractsrc.json"}}catch(m){return{success:!1,message:`Failed to create: ${m instanceof Error?m.message:String(m)}`}}}}}}async function w9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A);return JSON.parse(m),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(m){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:m instanceof Error?m.message:String(m),fix:{description:"Replace with valid default config",apply:async()=>{try{let W=jb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,F(W)),{success:!0,message:"Replaced with valid config"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function j9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A),y=JSON.parse(m),W=[];if(!y.outputDir)W.push("outputDir");if(!y.conventions)W.push("conventions");if(W.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${W.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let w=jb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let j of W)if(w[j]!==void 0)y[j]=w[j];return await $.writeFile(A,F(y)),{success:!0,message:"Added missing fields"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function B9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A),y=JSON.parse(m);if(y.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:y.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return y.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(A,F(y)),{success:!0,message:"Added versioning configuration"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function S9($,b){let A=$.join(await d$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(A),y=JSON.parse(m);if(y.hooks){let j=y.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(j).length} git hook(s) configured`}}let W=$.join(b.workspaceRoot,".husky");if(await $.exists(W))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return y.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(A,F(y)),{success:!0,message:"Added hooks configuration"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function Q9($,b){let A=await d$($,b),n=await P($,A),m=Tb(n);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[n.connect?.storage?.root?null:"storage.root",n.connect?.storage?.contextPack?null:"storage.contextPack",n.connect?.storage?.planPacket?null:"storage.planPacket",n.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),j=n.connect?.studio?.enabled&&n.connect?.studio?.mode==="review-bridge"&&!n.connect?.studio?.endpoint;if(w.length===0&&!j)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...w,...j?["connect.studio.endpoint"]:[]].join(", ")}`}}let y=[],W=n.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!n.builder?.api?.baseUrl)y.push("builder.api.baseUrl");if(m.startsWith("builder-")&&!W)y.push("builder.api.controlPlaneTokenEnvVar");if(m.startsWith("builder-")&&W&&!process.env[W])y.push(`env:${W}`);if((m==="builder-local"||m==="builder-hybrid")&&!n.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!n.builder?.localRuntime?.grantedTo)y.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:y.length===0?"pass":"warn",message:y.length===0?`Builder preset inferred (${m}) and required config is present`:`Builder preset inferred (${m}) but setup is missing ${y.join(", ")}`}}async function Z9($,b){let A=await d$($,b),n=await P($,A),m=Tb(n);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(A,".vscode","settings.json"),W=n.builder?.api?.baseUrl;if(!W)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let w=await $.readFile(y).catch(()=>""),j=w?a(w):void 0;if(j?.["contractspec.api.baseUrl"]===W)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(A,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...iA({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,F(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as X9}from"child_process";import{promisify as Y9}from"util";var u$=Y9(X9);async function Fn($,b){let A=[];return A.push(await H9(b)),A.push(await G9(b)),A.push(await q9($,b)),A.push(await O9($,b)),A.push(await J9($,b)),A}async function H9($){try{let{stdout:b}=await u$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function G9($){try{let{stdout:b}=await u$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function q9($,b){let A=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],n=null;for(let{file:m,name:y}of A){let W=$.join(b.workspaceRoot,m);if(await $.exists(W)){n=y;break}}if(!n){let m=$.join(b.workspaceRoot,".."),y=$.join(b.workspaceRoot,"../.."),W=[m,y];for(let w of W){for(let{file:j,name:B}of A){let S=$.join(w,j);if(await $.exists(S)){n=B;break}}if(n)break}}if(!n)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await u$(`${n} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${n}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${n} detected but not available`,details:`Install ${n} or use a different package manager`}}}async function O9($,b){let A=$.join(b.workspaceRoot,"node_modules");if(await $.exists(A))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await u$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await u$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function J9($,b){let A=$.join(b.workspaceRoot,"package.json");try{let n=await $.readFile(A),m=JSON.parse(n),y={...m.dependencies,...m.devDependencies};if("@contractspec/lib.contracts-spec"in y)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${y["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await u$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await u$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function vn($,b){let A=await dA($,b.workspaceRoot);if(A.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return A.map((n)=>({category:"docs",name:`Same-File DocBlocks (${n.packageName})`,status:n.severity==="warning"?"warn":"fail",message:n.message,details:$.relative(b.workspaceRoot,n.file),context:{ruleId:n.ruleId,file:n.file,line:n.line,column:n.column,packageName:n.packageName}}))}import{isExampleFile as U9,isFeatureFile as V9,scanAllSpecsFromSource as K9,scanExampleSource as _9,scanFeatureSource as z9}from"@contractspec/module.workspace";function L9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function pA($,b={}){let{fs:A,logger:n}=$,m=L9(),y=b.pattern??"**/*.{ts,tsx}";n.info("Scanning for contract layer files...");let W=await A.glob({pattern:y});for(let j of W){if(j.includes("node_modules")||j.includes("/dist/"))continue;try{let B=await A.readFile(j);if(V9(j)){let S=z9(B,j);m.features.set(S.key,S);continue}if(U9(j)){let S=_9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=K9(B,j);for(let Q of S)if(Q.specType==="app-config"&&Q.key)m.appConfigs.set(Q.key,Q)}}catch{}}try{let j=await A.glob({pattern:"**/.contractsrc.json"});for(let B of j){if(B.includes("node_modules"))continue;try{let S=await A.readFile(B),Q=JSON.parse(S);m.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){m.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let w={features:m.features.size,examples:m.examples.size,appConfigs:m.appConfigs.size,workspaceConfigs:m.workspaceConfigs.size,total:m.features.size+m.examples.size+m.appConfigs.size+m.workspaceConfigs.size};return n.info(`Discovered ${w.features} features, ${w.examples} examples, ${w.appConfigs} app configs, ${w.workspaceConfigs} workspace configs`),{inventory:m,stats:w}}function HJ($){let b=[];for(let[A,n]of $.features)b.push({key:A,file:n.filePath,type:"feature"});for(let[A,n]of $.examples)b.push({key:A,version:n.version,file:n.filePath,type:"example"});for(let[A,n]of $.appConfigs)b.push({key:A,version:n.version,file:n.filePath,type:"app-config"});for(let[,A]of $.workspaceConfigs)b.push({key:A.file,file:A.file,type:"workspace-config"});return b}function aA($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function gn($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function eA($,b){let A=$.join(b,"config/stability-policy.json");if(!await $.exists(A))return;try{let n=await $.readFile(A),m=JSON.parse(n);return{version:typeof m.version==="number"&&Number.isFinite(m.version)?m.version:1,criticalPackages:gn(m.criticalPackages).map(aA),criticalFeatureKeys:gn(m.criticalFeatureKeys),smokePackages:gn(m.smokePackages)}}catch{return}}function Zw($,b){let A=aA($);if(b?.criticalPackages.includes(A))return"critical";return"non-critical"}function Xw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function Bb($){return aA(`${aA($)}/config/stability-policy.json`)}async function Pn($,b){let A=[],n=await eA($,b.workspaceRoot),m=await pA({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return A.push(R9(m.stats.features)),A.push(I9(m.stats.examples)),A.push(C9(m.inventory.features,n,b)),A.push(x9(m.inventory.examples)),A.push(M9(m.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 I9($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function C9($,b,A){let n=[],m=[];for(let[y,W]of $)if(!(Boolean(W.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(W.sourceBlock??"")))if(Xw(y,b))m.push(y);else n.push(y);if(m.length===0&&n.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:b?Bb(A.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:m.length>0?"fail":"warn",message:m.length>0?`${m.length} critical feature(s) missing owners`:`${n.length} feature(s) missing owners`,details:m.length>0?`Critical features: ${m.join(", ")}`:`Features: ${n.slice(0,3).join(", ")}${n.length>3?"...":""}`,context:{policyPath:b?Bb(A.workspaceRoot):void 0,criticalMissingFeatures:m,missingFeatures:n}}}function x9($){let b=[];for(let[A,n]of $)if(!n.entrypoints.packageName)b.push(A);if(b.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function M9($){let b=[];for(let[,A]of $)if(!A.valid)b.push(A.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function kn($,b){let A=[];return A.push(await E9($,b)),A.push(await T9($,b)),A.push(await D9($,b)),A}async function E9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(A))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Db();return await $.writeFile(A,F(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function T9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(A))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let m=await $.readFile(A),y=JSON.parse(m);if(y.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let w=Db(),j=A$(y,w);return await $.writeFile(A,F(j)),{success:!0,message:"Registered MCP server"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function D9($,b){let A=lA();try{if(!await $.exists(A))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let m=await $.readFile(A);if(JSON.parse(m).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var N9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Yw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function F9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,n])=>{if(typeof n==="string")b[A]=n;return b},{})}function v9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function g9($,b,A){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:Yw}),m=[];for(let y of n){let W=$.dirname(y),w=$.relative(b,W);try{let j=JSON.parse(await $.readFile(y)),B=F9(j.scripts),S=await $.glob({patterns:N9,cwd:W,ignore:Yw});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:v9(B),testFileCount:S.length,tier:Zw(w,A)})}catch{continue}}return m}function P9($){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 k9($){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 Hw($,b,A){let n=await g9($,b,A),m=[];for(let W of n){if(W.tier==="critical")m.push(...P9(W));m.push(...k9(W))}let y=n.filter((W)=>W.tier==="critical").map((W)=>({packageName:W.packageName,packagePath:W.packagePath,hasBuildScript:W.hasBuildScript,hasTypecheckScript:W.hasTypecheckScript,hasLintScript:W.hasLintScript,hasTestScript:W.hasTestScript,usesPassWithNoTests:W.usesPassWithNoTests,testFileCount:W.testFileCount}));return{findings:m,criticalPackages:y}}function qw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Gw($,b,A,n){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:n,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||A.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:qw(b),context:{findings:b}}}async function Ow($,b){let A=await eA($,b.workspaceRoot);if(!A)return[];let n=await Hw($,b.workspaceRoot,A),m=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),y=n.findings.filter((j)=>m.has(j.code)),W=n.findings.filter((j)=>j.code==="tests-without-test-script"),w=n.findings.filter((j)=>j.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:y.length>0?"fail":"pass",message:y.length>0?`${y.length} critical package gate failure(s)`:`All ${n.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?qw(y):b.verbose?`Policy: ${Bb(b.workspaceRoot)}`:void 0,context:{policyPath:Bb(b.workspaceRoot),criticalPackages:n.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 r9=["src/contracts","contracts","src/specs","specs"];async function rn($,b){let A=[];return A.push(f9(b)),A.push(await c9($,b)),A.push(await h9($,b)),A.push(await d9($,b)),A.push(await o9($,b)),A.push(...await Ow($,b)),A}function f9($){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 c9($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let n of A){let m=$.join(n,"package.json");if(await $.exists(m))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${n}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function h9($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],n=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let W of A)for(let w of r9){let j=$.join(W,w);if(await $.exists(j)){let B=W===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${w}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let m=b.isMonorepo?"src/contracts":"src/contracts",y=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${m}/${y} to organize your specs`,fix:{description:`Create ${m}/ directory${y}`,apply:async()=>{try{let W=$.join(n,"src","contracts");return await $.mkdir(W),{success:!0,message:`Created ${m}/`}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}async function d9($,b){try{let A=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],n=b.isMonorepo?b.packageRoot:b.workspaceRoot,m=await $.glob({patterns:A,ignore:["node_modules/**","dist/**"],cwd:n});if(m.length>0){let W=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${m.length} contract file(s)${W}`,details:b.verbose?m.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:b.isMonorepo?`No contract files found in package "${b.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function u9($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let n=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(n))return{path:n,root:b.packageRoot,level:"package"}}let A=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.workspaceRoot,level:"workspace"};return null}async function o9($,b){try{let A=await u9($,b);if(!A)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let n=await $.readFile(A.path),m=JSON.parse(n),y=m.outputDir??"./src",W=$.join(A.root,y),w=b.isMonorepo?` (${A.level} level)`:"";if(await $.exists(W))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${y}${w}`,details:b.verbose?`Resolved to: ${W}`:void 0};let B=y==="./src"||y==="src",S=Array.isArray(m.packages)&&m.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||A.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${A.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${y}${w}`,details:b.verbose?`Expected at: ${W}`:void 0,fix:{description:`Create ${y} directory`,apply:async()=>{try{return await $.mkdir(W),{success:!0,message:`Created ${y}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var Jw=["cli","config","mcp","deps","docs","workspace","ai","layers"],Uw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var i9={checks:{runCliChecks:En,runConfigChecks:Nn,runMcpChecks:kn,runDepsChecks:Fn,runDocChecks:vn,runWorkspaceChecks:rn,runAiChecks:Mn,runLayerChecks:Pn},workspace:{findWorkspaceRoot:x,findPackageRoot:c,isMonorepo:Ub,getPackageName:P$}},l9={confirm:async()=>!1,input:async()=>""};async function Vw($,b,A=l9,n=i9){let{fs:m,logger:y}=$,W=b.categories??Jw,{checks:w,workspace:j}=n,B=j.findWorkspaceRoot(b.workspaceRoot),S=j.findPackageRoot(b.workspaceRoot),Q=j.isMonorepo(B),Z=Q?j.getPackageName(S):void 0,X={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let U=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${U}`)}let Y=[];for(let U of W){if(b.skipAi&&U==="ai")continue;y.info(`Checking ${Uw[U]}...`);let K=await t9(U,m,X,A,w);for(let q of K){if(q.fix&&(q.status==="fail"||q.status==="warn")){if(b.autoFix?!0:await A.confirm(`Fix "${q.name}"? ${q.fix.description}`)){y.info(`Applying fix: ${q.fix.description}`);let z=await q.fix.apply();if(z.success)y.info(`\u2713 ${z.message}`),q.status="pass",q.message=`Fixed: ${z.message}`,q.fix=void 0;else y.warn(`\u2717 ${z.message}`)}}Y.push(q)}}let H=Y.filter((U)=>U.status==="pass").length,J=Y.filter((U)=>U.status==="warn").length,O=Y.filter((U)=>U.status==="fail").length,V=Y.filter((U)=>U.status==="skip").length;return{checks:Y,passed:H,warnings:J,failures:O,skipped:V,healthy:O===0}}async function t9($,b,A,n,m){switch($){case"cli":return m.runCliChecks(b,A);case"config":return m.runConfigChecks(b,A);case"mcp":return m.runMcpChecks(b,A);case"deps":return m.runDepsChecks(b,A);case"docs":return m.runDocChecks(b,A);case"workspace":return m.runWorkspaceChecks(b,A);case"ai":return m.runAiChecks(b,A,n);case"layers":return m.runLayerChecks(b,A);default:return[]}}function dJ($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1967
|
+
`)}function uJ($){let A=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)A+=`
|
|
1968
|
+
${$.details}`;if($.fix)A+=`
|
|
1969
|
+
Fix available: ${$.fix.description}`;return A}async function fn($,b){let A=[],n=b.workspaceRoot??process.cwd(),m=await Vw($,{workspaceRoot:n,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let y of m.checks)if(y.status==="fail")A.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});else if(y.status==="warn")A.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});return A}b$();import{mkdtemp as QQ,rm as ZQ}from"fs/promises";import{tmpdir as XQ}from"os";import Nb from"path";import{DEFAULT_CONTRACTSRC as nQ}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as mQ}from"@contractspec/module.workspace";import yQ from"path";import{packageDocBlocks as p9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as a9,convertSpecToDocBlock as e9,extractModuleDocData as s9,loadSpecFromSource as $Q,scanAllSpecsFromSource as bQ,scanSpecSource as AQ}from"@contractspec/module.workspace";import hn from"path";import{dirname as Kw,sep as sA}from"path";class cn{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let A;if(b.specType==="app-config")A="app-config";else if(b.specType==="example")A="example";else if(b.specType==="feature")A="feature";if(A&&b.key){let n=Kw(b.filePath);this.modules.push({type:A,key:b.key,dirPath:n})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=Kw($),A=this.modules.filter((n)=>{let m=n.dirPath.endsWith(sA)?n.dirPath:n.dirPath+sA;return(b.endsWith(sA)?b:b+sA).startsWith(m)||b===n.dirPath});if(A.length===0)return;return A.sort((n,m)=>{let y={"app-config":3,example:2,feature:1},W=y[n.type],w=y[m.type];if(W!==w)return w-W;return m.dirPath.length-n.dirPath.length}),A[0]}}async function zw($,b,A){let{fs:n,logger:m}=A,y=[];if(m.info(`Generating docs for ${$.length} files...`),b.outputDir)await n.mkdir(b.outputDir);let W=new cn(A),w=[];for(let B of $)try{let S=await n.readFile(B),Q=bQ(S,B);if(Q.length>0)w.push(...Q);else{let Z=AQ(S,B);if(Z.specType!=="unknown")w.push(Z)}}catch(S){}W.initialize(w);let j=await Lw($,A);for(let B of j)if(y.push(B.entry.block),m.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await _w(B.entry.block,B.filePath,b.outputDir,W,n);for(let B of $)try{let S=await $Q(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=e9(Q,{rootPath:b.rootPath});if(y.push(Z),m.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await _w(Z,B,b.outputDir,W,n)}}catch(S){m.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)m.info(`Wrote ${y.length} doc files to ${b.outputDir}`);return{blocks:y,count:y.length}}async function bU($,b){return(await Lw($,b)).map(({entry:n})=>n.block)}function AU($,b){return p9(a9({packageName:$,srcRoot:b}))}async function Lw($,b){let A=[...new Set($)].sort((m,y)=>m.localeCompare(y)),n=[];for(let m of A){let y=await b.fs.readFile(m),W=m.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),w=s9(y,m,W);for(let j of w.entries)n.push({entry:j,filePath:m})}return n}async function _w($,b,A,n,m){let y=n.resolve(b),W=y?hn.join(A,y.key):hn.join(A,"_common");await m.mkdir(W);let w=hn.join(W,`${$.id}.md`),j=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1970
|
+
|
|
1971
|
+
${$.body}`;await m.writeFile(w,j)}async function Rw($,b,A,n,m={}){let y=m.config,W=await cA($,{cwd:m.specSearchRoot,config:y,pattern:m.specPattern??wQ(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=yQ.join(jQ(A,y),"docs"),j=await zw(W.map((S)=>S.filePath),{outputDir:w,format:"markdown",rootPath:n},$),B=0;for(let S of W){let Q=WQ(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await wb(S.filePath,$,y??nQ,{targets:Un(S.specType,{includeTests:Boolean(m.includeRuntimeTests)}),outputDir:y?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((X)=>X.success).length}return{specsCount:W.length,docsCount:j.count,materializedCount:B}}function WQ($){return mQ($.specType)}function wQ($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${dn($)}/**/*.ts`:void 0}function jQ($,b){let A=(b?.connect?.policy?.generatedPaths??[]).map(SQ).filter(Boolean);if(A.length>0)return A[0];if(b?.outputDir&&b.outputDir!=="./src")return dn(b.outputDir);return $}function BQ($){return dn($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function SQ($){let b=BQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function dn($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function $0($,b,A,n={}){let m=await QQ(Nb.join(XQ(),"contractspec-drift-"));try{await Rw($,b,m,n.rootPath,n.generation);let y=[],W=await import("fs/promises");async function w(Z){let X=await W.readdir(Z,{withFileTypes:!0}),Y=[];for(let H of X){let J=Nb.resolve(Z,H.name);if(H.isDirectory())Y.push(...await w(J));else Y.push(J)}return Y}let j=async(Z)=>{if(!await W.stat(Z).catch(()=>!1))return[];return(await w(Z)).map((Y)=>Nb.relative(Z,Y)).sort()},B=await j(m),S=await j(A),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){y.push(Z);continue}if(!B.includes(Z)){y.push(Z);continue}let X=await W.readFile(Nb.join(m,Z)),Y=await W.readFile(Nb.join(A,Z));if(!X.equals(Y))y.push(Z)}return{hasDrift:y.length>0,files:y}}finally{await ZQ(m,{recursive:!0,force:!0})}}async function un($,b){let{fs:A,logger:n}=$,m=[],y=await P(A);if(!y.outputDir)return n.info("No outputDir configured, skipping drift checks"),m;let W="./contracts",w=y.outputDir;if(!await A.exists(w))return n.info("Generated directory does not exist, skipping drift checks"),m;try{let j=await $0($,W,w);if(j.hasDrift)for(let B of j.files)m.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${w}/${B}`,context:{file:B}})}catch(j){n.warn("Drift detection failed",{error:j instanceof Error?j.message:String(j)})}return m}b$();function YQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function HQ($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function b0($,b,A,n={}){let{fs:m}=b,y=[],W=[],w=$.key??m.basename($.filePath).replace(/\.[jt]s$/,""),j=n.outputDir??A.outputDir??"./src",B=YQ(w),S={};if($.specType==="operation")S.handlerPath=m.join(j,"handlers",`${B}.handler.ts`),S.handlerTestPath=m.join(j,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=m.join(j,"components",`${B}.tsx`),S.componentTestPath=m.join(j,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=m.join(j,"forms",`${B}.form.tsx`),S.formTestPath=m.join(j,"forms",`${B}.form.test.tsx`);if(n.checkHandlers&&S.handlerPath)if(!await m.exists(S.handlerPath))y.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await m.readFile(S.handlerPath),X=`${HQ(w.split(".").pop()??w)}Spec`,Y=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),H=new RegExp(`typeof\\s+${X}\\b`).test(Z);if(!Y)W.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!H)W.push(`Handler ContractHandler typing does not reference expected spec var (${X}): ${S.handlerPath}`)}if(n.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await m.exists(Z))y.push(`Missing test file: ${Z}`)}return{valid:y.length===0,errors:y,warnings:W,expected:S}}async function on($,b){let{fs:A}=$,n=[],m=await P(A);for(let y of b){if(y.specType!=="operation")continue;let W=await b0(y,{fs:A},m,{checkHandlers:!0,outputDir:m.outputDir});for(let w of W.errors)n.push({ruleId:"handler-missing",severity:"warning",message:w,category:"handlers",file:y.filePath});for(let w of W.warnings)n.push({ruleId:"handler-warning",severity:"warning",message:w,category:"handlers",file:y.filePath})}return n}b$();import{createHash as VQ}from"crypto";import KQ from"path";var Fb={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},GQ={".handler.ts":"handler",".handler.tsx":"handler",".service.ts":"service",".service.tsx":"service",".test.ts":"test",".test.tsx":"test",".spec.ts":"test",".spec.tsx":"test",".component.tsx":"component",".tsx":"component",".form.tsx":"form",".hook.ts":"hook",".hook.tsx":"hook"};function qQ($){let b=$.toLowerCase();for(let[A,n]of Object.entries(GQ))if(b.endsWith(A))return n;if(b.includes("/handlers/"))return"handler";if(b.includes("/services/"))return"service";if(b.includes("/components/"))return"component";if(b.includes("/forms/"))return"form";if(b.includes("/hooks/"))return"hook";if(b.includes("/__tests__/"))return"test";return"other"}function Iw($,b){let A=[],n=new Set,m=(Z,X,Y)=>{let H=`${Z}:${X}`;if(n.has(H))return;n.add(H),A.push({filePath:b,specKey:Z,referenceType:X,lineNumber:Y,inferredType:qQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1972
|
+
`).length},W,w=new RegExp(Fb.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Fb.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Fb.namedImport);while((W=B.exec($))!==null){let X=W[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(X)for(let Y of X)m(Y,"import",y(W.index))}let S=new RegExp(Fb.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Fb.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return A}var Cw=["**/*.ts(x)"];async function A0($,b,A={}){let{fs:n}=b,m=A.includePatterns??Cw,y=A.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await n.glob({pattern:w,ignore:y});for(let B of j)try{let S=await n.readFile(B),Z=Iw(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function IU($,b={}){let{fs:A}=$,n=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of n){let w=await A.glob({pattern:W,ignore:m});for(let j of w)try{let B=await A.readFile(j),S=Iw(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 OQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,A){let n=OQ(b),m=[];if($==="operation")m.push({path:`${A}/handlers/${n}.handler.ts`,type:"handler"}),m.push({path:`${A}/handlers/${n}.handler.test.ts`,type:"test"});if($==="presentation")m.push({path:`${A}/components/${n}.tsx`,type:"component"}),m.push({path:`${A}/components/${n}.test.tsx`,type:"test"});if($==="form")m.push({path:`${A}/forms/${n}.form.tsx`,type:"form"}),m.push({path:`${A}/forms/${n}.form.test.tsx`,type:"test"});if($==="event")m.push({path:`${A}/handlers/${n}.handler.ts`,type:"handler"}),m.push({path:`${A}/handlers/${n}.handler.test.ts`,type:"test"});return m}import{Node as p,Project as JQ,SyntaxKind as UQ}from"ts-morph";function Mw($){let b=[],n=new JQ({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),m=(j)=>{if(!p.isObjectLiteralExpression(j))return;let B=j.getProperty("implementations");if(B&&p.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&p.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(p.isObjectLiteralExpression(Q)){let Z,X,Y,H=Q.getProperty("path");if(H&&p.isPropertyAssignment(H)){let V=H.getInitializer();if(p.isStringLiteral(V))Z=V.getLiteralText()}let J=Q.getProperty("type");if(J&&p.isPropertyAssignment(J)){let V=J.getInitializer();if(p.isStringLiteral(V))X=V.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let V=O.getInitializer();if(p.isStringLiteral(V))Y=V.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=n.getDescendantsOfKind(UQ.CallExpression);for(let j of y){let B=j.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=j.getArguments();if(S.length>0&&p.isObjectLiteralExpression(S[0]))return m(S[0]),b}}let W=n.getVariableStatements();for(let j of W)if(j.isExported())for(let B of j.getDeclarations()){let S=B.getInitializer();if(S&&p.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return m(S),b}}let w=n.getExportAssignment((j)=>!j.isExportEquals());if(w){let j=w.getExpression();if(p.isObjectLiteralExpression(j))m(j);else if(p.isAsExpression(j)&&p.isObjectLiteralExpression(j.getExpression()))m(j.getExpression())}return b}function Ew($){if($.length===0)return"missing";let b=$.filter((m)=>m.exists),A=$.filter((m)=>m.type!=="test");if(b.filter((m)=>m.type!=="test").length===0)return"missing";if($.every((m)=>m.exists))return"implemented";return"partial"}function TU($){let b=$.filter((m)=>m.status==="implemented").length,A=$.filter((m)=>m.status==="partial").length,n=$.filter((m)=>m.status==="missing").length;return{total:$.length,implemented:b,partial:A,missing:n,coverage:$.length>0?Math.round(b/$.length*100):100}}var _Q={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Tw($){return VQ("sha256").update($).digest("hex")}async function zQ($,b,A,n={},m){let y={..._Q,...n},W=y.computeHashes?Tw($.sourceBlock||""):void 0,w=$.key??KQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,H,J,O)=>{if(Q.has(Y))return;Q.add(Y);let V=await B.exists(Y),U=void 0,K=void 0;if(V&&y.computeHashes)try{U=await B.readFile(Y),K=Tw(U)}catch{}S.push({path:Y,type:H,source:J,exists:V,implementationSourceContent:U,implementationSourceHash:K,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Mw($.sourceBlock);for(let H of Y)await Z(H.path,H.type,"explicit",H.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await A0(w,b,y);for(let H of Y){if(H.filePath===$.filePath)continue;await Z(H.filePath,H.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??A.outputDir??"./src",H=xw($.specType,w,Y);for(let{path:J,type:O}of H)await Z(J,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Ew(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function Dw($,b,A,n={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await zQ(W,b,A,n,m);y.push(w)}catch(w){console.error(`Failed to resolve implementations for ${W}:`,w)}}return y}async function ln($,b,A){let{fs:n}=$,m=[],y=await P(n),W=A.implementation??{},w=b.filter((B)=>B.specType==="operation"),j=await Dw(w,{fs:n},y,{computeHashes:W.useCache??!0});for(let B of j){if(W.requireImplemented&&B.status==="missing")m.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")m.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!W.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);m.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)m.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return m}b$();import{isFeatureFile as IQ,scanAllSpecsFromSource as CQ,scanFeatureSource as xQ}from"@contractspec/module.workspace";function LQ($,b){return`${$}.v${b}`}function tn($,b,A,n,m,y={}){let{treatMissingAsError:W=!0}=y;if(!n||n.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let w=[],j=[],B=[];for(let S of n){let Q=LQ(S.key,S.version);if(m.has(Q))w.push(S);else if(j.push(S),W)B.push(`Spec ${b}.v${A} references test ${S.key}.v${S.version} which does not exist`)}return{valid:j.length===0,foundTests:w,missingTests:j,errors:B,specFile:$}}function Nw($,b){return`${$}.v${b}`}function Fw($,b){let A=new Map,n=new Map,m=[],y=[];for(let W of $){if(!W.key||!W.version)continue;let w=Nw(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=Nw(B,Q),X=RQ(b,j);if(!X||!X.has(Z)){m.push(w);continue}if(n.set(w,Z),!A.has(Z))A.set(Z,new Set);A.get(Z)?.add(w)}return{targetToTests:A,testToTarget:n,orphanedTests:m,testsWithoutTarget:y}}function RQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function MQ(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function pn($,b){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[b]}async function n0($,b={}){let{fs:A,logger:n}=$;n.info("Starting integrity analysis...",{options:b});let m=await h$(A,{config:b.config,cwd:b.cwd,pattern:b.pattern}),y=MQ(),W=[],w=[];for(let q of m){if((await A.stat(q)).isDirectory)continue;let z=await A.readFile(q);if(IQ(q)){let _=xQ(z,q);W.push(_)}else{let _=CQ(z,q);for(let L of _)if(L.specType!=="unknown"&&L.specType!=="feature"){let I=pn(y,L.specType);if(I&&L.key&&L.version!==void 0){let E=n$(L.key,L.version);I.set(E,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let j=b.featureKey?W.filter((q)=>q.key===b.featureKey):W,B=new Set;for(let q of j){for(let G of q.operations){let z=n$(G.key,G.version);if(B.add(`operation:${z}`),!y.operations.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"operation",ref:G})}for(let G of q.events){let z=n$(G.key,G.version);if(B.add(`event:${z}`),!y.events.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Event ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"event",ref:G})}for(let G of q.presentations){let z=n$(G.key,G.version);if(B.add(`presentation:${z}`),!y.presentations.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"presentation",ref:G})}for(let G of q.experiments){let z=n$(G.key,G.version);if(B.add(`experiment:${z}`),!y.experiments.has(z))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"experiment",ref:G})}for(let G of q.capabilities.provides){let z=n$(G.key,G.version);if(B.add(`capability:${z}`),!y.capabilities.has(z))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"capability",ref:G})}for(let G of q.capabilities.requires){let z=n$(G.key,G.version);B.add(`capability:${z}`)}for(let G of q.opToPresentationLinks){let z=n$(G.op.key,G.op.version),_=n$(G.pres.key,G.pres.version);if(!y.operations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked operation ${G.op.key}.v${G.op.version} not found`,file:q.filePath,featureKey:q.key,specType:"operation",ref:G.op});if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${G.pres.key}.v${G.pres.version} not found`,file:q.filePath,featureKey:q.key,specType:"presentation",ref:G.pres})}if(q.presentationsTargets)for(let G of q.presentationsTargets){let z=n$(G.key,G.version);if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${G.key}.v${G.version} not found`,file:q.filePath,featureKey:q.key,specType:"presentation",ref:{key:G.key,version:G.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let q of Q){let G=pn(y,q);if(!G)continue;for(let[z,_]of G)if(!B.has(`${q}:${z}`))S.push(_),w.push({severity:"warning",type:"orphaned",message:`${q} ${_.key}.v${_.version} is not linked to any feature`,file:_.file,specKey:_.key,specType:_.type})}let Z=[];for(let[,q]of y.testSpecs)Z.push({filePath:q.file,specType:"test-spec",key:q.key,version:q.version,testTarget:q.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let X=Fw(Z,y);for(let q of j)for(let G of q.opToPresentationLinks){let z=n$(G.op.key,G.op.version),_=X.targetToTests.get(z),L=!1,I=!1;if(_)for(let E of _){let N=y.testSpecs.get(E);if(N?.testCoverage){if(N.testCoverage.hasSuccess)L=!0;if(N.testCoverage.hasError)I=!0}}if(!_||!L||!I){let E=[];if(!L)E.push("success scenario");if(!I)E.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${G.op.key}.v${G.op.version} linked to presentation requires tests covering: ${E.join(", ")}`,file:q.filePath,featureKey:q.key,specType:"operation",ref:G.op})}}let Y={},H=0;for(let q of Q){let G=pn(y,q);if(!G)continue;let z=G.size,_=0,L=0,I=b.requireTestsFor?.includes(q);for(let[E,N]of G){if(B.has(`${q}:${E}`))_++;if(I){let M=n$(N.key,N.version),r=X.targetToTests.has(M),g=`${N.key}.test`,o0=y.testSpecs.has(n$(g,N.version));if(!r&&!o0)L++,H++,w.push({severity:"warning",type:"missing-test",message:`${q} ${N.key}.v${N.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:N.file,specKey:N.key,specType:N.type})}}Y[q]={total:z,covered:_,orphaned:z-_,missingTest:I?L:0}}let J=Object.values(Y).reduce((q,G)=>q+G.total,0),O=Object.values(Y).reduce((q,G)=>q+G.covered,0),V={total:J,linkedToFeature:O,orphaned:J-O,missingTest:H,byType:Y},K=!w.some((q)=>q.severity==="error");return n.info("Integrity analysis complete",{features:W.length,totalSpecs:J,orphaned:S.length,issues:w.length,healthy:K}),{inventory:y,features:j,coverage:V,issues:w,orphanedSpecs:S,healthy:K}}function sU($){let b=[];for(let A of Object.values($))for(let n of A.values())b.push(n);return b}function $V($,b){return $.filter((A)=>A.type===b)}function bV($,b){return $.filter((A)=>A.severity===b)}async function an($,b){let A=[],n=await P($.fs),m=await n0($,{config:n,pattern:b.pattern,all:!0});for(let y of m.issues)A.push({ruleId:`integrity-${y.type}`,severity:y.severity==="error"?"error":"warning",message:y.message,category:"integrity",file:y.file,context:{specKey:y.specKey,specType:y.specType,featureKey:y.featureKey,ref:y.ref}});return A}async function en($,b){let A=[],n=await pA($,{});for(let[m,y]of n.inventory.features){if(!y.key)A.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:y.filePath,context:{key:m}});if(!y.owners?.length)A.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${m}' missing 'owners' field`,category:"layers",file:y.filePath,context:{key:m}});if(y.operations.length===0&&y.events.length===0&&y.presentations.length===0)A.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${m}' has no operations, events, or presentations`,category:"layers",file:y.filePath,context:{key:m}})}for(let[m,y]of n.inventory.examples){if(!y.entrypoints.packageName)A.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${m}' missing 'packageName' in entrypoints`,category:"layers",file:y.filePath,context:{key:m}});if(!y.surfaces.templates&&!y.surfaces.sandbox.enabled&&!y.surfaces.studio.enabled&&!y.surfaces.mcp.enabled)A.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${m}' has no enabled surfaces`,category:"layers",file:y.filePath,context:{key:m}})}for(let m of n.inventory.workspaceConfigs.values())if(!m.valid)for(let y of m.errors)A.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${y}`,category:"layers",file:m.file});return A}b$();import{ContractsrcSchema as pQ,DEFAULT_CONTRACTSRC as y0}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as EQ}from"@contractspec/module.workspace";async function B$($,b={}){let{fs:A,scan:n=EQ}=$,m=await h$(A,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(Rb(w,b.config))continue;if(Ib(w))continue;try{let j=await A.readFile(w),B=n(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function QV($){let b=new Map;for(let A of $){let n=b.get(A.specType)??[];n.push(A),b.set(A.specType,n)}return b}var hw={};f(hw,{toPascalCase:()=>m0,syncPackageDeclarations:()=>oQ,resolvePackageDeclarationConfig:()=>vb,renderPackageDeclaration:()=>wm,normalizePath:()=>I$,matchesAllowMissing:()=>Wm,inferWorkspacePackageKind:()=>$m,getIndexExportPath:()=>Am,getCanonicalDeclarationRelativePath:()=>bm,discoverWorkspacePackages:()=>Pw,createPackageDeclarationIssue:()=>jm,buildPackageTitle:()=>gb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>H$,buildDomain:()=>mm,buildDeclarationTags:()=>ym,auditPackageDeclarations:()=>Pb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>sn,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>vw});var vw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},sn={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function vb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...vw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function $m($){let b=I$($);for(let[A,n]of Object.entries(sn))if(b.startsWith(A))return n;return null}function bm($,b){switch($){case"libs":case"modules":return`src/${b}.feature.ts`;case"integrations":return"src/integration.ts";case"apps":case"appsRegistry":return"src/blueprint.ts";case"bundles":return`src/bundles/${m0(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function Am($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${m0(b)}Bundle`;case"examples":return"./example"}}function nm($){return I$($).replace(/^packages\//,"").replace(/\//g,".")}function gb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function mm($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function ym($,b,A){return[...new Set([...A,"package",b,$])]}function Wm($,b,A){return $.some((n)=>{let m=I$(n);return m===I$(b)||m===A})}function I$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function m0($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function H$($,b){let A=m0(b);switch($){case"feature":return`${A}Feature`;case"integration":return`${A}IntegrationSpec`;case"app-config":return`${A}Blueprint`;case"module-bundle":return`${A}Bundle`;case"example":return`${A}Example`}}import{scanAllSpecsFromSource as TQ,scanSpecSource as DQ}from"@contractspec/module.workspace";var NQ=["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 Pw($,b={}){let A=I$(b.workspaceRoot??process.cwd()),n=await FQ($,A,b.config),m=await $.glob({cwd:A,patterns:n,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=vb(b.config),W=[];for(let w of m){let j=I$($.dirname(w)),B=$m(j);if(!B)continue;let S=await kw($,$.join(A,w)),Q=$.basename(j),Z=$.join(A,j),X=y.requiredByKind?.[gQ(B)];if(!X)continue;let Y=bm(B,Q);W.push({workspaceRoot:A,relativePackageRoot:j,packageRoot:Z,packageName:typeof S.name==="string"?S.name:j,packageDirName:Q,description:typeof S.description==="string"?S.description:void 0,kind:B,target:X,canonicalDeclarationRelativePath:Y,canonicalDeclarationPath:$.join(Z,Y),indexPath:$.join(Z,"src/index.ts"),indexExportPath:Am(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function Pb($,b={}){let A=await Pw($,b),n=[];for(let m of A){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=TQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[DQ(j,m.canonicalDeclarationPath)]).find((Q)=>Q.specType!=="unknown")?.specType,w=W===m.target}n.push({...m,exists:y,matchesExpectedTarget:w,detectedSpecType:W})}return n}async function FQ($,b,A){let n=$.join(b,"package.json");if(await $.exists(n)){let m=await kw($,n),y=vQ(m);if(y.length>0)return y.map((W)=>`${gw(W)}/package.json`)}if(A?.packages?.length)return A.packages.map((m)=>`${gw(m)}/package.json`);return NQ}function vQ($){if(Array.isArray($.workspaces))return $.workspaces.filter((A)=>typeof A==="string");let b=$.workspaces;if(Array.isArray(b?.packages))return b.packages.filter((A)=>typeof A==="string");return[]}function gQ($){return $==="appsRegistry"?"appsRegistry":$}function gw($){return $.replace(/\/+$/,"")}async function kw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function wm($){let{pkg:b,refs:A,owners:n,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:gb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:mm(b.packageDirName),owners:n,tags:ym(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return PQ(b,A,y);case"integration":return kQ(b,A,y);case"app-config":return rQ(b,A,y);case"module-bundle":return rA({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:H$("module-bundle",b.packageDirName)});case"example":return EA({key:y.key,version:y.version,description:y.description,title:y.title,domain:y.domain,owners:y.owners,tags:y.tags,stability:y.stability,packageName:b.packageName})}}function PQ($,b,A){let n=[Sb("operations",b.operations),Sb("events",b.events),Sb("presentations",b.presentations),Sb("experiments",b.experiments),Sb("workflows",b.workflows),Sb("dataViews",b.dataViews)].filter(Boolean);return`${$.packageName==="@contractspec/lib.contracts-spec"?"import { defineFeature } from './features';":"import { defineFeature } from '@contractspec/lib.contracts-spec/features';"}
|
|
1973
|
+
|
|
1974
|
+
export const ${H$("feature",$.packageDirName)} = defineFeature({
|
|
1975
|
+
meta: ${fQ(A)},
|
|
1976
|
+
${n.length>0?`${n.join(`
|
|
1945
1977
|
`)}
|
|
1946
1978
|
`:""}});
|
|
1947
|
-
`}function
|
|
1979
|
+
`}function kQ($,b,A){let n=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1948
1980
|
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1949
1981
|
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1950
1982
|
|
|
1951
|
-
const ${
|
|
1952
|
-
name: '${
|
|
1983
|
+
const ${H$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1984
|
+
name: '${gb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1953
1985
|
description: 'Managed configuration for ${$.packageName}.',
|
|
1954
1986
|
fields: {},
|
|
1955
1987
|
});
|
|
1956
1988
|
|
|
1957
|
-
const ${
|
|
1958
|
-
name: '${
|
|
1989
|
+
const ${H$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1990
|
+
name: '${gb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1959
1991
|
description: 'Secret material for ${$.packageName}.',
|
|
1960
1992
|
fields: {},
|
|
1961
1993
|
});
|
|
1962
1994
|
|
|
1963
|
-
export const ${
|
|
1995
|
+
export const ${H$("integration",$.packageDirName)} = defineIntegration({
|
|
1964
1996
|
meta: {
|
|
1965
|
-
...${
|
|
1997
|
+
...${fw(A)},
|
|
1966
1998
|
category: 'custom',
|
|
1967
1999
|
},
|
|
1968
2000
|
supportedModes: ['managed'],
|
|
1969
2001
|
capabilities: {
|
|
1970
2002
|
provides: [
|
|
1971
|
-
${
|
|
2003
|
+
${n||" // Add capability refs here"}
|
|
1972
2004
|
],
|
|
1973
2005
|
},
|
|
1974
|
-
configSchema: { schema: ${
|
|
1975
|
-
secretSchema: { schema: ${
|
|
2006
|
+
configSchema: { schema: ${H$("integration",$.packageDirName)}Config, example: {} },
|
|
2007
|
+
secretSchema: { schema: ${H$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1976
2008
|
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1977
2009
|
});
|
|
1978
|
-
`}function
|
|
1979
|
-
`),m=
|
|
2010
|
+
`}function rQ($,b,A){let n=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
2011
|
+
`),m=rw(b.workflows),y=rw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1980
2012
|
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1981
2013
|
|
|
1982
|
-
export const ${
|
|
2014
|
+
export const ${H$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1983
2015
|
meta: {
|
|
1984
|
-
...${
|
|
2016
|
+
...${fw(A)},
|
|
1985
2017
|
appId: '${Q$($.packageDirName)}',
|
|
1986
2018
|
},
|
|
1987
2019
|
capabilities: {
|
|
1988
2020
|
enabled: [
|
|
1989
2021
|
${W||" // Add capability refs here"}
|
|
1990
2022
|
],
|
|
1991
|
-
},${
|
|
2023
|
+
},${n?`
|
|
1992
2024
|
features: {
|
|
1993
2025
|
include: [
|
|
1994
|
-
${
|
|
2026
|
+
${n}
|
|
1995
2027
|
],
|
|
1996
2028
|
},`:""}${y?`
|
|
1997
2029
|
dataViews: {
|
|
@@ -2001,14 +2033,14 @@ ${y}
|
|
|
2001
2033
|
${m}
|
|
2002
2034
|
},`:""}
|
|
2003
2035
|
});
|
|
2004
|
-
`}function
|
|
2005
|
-
${b.map((
|
|
2036
|
+
`}function Sb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2037
|
+
${b.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
2006
2038
|
`)}
|
|
2007
|
-
],`}function
|
|
2039
|
+
],`}function rw($){return $.map((b,A)=>` ${A===0?"primary":`item${A+1}`}: {
|
|
2008
2040
|
key: '${b.key}',
|
|
2009
2041
|
version: '${b.version}',
|
|
2010
2042
|
},`).join(`
|
|
2011
|
-
`)}function
|
|
2043
|
+
`)}function fQ($){return`{
|
|
2012
2044
|
key: '${$.key}',
|
|
2013
2045
|
version: '${$.version}',
|
|
2014
2046
|
title: '${Q$($.title)}',
|
|
@@ -2017,13 +2049,13 @@ ${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
|
2017
2049
|
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
2050
|
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2019
2051
|
stability: '${$.stability}',
|
|
2020
|
-
}`}function
|
|
2021
|
-
`);let B=await
|
|
2052
|
+
}`}function fw($){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 cQ}from"@contractspec/module.workspace";var hQ={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 dQ($){return $.packageName!=="@contractspec/lib.schema"}function uQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function oQ($,b={}){let A=await Pb($,b),n=[],m=[],y=[];for(let W of A){if(!b.force&&W.exists&&W.matchesExpectedTarget){y.push({...W,action:"skipped",declarationCreated:!1,indexUpdated:!1,packageJsonUpdated:!1,dependenciesUpdated:[]});continue}let w=await iQ($,W),j=wm({pkg:W,refs:w,owners:b.config?.defaultOwners?.length?b.config.defaultOwners:["@contractspec-core"],defaultTags:b.config?.defaultTags??[]});if(!b.dryRun)await $.writeFile(W.canonicalDeclarationPath,`${j.trimEnd()}
|
|
2053
|
+
`);let B=await lQ($,W,b.dryRun,dQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await tQ($,W,b.dryRun);if(W.exists)m.push(W.canonicalDeclarationPath);else n.push(W.canonicalDeclarationPath);if(B)m.push(W.indexPath);if(Q)m.push($.join(W.packageRoot,"package.json"));y.push({...W,action:W.exists?"updated":"created",declarationCreated:!W.exists,indexUpdated:B,packageJsonUpdated:Q,dependenciesUpdated:S})}return{packages:y,createdFiles:n,updatedFiles:m}}function jm($,b){return{allowlisted:Wm(b,$.relativePackageRoot,$.packageName),message:$.exists?`Package declaration at ${$.canonicalDeclarationRelativePath} must be a ${$.target} spec.`:`Package ${$.relativePackageRoot} is missing its canonical ${$.target} declaration at ${$.canonicalDeclarationRelativePath}.`}}async function iQ($,b){let A=await $.glob({cwd:b.packageRoot,patterns:["src/**/*.{ts,tsx}"],absolute:!1,ignore:["**/dist/**","**/*.test.*","**/*.spec.*","**/*.stories.*"]}),n={operations:[],events:[],presentations:[],experiments:[],workflows:[],dataViews:[],capabilities:[],features:[]};for(let m of A){if(m===b.canonicalDeclarationRelativePath)continue;let y=await $.readFile($.join(b.packageRoot,m)),W=cQ(y,m);for(let w of W){if(!w.key||!w.version)continue;let j={key:w.key,version:w.version};switch(w.specType){case"operation":C$(n.operations,j);break;case"event":C$(n.events,j);break;case"presentation":C$(n.presentations,j);break;case"experiment":C$(n.experiments,j);break;case"workflow":C$(n.workflows,j);break;case"data-view":C$(n.dataViews,j);break;case"capability":C$(n.capabilities,j);break;case"feature":C$(n.features,j);break}}}return n}function C$($,b){if(!$.some((A)=>A.key===b.key&&A.version===b.version))$.push(b)}async function lQ($,b,A=!1,n=!0){if(!n)return!1;let m=`export * from "${b.indexExportPath}";`,y=new RegExp(`export \\* from ['"]${b.indexExportPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"];`),W=await $.exists(b.indexPath)?await $.readFile(b.indexPath):"";if(y.test(W))return!1;if(W=`${W.trimEnd()}
|
|
2022
2054
|
${m}
|
|
2023
|
-
`.trimStart(),!
|
|
2024
|
-
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function
|
|
2025
|
-
`).map((n)=>n.trim()).filter((n)=>n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")&&!n.startsWith("*/"));return b.length>0&&b.every((n)=>n.startsWith("import ")||n.startsWith("export *")||n.startsWith("export {")||n.startsWith("export type {")||n==="'use client';"||n==='"use client";'||n==="'use server';"||n==='"use server";')}function $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
|
|
2055
|
+
`.trimStart(),!A)await $.writeFile(b.indexPath,W);return!0}async function tQ($,b,A=!1){let n=$.join(b.packageRoot,"package.json"),m=JSON.parse(await $.readFile(n)),y=cw(m,"dependencies"),W=[],w=!1;for(let B of hQ[b.target]){if(!uQ(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=cw(m,"exports");if(w=w||W.length>0,typeof j["."]!=="string")j["."]="./src/index.ts",w=!0;if(w&&!A)await $.writeFile(n,`${JSON.stringify(m,null,"\t")}
|
|
2056
|
+
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function cw($,b){let A=$[b];if(typeof A==="object"&&A!==null&&!Array.isArray(A))return A;let n={};return $[b]=n,n}var aQ=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,eQ=/@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?)?['"]/,sQ=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,$4=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,b4=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,A4=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,n4=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function W0($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function m4($,b){let A=$.replaceAll("\\","/"),n=new Set(["contracts","features",...W0(b?.conventions?.operations),...W0(b?.conventions?.events),...W0(b?.conventions?.presentations),...W0(b?.conventions?.forms)]);return A.split("/").some((m)=>n.has(m))}function y4($,b,A){let n=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(n))return!1;if(n.includes("/node_modules/")||n.includes("/dist/")||b4.test(n)||$4.test(n)||n.endsWith(".d.ts")||n.endsWith(".test.ts")||n.endsWith(".spec.ts"))return!1;if(b.has(n))return!1;if(m4(n,A))return!1;return aQ.test(n)}function dw($){return $.replaceAll("\\","/").match(A4)?.[1]??null}function W4($){let b=$.split(`
|
|
2057
|
+
`).map((A)=>A.trim()).filter((A)=>A.length>0&&!A.startsWith("//")&&!A.startsWith("/*")&&!A.startsWith("*")&&!A.startsWith("*/"));return b.length>0&&b.every((A)=>A.startsWith("import ")||A.startsWith("export *")||A.startsWith("export {")||A.startsWith("export type {")||A==="'use client';"||A==='"use client";'||A==="'use server';"||A==='"use server";')}function w4($){if(!$)return y0;let b=pQ.safeParse($),A=b.success?b.data:{};return{...y0,...A,conventions:{...y0.conventions,...A.conventions??{}},ci:{...y0.ci,...A.ci??{}}}}async function Bm($,b){let{fs:A,logger:n}=$,m=[],y=b.config?w4(b.config):await P(A),W=vb(y),w=await B$({fs:A},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>dw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await A.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!y4(Q,j,y))continue;try{let Z=await A.readFile(Q);if(W4(Z))continue;let X=dw(Q);if(!(X!==null&&n4.test(X)&&B.has(X))&&!sQ.test(Z))continue;if(eQ.test(Z))continue;m.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:Q})}catch(Z){n.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await Pb(A,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=jm(Z,W.allowMissing??[]);m.push({ruleId:"policy-package-declaration",severity:X.allowlisted||W.severity==="warning"?"warning":"error",message:X.message,category:"policy",file:Z.canonicalDeclarationPath,context:{allowlisted:X.allowlisted,expectedTarget:Z.target,packageName:Z.packageName,packageRoot:Z.relativePackageRoot}})}}return m}import{validateSpecStructure as j4}from"@contractspec/module.workspace";async function Sm($){let b=[];for(let A of $){let n=j4(A);for(let m of n.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:m,category:"structure",file:A.filePath});for(let m of n.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:m,category:"structure",file:A.filePath})}return b}async function Qm($){let b=[],A=new Map,n=new Map;for(let m of $){if(!m.key||!m.version)continue;if(m.specType==="test-spec"){let y=`${m.key}.v${m.version}`;A.set(y,{key:m.key,version:m.version,file:m.filePath,type:"test-spec"})}if(m.testRefs&&m.testRefs.length>0){if(!n.has(m.filePath))n.set(m.filePath,[]);n.get(m.filePath)?.push({key:m.key,version:m.version,testRefs:m.testRefs})}}for(let[m,y]of n)for(let W of y){if(!W.testRefs)continue;let w=tn(m,W.key,W.version,W.testRefs,A,{treatMissingAsError:!0});for(let j of w.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:j,category:"test-refs",file:m,context:{specKey:W.key,specVersion:W.version,missingTests:w.missingTests}})}return b}b$();async function Zm($,b){let{fs:A}=$,n=[],m=await P(A);for(let y of b){if(y.specType!=="operation")continue;let W=await b0(y,{fs:A},m,{checkTests:!0,outputDir:m.outputDir});for(let w of W.errors)n.push({ruleId:"test-missing",severity:"warning",message:w,category:"tests",file:y.filePath});for(let w of W.warnings)n.push({ruleId:"test-warning",severity:"warning",message:w,category:"tests",file:y.filePath})}return n}function e($,b,A){let n={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},m=b.filter((w)=>w.severity==="error").length,y=b.filter((w)=>w.severity==="warning").length,W=b.filter((w)=>w.severity==="note").length;return{category:$,label:n[$],errors:m,warnings:y,notes:W,passed:m===0,durationMs:A}}async function uw($){try{if(!await $.exists(".git/HEAD"))return{};let A=await $.readFile(".git/HEAD"),n=A.match(/^ref: (.+)$/m);if(n){let y=n[1]?.replace("refs/heads/",""),W=`.git/${n[1]}`;if(await $.exists(W))return{commitSha:(await $.readFile(W)).trim(),branch:y};return{branch:y}}return{commitSha:A.trim()}}catch{return{}}}function ow($){let b=$.config?.ci?.checks,A=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)A.push("handlers");if($.checkTests)A.push("tests");if($.implementation)A.push("implementation");if($.checkDrift)A.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return A.filter((n)=>!$.skip?.includes(n));return A}async function QK($,b={}){let A=Date.now(),{fs:n,logger:m}=$,y=[],W=[],w=ow(b);m.info("Starting CI checks...",{checks:w});let j=await P(n),B=await cA($,{config:j,pattern:b.pattern});if(w.includes("structure")){let J=Date.now(),O=await Sm(B);y.push(...O),W.push(e("structure",O,Date.now()-J))}if(w.includes("integrity")){let J=Date.now(),O=await an($,b);y.push(...O),W.push(e("integrity",O,Date.now()-J))}if(w.includes("deps")){let J=Date.now(),O=await Cn($,b);y.push(...O),W.push(e("deps",O,Date.now()-J))}if(w.includes("doctor")){let J=Date.now(),O=await fn($,b);y.push(...O),W.push(e("doctor",O,Date.now()-J))}if(w.includes("docs")){let J=Date.now(),O=await xn($,b);y.push(...O),W.push(e("docs",O,Date.now()-J))}if(w.includes("policy")){let J=Date.now(),O=await Bm($,b);y.push(...O),W.push(e("policy",O,Date.now()-J))}if(w.includes("handlers")||b.checkHandlers){let J=Date.now(),O=await on($,B);y.push(...O),W.push(e("handlers",O,Date.now()-J))}if(w.includes("tests")||b.checkTests){let J=Date.now(),O=await Zm($,B);y.push(...O),W.push(e("tests",O,Date.now()-J))}if(w.includes("test-refs")){let J=Date.now(),O=await Qm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-J))}if(w.includes("coverage")){let J=Date.now(),O=await In($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-J))}if(w.includes("implementation")){let J=Date.now(),O=await ln($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-J))}if(w.includes("layers")){let J=Date.now(),O=await en($,b);y.push(...O),W.push(e("layers",O,Date.now()-J))}if(w.includes("drift")){let J=Date.now(),O=await un($,b);y.push(...O),W.push(e("drift",O,Date.now()-J))}let S=y.filter((J)=>J.severity==="error").length,Q=y.filter((J)=>J.severity==="warning").length,Z=y.filter((J)=>J.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await uw(n),H={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-A,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:H.durationMs}),H}var XK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],YK={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function JK($,b={}){let{fs:A,logger:n}=$,m=(b.outputDir??"./src").replace(/\\/g,"/"),y=["generated/**","dist/**",".turbo/**"],W=[`${m}/handlers/**/*.handler.ts`,`${m}/handlers/**/*.handler.test.ts`,`${m}/components/**/*.tsx`,`${m}/components/**/*.test.tsx`,`${m}/forms/**/*.form.tsx`,`${m}/forms/**/*.form.test.tsx`,`${m}/**/*.runner.ts`,`${m}/**/*.renderer.tsx`],w=b.generatedOnly?[...y,...W]:[...y,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...W],j=await A.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await A.stat(Q),X=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&X<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)n.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await A.remove(Q),n.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}b$();var Uj={};f(Uj,{writeReviewPacket:()=>Im,writeDecisionEnvelope:()=>ob,withBranch:()=>i$,verifyConnectMutation:()=>H6,resolveWorkspace:()=>l,resolveStoragePaths:()=>X$,replayConnectDecision:()=>i4,persistLatestArtifacts:()=>Lm,persistDecisionArtifacts:()=>ub,normalizeEvalInput:()=>P4,matchConfiguredPath:()=>kb,loadStoredDecision:()=>ib,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>l4,isReviewCommand:()=>Xm,isDeniedCommand:()=>Ym,isAllowedCommand:()=>w0,initConnectWorkspace:()=>h4,inferSurfaces:()=>cb,evaluateConnectDecision:()=>v4,ensureStorage:()=>db,defaultActor:()=>fb,decisionArtifactRefs:()=>Zb,createConnectControlPlaneRuntime:()=>m6,connectVerdictToPolicy:()=>x$,configuredThreshold:()=>o$,compileConnectPlanPacket:()=>lb,buildConnectContextPack:()=>hb,assessConnectPolicy:()=>rb,assertConnectEnabled:()=>m$,artifactRef:()=>_$,appendAuditRecord:()=>Rm,analyzeConnectImpact:()=>l$,CONTROL_PLANE_TRACE_GET_REF:()=>j0,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>B0,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Om,CONTROL_PLANE_PLAN_COMPILE_REF:()=>qm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>V$,AGENT_APPROVALS_REF:()=>S0,ACP_TERMINAL_EXEC_REF:()=>Z4,ACP_FS_ACCESS_REF:()=>Q4});import B4 from"micromatch";function m$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function kb($,b,A){if(!A||A.length===0)return!1;let n=b.replaceAll("\\","/");return B4.isMatch(n,A,{contains:!0})}function o$($,b,A){return $.config.connect?.policy?.reviewThresholds?.[b]??A}function w0($,b){return Hm($.config.connect?.commands?.allow,b)}function Xm($,b){return Hm($.config.connect?.commands?.review,b)}function Ym($,b){return Hm($.config.connect?.commands?.deny,b)}function Hm($,b){if(!$||$.length===0)return!1;return $.some((A)=>b===A||b.startsWith(`${A} `))}function lw($,b){if(b.length===0)return{state:"none"};for(let n of b)if(Ym($,n))return{commandMatch:n,state:"deny"};for(let n of b)if(Xm($,n))return{commandMatch:n,state:"review"};if(b.every((n)=>w0($,n)))return{state:"allow"};let A=b.find(S4);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((n)=>!w0($,n)),state:"unknown"}}function S4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return iw(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return iw(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function iw($,b){return b.every((A)=>$.includes(A)||$.includes(A.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Om={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},j0={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},B0={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},V$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},Q4={key:"acp.fs.access",version:"1.0.0",kind:"command"},Z4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},S0={key:"agent.approvals",version:"1.0.0",kind:"command"};function rb($,b){let A=b.touchedPaths.find((Z)=>kb($,Z,$.config.connect?.policy?.immutablePaths)),n=b.touchedPaths.find((Z)=>kb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>kb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=lw($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=X4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(A),protectedPath:Boolean(n),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=Y4({breakingChange:b.impactAnalysis.breakingChange,commandMatch:y,commandState:W,contractDrift:j,protectedPath:n,unknownPaths:b.impactAnalysis.unknownPaths}),Q=x$(B);return{commandMatch:y,commandState:W,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:m,immutablePath:A,protectedPath:n,requiredApprovals:Q.requiresApproval?[{capability:V$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function x$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function X4($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(o$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(o$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(o$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(o$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(o$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(H4)[0]??"permit"}function Y4($){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 H4($,b){return tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as N4}from"crypto";var $j={};f($j,{formatPrComment:()=>pw,formatMinimalComment:()=>Jm,formatJson:()=>ew,formatCheckRun:()=>aw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>V4});function pw($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)A.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else A.push("\u2705 **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| \u2796 Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let n=$.deltas.filter((y)=>y.severity==="breaking"),m=$.deltas.filter((y)=>y.severity==="non_breaking");if(n.length>0){A.push("#### \uD83D\uDD34 Breaking Changes"),A.push("");for(let y of n)A.push(`- **${y.specKey}**: ${y.description}`);A.push("")}if(m.length>0){A.push("#### \uD83D\uDFE1 Non-breaking Changes"),A.push("");for(let y of m)A.push(`- **${y.specKey}**: ${y.description}`);A.push("")}}if($.addedSpecs.length>0){A.push("### Added Specs"),A.push("");for(let n of $.addedSpecs)A.push(`- \`${n.key}\` v${n.version} (${n.type})`);A.push("")}if($.removedSpecs.length>0){A.push("### Removed Specs"),A.push("");for(let n of $.removedSpecs)A.push(`- \`${n.key}\` v${n.version} (${n.type})`);A.push("")}if(b.drift)if(b.drift.hasDrift){A.push("### \u26A0\uFE0F Drift Detected"),A.push(""),A.push("The following generated files are out of sync with their specs:"),A.push("");for(let n of b.drift.files)A.push(`- \`${n}\``);A.push(""),A.push("Run `contractspec generate` to regenerate artifacts."),A.push("")}else A.push("### \u2705 No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
2058
|
+
`)}function Jm($){if($.hasBreaking)return`\u274C **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`\u26A0\uFE0F **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"\u2705 **No contract impact**"}function aw($,b,A={}){let n=A.key??"ContractSpec Impact",m=A.failOnBreaking??!0,y,W;if($.hasBreaking)y=m?"failure":"neutral",W=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)y="success",W=`Non-breaking changes (${$.summary.nonBreaking})`;else y="success",W="No contract impact";let w=Jm($);return{name:n,headSha:b,conclusion:y,title:W,summary:w,annotations:$.deltas.filter((j)=>j.severity==="breaking").slice(0,50).map((j)=>({path:j.path,startLine:1,endLine:1,annotationLevel:"failure",message:j.description,title:`Breaking: ${j.rule}`}))}}function ew($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((A)=>({type:A.rule,path:A.specKey,summary:A.description,severity:A.severity==="breaking"?"breaking":A.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as G4,computeIoDiff as q4,generateSnapshot as sw}from"@contractspec/module.workspace";async function K$($,b={}){let{fs:A,git:n,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting impact detection...",{baseline:b.baseline});let w=(await A.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${w.length} spec files`);let j=await O4(A,w,y),B=sw(j),S;if(b.baseline){let X=await J4(A,n,w,b.baseline,y);S=sw(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=U4(S.specs,B.specs),Z=G4(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 O4($,b,A){let n=[];for(let m of b){let y=await $.readFile(m);n.push({path:m,content:y})}return n}async function J4($,b,A,n,m){let y=[];for(let W of A)try{let w=await b.showFile(n,W);y.push({path:W,content:w})}catch{}return y}function U4($,b){let A=[],n=new Map($.map((y)=>[`${y.key}@${y.version}`,y])),m=new Map(b.map((y)=>[`${y.key}@${y.version}`,y]));for(let[y,W]of m){let w=n.get(y);if(w&&W.type==="operation"&&w.type==="operation"){let j=q4(w.io,W.io);A.push(...j)}}return A}var V4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
2027
2059
|
# Contract Impact Detection
|
|
2028
2060
|
|
|
2029
2061
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -2069,49 +2101,49 @@ The system consists of three layers:
|
|
|
2069
2101
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
2070
2102
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
2071
2103
|
3. **Integrations**: CLI command + GitHub Action
|
|
2072
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
2073
|
-
`;await $.writeFile(b.auditFile,`${
|
|
2074
|
-
`)}async function
|
|
2075
|
-
`);if(
|
|
2104
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as Aj,readFileSync as nj}from"fs";import{basename as K4,join as Um,resolve as _4}from"path";import{ContractsrcSchema as z4,DEFAULT_CONTRACTSRC as L4}from"@contractspec/lib.contracts-spec/workspace-config";function l($={}){let b=_4($.cwd??process.cwd()),A=$.workspaceRoot??x(b),n=$.packageRoot??c(b),m=$.config??R4(A,n),y=I4(n,A);return{cwd:b,workspaceRoot:A,packageRoot:n,config:m,repoId:y,branch:"unknown"}}function i$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function fb($,b){return b??{id:`cli:${$}`,type:"human"}}function cb($){let b=new Set;for(let A of $){if(A.includes("/cli-")||A.includes("/apps/cli-"))b.add("cli");if(A.includes("/contracts-spec/")||A.includes("/specs/"))b.add("contract");if(A.includes("/components/")||A.includes("/ui/")||A.endsWith(".tsx")||A.endsWith(".jsx"))b.add("ui");if(A.includes("/integrations/")||A.includes("/provider"))b.add("integration");if(A.includes("/libs/")||A.includes("/shared/")||A.includes("/utils/"))b.add("library");if(A.includes("/modules/")||A.includes("/bundles/")||A.includes("/examples/"))b.add("solution");if(A.includes("/runtime/"))b.add("runtime");if(A.includes("/harness"))b.add("harness");if(A.includes("/ai-agent/"))b.add("agent");if(A.includes("/knowledge/"))b.add("knowledge");if(A.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function R4($,b){let A={...L4};if($!==b)A=bj(A,Um($,".contractsrc.json"));return bj(A,Um(b,".contractsrc.json"))}function bj($,b){if(!Aj(b))return $;try{let A=nj(b,"utf-8"),n=JSON.parse(A),m=z4.safeParse(n);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function I4($,b){let A=Um($,"package.json");if(Aj(A))try{let n=JSON.parse(nj(A,"utf-8"));if(n.name)return n.name}catch{}return K4(b)}async function l$($,b){let A=await B$({fs:$.fs},{config:b.workspace.config}),n=new Map(A.filter((j)=>typeof j.key==="string").map((j)=>[j.key,j])),m=b.touchedPaths.map((j)=>C4($.fs,b.workspace,j,A,n)),y=b.baseline!=null?await K$({...$,logger:$.logger??yj},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,W=await x4($,b.workspace,b.touchedPaths),w=zm([...m.flatMap((j)=>j.contracts),...(y?.deltas??[]).map((j)=>({key:j.specKey,version:j.specVersion,kind:j.specType==="event"?"event":"command"}))]);return{breakingChange:y?.hasBreaking===!0,driftFiles:W,impactResult:y,impactedContracts:w,pathImpacts:m,unknownPaths:m.filter((j)=>j.contracts.length===0).map((j)=>j.path)}}function C4($,b,A,n,m){let y=$.resolve(b.workspaceRoot,A),W=_m(A),w=n.map((Y)=>{let H=y$($.relative(b.workspaceRoot,Y.filePath));return{score:T4(A,W,H,Y.key),spec:Y}}).filter((Y)=>Y.score>=45).sort((Y,H)=>H.score-Y.score).slice(0,3),j=n.find((Y)=>Y.filePath===y),B=j?[{score:100,spec:j}]:w,S=B.filter((Y)=>typeof Y.spec.key==="string").map((Y)=>Km(Y.spec.key,Y.spec.version,Y.spec.kind)),Q=B.flatMap((Y)=>[...Y.spec.emittedEvents??[],...Y.spec.policyRefs??[],...Y.spec.testRefs??[]].map((H)=>m.get(H.key)).filter(Boolean).map((H)=>Km(H.key,H.version,H.kind))),Z=zm([...S,...Q]),X=zm([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((Y)=>Y.spec.policyRefs??[]).map((Y)=>Km(Y.key,Y.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:A,policies:X,reasons:B.map((Y)=>`${Y.spec.key??Y.spec.filePath} matched with score ${Y.score}`),surfaces:cb([A])}}async function x4($,b,A){let n=M4($.fs,b,A),m=await Promise.all(n.map(async(y)=>{let W=$.fs.resolve(b.packageRoot,y.comparisonRoot),w=await $0({...$,logger:$.logger??yj},b.workspaceRoot,W,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),j=y.filterPrefix&&y.filterPrefix!==y.comparisonRoot?y$($.fs.relative(y.comparisonRoot,y.filterPrefix)):void 0;return w.files.filter((B)=>j?y$(B)===j||y$(B).startsWith(`${j}/`):!0).map((B)=>y$($.fs.join(y.comparisonRoot,B)))}));return[...new Set(m.flat())].sort()}function M4($,b,A){let n=(b.config.connect?.policy?.generatedPaths??[]).map(D4).filter(Boolean),m=b.config.outputDir&&b.config.outputDir!=="./src"?y$(b.config.outputDir):void 0,y=new Map;for(let W of A){let w=y$(W);if(m&&w.startsWith(m))y.set(m,{comparisonRoot:m});for(let j of n)if(w.startsWith(j)){let B=E4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function E4($,b,A){if(b&&A.startsWith(b))return b;return $.basename(A)==="docs"?y$($.dirname(A)):A}function T4($,b,A,n){if(y$($)===y$(A))return 100;let m=_m(A),y=_m(n??""),W=mj($)===mj(A)?40:0,w=Vm($.split("/"),A.split("/"),5),j=Vm(b,m,5),B=Vm(b,y,4);return W+w+j+B}function Vm($,b,A){let n=new Set(b);return $.filter((m)=>n.has(m)).length*A}function _m($){return y$($).split(/[\/._-]+/).filter(Boolean)}function mj($){return y$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function D4($){return y$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function y$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Km($,b,A){return{key:$,version:String(b??"1.0.0"),kind:A==="query"||A==="event"||A==="policy"||A==="capability"?A:"command"}}function zm($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var yj={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function hb($,b){let A=l(b);m$(A),A=i$(A,await $.git.currentBranch());let n=fb(b.taskId,b.actor),m=await F4($,A.workspaceRoot,b),y=await l$($,{baseline:b.baseline,touchedPaths:m,workspace:A}),W=A.config.connect?.canonPacks??[];return{id:`connect.ctx_${N4()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:n,knowledge:W.map((w)=>({spaceKey:w.ref,category:"canonical",trustLevel:w.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:y.impactedContracts,affectedSurfaces:y.pathImpacts.length>0?[...new Set(y.pathImpacts.flatMap((w)=>w.surfaces))].sort():cb(m),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...W.map((w)=>({key:w.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...W.map((w)=>({kind:"canon-pack",ref:w.ref}))],acceptanceChecks:A.config.connect?.policy?.smokeChecks??[]}}async function F4($,b,A){let n=A.paths??[];if(n.length>0)return n.map((y)=>Wj($.fs,b,y));if(!A.baseline)return[];return(await $.git.diffFiles(A.baseline)).map((y)=>Wj($.fs,b,y))}function Wj($,b,A){let n=$.resolve(b,A);return $.relative(b,n).replaceAll("\\","/")}import{resolve as t$}from"path";function X$($){let b=$.config.connect?.storage,A=t$($.packageRoot,b?.root??".contractspec/connect");return{root:A,contextPack:t$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:t$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:t$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:t$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:t$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:t$(A,"decisions")}}async function db($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function Lm($,b,A){if(A.contextPack)await Z$($,b.contextPack,A.contextPack);if(A.planPacket)await Z$($,b.planPacket,A.planPacket);if(A.patchVerdict)await Z$($,b.patchVerdict,A.patchVerdict)}async function ub($,b,A,n){let m=$.join(b.decisionsDir,A);if(await $.mkdir(m),n.contextPack)await Z$($,$.join(m,"context-pack.json"),n.contextPack);if(n.planPacket)await Z$($,$.join(m,"plan-packet.json"),n.planPacket);if(n.patchVerdict)await Z$($,$.join(m,"patch-verdict.json"),n.patchVerdict);if(n.reviewPacket)await Z$($,$.join(m,"review-packet.json"),n.reviewPacket);if(n.evaluationResult!==void 0)await Z$($,$.join(m,"evaluation-result.json"),n.evaluationResult);if(n.replayBundle!==void 0)await Z$($,$.join(m,"replay-bundle.json"),n.replayBundle);return m}async function ob($,b,A,n){let m=$.join(b.decisionsDir,A,"decision-envelope.json");return await Z$($,m,n),m}async function Rm($,b,A){let n=await wj($,b.auditFile)??"",m=`${JSON.stringify(A)}
|
|
2105
|
+
`;await $.writeFile(b.auditFile,`${n}${m}`)}async function Im($,b,A){let n=$.join(b.reviewPacketsDir,`${A.id}.json`);return await Z$($,n,A),n}async function ib($,b,A){let n=$.join(b.decisionsDir,A);return{historyDir:n,contextPack:await Qb($,$.join(n,"context-pack.json")),planPacket:await Qb($,$.join(n,"plan-packet.json")),patchVerdict:await Qb($,$.join(n,"patch-verdict.json")),reviewPacket:await Qb($,$.join(n,"review-packet.json")),envelope:await Qb($,$.join(n,"decision-envelope.json"))}}async function Cm($,b){let A=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),n=[];for(let m of A){let y=await Qb($,m);if(y)n.push({filePath:m,packet:y})}return n.sort((m,y)=>m.packet.id.localeCompare(y.packet.id))}function _$($,b,A){return $.relative(b.packageRoot,$.resolve(A)).replaceAll("\\","/")}function Zb($,b,A,n,m){let y=$.join(A.decisionsDir,n);return{contextPack:_$($,b,$.join(y,"context-pack.json")),planPacket:_$($,b,$.join(y,"plan-packet.json")),patchVerdict:_$($,b,$.join(y,"patch-verdict.json")),reviewPacket:m.reviewPacket?_$($,b,$.join(y,"review-packet.json")):void 0,evaluationResult:m.evaluationResult?_$($,b,$.join(y,"evaluation-result.json")):void 0,replayBundle:m.replayBundle?_$($,b,$.join(y,"replay-bundle.json")):void 0}}async function Z$($,b,A){await $.writeFile(b,`${JSON.stringify(A,null,2)}
|
|
2106
|
+
`)}async function Qb($,b){let A=await wj($,b);if(!A)return;try{return JSON.parse(A)}catch{return}}async function wj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function v4($,b,A){let n=l(b);if(m$(n),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let m=X$(n),y=await ib($.fs,m,b.decisionId),W=g4(n,y),w=b.scenarioKey?await A.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:W}):await A.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:W}),j=await ub($.fs,m,b.decisionId,{evaluationResult:w}),B=await $.fs.exists($.fs.join(j,"replay-bundle.json")),S={artifacts:Zb($.fs,n,m,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(y.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:y.envelope?.createdAt??new Date().toISOString(),runtimeLink:y.envelope?.runtimeLink,taskId:y.contextPack?.taskId??b.decisionId,verdict:y.patchVerdict?.verdict??"permit"};return await ob($.fs,m,b.decisionId,S),{historyDir:j,evaluation:w,context:W}}function g4($,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 P4($){return $}import{DEFAULT_CONTRACTSRC as c4}from"@contractspec/lib.contracts-spec/workspace-config";async function Q0($,b){let A=$.join(b.root,".gitignore"),n=b.behavior??"auto",m=Sj(b.patterns);if(m.length===0||n==="skip")return{target:"gitignore",filePath:A,action:"skipped",message:n==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(n==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${A}?`,!0))return{target:"gitignore",filePath:A,action:"skipped",message:"User skipped ContractSpec gitignore update"};let y=await $.exists(A),W=y?await $.readFile(A):"",w=k4(W,m);if(Bj(W)===Bj(w))return{target:"gitignore",filePath:A,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(A,w),{target:"gitignore",filePath:A,action:y?"merged":"created",message:y?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(y){return{target:"gitignore",filePath:A,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}function k4($,b){let A=r4(b),n=f4(),m=$.replace(/\r\n/g,`
|
|
2107
|
+
`);if(n.test(m))return m.replace(n,A);if(m.trim().length===0)return A;return`${m.endsWith(`
|
|
2076
2108
|
`)?m:`${m}
|
|
2077
2109
|
`}
|
|
2078
|
-
${
|
|
2110
|
+
${A}`}function r4($){return`# contractspec:init:gitignore:start
|
|
2079
2111
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
2080
|
-
${
|
|
2112
|
+
${Sj($).join(`
|
|
2081
2113
|
`)}
|
|
2082
2114
|
# contractspec:init:gitignore:end
|
|
2083
|
-
`}function
|
|
2084
|
-
`).trimEnd()}function Bj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function 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=
|
|
2115
|
+
`}function f4(){return new RegExp(`${jj("# contractspec:init:gitignore:start")}[\\s\\S]*?${jj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function jj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bj($){return $.replace(/\r\n/g,`
|
|
2116
|
+
`).trimEnd()}function Sj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function h4($,b={}){let A=l(b),n=b.scope==="package"?A.packageRoot:A.workspaceRoot,m=$.join(n,".contractsrc.json"),y={connect:{...c4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=A$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,F(S)),W="merged"}else await $.writeFile(m,F(y));let w=X$(l({...b,workspaceRoot:n,packageRoot:n}));await db($,w);let j=await Q0($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Eb.connect,Eb.verificationCache],prompts:b.prompts,root:A.workspaceRoot});return{configPath:m,targetRoot:n,action:W,gitignore:j}}import{randomUUID as Z0}from"crypto";async function lb($,b){let A=l(b);m$(A),A=i$(A,await $.git.currentBranch());let{commands:n,touchedPaths:m}=d4(b.candidate),y=await hb($,{...b,paths:m}),W=fb(b.taskId,b.actor),w=u4(b.candidate.steps,b.candidate),j=await l$($,{baseline:b.baseline,touchedPaths:m,workspace:A}),B=rb(A,{commands:n,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${Z0()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:A.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:o4(m.length,n.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:qm,planVerify:Om,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...n.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function d4($){let b=new Set($.touchedPaths??[]),A=new Set($.commands??[]);for(let n of $.steps??[]){if(typeof n==="string")continue;for(let m of n.paths??[])b.add(m);for(let m of n.commands??[])A.add(m)}return{commands:[...A],touchedPaths:[...b]}}function u4($,b){if(!$||$.length===0)return[{id:`step_${Z0()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((A)=>typeof A==="string"?{id:`step_${Z0()}`,summary:A}:{id:`step_${Z0()}`,summary:A.summary,paths:A.paths,commands:A.commands,contractRefs:A.contractRefs})}function o4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function i4($,b,A){let n=l(b);m$(n);let m=X$(n),y=await ib($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=A&&(W.decisionId||W.traceId)?await A.getExecutionTrace(W):null,j=A&&w?await A.replayExecutionTrace(W):null;return{decisionId:b.decisionId,historyDir:y.historyDir,contextPack:y.contextPack,planPacket:y.planPacket,patchVerdict:y.patchVerdict,reviewPacket:y.reviewPacket,trace:w??void 0,replay:j??void 0,source:w?"local+control-plane":"local"}}async function l4($,b={}){let A=l(b);return m$(A),Cm($.fs,X$(A))}import{buildChannelPlanTrace as t4,compileChannelPlan as p4,finalizeChannelPlan as a4,replayExecutionTrace as e4,resolveChannelExecutionActor as s4}from"@contractspec/integration.runtime/channel";import{createHash as $6}from"crypto";var tb="connect.local",b6="connect.runtime-link.v1",A6="connect.adapter.v1",n6="connect-control-plane-bridge";function m6($){return{linkDecision:async({connectDecisionId:b,createdAt:A,input:n,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(A),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:n.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:tb,externalEventId:b,eventType:n.tool==="acp.fs.access"?`connect.fs.${n.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:j6(y.objective,n)},metadata:Zj({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:B6(j),traceId:B.traceId});if(S.duplicate)return y6($.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=s4(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:w6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=p4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=a4({plan:X,decision:W6(m),approvalTimeoutMs:900000,now:w}),H=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:Y.policy?.verdict??"blocked",riskTier:Y.policy?.riskTier??"blocked",confidence:Y.policy?.confidence??0.5,modelName:n6,promptVersion:b6,policyVersion:A6,toolTrace:t4(Y),actionPlan:Y,requiresApproval:Y.approval.required,approvalStatus:Y.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:Y.approval.required?"pending":"processed",decisionId:H.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:tb,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Zj({connectDecisionId:b,connectVerdict:m.verdict,tool:n.tool})}),{approvalStatus:H.approvalStatus,decisionId:H.id,planId:Y.id,providerKey:tb,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Qj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let A=await Qj($.traceService,b);return A?e4(A):null}}}async function y6($,b,A){let m=(await $.listDecisions({externalEventId:A,limit:1,providerKey:tb,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:tb,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Qj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function W6($){let b=x$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((A)=>`${A.status}:${A.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function w6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function j6($,b){return`${$} [${b.tool}]`}function B6($){return $6("sha256").update($).digest("hex")}function Zj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as Y6}from"crypto";async function Xj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=S6(b);if(!A)return{};let n=await Vb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:A,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:A==="ui"?Q6(b):void 0,query:xm(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:n.verdict==="permit"?"pass":n.verdict==="rewrite"?"warn":"fail",detail:n.reason},reason:n.reason,remediation:n.selected!=null?[`Prefer ${n.selected.candidate.source} candidate ${n.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:n,verdict:n.verdict}}function S6($){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 Q6($){let b=xm($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function Yj($){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 Z6}from"crypto";function Hj($,b,A){let n=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:A?`Generated path: ${A}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||A?"warn":"pass",detail:n}}function Gj($,b){let A=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",n=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:A,detail:n}}function qj($,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 Oj($,b,A,n,m,y){let W=y.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${y.runtimeLink.decisionId}`:y.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${y.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${Z6()}`,sourceDecisionId:b,objective:n.objective,reason:y.reason,summary:{paths:m,impactedContracts:A.impactedContracts,affectedSurfaces:A.affectedSurfaces,requiredChecks:n.requiredChecks},evidence:[{type:"context-pack",ref:y.artifactRefs.contextPack},{type:"plan-packet",ref:y.artifactRefs.planPacket},{type:"patch-verdict",ref:y.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:W}],requiredApprovals:[{capability:V$.key,reason:y.reason}],controlPlane:{traceQuery:j0,policyExplain:B0,approvalStatus:y.runtimeLink?.approvalStatus,decisionId:y.runtimeLink?.decisionId,traceId:y.runtimeLink?.traceId??A.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Mm($,b,A,n,m,y,W,w,j){let B=x$(W);return{decisionId:$,summary:n.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:m,checks:y,verdict:W,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:j?.approvalStatus,decisionId:j?.decisionId,traceId:j?.traceId??A.actor.traceId},approvalOperationRefs:W==="require_review"?[`${V$.key}@${V$.version}`,`${S0.key}@${S0.version}`]:void 0,remediation:X6(W),reviewPacketRef:w,replay:{traceQuery:j0,policyExplain:B0}}}function X6($){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 H6($,b,A={}){let n=l(b);m$(n),n=i$(n,await $.git.currentBranch());let m=`connect.dec_${Y6()}`,y=(A.now??(()=>new Date))().toISOString(),W=X$(n);await db($.fs,W);let{contextPack:w,planPacket:j}=await lb($,{...b,candidate:O6(b)}),B=J6(b),S=await l$($,{baseline:b.baseline,touchedPaths:B,workspace:n}),Q=await U6(A,n.config.connect?.policy?.smokeChecks??[],n.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=rb(n,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await Xj($,b),H=[Hj(X.immutablePath,X.protectedPath,X.generatedPath),Gj(X.commandState,X.commandMatch),qj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],J=G6(X,Y.verdict),O=x$(J),V=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",U=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:V$.key,reason:V}]:[],K={...j,requiredApprovals:U,verificationStatus:O.verificationStatus},q=Zb($.fs,n,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),G=S.pathImpacts.length>0?S.pathImpacts.map((r)=>({file:r.path,contracts:r.contracts,policies:r.policies,surfaces:r.surfaces})):B.map((r)=>({file:r,contracts:w.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:w.affectedSurfaces})),z=Mm(m,b,w,K,G,H,J,void 0),_=A.controlPlane?await A.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:z,planPacket:K,workspace:n}):null,L=_?{...j,requiredApprovals:U,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:_.decisionId,traceId:_.traceId??j.controlPlane.traceId}}:K,I=J==="require_review"?Oj(n,m,w,L,B,{artifactRefs:q,reason:V,runtimeLink:_}):void 0,E=Mm(m,b,w,L,G,H,J,I?_$($.fs,n,$.fs.join(W.reviewPacketsDir,`${I.id}.json`)):void 0,_);if(Y.remediation?.length)E.remediation=Y.remediation;if(await Lm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:E}),I)await Im($.fs,W,I);let N=await ub($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:E,reviewPacket:I}),M={artifacts:Zb($.fs,n,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:m,createdAt:y,runtimeLink:_??void 0,taskId:b.taskId,verdict:J};return await ob($.fs,W,m,M),await Rm($.fs,W,Yj({contextPack:w,createdAt:y,envelope:M,reviewPacket:I,verifyInput:b,workspace:n})),{contextPack:w,planPacket:L,patchVerdict:E,reviewPacket:I,historyDir:N}}function G6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return q6($.verdict,b)}function q6($,b){if(!b)return $;return Jj($)<=Jj(b)?$:b}function Jj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function O6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function J6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function U6($,b,A){if(!$.runCommand)return[];let n=[];for(let m of b){let y=await $.runCommand(m,{cwd:A});n.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return n}H0();var Dm={};f(Dm,{generateWorkflowSpec:()=>dW,generateWorkflowRunnerTemplate:()=>kA,generateWorkflowDevkitWorkflowTemplate:()=>NA,generateWorkflowDevkitStreamRouteTemplate:()=>gA,generateWorkflowDevkitStartRouteTemplate:()=>FA,generateWorkflowDevkitGenericTemplate:()=>PA,generateWorkflowDevkitFollowUpRouteTemplate:()=>vA,generateVisualizationSpec:()=>qW,generateTranslationSpec:()=>HW,generateThemeSpec:()=>hW,generateTestTemplate:()=>NW,generateTestSpec:()=>YW,generateTelemetrySpec:()=>cW,generatePwaAppManifestSpec:()=>KW,generateProductIntentSpec:()=>JW,generatePresentationSpec:()=>fW,generatePolicySpec:()=>XW,generateOperationSpec:()=>rW,generateMigrationSpec:()=>kW,generateKnowledgeSpaceSpec:()=>gW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>vW,generateHarnessSuiteSpec:()=>VW,generateHarnessScenarioSpec:()=>UW,generateHandlerTemplate:()=>TW,generateFormSpec:()=>EW,generateFeatureSpec:()=>MW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>EA,generateEventSpec:()=>CW,generateDataViewSpec:()=>IW,generateDataViewRendererTemplate:()=>TA,generateComponentTemplate:()=>DW,generateCapabilitySpec:()=>ZW,generateAppBlueprintSpec:()=>RW,generateAgentSpec:()=>OW});H0();class Kj{ai;templates=Dm;constructor($){this.ai=new Y0($)}}function qz($){return new Kj($)}import{scanSpecSource as M6}from"@contractspec/module.workspace";function _j($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function _z($,b,A={}){let{fs:n,logger:m}=b,y=await n.exists($);if(!y&&!A.force)return{specPath:$,specInfo:_j($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let W=_j($),w;if(y)try{let B=await n.readFile($);W=M6(B,$),w=W.key}catch{}let j=[];if(A.clean&&w)try{let B=await A0(w,{fs:n});for(let S of B)try{await n.remove(S.filePath),j.push(S.filePath),m.info(`Removed artifact: ${S.filePath}`)}catch{m.warn(`Could not remove artifact: ${S.filePath}`)}}catch{m.warn("Could not discover implementations for cleanup")}if(y)await n.remove($),m.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:W,deleted:!0,cleanedFiles:j,errors:[]}}import{computeSemanticDiff as E6}from"@contractspec/module.workspace";async function Rz($,b,A,n={}){let{fs:m,git:y}=A;if(!await m.exists($))throw Error(`Spec file not found: ${$}`);let w=await m.readFile($),j,B;if(n.baseline)j=await y.showFile(n.baseline,$),B=`${n.baseline}:${$}`;else{if(!await m.exists(b))throw Error(`Spec file not found: ${b}`);j=await m.readFile(b),B=b}let S=E6(w,$,j,B,{breakingOnly:n.breakingOnly});return{spec1:$,spec2:B,differences:S}}b$();import{openApiForRegistry as T6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Nm}from"@contractspec/lib.contracts-spec/operations";async function D6($,b){let{fs:A,logger:n}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;n.info("Loading registry...",{registryPath:m});let W=await N6(m,A);n.info("Generating OpenAPI document...");let w=T6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2117
|
+
`,B=A.resolve(y);return await A.mkdir(A.dirname(B)),await A.writeFile(B,j),n.info(`OpenAPI document written to ${B}`),{document:w,outputPath:B,json:j}}async function N6($,b){let n=await import(b.resolve($));if(n instanceof Nm)return n;if(n.registry instanceof Nm)return n.registry;let m=typeof n.createRegistry==="function"?n.createRegistry:typeof n.default==="function"?n.default:void 0;if(m){let y=await m();if(y instanceof Nm)return y}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as F6,parseOpenApi as v6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Fm,dirname as zj,join as Xb}from"path";function g6($,b,A){if(b.outputDir)return b.outputDir;let{outputDir:n,conventions:m}=A;switch($){case"operation":return Xb(n,m.operations.split("|")[0]??"operations");case"event":return Xb(n,m.events);case"model":return Xb(n,"models");default:return n}}async function Lj($,b,A){let{fs:n,logger:m}=A,{source:y,prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;m.info(`Importing from OpenAPI: ${y}`);let X=await v6(y,{fetch:globalThis.fetch,readFile:(U)=>n.readFile(U)});if(X.warnings.length>0)for(let U of X.warnings)m.warn(`Parse warning: ${U}`);m.info(`Parsed ${X.operations.length} operations from ${X.info.title} v${X.info.version}`);let Y=F6(X,$,{prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q});m.info(`Import result: ${Y.summary.imported} imported, ${Y.summary.skipped} skipped, ${Y.summary.errors} errors`);let H=[],J=[],O=[],V=new Map;for(let U of Y.operationSpecs){let K="operation",q=null;if(U.code.includes("defineEvent("))K="event",q=U.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((U.code.includes("defineSchemaModel(")||U.code.includes("new EnumType(")||U.code.includes("ScalarTypeEnum.")||U.code.includes("new ZodSchemaType(")||U.code.includes("z.enum(")||U.code.includes("new JsonSchemaType(")||U.code.includes("new GraphQLSchemaType("))&&!U.code.includes("defineCommand(")&&!U.code.includes("defineQuery("))K="model";else K="operation",q=U.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let G=g6(K,b,$),z=Xb(G,U.fileName);if(!q&&K==="model"){if(U.code.includes("new ZodSchemaType("))q=U.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(U.code.includes("new JsonSchemaType("))q=U.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(U.code.includes("new GraphQLSchemaType("))q=U.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!q)q=U.code.match(/export const (\w+)\s*=/)}if(Z)m.info(`[DRY RUN] Would create: ${z}`);else{let _=zj(z);if(!await n.exists(_))await n.mkdir(_);await n.writeFile(z,U.code),m.info(`Created: ${z}`)}if(H.push({path:z,operationId:U.source.sourceId,specName:U.fileName.replace(".ts","")}),q){let _=zj(z),L=V.get(_)||[];L.push({file:Fm(z),name:q[1],type:K}),V.set(_,L)}}if(!Z&&H.length>0)for(let[U,K]of V.entries()){if(K.length===0)continue;let q=K.map((M)=>M.type),G=q.every((M)=>M==="operation"),z=q.every((M)=>M==="event"),_=q.every((M)=>M==="model"),L=`/**
|
|
2086
2118
|
* Auto-generated registry file.
|
|
2087
2119
|
*/
|
|
2088
|
-
`;
|
|
2120
|
+
`;K.forEach((M)=>{let r=`./${Fm(M.file,".ts")}`;L+=`import { ${M.name} } from '${r}';
|
|
2089
2121
|
`}),L+=`
|
|
2090
|
-
`;let
|
|
2122
|
+
`;let I=!1;if(G)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
2091
2123
|
|
|
2092
2124
|
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
2093
|
-
`,
|
|
2094
|
-
`}),
|
|
2125
|
+
`,K.forEach((M)=>{L+=`operationRegistry.register(${M.name});
|
|
2126
|
+
`}),I=!0;else if(z)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
2095
2127
|
|
|
2096
2128
|
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2097
|
-
`,
|
|
2098
|
-
`}),
|
|
2129
|
+
`,K.forEach((M)=>{L+=`eventRegistry.register(${M.name});
|
|
2130
|
+
`}),I=!0;else if(_)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
2099
2131
|
|
|
2100
2132
|
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2101
|
-
`,
|
|
2102
|
-
`}),
|
|
2133
|
+
`,K.forEach((M)=>{L+=`modelRegistry.register(${M.name});
|
|
2134
|
+
`}),I=!0;if(I){let M=Xb(U,"registry.ts");await n.writeFile(M,L),m.info(`Created/Updated registry: ${M}`)}let E=`/**
|
|
2103
2135
|
* Auto-generated barrel file.
|
|
2104
2136
|
*/
|
|
2105
2137
|
|
|
2106
|
-
`;if(
|
|
2107
|
-
`}),
|
|
2108
|
-
`;let
|
|
2109
|
-
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function
|
|
2138
|
+
`;if(K.forEach((M)=>{let r=`./${Fm(M.file,".ts")}`;E+=`export * from '${r}';
|
|
2139
|
+
`}),I)E+=`export * from './registry';
|
|
2140
|
+
`;let N=Xb(U,"index.ts");await n.writeFile(N,E),m.info(`Created/Updated index: ${N}`)}for(let U of Y.skipped)J.push({operationId:U.sourceId,reason:U.reason}),m.debug(`Skipped: ${U.sourceId} - ${U.reason}`);for(let U of Y.errors)O.push({operationId:U.sourceId,error:U.error}),m.error(`Error: ${U.sourceId} - ${U.error}`);return{imported:Y.summary.imported,skipped:Y.summary.skipped,errors:Y.summary.errors,files:H,skippedOperations:J,errorMessages:O}}import{importFromOpenApi as P6,parseOpenApi as k6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as r6,join as f6}from"path";async function kz($,b,A){let{fs:n,logger:m}=A,{sources:y,sourceName:W,interactive:w,force:j,dryRun:B}=$,{outputDir:S}=b,Q=y??b.openapi?.sources??[];if(W){if(Q=Q.filter((X)=>X.name===W),Q.length===0)throw Error(`Source not found: ${W}`)}if(Q.length===0)return m.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let Z={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let X of Q){m.info(`Syncing with source: ${X.name}`);let Y=X.url??X.file;if(!Y){m.warn(`Source ${X.name} has no url or file configured`);continue}let H=await k6(Y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});m.info(`Parsed ${H.operations.length} operations from ${X.name}`);let J=P6(H,b,{prefix:X.prefix,tags:X.tags,exclude:X.exclude,defaultStability:X.defaultStability,defaultAuth:X.defaultAuth});for(let O of J.operationSpecs){let V=f6(S,O.fileName);if(!await n.exists(V)){if(!B){let K=r6(V);await n.mkdir(K),await n.writeFile(V,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:V}),m.info(`Added: ${O.source.sourceId}`)}else if(await n.readFile(V)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:V});else if(j==="openapi"){if(!B)await n.writeFile(V,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:V}),m.info(`Updated: ${O.source.sourceId}`)}else if(j==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:V}),m.info(`Kept: ${O.source.sourceId}`);else if(w)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:V}),m.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:V}),m.warn(`Conflict: ${O.source.sourceId}`)}}return m.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as c6}from"@contractspec/lib.contracts-transformers/openapi";async function cz($,b){let{fs:A,logger:n}=b,{specPath:m,openApiSource:y,ignoreDescriptions:W,ignoreTags:w,ignoreTransport:j}=$;n.info(`Validating specs against OpenAPI: ${y}`);let B=await c6(y,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});n.info(`Parsed ${B.operations.length} operations from ${B.info.title}`);let S=new Map;for(let O of B.operations)S.set(O.operationId,O);let Q=[],Z=0,X=0,Y=await A.stat(m),H=[];if(Y.isDirectory){let O=await A.glob({pattern:"**/*.ts",cwd:m,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});H.push(...O)}else H.push(m);n.info(`Found ${H.length} spec files to validate`);for(let O of H)try{let V=await A.readFile(O),U=V.match(/operationId:\s*['"]([^'"]+)['"]/)||V.match(/name:\s*['"]([^'"]+)['"]/)||V.match(/export\s+const\s+(\w+)Spec\s*=/);if(!U||!U[1]){n.debug(`Could not extract operationId from ${O}`);continue}let K=U[1];Z++;let q;if(q=S.get(K),!q){let _=K.replace(/([A-Z])/g,"_$1").toLowerCase();q=S.get(_)}if(!q){for(let[_,L]of S)if(_.toLowerCase().includes(K.toLowerCase())||K.toLowerCase().includes(_.toLowerCase())){q=L;break}}if(!q){Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${K}`}]}),X++;continue}let G=[];if(q.deprecated&&!V.includes("deprecated"))G.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!j){let _=V.match(/path:\s*['"]([^'"]+)['"]/);if(_&&_[1]!==q.path)G.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${_[1]}", OpenAPI has "${q.path}"`})}if(!j){let _=V.match(/method:\s*['"]([^'"]+)['"]/);if(_?.[1]&&_[1].toLowerCase()!==q.method.toLowerCase())G.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${_[1]}", OpenAPI has "${q.method.toUpperCase()}"`})}let z=G.length===0;if(!z)X++;Q.push({specPath:O,operationId:q.operationId,valid:z,diffs:G})}catch(V){n.error(`Error validating ${O}: ${V}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${V instanceof Error?V.message:String(V)}`}]}),X++}let J=X===0;return n.info(`Validation ${J?"passed":"failed"}: ${Z} specs checked, ${X} with differences`),{valid:J,specsValidated:Z,specsWithDiffs:X,results:Q}}async function ez($,b,A){let{fs:n,logger:m}=$,{source:y,outputDir:W}=b,w=n.resolve(A??process.cwd(),y);if(!await n.exists(w))throw Error(`Source file not found: ${w}`);let B={...await P(n,A),outputDir:W};return m.info(`Extracting contracts from ${w} to ${W}`),Lj(B,{source:w,outputDir:W,dryRun:!1},$)}var Ij={};f(Ij,{validateFeatureRefs:()=>u6,getArrayNameForSpecType:()=>Rj,detectFeatureContext:()=>h6,computeAddSpecEdit:()=>d6});function h6($,b){let A=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],n=null;for(let{type:Q,regex:Z,specType:X}of A){let Y;Z.lastIndex=0;while((Y=Z.exec($))!==null)if(!n||Y.index>n.index)n={type:Q,specType:X,index:Y.index}}if(!n)return null;let m=$.slice(n.index)+b,y=n.type;new RegExp(`${y}\\s*:\\s*\\[`).exec(m);let w=$.slice(n.index),j=0,B=!1,S="";for(let Q=0;Q<w.length;Q++){let Z=w[Q],X=Q>0?w[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&X!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")j++;else if(Z==="]"){if(j--,j===0)return null}}if(j>0)return{type:n.type,specType:n.specType};return null}function d6($,b){let A=Rj(b.type),m=new RegExp(`${A}\\s*:\\s*\\[`,"g").exec($);if(m){let y=m.index+m[0].length,W=typeof b.version==="string"?`'${b.version}'`:b.version,w=`
|
|
2141
|
+
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function Rj($){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 u6($,b){let A=[],n=(m,y,W)=>{for(let w of m){let j=`${w.key}.v${w.version}`;if(!y.has(j))A.push({key:w.key,version:w.version,type:W,message:`${W} ${w.key}.v${w.version} not found`})}};return n($.operations,b.operations,"Operation"),n($.events,b.events,"Event"),n($.presentations,b.presentations,"Presentation"),n($.experiments,b.experiments,"Experiment"),A}var Ej={};f(Ej,{removeReferenceStrategy:()=>J0,implementSkeletonStrategy:()=>O0,implementAiStrategy:()=>q0,generateFixLinks:()=>o6,FixService:()=>Mj,FIX_STRATEGY_STABILITY:()=>bA,FIX_STRATEGY_LABELS:()=>e6,CiOutputSchema:()=>B7});function o6($,b){let A=[];if(!$.ref||!$.file)return A;if(b.includeCli)A.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let n=$.file.startsWith("/")?$.file:`/${$.file}`,m=$.ref,y=m.line||1,W=m.column||1;A.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${n}:${y}:${W}`})}if(b.includeGithubIssue&&b.repository){let n=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),m=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
2110
2142
|
|
|
2111
2143
|
> ${$.message}
|
|
2112
2144
|
|
|
2113
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
2114
|
-
`)}function
|
|
2145
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);A.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${n}&body=${m}`})}return A}import s6 from"path";function M$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function E$($,b){let A=$.enrichment?.owners?.length?$.enrichment.owners.map((W)=>`'${W}'`).join(", "):"'@team'",n=$.enrichment?.tags?.length?$.enrichment.tags.map((W)=>`'${W}'`).join(", "):"",m=$.description||`TODO: Add description for ${$.key}`,y=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([W,w])=>{if(w!==void 0)y.push(`${W}: ${w}`)});return y.push(`owners: [${A}]`),y.push(`tags: [${n}]`),y.push(`description: '${m}'`),y.join(`,
|
|
2146
|
+
`)}function ab($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"Spec",n=E$($,{kind:"'api'"});return`/**
|
|
2115
2147
|
* Capability: ${$.key}
|
|
2116
2148
|
*
|
|
2117
2149
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2122,9 +2154,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",labe
|
|
|
2122
2154
|
|
|
2123
2155
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
2124
2156
|
|
|
2125
|
-
export const ${
|
|
2157
|
+
export const ${A} = defineCapability({
|
|
2126
2158
|
meta: {
|
|
2127
|
-
${
|
|
2159
|
+
${n}
|
|
2128
2160
|
},
|
|
2129
2161
|
|
|
2130
2162
|
provides: [
|
|
@@ -2148,7 +2180,7 @@ export const ${n} = defineCapability({
|
|
|
2148
2180
|
// }
|
|
2149
2181
|
],
|
|
2150
2182
|
});
|
|
2151
|
-
`}function
|
|
2183
|
+
`}function eb($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"EventSpec",n=A.replace("Spec","Payload"),m=E$($);return`/**
|
|
2152
2184
|
* Event: ${$.key}
|
|
2153
2185
|
*
|
|
2154
2186
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2161,8 +2193,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
2161
2193
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2162
2194
|
|
|
2163
2195
|
// TODO: Define event payload schema
|
|
2164
|
-
export const ${
|
|
2165
|
-
name: '${
|
|
2196
|
+
export const ${n} = new SchemaModel({
|
|
2197
|
+
name: '${n}',
|
|
2166
2198
|
description: 'Payload for ${$.key} event',
|
|
2167
2199
|
fields: {
|
|
2168
2200
|
// Add your payload fields here
|
|
@@ -2172,12 +2204,12 @@ export const ${A} = new SchemaModel({
|
|
|
2172
2204
|
},
|
|
2173
2205
|
});
|
|
2174
2206
|
|
|
2175
|
-
export const ${
|
|
2207
|
+
export const ${A} = defineEvent({
|
|
2176
2208
|
meta: {
|
|
2177
2209
|
${m}
|
|
2178
2210
|
},
|
|
2179
2211
|
|
|
2180
|
-
payload: ${
|
|
2212
|
+
payload: ${n},
|
|
2181
2213
|
|
|
2182
2214
|
// TODO: Specify PII fields if any
|
|
2183
2215
|
// piiFields: ['user.email'],
|
|
@@ -2188,7 +2220,7 @@ export const ${n} = defineEvent({
|
|
|
2188
2220
|
// policy: 'archive',
|
|
2189
2221
|
// },
|
|
2190
2222
|
});
|
|
2191
|
-
`}function
|
|
2223
|
+
`}function i6($){let b=$.toLowerCase(),A=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let n of A)if(b.includes(n))return"query";return"command"}function sb($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"Spec",n=A.replace("Spec","Input"),m=A.replace("Spec","Output"),y=i6($.key),W=y==="query"?"defineQuery":"defineCommand",w=$.enrichment?.goal||"TODO: Define the business goal",j=$.enrichment?.context||"TODO: Provide context",B=E$($,{goal:`'${w}'`,context:`'${j}'`});return`/**
|
|
2192
2224
|
* Operation: ${$.key}
|
|
2193
2225
|
*
|
|
2194
2226
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2201,8 +2233,8 @@ import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
|
2201
2233
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2202
2234
|
|
|
2203
2235
|
// TODO: Define input schema
|
|
2204
|
-
export const ${
|
|
2205
|
-
name: '${
|
|
2236
|
+
export const ${n} = new SchemaModel({
|
|
2237
|
+
name: '${n}',
|
|
2206
2238
|
description: 'Input for ${$.key}',
|
|
2207
2239
|
fields: {
|
|
2208
2240
|
// Add your input fields here
|
|
@@ -2220,13 +2252,13 @@ export const ${m} = new SchemaModel({
|
|
|
2220
2252
|
},
|
|
2221
2253
|
});
|
|
2222
2254
|
|
|
2223
|
-
export const ${
|
|
2255
|
+
export const ${A} = ${W}({
|
|
2224
2256
|
meta: {
|
|
2225
2257
|
${B}
|
|
2226
2258
|
},
|
|
2227
2259
|
|
|
2228
2260
|
io: {
|
|
2229
|
-
input: ${
|
|
2261
|
+
input: ${n},
|
|
2230
2262
|
output: ${m},
|
|
2231
2263
|
errors: {
|
|
2232
2264
|
// TODO: Define possible errors
|
|
@@ -2266,7 +2298,7 @@ export const ${n} = ${W}({
|
|
|
2266
2298
|
examples: [],
|
|
2267
2299
|
},
|
|
2268
2300
|
});
|
|
2269
|
-
`}function
|
|
2301
|
+
`}function l6($){let b=$.toLowerCase();if(b.includes("doc")||b.includes("guide")||b.includes("readme"))return"markdown";if(b.includes("data")||b.includes("api")||b.includes("export"))return"data";return"web_component"}function $A($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"PresentationSpec",n=l6($.key),m=E$($);return`/**
|
|
2270
2302
|
* Presentation: ${$.key}
|
|
2271
2303
|
*
|
|
2272
2304
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2277,12 +2309,12 @@ export const ${n} = ${W}({
|
|
|
2277
2309
|
|
|
2278
2310
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
2279
2311
|
|
|
2280
|
-
export const ${
|
|
2312
|
+
export const ${A} = definePresentation({
|
|
2281
2313
|
meta: {
|
|
2282
2314
|
${m}
|
|
2283
2315
|
},
|
|
2284
2316
|
|
|
2285
|
-
kind: '${
|
|
2317
|
+
kind: '${n}',
|
|
2286
2318
|
|
|
2287
2319
|
// TODO: Define content structure
|
|
2288
2320
|
content: {
|
|
@@ -2306,7 +2338,7 @@ export const ${n} = definePresentation({
|
|
|
2306
2338
|
// focusable: true,
|
|
2307
2339
|
// },
|
|
2308
2340
|
});
|
|
2309
|
-
`}import H$ from"path";function 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
|
|
2341
|
+
`}import G$ from"path";function G0($,b){if(b.outputDir)return vm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=t6($.featureFile);if(A)return vm(A,$.ref.key,$.specType)}return vm(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function t6($){let b=G$.dirname($),A=G$.parse($).root,n=0;while(b!==A&&n<50){if(G$.basename(b)==="src")return b;b=G$.dirname(b),n++}b=G$.dirname($),n=0;while(b!==A&&n<50)b=G$.dirname(b),n++;let m=$.lastIndexOf(`${G$.sep}src${G$.sep}`);if(m!==-1)return $.substring(0,m+5);return null}function vm($,b,A){let n=b.replace(/\./g,"-").toLowerCase(),m=p6(A),y=a6(A);return G$.join($,y,`${n}${m}`)}function p6($){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 a6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var e6={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},bA={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function q0($,b,A){let{fs:n,logger:m}=A,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:bA["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await $7(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=n7(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=G0($,b),Z=[];if(!b.dryRun){let X=s6.dirname(Q);await n.mkdir(X),await n.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(j){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}async function $7($,b,A){if(A.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:m}=await Promise.resolve().then(() => (H0(),Vj)),y=b7(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){A.warn("AIGenerator call failed, falling back to heuristics",{error:m instanceof Error?m.message:String(m)})}let n=A7($.key,$.specType);return{...$,description:n.description,enrichment:{goal:n.goal,context:n.context,owners:["@team"],tags:n.tags}}}function b7($){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 A7($,b){let A=$.split("."),n=A[0]||"unknown",m=A.slice(1).join(" ").replace(/_/g," "),y=[n],W=m.toLowerCase().split(" "),j=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>W.some((S)=>S.includes(B)));return{description:`${Cj(b)} for ${n} ${m}`,goal:`Enable ${m} functionality in the ${n} domain`,context:`Part of the ${n} feature set. Generated by ContractSpec AI fix.`,tags:[...y,...j]}}function n7($){switch($.specType){case"operation":return sb($);case"event":return eb($);case"presentation":return $A($);case"capability":return ab($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import m7 from"path";async function O0($,b,A){let{fs:n}=A,{ref:m,specType:y,featureKey:W}=$;try{let w={key:m.key,version:m.version,specType:y,stability:bA["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=y7(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=G0($,b),S=[];if(!b.dryRun){let Q=m7.dirname(B);await n.mkdir(Q),await n.writeFile(B,j),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function y7($){switch($.specType){case"operation":return sb($);case"event":return eb($);case"presentation":return $A($);case"capability":return ab($);default:return}}async function J0($,b,A){let{fs:n}=A,{ref:m,featureFile:y,specType:W}=$;try{let w=await n.readFile(y),j=w,B=W7(w,m,W);if(B===w)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${m.key}.v${m.version} in ${y}`};let S=[];if(!b.dryRun)await n.writeFile(y,B),S.push({path:y,action:"modified",previousContent:j});else S.push({path:y,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function W7($,b,A){if(!w7(A))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=j7(w),w}function w7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j7($){return $.replace(/,(\s*)\]/g,"$1]")}class Mj{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,A)=>J0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,A)=>O0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,A)=>q0(b,A,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let A=this.strategies.get(b.strategy);if(!A)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),A.fix($,b)}async batchFix($){let b=[],A=0,n=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)A++;else n++}catch(y){n++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:A,failed:n,results:b}}async scanAndGetFixables($={}){return(await n0(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((A)=>this.getToFix(A)).filter((A)=>A!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let A=this.parseFixableIssue($);if(!A)return null;return{...A,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:A,preferAi:n,select:m}=b;if(A)return Promise.resolve(A);if(n&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof m==="function")return m($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as Yb}from"zod";var B7=Yb.union([Yb.array(Yb.unknown()),Yb.object({issues:Yb.array(Yb.unknown())}).transform(($)=>$.issues)]);import{exec as S7}from"child_process";import{promisify as Q7}from"util";var Z7=Q7(S7),Tj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function aL($,b,A={}){if($.length===0)return;let n=A.cwd??process.cwd(),m=Tj[A.type??"biome"]??Tj.biome,y=50;for(let W=0;W<$.length;W+=y){let j=$.slice(W,W+y).map((B)=>`"${B}"`).join(" ");try{await Z7(`${m} ${j}`,{cwd:n})}catch(B){}}}import T$ from"path";async function bR($,b){let A=T$.join(b,"contracts"),n=T$.join(b,"generated"),m=T$.join(n,"docs"),y=await $.fs.exists(A),W=await $.fs.exists(n);if(!y)return{hasContracts:!1,hasGenerated:W,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let w=await B$($,{pattern:"contracts/**/*.ts"}),j=[];if(W)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts"),H=T$.join(m,`${Y}.md`);if(!await $.fs.exists(H))j.push(Y)}else if(w.length>0)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts");j.push(Y)}let B=T$.join(A,"index.ts"),S=T$.join(A,"registry.ts"),Q=w.length>0&&!await $.fs.exists(B),Z=w.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:W,missingDocs:j,missingIndex:Q,missingRegistry:Z,totalSpecs:w.length}}var vj={};f(vj,{runHook:()=>Dj,getAvailableHooks:()=>Nj});import{exec as X7}from"child_process";import{promisify as Y7}from"util";var H7=Y7(X7);async function Dj($,b){let{fs:A,logger:n}=$,{hookName:m,dryRun:y=!1}=b,W=x(b.workspaceRoot);n.info(`Running hook: ${m}`,{workspaceRoot:W,dryRun:y});let w=await Fj(A,W);if(!w)return{hookName:m,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let j=w[m];if(!j||j.length===0)return{hookName:m,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${m}`};n.info(`Found ${j.length} command(s) for ${m}`);let B=[],S=!0;for(let Z of j){if(y){n.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}n.info(`Executing: ${Z}`);try{let{stdout:X,stderr:Y}=await H7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),n.info(`\u2713 ${Z}`)}catch(X){S=!1;let Y=X;B.push({command:Z,success:!1,exitCode:Y.code??1,stdout:Y.stdout??"",stderr:Y.stderr??Y.message??String(X)}),n.error(`\u2717 ${Z}`,{exitCode:Y.code,stderr:Y.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:m,success:S,commandResults:B,totalCommands:j.length,successfulCommands:Q,summary:S?`\u2713 All ${j.length} command(s) passed`:`\u2717 ${Q}/${j.length} command(s) passed`}}async function Nj($,b){let A=await Fj($.fs,b);return A?Object.keys(A):[]}async function Fj($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return null;try{let n=await $.readFile(A);return JSON.parse(n).hooks??null}catch{return null}}import{detectFramework as G7,extractFromProject as q7}from"@contractspec/lib.source-extractors";import{generateOperations as O7,generateRegistry as J7,generateSchemas as U7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as V7}from"@contractspec/lib.source-extractors/extractors";import{dirname as K7,join as gm}from"path";async function _7($,b,A,n){let{fs:m,logger:y}=A,W=n??process.cwd();V7(),y.info(`Scanning source code in ${W}...`);let w={readFile:(K)=>m.readFile(K),glob:(K,q)=>m.glob({pattern:K,cwd:q?.cwd}),exists:(K)=>m.exists(K)},j=await G7(W,{readFile:(K)=>m.readFile(K),glob:(K)=>m.glob({pattern:K})});if(j.frameworks.length===0)return y.warn("No supported frameworks detected"),{success:!1,report:z7(),errors:["No supported frameworks detected in project"]};y.info(`Detected frameworks: ${j.frameworks.map((K)=>K.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let K of B.getAll())if("setFs"in K&&typeof K.setFs==="function")K.setFs(w);let S={scope:b.scope,framework:b.framework},Q=await q7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:L7(Q.errors??[]),errors:Q.errors?.map((K)=>K.message)};let Z=Q.ir;if(y.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:R7(Z)};let X=b.outputDir??gm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},H=O7(Z,Y),J=U7(Z,Y),O=J7(H),V=[...H,...J,O];if(!b.dryRun)for(let K of V){let q=gm(X,K.path),G=K7(q);if(!await m.exists(G))await m.mkdir(G);await m.writeFile(q,K.content),y.info(`Created: ${q}`)}else for(let K of V)y.info(`[DRY RUN] Would create: ${gm(X,K.path)}`);let U={files:V,operationsGenerated:H.length,schemasGenerated:J.length,warnings:[]};return{success:!0,ir:Z,generation:U,report:I7(Z,U,b)}}function z7(){return`# Import Report
|
|
2310
2342
|
|
|
2311
2343
|
## \u274C No Supported Frameworks Detected
|
|
2312
2344
|
|
|
@@ -2323,13 +2355,13 @@ No supported frameworks were detected in the project.
|
|
|
2323
2355
|
- Next.js API Routes
|
|
2324
2356
|
|
|
2325
2357
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
2326
|
-
`}function
|
|
2358
|
+
`}function L7($){return`# Import Report
|
|
2327
2359
|
|
|
2328
2360
|
## \u274C Extraction Failed
|
|
2329
2361
|
|
|
2330
2362
|
${$.map((b)=>`- ${b.message}`).join(`
|
|
2331
2363
|
`)}
|
|
2332
|
-
`}function
|
|
2364
|
+
`}function R7($){return`# Import Analysis Report
|
|
2333
2365
|
|
|
2334
2366
|
## Summary
|
|
2335
2367
|
|
|
@@ -2361,7 +2393,7 @@ ${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).jo
|
|
|
2361
2393
|
|
|
2362
2394
|
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
2363
2395
|
`):"None"}
|
|
2364
|
-
`}function
|
|
2396
|
+
`}function I7($,b,A){return`# Import Report${A.dryRun?" (Dry Run)":""}
|
|
2365
2397
|
|
|
2366
2398
|
## \u2705 Import Successful
|
|
2367
2399
|
|
|
@@ -2387,42 +2419,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
|
2387
2419
|
|
|
2388
2420
|
### Next Steps
|
|
2389
2421
|
|
|
2390
|
-
1. Review generated contracts in \`${
|
|
2422
|
+
1. Review generated contracts in \`${A.outputDir??"generated/"}\`
|
|
2391
2423
|
2. Fill in TODO placeholders with business context
|
|
2392
2424
|
3. Run \`contractspec validate\` to verify contracts
|
|
2393
2425
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
2394
|
-
`}function
|
|
2395
|
-
`)}function
|
|
2396
|
-
`)}async function
|
|
2397
|
-
`)}function
|
|
2398
|
-
`)}function
|
|
2399
|
-
`)}function
|
|
2400
|
-
`);
|
|
2401
|
-
`)}function
|
|
2402
|
-
`)}async function
|
|
2426
|
+
`}function C7($,b,A={}){let n=[];if(n.push("# Import Report"),n.push(""),n.push(`**Generated**: ${new Date().toISOString()}`),n.push(""),n.push("## Summary"),n.push(""),n.push("| Metric | Count |"),n.push("|--------|-------|"),n.push(`| Files Scanned | ${$.stats.filesScanned} |`),n.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),n.push(`| Schemas Found | ${$.stats.schemasFound} |`),n.push(`| Errors Found | ${$.stats.errorsFound} |`),n.push(`| Events Found | ${$.stats.eventsFound} |`),n.push(""),A.includeStats!==!1)n.push("### Confidence"),n.push(""),n.push("| Level | Count |"),n.push("|-------|-------|"),n.push(`| High | ${$.stats.highConfidence} |`),n.push(`| Medium | ${$.stats.mediumConfidence} |`),n.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),n.push("");n.push("### Frameworks Detected"),n.push("");for(let m of $.project.frameworks)n.push(`- **${m.name}** (${m.confidence})`);if(n.push(""),A.includeEndpoints!==!1&&$.endpoints.length>0){n.push("## Endpoints"),n.push(""),n.push("| Method | Path | Kind | Confidence |"),n.push("|--------|------|------|------------|");for(let m of $.endpoints)n.push(`| ${m.method} | \`${m.path}\` | ${m.kind} | ${m.confidence.level} |`);n.push("")}if(A.includeSchemas!==!1&&$.schemas.length>0){n.push("## Schemas"),n.push(""),n.push("| Name | Type | Confidence |"),n.push("|------|------|------------|");for(let m of $.schemas)n.push(`| ${m.name} | ${m.schemaType} | ${m.confidence.level} |`);n.push("")}if(b&&A.includeIssues!==!1){n.push("## Verification"),n.push(""),n.push("| Status | Count |"),n.push("|--------|-------|"),n.push(`| Valid | ${b.summary.validEndpoints} |`),n.push(`| Warnings | ${b.summary.warningEndpoints} |`),n.push(`| Errors | ${b.summary.errorEndpoints} |`),n.push("");let m=b.endpointResults.filter((y)=>y.issues.length>0);if(m.length>0){n.push("### Issues"),n.push("");for(let y of m){n.push(`#### ${y.endpoint.method} ${y.endpoint.path}`);for(let W of y.issues){let w=W.severity==="error"?"\u274C":W.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(n.push(`- ${w} **${W.code}**: ${W.message}`),W.suggestion)n.push(` - *Suggestion*: ${W.suggestion}`)}n.push("")}}}if(A.includeAmbiguities!==!1&&$.ambiguities.length>0){n.push("## Ambiguities (Require Review)"),n.push("");for(let m of $.ambiguities)if(n.push(`- **${m.type}** (${m.itemId}): ${m.description}`),m.suggestion)n.push(` - *Suggestion*: ${m.suggestion}`);n.push("")}return n.push("## Next Steps"),n.push(""),n.push("1. Review generated contracts in the output directory"),n.push("2. Fill in TODO placeholders with business context"),n.push("3. Run `contractspec validate` to verify contracts"),n.push("4. Move stable contracts from `generated/` to `curated/`"),n.push(""),n.join(`
|
|
2427
|
+
`)}function x7($,b){let A=[];A.push(""),A.push("\uD83D\uDCCA Summary"),A.push(` Files scanned: ${$.stats.filesScanned}`),A.push(` Endpoints: ${$.stats.endpointsFound}`),A.push(` Schemas: ${$.stats.schemasFound}`),A.push(""),A.push("\uD83D\uDCC8 Confidence"),A.push(` High: ${$.stats.highConfidence}`),A.push(` Medium: ${$.stats.mediumConfidence}`),A.push(` Low: ${$.stats.lowConfidence}`),A.push(""),A.push("\uD83D\uDD27 Frameworks");for(let n of $.project.frameworks)A.push(` \u2022 ${n.name}`);if(A.push(""),b)A.push("\u2705 Verification"),A.push(` Valid: ${b.summary.validEndpoints}`),A.push(` Warnings: ${b.summary.warningEndpoints}`),A.push(` Errors: ${b.summary.errorEndpoints}`),A.push("");return A.join(`
|
|
2428
|
+
`)}async function M7($,b,A){let{logger:n}=A,m=[],y=[...$.ambiguities];n.info(`Verifying ${$.endpoints.length} endpoints...`);for(let w of $.endpoints){let j=[];if(w.confidence.level==="low"||w.confidence.level==="ambiguous")j.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${w.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!w.input&&(w.method==="POST"||w.method==="PUT"||w.method==="PATCH"))j.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!w.output)j.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(b.checkDuplicates){if($.endpoints.filter((Q)=>Q.id!==w.id&&Q.path===w.path&&Q.method===w.method).length>0)j.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${w.method} ${w.path} found`,severity:"error"})}if(b.checkConflicts){let S=E7(w,$.endpoints);for(let Q of S)j.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=j.some((S)=>S.severity==="error")?"error":j.some((S)=>S.severity==="warning")?"warning":"valid";m.push({endpoint:w,status:B,issues:j})}if(b.validateSchemas){for(let w of $.schemas)if(!w.fields||w.fields.length===0)y.push({type:"schema",itemId:w.id,description:`Schema ${w.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:w.source})}let W={totalEndpoints:m.length,validEndpoints:m.filter((w)=>w.status==="valid").length,warningEndpoints:m.filter((w)=>w.status==="warning").length,errorEndpoints:m.filter((w)=>w.status==="error").length,totalIssues:m.reduce((w,j)=>w+j.issues.length,0)};return n.info(`Verification complete: ${W.validEndpoints} valid, ${W.warningEndpoints} warnings, ${W.errorEndpoints} errors`),{valid:W.errorEndpoints===0,endpointResults:m,ambiguities:y,summary:W}}function E7($,b){let A=[],n=$.path.split("/").filter(Boolean);for(let m of b){if(m.id===$.id)continue;if(m.method!==$.method)continue;let y=m.path.split("/").filter(Boolean);if(y.length!==n.length)continue;let W=!0;for(let w=0;w<n.length;w++){let j=n[w]??"",B=y[w]??"",S=j.startsWith(":")||j.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&j!==B){W=!1;break}}if(W&&$.path!==m.path)A.push(m)}return A}function zR($,b="feature-map",A={}){switch(b){case"feature-map":return rm($,A);case"orphans":return T7($,A);case"dependencies":return D7($,A);case"full":return N7($,A);default:return rm($,A)}}function rm($,b){let{direction:A="LR",showVersions:n=!0,maxNodes:m=50}=b,y=[`flowchart ${A}`],W=$.features;if(b.featureKeys&&b.featureKeys.length>0)W=W.filter((Z)=>b.featureKeys?.includes(Z.key));let w=0,j=!1;if(W.length>0){y.push(" subgraph features [Features]");for(let Z of W){if(w>=m)break;let X=v(`F_${Z.key}`),Y=Z.title??Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}let B=Pm(W,"operations",$.inventory);if(B.length>0&&w<m){y.push(" subgraph ops [Operations]");for(let Z of B){if(w>=m)break;let X=v(`O_${Z.key}_v${Z.version}`),Y=n?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}let S=Pm(W,"events",$.inventory);if(S.length>0&&w<m){y.push(" subgraph events [Events]");for(let Z of S){if(w>=m)break;let X=v(`E_${Z.key}_v${Z.version}`),Y=n?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}let Q=Pm(W,"presentations",$.inventory);if(Q.length>0&&w<m){y.push(" subgraph presentations [Presentations]");for(let Z of Q){if(w>=m)break;let X=v(`P_${Z.key}_v${Z.version}`),Y=n?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${S$(Y)}"]`),w++}y.push(" end")}for(let Z of W){let X=v(`F_${Z.key}`);for(let Y of Z.operations){let H=v(`O_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${H}`)}for(let Y of Z.events){let H=v(`E_${Y.key}_v${Y.version}`);y.push(` ${X} -.-> ${H}`)}for(let Y of Z.presentations){let H=v(`P_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${H}`)}}if(j)y.push(` note["... and more (truncated at ${m} nodes)"]`);return y.join(`
|
|
2429
|
+
`)}function T7($,b){let{direction:A="TB",showVersions:n=!0,maxNodes:m=50}=b,y=[`flowchart ${A}`],W=new Set,w=new Set,j=new Set;for(let Q of $.features){for(let Z of Q.operations)W.add(`${Z.key}.v${Z.version}`);for(let Z of Q.events)w.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)j.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){y.push(" subgraph features [Features]");for(let Q of $.features){if(B>=m)break;let Z=v(`F_${Q.key}`);y.push(` ${Z}["${S$(Q.title??Q.key)}"]`),B++}y.push(" end")}if($.orphanedSpecs.length>0){y.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=m)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=n?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${S$(X)}"]`),B++}y.push(" end")}let S=[];for(let Q of W){let[Z,X]=km(Q);if(Z&&X)S.push({type:"operation",key:Z,version:X})}for(let Q of w){let[Z,X]=km(Q);if(Z&&X)S.push({type:"event",key:Z,version:X})}for(let Q of j){let[Z,X]=km(Q);if(Z&&X)S.push({type:"presentation",key:Z,version:X})}if(S.length>0&&B<m){y.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=m)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),X=n?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${S$(X)}"]`),B++}y.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let X of Q.operations){let Y=v(`operation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}for(let X of Q.events){let Y=v(`event_${X.key}_v${X.version}`);y.push(` ${Z} -.-> ${Y}`)}for(let X of Q.presentations){let Y=v(`presentation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}}return y.join(`
|
|
2430
|
+
`)}function D7($,b){let{direction:A="TB",showVersions:n=!0,maxNodes:m=50}=b,y=[`flowchart ${A}`],W=0;for(let w of $.features){if(W>=m)break;let j=v(`F_${w.key}`);y.push(` ${j}["${S$(w.title??w.key)}"]`),W++;for(let B of w.operations){if(W>=m)break;let S=v(`O_${B.key}_v${B.version}`),Q=n?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${S$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.events){if(W>=m)break;let S=v(`E_${B.key}_v${B.version}`),Q=n?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${S$(Q)}"]`),y.push(` ${j} -.-> ${S}`),W++}for(let B of w.presentations){if(W>=m)break;let S=v(`P_${B.key}_v${B.version}`),Q=n?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${S$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);y.push(` ${S} --> ${Q}`)}}return y.join(`
|
|
2431
|
+
`)}function N7($,b){let A=rm($,b);if($.orphanedSpecs.length===0)return A;let n=A.split(`
|
|
2432
|
+
`);n.push(" subgraph orphaned [Orphaned Specs]");for(let m of $.orphanedSpecs.slice(0,20)){let y=v(`orphan_${m.type}_${m.key}_v${m.version}`),W=`${m.key}.v${m.version}`;n.push(` ${y}["${S$(W)}"]:::orphan`)}return n.push(" end"),n.push(" classDef orphan stroke-dasharray: 5 5"),n.join(`
|
|
2433
|
+
`)}function Pm($,b,A){let n=new Set,m=[];for(let y of $)for(let W of y[b]){let w=`${W.key}.v${W.version}`;if(!n.has(w))n.add(w),m.push(W)}return m}function km($){let b=$.match(/^(.+)\.v(\d+)$/);if(!b)return[void 0,void 0];return[b[1],b[2]]}function v($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function S$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as F7,specToMarkdown as D$}from"@contractspec/module.workspace";function RR($,b,A){let n=[];if(A.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))n.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))n.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(A.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))n.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))n.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(b))n.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return n}function IR($,b){let A=[];A.push(`# Verification Report: ${$.meta.key}`),A.push("");let n=b.filter((W)=>W.severity==="error"),m=b.filter((W)=>W.severity==="warning"),y=b.filter((W)=>W.severity==="info");if(A.push("## Summary"),A.push(""),A.push(`- Errors: ${n.length}`),A.push(`- Warnings: ${m.length}`),A.push(`- Info: ${y.length}`),A.push(""),n.length>0){A.push("## Errors"),A.push("");for(let W of n)A.push(`- \u274C **${W.category}**: ${W.message}`);A.push("")}if(m.length>0){A.push("## Warnings"),A.push("");for(let W of m)A.push(`- \u26A0\uFE0F **${W.category}**: ${W.message}`);A.push("")}if(y.length>0){A.push("## Info"),A.push("");for(let W of y)A.push(`- \u2139\uFE0F **${W.category}**: ${W.message}`);A.push("")}return A.join(`
|
|
2434
|
+
`)}async function ER($,b){let A=[];A.push(D$($,"context"));let n=await B$(b),m=async(y)=>{let W=n.find((j)=>j.key===y.name&&j.version===y.version);if(!W)return null;return(await F7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){A.push(`
|
|
2403
2435
|
## Operations (${$.operations.length})
|
|
2404
|
-
`);for(let y of $.operations){let W=await m(y);if(W)
|
|
2436
|
+
`);for(let y of $.operations){let W=await m(y);if(W)A.push(D$(W,"full"));else A.push(`### ${y.name} (v${y.version})
|
|
2405
2437
|
|
|
2406
|
-
*Spec not found*`);
|
|
2438
|
+
*Spec not found*`);A.push("---")}}if($.events?.length){A.push(`
|
|
2407
2439
|
## Events (${$.events.length})
|
|
2408
|
-
`);for(let y of $.events){let W=await m(y);if(W)
|
|
2440
|
+
`);for(let y of $.events){let W=await m(y);if(W)A.push(D$(W,"full"));else A.push(`### ${y.name} (v${y.version})
|
|
2409
2441
|
|
|
2410
|
-
*Spec not found*`);
|
|
2442
|
+
*Spec not found*`);A.push("---")}}if($.presentations?.length){A.push(`
|
|
2411
2443
|
## Presentations (${$.presentations.length})
|
|
2412
|
-
`);for(let y of $.presentations){let W=await m(y);if(W)
|
|
2413
|
-
|
|
2414
|
-
*Spec not found*`);
|
|
2415
|
-
`)}function
|
|
2416
|
-
`)}function
|
|
2417
|
-
`)}function
|
|
2418
|
-
`)}function
|
|
2419
|
-
`)}function
|
|
2420
|
-
`)}import{RegeneratorService as
|
|
2444
|
+
`);for(let y of $.presentations){let W=await m(y);if(W)A.push(D$(W,"full"));else A.push(`### ${y.name} (v${y.version})
|
|
2445
|
+
|
|
2446
|
+
*Spec not found*`);A.push("---")}}return A.join(`
|
|
2447
|
+
`)}function v7($,b){let A=[];if(A.push(`# Implementation Guide: ${$.meta.key}`),A.push(""),A.push(`**Target Agent**: ${b}`),A.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),A.push(""),$.meta.description)A.push("## Overview"),A.push(""),A.push($.meta.description),A.push("");if($.meta.goal)A.push("## Goal"),A.push(""),A.push($.meta.goal),A.push("");if($.meta.context)A.push("## Context"),A.push(""),A.push($.meta.context),A.push("");if(A.push("## Implementation Steps"),A.push(""),$.specType==="operation"){if(A.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)A.push("2. Implement input validation according to the schema"),A.push("3. Implement the core business logic"),A.push("4. Return output matching the expected schema");if($.hasPolicy)A.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){A.push("6. Emit events on success:");for(let n of $.emittedEvents)A.push(` - \`${n.name}\` (v${n.version})`)}A.push("7. Add error handling for expected failure cases"),A.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(A.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){A.push("2. Implement operations:");for(let n of $.operations)A.push(` - \`${n.name}\` (v${n.version})`)}if($.presentations&&$.presentations.length>0){A.push("3. Implement presentations:");for(let n of $.presentations)A.push(` - \`${n.name}\` (v${n.version})`)}A.push("4. Wire up feature exports"),A.push("5. Add integration tests")}else A.push("1. Review the spec requirements"),A.push("2. Implement the core logic"),A.push("3. Add tests"),A.push("4. Document the implementation");if(A.push(""),A.push("## Constraints"),A.push(""),A.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)A.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)A.push(`- Tags: ${$.meta.tags.join(", ")}`);if(A.push(""),b==="cursor-cli")A.push("## Cursor Notes"),A.push(""),A.push("- Use Composer mode for multi-file changes"),A.push("- Reference this guide in your cursor rules"),A.push("- Break implementation into small, focused commits");else if(b==="claude-code")A.push("## Claude Code Notes"),A.push(""),A.push("- Use extended thinking for complex logic"),A.push("- Ask for clarification on ambiguous requirements"),A.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")A.push("## General Notes"),A.push(""),A.push("- Use inline comments to guide generation"),A.push("- Review generated code carefully");return A.push(""),A.push("## Spec Definition"),A.push(""),A.push(D$($,"full")),A.join(`
|
|
2448
|
+
`)}function g7($){let b=[];if(b.push(`# ${$.meta.key}`),b.push(""),b.push(`Description: ${$.meta.description??"No description"}`),b.push(""),b.push("## Rules"),b.push(""),$.specType==="operation"){if(b.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)b.push("- Validate input and output against schemas");if($.hasPolicy)b.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)b.push("- Emit documented events")}else if($.specType==="feature")b.push("- Implement all operations and presentations"),b.push("- Follow modular architecture");else b.push(`- Follow ${$.specType} patterns`);return b.push("- Follow project code quality standards"),b.push("- Write tests for new functionality"),b.join(`
|
|
2449
|
+
`)}function TR($,b,A="generic-mcp"){switch(b){case"guide":return v7($,A);case"rules":return g7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as P7}from"fs/promises";import{createRequire as k7}from"module";import{dirname as r7,resolve as Pj}from"path";import{pathToFileURL as f7}from"url";import gj from"vm";import fm from"typescript";async function W$($,b={}){let A=Pj(process.cwd(),$),n=b.runtime??d7();try{let m=n==="bun"?await c7(A):await h7(A);return{modulePath:A,exports:m}}catch(m){throw Error(rj(A,m))}}async function fR($,b){let A=Pj(process.cwd(),$);if(!await b.exists(A))return null;return W$(A)}async function U0($,b={}){return(await W$($,b)).exports}async function kj($,b){let A=await U0($);return fj(A,$,b)}function rj($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function fj($,b,A){if(A.isValue($))return $;for(let n of A.instanceKeys??[])if(A.isValue($[n]))return $[n];for(let n of A.factoryKeys??[]){let m=$[n];if(typeof m!=="function")continue;let y=await m();if(A.isValue(y))return y}throw Error(`${A.description} module ${b} must export a supported instance or factory.`)}async function c7($){return await import(f7($).href)}async function h7($){return await u7($)??{}}function d7(){return typeof globalThis.Bun<"u"?"bun":"node"}var cR={formatModuleLoadError:rj,resolveAuthoredModuleValue:fj};async function u7($){let b=await P7($,"utf-8"),A=fm.transpileModule(b,{compilerOptions:{module:fm.ModuleKind.CommonJS,target:fm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),n={},m={exports:n},y=k7($),W=gj.createContext({module:m,exports:n,require:y,__dirname:r7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new gj.Script(A.outputText,{filename:$}).runInContext(W),m.exports}var ij={};f(ij,{renderOnboardingGuides:()=>dm,listOnboardingTracks:()=>V0,getOnboardingTrack:()=>hm,createOnboardingConnectArtifacts:()=>AZ,buildOnboardingPlan:()=>bZ,ONBOARDING_TRACKS:()=>cm});var cm=[{id:"contracts",title:"Contracts",summary:"Author and validate spec-first contracts before implementation.",description:"Use ContractSpec contracts as the durable source of truth for operations, events, presentations, and validation.",reuseFamily:"contracts",adoptionQuery:"contract operation event policy presentation spec-first contracts",primaryDocsRoute:"/docs/getting-started/start-here",secondaryDocsRoutes:["/docs/guides/spec-validation-and-typing","/docs/guides/generate-docs-clients-schemas"],packages:["@contractspec/lib.contracts-spec","@contractspec/lib.schema"],recommendedCommands:["contractspec create --type operation","contractspec generate","contractspec validate","contractspec ci"],starterExample:{key:"minimal",packageRef:"@contractspec/example.minimal",title:"Minimal",summary:"Smallest reference implementation for baseline ContractSpec usage."},connectSurfaces:["cli","contract","runtime"]},{id:"ui-design",title:"UI Design",summary:"Adopt the design system and contract-backed theming flow.",description:"Use ThemeSpec, the design system, and composed UI surfaces instead of ad-hoc theme files or raw primitives.",reuseFamily:"ui",adoptionQuery:"ui design system theme tokens composed controls themes",adoptionPlatform:"web",primaryDocsRoute:"/docs/tech/contracts/themes",secondaryDocsRoutes:["/docs/guides/first-module-bundle","/docs/getting-started/installation"],packages:["@contractspec/lib.design-system","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec create --type theme","contractspec generate","contractspec validate"],starterExample:{key:"data-grid-showcase",packageRef:"@contractspec/example.data-grid-showcase",title:"Data Grid Showcase",summary:"Reference app for composed design-system tables and contract-backed UI rendering."},connectSurfaces:["cli","runtime","ui"]},{id:"knowledge",title:"Knowledge",summary:"Model trusted knowledge spaces, sources, and retrieval flows.",description:"Use knowledge spaces, bindings, and governed retrieval instead of prompt-only context injection.",reuseFamily:"sharedLibs",adoptionQuery:"knowledge spaces sources bindings retrieval canon ingestion assistant",primaryDocsRoute:"/docs/knowledge",secondaryDocsRoutes:["/docs/knowledge/spaces","/docs/knowledge/examples"],packages:["@contractspec/lib.knowledge","@contractspec/lib.ai-agent"],recommendedCommands:["contractspec create --type knowledge","contractspec validate","contractspec connect adoption resolve --family sharedLibs --stdin"],starterExample:{key:"knowledge-canon",packageRef:"@contractspec/example.knowledge-canon",title:"Knowledge Canon",summary:"Minimal contract-first knowledge space example with bindings and source samples."},advancedExample:{key:"policy-safe-knowledge-assistant",packageRef:"@contractspec/example.policy-safe-knowledge-assistant",title:"Policy-Safe Knowledge Assistant",summary:"End-to-end governed knowledge assistant with policy, locale, and learning flows."},connectSurfaces:["cli","knowledge","mcp","runtime"]},{id:"ai-agents",title:"AI Agents",summary:"Define agents, tools, approvals, and MCP-aware execution.",description:"Use the ContractSpec agent runtime and agent specs instead of ad-hoc prompt wrappers.",reuseFamily:"sharedLibs",adoptionQuery:"ai agent tools approvals mcp orchestration unified agent runtime",primaryDocsRoute:"/docs/libraries/ai-agent",secondaryDocsRoutes:["/docs/advanced/mcp","/docs/getting-started/cli"],packages:["@contractspec/lib.ai-agent","@contractspec/lib.contracts-spec"],recommendedCommands:["contractspec create --type agent","contractspec agent export --spec <path> --format opencode","contractspec validate"],starterExample:{key:"agent-console",packageRef:"@contractspec/example.agent-console",title:"Agent Console",summary:"Reference autonomous-agent workspace with runs, tools, metrics, and replay."},connectSurfaces:["agent","cli","mcp","runtime"]},{id:"learning-journey",title:"Learning Journey",summary:"Guide users through milestones, progression, and adaptive journeys.",description:"Use the learning-journey module and example family for structured onboarding and progression flows.",reuseFamily:"solutions",adoptionQuery:"learning journey onboarding progression coaching drills guided wizard",primaryDocsRoute:"/docs/guides/first-module-bundle",secondaryDocsRoutes:["/docs/getting-started/start-here"],packages:["@contractspec/module.learning-journey","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec examples list --query learning-journey","contractspec validate","contractspec doctor"],starterExample:{key:"learning-journey-ui-onboarding",packageRef:"@contractspec/example.learning-journey-ui-onboarding",title:"Learning Journey UI Onboarding",summary:"Checklist- and journey-map-based onboarding mini app."},advancedExample:{key:"learning-journey-registry",packageRef:"@contractspec/example.learning-journey-registry",title:"Learning Journey Registry",summary:"Registry and template aggregation surface for broader learning-journey compositions."},connectSurfaces:["cli","runtime","solution"]}];function V0(){return cm}function hm($){return cm.find((b)=>b.id===$)}function dm($){return{agentGuide:o7($),humanGuide:l7($)}}function o7($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let A of $.recommendations)b.push(...i7(A.track,A.reason));return b.join(`
|
|
2450
|
+
`)}function i7($,b){let A=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let n of $.recommendedCommands)A.push(`- \`${n}\``);return[...A,""]}function l7($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((A,n)=>`${n+1}. \`${A}\``),"","## Track Guide",""];for(let A of $.recommendations)b.push(...t7(A.track,A.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let A of $.builderNextSteps)b.push(`- \`${A}\``);b.push("")}return b.join(`
|
|
2451
|
+
`)}function t7($,b){let A=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)A.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(A.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)A.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);A.push("","Commands:");for(let n of $.recommendedCommands)A.push(`- \`${n}\``);return A.push("",`Packages: ${$.packages.map((n)=>`\`${n}\``).join(", ")}`,""),A}import{buildContext as p7}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as a7}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as e7}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function cj($,b,A,n){let m=p7({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:A,workspaceId:n}),y=await a7(e7(s7(b)),m);return{journeyContext:m,journeyPlan:y}}function hj($){if(!$||$.length===0)return[...V0()];return $.map((b)=>{let A=hm(b);if(!A)throw Error(`Unknown onboarding track: ${b}`);return A})}function dj($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function uj($){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 oj($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let A of V0()){if(A.starterExample.key===b)return A.starterExample;if(A.advancedExample?.key===b)return A.advancedExample}return}function um($,b){return $Z($,b.flatMap((A)=>A.track.connectSurfaces))}function s7($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((A)=>({defaultSurface:A.id,path:`/onboard/${A.id}`,routeId:`onboard-${A.id}`})),surfaces:Object.fromEntries($.map((A)=>[A.id,{commands:A.recommendedCommands.map((n,m)=>({commandId:`${A.id}-${m}`,intent:`Run ${n}`,title:n})),data:[{hydrateInto:"track",recipeId:`track-${A.id}`,source:{entityType:`onboarding.${A.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${A.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:A.id,title:A.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function $Z($,b){return[...new Set([...$,...b])].sort()}async function bZ($,b={}){let A=await $b($.fs,b),n=hj(b.selectedTracks),m=dj(A.config),W=[...await Promise.all(n.map(async(Y)=>{let H=await Vb($,{config:A.config,cwd:A.cwd,family:Y.reuseFamily,packageRoot:A.packageRoot,platform:Y.adoptionPlatform,query:Y.adoptionQuery,workspaceRoot:A.workspaceRoot});return{reason:H.reason,resolution:H,score:H.selected?.score??0,selected:!1,track:Y}}))].sort((Y,H)=>H.score-Y.score).map((Y,H)=>({...Y,selected:H===0})),w=W[0]?.track;if(!w)throw Error("No onboarding tracks are available.");let{journeyContext:j,journeyPlan:B}=await cj(w,n,A.workspaceRoot,A.packageRoot),S=oj(w,b.forcedExampleKey)??w.starterExample,Q=nZ(["contractspec onboard",...w.recommendedCommands,"contractspec doctor"]),Z=uj(m),X={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:m,builderNextSteps:Z,config:A.config,cwd:A.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:j,journeyPlan:B,nextCommands:Q,packageRoot:A.packageRoot,primaryTrack:w,recommendations:W,selectedExample:S,workspaceRoot:A.workspaceRoot};return{...X,guides:dm(X)}}async function AZ($,b){if(!b.config.connect?.enabled)return;let A=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,n=[b.agentGuidePath,b.humanGuidePath],m=await hb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:n,taskId:A,workspaceRoot:b.workspaceRoot}),y=await lb($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((W)=>W.track.id).join(", ")}`,steps:b.recommendations.map((W)=>({commands:W.track.recommendedCommands,paths:n,summary:`Adopt ${W.track.title}`})),touchedPaths:n},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:n,taskId:A,workspaceRoot:b.workspaceRoot});return{contextPack:{...m,affectedSurfaces:um(m.affectedSurfaces,b.recommendations)},planPacket:{...y.planPacket,affectedSurfaces:um(y.planPacket.affectedSurfaces,b.recommendations)}}}function nZ($){return[...new Set($)]}var lj=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],mZ=[...lj,{name:"@contractspec/lib.schema",description:"Extended schema utilities and common types"},{name:"@contractspec/app.cli-contractspec",dev:!0,description:"ContractSpec CLI for validation, scaffolding, and code generation"},{name:"typescript",dev:!0,description:"TypeScript compiler for type checking"}];function om($){return $==="minimal"?lj:mZ}function im($){return $.filter((b)=>!b.dev)}function lm($){return $.filter((b)=>b.dev)}import{exec as yZ}from"child_process";import{promisify as WZ}from"util";var wZ=WZ(yZ),jZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function QI($,b,A=jZ){let n=om(b.mode),m=im(n),y=lm(n),W=[],w=[],j=[],B=$.join(b.workspaceRoot,"package.json");if(!await $.exists(B))return{success:!1,installed:[],skipped:[],errors:[{name:"package.json",action:"error",message:"No package.json found. Run `npm init` first."}],summary:"No package.json found in workspace root."};let Q=await $.readFile(B),Z=JSON.parse(Q),X=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),Y=e$(b.workspaceRoot),H=m.filter((U)=>{if(X.has(U.name)&&!b.force)return w.push({name:U.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),J=y.filter((U)=>{if(X.has(U.name)&&!b.force)return w.push({name:U.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let U=[...H,...J];return{success:!0,installed:U.map((K)=>({name:K.name,action:"installed",message:`Would install: ${K.description}`,dev:K.dev})),skipped:w,errors:[],summary:`Dry run: would install ${U.length} package(s), skip ${w.length}.`}}if(!b.skipPrompts&&(H.length>0||J.length>0)){let U=H.length+J.length;if(!await A.confirm(`Install ${U} package(s) using ${Y}?`))return{success:!0,installed:[],skipped:[...w,...H.map((q)=>({name:q.name,action:"skipped",message:"User cancelled"})),...J.map((q)=>({name:q.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(H.length>0){let U=await tj(H,Y,b.workspaceRoot,!1);for(let K of U)if(K.action==="installed")W.push(K);else j.push(K)}if(J.length>0){let U=await tj(J,Y,b.workspaceRoot,!0);for(let K of U)if(K.action==="installed")W.push(K);else j.push(K)}let O=j.length===0,V=O?`Successfully installed ${W.length} package(s), skipped ${w.length}.`:`Installed ${W.length}, skipped ${w.length}, failed ${j.length}.`;return{success:O,installed:W,skipped:w,errors:j,summary:V}}async function tj($,b,A,n){let m=[],y=$.map((W)=>W.version?`${W.name}@${W.version}`:W.name);try{let w=`${dy(b,n)} ${y.join(" ")}`;await wZ(w,{cwd:A,timeout:120000});for(let j of $)m.push({name:j.name,action:"installed",message:j.description,dev:n})}catch(W){let w=W instanceof Error?W.message:String(W);for(let j of $)m.push({name:j.name,action:"error",message:`Failed to install: ${w}`,dev:n})}return m}async function ZI($,b){let A=$.join(b,"package.json");try{let n=await $.readFile(A),m=JSON.parse(n);return"@contractspec/lib.contracts-spec"in{...m.dependencies,...m.devDependencies}}catch{return!1}}function XI($){let b=om($),A=[];A.push(`ContractSpec ${$} installation:`),A.push("");let n=im(b);if(n.length>0){A.push("Dependencies:");for(let y of n)A.push(` \u2022 ${y.name} - ${y.description}`)}let m=lm(b);if(m.length>0){A.push(""),A.push("Dev Dependencies:");for(let y of m)A.push(` \u2022 ${y.name} - ${y.description}`)}return A.join(`
|
|
2452
|
+
`)}import{RegeneratorService as BZ}from"@contractspec/lib.contracts-spec/regenerator";function UI($){return new BZ({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class K0{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,A;try{A=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(n){throw Error(`Registry request failed: ${b} (${n instanceof Error?n.message:String(n)})`)}if(!A.ok){let n=await A.text().catch(()=>"");throw Error(`Registry request failed: ${A.status} ${A.statusText} ${n}`)}return await A.json()}}function tm($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function KI($,b,A){let{logger:n}=A,m=tm(b.registryUrl);n.info(`Adding spec to registry: ${$}`,{registryUrl:m}),await new K0({registryUrl:m}).getJson(`/specs/add?path=${encodeURIComponent($)}`),n.info("Spec added to registry successfully")}async function _I($,b){let{logger:A}=b,n=tm($.registryUrl);A.info("Listing specs from registry",{registryUrl:n});let m=new K0({registryUrl:n}),y=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",W=await m.getJson(`/specs${y}`);return A.info(`Found ${W.length} specs`),W}async function zI($,b,A){let{logger:n}=A,m=tm(b.registryUrl);n.info(`Searching registry: ${$}`,{registryUrl:m});let W=await new K0({registryUrl:m}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return n.info(`Found ${W.length} results`),W}class SZ{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:A}=$,n=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${n.join(", ")}...`);try{let m=this.fs.join(A,b.rulesDir??".rules");if(!await this.fs.exists(m))return{success:!1,files:[],errors:[`Rules directory not found: ${m}`]};let W=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${W}`);let w=[];for(let j of n){let B=this.getTargetFileName(j);if(B){let S=this.fs.join(A,B);w.push(S)}}return{success:!0,files:w,logs:[`Successfully synchronized rules to ${w.length} targets.`]}}catch(m){let y=m instanceof Error?m.message:String(m);return this.logger.error(`Rule synchronization failed: ${y}`),{success:!1,files:[],errors:[y]}}}async generateConfig($){let{config:b}=$,A={rules:(b.rules??[]).map((n)=>this.fs.join(b.rulesDir??".rules",n)),targets:$.targets||b.targets};return JSON.stringify(A,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}function _0($,b,A,n){let m=AA(b,A),y=QZ(A);if(y.test($))return $.replace(y,m);if(n&&pm($)===pm(n))return m;return`${m}${$}`}function AA($,b){let A=pm($);return`${b.startMarker}
|
|
2421
2453
|
${b.note}
|
|
2422
|
-
${
|
|
2454
|
+
${A}
|
|
2423
2455
|
${b.endMarker}
|
|
2424
|
-
`}function
|
|
2425
|
-
`).trimEnd()}function 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=`
|
|
2456
|
+
`}function pm($){return $.replace(/\r\n/g,`
|
|
2457
|
+
`).trimEnd()}function QZ($){return new RegExp(`${pj($.startMarker)}[\\s\\S]*?${pj($.endMarker)}(?:\\r?\\n)?`)}function pj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ZZ="<!-- contractspec:init:agents:start -->",XZ="<!-- contractspec:init:agents:end -->",YZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:XZ,note:YZ,startMarker:ZZ};async function am($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,"AGENTS.md");try{let y=await $.exists(m),W=Sw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await A.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:m,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(m,_0(w,W,aj,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,AA(W,aj)),{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 HZ,generateBiomePreset as GZ}from"@contractspec/biome-config";async function em($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,"biome.jsonc"),y=$.join(n,".contractspec","biome"),W=$.join(y,"plugins"),w=$.join(y,"ai"),j=HZ("consumer");try{let B=await $.exists(m);if(B&&b.interactive){if(!await A.confirm(`${m} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:m,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(W),await $.mkdir(w),await $.writeFile(m,GZ("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(j.plugins))await $.writeFile($.join(W,S),Q);return await $.writeFile($.join(w,"consumer.md"),j.aiRules),{target:"biome-config",filePath:m,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:m,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function sm($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,".contractsrc.json");try{let y=await $.exists(m),W=jb(b);if(y){let w=await $.readFile(m),j=a(w);if(!j)return{target:"cli-config",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=A$(j,W);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof W==="object"&&W!==null){let S={};if("connect"in W)S.connect=W.connect;if("builder"in W)S.builder=W.builder;await $.writeFile(m,F(Dn(B,S)))}else await $.writeFile(m,F(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,F(W)),{target:"cli-config",filePath:m,action:"created",message:"Created CLI configuration"}}catch(y){return{target:"cli-config",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function $y($,b,A){let n=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(n,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(n))await $.mkdir(n);let W=await $.exists(m),w=Bw(b);if(W)if(b.interactive){if(!await A.confirm(`${m} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:m,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:m,action:"skipped",message:"File already exists"};return await $.writeFile(m,w),{target:"cursor-rules",filePath:m,action:W?"merged":"created",message:W?"Updated Cursor rules":"Created Cursor rules"}}catch(y){return{target:"cursor-rules",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function by($,b,A){let n=lA();try{let m=await $.exists(n),y=jw();if(b.interactive){if(!await A.confirm(`Configure Claude Desktop at ${n}?`))return{target:"mcp-claude",filePath:n,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(n),B=a(j);if(!B)return{target:"mcp-claude",filePath:n,action:"error",message:"Existing file is not valid JSON"};let S=A$(B,y);return await $.writeFile(n,F(S)),{target:"mcp-claude",filePath:n,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=n.substring(0,n.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(n,F(y)),{target:"mcp-claude",filePath:n,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:n,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function Ay($,b,A){let n=$.join(b.workspaceRoot,".cursor"),m=$.join(n,"mcp.json");try{if(!await $.exists(n))await $.mkdir(n);let W=await $.exists(m),w=Db();if(W){let j=await $.readFile(m),B=a(j);if(!B)return{target:"mcp-cursor",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=A$(B,w);return await $.writeFile(m,F(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,F(w)),{target:"mcp-cursor",filePath:m,action:"created",message:"Created Cursor MCP configuration"}}catch(y){return{target:"mcp-cursor",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}var qZ="<!-- contractspec:init:usage:start -->",OZ="<!-- contractspec:init:usage:end -->",JZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",ej={endMarker:OZ,note:JZ,startMarker:qZ};async function ny($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,"USAGE.md");try{let y=await $.exists(m),W=Qw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await A.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:m,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(m,_0(w,W,ej,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,AA(W,ej)),{target:"usage-md",filePath:m,action:"created",message:"Created usage guide"}}catch(y){return{target:"usage-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function my($,b,A){let n=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(n,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=iA(b);if(w){let B=await $.readFile(y),S=a(B);if(!S)return{target:"vscode-settings",filePath:y,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=A$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,F(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,F(j)),{target:"vscode-settings",filePath:y,action:"created",message:"Created VS Code settings"}}catch(W){return{target:"vscode-settings",filePath:y,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var UZ={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??""},VZ={"agents-md":am,"biome-config":em,"cli-config":sm,"cursor-rules":$y,"mcp-claude":by,"mcp-cursor":Ay,"usage-md":ny,"vscode-settings":my},KZ={findWorkspaceRoot:x,findPackageRoot:c,isMonorepo:Ub,getPackageName:P$};async function QC($,b,A=UZ,n={}){let m=[],y=b.targets.length>0?b.targets:Mb,W={...KZ,...n.workspace},w={...VZ,...n.targets},j=n.setupGitignore??Q0,B=b.workspaceRoot,S=W.findWorkspaceRoot(B),Q=b.packageRoot??W.findPackageRoot(B),Z=b.isMonorepo??W.isMonorepo(S),X=b.packageName??(Z?W.getPackageName(Q):void 0),Y=await sj($,[Q,S]),H=b.preset??Tb(Y);if(b.interactive&&!b.preset)H=await A.select("Select initialization preset:",bw.map((g)=>({value:g,label:Aw[g],description:nw[g],selected:g===H})));let J=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)J=await A.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${X??Q})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${S})`,description:"Create config files at the workspace root"}]);let V=Z&&J==="package"?Q:S,U=await sj($,[V]),K={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:J,packageName:X,preset:H,builderApiBaseUrl:b.builderApiBaseUrl??U?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??U?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??U?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??U?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??U?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??U?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??U?.connect?.studio?.queue},q=mw(H,y);if(b.interactive)q=await A.multiSelect("Select components to configure:",Mb.map((g)=>({value:g,label:$w[g],selected:q.includes(g)})));let G=K.projectName;if(b.interactive&&!G){let g=J==="package"&&X?X:V.split("/").pop()??"my-project";G=await A.input("Project name:",g)}let z=K.builderApiBaseUrl;if(b.interactive&&H.startsWith("builder-"))z=await A.input("Builder API base URL:",z??"https://api.contractspec.io");let{builderLocalRuntimeId:_,builderLocalGrantedTo:L}=K;if(b.interactive&&(H==="builder-local"||H==="builder-hybrid"))_=await A.input("Default local runtime target id:",_??"rt_local_daemon"),L=await A.input("Default local runtime grant target:",L??"local:operator");let I={...K,projectName:G,targets:q,builderApiBaseUrl:z,builderLocalRuntimeId:_,builderLocalGrantedTo:L};for(let g of q){let o0=await _Z($,g,I,A,w);m.push(o0)}let E=await j($,{behavior:I.gitignoreBehavior,interactive:I.interactive,patterns:ww({preset:H}),prompts:A,root:S});if(I.gitignoreBehavior!=="skip"||E.action!=="skipped")m.push(E);let N=m.filter((g)=>g.action!=="error").length,M=m.filter((g)=>g.action==="error").length,r=Z?` (${J} level)`:"";return{success:M===0,preset:H,files:m,summary:`Setup complete${r}: ${N} configured, ${M} failed.`,nextSteps:Ww(I)}}async function _Z($,b,A,n,m){let y=m[b];if(y)return y($,A,n);return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}async function sj($,b){for(let A of b){let n=$.join(A,".contractsrc.json");if(!await $.exists(n))continue;let m=a(await $.readFile(n));if(m)return m}return null}import{validateBlueprint as zZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as LZ}from"path";async function RC($,b){let{fs:A}=b,n=LZ(process.cwd(),$);if(!await A.exists(n))return{valid:!1,errors:[`Blueprint file not found: ${n}`]};try{let m=await W$(n),y=RZ(m.exports),W=zZ(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 RZ($){let b=Object.values($).filter(IZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function IZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as CZ,dirname as yy,join as nA}from"path";async function MC($,b,A,n,m){let{fs:y}=m,W=n.implementationPath;if(!W){let S=yy($),Q=CZ($,".ts"),Z=[nA(S,Q.replace(".contracts",".handler")+".ts"),nA(S,Q.replace(".presentation","")+".tsx"),nA(S,Q.replace(".form",".form")+".tsx"),nA(yy(S),"handlers",Q.replace(".contracts",".handler")+".ts"),nA(yy(S),"components",Q.replace(".presentation","")+".tsx")];for(let X of Z)if(await y.exists(X)){W=X;break}}if(!W||!await y.exists(W))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let w=await y.readFile(W),B=await new UA(A).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as xZ,validateBuilderReadinessReport as MZ,validateBuilderWorkspace as EZ,validateBuilderWorkspaceSnapshot as TZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as DZ,validateExternalPatchProposal as NZ,validateProviderRoutingPolicy as FZ,validateRuntimeTarget as vZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as gZ,validateLayoutSlots as PZ}from"@contractspec/lib.surface-runtime/spec";async function vC($,b){if(!hZ($.specType))return{valid:!0,errors:[],warnings:[]};let A=sZ($.filePath),n=[`${A}/package.json`,`${A}/README.md`,`${A}/src/index.ts`,$.filePath],m=[];for(let w of n)if(!await b.exists(w))m.push(`Missing package scaffold file: ${w}`);if(m.length>0)return{valid:!1,errors:m,warnings:[]};let y;try{y=(await W$($.filePath)).exports}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)],warnings:[]}}let W=$.specType==="module-bundle"?kZ(y):$.specType==="builder-spec"?rZ(y):fZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function kZ($){let b=[],A=[],n=cZ($,dZ);if(n.length===0)return A.push(Wy("module-bundle","bundle")),{errors:b,warnings:A};for(let m of n){let y=Object.values(m.value.surfaces);for(let W of y){try{PZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of gZ(W).warnings)A.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:A}}function rZ($){let b=[],A=[],n=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(uZ(y)){n+=1,b.push(...z0(m,EZ(y)));continue}if(oZ(y)){n+=1,b.push(...z0(m,xZ(y)));continue}if(iZ(y)){n+=1,b.push(...z0(m,MZ(y)));continue}if(lZ(y))n+=1,b.push(...z0(m,TZ(y)))}if(n===0)A.push(Wy("builder-spec","builder"));return{errors:b,warnings:A}}function fZ($){let b=[],A=[],n=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(tZ(y)){n+=1,b.push(...L0(m,vZ(y)));continue}if(pZ(y)){n+=1,b.push(...L0(m,FZ(y)));continue}if(aZ(y)){n+=1,b.push(...L0(m,DZ(y)));continue}if(eZ(y))n+=1,b.push(...L0(m,NZ(y)))}if(n===0)A.push(Wy("provider-spec","provider"));return{errors:b,warnings:A}}function cZ($,b){return Object.entries($).filter(([A,n])=>A!=="__esModule"&&b(n)).map(([A,n])=>({exportName:A,value:n}))}function z0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function L0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function hZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function dZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function uZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function oZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function iZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function lZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function tZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function pZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function aZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function eZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function sZ($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Wy($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as $2}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as b2}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as A2}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as n2}from"@contractspec/module.workspace";async function b1($,b={}){let A=[],n=[],m;if(!b.skipStructure){m=n2($),A.push(...m.errors),n.push(...m.warnings);let y=await m2($);A.push(...y.errors),n.push(...y.warnings)}return{valid:A.length===0,structureResult:m,errors:A,warnings:n,code:$.sourceBlock}}async function dC($,b={}){return Promise.all($.map(async(A)=>({spec:A,...await b1(A,b)})))}async function p$($,b,A={}){let{fs:n}=b;if(!await n.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let y=await n.readFile($),W=[],w=[],j=void 0;if(!A.skipStructure){let B=await B$(b,{pattern:$});for(let S of B){let Q=await b1(S,A);j=Q.structureResult,W.push(...Q.errors),w.push(...Q.warnings)}}return{valid:W.length===0,structureResult:j,errors:W,warnings:w,code:y}}async function uC($,b,A={}){let n=new Map;for(let m of $){let y=await p$(m,b,A);n.set(m,y)}return n}async function m2($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await W$($.filePath);if($.specType==="app-config"){let m=y2(b.exports,$),y=$2(m);return{errors:y.errors.map((W)=>$1(W)),warnings:[...y.warnings,...y.info].map((W)=>$1(W))}}if($.specType==="feature"){let m=W2(b.exports,$),y=b2(m);return{errors:y.issues.filter((W)=>W.level==="error").map((W)=>R0(W)),warnings:y.issues.filter((W)=>W.level!=="error").map((W)=>R0(W))}}let A=w2(b.exports,$),n=A2(A);return{errors:n.issues.filter((m)=>m.level==="error").map((m)=>R0(m)),warnings:n.issues.filter((m)=>m.level!=="error").map((m)=>R0(m))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function y2($,b){return wy($,b.exportName,j2)}function W2($,b){return wy($,b.exportName,B2)}function w2($,b){return wy($,b.exportName,S2)}function wy($,b,A){if(b&&A($[b]))return $[b];let n=Object.values($).find(A);if(!n)throw Error("Expected authored module to export a compatible spec value.");return n}function j2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function B2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function S2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function $1($){let b=$.code?`[${$.code}] `:"",A=$.path?`${$.path}: `:"";return`${b}${A}${$.message}`}function R0($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as Q2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as By}from"fs/promises";import{resolve as I0}from"path";async function aC($,b,A,n){let{fs:m}=n,y=I0(process.cwd(),b);if(!await m.exists(y))return{valid:!1,errors:[`Tenant config file not found: ${y}`]};try{let W=await Z2(y),w=await X2(A.connections,m),j=await Y2(A.translationCatalog,m),B=await H2(A.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=Q2($,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 Z2($){if($.endsWith(".json")){let n=await By($,"utf-8"),m=JSON.parse(n);if(!A1(m))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return m}let b=await W$($),A=Object.values(b.exports).filter(A1);if(A.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return A[0]}function A1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function W1($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((A)=>A.trim()).filter(Boolean)}async function X2($,b){let A=W1($);if(!A.length)return[];let n=[];for(let m of A){let y=I0(process.cwd(),m);if(!await b.exists(y)){console.warn(`Warning: Connection file not found: ${y}`);continue}if(y.endsWith(".json")){let w=await By(y,"utf-8"),j=JSON.parse(w);n.push(...jy(j));continue}let W=await W$(y);n.push(...jy(W.exports))}return n}function jy($){if(Array.isArray($)){let b=$.filter(n1);if(b.length)return b}if(n1($))return[$];if($&&typeof $==="object"){let A=Object.values($).flatMap((n)=>jy(n));if(A.length)return A}return[]}function n1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function Y2($,b){if(!$)return;let A=I0(process.cwd(),$);if(!await b.exists(A))return;if(A.endsWith(".json")){let y=await By(A,"utf-8"),W=JSON.parse(y);if(m1(W))return y1(W);return}let n=await W$(A),m=Object.values(n.exports).filter(m1);if(m.length===0)return;return y1(m[0])}function m1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function y1($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function H2($){let b=W1($);if(!b.length)return;let{IntegrationSpecRegistry:A}=await import("@contractspec/lib.contracts-integrations"),n=new A;for(let m of b){let{modulePath:y,exportName:W}=G2(m);if(!y)continue;let w=I0(process.cwd(),y);try{let j=await W$(w),B=q2(j.exports,W);if(B)await B(n)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return n}function G2($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),n=b?.trim()??null,m=A?.trim();return{modulePath:n,exportName:m}}function q2($,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 jx($,b,A={},n){let{fs:m,logger:y}=$,W=await m.glob({pattern:A.pattern}),w=A.outputDirs?.length?A.outputDirs:[void 0],j=[],B=n?.validate??((Q)=>p$(Q,{fs:m,logger:y})),S=n?.build??((Q,Z)=>wb(Q,{fs:m,logger:y},Z?{...b,outputDir:Z}:b,{...A.buildOptions??{},outputDir:Z}));for(let Q of W)for(let Z of w){let X={specPath:Q,outputDir:Z};if(A.validate)try{X.validation=await B(Q)}catch(Y){X.error={phase:"validate",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}if(!A.dryRun)try{X.build=await S(Q,Z)}catch(Y){X.error={phase:"build",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}else y.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});j.push(X)}return{specs:W,runs:j}}import{generateText as O2}from"ai";var J2=`
|
|
2426
2458
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2427
2459
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2428
2460
|
|
|
@@ -2440,7 +2472,7 @@ Generate scenarios covering:
|
|
|
2440
2472
|
- Happy path (valid input, successful execution)
|
|
2441
2473
|
- Edge cases (boundary values, optional fields)
|
|
2442
2474
|
- Error cases (invalid input, business rule violations)
|
|
2443
|
-
`.trim();class
|
|
2475
|
+
`.trim();class U2{logger;defaultModel;generateTextImpl;constructor($,b,A=O2){this.logger=$;this.defaultModel=b;this.generateTextImpl=A}async generateTests($,b={}){let A=b.model??this.defaultModel;if(!A)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let n=`
|
|
2444
2476
|
Generate a TestSpec for the following Operation:
|
|
2445
2477
|
|
|
2446
2478
|
\`\`\`json
|
|
@@ -2449,23 +2481,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2449
2481
|
|
|
2450
2482
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2451
2483
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2452
|
-
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:
|
|
2453
|
-
`)}function
|
|
2454
|
-
`)}function
|
|
2455
|
-
`);for(let
|
|
2456
|
-
`)}function
|
|
2484
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:A,system:J2,prompt:n});this.logUsage(y);let W=this.parseResponse(m);return this.enrichSpec(W,$)}catch(m){throw this.logger.error("Failed to generate tests",{error:m}),m}}parseResponse($){try{let b=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(b)}catch(b){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,b){let A={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},n={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:A,target:n,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let b=$;this.logger.debug(`AI Usage: ${b.promptTokens} prompt + ${b.completionTokens} completion = ${b.totalTokens} total tokens`)}}import{OperationSpecRegistry as w1}from"@contractspec/lib.contracts-spec";import{TestRunner as j1}from"@contractspec/lib.contracts-spec/tests";import{resolve as Sy}from"path";async function Gx($,b){let A=new j1({registry:b}),n=[],m=0,y=0;for(let W of $){let w=await A.run(W);n.push(w),m+=w.passed,y+=w.failed}return{results:n,passed:m,failed:y}}async function qx($,b,A){let{logger:n}=A,m;if(b.registry)m=await K2(Sy(b.registry));else m=new w1,n.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let y=new j1({registry:m}),W=[],w=!0;for(let j of $)try{let B=Sy(j),S=await U0(B),Q=B1(S);if(Q.length===0){n.warn(`No TestSpec exports found in ${j}`);continue}for(let Z of Q){n.info(`Running ${Z.meta.key}...`);let X=await y.run(Z);if(W.push(X),X.failed>0)w=!1,n.error(`${Z.meta.key} failed (${X.failed}/${X.scenarios.length})`);else n.info(`${Z.meta.key} passed (${X.passed}/${X.scenarios.length})`)}}catch(B){n.error(`Failed to load/run spec ${j}: ${B instanceof Error?B.message:String(B)}`),w=!1}return{results:W,passed:w}}async function Ox($,b){let A=[];for(let n of $)try{let m=Sy(n),y=await U0(m),W=B1(y);A.push(...W)}catch(m){b.logger.warn(`Failed to load tests from ${n}: ${m instanceof Error?m.message:String(m)}`)}return A}function B1($){let b=[];for(let A of Object.values($))if(V2(A))b.push(A);return b}function V2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function K2($){return kj($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof w1,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as mA}from"@contractspec/module.workspace";import{IndentationText as _2,Node as Hb,Project as z2,QuoteKind as L2,SyntaxKind as R2}from"ts-morph";function I2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Rx($,b,A={}){let{fs:n,logger:m}=b;if(!await n.exists($))return{specPath:$,specInfo:I2($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let W=await n.readFile($),w;if(A.content!==void 0)w=A.content;else if(A.fields?.length)w=C2(W,A.fields);else return{specPath:$,specInfo:mA(W,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!A.skipValidation){await n.writeFile($,w);let j=await p$($,b);if(j.errors.length>0)return await n.writeFile($,W),{specPath:$,specInfo:mA(w,$),updated:!1,errors:j.errors,warnings:j.warnings};if(j.warnings.length>0&&!A.allowWarnings)return await n.writeFile($,W),{specPath:$,specInfo:mA(w,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:j.warnings};return m.info(`Updated spec: ${$}`),{specPath:$,specInfo:mA(w,$),updated:!0,errors:[],warnings:j.warnings}}return await n.writeFile($,w),m.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:mA(w,$),updated:!0,errors:[],warnings:[]}}function C2($,b){let n=new z2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:_2.TwoSpaces,quoteKind:L2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=M2(n);if(!m)return $;for(let y of b)x2(m,y);return n.getFullText()}function x2($,b){let A=b.key.split(".").map((w)=>w.trim()).filter(Boolean);if(A.length===0)return;let n=$;for(let w of A.slice(0,-1)){if(!n.getProperty(w))n.addPropertyAssignment({name:w,initializer:"{}"});let B=n.getPropertyOrThrow(w);if(!Hb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!Hb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(R2.ObjectLiteralExpression);if(!Q)return;n=Q}let m=A[A.length-1];if(!m)return;let y=E2(b.value),W=n.getProperty(m);if(W&&Hb.isPropertyAssignment(W)){W.setInitializer(y);return}n.addPropertyAssignment({name:m,initializer:y})}function M2($){for(let b of $.getVariableDeclarations()){let A=b.getInitializer();if(!A)continue;if(Hb.isObjectLiteralExpression(A))return A;if(Hb.isCallExpression(A)){let n=A.getArguments()[0];if(n&&Hb.isObjectLiteralExpression(n))return n}}return}function E2($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var L1={};f(L1,{getPackageUpgradeCommand:()=>J1,getDefaultVersioningConfig:()=>x0,getDefaultHooksConfig:()=>M0,applyGuidedUpgrade:()=>z1,applyConfigUpgrades:()=>O1,analyzeUpgrades:()=>C0,analyzeGuidedUpgrade:()=>Yy});import{GeneratedReleaseManifestSchema as K1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as r2,DEFAULT_CONTRACTSRC as f2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function S1($){return $.packages.map((b)=>{let A=b.version?`@${b.version}`:"";return`- ${b.name}${A} (${b.releaseType})`})}function Q1($){return $.map((b)=>` - ${b}`)}function Qy($,b){return $.audiences.filter((A)=>b.includes(A.kind)).map((A)=>`- ${T2(A.kind)}: ${A.summary}`)}function Z1($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...S1($),...Qy($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));return b.join(`
|
|
2485
|
+
`)}function X1($){let b=[`### ${$.summary}`,...S1($),...Qy($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`);return b.join(`
|
|
2486
|
+
`)}function Y1($){let b=[`### ${$.summary}`,...Qy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2487
|
+
`);for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`),b.push(...Q1(A.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let A of $.upgradeSteps)b.push(` - [${A.level}] ${A.title}: ${A.summary}`),b.push(...A.instructions.map((n)=>` - ${n}`))}return b.join(`
|
|
2488
|
+
`)}function Zy($){return["# Patch Notes","",...$.releases.map(Z1)].join(`
|
|
2457
2489
|
|
|
2458
|
-
`)}function
|
|
2490
|
+
`)}function Xy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[X1(b),"",Y1(b)])].join(`
|
|
2459
2491
|
|
|
2460
|
-
`)}function
|
|
2492
|
+
`)}function H1($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...Q1(b.instructions)].join(`
|
|
2461
2493
|
`)).join(`
|
|
2462
|
-
`)}function
|
|
2463
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2464
|
-
`)}function
|
|
2465
|
-
`),
|
|
2466
|
-
`),!0}async function
|
|
2467
|
-
`),!0}async function
|
|
2468
|
-
`),m="info";for(let j of
|
|
2494
|
+
`)}function Gb($,b){let A=b.targetPackages.map((n)=>`${n.name}: ${n.currentVersion??"unknown"} -> ${n.targetVersion??"latest"}`).join(`
|
|
2495
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",A||"- No package version targets were inferred.","","Required steps:",H1(b)].join(`
|
|
2496
|
+
`)}function T2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as q1,countUpgradePlanStepLevels as D2,createAgentPromptBundles as N2,dedupeUpgradePlanSteps as F2,sortReleaseManifest as G1}from"@contractspec/lib.contracts-spec";function v2($,b){if(b.length===0)return G1($);let A=new Map(b.map((n)=>[n.name,n.currentVersion??"0.0.0"]));return G1({...$,releases:$.releases.filter((n)=>n.packages.some((m)=>{let y=A.get(m.name);if(!y||!m.version)return!1;return q1(m.version,y)===1}))})}function yA($,b,A,n){let m=v2($,b),y=g2(m,b),W=F2(m.flatMap((S)=>S.upgradeSteps)),w=D2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=N2(j,A,n);return{...j,agentPrompts:B}}function g2($,b){let A=new Map(b.map((m)=>[m.name,m.currentVersion])),n=new Map;for(let m of $)for(let y of m.packages){let W=A.get(y.name),w=n.get(y.name);if(!w){n.set(y.name,{name:y.name,currentVersion:W,targetVersion:y.version});continue}if(y.version&&w.targetVersion&&q1(y.version,w.targetVersion)===1)w.targetVersion=y.version}return Array.from(n.values()).sort((m,y)=>m.name.localeCompare(y.name))}async function C0($,b){let{fs:A,logger:n}=$,m=c(b.workspaceRoot),y=x(b.workspaceRoot),W=e$(y);n.info("Analyzing available upgrades...",{workspaceRoot:y,packageRoot:m,packageManager:W});let w=await P2(A,m),j=await k2(A,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function P2($,b){let A=$.join(b,"package.json");if(!await $.exists(A))return[];try{let n=await $.readFile(A),m=JSON.parse(n),y=m.dependencies??{},W=m.devDependencies??{},w=[],j={...y,...W};for(let[B,S]of Object.entries(j))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))w.push({name:B,currentVersion:S,isDevDependency:!!W[B]});return w}catch{return[]}}async function k2($,b,A){let n=$.join(b,".contractsrc.json"),m=xb({configRoot:b,workspaceRoot:A});if(!await $.exists(n))return[];try{let y=await $.readFile(n),W=JSON.parse(y),w=[],j=W.$schema;if(!j||j!==m)w.push({key:"$schema",currentValue:j,suggestedValue:m,isNew:!j});if(!W.versioning)w.push({key:"versioning",currentValue:void 0,suggestedValue:x0(),isNew:!0});else if(W.versioning.integrateWithChangesets===void 0)w.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!W.hooks)w.push({key:"hooks",currentValue:void 0,suggestedValue:M0(),isNew:!0});if(!W.release)w.push({key:"release",currentValue:void 0,suggestedValue:U1(),isNew:!0});if(!W.upgrade)w.push({key:"upgrade",currentValue:void 0,suggestedValue:V1(),isNew:!0});return w}catch{return[]}}async function O1($,b){let{fs:A,logger:n}=$,m=c(b.workspaceRoot),y=x(b.workspaceRoot),W=xb({configRoot:m,workspaceRoot:y});if(b.dryRun)n.info("Dry run - no changes will be made");let w=A.join(m,".contractsrc.json");if(!await A.exists(w))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let j=await A.readFile(w),B=JSON.parse(j),S=0,Q=B.$schema;if(!Q||Q!==W)B.$schema=W,S++;if(!B.versioning)B.versioning=x0(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=M0(),S++;if(!B.release)B.release=U1(),S++;if(!B.upgrade)B.upgrade=V1(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await A.writeFile(w,JSON.stringify(B,null,2)+`
|
|
2497
|
+
`),n.info("Configuration upgraded",{sectionsUpgraded:S});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:S,summary:b.dryRun?`Would upgrade ${S} config section(s)`:`Upgraded ${S} config section(s)`}}catch(j){let B=j instanceof Error?j.message:String(j);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function J1($,b,A){let n=A?b.map((m)=>`${m.name}@latest`).join(" "):b.map((m)=>m.name).join(" ");switch($){case"bun":return`bun add ${n}`;case"pnpm":return`pnpm add ${n}`;case"yarn":return`yarn add ${n}`;default:return`npm install ${n}`}}function x0(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function M0(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function U1(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function V1(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var c2="**/*.{ts,tsx,js,jsx,mjs,cjs}",_1=f2.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Yy($,b){let{fs:A}=$,n=c(b.workspaceRoot),m=x(b.workspaceRoot),y=await d2(A,n,m),W=await h2(A,n,m,b.manifestPaths??y.manifestPaths),w=await C0($,{workspaceRoot:n,dryRun:b.dryRun}),j=[b.agentTarget??y.defaultAgentTarget??"codex"],B=yA(W.manifest,w.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),j,Gb),S=u2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:o2(S)}}async function z1($,b){let{fs:A,logger:n}=$,m=c(b.workspaceRoot),y=await Yy($,b),W=[];if(!b.dryRun){for(let j of y.plan.steps){if(j.level!=="auto")continue;for(let B of j.autofixes??[])if(await i2(A,m,B))W.push(B.id)}n.info("Applied guided upgrade autofixes",{count:W.length,workspaceRoot:m})}let w=y.plan.steps.filter((j)=>j.level!=="auto");return{success:!0,packagesUpgraded:W.filter((j)=>j.startsWith("pkg:")).length,configSectionsUpgraded:W.filter((j)=>j.startsWith("config:")).length,summary:b.dryRun?`Would apply ${y.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${W.length} deterministic upgrade autofix(es)`,appliedAutofixes:W,remainingSteps:w,humanChecklist:y.humanChecklist,promptBundle:y.plan.agentPrompts[0],plan:y.plan,manifestPath:y.manifestPath}}async function h2($,b,A,n){let m=n??["generated/releases/upgrade-manifest.json"],y=Array.from(new Set([b,A]));for(let W of m){let w=W.startsWith("/")?[W]:y.map((j)=>$.join(j,W));for(let j of w){if(!await $.exists(j))continue;let B=K1.parse(JSON.parse(await $.readFile(j)));return{path:j,manifest:B}}}return{manifest:K1.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function d2($,b,A){for(let n of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(A,".contractsrc.json")]))){if(!await $.exists(n))continue;try{let m=JSON.parse(await $.readFile(n)),y=r2.safeParse(m);if(y.success)return{..._1,...y.data.upgrade}}catch{continue}}return _1}function u2($,b,A){let n=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;n.push({id:`pkg:${S.name}`,kind:"package-json",title:`Update ${S.name}`,summary:`Update ${S.name} to ${Q.targetVersion}`,packageName:S.name,dependencyType:S.isDevDependency?"devDependencies":"dependencies",from:S.currentVersion,to:Q.targetVersion})}let m=A.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),y=[];if(n.length>0)y.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:n.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:n.map((S)=>S.packageName??""),autofixes:n});if(m.length>0)y.push({id:"upgrade-contractsrc-config",title:"Refresh .contractsrc.json defaults",summary:"Bring workspace release and upgrade config in line with current defaults.",level:"auto",instructions:m.map((S)=>`${S.configPath} -> updated`),autofixes:m});let W=[...y,...$.steps],w=W.filter((S)=>S.level==="auto").length,j=W.filter((S)=>S.level==="assisted").length,B=W.filter((S)=>S.level==="manual").length;return{...$,steps:W,autofixCount:w,assistedCount:j,manualCount:B,agentPrompts:yA({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),Gb).agentPrompts}}function o2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function i2($,b,A){switch(A.kind){case"package-json":return l2($,b,A);case"contractsrc":return t2($,b,A);case"import-rewrite":return p2($,b,A);case"codemod":return!1}}async function l2($,b,A){let n=$.join(b,"package.json");if(!await $.exists(n))return!1;let m=JSON.parse(await $.readFile(n)),y=A.dependencyType??"dependencies",W=m[y]??{};if(!A.packageName||!A.to||!W[A.packageName])return!1;return W[A.packageName]=A.to,m[y]=W,await $.writeFile(n,JSON.stringify(m,null,2)+`
|
|
2498
|
+
`),!0}async function t2($,b,A){let n=$.join(b,".contractsrc.json"),m=await $.exists(n)?JSON.parse(await $.readFile(n)):{};if(!A.configPath)return!1;return a2(m,A.configPath,A.value),await $.writeFile(n,JSON.stringify(m,null,2)+`
|
|
2499
|
+
`),!0}async function p2($,b,A){if(!A.from||!A.to)return!1;let n=await $.glob({pattern:A.path??c2,cwd:b,absolute:!0}),m=!1;for(let y of n){let W=await $.readFile(y);if(!W.includes(A.from))continue;await $.writeFile(y,W.split(A.from).join(A.to)),m=!0}return m}function a2($,b,A){let n=b.split("."),m=$;for(let W of n.slice(0,-1)){let w=m[W];if(!w||typeof w!=="object"||Array.isArray(w))m[W]={};m=m[W]}let y=n.at(-1);if(y)m[y]=A}import{existsSync as Hy,mkdirSync as e2,readFileSync as s2,renameSync as $X,statSync as bX,writeFileSync as AX}from"fs";import{dirname as nX,join as mX}from"path";var yX=".contractspec/verification-cache.json",R1=1;class I1{filePath;cache;isDirty=!1;constructor($,b){let A=b??process.cwd();this.filePath=$??mX(A,yX),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Hy(this.filePath))return;let $=s2(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==R1)return;for(let[A,n]of Object.entries(b.entries))this.cache.set(A,n)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=nX(this.filePath);if(!Hy($))e2($,{recursive:!0});let b={version:R1,entries:Object.fromEntries(this.cache.entries())},A=`${this.filePath}.tmp`;AX(A,JSON.stringify(b,null,2),"utf-8"),$X(A,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(Hy(this.filePath))$=bX(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function ox($,b){return new I1($,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,A]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(A).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function lx(){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 A=this.getStorageKey($);if(await this.store.update(A,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),A=this.keyIndex.has($);if(A)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return A}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function px($){return new x1($)}import{createHash as WX}from"crypto";var M1={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function E1($){return WX("sha256").update($).digest("hex")}function T1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function wX($){try{let b=$.split("|"),A=new Map;for(let W of b){let[w,j]=W.split(":");if(w&&j)A.set(w,j)}let n=A.get("spec"),m=A.get("impl"),y=A.get("tier");if(!n||!m||!y)return null;return{specHash:n,implHash:m,tier:y,aiModelVersion:A.get("model")}}catch{return null}}function jX($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class D1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...M1,...b},this.stats={hits:0,misses:0}}createKey($,b,A,n){return{specHash:E1($),implHash:E1(b),tier:A,aiModelVersion:A==="ai_review"?n:void 0}}async lookup($){let b=T1($),A=await this.storage.get(b);if(!A)return this.stats.misses++,{hit:!1,reason:"not_found"};if(A.meta.expiresAt){let n=new Date(A.meta.expiresAt).getTime();if(Date.now()>n)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(A.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(A.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&A.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:A}}async store($,b,A={}){let n=T1($),m=jX($.tier,this.config),y={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+m).toISOString(),dependencies:A.dependencies??[],specName:A.specName,implPath:A.implPath}};await this.storage.set(n,y),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),A=0;for(let n of b){let m=await this.storage.get(n);if(!m)continue;if(m.meta.dependencies.includes($))await this.storage.delete(n),A++;if(m.meta.specName===$||m.meta.implPath===$)await this.storage.delete(n),A++}return A}async invalidateForSpec($){let b=await this.storage.keys(),A=0;for(let n of b){let m=wX(n);if(m&&m.specHash.startsWith($.substring(0,16)))await this.storage.delete(n),A++}return A}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let b=[];for(let n of $){let m=await this.storage.get(n);if(m)b.push({key:n,createdAt:new Date(m.meta.createdAt).getTime()})}b.sort((n,m)=>n.createdAt-m.createdAt);let A=b.length-this.config.maxEntries;for(let n=0;n<A;n++){let m=b[n];if(m)await this.storage.delete(m.key)}}}function yM($,b){return new D1($,b)}import{generateVerificationPrompt as BX}from"@contractspec/lib.contracts-spec/llm";function SX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let j=JSON.parse(b[1]);return{compliant:j.passed??!1,confidence:(j.score??0)/100,findings:(j.issues??[]).map((B)=>({category:String(B.category??"semantic"),severity:String(B.severity??"warning"),message:String(B.message??""),location:B.location?String(B.location):void 0,suggestion:B.suggestion?String(B.suggestion):void 0})),rawResponse:$}}catch{}let A=[],n=$.split(`
|
|
2500
|
+
`),m="info";for(let j of n){let B=j.toLowerCase();if(B.includes("error")||B.includes("critical"))m="error";else if(B.includes("warning")||B.includes("should"))m="warning";else if(B.includes("info")||B.includes("note"))m="info";let S=j.match(/^[-*\u2022]\s*(.+)$/),Q=j.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)A.push({category:"semantic",severity:m,message:Z})}}let y=A.some((j)=>j.severity==="error"),W=!y,w=y?0.3:A.length===0?0.9:0.7;return{compliant:W,confidence:w,findings:A,rawResponse:$}}async function N1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2469
2501
|
{
|
|
2470
2502
|
"passed": true,
|
|
2471
2503
|
"score": 50,
|
|
@@ -2482,16 +2514,16 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2482
2514
|
],
|
|
2483
2515
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2484
2516
|
}
|
|
2485
|
-
\`\`\``;try{let
|
|
2517
|
+
\`\`\``;try{let A=b.aiProvider??"anthropic";if(A==="anthropic"){let{anthropic:n}=await import("@ai-sdk/anthropic"),{generateText:m}=await import("ai");return(await m({model:n("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(A==="openai"){let{openai:n}=await import("@ai-sdk/openai"),{generateText:m}=await import("ai");return(await m({model:n("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${A}`)}catch(A){return`\`\`\`json
|
|
2486
2518
|
{
|
|
2487
2519
|
"passed": false,
|
|
2488
2520
|
"score": 0,
|
|
2489
2521
|
"issues": [
|
|
2490
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2522
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${A instanceof Error?A.message:"Unknown error"}" }
|
|
2491
2523
|
],
|
|
2492
2524
|
"summary": "AI verification encountered an error"
|
|
2493
2525
|
}
|
|
2494
|
-
\`\`\``}}async function
|
|
2526
|
+
\`\`\``}}async function WA($,b={}){let{spec:A,implementationCode:n,implementationPath:m}=$,y=Date.now(),W=BX(A,n),w=await N1(W.taskPrompt,b),j=SX(w),B=j.findings.map((X)=>({severity:X.severity,category:"semantic",message:X.message,location:X.location?{file:X.location}:m?{file:m}:void 0,suggestion:X.suggestion})),S=Math.round(j.confidence*100),Q=j.compliant,Z=j.findings.filter((X)=>X.suggestion).map((X)=>X.suggestion);return{tier:"ai_review",passed:Q,score:S,issues:B,suggestions:Z,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Q?1:0}},meta:{specName:A.meta.key,specVersion:A.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-y}}}function E0($){let{spec:b,implementationCode:A,implementationPath:n}=$,m=Date.now(),y=[];if(A.includes("console.log"))y.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(A.includes("// TODO")||A.includes("// FIXME"))y.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(b.policy.auth!=="anonymous"&&!A.includes("auth"))y.push({severity:"warning",category:"semantic",message:`Spec requires ${b.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let W=y.filter((j)=>j.severity==="error").length===0?80:40,w=y.filter((j)=>j.severity==="error").length===0;return{tier:"ai_review",passed:w,score:W,issues:y,suggestions:y.filter((j)=>j.suggestion).map((j)=>j.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:w?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}function QX($,b){return`You are analyzing a code implementation against its specification.
|
|
2495
2527
|
|
|
2496
2528
|
## Spec Schema Fields
|
|
2497
2529
|
${$}
|
|
@@ -2538,43 +2570,43 @@ Match types:
|
|
|
2538
2570
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2539
2571
|
- "mismatch": Different meaning despite similar naming
|
|
2540
2572
|
- "missing": Spec field not found in implementation
|
|
2541
|
-
`}function
|
|
2542
|
-
`)}function
|
|
2543
|
-
`),
|
|
2544
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let
|
|
2545
|
-
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function
|
|
2546
|
-
`)}function
|
|
2547
|
-
`)}function
|
|
2548
|
-
`),
|
|
2549
|
-
`).trim()||void 0,B=j?.match(
|
|
2550
|
-
${b.map((
|
|
2573
|
+
`}function ZX($){let b=[],A=(n,m)=>{try{let W=n?._def?.shape;if(W&&typeof W==="function"){let w=W();for(let[j,B]of Object.entries(w)){let Q=B?._def?.typeName??"unknown";b.push(`- ${j}: ${String(Q).replace("Zod","").toLowerCase()} (${m})`)}}}catch{b.push(`- [unable to extract ${m} fields]`)}};if($.io.input)A($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))A($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2574
|
+
`)}function XX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let A=JSON.parse(b[1]);return{fieldMappings:(A.fieldMappings??[]).map((n)=>({specField:String(n.specField??""),specType:String(n.specType??"unknown"),implementationField:n.implementationField?String(n.implementationField):void 0,implementationType:n.implementationType?String(n.implementationType):void 0,match:n.match??"missing",aiConfidence:typeof n.aiConfidence==="number"?n.aiConfidence:0.5,suggestion:n.suggestion?String(n.suggestion):void 0})),intentAlignment:{score:typeof A.intentAlignment?.score==="number"?A.intentAlignment.score:50,issues:Array.isArray(A.intentAlignment?.issues)?A.intentAlignment.issues:[],suggestions:Array.isArray(A.intentAlignment?.suggestions)?A.intentAlignment.suggestions:[]},semanticIssues:(A.semanticIssues??[]).map((n)=>({category:String(n.category??"semantic"),severity:n.severity??"warning",message:String(n.message??""),suggestion:n.suggestion?String(n.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function F1($,b={}){let{spec:A,implementationCode:n}=$,m=ZX(A),y=QX(m,n),W=await N1(y,b);return XX(W)}async function YX($,b={}){let{spec:A,implementationCode:n,implementationPath:m}=$,y=Date.now(),W=await WA($,b),w;if(b.aiApiKey)try{w=await F1($,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 HX}from"@contractspec/lib.contracts-spec/operations";function GX($,b){let A=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),n=$.toLowerCase(),m=A.filter((B)=>n.includes(B)),y=A.length>0?m.length/A.length:0,W=b.key.toLowerCase().replace(/\s+/g,""),w=n.includes(W)||n.includes(`test('${b.key.toLowerCase()}'`)||n.includes(`it('${b.key.toLowerCase()}'`)||n.includes(`describe('${b.key.toLowerCase()}'`),j=y>=0.3||w;return{name:b.key,type:"scenario",passed:j,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:j?void 0:`Scenario keywords not found in implementation (${Math.round(y*100)}% coverage)`}}function qX($,b){let A=JSON.stringify(b.input),n=JSON.stringify(b.output),m=v1(b.input),y=v1(b.output),W=$.toLowerCase(),w=m.filter((X)=>W.includes(X.toLowerCase())),j=y.filter((X)=>W.includes(X.toLowerCase())),B=m.length>0?w.length/m.length:1,S=y.length>0?j.length/y.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${A.slice(0,100)}...; Output: ${n.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function v1($){let b=[];function A(n){if(typeof n==="string"&&n.length>2)b.push(n);else if(Array.isArray(n))n.forEach(A);else if(n&&typeof n==="object")Object.values(n).forEach(A)}return A($),b}function OX($,b,A){let n=$.includes(b),m=A.http?$.includes(String(A.http)):!0,y=A.when??A.description,W=y.toLowerCase().split(/\s+/).filter((Q)=>Q.length>3),w=$.toLowerCase(),j=W.filter((Q)=>w.includes(Q)),B=W.length>0?j.length/W.length:1,S=n&&(m||B>=0.3);return{name:`Error: ${b}`,type:"error",passed:S,expected:`When: ${y}; Return: ${b} (HTTP ${A.http??400})`,details:S?void 0:!n?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function JX($,b){let A=b.sideEffects?.emits??[],n=[];for(let m of A){let y=HX(m)?m.ref.key:m.key,W=m.when,w=W.toLowerCase().split(/\s+/).filter((Z)=>Z.length>3),j=$.toLowerCase(),B=j.includes(y.toLowerCase()),S=w.filter((Z)=>j.includes(Z)),Q=w.length>0?S.length/w.length:1;n.push({name:`Event: ${y}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${y} when: ${W}`,details:!B?`Event '${y}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return n}function UX($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let A=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],n=$.toLowerCase(),m=A.some((y)=>n.includes(y));return{name:"Idempotency",type:"scenario",passed:m,expected:"Operation should be idempotent (safe to retry)",details:m?void 0:"No idempotency pattern found for idempotent operation"}}function T0($){let{spec:b,implementationCode:A,implementationPath:n}=$,m=Date.now(),y=[];for(let Y of b.acceptance?.scenarios??[])y.push(GX(A,Y));for(let Y of b.acceptance?.examples??[])y.push(qX(A,Y));for(let[Y,H]of Object.entries(b.io.errors??{}))y.push(OX(A,Y,H));y.push(...JX(A,b));let W=UX(A,b);if(W)y.push(W);let w=y.filter((Y)=>!Y.passed).map((Y)=>({severity:Y.type==="error"?"error":"warning",category:Y.type==="scenario"?"scenario":Y.type==="example"?"scenario":"error_handling",message:Y.details??`${Y.type} not covered: ${Y.name}`,location:n?{file:n}:void 0,suggestion:Y.expected?`Expected: ${Y.expected}`:void 0})),j=y.filter((Y)=>Y.type==="scenario"),B=y.filter((Y)=>Y.type==="error"),S=y.filter((Y)=>Y.passed).length,Q=y.length>0?Math.round(S/y.length*100):100,Z=w.filter((Y)=>Y.severity==="error").length===0,X=y.filter((Y)=>!Y.passed&&Y.expected).map((Y)=>`${Y.name}: ${Y.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:w,suggestions:X,coverage:{scenarios:{total:j.length,covered:j.filter((Y)=>Y.passed).length},errors:{total:B.length,handled:B.filter((Y)=>Y.passed).length},fields:{total:y.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}import{isEmitDeclRef as VX}from"@contractspec/lib.contracts-spec/operations";function KX($){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 _X($){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 zX($,b){if(_X(b))return{name:"contracts_import",passed:!0};let A=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function LX($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let n=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:n,details:n?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function RX($){let b=/:\s*any\b|as\s+any\b|<any>/,A=$.split(`
|
|
2575
|
+
`),n=[];for(let m=0;m<A.length;m++){let y=A[m]??"";if(y.trim().startsWith("//")||y.trim().startsWith("*"))continue;if(b.test(y))n.push(m+1)}return{name:"no_any_type",passed:n.length===0,details:n.length>0?`Found 'any' type on lines: ${n.slice(0,5).join(", ")}${n.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function IX($,b){let A=b.io.errors;if(!A||Object.keys(A).length===0)return{name:"error_handling",passed:!0};let n=Object.keys(A),m=[];for(let y of n)if(!$.includes(y))m.push(y);return{name:"error_handling",passed:m.length===0,details:m.length>0?`Missing error handling for: ${m.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function CX($,b){let A=b.sideEffects?.emits;if(!A||A.length===0)return{name:"event_emission",passed:!0};let n=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),m=A.map((W)=>{if(VX(W))return W.ref.key;return W.key}),y=m.filter((W)=>$.includes(W));return{name:"event_emission",passed:n&&y.length>0,details:!n?"No event emission pattern found":y.length===0?`Events not referenced: ${m.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function xX($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let A=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:A,details:A?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function MX($,b){let A=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:A,details:A?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function wA($){let{spec:b,implementationCode:A,implementationPath:n}=$,m=Date.now(),y=[KX(A),zX(A,n),LX(A,b),RX(A),IX(A,b),CX(A,b),xX(A,b),MX(A,b)],W=y.filter((X)=>!X.passed).map((X)=>({severity:X.name==="no_any_type"?"warning":"error",category:X.name.includes("import")?"import":X.name.includes("export")?"export":"type",message:X.details??`Check failed: ${X.name}`,location:n?{file:n}:void 0,suggestion:X.suggestion})),w=y.filter((X)=>X.passed).length,j=Math.round(w/y.length*100),B=W.filter((X)=>X.severity==="error").length===0,S=y.filter((X)=>!X.passed&&X.suggestion).map((X)=>X.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=y.find((X)=>X.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:j,issues:W,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:y.length,implemented:w}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}var EX={verbose:!1},TX=["structure","behavior","ai_review"];class D0{config;constructor($={}){this.config={...EX,...$}}async verify($,b,A={}){let n=Date.now(),m=new Map,y=[],W={spec:$,implementationCode:b},w=A.tiers??["structure","behavior"];for(let Z of TX){if(!w.includes(Z))continue;let X;switch(Z){case"structure":X=wA(W);break;case"behavior":X=T0(W);break;case"ai_review":if(this.config.aiApiKey)X=await WA(W,this.config);else X=E0(W);break;default:continue}if(m.set(Z,X),y.push(...X.issues),A.failFast&&!X.passed)break}let j=Array.from(m.values()),B=j.every((Z)=>Z.passed),S=j.length>0?Math.round(j.reduce((Z,X)=>Z+X.score,0)/j.length):100,Q=this.generateSummary(j,y);return{passed:B,score:S,reports:m,allIssues:y,summary:Q,duration:Date.now()-n}}verifyStructure($,b,A){return wA({spec:$,implementationCode:b,implementationPath:A})}verifyBehavior($,b,A){return T0({spec:$,implementationCode:b,implementationPath:A})}async verifyAI($,b,A){let n={spec:$,implementationCode:b,implementationPath:A};if(this.config.aiApiKey)return WA(n,this.config);return E0(n)}quickVerify($,b){return wA({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[n,m]of $.reports){if(b.push(`## ${this.formatTierName(n)}`),b.push(""),b.push(`**Status:** ${m.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${m.score}/100`),b.push(""),m.issues.length>0){b.push("### Issues"),b.push("");for(let y of m.issues){let W=y.severity==="error"?"\u274C":y.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(b.push(`${W} **${y.category}**: ${y.message}`),y.suggestion)b.push(` - Suggestion: ${y.suggestion}`)}b.push("")}if(m.coverage.scenarios.total>0)b.push(`**Scenarios:** ${m.coverage.scenarios.covered}/${m.coverage.scenarios.total}`);if(m.coverage.errors.total>0)b.push(`**Errors handled:** ${m.coverage.errors.handled}/${m.coverage.errors.total}`);b.push("")}let A=Array.from($.reports.values()).flatMap((n)=>n.suggestions);if(A.length>0){b.push("## Suggestions"),b.push("");for(let n of A.slice(0,10))b.push(`- ${n}`);if(A.length>10)b.push(`- ... and ${A.length-10} more`);b.push("")}return b.join(`
|
|
2576
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let A=[],n=$.every((j)=>j.passed),m=$.length>0?Math.round($.reduce((j,B)=>j+B.score,0)/$.length):100;A.push(n?"\u2713 Verification passed":"\u2717 Verification failed"),A.push(`Score: ${m}/100`),A.push("");for(let j of $){let B=j.passed?"\u2713":"\u2717";A.push(`${B} ${j.tier}: ${j.score}/100`)}A.push("");let y=b.filter((j)=>j.severity==="error"),W=b.filter((j)=>j.severity==="warning"),w=b.filter((j)=>j.severity==="info");if(y.length>0)A.push(`Errors: ${y.length}`);if(W.length>0)A.push(`Warnings: ${W.length}`);if(w.length>0)A.push(`Info: ${w.length}`);return A.join(`
|
|
2577
|
+
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function DX($){return new D0($)}var NX=new D0;var WB={};f(WB,{saveReleaseDraft:()=>t1,renderUpgradePrompt:()=>Gb,renderUpgradeChecklist:()=>H1,renderPatchNotes:()=>Zy,renderMigrationGuide:()=>Y1,renderMaintainerSummary:()=>Z1,renderCustomerPatchNote:()=>X1,renderCustomerGuide:()=>Xy,prepareReleaseAuthoring:()=>l1,parseConventionalCommit:()=>v0,isConventionalCommit:()=>fX,initReleaseArtifacts:()=>$B,getHighestBumpType:()=>qy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>i1,formatKeepAChangelog:()=>jA,formatConventionalChangelog:()=>P1,formatChangelogJson:()=>N0,filterCommitsByScope:()=>cX,filterBumpableCommits:()=>hX,commitsToChangeEntries:()=>Oy,commitToChangeEntry:()=>r1,checkReleaseArtifacts:()=>AB,buildReleaseArtifacts:()=>bB,applyVersionBump:()=>o1,analyzeVersionsFromCommits:()=>qb,analyzeVersions:()=>XA,DEFAULT_COMMIT_TYPE_MAP:()=>F0});import{basename as FX,dirname as vX}from"path";function jA($){let b=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],A=[...$].sort((n,m)=>k1(n.version,m.version));for(let n of A){b.push(`## [${n.version}] - ${n.date}`),b.push("");let m=n.changes.filter((Q)=>Q.type==="added"),y=n.changes.filter((Q)=>Q.type==="changed"),W=n.changes.filter((Q)=>Q.type==="deprecated"),w=n.changes.filter((Q)=>Q.type==="removed"),j=n.changes.filter((Q)=>Q.type==="fixed"),B=n.changes.filter((Q)=>Q.type==="security"),S=n.breakingChanges??n.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### \u26A0\uFE0F Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(m.length>0)b.push("### Added"),m.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(y.length>0)b.push("### Changed"),y.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(W.length>0)b.push("### Deprecated"),W.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(w.length>0)b.push("### Removed"),w.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(j.length>0)b.push("### Fixed"),j.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(B.length>0)b.push("### Security"),B.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("")}return b.join(`
|
|
2578
|
+
`)}function P1($){let b=["# Changelog",""],A=[...$].sort((n,m)=>k1(n.version,m.version));for(let n of A){let m=n.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":n.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${n.version} (${n.date}) - ${m}`),b.push("");let y={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let W of n.changes){let w=y[W.type]??"chore",j=W.path?`(${W.path})`:"",B=W.type==="breaking"?"!":"";b.push(`- **${w}${j}${B}**: ${W.description}`)}b.push("")}return b.join(`
|
|
2579
|
+
`)}function N0($,b){let A=$.analyses.filter((y)=>y.needsBump),n=new Date().toISOString(),m=n.split("T")[0]??"";return{generatedAt:n,baseline:b,specs:A.map((y)=>({key:y.specKey,version:y.suggestedVersion,path:y.specPath,entries:[{version:y.suggestedVersion,date:m,bumpType:y.bumpType,changes:y.changes,breakingChanges:y.changes.filter((W)=>W.type==="breaking")}]})),libraries:PX(A,m)}}function gX($){let b=$.split("/"),A=b.lastIndexOf("packages");if(A>=0&&A+2<b.length)return b.slice(0,A+3).join("/");return vX($)}var g1={major:3,minor:2,patch:1};function PX($,b){let A=new Map;for(let n of $){let m=gX(n.specPath),y=A.get(m);if(y)y.push(n);else A.set(m,[n])}return Array.from(A.entries()).flatMap(([n,m])=>{let y=m[0];if(!y)return[];let W=m.reduce((w,j)=>{return(g1[j.bumpType]??0)>(g1[w.bumpType]??0)?j:w},y);return[{name:FX(n),path:n,version:W.suggestedVersion,entries:[{version:W.suggestedVersion,date:b,bumpType:W.bumpType,changes:m.flatMap((w)=>w.changes),breakingChanges:m.flatMap((w)=>w.changes).filter((w)=>w.type==="breaking")}]}]})}function k1($,b){let A=(y)=>{return y.split(".").map((w)=>parseInt(w,10)||0)},n=A($),m=A(b);for(let y=0;y<3;y++){let W=n[y]??0,w=m[y]??0;if(W!==w)return w-W}return 0}var F0={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},kX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,rX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function v0($){let b=$.split(`
|
|
2580
|
+
`),A=b[0]?.trim();if(!A)return null;let n=A.match(kX);if(!n)return null;let[,m,y,W,w]=n;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2581
|
+
`).trim()||void 0,B=j?.match(rX),S=B?.[1];return{type:m.toLowerCase(),scope:y?.toLowerCase(),breaking:!!W||!!B,description:w.trim(),body:j,breakingDescription:S,raw:$}}function fX($){return v0($)!==null}function Gy($,b=F0){if($.breaking)return"major";return b[$.type]??null}function qy($,b=F0){let A=["major","minor","patch"],n=null;for(let m of $){let y=Gy(m,b);if(!y)continue;if(!n){n=y;continue}let W=A.indexOf(n);if(A.indexOf(y)<W)n=y}return n}function r1($){if($.breaking)return{type:"breaking",description:$.breakingDescription??$.description,path:$.scope};switch($.type){case"feat":return{type:"added",description:$.description,path:$.scope};case"fix":return{type:"fixed",description:$.description,path:$.scope};case"deprecate":return{type:"deprecated",description:$.description,path:$.scope};case"remove":return{type:"removed",description:$.description,path:$.scope};case"security":return{type:"security",description:$.description,path:$.scope};default:return{type:"changed",description:$.description,path:$.scope}}}function Oy($){return $.map(r1)}function cX($,b){return $.filter((A)=>A.scope?.toLowerCase()===b.toLowerCase())}function hX($,b=F0){return $.filter((A)=>Gy(A,b)!==null)}import{z as T}from"zod";import{ReleaseCapsuleSchema as f1}from"@contractspec/lib.contracts-spec";import{dump as dX,load as uX}from"js-yaml";var oX=".changeset/*.md",iX=".changeset/*.release.yaml",lX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,tX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function pX($,b){return(await $.glob({pattern:oX,cwd:b,absolute:!0})).filter((n)=>$.basename(n)!=="README.md")}async function BA($,b){let A=await pX($,b),n=[];for(let m of A){let y=await $.readFile(m);n.push(aX($.basename(m),y))}return n}async function SA($,b,A,n){let m=await $.glob({pattern:iX,cwd:b,absolute:!0}),y=new Map(A.map((j)=>[j.slug,j.packages])),W=new Map,w=[];for(let j of m){let B=$.basename(j).replace(/\.release\.yaml$/,"");if(n&&!n.has(B))continue;try{let S=uX(await $.readFile(j)),Q=eX(S,B,y.get(B)??[]);W.set(B,Q)}catch(S){w.push(sX(j,B,S))}}return{capsules:W,issues:w}}async function QA($,b){let A=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),n=[];for(let m of A){let y=JSON.parse(await $.readFile(m));if(!y.name||!y.version||y.private===!0)continue;let W=$.relative(b,$.dirname(m))||".";n.push({name:y.name,dir:W,version:y.version})}return n.sort((m,y)=>m.dir.localeCompare(y.dir))}function g0($,b){let A=new Set;for(let n of $){let m=b.find((y)=>y.dir==="."?!n.startsWith("packages/"):n===y.dir||n.startsWith(`${y.dir}/`));if(m)A.add(m.name)}return Array.from(A).sort((n,m)=>n.localeCompare(m))}function P0($,b){return`---
|
|
2582
|
+
${b.map((n)=>`"${n.name}": ${n.releaseType}`).join(`
|
|
2551
2583
|
`)}
|
|
2552
2584
|
---
|
|
2553
2585
|
|
|
2554
2586
|
${$}
|
|
2555
|
-
`}function
|
|
2556
|
-
`)}function
|
|
2557
|
-
`)){let j=w.trim().match(
|
|
2558
|
-
`)}function
|
|
2587
|
+
`}function k0($){return dX(f1.parse($),{noRefs:!0,lineWidth:100})}function ZA($){return $.map((b)=>{let A=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",n=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${A} ${b.message}.${n}`.trim()}).join(`
|
|
2588
|
+
`)}function aX($,b){let A=$.replace(/\.md$/,""),n=b.match(lX);if(!n)return{slug:A,summary:b.trim(),packages:[]};let m=n[1]??"",y=(n[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2589
|
+
`)){let j=w.trim().match(tX);if(!j)continue;let B=j[1],S=j[2];if(!B||S==="none")continue;W.push({name:B,releaseType:S})}return{slug:A,summary:y,packages:W}}function eX($,b,A){let n=typeof $==="object"&&$!==null?$:{},m=Array.isArray(n.packageNames)?n.packageNames.filter((y)=>typeof y==="string").map((y)=>({name:y,releaseType:n.releaseType??"patch"})):[];return f1.parse({...n,slug:b,packages:Array.isArray(n.packages)&&n.packages.length>0?n.packages:m.length>0?m:A})}function sX($,b,A){let n=typeof A==="object"&&A!==null?A:null,m=Array.isArray(n?.issues)?n.issues.map((W)=>W.message).filter((W)=>typeof W==="string"):[],y=m.length>0?`Release capsule validation failed: ${m.join("; ")}`:typeof n?.reason==="string"?`Release capsule YAML parse failed: ${n.reason}`:`Release capsule parse failed: ${A instanceof Error?A.message:String(A)}`;return{slug:b,filePath:$,message:y,line:typeof n?.mark?.line==="number"?n.mark.line+1:void 0,column:typeof n?.mark?.column==="number"?n.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as u1,determineBumpType as $Y}from"@contractspec/lib.contracts-spec";async function XA($,b={}){let{fs:A,git:n,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting version analysis...",{baseline:b.baseline});let W=b.pattern??"**/*.{operation,event,presentation}.ts",j=(await A.glob({pattern:W,cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${j.length} spec files`);let B=[],S=0,Q=0;for(let X of j)try{let Y=await A.readFile(X),H=r0(Y);if(!H)continue;let J=null;if(b.baseline)try{J=await n.showFile(b.baseline,X)}catch{J=null}let O=bY(Y,J),V=O.some((z)=>z.type==="breaking"),U=O.length>0&&!V,K=O.length>0;if(V)S++;if(U)Q++;let q=$Y(V,U),G=K?u1(H.version,q):H.version;B.push({specPath:X,specKey:H.key,currentVersion:H.version,suggestedVersion:G,bumpType:q,changes:O,hasBreaking:V,needsBump:K})}catch(Y){m.warn(`Failed to analyze ${X}:`,{error:Y instanceof Error?Y.message:String(Y)})}let Z=B.filter((X)=>X.needsBump).length;return m.info("Version analysis complete",{totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q}),{analyses:B,totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q,baseline:b.baseline}}async function qb($,b={}){let{git:A,logger:n}=$,m=b.baseline??"HEAD~10";n.info("Analyzing commits for version bump...",{baseline:m});try{let y=await A.log(m),W=[],w=[];for(let Q of y){let Z=v0(Q.message);if(Z)W.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),w.push(Z)}let j=qy(w),B=Oy(w),S=W.filter((Q)=>Q.breaking).length;return n.info("Commit analysis complete",{totalCommits:W.length,breakingCommits:S,suggestedBumpType:j}),{suggestedBumpType:j,commits:W,changes:B,totalCommits:W.length,breakingCommits:S}}catch(y){return n.warn("Failed to analyze commits",{error:y instanceof Error?y.message:String(y)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function o1($,b){let{fs:A,logger:n}=$,{specPath:m,dryRun:y=!1,config:W}=b;n.info("Applying version bump...",{specPath:m,bumpType:b.bumpType});try{let w=await A.readFile(m),j=r0(w);if(!j)return{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:h1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=u1(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=nY(w,j.version,S);await A.writeFile(m,X)}if(n.info("Version bump applied",{specPath:m,previousVersion:j.version,newVersion:S}),W?.integrateWithChangesets)await WY($,{specPath:m,bumpType:B,summary:b.changeDescription??`Bump ${j.key} to ${S}`,dryRun:y});return{success:!0,specPath:m,specKey:j.key,previousVersion:j.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(w){let j=w instanceof Error?w.message:String(w);return n.error("Version bump failed",{specPath:m,error:j}),{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:h1(),error:j}}}async function i1($,b={}){let{logger:A}=$,n=b.tiers??["spec","library","monorepo"],m=b.format??"keep-a-changelog";A.info("Generating changelogs...",{tiers:n,format:m});let y=await XA($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),W=[],w=new Map,j="",B=0;if(n.includes("spec"))for(let Q of y.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:mY(Q),kind:"changelog",specKey:Q.specKey,specVersion:Q.suggestedVersion,entries:[{version:Q.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:Q.bumpType,changes:Q.changes,breakingChanges:Q.changes.filter((X)=>X.type==="breaking")}]};W.push(Z),B++}if(n.includes("library")){let Q=yY(y.analyses);for(let[Z,X]of Q){let Y=X.filter((H)=>H.needsBump);if(Y.length>0)w.set(Z,jA(Y.map(d1))),B+=Y.length}}if(n.includes("monorepo")){let Q=y.analyses.filter((Z)=>Z.needsBump).map(d1);j=jA(Q)}let S=N0(y,b.baseline);return A.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:W,libraryMarkdown:w,monorepoMarkdown:j,json:S,totalEntries:B}}function r0($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),A=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!A)return null;let n=b[1],m=A[1];if(!n||!m)return null;return{key:n,version:m}}function bY($,b){let A=[];if(!b)return A.push({type:"added",description:"New spec added"}),A;let n=r0($),m=r0(b);if(!n||!m)return A;if(n.version!==m.version)A.push({type:"changed",description:`Version updated from ${m.version} to ${n.version}`,path:"meta.version"});let y=AY($,b);if(y.breaking)A.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(y.nonBreaking)A.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return A}function AY($,b){let A=/io:\s*\{[\s\S]*?\}/,n=$.match(A)?.[0]??"",m=b.match(A)?.[0]??"";if(n===m)return{breaking:!1,nonBreaking:!1};let y=c1(n),W=c1(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 c1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((n)=>n[1]).filter((n)=>!!n)}function nY($,b,A){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${A}'`)}function h1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function mY($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],A=$.changes.filter((y)=>y.type==="breaking"),n=$.changes.filter((y)=>y.type==="changed"),m=$.changes.filter((y)=>y.type==="added");if(A.length>0)b.push("### Breaking Changes"),A.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(m.length>0)b.push("### Added"),m.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(n.length>0)b.push("### Changed"),n.forEach((y)=>b.push(`- ${y.description}`)),b.push("");return b.join(`
|
|
2590
|
+
`)}function yY($){let b=new Map;for(let A of $){let y=A.specPath.match(/(.+?\/src\/)/)?.[1]??A.specPath,W=b.get(y)??[];W.push(A),b.set(y,W)}return b}function d1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function WY($,b){let{fs:A,logger:n}=$,{specPath:m,bumpType:y,summary:W,dryRun:w}=b;try{let j=c(m),B=P$(j);if(!B){n.warn("Could not determine package name for changeset",{specPath:m});return}let S=j,Q=null;while(!0){let H=A.join(S,".changeset");if(await A.exists(H)){Q=H;break}let J=A.dirname(S);if(J===S)break;S=J}if(!Q){n.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${wY()}.md`,X=A.join(Q,Z),Y=`---
|
|
2559
2591
|
"${B}": ${y}
|
|
2560
2592
|
---
|
|
2561
2593
|
|
|
2562
2594
|
${W}
|
|
2563
|
-
`;if(!w)await n.writeFile(X,Y),A.info("Generated changeset",{filePath:X});else A.info("Would generate changeset",{filePath:X,content:Y})}catch(j){A.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function $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((
|
|
2595
|
+
`;if(!w)await A.writeFile(X,Y),n.info("Generated changeset",{filePath:X});else n.info("Would generate changeset",{filePath:X,content:Y})}catch(j){n.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function wY(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],A=["run","fly","hop","eat","nap","cry","sing"],n=$[Math.floor(Math.random()*$.length)],m=b[Math.floor(Math.random()*b.length)],y=A[Math.floor(Math.random()*A.length)],W=Math.floor(Math.random()*1000);return`${n}-${m}-${y}-${W}`}var jY=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 l1($,b={}){let{fs:A,git:n,logger:m,ai:y}=$,W=x(b.workspaceRoot),w=await QA(A,W),j=b.baseline?await n.diffFiles(b.baseline):[],B=await BA(A,W),S=await SA(A,W,B),Q=b.packages&&b.packages.length>0?b.packages:g0(j,w),Z=b.baseline?await qb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??XY(B,S.capsules,Q),H=Y?A.join(W,".changeset",`${Y}.md`):void 0,J=Y?A.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((G)=>G.slug===Y):void 0,V=Y?S.capsules.get(Y):void 0,U=b.releaseType??V?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??YY(Q)),K=(H?await A.exists(H):!1)||(J?await A.exists(J):!1),q=await SY(y,BY({existingCapsule:V,existingChangeset:O,packageNames:Q,releaseType:U,summary:b.summary,workspacePackages:w,isBreaking:U==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await n.log(b.baseline)).map((G)=>G.message):[],parseIssues:S.issues.map((G)=>G.message)},m);return{workspaceRoot:W,source:K?"existing":"created",changesetPath:H??A.join(W,".changeset",`${q.slug}.md`),capsulePath:J??A.join(W,".changeset",`${q.slug}.release.yaml`),draft:q,warnings:S.issues.length?[`Some release capsules could not be parsed. ${ZA(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:A}=$,n=x(b.workspaceRoot),m=YA(b.draft),y=A.join(n,".changeset",`${m.slug}.md`),W=A.join(n,".changeset",`${m.slug}.release.yaml`),w=await A.exists(y)||await A.exists(W)?"updated":"created",j=P0(m.summary,m.packages),B=k0(ZY(m));return await A.writeFile(y,j),await A.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function BY($){if($.existingCapsule)return YA({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((n)=>({...n,version:$.workspacePackages.find((m)=>m.name===n.name)?.version??n.version})):$.packageNames.map((n)=>({name:n,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===n)?.version})),A=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return YA({slug:$.selectedSlug??HY(A),summary:A,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:p1(A),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function SY($,b,A,n){if(!$)return b;try{let m=await $.generateStructured({schema:jY,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 QY(b,m.object)}catch(m){return n.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:m instanceof Error?m.message:String(m)}),b}}function QY($,b){let A=[...$.audiences];return Jy(A,"maintainer",b.maintainerSummary),Jy(A,"customer",b.customerSummary),Jy(A,"integrator",b.integratorSummary),YA({...$,summary:a1($.summary)?b.summary:$.summary,audiences:A,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function YA($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:p1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function ZY($){let{releaseType:b,...A}=YA($);return{schemaVersion:"1",...A}}function p1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Jy($,b,A){let n=$.find((m)=>m.kind===b);if(n&&!a1(n.summary))return;if(n){n.summary=A;return}$.push({kind:b,summary:A})}function XY($,b,A){let n=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(n.size===1)return Array.from(n)[0];if(A.length===0)return;let m=Array.from(n).filter((y)=>{let W=b.get(y),w=$.find((B)=>B.slug===y);return(W?.packages.map((B)=>B.name)??w?.packages.map((B)=>B.name)??[]).some((B)=>A.includes(B))});return m.length===1?m[0]:void 0}function YY($){return $.length>0?"minor":"patch"}function a1($){return $.trim().startsWith("Describe the ")}function HY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as e1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as GY,DEFAULT_CONTRACTSRC as qY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var s1="generated/releases",OY="1970-01-01T00:00:00.000Z",f0=qY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function $B($,b={}){let{fs:A,git:n,logger:m}=$,y=x(b.workspaceRoot),W=await QA(A,y),w=b.baseline?await n.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:g0(w,W),B=b.baseline?await qb($,{baseline:b.baseline,workspaceRoot:y}):null,S=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:y}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??KY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??RY(X),H=j.map((q)=>({name:q,releaseType:Z,version:W.find((G)=>G.name===q)?.version})),J={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:H,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:X},{kind:"customer",summary:X}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=A.join(y,".changeset",`${Y}.md`),V=A.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await A.exists(O))throw Error(`Changeset already exists: ${O}`);if(await A.exists(V))throw Error(`Release capsule already exists: ${V}`)}let U=P0(X,H),K=k0(J);if(!b.dryRun)await A.writeFile(O,U),await A.writeFile(V,K);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:V,changesetContent:U,capsuleContent:K,packages:H,releaseType:Z,isBreaking:J.isBreaking}}async function bB($,b={}){let{fs:A,logger:n}=$,m=x(b.workspaceRoot),y=await nB(A,m),W=A.join(m,b.outputDir??s1),w=A.join(W,"manifest.json"),j=await VY(A,w),B=await BA(A,m),S=await mB($,{workspaceRoot:m,changesets:B,scope:b.scope??"current",baseline:b.baseline}),Q=await SA(A,m,B,S);if(Q.issues.length>0)throw Error(ZA(Q.issues));let Z=Q.capsules,X=await QA(A,m),Y=new Map((j?.releases??[]).map((_)=>[_.slug,_])),H=(b.scope??"current")!=="all",J=Array.from(Z.entries()).map(([_,L])=>{let I=Y.get(_),E=L.packages.map((N)=>({...N,version:yB(N,X,I,H)}));return{slug:_,version:_Y(L,X,I,H),summary:L.summary,date:I?.date??LY(),isBreaking:L.isBreaking,packages:E,affectedRuntimes:[...L.affectedRuntimes],affectedFrameworks:[...L.affectedFrameworks],audiences:[...L.audiences],deprecations:[...L.deprecations],migrationInstructions:[...L.migrationInstructions],upgradeSteps:[...L.upgradeSteps],validation:L.validation}}),O=e1.parse({generatedAt:zY(J),releases:J}),V=b.agentTargets??y.agentTargets??["codex"],U=yA(O,[],V,Gb),K=A.join(W,"upgrade-manifest.json"),q=A.join(W,"patch-notes.md"),G=A.join(W,"customer-guide.md"),z=Object.fromEntries(U.agentPrompts.map((_)=>[_.agent,A.join(W,"prompts",`${_.agent}.md`)]));if(!b.dryRun){await A.writeFile(w,JSON.stringify(O,null,2)),await A.writeFile(K,JSON.stringify(O,null,2)),await A.writeFile(q,Zy(O)),await A.writeFile(G,Xy(O));for(let _ of U.agentPrompts)await A.writeFile(z[_.agent]??"",_.prompt)}return n.info("Built release artifacts",{outputDir:W,releasesBuilt:O.releases.length}),{outputDir:W,manifestPath:w,upgradeManifestPath:K,patchNotesPath:q,customerGuidePath:G,promptPaths:z,manifest:O,upgradePlan:U,releasesBuilt:O.releases.length}}async function AB($,b={}){let{fs:A}=$,n=x(b.workspaceRoot),m=await nB(A,n),y=A.join(n,b.outputDir??s1),W=[],w=[],j=[],B=await BA(A,n),S=await mB($,{workspaceRoot:n,changesets:B,scope:b.scope??"current",baseline:b.baseline}),Q=await SA(A,n,B,S),Z=Q.capsules,X=B.length>0,Y=!X&&Z.size>0;j.push(...Q.issues.map((H)=>ZA([H]))),Ob(W,X||Y,"changesets",X?`Found ${B.length} release changeset(s).`:Y?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let H of B)if(!Z.has(H.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${H.slug}.`);for(let[H,J]of Z){if(J.isBreaking&&J.migrationInstructions.length===0)j.push(`Breaking release ${H} is missing migration instructions.`);if(J.validation.commands.length===0)j.push(`Release capsule ${H} is missing validation commands.`);if(J.validation.evidence.length===0)j.push(`Release capsule ${H} is missing validation evidence.`)}if(b.baseline){try{let H=await K$($,{baseline:b.baseline,workspaceRoot:n});if(Ob(W,!0,"impact",`Impact status: ${H.status}`),H.summary.breaking>0&&!Array.from(Z.values()).some((J)=>J.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(H){Ob(W,!1,"impact",c0(H)),j.push(`Impact detection failed: ${c0(H)}`)}try{let H=await XA($,{baseline:b.baseline,workspaceRoot:n});Ob(W,!0,"versioning",`${H.specsNeedingBump} spec(s) need version review.`)}catch(H){Ob(W,!1,"versioning",c0(H)),j.push(`Version analysis failed: ${c0(H)}`)}}if(b.strict)for(let H of m.publishArtifacts??[]){let J=A.join(y,H);if(!await A.exists(J))j.push(`Missing generated release artifact: ${J}`)}if(Ob(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!X&&!Y)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function nB($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return f0;try{let n=JSON.parse(await $.readFile(A)),m=GY.safeParse(n);return m.success?{...f0,...m.data.release}:f0}catch{return f0}}async function mB($,b){if(b.scope==="all")return;if(b.changesets.length>0)return new Set(b.changesets.map((m)=>m.slug));let A=await JY($.git,b.baseline),n=new Set;for(let m of A){let y=UY(m.path);if(!y)continue;if(m.path.endsWith(".release.yaml")||m.path.endsWith(".md"))n.add(y)}return n.size>0?n:void 0}async function JY($,b){if(b&&b!=="HEAD"&&$.diffNameStatus)return $.diffNameStatus(b,[".changeset"]);if($.statusFiles)return $.statusFiles([".changeset"]);if(b)return(await $.diffFiles(b,[".changeset"])).map((n)=>({status:"M",path:n}));return[]}function UY($){let A=$.replace(/\\/g,"/").split("/").pop();if(!A||A==="README.md")return;if(A.endsWith(".release.yaml"))return A.replace(/\.release\.yaml$/,"");if(A.endsWith(".md"))return A.replace(/\.md$/,"");return}async function VY($,b){if(!await $.exists(b))return;try{return e1.parse(JSON.parse(await $.readFile(b)))}catch{return}}function KY($){return $.length>0?"minor":"patch"}function _Y($,b,A,n){return $.packages.map((y)=>yB(y,b,A,n)).find((y)=>typeof y==="string")??"0.0.0"}function yB($,b,A,n){let m=b.find((W)=>W.name===$.name)?.version,y=A?.packages.find((W)=>W.name===$.name)?.version;return n?m??$.version??y:$.version??y??m}function zY($){let A=$.map((n)=>n.date).filter(Boolean).sort().at(-1);return A?`${A}T00:00:00.000Z`:OY}function LY(){return new Date().toISOString().split("T")[0]??"1970-01-01"}function RY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Ob($,b,A,n){$.push({name:A,ok:b,message:n})}function c0($){return $ instanceof Error?$.message:String($)}var qB={};f(qB,{silentLogger:()=>BB,runWorkflow:()=>SB,loadWorkflows:()=>Ky,loadVibeConfig:()=>d0,installPack:()=>GB,getWorkflow:()=>ZB,exportContext:()=>jB,consoleLogger:()=>Vy,builtinWorkflows:()=>u0,DEFAULT_VIBE_CONFIG:()=>h0});import{existsSync as IY}from"fs";import{readFile as CY}from"fs/promises";import{join as Uy}from"path";import xY from"js-yaml";var h0={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function d0($){let b=$??process.cwd(),A=x(b)??b,n=[Uy(A,".contractspec","vibe","config.json"),Uy(A,".contractspec","vibe","config.yaml"),Uy(A,".contractspec","vibe","config.yml")],m={};for(let y of n)if(IY(y))try{let W=await CY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=xY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...h0,...m}}import{existsSync as MY}from"fs";import{copyFile as EY,mkdir as wB,readFile as TY,writeFile as DY}from"fs/promises";import{dirname as NY,join as Jb}from"path";import{glob as FY}from"glob";var vY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function jB($){let b=$??process.cwd(),A=x(b)??b,n=await d0(b),m=Jb(A,".contractspec","context"),y=Jb(m,"files"),W=[...vY],w=Jb(A,".gitignore");if(MY(w)){let H=(await TY(w,"utf-8")).split(`
|
|
2596
|
+
`).map((J)=>J.trim()).filter((J)=>J&&!J.startsWith("#"));W=[...W,...H]}let j=n.contextExportAllowlist.length>0?n.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let Y of j){let H=await FY(Y,{cwd:A,ignore:W,nodir:!0,dot:!0});B.push(...H)}let S=Array.from(new Set(B)).sort();if(S.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await wB(y,{recursive:!0});let Q=[];for(let Y of S){let H=Jb(A,Y),J=Jb(y,Y);await wB(NY(J),{recursive:!0}),await EY(H,J),Q.push({path:Y,size:0})}let Z=Jb(m,"index.json"),X={generatedAt:new Date().toISOString(),files:Q.map((Y)=>Y.path),config:{allowlist:n.contextExportAllowlist,ignores:W.length}};return await DY(Z,JSON.stringify(X,null,2)),{success:!0,files:S,indexPath:Z}}var u0=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and generate artifacts.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
|
|
2565
2597
|
Please review them and move selected files to contracts/ directory.
|
|
2566
|
-
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"release",label:"Prepare Release",command:"contractspec release prepare"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as
|
|
2567
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2568
|
-
`);let y={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let W of $.steps){let w={id:W.id,name:W.label,status:"skip",command:W.command};if(W.tracks&&!W.tracks.includes(b.track)){y.steps.push(w);continue}if(W.condition){if(!await W.condition(b)){y.steps.push(w);continue}}if(
|
|
2569
|
-
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)
|
|
2598
|
+
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"release",label:"Prepare Release",command:"contractspec release prepare"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as gY}from"child_process";var BB={log:()=>{},warn:()=>{},error:()=>{}},Vy={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function SB($,b,A){let n=A?.logger??Vy,m=A?.prompter;if(n.log(`
|
|
2599
|
+
Running Workflow: ${$.name}`),$.description)n.log($.description);if(n.log(`Track: ${b.track}`),b.dryRun)n.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2600
|
+
`);let y={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let W of $.steps){let w={id:W.id,name:W.label,status:"skip",command:W.command};if(W.tracks&&!W.tracks.includes(b.track)){y.steps.push(w);continue}if(W.condition){if(!await W.condition(b)){y.steps.push(w);continue}}if(n.log(`
|
|
2601
|
+
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)n.log(` Command: ${W.command}`);if(W.manualCheckpoint){if(b.dryRun)n.warn(" [Manual Checkpoint] Would pause here for user input.");else if(m){if(W.manualMessage)n.log(W.manualMessage);let j=await m.select({message:"Checkpoint action:",choices:[{name:"Proceed",value:"proceed",description:"Run this step"},{name:"Skip Step",value:"skip",description:"Skip this step and continue"},{name:"Abort Workflow",value:"abort",description:"Exit workflow"}]});if(j==="abort")return n.warn("Workflow aborted by user."),y.success=!1,y.steps.push({...w,status:"skip",error:"Aborted by user"}),y;if(j==="skip"){n.warn(" \u2192 Skipped by user."),y.steps.push(w);continue}}}if(!b.dryRun)try{if(W.execute)await W.execute(b);else if(W.command)await PY(W.command,b.root);w.status="pass",y.stepsExecuted.push(W.id),y.steps.push(w),n.log(" \u2713 Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return n.error(` \u274C Failed: ${B}`),y.success=!1,y.error=j instanceof Error?j:Error(String(j)),w.status="fail",w.error=B,y.stepsExecuted.push(W.id),y.steps.push(w),y}else y.steps.push(w)}return y}async function PY($,b){let A=$.split(" "),n=A[0],m=A.slice(1);if(!n)throw Error("Invalid command");return new Promise((y,W)=>{let w=gY(n,m,{cwd:b,stdio:"inherit",shell:!0});w.on("error",W),w.on("exit",(j)=>{if(j===0)y();else W(Error(`Command exited with code ${j}`))})})}import{existsSync as kY}from"fs";import{readdir as rY,readFile as fY}from"fs/promises";import{join as QB}from"path";import cY from"js-yaml";async function Ky($){let b=[...u0],A=$??process.cwd(),n=x(A)??A,m=QB(n,".contractspec","vibe","workflows");if(kY(m))try{let y=await rY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await fY(QB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=cY.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 ZB($,b){return(await Ky(b)).find((n)=>n.id===$)}import{existsSync as _y}from"fs";import{copyFile as XB,mkdir as YB,readdir as HB,stat as hY}from"fs/promises";import{join as N$,resolve as dY}from"path";async function GB($,b){let A=b??process.cwd(),n=x(A)??A;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let m=dY(A,$);if(!_y(m))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${m}`};let y=0,W=0,w=N$(m,"workflows");if(_y(w)){let B=N$(n,".contractspec","vibe","workflows");await YB(B,{recursive:!0});let S=await HB(w);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await XB(N$(w,Q),N$(B,Q)),y++}let j=N$(m,"templates");if(_y(j)){let B=N$(n,".contractspec","vibe","templates");await YB(B,{recursive:!0});let S=await HB(j);for(let Q of S){let Z=N$(j,Q),X=N$(B,Q);if((await hY(Z)).isFile())await XB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as uY}from"@contractspec/module.workspace";var OB=["product","eng","qa"];function oY($){return OB.includes($)}async function uE($,b){if(!oY(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${OB.join(", ")}`);let A,n,m;if(b.specFiles&&b.specFiles.length>0)A=b.specFiles;else{let W=await iY($,{baseline:b.baseline});if(n=W.totalSpecs,m=W.changedFilesCount,b.baseline){if(W.changedFilesCount===0)return{views:[],totalSpecs:n,changedFilesCount:0,status:"no_changes"};if(W.specFiles.length===0)return{views:[],totalSpecs:n,changedFilesCount:m,status:"no_changed_specs"}}A=W.specFiles}if(A.length===0)return{views:[],totalSpecs:n,changedFilesCount:m,status:"no_specs"};let y=[];for(let W of A){let w=await lY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:n,changedFilesCount:m,status:"success"}}async function iY($,b={}){let n=(await B$({fs:$.fs})).map((w)=>w.filePath),m=n.length;if(!b.baseline)return{specFiles:n,totalSpecs:m};let y=await $.git.diffFiles(b.baseline);if(y.length===0)return{specFiles:[],totalSpecs:m,changedFilesCount:0,hasChanges:!1};let W=n.filter((w)=>y.some((j)=>w.endsWith(j)||j.endsWith(w)||w.includes(j)||j.includes(w)));return{specFiles:W,totalSpecs:m,changedFilesCount:y.length,hasChanges:W.length>0}}async function lY($,b,A){if(!await A.fs.exists($))throw Error(`File not found: ${$}`);let n=await uY($);if(n.length===0)return`No specs found in ${$} (Parse result empty)`;return n.map((m)=>tY(m,b)).join(`
|
|
2570
2602
|
|
|
2571
2603
|
---
|
|
2572
2604
|
|
|
2573
|
-
`)}function
|
|
2574
|
-
`)}function
|
|
2605
|
+
`)}function tY($,b){let A=[];switch(b){case"product":pY($,A);break;case"eng":aY($,A);break;case"qa":eY($,A);break}return A.join(`
|
|
2606
|
+
`)}function pY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2575
2607
|
${$.meta.goal}
|
|
2576
2608
|
`);if($.meta.context)b.push(`### Context
|
|
2577
2609
|
${$.meta.context}
|
|
2578
|
-
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((
|
|
2579
|
-
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((
|
|
2580
|
-
`)}export{
|
|
2610
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- \u2705 Enforces Business Policies");if($.hasIo)b.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((A)=>b.push(`- **${A.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function aY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function eY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2611
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((A)=>b.push(`- \uD83E\uDDEA \`${A.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((A)=>b.push(`- [ ] Verify event \`${A.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((A)=>b.push(`- [ ] Test Operation flow: \`${A.name}\``));if($.presentations?.length)$.presentations.forEach((A)=>b.push(`- [ ] Test UI Component: \`${A.name}\``))}}function tE($,b,A,n){let{watcher:m,fs:y,logger:W}=$,w=m.watch(A),j=n?.validate??(async(S)=>{await p$(S,{fs:y,logger:W})}),B=n?.build??(async(S)=>{await wb(S,{fs:y,logger:W},b)});return w.on(async(S)=>{if(S.type!=="change")return;if(W.info("watchSpecs.changed",{path:S.path}),A.runValidate)await j(S.path);if(A.runBuild)if(A.dryRun)W.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),w}async function eE($,b,A={}){let n=(A.getWorkspaceInfo??hy)(b),m=$.join(n.workspaceRoot,".contractsrc.json"),y=$.join(n.packageRoot,".contractsrc.json"),W=await $.exists(m),w=n.workspaceRoot!==n.packageRoot?await $.exists(y):!1,j;if(W)try{let B=await $.readFile(m),S=JSON.parse(B);if(S.packages||S.excludePackages||S.recursive)j={packages:S.packages,excludePackages:S.excludePackages,recursive:S.recursive}}catch{}return{...n,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?y:void 0}}async function sE($,b){let A=[],n=$.join(b,".contractsrc.json");if(await $.exists(n))A.push(n);let m=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let y of m)if(y!==n)A.push(y);return A}async function $T($,b,A){let n={};if(b&&await $.exists(b))try{let m=await $.readFile(b);n=JSON.parse(m)}catch{}if(A&&await $.exists(A))try{let m=await $.readFile(A),y=JSON.parse(m);n=JB(n,y)}catch{}return n}function JB($,b){let A={...$};for(let n of Object.keys(b)){let m=$[n],y=b[n];if(typeof m==="object"&&m!==null&&!Array.isArray(m)&&typeof y==="object"&&y!==null&&!Array.isArray(y))A[n]=JB(m,y);else A[n]=y}return A}function bT($){let b=[];if(b.push(`Package Manager: ${$.packageManager}`),b.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(b.push("Monorepo: Yes"),b.push(`Package Root: ${$.packageRoot}`),$.packageName)b.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)b.push(`Package Patterns: ${$.packages.join(", ")}`)}else b.push("Monorepo: No");if($.workspaceConfigPath)b.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)b.push(`Package Config: ${$.packageConfigPath}`);return b.join(`
|
|
2612
|
+
`)}export{tE as watchSpecs,qB as vibe,WB as versioning,YX as verifyWithAIEnhanced,WA as verifyWithAI,wA as verifyStructure,NX as verifyService,F1 as verifySemanticFields,M7 as verifyImportedContracts,RR as verifyImplementationAgainstParsedSpec,T0 as verifyBehavior,aC as validateTenantConfig,uC as validateSpecs,p$ as validateSpec,b1 as validateScannedSpec,vC as validatePackageScaffold,MC as validateImplementationWithAgent,b0 as validateImplementationFiles,dC as validateDiscoveredSpecs,RC as validateBlueprint,oY as validateAudience,cz as validateAgainstOpenApiService,eW as utils,L1 as upgrade,Rx as updateSpec,OQ as toKebabCase,uW as templates,kz as syncWithOpenApiService,jx as syncSpecs,wX as stringToCacheKey,ny as setupUsageMd,Q0 as setupGitignore,am as setupAgentsMd,zI as searchRegistry,a as safeParseJson,Gx as runTests,qx as runTestSpecs,QC as runSetup,QI as runQuickstart,Vw as runDoctor,QK as runCIChecks,mw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,zQ as resolveImplementations,Un as resolveDefaultBuildTargets,fj as resolveAuthoredModuleValue,Dw as resolveAllImplementations,AA as renderManagedMarkdownBlock,sy as prompts,fy as parseGitModules,Mw as parseExplicitImplementations,hw as packageDeclarations,aH as operationRegistry,ij as onboarding,pm as normalizeMarkdownContent,iT as module,$T as mergeMonorepoConfigs,_0 as mergeManagedMarkdown,k4 as mergeGitignoreContent,P as loadWorkspaceConfig,AU as loadPackageAuthoredDocBlocks,kj as loadAuthoredModuleValue,fR as loadAuthoredModuleIfExists,U0 as loadAuthoredModuleExports,W$ as loadAuthoredModule,bU as loadAuthoredDocBlocksFromSourceFiles,Ox as listTests,iY as listSpecsForView,B$ as listSpecs,_I as listFromRegistry,Yn as listAgentTypes,Ub as isMonorepo,ZI as isContractSpecInstalled,aO as isConnectPreset,pO as isBuilderPreset,Tb as inferSetupPresetFromConfig,qQ as inferImplementationType,_7 as importFromSourceService,Lj as importFromOpenApiService,$j as impact,vj as hooks,QV as groupSpecsByType,w5 as getWorkspacePackages,hy as getWorkspaceInfo,g3 as getRunCommand,im as getProductionDependencies,P$ as getPackageName,B5 as getMetaRepoInfo,dy as getInstallCommand,TU as getImplementationSummary,DO as getGraphStats,eE as getExtendedWorkspaceInfo,P3 as getExecCommand,lm as getDevDependencies,om as getDependencies,xw as getConventionPaths,EO as getContractNode,lA as getClaudeDesktopConfigPath,Tn as getBuilderRuntimeModeForPreset,yw as getBuilderBootstrapPresetForSetupPreset,tW as getApiKey,sU as getAllSpecs,HJ as getAllLayerLocations,Kb as getAgentAdapter,nn as getAIProvider,xA as genericMCPAdapter,dW as generateWorkflowSpec,kA as generateWorkflowRunnerTemplate,NA as generateWorkflowDevkitWorkflowTemplate,gA as generateWorkflowDevkitStreamRouteTemplate,FA as generateWorkflowDevkitStartRouteTemplate,PA as generateWorkflowDevkitGenericTemplate,vA as generateWorkflowDevkitFollowUpRouteTemplate,iA as generateVscodeSettings,qW as generateVisualizationSpec,uE as generateViews,lY as generateView,Qw as generateUsageGuide,HW as generateTranslationSpec,hW as generateThemeSpec,NW as generateTestTemplate,YW as generateTestSpec,cW as generateTelemetrySpec,KW as generatePwaAppManifestSpec,JW as generateProductIntentSpec,fW as generatePresentationSpec,XW as generatePolicySpec,rW as generateOperationSpec,kW as generateMigrationSpec,zR as generateMermaidDiagram,C7 as generateMarkdownReport,gW as generateKnowledgeSpaceSpec,GW as generateJobSpec,vW as generateIntegrationSpec,VW as generateHarnessSuiteSpec,UW as generateHarnessScenarioSpec,TW as generateHandlerTemplate,v7 as generateGuideFromParsedSpec,EW as generateFormSpec,MW as generateFeatureSpec,ER as generateFeatureContextMarkdown,xW as generateExperimentSpec,EA as generateExampleSpec,CW as generateEventSpec,zw as generateDocsFromSpecs,IW as generateDataViewSpec,TA as generateDataViewRendererTemplate,g7 as generateCursorRulesFromParsedSpec,Bw as generateCursorRules,Db as generateCursorMcpConfig,jb as generateContractsrcConfig,DW as generateComponentTemplate,x7 as generateCliReport,jw as generateClaudeMcpConfig,ZW as generateCapabilitySpec,Rw as generateArtifacts,RW as generateAppBlueprintSpec,Sw as generateAgentsGuide,OW as generateAgentSpec,AW as formatters,bT as formatWorkspaceInfo,IR as formatVerificationReport,XI as formatQuickstartPreview,rj as formatModuleLoadError,F as formatJson,aL as formatFiles,dJ as formatDoctorSummary,uJ as formatCheckResult,Ej as fix,x as findWorkspaceRoot,c as findPackageRoot,cy as findMetaRepoRoot,sE as findAllConfigFiles,$V as filterIssuesByType,bV as filterIssuesBySeverity,Ij as features,Iw as extractSpecReferences,ez as extractContracts,TR as exportSpecForLLM,D6 as exportOpenApi,TO as exportGraphAsDot,iW as ensurePackageScaffold,cA as discoverSpecs,h$ as discoverSpecFiles,pA as discoverLayers,A0 as discoverImplementationsForSpec,IU as discoverAllImplementations,Ew as determineStatus,S5 as detectRepositoryType,e$ as detectPackageManager,_z as deleteSpec,A$ as deepMergePreserve,Dn as deepMergeOverwrite,IA as cursorCLIAdapter,px as createWorkspaceStateCacheStorage,N5 as createWorkspaceRegistry,DX as createVerifyService,yM as createVerificationCacheService,qz as createSpecCreator,Ww as createSetupNextSteps,ww as createSetupGitignorePatterns,UI as createRegeneratorService,E0 as createQuickAIReview,rA as createPackageTargetSpecSource,vy as createNoopLoggerAdapter,gy as createNodeWatcherAdapter,Ny as createNodeGitAdapter,Ey as createNodeFsAdapter,Iy as createNodeAiAdapter,R3 as createNodeAdapters,lx as createInMemoryCacheStorage,ox as createFileSystemCacheStorage,L9 as createEmptyLayerInventory,Fy as createConsoleLoggerAdapter,T3 as createBunFsAdapter,n9 as createBuilderWorkspaceId,Z8 as createAgentGuideService,Uj as connect,E1 as computeContentHash,Rz as compareSpecs,JK as cleanArtifacts,LA as claudeCodeAdapter,T1 as cacheKeyToString,wb as buildSpec,dA as analyzeWorkspaceDocBlocks,n0 as analyzeIntegrity,bR as analyzeGap,sW as analyzeDeps,X8 as agentGuideService,Xn as agentAdapters,Zn as adoption,KI as addToRegistry,cR as __moduleLoaderInternals,x1 as WorkspaceStateCacheStorage,FH as WorkspaceBundle,D0 as VerifyService,D1 as VerificationCacheService,OB as VALID_AUDIENCES,U2 as TestGeneratorService,Kj as SpecCreatorService,JA as SimpleAgent,$w as SETUP_TARGET_LABELS,Aw as SETUP_PRESET_LABELS,nw as SETUP_PRESET_DESCRIPTIONS,Eb as SETUP_GITIGNORE_PATTERNS,SZ as RuleSyncService,K0 as RegistryClient,g5 as PrActionService,OA as OpenAICodexAgent,lj as MINIMAL_DEPENDENCIES,C1 as InMemoryCacheStorage,CA as GenericMCPAdapter,I1 as FileSystemCacheStorage,mZ as FULL_DEPENDENCIES,F5 as DriftActionService,q$ as DEFAULT_SPEC_PATTERNS,v$ as DEFAULT_FS_IGNORES,M1 as DEFAULT_CACHE_CONFIG,RA as CursorCLIAdapter,qA as CursorAgent,GA as ClaudeCodeAgent,zA as ClaudeCodeAdapter,qZ as CONTRACTSPEC_USAGE_BLOCK_START,OZ as CONTRACTSPEC_USAGE_BLOCK_END,ZZ as CONTRACTSPEC_AGENTS_BLOCK_START,XZ as CONTRACTSPEC_AGENTS_BLOCK_END,YK as CI_CHECK_CATEGORY_LABELS,Uw as CHECK_CATEGORY_LABELS,UA as AgentOrchestrator,MA as AgentGuideService,Mb as ALL_SETUP_TARGETS,bw as ALL_SETUP_PRESETS,XK as ALL_CI_CHECK_CATEGORIES,Jw as ALL_CHECK_CATEGORIES,Y0 as AIGenerator};
|