@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/node/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(n
|
|
3
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
4
|
-
`).map((
|
|
1
|
+
import{createRequire as _B}from"node:module";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$=_B(import.meta.url);import{ContractsrcSchema as zS,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=zS.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 K6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as _6,buildEventSpecPrompt as z6,buildFormPrompt as L6,buildHandlerPrompt as R6,buildOperationSpecPrompt as I6,buildPresentationSpecPrompt as C6,buildTestPrompt as x6,getCodeGenSystemPrompt as pb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Tm,generateText as X0,streamText as M6}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 K6(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=I6($,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=z6($);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=C6($,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:R6($),system:pb()})).text}async generateComponent($){let b=this.getModel();return(await X0({model:b,prompt:_6($),system:pb()})).text}async generateForm($){let b=this.getModel();return(await X0({model:b,prompt:L6($),system:pb()})).text}async generateTests($,b,A){let n=this.getModel();return(await X0({model:n,prompt:x6($,b,A),system:pb()})).text}async streamCodeGeneration($,b){let A=this.getModel(),n=await M6({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 tT from"@contractspec/module.workspace";import{anthropic as zB}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 LB,generateText as RB,streamText as IB}from"ai";import{ollama as CB}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 RB({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 LB(n)).object}},async streamText(b,A){let n=i0($),m=await IB({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 zB(m)}case"openai":{let m=A??Ry.openai;return Ly(m)}case"ollama":return CB(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 tB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as xB,stat as MB,mkdir as Cy,readFile as EB,rm as TB,writeFile as DB}from"node:fs/promises";import{basename as NB,dirname as xy,isAbsolute as FB,join as vB,relative as gB,resolve as My}from"node:path";import{glob as PB}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 xB(A(n)),!0}catch{return!1}},async readFile(n){return EB(A(n),"utf-8")},async writeFile(n,m){let y=A(n),W=xy(y);await Cy(W,{recursive:!0}),await DB(y,m,"utf-8")},async remove(n){await TB(A(n),{recursive:!0,force:!0})},async stat(n){let m=await MB(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 PB(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 NB(n)},join(...n){return vB(...n)},relative(n,m){return gB(n,m)}};function A(n){return FB(n)?n:My(b,n)}}import{spawnSync as kB}from"node:child_process";import{existsSync as Ty,readFileSync as Dy}from"node:fs";import{access as rB}from"node:fs/promises";import{resolve as HA}from"node:path";function Ny($){let b=$??process.cwd();return{async currentBranch(){try{let A=g$(["rev-parse","--abbrev-ref","HEAD"],b).trim()||fB(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 cB(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 rB(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(`
|
|
2
|
+
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(A,n){try{let m=n&&n.length>0?["--",...n]:[];return g$(["diff","--name-only",`${A}...HEAD`,...m],b).trim().split(`
|
|
3
|
+
`).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 hB(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 dB(y)}catch{return[]}}}}function fB($){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 cB($,b){let A=HA($,b);if(!Ty(A))return;return Dy(A,"utf8")}function g$($,b,A={}){let n=kB("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 hB($){return $.split(`
|
|
4
|
+
`).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 dB($){return $.split(`
|
|
5
|
+
`).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 uB()}}}function vy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:oB}}function uB(){return{start($){console.warn(`⏳ ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`✅ ${$??"Done"}`)},fail($){console.error(`❌ ${$??"Failed"}`)},warn($){console.warn(`⚠️ ${$??"Warning"}`)},stop(){}}}function oB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import iB from"chokidar";var lB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function gy($){let b=$??process.cwd();return{watch(A){let n=[],m,y=iB.watch(A.pattern,{cwd:b,ignored:A.ignore??lB,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 C3($={}){let{cwd:b,config:A,silent:n}=$,m=A??tB;return{fs:Ey(b),git:Ny(b),watcher:gy(b),ai:Iy(m),logger:n?vy():Fy()}}import{stat as pB,mkdir as aB}from"node:fs/promises";import{basename as eB,dirname as sB,isAbsolute as $5,join as b5,relative as A5,resolve as Py}from"node:path";import{glob as n5}from"glob";function N3($){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 pB(A(n));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(n){await aB(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 n5(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 sB(n)},basename(n){return eB(n)},join(...n){return b5(...n)},relative(n,m){return A5(n,m)}};function A(n){return $5(n)?n:Py(b,n)}}import{existsSync as o,readFileSync as z$}from"node:fs";import{tmpdir as m5}from"node:os";import{dirname as l0,isAbsolute as y5,join as u,relative as W5,resolve as a$}from"node: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=W5(b,$);return A===""||!A.startsWith("..")&&!y5(A)}function t0($){let b=a$($),A=a$(m5());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 j5($){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(`
|
|
6
|
+
`).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"))&&B5(B);n.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return n}catch{return[]}}function B5($){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 S5($){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 Q5($,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?j5(A):void 0,W=P$(b),w=Q5($,m),j=w==="meta-repo"?S5($):void 0;return{packageManager:n,workspaceRoot:A,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function k3($,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 r3($,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=`
|
|
5
7
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
6
8
|
|
|
7
9
|
SPECIFICATION:
|
|
@@ -30,7 +32,7 @@ Provide a structured validation report:
|
|
|
30
32
|
- Are there any missing edge cases?
|
|
31
33
|
|
|
32
34
|
Be thorough and precise. Use a critical but constructive tone.
|
|
33
|
-
`,
|
|
35
|
+
`,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.
|
|
34
36
|
|
|
35
37
|
Your code is:
|
|
36
38
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -73,10 +75,10 @@ Spec:
|
|
|
73
75
|
${$.specCode}
|
|
74
76
|
|
|
75
77
|
Code:
|
|
76
|
-
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],
|
|
77
|
-
`);for(let
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
78
|
+
${$.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(`
|
|
79
|
+
`);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(`
|
|
80
|
+
`);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(`
|
|
81
|
+
`);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 Z5}from"child_process";import{existsSync as iy}from"fs";import{mkdir as ly,readFile as X5,rm as Y5,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=Z5(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 X5(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
|
|
80
82
|
|
|
81
83
|
This workspace was prepared for Cursor AI code generation.
|
|
82
84
|
|
|
@@ -92,18 +94,18 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
92
94
|
4. Save the result as output.ts
|
|
93
95
|
|
|
94
96
|
Workspace path: ${b}
|
|
95
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Y$(
|
|
97
|
+
`),{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
|
|
96
98
|
|
|
97
99
|
**Task Type:** ${$.type}
|
|
98
100
|
**Generated:** ${new Date().toISOString()}
|
|
99
101
|
|
|
100
|
-
`,
|
|
102
|
+
`,A=`## Specification
|
|
101
103
|
|
|
102
104
|
\`\`\`typescript
|
|
103
105
|
${$.specCode}
|
|
104
106
|
\`\`\`
|
|
105
107
|
|
|
106
|
-
`,
|
|
108
|
+
`,n={generate:`## Task: Generate Implementation
|
|
107
109
|
|
|
108
110
|
### Requirements:
|
|
109
111
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -196,7 +198,7 @@ ${$.existingCode||""}
|
|
|
196
198
|
- Enhance error messages
|
|
197
199
|
|
|
198
200
|
### Output Format:
|
|
199
|
-
Refactored code that maintains functionality while improving quality.`};return b+
|
|
201
|
+
Refactored code that maintains functionality while improving quality.`};return b+A+(n[$.type]||n.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
200
202
|
|
|
201
203
|
## Specification
|
|
202
204
|
\`\`\`typescript
|
|
@@ -254,7 +256,7 @@ export function implementation() {
|
|
|
254
256
|
// Implementation goes here
|
|
255
257
|
throw new Error('Not implemented');
|
|
256
258
|
}
|
|
257
|
-
`}async cleanupWorkDir($){try{await
|
|
259
|
+
`}async cleanupWorkDir($){try{await Y5($,{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=`
|
|
258
260
|
Review this code implementation against its specification.
|
|
259
261
|
|
|
260
262
|
SPECIFICATION:
|
|
@@ -274,7 +276,7 @@ Provide a detailed validation report including:
|
|
|
274
276
|
4. Recommendations for improvement
|
|
275
277
|
|
|
276
278
|
Format as a structured report.
|
|
277
|
-
`,
|
|
279
|
+
`,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.
|
|
278
280
|
|
|
279
281
|
Generate production-quality code that is:
|
|
280
282
|
- Type-safe and well-typed
|
|
@@ -311,9 +313,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
311
313
|
${$.existingCode}
|
|
312
314
|
|
|
313
315
|
Spec:
|
|
314
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],
|
|
315
|
-
`);for(let
|
|
316
|
-
`);for(let
|
|
316
|
+
${$.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(`
|
|
317
|
+
`);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(`
|
|
318
|
+
`);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 q5 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.
|
|
317
319
|
|
|
318
320
|
Here is the contract spec:
|
|
319
321
|
|
|
@@ -332,7 +334,7 @@ Generate a complete handler implementation that:
|
|
|
332
334
|
|
|
333
335
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
334
336
|
|
|
335
|
-
Return only the TypeScript code for the handler function.`}function
|
|
337
|
+
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.
|
|
336
338
|
|
|
337
339
|
Here is the presentation spec:
|
|
338
340
|
|
|
@@ -351,7 +353,7 @@ Generate a complete React component that:
|
|
|
351
353
|
|
|
352
354
|
The component should follow Atomic Design principles and be reusable.
|
|
353
355
|
|
|
354
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
356
|
+
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.
|
|
355
357
|
|
|
356
358
|
Here is the form spec:
|
|
357
359
|
|
|
@@ -371,7 +373,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
371
373
|
|
|
372
374
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
373
375
|
|
|
374
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
376
|
+
Return only the TypeScript/TSX code for the form component.`}function $n($,b,A){return`You are a senior developer writing comprehensive tests.
|
|
375
377
|
|
|
376
378
|
Spec:
|
|
377
379
|
\`\`\`typescript
|
|
@@ -384,7 +386,7 @@ ${b}
|
|
|
384
386
|
\`\`\`
|
|
385
387
|
|
|
386
388
|
Generate complete test suite using Vitest that:
|
|
387
|
-
${
|
|
389
|
+
${A==="handler"?`
|
|
388
390
|
- Test all acceptance scenarios from the spec
|
|
389
391
|
- Test error cases defined in spec.io.errors
|
|
390
392
|
- Verify events are emitted correctly
|
|
@@ -398,7 +400,7 @@ ${n==="handler"?`
|
|
|
398
400
|
|
|
399
401
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
400
402
|
|
|
401
|
-
Return only the TypeScript test code.`}function
|
|
403
|
+
Return only the TypeScript test code.`}function bn(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
402
404
|
- Type-safe API design
|
|
403
405
|
- React and modern hooks
|
|
404
406
|
- Test-driven development
|
|
@@ -412,7 +414,7 @@ Generate production-ready code that is:
|
|
|
412
414
|
- Defensive and error-safe
|
|
413
415
|
- Easy to maintain and extend
|
|
414
416
|
|
|
415
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
417
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as H5}from"@contractspec/lib.ai-providers";function nn($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return H5(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=`
|
|
416
418
|
Review the following implementation against its specification.
|
|
417
419
|
|
|
418
420
|
Specification:
|
|
@@ -426,15 +428,15 @@ Provide a detailed validation report:
|
|
|
426
428
|
2. Are there any missing features?
|
|
427
429
|
3. Are there any bugs or issues?
|
|
428
430
|
4. Suggestions for improvement
|
|
429
|
-
`,
|
|
430
|
-
${$.specCode}`;case"test":return
|
|
431
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
431
|
+
`,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:
|
|
432
|
+
${$.specCode}`;case"test":return $n($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
433
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as G5}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=G5(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:
|
|
432
434
|
${$.specCode}
|
|
433
435
|
|
|
434
436
|
`;if($.existingCode)b+=`Existing Code:
|
|
435
437
|
${$.existingCode}
|
|
436
438
|
|
|
437
|
-
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class
|
|
439
|
+
`;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(`⚠️ Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!A.canHandle($))return console.log(k$.yellow(`⚠️ Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let n=q5(`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:()=>V5,buildPresentationSpecPrompt:()=>U5,buildOperationSpecPrompt:()=>O5,buildEventSpecPrompt:()=>J5,addExampleContext:()=>K5});function O5($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
438
440
|
|
|
439
441
|
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
440
442
|
|
|
@@ -452,7 +454,7 @@ Create a complete contract specification following these guidelines:
|
|
|
452
454
|
8. **Feature Flags**: Any flags that gate this operation
|
|
453
455
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
454
456
|
|
|
455
|
-
Respond with a structured spec.`}function
|
|
457
|
+
Respond with a structured spec.`}function J5($){return`You are a senior software architect creating an event specification.
|
|
456
458
|
|
|
457
459
|
User description: ${$}
|
|
458
460
|
|
|
@@ -466,7 +468,7 @@ Create a complete event specification following these guidelines:
|
|
|
466
468
|
|
|
467
469
|
Events represent things that have already happened and should use past tense.
|
|
468
470
|
|
|
469
|
-
Respond with a structured spec.`}function
|
|
471
|
+
Respond with a structured spec.`}function U5($,b){return`You are a senior software architect creating a presentation specification.
|
|
470
472
|
|
|
471
473
|
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
472
474
|
|
|
@@ -484,7 +486,7 @@ Create a complete presentation specification following these guidelines:
|
|
|
484
486
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
485
487
|
- Data structure description`}
|
|
486
488
|
|
|
487
|
-
Respond with a structured spec.`}function
|
|
489
|
+
Respond with a structured spec.`}function V5(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
488
490
|
|
|
489
491
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
490
492
|
|
|
@@ -494,7 +496,7 @@ Your specs are:
|
|
|
494
496
|
- Business-oriented (capturing the "why" not just "what")
|
|
495
497
|
- Designed for both humans and AI agents to understand
|
|
496
498
|
|
|
497
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
499
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function K5($,b){if(b.length===0)return $;return`${$}
|
|
498
500
|
|
|
499
501
|
Here are some good examples for reference:
|
|
500
502
|
|
|
@@ -502,47 +504,47 @@ ${b.join(`
|
|
|
502
504
|
|
|
503
505
|
`)}
|
|
504
506
|
|
|
505
|
-
Follow this structure and quality level.`}import{defineModuleBundle as
|
|
506
|
-
`)}function
|
|
507
|
+
Follow this structure and quality level.`}import{defineModuleBundle as _5}from"@contractspec/lib.surface-runtime/spec";var gH=_5({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:()=>x5,formatAsTextLines:()=>bW,formatAsText:()=>M5,formatAsSarif:()=>R5,formatAsJson:()=>z5});function z5($,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 L5={"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 R5($,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=L5[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:I5(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:C5(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 I5($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function C5($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function x5($){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?"✓":"✗",B=w.passed?"success":"error",S=E5(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=T5($.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:"─".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:"✅ All CI checks passed!",style:"success"});else A.push({text:"❌ CI checks failed",style:"error"});return A.push({text:"",style:"normal"}),A}function M5($,b={}){return bW($,b).map((n)=>" ".repeat(n.indent??0)+n.text).join(`
|
|
508
|
+
`)}function E5($){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"?"✗":$.severity==="warning"?"⚠":"○",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 T5($){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 D5}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as N5}from"@contractspec/lib.contracts-spec/operations/report";function F5(){let $=new D5;return N5($),$}var sH=F5();class v5{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 g5($){if(!$)return"—";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 P5{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)}
|
|
507
509
|
|
|
508
|
-
*(output truncated)*`},
|
|
509
|
-
`)},m=
|
|
510
|
+
*(output truncated)*`},n=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
511
|
+
`)},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??"—",S=g5(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(`
|
|
510
512
|
`)}
|
|
511
|
-
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>$5,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>Un,normalizeText:()=>wW,inferFamilyFromPath:()=>Z0,hasLocalShadcnRegistry:()=>Q0,getContractSpecAdoptionCatalog:()=>Jn,createAdoptionCatalogDocument:()=>w0,candidateTokens:()=>j0});function x($,b,n,A,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:n,packageKind:A,title:j.title??b,description:w,capabilityTags:y,preferredUseCases:W,avoidWhen:j.avoidWhen,platforms:j.platforms,replacementImportHints:j.replacementImportHints,resolutionPriority:m,runtimes:j.runtimes}}var nW=[x("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),x("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),x("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),x("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),x("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var AW=[x("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),x("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),x("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),x("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),x("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),x("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),x("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),x("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var mW=[x("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),x("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),x("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),x("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),x("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),x("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),x("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),x("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),x("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var yW=[x("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),x("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),x("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),x("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),x("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),x("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var WW=[x("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),x("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),x("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var DS=[...WW,...nW,...AW,...mW,...yW];function Jn(){return[...DS].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function w0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:Jn()}}import{DEFAULT_CONTRACTSRC as cS}from"@contractspec/lib.contracts-spec/workspace-config";function wW($){return $.toLowerCase().trim()}function e$($){return wW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function k$($){return[...new Set($.flatMap((b)=>e$(b)))]}function j0($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return k$(b)}function Un($,b){let n=new Set(b);return $.filter((A)=>n.has(A)).length}import{resolve as NS}from"node:path";import{ContractsrcSchema as FS,DEFAULT_CONTRACTSRC as B0}from"@contractspec/lib.contracts-spec/workspace-config";async function s$($,b={}){let n=NS(b.cwd??process.cwd()),A=b.workspaceRoot??I(n),m=b.packageRoot??c(n),y=b.config?BW(B0,b.config):await vS($,A,m);return{adoption:y.connect?.adoption??B0.connect.adoption,config:y,cwd:n,packageRoot:m,workspaceRoot:A}}async function vS($,b,n){let A=B0;if(b!==n)A=await jW($,A,$.join(b,".contractsrc.json"));return jW($,A,$.join(n,".contractsrc.json"))}async function jW($,b,n){if(!await $.exists(n))return b;try{let A=JSON.parse(await $.readFile(n)),m=FS.safeParse(A);if(!m.success)return b;return BW(b,m.data)}catch{return b}}function BW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var gS=["package.json","packages/*/package.json"];async function S0($,b){let[n,A]=await Promise.all([PS($,b),kS($,b)]);return{fileCandidates:A,packageCandidates:n}}async function Q0($,b){let n=$.join(b.workspaceRoot,"components.json");if(await $.exists(n))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function PS($,b){let n=await $.glob({patterns:gS,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),A=[];for(let m of n)try{let y=JSON.parse(await $.readFile($.join(b.workspaceRoot,m))),W=Z0(m);if(!W)continue;let w=y.name??$.dirname(m);A.push({id:`workspace.package.${w}`,source:"workspace",family:W,title:w,description:y.description??`Local reusable package at ${m}.`,packageKind:fS(m),packageRef:w,capabilityTags:k$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return A}async function kS($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((A)=>{let m=Z0(A);if(!m)return[];let y=A.split("/").pop()?.replace(/\.[^.]+$/,"")??A;return[{id:`workspace.file.${A}`,source:"workspace",family:m,title:y,description:`Local reusable source at ${A}.`,filePath:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:rS(m,A)}]})}function Z0($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function rS($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function fS($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Jb($,b){let n=await s$($.fs,b),A=aS(b),m=k$([A,b.symbol??"",...b.paths??[]]),y=await S0($.fs,n),W=await eS($,n),w=await Q0($.fs,n),j=hS(n,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...sS(b.family,b.platform,w)]),B=j[0]??null,S=j.length>1&&B!=null&&B.candidate.source===j[1].candidate.source&&Math.abs(B.score-j[1].score)<=40,Q=tS(n,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:A,reason:pS(B,S),selected:B,verdict:Q}}function hS($,b,n,A){return A.filter((m)=>m.family===n.family&&oS($,m.family)).filter((m)=>iS(m,n.platform)).map((m)=>dS(m,b,n.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function dS($,b,n){let A=j0($),m=k$(n??[]),y=[],W=Un(b,A)*25,w=Un(m,A)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:uS($.source)+($.resolutionPriority??0)+W+w}}function uS($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function oS($,b){return $.adoption.families?.[b]??!0}function iS($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function tS($,b,n,A){let m=$.adoption.thresholds??cS.connect.adoption.thresholds;if(n)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return lS(b.candidate,A)?"permit":m.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return m.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return m.newImplementation??"require_review";return m.newExternalDependency??"require_review"}function lS($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function pS($,b){if(b)return"Multiple similarly strong adoption candidates were found.";if(!$)return"No reusable workspace or ContractSpec candidate matched the request.";return`Selected ${$.candidate.source} candidate ${$.candidate.title}.`}function aS($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function eS($,b){let n=Jn(),A=b.adoption.catalog?.overrideManifestPath;if(!A||!await $.fs.exists($.fs.join(b.workspaceRoot,A)))return n;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,A)),y=JSON.parse(m);return[...n,...Array.isArray(y)?y:y.entries??[]]}catch{return n}}function sS($,b,n){if($==="ui"&&b==="web"&&n)return[$b("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[$b("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[$b("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[$b("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[$b("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[$b("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function $b($,b,n,A,m){return{id:$,source:"ecosystem",packageRef:n,family:b,packageKind:"primitive",title:A,description:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:m}}async function $5($,b={}){let n=await s$($.fs,b),A=w0(),m=$.fs.join(n.workspaceRoot,n.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(m,`${JSON.stringify(A,null,2)}
|
|
512
|
-
`),{catalog:
|
|
513
|
+
`}}var Zn={};f(Zn,{uniqueTokens:()=>r$,tokenize:()=>s$,syncAdoptionCatalog:()=>W8,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 k5=[...wW,...nW,...mW,...yW,...WW];function KA(){return[...k5].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function Wn($=new Date){return{version:1,generatedAt:$.toISOString(),entries:KA()}}import{DEFAULT_CONTRACTSRC as l5}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 r5}from"node:path";import{ContractsrcSchema as f5,DEFAULT_CONTRACTSRC as jn}from"@contractspec/lib.contracts-spec/workspace-config";async function $b($,b={}){let A=r5(b.cwd??process.cwd()),n=b.workspaceRoot??x(A),m=b.packageRoot??c(A),y=b.config?SW(jn,b.config):await c5($,n,m);return{adoption:y.connect?.adoption??jn.connect.adoption,config:y,cwd:A,packageRoot:m,workspaceRoot:n}}async function c5($,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=f5.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 h5=["package.json","packages/*/package.json"];async function Bn($,b){let[A,n]=await Promise.all([d5($,b),u5($,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 d5($,b){let A=await $.glob({patterns:h5,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:i5(m),packageRef:w,capabilityTags:r$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return n}async function u5($,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:o5(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 o5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function i5($){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=n8(b),m=r$([n,b.symbol??"",...b.paths??[]]),y=await Bn($.fs,A),W=await m8($,A),w=await Sn($.fs,A),j=t5(A,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...y8(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=$8(A,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:n,reason:A8(B,S),selected:B,verdict:Q}}function t5($,b,A,n){return n.filter((m)=>m.family===A.family&&e5($,m.family)).filter((m)=>s5(m,A.platform)).map((m)=>p5(m,b,A.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function p5($,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:a5($.source)+($.resolutionPriority??0)+W+w}}function a5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function e5($,b){return $.adoption.families?.[b]??!0}function s5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function $8($,b,A,n){let m=$.adoption.thresholds??l5.connect.adoption.thresholds;if(A)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return b8(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 b8($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function A8($,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 n8($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function m8($,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 y8($,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 W8($,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)}
|
|
514
|
+
`),{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":"✏️";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(`- ⚠️ ${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(`
|
|
513
515
|
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
514
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let
|
|
515
|
-
`)}}generateConfig($){let b=$.meta,
|
|
516
|
-
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var
|
|
517
|
-
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,
|
|
518
|
-
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let
|
|
516
|
+
`)}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 j8}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)=>`⚠️ ${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:j8["cursor-cli"],taskPrompt:b.join(`
|
|
517
|
+
`)}}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(`
|
|
518
|
+
`)}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 B8}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:B8["generic-mcp"],taskPrompt:b.join(`
|
|
519
|
+
`)}}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(`
|
|
520
|
+
`)}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 S8,operationSpecToFullMarkdown as Q8}from"@contractspec/lib.contracts-spec/llm";var Z8={defaultAgent:"generic-mcp",verbose:!1};class MA{config;constructor($={}){this.config={...Z8,...$}}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=Q8($);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 S8($,{taskType:A,existingCode:n})}listAgentTypes(){return Yn()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function X8($){return new MA($)}var Y8=new MA;import{detectAuthoringTarget as wS,generateComponentTemplate as jS,generateHandlerTemplate as BS,generateTestTemplate as SS,getAuthoringTargetDefinition as QS,inferSpecTypeFromFilePath as ZS,scanSpecSource as XS}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';
|
|
519
521
|
|
|
520
522
|
export const ${nb($.key)}Capability = defineCapability({
|
|
521
523
|
meta: {
|
|
522
524
|
key: '${$.key}',
|
|
523
525
|
version: '${$.version}',
|
|
524
526
|
kind: '${$.kind??"api"}',
|
|
525
|
-
title: '${k(
|
|
527
|
+
title: '${k(Ab($))}',
|
|
526
528
|
description: '${k($.description)}',
|
|
527
|
-
domain: '${k(
|
|
528
|
-
owners: [${
|
|
529
|
-
tags: [${
|
|
529
|
+
domain: '${k(f$($))}',
|
|
530
|
+
owners: [${w$($.owners)}],
|
|
531
|
+
tags: [${w$($.tags)}],
|
|
530
532
|
stability: '${$.stability}',
|
|
531
533
|
},
|
|
532
534
|
provides: [],
|
|
533
535
|
requires: [],
|
|
534
536
|
});
|
|
535
|
-
`}function
|
|
537
|
+
`}function XW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
536
538
|
|
|
537
539
|
export const ${nb($.key)}Policy = definePolicy({
|
|
538
540
|
meta: {
|
|
539
541
|
key: '${$.key}',
|
|
540
542
|
version: '${$.version}',
|
|
541
|
-
title: '${k(
|
|
543
|
+
title: '${k(Ab($))}',
|
|
542
544
|
description: '${k($.description)}',
|
|
543
|
-
domain: '${k(
|
|
544
|
-
owners: [${
|
|
545
|
-
tags: [${
|
|
545
|
+
domain: '${k(f$($))}',
|
|
546
|
+
owners: [${w$($.owners)}],
|
|
547
|
+
tags: [${w$($.tags)}],
|
|
546
548
|
stability: '${$.stability}',
|
|
547
549
|
scope: '${$.scope??"feature"}',
|
|
548
550
|
},
|
|
@@ -550,27 +552,27 @@ export const ${nb($.key)}Policy = definePolicy({
|
|
|
550
552
|
{
|
|
551
553
|
effect: 'allow',
|
|
552
554
|
actions: ['read'],
|
|
553
|
-
resource: { type: '${k(
|
|
555
|
+
resource: { type: '${k(f$($))}' },
|
|
554
556
|
reason: 'TODO: replace with real access rules',
|
|
555
557
|
},
|
|
556
558
|
],
|
|
557
559
|
});
|
|
558
|
-
`}function
|
|
560
|
+
`}function YW($){let b=$.targetVersion??"1.0.0",A=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
559
561
|
|
|
560
562
|
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
561
563
|
meta: {
|
|
562
564
|
key: '${$.key}',
|
|
563
565
|
version: '${$.version}',
|
|
564
|
-
title: '${k(
|
|
566
|
+
title: '${k(Ab($))}',
|
|
565
567
|
description: '${k($.description)}',
|
|
566
|
-
domain: '${k(
|
|
567
|
-
owners: [${
|
|
568
|
-
tags: [${
|
|
568
|
+
domain: '${k(f$($))}',
|
|
569
|
+
owners: [${w$($.owners)}],
|
|
570
|
+
tags: [${w$($.tags)}],
|
|
569
571
|
stability: '${$.stability}',
|
|
570
572
|
},
|
|
571
573
|
target: {
|
|
572
574
|
type: '${$.targetType}',
|
|
573
|
-
${$.targetType}: ${
|
|
575
|
+
${$.targetType}: ${A},
|
|
574
576
|
},
|
|
575
577
|
scenarios: [
|
|
576
578
|
{
|
|
@@ -580,23 +582,23 @@ export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
|
580
582
|
},
|
|
581
583
|
],
|
|
582
584
|
});
|
|
583
|
-
`}function
|
|
585
|
+
`}function HW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
584
586
|
|
|
585
587
|
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
586
588
|
meta: {
|
|
587
589
|
key: '${$.key}',
|
|
588
590
|
version: '${$.version}',
|
|
589
|
-
domain: '${k(
|
|
591
|
+
domain: '${k(f$($))}',
|
|
590
592
|
description: '${k($.description)}',
|
|
591
|
-
owners: [${
|
|
592
|
-
tags: [${
|
|
593
|
+
owners: [${w$($.owners)}],
|
|
594
|
+
tags: [${w$($.tags)}],
|
|
593
595
|
stability: '${$.stability}',
|
|
594
596
|
},
|
|
595
597
|
locale: '${$.locale}',
|
|
596
598
|
fallback: '${$.fallback??$.locale}',
|
|
597
599
|
messages: {
|
|
598
600
|
'${$.key}.title': {
|
|
599
|
-
value: '${k(
|
|
601
|
+
value: '${k(Ab($))}',
|
|
600
602
|
description: 'TODO: replace with a real localized message',
|
|
601
603
|
},
|
|
602
604
|
},
|
|
@@ -607,29 +609,29 @@ export const ${nb($.key)}Job = defineJob({
|
|
|
607
609
|
meta: {
|
|
608
610
|
key: '${$.key}',
|
|
609
611
|
version: '${$.version}',
|
|
610
|
-
title: '${k(
|
|
612
|
+
title: '${k(Ab($))}',
|
|
611
613
|
description: '${k($.description)}',
|
|
612
|
-
domain: '${k(
|
|
613
|
-
owners: [${
|
|
614
|
-
tags: [${
|
|
614
|
+
domain: '${k(f$($))}',
|
|
615
|
+
owners: [${w$($.owners)}],
|
|
616
|
+
tags: [${w$($.tags)}],
|
|
615
617
|
stability: '${$.stability}',
|
|
616
618
|
},
|
|
617
619
|
payload: { schema: {} },
|
|
618
620
|
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
619
621
|
});
|
|
620
|
-
`}function
|
|
622
|
+
`}function qW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
621
623
|
|
|
622
624
|
export const ${nb($.key)}Visualization = defineVisualization({
|
|
623
625
|
meta: {
|
|
624
626
|
key: '${$.key}',
|
|
625
627
|
version: '${$.version}',
|
|
626
|
-
title: '${k(
|
|
628
|
+
title: '${k(Ab($))}',
|
|
627
629
|
description: '${k($.description)}',
|
|
628
630
|
goal: 'TODO: describe the decision this visualization supports',
|
|
629
631
|
context: 'TODO: describe where this visualization appears',
|
|
630
|
-
domain: '${k(
|
|
631
|
-
owners: [${
|
|
632
|
-
tags: [${
|
|
632
|
+
domain: '${k(f$($))}',
|
|
633
|
+
owners: [${w$($.owners)}],
|
|
634
|
+
tags: [${w$($.tags)}],
|
|
633
635
|
stability: '${$.stability}',
|
|
634
636
|
},
|
|
635
637
|
source: {
|
|
@@ -645,19 +647,19 @@ export const ${nb($.key)}Visualization = defineVisualization({
|
|
|
645
647
|
measure: 'value',
|
|
646
648
|
},
|
|
647
649
|
});
|
|
648
|
-
`}function
|
|
650
|
+
`}function Ab($){return $.title??H8($.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 H8($){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.${q8($.key.split(".").at(-1)??$.key)}`,A=`${mb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
649
651
|
|
|
650
|
-
const ${
|
|
652
|
+
const ${A} = defineExample({
|
|
651
653
|
meta: {
|
|
652
654
|
key: '${$.key}',
|
|
653
655
|
version: '${$.version}',
|
|
654
|
-
title: '${
|
|
655
|
-
description: '${
|
|
656
|
+
title: '${h(_b($))}',
|
|
657
|
+
description: '${h($.description)}',
|
|
656
658
|
kind: 'template',
|
|
657
659
|
visibility: 'experimental',
|
|
658
660
|
stability: '${$.stability}',
|
|
659
|
-
owners: [${
|
|
660
|
-
tags: [${
|
|
661
|
+
owners: [${s($.owners)}],
|
|
662
|
+
tags: [${s($.tags)}],
|
|
661
663
|
},
|
|
662
664
|
surfaces: {
|
|
663
665
|
templates: true,
|
|
@@ -670,51 +672,51 @@ const ${n} = defineExample({
|
|
|
670
672
|
},
|
|
671
673
|
});
|
|
672
674
|
|
|
673
|
-
export default ${
|
|
674
|
-
export { ${
|
|
675
|
-
`}function
|
|
675
|
+
export default ${A};
|
|
676
|
+
export { ${A} };
|
|
677
|
+
`}function OW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
676
678
|
|
|
677
|
-
export const ${
|
|
679
|
+
export const ${mb($.key)}Agent = defineAgent({
|
|
678
680
|
meta: {
|
|
679
681
|
key: '${$.key}',
|
|
680
682
|
version: '${$.version}',
|
|
681
|
-
description: '${
|
|
682
|
-
owners: [${
|
|
683
|
-
tags: [${
|
|
683
|
+
description: '${h($.description)}',
|
|
684
|
+
owners: [${s($.owners)}],
|
|
685
|
+
tags: [${s($.tags)}],
|
|
684
686
|
stability: '${$.stability}',
|
|
685
687
|
},
|
|
686
|
-
instructions: '${
|
|
688
|
+
instructions: '${h($.instructions)}',
|
|
687
689
|
tools: [{ name: 'todo' }],
|
|
688
690
|
});
|
|
689
|
-
`}function
|
|
691
|
+
`}function JW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
690
692
|
|
|
691
|
-
export const ${
|
|
693
|
+
export const ${mb($.key)}ProductIntent = defineProductIntentSpec({
|
|
692
694
|
id: '${$.id??`${$.key}-run`}',
|
|
693
695
|
meta: {
|
|
694
696
|
key: '${$.key}',
|
|
695
697
|
version: '${$.version}',
|
|
696
|
-
title: '${
|
|
697
|
-
description: '${
|
|
698
|
+
title: '${h(_b($))}',
|
|
699
|
+
description: '${h($.description)}',
|
|
698
700
|
goal: 'TODO: capture the desired product outcome',
|
|
699
701
|
context: 'TODO: capture the decision context',
|
|
700
702
|
stability: '${$.stability}',
|
|
701
|
-
owners: [${
|
|
702
|
-
tags: [${
|
|
703
|
+
owners: [${s($.owners)}],
|
|
704
|
+
tags: [${s($.tags)}],
|
|
703
705
|
},
|
|
704
|
-
question: '${
|
|
706
|
+
question: '${h($.question)}',
|
|
705
707
|
insights: { insights: [] },
|
|
706
708
|
});
|
|
707
|
-
`}function
|
|
709
|
+
`}function UW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
708
710
|
|
|
709
|
-
export const ${
|
|
711
|
+
export const ${mb($.key)}HarnessScenario = defineHarnessScenario({
|
|
710
712
|
meta: {
|
|
711
713
|
key: '${$.key}',
|
|
712
714
|
version: '${$.version}',
|
|
713
|
-
title: '${
|
|
714
|
-
description: '${
|
|
715
|
-
domain: '${
|
|
716
|
-
owners: [${
|
|
717
|
-
tags: [${
|
|
715
|
+
title: '${h(_b($))}',
|
|
716
|
+
description: '${h($.description)}',
|
|
717
|
+
domain: '${h(Gn($))}',
|
|
718
|
+
owners: [${s($.owners)}],
|
|
719
|
+
tags: [${s($.tags)}],
|
|
718
720
|
stability: '${$.stability}',
|
|
719
721
|
},
|
|
720
722
|
target: {
|
|
@@ -739,17 +741,17 @@ export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
|
739
741
|
},
|
|
740
742
|
],
|
|
741
743
|
});
|
|
742
|
-
`}function
|
|
744
|
+
`}function VW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
743
745
|
|
|
744
|
-
export const ${
|
|
746
|
+
export const ${mb($.key)}HarnessSuite = defineHarnessSuite({
|
|
745
747
|
meta: {
|
|
746
748
|
key: '${$.key}',
|
|
747
749
|
version: '${$.version}',
|
|
748
|
-
title: '${
|
|
749
|
-
description: '${
|
|
750
|
-
domain: '${
|
|
751
|
-
owners: [${
|
|
752
|
-
tags: [${
|
|
750
|
+
title: '${h(_b($))}',
|
|
751
|
+
description: '${h($.description)}',
|
|
752
|
+
domain: '${h(Gn($))}',
|
|
753
|
+
owners: [${s($.owners)}],
|
|
754
|
+
tags: [${s($.tags)}],
|
|
753
755
|
stability: '${$.stability}',
|
|
754
756
|
},
|
|
755
757
|
scenarios: [
|
|
@@ -762,99 +764,129 @@ export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
|
762
764
|
weight: 1,
|
|
763
765
|
},
|
|
764
766
|
],
|
|
765
|
-
summary: '${
|
|
766
|
-
tags: [${
|
|
767
|
+
summary: '${h($.description)}',
|
|
768
|
+
tags: [${s($.tags)}],
|
|
767
769
|
});
|
|
768
|
-
`}function
|
|
770
|
+
`}function KW($){let b=$.currentRelease??$.version;return`import { definePwaAppManifest } from '@contractspec/lib.contracts-spec/pwa';
|
|
771
|
+
|
|
772
|
+
export const ${mb($.key)}PwaApp = definePwaAppManifest({
|
|
773
|
+
meta: {
|
|
774
|
+
key: '${$.key}',
|
|
775
|
+
version: '${$.version}',
|
|
776
|
+
appId: '${$.appId??$.key}',
|
|
777
|
+
title: '${h(_b($))}',
|
|
778
|
+
description: '${h($.description)}',
|
|
779
|
+
domain: '${h(Gn($))}',
|
|
780
|
+
stability: '${$.stability}',
|
|
781
|
+
owners: [${s($.owners)}],
|
|
782
|
+
tags: [${s($.tags)}],
|
|
783
|
+
},
|
|
784
|
+
currentRelease: '${b}',
|
|
785
|
+
defaultUpdatePolicy: {
|
|
786
|
+
mode: 'optional',
|
|
787
|
+
minSupportedVersion: '${b}',
|
|
788
|
+
},
|
|
789
|
+
releases: [
|
|
790
|
+
{
|
|
791
|
+
version: '${b}',
|
|
792
|
+
releasedAt: new Date().toISOString(),
|
|
793
|
+
notes: 'Initial release manifest.',
|
|
794
|
+
},
|
|
795
|
+
],
|
|
796
|
+
offline: {
|
|
797
|
+
supported: true,
|
|
798
|
+
},
|
|
799
|
+
});
|
|
800
|
+
`}function _b($){return $.title??G8($.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 G8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function q8($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=R8($.key.split(".").pop()??"App")+"AppConfig",A=O8($),n=J8($),m=_W("dataViews",$.dataViews),y=_W("workflows",$.workflows),W=U8($),w=V8($),j=K8($),B=_8($),S=z8($),Q=L8($),Z=$.notes?` notes: '${D($.notes)}',
|
|
769
801
|
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
770
802
|
|
|
771
803
|
export const ${b} = defineAppConfig({
|
|
772
804
|
meta: {
|
|
773
|
-
key: '${
|
|
805
|
+
key: '${D($.key)}',
|
|
774
806
|
version: '${$.version}',
|
|
775
|
-
title: '${
|
|
776
|
-
description: '${
|
|
777
|
-
domain: '${
|
|
778
|
-
owners: [${$.owners.map((X)=>`'${
|
|
779
|
-
tags: [${$.tags.map((X)=>`'${
|
|
807
|
+
title: '${D($.title)}',
|
|
808
|
+
description: '${D($.description)}',
|
|
809
|
+
domain: '${D($.domain)}',
|
|
810
|
+
owners: [${$.owners.map((X)=>`'${D(X)}'`).join(", ")}],
|
|
811
|
+
tags: [${$.tags.map((X)=>`'${D(X)}'`).join(", ")}],
|
|
780
812
|
stability: '${$.stability}',
|
|
781
|
-
appId: '${
|
|
813
|
+
appId: '${D($.appId)}',
|
|
782
814
|
},
|
|
783
|
-
${
|
|
784
|
-
`}function
|
|
785
|
-
`:"",
|
|
815
|
+
${A}${n}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
816
|
+
`}function O8($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((n)=>zW(n)).join(", ")}],
|
|
817
|
+
`:"",A=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((n)=>zW(n)).join(", ")}],
|
|
786
818
|
`:"";return` capabilities: {
|
|
787
|
-
${b}${
|
|
788
|
-
`}function
|
|
789
|
-
`:"",
|
|
819
|
+
${b}${A} },
|
|
820
|
+
`}function J8($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((n)=>`{ key: '${D(n)}' }`).join(", ")}],
|
|
821
|
+
`:"",A=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((n)=>`{ key: '${D(n)}' }`).join(", ")}],
|
|
790
822
|
`:"";return` features: {
|
|
791
|
-
${b}${
|
|
792
|
-
`}function
|
|
793
|
-
key: '${
|
|
794
|
-
version: '${
|
|
823
|
+
${b}${A} },
|
|
824
|
+
`}function _W($,b){if(b.length===0)return"";let A=b.map((n)=>` ${n.slot}: {
|
|
825
|
+
key: '${D(n.key)}'${n.version?`,
|
|
826
|
+
version: '${n.version}'`:""}
|
|
795
827
|
}`).join(`,
|
|
796
828
|
`);return` ${$}: {
|
|
797
|
-
${
|
|
829
|
+
${A}
|
|
798
830
|
},
|
|
799
|
-
`}function
|
|
800
|
-
${$.policyRefs.map((
|
|
801
|
-
key: '${
|
|
802
|
-
version: '${
|
|
831
|
+
`}function U8($){if($.policyRefs.length===0)return"";return` policies: [
|
|
832
|
+
${$.policyRefs.map((A)=>` {
|
|
833
|
+
key: '${D(A.key)}'${A.version?`,
|
|
834
|
+
version: '${A.version}'`:""}
|
|
803
835
|
}`).join(`,
|
|
804
836
|
`)}
|
|
805
837
|
],
|
|
806
|
-
`}function
|
|
807
|
-
`,
|
|
838
|
+
`}function V8($){if(!$.theme)return"";let b=` primary: { key: '${D($.theme.key)}', version: '${$.theme.version}' },
|
|
839
|
+
`,A=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((n)=>`{ key: '${D(n.key)}', version: '${n.version}' }`).join(", ")}],
|
|
808
840
|
`:"";return` theme: {
|
|
809
|
-
${b}${
|
|
810
|
-
`}function
|
|
841
|
+
${b}${A} },
|
|
842
|
+
`}function K8($){if(!$.telemetry)return"";return` telemetry: {
|
|
811
843
|
spec: {
|
|
812
|
-
key: '${
|
|
844
|
+
key: '${D($.telemetry.key)}'${$.telemetry.version?`,
|
|
813
845
|
version: '${$.telemetry.version}'`:""}
|
|
814
846
|
},
|
|
815
847
|
},
|
|
816
|
-
`}function
|
|
817
|
-
`:"",
|
|
848
|
+
`}function _8($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((n)=>LW(n)).join(", ")}],
|
|
849
|
+
`:"",A=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((n)=>LW(n)).join(", ")}],
|
|
818
850
|
`:"";return` experiments: {
|
|
819
|
-
${b}${
|
|
820
|
-
`}function
|
|
821
|
-
${$.featureFlags.map((
|
|
822
|
-
key: '${
|
|
823
|
-
enabled: ${
|
|
824
|
-
${
|
|
825
|
-
${
|
|
851
|
+
${b}${A} },
|
|
852
|
+
`}function z8($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
853
|
+
${$.featureFlags.map((A)=>` {
|
|
854
|
+
key: '${D(A.key)}',
|
|
855
|
+
enabled: ${A.enabled},
|
|
856
|
+
${A.variant?`variant: '${D(A.variant)}',`:""}
|
|
857
|
+
${A.description?`description: '${D(A.description)}',`:""}
|
|
826
858
|
}`).join(`,
|
|
827
859
|
`)}
|
|
828
860
|
],
|
|
829
|
-
`}function
|
|
830
|
-
${$.routes.map((
|
|
861
|
+
`}function L8($){if($.routes.length===0)return"";return` routes: [
|
|
862
|
+
${$.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(`,
|
|
831
863
|
`)}
|
|
832
864
|
],
|
|
833
|
-
`}function
|
|
865
|
+
`}function zW($){return`{ key: '${D($)}' }`}function LW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${D($.key)}'${b} }`}function R8($){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=I8($.name.split(".").pop()??"DataView")+"DataView",A=$.fields.map((y)=>` {
|
|
834
866
|
key: '${y.key}',
|
|
835
|
-
label: '${
|
|
867
|
+
label: '${zb(y.label)}',
|
|
836
868
|
dataPath: '${y.dataPath}',
|
|
837
|
-
${y.format?`format:
|
|
869
|
+
${y.format?`format: ${C8(y.format)},`:""}
|
|
838
870
|
${y.sortable?"sortable: true,":""}
|
|
839
871
|
${y.filterable?"filterable: true,":""}
|
|
840
872
|
}`).join(`,
|
|
841
|
-
`),
|
|
873
|
+
`),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';
|
|
842
874
|
|
|
843
875
|
export const ${b}: DataViewSpec = {
|
|
844
876
|
meta: {
|
|
845
877
|
key: '${$.name}',
|
|
846
878
|
version: ${$.version},
|
|
847
879
|
entity: '${$.entity}',
|
|
848
|
-
title: '${
|
|
849
|
-
description: '${
|
|
850
|
-
domain: '${
|
|
880
|
+
title: '${zb($.title)}',
|
|
881
|
+
description: '${zb($.description||"Describe the purpose of this data view.")}',
|
|
882
|
+
domain: '${zb($.domain||$.entity)}',
|
|
851
883
|
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
852
884
|
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
853
885
|
stability: '${$.stability}',
|
|
854
886
|
},
|
|
855
887
|
source: {
|
|
856
888
|
primary: {
|
|
857
|
-
|
|
889
|
+
key: '${$.primaryOperation.name}',
|
|
858
890
|
version: ${$.primaryOperation.version},
|
|
859
891
|
},
|
|
860
892
|
${m}
|
|
@@ -865,10 +897,10 @@ export const ${b}: DataViewSpec = {
|
|
|
865
897
|
view: {
|
|
866
898
|
kind: '${$.kind}',
|
|
867
899
|
fields: [
|
|
868
|
-
${
|
|
900
|
+
${A}
|
|
869
901
|
],
|
|
870
902
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
871
|
-
${
|
|
903
|
+
${n}
|
|
872
904
|
filters: [
|
|
873
905
|
// Example filter:
|
|
874
906
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -879,17 +911,17 @@ ${n}
|
|
|
879
911
|
],
|
|
880
912
|
},
|
|
881
913
|
states: {
|
|
882
|
-
// empty: {
|
|
883
|
-
// error: {
|
|
914
|
+
// empty: { key: 'app.data.empty', version: '1.0.0' },
|
|
915
|
+
// error: { key: 'app.data.error', version: '1.0.0' },
|
|
884
916
|
},
|
|
885
917
|
};
|
|
886
|
-
`}function
|
|
918
|
+
`}function I8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function zb($){return $.replace(/'/g,"\\'")}function C8($){if(typeof $==="string")return`'${zb($)}'`;return JSON.stringify($)}function TA({exportName:$,specImportPath:b,rendererName:A,viewKind:n}){return`'use client';
|
|
887
919
|
|
|
888
920
|
import * as React from 'react';
|
|
889
921
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
890
922
|
import { ${$} } from '${b}';
|
|
891
923
|
|
|
892
|
-
export interface ${
|
|
924
|
+
export interface ${A}Props {
|
|
893
925
|
items?: Record<string, unknown>[];
|
|
894
926
|
item?: Record<string, unknown> | null;
|
|
895
927
|
className?: string;
|
|
@@ -899,17 +931,17 @@ export interface ${n}Props {
|
|
|
899
931
|
}
|
|
900
932
|
|
|
901
933
|
/**
|
|
902
|
-
* Auto-generated renderer for the "${
|
|
934
|
+
* Auto-generated renderer for the "${n}" data view.
|
|
903
935
|
* Customize as needed for app-specific behaviour.
|
|
904
936
|
*/
|
|
905
|
-
export function ${
|
|
937
|
+
export function ${A}({
|
|
906
938
|
items = [],
|
|
907
939
|
item = null,
|
|
908
940
|
className,
|
|
909
941
|
renderActions,
|
|
910
942
|
onSelect,
|
|
911
943
|
onRowClick,
|
|
912
|
-
}: ${
|
|
944
|
+
}: ${A}Props) {
|
|
913
945
|
return (
|
|
914
946
|
<DataViewRenderer
|
|
915
947
|
spec={${$}}
|
|
@@ -922,7 +954,7 @@ export function ${n}({
|
|
|
922
954
|
/>
|
|
923
955
|
);
|
|
924
956
|
}
|
|
925
|
-
`}function CW($){let{name:b,version:
|
|
957
|
+
`}function CW($){let{name:b,version:A,description:n,stability:m,owners:y,tags:W,piiFields:w}=$,j=x8(b.replace(/\./g,"_"))+"V"+A,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
926
958
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
927
959
|
|
|
928
960
|
// TODO: Define event payload schema
|
|
@@ -938,33 +970,33 @@ export const ${B} = new SchemaModel({
|
|
|
938
970
|
export const ${j} = defineEvent({
|
|
939
971
|
name: '${b}',
|
|
940
972
|
name: '${b}',
|
|
941
|
-
version: '${
|
|
942
|
-
description: '${
|
|
943
|
-
description: '${
|
|
973
|
+
version: '${A}',
|
|
974
|
+
description: '${n}',
|
|
975
|
+
description: '${n}',
|
|
944
976
|
stability: '${m}',
|
|
945
977
|
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
946
978
|
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
947
979
|
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
948
980
|
payload: ${B},
|
|
949
981
|
});
|
|
950
|
-
`}function
|
|
982
|
+
`}function x8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function xW($){let b=E8($.name.split(".").pop()??"Experiment")+"Experiment",A=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
951
983
|
${y.overrides.map((w)=>` {
|
|
952
984
|
type: '${w.type}',
|
|
953
|
-
target: '${
|
|
985
|
+
target: '${d(w.target)}',
|
|
954
986
|
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
955
987
|
}`).join(`,
|
|
956
988
|
`)}
|
|
957
989
|
],`:"";return` {
|
|
958
|
-
id: '${
|
|
959
|
-
name: '${
|
|
960
|
-
${y.description?`description: '${
|
|
990
|
+
id: '${d(y.id)}',
|
|
991
|
+
name: '${d(y.name)}',
|
|
992
|
+
${y.description?`description: '${d(y.description)}',`:""}
|
|
961
993
|
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
962
994
|
${W}
|
|
963
995
|
}`}).join(`,
|
|
964
|
-
`),
|
|
996
|
+
`),n=M8($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
965
997
|
${$.successMetrics.map((y)=>` {
|
|
966
|
-
name: '${
|
|
967
|
-
telemetryEvent: { name: '${
|
|
998
|
+
name: '${d(y.name)}',
|
|
999
|
+
telemetryEvent: { name: '${d(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
968
1000
|
aggregation: '${y.aggregation}',
|
|
969
1001
|
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
970
1002
|
}`).join(`,
|
|
@@ -973,42 +1005,42 @@ ${$.successMetrics.map((y)=>` {
|
|
|
973
1005
|
|
|
974
1006
|
export const ${b}: ExperimentSpec = {
|
|
975
1007
|
meta: {
|
|
976
|
-
key: '${
|
|
1008
|
+
key: '${d($.name)}',
|
|
977
1009
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
978
|
-
title: '${
|
|
979
|
-
description: '${
|
|
980
|
-
domain: '${
|
|
981
|
-
owners: [${$.owners.map((y)=>`'${
|
|
982
|
-
tags: [${$.tags.map((y)=>`'${
|
|
1010
|
+
title: '${d($.name)} experiment',
|
|
1011
|
+
description: '${d($.description||"Describe the experiment goal.")}',
|
|
1012
|
+
domain: '${d($.domain)}',
|
|
1013
|
+
owners: [${$.owners.map((y)=>`'${d(y)}'`).join(", ")}],
|
|
1014
|
+
tags: [${$.tags.map((y)=>`'${d(y)}'`).join(", ")}],
|
|
983
1015
|
stability: '${$.stability}',
|
|
984
1016
|
},
|
|
985
|
-
controlVariant: '${
|
|
1017
|
+
controlVariant: '${d($.controlVariant)}',
|
|
986
1018
|
variants: [
|
|
987
|
-
${
|
|
1019
|
+
${A}
|
|
988
1020
|
],
|
|
989
|
-
allocation: ${
|
|
1021
|
+
allocation: ${n},
|
|
990
1022
|
${m}
|
|
991
1023
|
};
|
|
992
|
-
`}function
|
|
1024
|
+
`}function M8($){switch($.type){case"random":return`{
|
|
993
1025
|
type: 'random',
|
|
994
|
-
${$.salt?`salt: '${
|
|
1026
|
+
${$.salt?`salt: '${d($.salt)}',`:""}
|
|
995
1027
|
}`;case"sticky":return`{
|
|
996
1028
|
type: 'sticky',
|
|
997
1029
|
attribute: '${$.attribute}',
|
|
998
|
-
${$.salt?`salt: '${
|
|
1030
|
+
${$.salt?`salt: '${d($.salt)}',`:""}
|
|
999
1031
|
}`;case"targeted":return`{
|
|
1000
1032
|
type: 'targeted',
|
|
1001
1033
|
rules: [
|
|
1002
1034
|
${$.rules.map((b)=>` {
|
|
1003
|
-
variantId: '${
|
|
1035
|
+
variantId: '${d(b.variantId)}',
|
|
1004
1036
|
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1005
|
-
${b.policy?`policy: { name: '${
|
|
1006
|
-
${b.expression?`expression: '${
|
|
1037
|
+
${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}`:""} },`:""}
|
|
1038
|
+
${b.expression?`expression: '${d(b.expression)}',`:""}
|
|
1007
1039
|
}`).join(`,
|
|
1008
1040
|
`)}
|
|
1009
1041
|
],
|
|
1010
1042
|
fallback: '${$.fallback??"control"}',
|
|
1011
|
-
}`;default:return
|
|
1043
|
+
}`;default:return T8($)}}function E8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function d($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function T8($){throw Error(`Unsupported allocation type ${$}`)}function D8($){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(`
|
|
1012
1044
|
`);return`/**
|
|
1013
1045
|
* ${$.title} Feature
|
|
1014
1046
|
*
|
|
@@ -1017,15 +1049,15 @@ ${$.rules.map((b)=>` {
|
|
|
1017
1049
|
|
|
1018
1050
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
1019
1051
|
|
|
1020
|
-
export const ${
|
|
1052
|
+
export const ${D8($.key)}Feature = defineFeature({
|
|
1021
1053
|
meta: {
|
|
1022
1054
|
key: '${$.key}',
|
|
1023
1055
|
version: '${$.version}',
|
|
1024
1056
|
title: '${$.title}',
|
|
1025
1057
|
description: '${$.description||"TODO: Add description"}',
|
|
1026
1058
|
domain: '${$.domain}',
|
|
1027
|
-
owners: [${$.owners.map((
|
|
1028
|
-
tags: [${$.tags.map((
|
|
1059
|
+
owners: [${$.owners.map((A)=>`'${A}'`).join(", ")}],
|
|
1060
|
+
tags: [${$.tags.map((A)=>`'${A}'`).join(", ")}],
|
|
1029
1061
|
stability: '${$.stability||"beta"}',
|
|
1030
1062
|
},
|
|
1031
1063
|
|
|
@@ -1045,7 +1077,7 @@ ${b($.presentations)||" // Add presentations here"}
|
|
|
1045
1077
|
${b($.experiments)||" // Add experiments here"}
|
|
1046
1078
|
],
|
|
1047
1079
|
});
|
|
1048
|
-
`}function
|
|
1080
|
+
`}function N8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function EW($){let b=N8($.key),A=`${b}FormModel`,n=`${b}Form`;return`/**
|
|
1049
1081
|
* ${$.title} Form
|
|
1050
1082
|
*
|
|
1051
1083
|
* Auto-generated form spec.
|
|
@@ -1054,8 +1086,8 @@ ${b($.experiments)||" // Add experiments here"}
|
|
|
1054
1086
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
1055
1087
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
1056
1088
|
|
|
1057
|
-
const ${
|
|
1058
|
-
name: '${
|
|
1089
|
+
const ${A} = defineSchemaModel({
|
|
1090
|
+
name: '${A}',
|
|
1059
1091
|
description: '${$.description||"TODO: Add form model description"}',
|
|
1060
1092
|
fields: {
|
|
1061
1093
|
${$.primaryFieldKey}: {
|
|
@@ -1065,7 +1097,7 @@ const ${n} = defineSchemaModel({
|
|
|
1065
1097
|
},
|
|
1066
1098
|
});
|
|
1067
1099
|
|
|
1068
|
-
export const ${
|
|
1100
|
+
export const ${n} = defineFormSpec({
|
|
1069
1101
|
meta: {
|
|
1070
1102
|
key: '${$.key}',
|
|
1071
1103
|
version: '${$.version}',
|
|
@@ -1076,7 +1108,7 @@ export const ${A} = defineFormSpec({
|
|
|
1076
1108
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1077
1109
|
stability: '${$.stability||"beta"}',
|
|
1078
1110
|
},
|
|
1079
|
-
model: ${
|
|
1111
|
+
model: ${A},
|
|
1080
1112
|
fields: [
|
|
1081
1113
|
{
|
|
1082
1114
|
kind: 'text',
|
|
@@ -1101,13 +1133,13 @@ export const ${A} = defineFormSpec({
|
|
|
1101
1133
|
form: 'react-hook-form',
|
|
1102
1134
|
},
|
|
1103
1135
|
});
|
|
1104
|
-
`}function
|
|
1105
|
-
import { ${
|
|
1136
|
+
`}function TW($,b){let A=F8($.split(".").pop()||"unknown")+"Handler",n=DA($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1137
|
+
import { ${n} } from '../contracts/${FW($)}.contracts';
|
|
1106
1138
|
|
|
1107
1139
|
/**
|
|
1108
1140
|
* Handler for ${$}
|
|
1109
1141
|
*/
|
|
1110
|
-
export const ${
|
|
1142
|
+
export const ${A}: ContractHandler<typeof ${n}> = async (
|
|
1111
1143
|
input,
|
|
1112
1144
|
context
|
|
1113
1145
|
) => {
|
|
@@ -1127,27 +1159,27 @@ export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
|
1127
1159
|
throw error;
|
|
1128
1160
|
}
|
|
1129
1161
|
};
|
|
1130
|
-
`}function
|
|
1162
|
+
`}function DW($,b){let A=DA($);return`import React from 'react';
|
|
1131
1163
|
|
|
1132
|
-
interface ${
|
|
1164
|
+
interface ${A}Props {
|
|
1133
1165
|
// TODO: Define props based on presentation spec
|
|
1134
1166
|
}
|
|
1135
1167
|
|
|
1136
1168
|
/**
|
|
1137
1169
|
* ${b}
|
|
1138
1170
|
*/
|
|
1139
|
-
export const ${
|
|
1171
|
+
export const ${A}: React.FC<${A}Props> = (props) => {
|
|
1140
1172
|
return (
|
|
1141
1173
|
<div>
|
|
1142
1174
|
{/* TODO: Implement component UI */}
|
|
1143
|
-
<p>Component: ${
|
|
1175
|
+
<p>Component: ${A}</p>
|
|
1144
1176
|
</div>
|
|
1145
1177
|
);
|
|
1146
1178
|
};
|
|
1147
|
-
`}function
|
|
1148
|
-
import { ${
|
|
1179
|
+
`}function NW($,b){let A=b==="handler"?"../handlers":"../components",n=DA($);return`import { describe, it, expect } from 'bun:test';
|
|
1180
|
+
import { ${n} } from '${A}/${FW($)}';
|
|
1149
1181
|
|
|
1150
|
-
describe('${
|
|
1182
|
+
describe('${n}', () => {
|
|
1151
1183
|
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
1152
1184
|
// TODO: Implement test
|
|
1153
1185
|
expect(true).toBe(true);
|
|
@@ -1163,27 +1195,27 @@ describe('${A}', () => {
|
|
|
1163
1195
|
// TODO: Test accessibility
|
|
1164
1196
|
});`}
|
|
1165
1197
|
});
|
|
1166
|
-
`}function
|
|
1198
|
+
`}function F8($){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=d8($.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(`,
|
|
1167
1199
|
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1168
|
-
${$.capabilitiesRequired.map((
|
|
1200
|
+
${$.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(`,
|
|
1169
1201
|
`)}
|
|
1170
|
-
],`:"",j=
|
|
1171
|
-
`:"",X=
|
|
1202
|
+
],`:"",j=v8($.configFields),B=P8($.configFields),S=g8($.secretFields),Q=k8($.secretFields),Z=$.docsUrl?` docsUrl: '${j$($.docsUrl)}',
|
|
1203
|
+
`:"",X=r8($.rateLimitRpm,$.rateLimitRph),Y=f8(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1172
1204
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
1173
1205
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
1174
1206
|
|
|
1175
|
-
export const ${
|
|
1207
|
+
export const ${A}: IntegrationSpec = {
|
|
1176
1208
|
meta: {
|
|
1177
1209
|
key: '${$.name}',
|
|
1178
1210
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
1179
1211
|
category: '${$.category}',
|
|
1180
|
-
displayName: '${
|
|
1181
|
-
title: '${
|
|
1182
|
-
description: '${
|
|
1183
|
-
domain: '${
|
|
1184
|
-
owners: [${$.owners.map((
|
|
1185
|
-
tags: [${$.tags.map((
|
|
1186
|
-
stability: StabilityEnum.${
|
|
1212
|
+
displayName: '${j$($.displayName)}',
|
|
1213
|
+
title: '${j$($.title)}',
|
|
1214
|
+
description: '${j$($.description)}',
|
|
1215
|
+
domain: '${j$($.domain)}',
|
|
1216
|
+
owners: [${$.owners.map((H)=>`'${j$(H)}'`).join(", ")}],
|
|
1217
|
+
tags: [${$.tags.map((H)=>`'${j$(H)}'`).join(", ")}],
|
|
1218
|
+
stability: StabilityEnum.${h8($.stability)},
|
|
1187
1219
|
},
|
|
1188
1220
|
supportedModes: [${y}],
|
|
1189
1221
|
capabilities: {
|
|
@@ -1206,48 +1238,48 @@ ${Z}${X}${Y} healthCheck: {
|
|
|
1206
1238
|
},
|
|
1207
1239
|
};
|
|
1208
1240
|
|
|
1209
|
-
export function ${
|
|
1241
|
+
export function ${n}(
|
|
1210
1242
|
registry: IntegrationSpecRegistry
|
|
1211
1243
|
): IntegrationSpecRegistry {
|
|
1212
|
-
return registry.register(${
|
|
1244
|
+
return registry.register(${A});
|
|
1213
1245
|
}
|
|
1214
|
-
`}function
|
|
1215
|
-
`:"",
|
|
1246
|
+
`}function v8($){let b=$.filter((m)=>m.required),A=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1247
|
+
`:"",n=$.length?$.map((m)=>{let y=m.description?`, description: '${j$(m.description)}'`:"";return` ${m.key}: { type: '${c8(m.type)}'${y} }`}).join(`,
|
|
1216
1248
|
`):"";return` schema: {
|
|
1217
1249
|
type: 'object',
|
|
1218
|
-
${
|
|
1219
|
-
${
|
|
1250
|
+
${A} properties: {
|
|
1251
|
+
${n||" "}
|
|
1220
1252
|
},
|
|
1221
1253
|
},
|
|
1222
|
-
`}function
|
|
1223
|
-
`:"",
|
|
1254
|
+
`}function g8($){let b=$.filter((m)=>m.required),A=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1255
|
+
`:"",n=$.length?$.map((m)=>{let y=m.description?`, description: '${j$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
1224
1256
|
`):"";return` schema: {
|
|
1225
1257
|
type: 'object',
|
|
1226
|
-
${
|
|
1227
|
-
${
|
|
1258
|
+
${A} properties: {
|
|
1259
|
+
${n||" "}
|
|
1228
1260
|
},
|
|
1229
1261
|
},
|
|
1230
|
-
`}function
|
|
1231
|
-
${$.map((
|
|
1262
|
+
`}function P8($){if($.length===0)return"{}";return`{
|
|
1263
|
+
${$.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(`,
|
|
1232
1264
|
`)}
|
|
1233
|
-
}`}function
|
|
1234
|
-
${$.map((
|
|
1265
|
+
}`}function k8($){if($.length===0)return"{}";return`{
|
|
1266
|
+
${$.map((A)=>` ${A.key}: '${A.key.toUpperCase()}_SECRET'`).join(`,
|
|
1235
1267
|
`)}
|
|
1236
|
-
}`}function
|
|
1268
|
+
}`}function r8($,b){if($==null&&b==null)return"";let A=[];if($!=null)A.push(` rpm: ${$}`);if(b!=null)A.push(` rph: ${b}`);return` constraints: {
|
|
1237
1269
|
rateLimit: {
|
|
1238
|
-
${
|
|
1270
|
+
${A.join(`,
|
|
1239
1271
|
`)}
|
|
1240
1272
|
},
|
|
1241
1273
|
},
|
|
1242
|
-
`}function
|
|
1243
|
-
`:"",m=
|
|
1244
|
-
`:"";if(!
|
|
1245
|
-
${
|
|
1246
|
-
`}function
|
|
1274
|
+
`}function f8($,b,A){if(!$.includes("byok"))return"";let n=b?` setupInstructions: '${j$(b)}',
|
|
1275
|
+
`:"",m=A&&A.length?` requiredScopes: [${A.map((y)=>`'${j$(y)}'`).join(", ")}],
|
|
1276
|
+
`:"";if(!n&&!m)return"";return` byokSetup: {
|
|
1277
|
+
${n}${m} },
|
|
1278
|
+
`}function c8($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function h8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function d8($){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=t8($.name.split(".").pop()??"KnowledgeSpace"),A=`${b}KnowledgeSpace`,n=`register${b}KnowledgeSpace`,m=u8($),y=o8($),W=i8($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1247
1279
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1248
1280
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1249
1281
|
|
|
1250
|
-
export const ${
|
|
1282
|
+
export const ${A}: KnowledgeSpaceSpec = {
|
|
1251
1283
|
meta: {
|
|
1252
1284
|
key: '${$.name}',
|
|
1253
1285
|
version: ${$.version},
|
|
@@ -1258,7 +1290,7 @@ export const ${n}: KnowledgeSpaceSpec = {
|
|
|
1258
1290
|
domain: '${O$($.domain)}',
|
|
1259
1291
|
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1260
1292
|
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1261
|
-
stability: StabilityEnum.${
|
|
1293
|
+
stability: StabilityEnum.${l8($.stability)},
|
|
1262
1294
|
},
|
|
1263
1295
|
retention: ${m},
|
|
1264
1296
|
access: {
|
|
@@ -1267,54 +1299,54 @@ ${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` ve
|
|
|
1267
1299
|
${W} description: '${O$($.description||$.displayName)}',
|
|
1268
1300
|
};
|
|
1269
1301
|
|
|
1270
|
-
export function ${
|
|
1302
|
+
export function ${n}(
|
|
1271
1303
|
registry: KnowledgeSpaceRegistry
|
|
1272
1304
|
): KnowledgeSpaceRegistry {
|
|
1273
|
-
return registry.register(${
|
|
1305
|
+
return registry.register(${A});
|
|
1274
1306
|
}
|
|
1275
|
-
`}function
|
|
1276
|
-
`,
|
|
1277
|
-
`;return`${b}${
|
|
1307
|
+
`}function u8($){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 o8($){let b=` trustLevel: '${$.trustLevel}',
|
|
1308
|
+
`,A=` automationWritable: ${$.automationWritable},
|
|
1309
|
+
`;return`${b}${A}`}function i8($){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: {
|
|
1278
1310
|
${b.join(`,
|
|
1279
1311
|
`)}
|
|
1280
1312
|
},
|
|
1281
|
-
`}function
|
|
1313
|
+
`}function l8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function t8($){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=`${p8($.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';
|
|
1282
1314
|
|
|
1283
|
-
export const ${
|
|
1315
|
+
export const ${A}: MigrationSpec = {
|
|
1284
1316
|
meta: {
|
|
1285
1317
|
key: '${$.name}',
|
|
1286
1318
|
version: ${$.version},
|
|
1287
|
-
title: '${
|
|
1288
|
-
description: '${
|
|
1289
|
-
domain: '${
|
|
1319
|
+
title: '${c$($.title)}',
|
|
1320
|
+
description: '${c$($.description??"")}',
|
|
1321
|
+
domain: '${c$($.domain)}',
|
|
1290
1322
|
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1291
1323
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1292
1324
|
stability: '${$.stability}',
|
|
1293
1325
|
},
|
|
1294
1326
|
plan: {
|
|
1295
1327
|
up: [
|
|
1296
|
-
${
|
|
1328
|
+
${PW($.up)}
|
|
1297
1329
|
],${$.down&&$.down.length?`
|
|
1298
1330
|
down: [
|
|
1299
|
-
${
|
|
1331
|
+
${PW($.down)}
|
|
1300
1332
|
],`:""}
|
|
1301
1333
|
},
|
|
1302
|
-
${
|
|
1334
|
+
${n}
|
|
1303
1335
|
};
|
|
1304
|
-
`}function
|
|
1336
|
+
`}function PW($){return $.map((b)=>{let A=b.description?`description: '${c$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1305
1337
|
kind: 'schema',
|
|
1306
|
-
${
|
|
1307
|
-
sql: \`${
|
|
1338
|
+
${A}
|
|
1339
|
+
sql: \`${c$(b.sql??"")}\`,
|
|
1308
1340
|
}`;case"data":return` {
|
|
1309
1341
|
kind: 'data',
|
|
1310
|
-
${
|
|
1311
|
-
script: \`${
|
|
1342
|
+
${A}
|
|
1343
|
+
script: \`${c$(b.script??"")}\`,
|
|
1312
1344
|
}`;case"validation":default:return` {
|
|
1313
1345
|
kind: 'validation',
|
|
1314
|
-
${
|
|
1315
|
-
assertion: \`${
|
|
1346
|
+
${A}
|
|
1347
|
+
assertion: \`${c$(b.assertion??"")}\`,
|
|
1316
1348
|
}`}}).join(`,
|
|
1317
|
-
`)}function
|
|
1349
|
+
`)}function p8($){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=a8(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';
|
|
1318
1350
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1319
1351
|
|
|
1320
1352
|
// TODO: Define input schema
|
|
@@ -1337,15 +1369,15 @@ export const ${Y} = new SchemaModel({
|
|
|
1337
1369
|
},
|
|
1338
1370
|
});
|
|
1339
1371
|
|
|
1340
|
-
export const ${Z} = define${
|
|
1372
|
+
export const ${Z} = define${qn(n)}({
|
|
1341
1373
|
meta: {
|
|
1342
1374
|
key: '${b}',
|
|
1343
1375
|
key: '${b}',
|
|
1344
|
-
version: '${
|
|
1376
|
+
version: '${A}',
|
|
1345
1377
|
stability: '${w}',
|
|
1346
1378
|
stability: '${w}',
|
|
1347
|
-
owners: [${j.map((
|
|
1348
|
-
tags: [${B.map((
|
|
1379
|
+
owners: [${j.map((H)=>`'${H}'`).join(", ")}],
|
|
1380
|
+
tags: [${B.map((H)=>`'${H}'`).join(", ")}],
|
|
1349
1381
|
description: '${m}',
|
|
1350
1382
|
goal: '${y}',
|
|
1351
1383
|
context: '${W}',
|
|
@@ -1366,7 +1398,7 @@ export const ${Z} = define${q0(A)}({
|
|
|
1366
1398
|
|
|
1367
1399
|
policy: {
|
|
1368
1400
|
auth: '${S}',
|
|
1369
|
-
${Q.length>0?`flags: [${Q.map((
|
|
1401
|
+
${Q.length>0?`flags: [${Q.map((H)=>`'${H}'`).join(", ")}],`:"// flags: [],"}
|
|
1370
1402
|
},
|
|
1371
1403
|
|
|
1372
1404
|
sideEffects: {
|
|
@@ -1380,9 +1412,9 @@ export const ${Z} = define${q0(A)}({
|
|
|
1380
1412
|
},
|
|
1381
1413
|
|
|
1382
1414
|
transport: {
|
|
1383
|
-
rest: { method: '${
|
|
1415
|
+
rest: { method: '${n==="command"?"POST":"GET"}' },
|
|
1384
1416
|
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1385
|
-
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(
|
|
1417
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(A).replace(/\./g,"_")}' },
|
|
1386
1418
|
},
|
|
1387
1419
|
|
|
1388
1420
|
acceptance: {
|
|
@@ -1403,7 +1435,7 @@ export const ${Z} = define${q0(A)}({
|
|
|
1403
1435
|
],
|
|
1404
1436
|
},
|
|
1405
1437
|
});
|
|
1406
|
-
`}function
|
|
1438
|
+
`}function qn($){return $.charAt(0).toUpperCase()+$.slice(1)}function a8($){return $.split(/[-_.]/).map(qn).join("")}function fW($){let{name:b,version:A,description:n,stability:m,owners:y,tags:W,presentationKind:w}=$,j=e8(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1407
1439
|
kind: 'web_component',
|
|
1408
1440
|
framework: 'react',
|
|
1409
1441
|
componentKey: '${b.replace(/\./g,"_")}',
|
|
@@ -1420,7 +1452,7 @@ export const ${Z} = define${q0(A)}({
|
|
|
1420
1452
|
},`;break;case"markdown":B=` content: {
|
|
1421
1453
|
kind: 'markdown',
|
|
1422
1454
|
content: \`
|
|
1423
|
-
# ${
|
|
1455
|
+
# ${n}
|
|
1424
1456
|
|
|
1425
1457
|
TODO: Add markdown content here
|
|
1426
1458
|
\`,
|
|
@@ -1441,11 +1473,11 @@ import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
|
1441
1473
|
export const ${j}: PresentationSpec = {
|
|
1442
1474
|
meta: {
|
|
1443
1475
|
key: '${b}',
|
|
1444
|
-
version: ${
|
|
1476
|
+
version: ${A},
|
|
1445
1477
|
stability: '${m}',
|
|
1446
1478
|
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1447
1479
|
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1448
|
-
description: '${
|
|
1480
|
+
description: '${n}',
|
|
1449
1481
|
},
|
|
1450
1482
|
|
|
1451
1483
|
policy: {
|
|
@@ -1455,25 +1487,25 @@ export const ${j}: PresentationSpec = {
|
|
|
1455
1487
|
|
|
1456
1488
|
${B}
|
|
1457
1489
|
};
|
|
1458
|
-
`}function
|
|
1490
|
+
`}function e8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function cW($){let b=s8($.name.split(".").pop()??"Telemetry")+"Telemetry",A=$.providers?.length?`providers: [
|
|
1459
1491
|
${$.providers.map((m)=>` {
|
|
1460
1492
|
type: '${m.type}',
|
|
1461
|
-
config: ${
|
|
1493
|
+
config: ${$S(m.config)},
|
|
1462
1494
|
}`).join(`,
|
|
1463
1495
|
`)}
|
|
1464
|
-
],`:"",
|
|
1496
|
+
],`:"",n=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1465
1497
|
type: '${w.type}',
|
|
1466
1498
|
${w.required?"required: true,":""}
|
|
1467
1499
|
${w.pii?"pii: true,":""}
|
|
1468
1500
|
${w.redact?"redact: true,":""}
|
|
1469
|
-
${w.description?`description: '${
|
|
1501
|
+
${w.description?`description: '${t(w.description)}',`:""}
|
|
1470
1502
|
}`).join(`,
|
|
1471
1503
|
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1472
1504
|
enabled: true,
|
|
1473
1505
|
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1474
1506
|
thresholds: [
|
|
1475
1507
|
${m.anomalyRules.map((w)=>` {
|
|
1476
|
-
metric: '${
|
|
1508
|
+
metric: '${t(w.metric)}',
|
|
1477
1509
|
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1478
1510
|
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1479
1511
|
}`).join(`,
|
|
@@ -1484,46 +1516,46 @@ ${m.anomalyRules.map((w)=>` {
|
|
|
1484
1516
|
enabled: true,
|
|
1485
1517
|
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1486
1518
|
},`:"";return` {
|
|
1487
|
-
name: '${
|
|
1519
|
+
name: '${t(m.name)}',
|
|
1488
1520
|
version: ${m.version},
|
|
1489
1521
|
semantics: {
|
|
1490
|
-
what: '${
|
|
1491
|
-
${m.who?`who: '${
|
|
1492
|
-
${m.why?`why: '${
|
|
1522
|
+
what: '${t(m.what)}',
|
|
1523
|
+
${m.who?`who: '${t(m.who)}',`:""}
|
|
1524
|
+
${m.why?`why: '${t(m.why)}',`:""}
|
|
1493
1525
|
},
|
|
1494
1526
|
privacy: '${m.privacy}',
|
|
1495
1527
|
properties: {
|
|
1496
1528
|
${y}
|
|
1497
1529
|
},
|
|
1498
1530
|
${typeof m.retentionDays==="number"?`retention: { days: ${m.retentionDays}, ${m.retentionPolicy?`policy: '${m.retentionPolicy}'`:""} },`:""}
|
|
1499
|
-
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${
|
|
1531
|
+
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${t(m.samplingConditions)}']`:""} },`:""}
|
|
1500
1532
|
${W}
|
|
1501
|
-
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${
|
|
1533
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${t(w)}'`).join(", ")}],`:""}
|
|
1502
1534
|
}`}).join(`,
|
|
1503
1535
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1504
1536
|
|
|
1505
1537
|
export const ${b}: TelemetrySpec = {
|
|
1506
1538
|
meta: {
|
|
1507
|
-
key: '${
|
|
1539
|
+
key: '${t($.name)}',
|
|
1508
1540
|
version: ${$.version},
|
|
1509
|
-
title: '${
|
|
1510
|
-
description: '${
|
|
1511
|
-
domain: '${
|
|
1512
|
-
owners: [${$.owners.map((m)=>`'${
|
|
1513
|
-
tags: [${$.tags.map((m)=>`'${
|
|
1541
|
+
title: '${t($.name)} telemetry',
|
|
1542
|
+
description: '${t($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1543
|
+
domain: '${t($.domain)}',
|
|
1544
|
+
owners: [${$.owners.map((m)=>`'${t(m)}'`).join(", ")}],
|
|
1545
|
+
tags: [${$.tags.map((m)=>`'${t(m)}'`).join(", ")}],
|
|
1514
1546
|
stability: '${$.stability}',
|
|
1515
1547
|
},
|
|
1516
1548
|
config: {
|
|
1517
1549
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1518
1550
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1519
1551
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1520
|
-
${
|
|
1552
|
+
${A}
|
|
1521
1553
|
},
|
|
1522
1554
|
events: [
|
|
1523
|
-
${
|
|
1555
|
+
${n}
|
|
1524
1556
|
],
|
|
1525
1557
|
};
|
|
1526
|
-
`}function
|
|
1558
|
+
`}function s8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function $S($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${t(b)}'`}function bS($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function hW($){return`/**
|
|
1527
1559
|
* ${$.title} Theme
|
|
1528
1560
|
*
|
|
1529
1561
|
* Auto-generated theme spec.
|
|
@@ -1531,7 +1563,7 @@ ${A}
|
|
|
1531
1563
|
|
|
1532
1564
|
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1533
1565
|
|
|
1534
|
-
export const ${
|
|
1566
|
+
export const ${bS($.key)}Theme = defineTheme({
|
|
1535
1567
|
meta: {
|
|
1536
1568
|
key: '${$.key}',
|
|
1537
1569
|
version: '${$.version}',
|
|
@@ -1551,11 +1583,11 @@ export const ${t5($.key)}Theme = defineTheme({
|
|
|
1551
1583
|
},
|
|
1552
1584
|
},
|
|
1553
1585
|
});
|
|
1554
|
-
`}function
|
|
1555
|
-
`),
|
|
1586
|
+
`}function dW($){let b=nS($.name.split(".").pop()??"Workflow")+"Workflow",A=$.steps.map((m)=>AS(m)).join(`,
|
|
1587
|
+
`),n=$.transitions.map((m)=>` {
|
|
1556
1588
|
from: '${m.from}',
|
|
1557
1589
|
to: '${m.to}',
|
|
1558
|
-
${m.condition?` condition: '${
|
|
1590
|
+
${m.condition?` condition: '${yb(m.condition)}',`:""}
|
|
1559
1591
|
}`).join(`,
|
|
1560
1592
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1561
1593
|
|
|
@@ -1571,9 +1603,9 @@ export const ${b}: WorkflowSpec = {
|
|
|
1571
1603
|
meta: {
|
|
1572
1604
|
key: '${$.name}',
|
|
1573
1605
|
version: ${$.version},
|
|
1574
|
-
title: '${
|
|
1575
|
-
description: '${
|
|
1576
|
-
domain: '${
|
|
1606
|
+
title: '${yb($.title)}',
|
|
1607
|
+
description: '${yb($.description)}',
|
|
1608
|
+
domain: '${yb($.domain)}',
|
|
1577
1609
|
stability: '${$.stability}',
|
|
1578
1610
|
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1579
1611
|
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
@@ -1581,22 +1613,22 @@ export const ${b}: WorkflowSpec = {
|
|
|
1581
1613
|
definition: {
|
|
1582
1614
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1583
1615
|
`:""} steps: [
|
|
1584
|
-
${
|
|
1616
|
+
${A}
|
|
1585
1617
|
],
|
|
1586
1618
|
transitions: [
|
|
1587
|
-
${
|
|
1619
|
+
${n}
|
|
1588
1620
|
],
|
|
1589
1621
|
},
|
|
1590
1622
|
${$.policyFlags.length>0?`policy: {
|
|
1591
1623
|
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1592
1624
|
},`:"// policy: { flags: [] },"}
|
|
1593
1625
|
};
|
|
1594
|
-
`}function
|
|
1595
|
-
`)}function
|
|
1626
|
+
`}function AS($){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(`
|
|
1627
|
+
`)}function nS($){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';
|
|
1596
1628
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1597
1629
|
import { ${$} } from '${b}';
|
|
1598
1630
|
|
|
1599
|
-
export async function ${
|
|
1631
|
+
export async function ${A}(input = {}, bridge = {}) {
|
|
1600
1632
|
"use workflow";
|
|
1601
1633
|
|
|
1602
1634
|
// Keep the workflow function deterministic.
|
|
@@ -1613,7 +1645,7 @@ export async function ${n}(input = {}, bridge = {}) {
|
|
|
1613
1645
|
},
|
|
1614
1646
|
});
|
|
1615
1647
|
}
|
|
1616
|
-
`}function
|
|
1648
|
+
`}function FA($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1617
1649
|
import { ${b} } from '${$}';
|
|
1618
1650
|
|
|
1619
1651
|
export const POST = createWorkflowDevkitStartRoute({
|
|
@@ -1622,17 +1654,17 @@ export const POST = createWorkflowDevkitStartRoute({
|
|
|
1622
1654
|
return [body];
|
|
1623
1655
|
},
|
|
1624
1656
|
});
|
|
1625
|
-
`}function
|
|
1657
|
+
`}function vA(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1626
1658
|
|
|
1627
1659
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1628
1660
|
resolveToken({ runId }) {
|
|
1629
1661
|
return \`workflow-session:\${runId}\`;
|
|
1630
1662
|
},
|
|
1631
1663
|
});
|
|
1632
|
-
`}function
|
|
1664
|
+
`}function gA(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1633
1665
|
|
|
1634
1666
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1635
|
-
`}function
|
|
1667
|
+
`}function PA($,b){return`import { ${b} } from '${$}';
|
|
1636
1668
|
|
|
1637
1669
|
export const workflowDevkitBootstrap = {
|
|
1638
1670
|
workflow: ${b},
|
|
@@ -1644,13 +1676,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1644
1676
|
};
|
|
1645
1677
|
},
|
|
1646
1678
|
};
|
|
1647
|
-
`}function
|
|
1679
|
+
`}function kA({exportName:$,specImportPath:b,runnerName:A,workflowName:n}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1648
1680
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1649
1681
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1650
1682
|
import { ${$} } from '${b}';
|
|
1651
1683
|
|
|
1652
1684
|
/**
|
|
1653
|
-
* Runner wiring for ${
|
|
1685
|
+
* Runner wiring for ${n}.
|
|
1654
1686
|
*
|
|
1655
1687
|
* TODO:
|
|
1656
1688
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1662,7 +1694,7 @@ registry.register(${$});
|
|
|
1662
1694
|
|
|
1663
1695
|
const stateStore = new InMemoryStateStore();
|
|
1664
1696
|
|
|
1665
|
-
export const ${
|
|
1697
|
+
export const ${A} = new WorkflowRunner({
|
|
1666
1698
|
registry,
|
|
1667
1699
|
stateStore,
|
|
1668
1700
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1684,12 +1716,12 @@ export const ${n} = new WorkflowRunner({
|
|
|
1684
1716
|
// console.log(event, payload);
|
|
1685
1717
|
},
|
|
1686
1718
|
});
|
|
1687
|
-
`}import{getAuthoringTargetDefinition as
|
|
1688
|
-
`],[y,`# ${
|
|
1719
|
+
`}import{getAuthoringTargetDefinition as mS}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=yS($,b.specPath),n=WS($,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)+`
|
|
1720
|
+
`],[y,`# ${n}
|
|
1689
1721
|
|
|
1690
|
-
${
|
|
1722
|
+
${oW[b.target]}.
|
|
1691
1723
|
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1692
|
-
`],[b.specPath,b.specCode]],S={packageRoot:
|
|
1724
|
+
`],[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";
|
|
1693
1725
|
|
|
1694
1726
|
export const ${$.exportName} = defineModuleBundle({
|
|
1695
1727
|
meta: {
|
|
@@ -1758,22 +1790,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1758
1790
|
supportedArtifactTypes: ["patch"],
|
|
1759
1791
|
knownConstraints: [],
|
|
1760
1792
|
};
|
|
1761
|
-
`}}function
|
|
1793
|
+
`}}function yS($,b){let A=On(b),n="/src/",m=A.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return A.slice(0,m)}function WS($,b,A){let n=mS(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??XS,j=W?.inferSpecTypeFromFilePath??ZS,B=W?.generateHandlerTemplate??BS,S=W?.generateComponentTemplate??jS,Q=W?.generateTestTemplate??SS,{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 YS(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 YS($,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";
|
|
1762
1794
|
|
|
1763
|
-
export interface ${
|
|
1795
|
+
export interface ${J$($$(A,n,b))}Props {
|
|
1764
1796
|
className?: string;
|
|
1765
1797
|
}
|
|
1766
1798
|
|
|
1767
|
-
export function ${
|
|
1799
|
+
export function ${J$($$(A,n,b))}Form({
|
|
1768
1800
|
className,
|
|
1769
|
-
}: ${
|
|
1770
|
-
return <form className={className}>TODO: implement ${
|
|
1801
|
+
}: ${J$($$(A,n,b))}Props) {
|
|
1802
|
+
return <form className={className}>TODO: implement ${$$(A,n,b)}</form>;
|
|
1771
1803
|
}
|
|
1772
|
-
`;
|
|
1804
|
+
`;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=OS(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}),VS(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=JS(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:US(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 _=GS(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??QS(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 HS(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,KS(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 HS($,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 GS($){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 qS($,"name")??b.key??Kn(_S(A))}function qS($,b){let A=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(A)?.[1]??null}function OS($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function JS($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function US($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function VS($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function KS($){return $.endsWith(`
|
|
1773
1805
|
`)?$:`${$}
|
|
1774
|
-
`}function H8($){return $.replaceAll("\\","/").split("/").pop()??$}$$();import{scanAllSpecsFromSource as K8,scanSpecSource as _8}from"@contractspec/module.workspace";import z8 from"micromatch";var aW={};f(aW,{validators:()=>U8,urlSchema:()=>J8,isValidVersion:()=>O8,isValidIdentifier:()=>lW,isValidDotName:()=>pW,isTestFile:()=>zb,isLibraryDefinitionFile:()=>Lb,emailSchema:()=>V8});import _0 from"micromatch";function zb($,b){let n=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _0.isMatch($,n)}function Lb($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(_0.isMatch($,b))return!1;let n=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return _0.isMatch($,n)}import*as J$ from"zod";function lW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function pW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function O8($){return Number.isInteger($)&&$>0}var V8=J$.string().email(),J8=J$.string().url(),U8={specName:J$.string().refine(pW,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:J$.number().int().positive(),identifier:J$.string().refine(lW,{message:"Must be a valid TypeScript identifier"}),owner:J$.string().startsWith("@"),tag:J$.string().min(1)};function Rb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function L8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],n=[...Rb($?.conventions.models),...Rb($?.conventions.operations),...Rb($?.conventions.events),...Rb($?.conventions.presentations),...Rb($?.conventions.forms)];return[...new Set(b.flatMap((A)=>{let m=A==="**"?"":`${A}/`,y=q$.map((w)=>`${m}${w}`),W=n.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function R8($,b,n){if($.specType==="unknown")return!1;if(b.type&&!n.includes($.specType))return!1;return!0}function C8($,b){let n=$.filePath.localeCompare(b.filePath);if(n!==0)return n;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function c$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((n,A)=>n.localeCompare(A));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:L8(b.config)})}async function cn($,b={}){let n=await c$($.fs,b),A=b.type?Array.isArray(b.type)?b.type:[b.type]:[],m=[];for(let y of n){if(b.config?.excludePackages&&z8.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||zb(y,b.config)||Lb(y))continue;try{let W=await $.fs.readFile(y),w=K8(W,y),j=w.length>0?w:[_8(W,y)];for(let B of j)if(R8(B,b,A))m.push(B)}catch{}}return m.sort(C8)}function L$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function hn($){let b=JSON.parse($),n=new Map,A=0,m=0,y=0,W=0,w=0,j=0,B=0,S=0;for(let[Z,X]of Object.entries(b)){let Y=x8(Z,X);n.set(Z,Y),A+=Y.statements.total,m+=Y.statements.covered,y+=Y.branches.total,W+=Y.branches.covered,w+=Y.functions.total,j+=Y.functions.covered,B+=Y.lines.total,S+=Y.lines.covered}let Q={statements:{covered:m,total:A,pct:L$(m,A)},branches:{covered:W,total:y,pct:L$(W,y)},functions:{covered:j,total:w,pct:L$(j,w)},lines:{covered:S,total:B,pct:L$(S,B)}};return{files:n,total:Q}}function x8($,b){let n=Object.keys(b.statementMap).length,A=Object.values(b.s).filter((S)=>S>0).length,m=Object.keys(b.fnMap).length,y=Object.values(b.f).filter((S)=>S>0).length,W=0,w=0;for(let S of Object.values(b.b))W+=S.length,w+=S.filter((Q)=>Q>0).length;let j=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(j.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:A,total:n,pct:L$(A,n)},branches:{covered:w,total:W,pct:L$(w,W)},functions:{covered:y,total:m,pct:L$(y,m)},lines:{covered:B.size,total:j.size,pct:L$(B.size,j.size)}}}function z0($){switch($){case"istanbul":return{parse:hn};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function L0($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function R0($,b,n,A){let m=[];if(n.statements!==void 0&&A.statements.pct<n.statements)m.push({metric:"statements",required:n.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${n.statements}%`});if(n.branches!==void 0&&A.branches.pct<n.branches)m.push({metric:"branches",required:n.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${n.branches}%`});if(n.functions!==void 0&&A.functions.pct<n.functions)m.push({metric:"functions",required:n.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${n.functions}%`});if(n.lines!==void 0&&A.lines.pct<n.lines)m.push({metric:"lines",required:n.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${n.lines}%`});if(n.mutations!==void 0)m.push({metric:"mutations",required:n.mutations,actual:0,message:`Mutation coverage required (${n.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:n,actual:A,passed:m.length===0,failures:m}}async function C0($,b,n){let{fs:A,logger:m}=$,y=[],W=n.workspaceRoot?`${n.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await A.exists(X)){j=await A.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=L0(B??"coverage.json"),Z=z0(S).parse(j);for(let X of b){if(X.specType!=="test-spec"||!X.key||!X.version||!X.sourceBlock)continue;let Y=X.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!Y||!Y[1])continue;let G=Y[1],V={},O=G.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=G.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=G.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let U=G.match(/lines\s*:\s*(\d+)/);if(U&&U[1])V.lines=parseInt(U[1],10);if(Object.keys(V).length===0)continue;let H=R0(X.key,X.version,V,Z.total);for(let q of H.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:q.metric,required:q.required,actual:q.actual}})}return y}$$();import{addContractNode as I8,buildReverseEdges as E8,createContractGraph as M8,detectCycles as T8,findMissingDependencies as D8,parseImportedSpecNames as N8,toDot as F8}from"@contractspec/module.workspace";async function eW($,b={}){let{fs:n}=$,A=await c$(n,{config:b.config,pattern:b.pattern}),m=M8();for(let w of A){let j=await n.readFile(w),B=n.relative(".",w),S=n.basename(w).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=N8(j,w);I8(m,S,B,Q)}E8(m);let y=T8(m),W=D8(m);return{graph:m,total:m.size,cycles:y,missing:W}}function UO($,b){return $.get(b)}function KO($){return F8($)}function _O($){let b=Array.from($.values()),n=b.filter((W)=>W.dependencies.length>0),A=b.filter((W)=>W.dependencies.length===0),m=b.filter((W)=>W.dependents.length>0),y=b.filter((W)=>W.dependents.length===0);return{total:$.size,withDeps:n.length,withoutDeps:A.length,used:m.length,unused:y.length}}async function x0($,b){let n=[],A=await P($.fs),m=await eW($,{config:A,pattern:b.pattern});for(let y of m.cycles)n.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${y.join(" → ")}`,category:"deps",context:{cycle:y}});for(let y of m.missing)for(let W of y.missing)n.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${y.contract} requires ${W}`,category:"deps",context:{contract:y.contract,missing:W}});return n}import{analyzePackageDocBlocks as v8}from"@contractspec/module.workspace";var g8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function P8($,b){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:g8}),A=new Map;for(let W of n){let w=$.dirname(W),j=$.join(w,"src");if(!await $.exists(j))continue;try{let B=JSON.parse(await $.readFile(W));A.set(w,{packageName:B.name??$.relative(b,w),packageRoot:w,srcRoot:j})}catch{continue}}let m=$.join(b,"package.json"),y=$.join(b,"src");if(await $.exists(m)&&await $.exists(y))try{let W=JSON.parse(await $.readFile(m));A.set(b,{packageName:W.name??b,packageRoot:b,srcRoot:y})}catch{}return[...A.values()].sort((W,w)=>W.packageRoot.localeCompare(w.packageRoot))}async function dn($,b){let n=[],A=await P8($,b);for(let m of A){let y=v8({packageName:m.packageName,srcRoot:m.srcRoot});for(let W of y.diagnostics)n.push({...W,packageName:m.packageName,packageRoot:m.packageRoot,srcRoot:m.srcRoot})}return n}async function I0($,b){let n=b.workspaceRoot??process.cwd();return(await dn($.fs,n)).map((m)=>({ruleId:m.ruleId,severity:m.severity==="warning"?"warning":"error",message:m.message,category:"docs",file:m.file,line:m.line,column:m.column,context:{packageName:m.packageName,packageRoot:m.packageRoot,...m.context}}))}async function E0($,b,n){let A=[],m=await k8($,b);if(A.push(m),m.status==="pass")A.push(await r8($,b,n));return A}async function k8($,b){let n=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(n))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let m=await $.readFile(n),y=JSON.parse(m),W=y.aiProvider??"claude",w=y.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${W}, Model: ${w}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function r8($,b,n){let A=$.join(b.workspaceRoot,".contractsrc.json");try{let m=await $.readFile(A),W=JSON.parse(m).aiProvider??"claude",j={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[W];if(!j)return{category:"ai",name:"API Key",status:"pass",message:`${W} does not require an API key`};if(!!process.env[j])return{category:"ai",name:"API Key",status:"pass",message:`${j} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${j} not set`,details:`Set ${j} in your environment to use AI features`,fix:n?{description:`Set ${j} environment variable`,apply:async()=>{let S=await n.input(`Enter your ${W} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${j}=`))return{success:!1,message:`${j} already in .env, update manually`};Z+=`
|
|
1806
|
+
`}function _S($){return $.replaceAll("\\","/").split("/").pop()??$}b$();import{scanAllSpecsFromSource as xS,scanSpecSource as MS}from"@contractspec/module.workspace";import ES from"micromatch";var eW={};f(eW,{validators:()=>CS,urlSchema:()=>IS,isValidVersion:()=>LS,isValidIdentifier:()=>pW,isValidDotName:()=>aW,isTestFile:()=>Rb,isLibraryDefinitionFile:()=>Ib,emailSchema:()=>RS});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 LS($){return Number.isInteger($)&&$>0}var RS=U$.string().email(),IS=U$.string().url(),CS={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 TS($){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 DS($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function NS($,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:TS(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&&ES.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=xS(W,y),j=w.length>0?w:[MS(W,y)];for(let B of j)if(DS(B,b,n))m.push(B)}catch{}}return m.sort(NS)}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=FS(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 FS($,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 vS,buildReverseEdges as gS,createContractGraph as PS,detectCycles as kS,findMissingDependencies as rS,parseImportedSpecNames as fS,toDot as cS}from"@contractspec/module.workspace";async function sW($,b={}){let{fs:A}=$,n=await h$(A,{config:b.config,pattern:b.pattern}),m=PS();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=fS(j,w);vS(m,S,B,Q)}gS(m);let y=kS(m),W=rS(m);return{graph:m,total:m.size,cycles:y,missing:W}}function DO($,b){return $.get(b)}function NO($){return cS($)}function FO($){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(" → ")}`,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 hS}from"@contractspec/module.workspace";var dS=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function uS($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:dS}),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 uS($,b);for(let m of n){let y=hS({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 oS($,b);if(n.push(m),m.status==="pass")n.push(await iS($,b,A));return n}async function oS($,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 iS($,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+=`
|
|
1775
1807
|
`}return Z+=`${j}=${S}
|
|
1776
|
-
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${j} to .env (restart required)`}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as
|
|
1808
|
+
`,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 lS}from"node:child_process";import{promisify as tS}from"node:util";var uA=tS(lS);async function En($,b){let A=[];return A.push(await pS(b)),A.push(await aS(b)),A.push(await eS($,b)),A}async function pS($){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 aS($){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 eS($,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 sS,relative as $9}from"node:path";var b9="contractspec",A9="contractsrc.schema.json";function n9($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function xb($){return n9($9($.configRoot,sS($.workspaceRoot,"node_modules",b9,A9)))}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 eO($){return $.startsWith("builder-")}function sO($){return $==="connect"}function Ww($){let b=R$($),A=m9($.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 m9($){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=y9($),m=W9($);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
|
|
1777
1809
|
|
|
1778
1810
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1779
1811
|
|
|
@@ -1794,10 +1826,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1794
1826
|
## Contract Locations
|
|
1795
1827
|
|
|
1796
1828
|
Contracts are located in:
|
|
1797
|
-
- \`${
|
|
1798
|
-
- \`${
|
|
1799
|
-
- \`${
|
|
1800
|
-
- \`${
|
|
1829
|
+
- \`${n}/operations/\` - Command and query specs
|
|
1830
|
+
- \`${n}/events/\` - Event specs
|
|
1831
|
+
- \`${n}/presentations/\` - UI presentation specs
|
|
1832
|
+
- \`${n}/features/\` - Feature module specs
|
|
1801
1833
|
|
|
1802
1834
|
## When Making Changes
|
|
1803
1835
|
|
|
@@ -1839,7 +1871,7 @@ defineCommand({
|
|
|
1839
1871
|
- Events must be declared in contracts before being emitted.
|
|
1840
1872
|
- UI components should reference presentation contracts.
|
|
1841
1873
|
- Feature flags should be defined in feature modules.
|
|
1842
|
-
`}function
|
|
1874
|
+
`}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?`
|
|
1843
1875
|
## Monorepo Scope
|
|
1844
1876
|
|
|
1845
1877
|
This guide is scoped to the current package.
|
|
@@ -1899,8 +1931,8 @@ ${W}
|
|
|
1899
1931
|
|
|
1900
1932
|
## Initialization Preset
|
|
1901
1933
|
|
|
1902
|
-
- This workspace was initialized with the \`${
|
|
1903
|
-
`}function
|
|
1934
|
+
- This workspace was initialized with the \`${n}\` setup preset.
|
|
1935
|
+
`}function Qw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1904
1936
|
|
|
1905
1937
|
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1906
1938
|
|
|
@@ -1929,68 +1961,68 @@ This workspace uses ContractSpec to keep contracts, generated artifacts, and AI
|
|
|
1929
1961
|
|
|
1930
1962
|
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1931
1963
|
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1932
|
-
`}function
|
|
1933
|
-
`}async function N0($,b){let n=[];return n.push(await $9($,b)),n.push(await b9($,b)),n.push(await n9($,b)),n.push(await A9($,b)),n.push(await m9($,b)),n.push(await y9($,b)),n.push(await W9($,b)),n}async function h$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function $9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(await $.exists(n))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let m=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(m)),{success:!0,message:"Created .contractsrc.json"}}catch(m){return{success:!1,message:`Failed to create: ${m instanceof Error?m.message:String(m)}`}}}}}}async function b9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n);return JSON.parse(m),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(m){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:m instanceof Error?m.message:String(m),fix:{description:"Replace with valid default config",apply:async()=>{try{let W=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(W)),{success:!0,message:"Replaced with valid config"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function n9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m),W=[];if(!y.outputDir)W.push("outputDir");if(!y.conventions)W.push("conventions");if(W.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${W.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let w=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let j of W)if(w[j]!==void 0)y[j]=w[j];return await $.writeFile(n,N(y)),{success:!0,message:"Added missing fields"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function A9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:y.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return y.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(n,N(y)),{success:!0,message:"Added versioning configuration"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function m9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.hooks){let j=y.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(j).length} git hook(s) configured`}}let W=$.join(b.workspaceRoot,".husky");if(await $.exists(W))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return y.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(n,N(y)),{success:!0,message:"Added hooks configuration"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function y9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),j=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(w.length===0&&!j)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...w,...j?["connect.studio.endpoint"]:[]].join(", ")}`}}let y=[],W=A.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!A.builder?.api?.baseUrl)y.push("builder.api.baseUrl");if(m.startsWith("builder-")&&!W)y.push("builder.api.controlPlaneTokenEnvVar");if(m.startsWith("builder-")&&W&&!process.env[W])y.push(`env:${W}`);if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)y.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:y.length===0?"pass":"warn",message:y.length===0?`Builder preset inferred (${m}) and required config is present`:`Builder preset inferred (${m}) but setup is missing ${y.join(", ")}`}}async function W9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(n,".vscode","settings.json"),W=A.builder?.api?.baseUrl;if(!W)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let w=await $.readFile(y).catch(()=>""),j=w?a(w):void 0;if(j?.["contractspec.api.baseUrl"]===W)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(n,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...tn({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as w9}from"node:child_process";import{promisify as j9}from"node:util";var d$=j9(w9);async function F0($,b){let n=[];return n.push(await B9(b)),n.push(await S9(b)),n.push(await Q9($,b)),n.push(await Z9($,b)),n.push(await X9($,b)),n}async function B9($){try{let{stdout:b}=await d$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function S9($){try{let{stdout:b}=await d$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function Q9($,b){let n=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:m,name:y}of n){let W=$.join(b.workspaceRoot,m);if(await $.exists(W)){A=y;break}}if(!A){let m=$.join(b.workspaceRoot,".."),y=$.join(b.workspaceRoot,"../.."),W=[m,y];for(let w of W){for(let{file:j,name:B}of n){let S=$.join(w,j);if(await $.exists(S)){A=B;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await d$(`${A} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function Z9($,b){let n=$.join(b.workspaceRoot,"node_modules");if(await $.exists(n))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await d$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function X9($,b){let n=$.join(b.workspaceRoot,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A),y={...m.dependencies,...m.devDependencies};if("@contractspec/lib.contracts-spec"in y)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${y["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await d$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function v0($,b){let n=await dn($,b.workspaceRoot);if(n.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return n.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(b.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as Y9,isFeatureFile as G9,scanAllSpecsFromSource as H9,scanExampleSource as q9,scanFeatureSource as O9}from"@contractspec/module.workspace";function V9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function an($,b={}){let{fs:n,logger:A}=$,m=V9(),y=b.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let W=await n.glob({pattern:y});for(let j of W){if(j.includes("node_modules")||j.includes("/dist/"))continue;try{let B=await n.readFile(j);if(G9(j)){let S=O9(B,j);m.features.set(S.key,S);continue}if(Y9(j)){let S=q9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=H9(B,j);for(let Q of S)if(Q.specType==="app-config"&&Q.key)m.appConfigs.set(Q.key,Q)}}catch{}}try{let j=await n.glob({pattern:"**/.contractsrc.json"});for(let B of j){if(B.includes("node_modules"))continue;try{let S=await n.readFile(B),Q=JSON.parse(S);m.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){m.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let w={features:m.features.size,examples:m.examples.size,appConfigs:m.appConfigs.size,workspaceConfigs:m.workspaceConfigs.size,total:m.features.size+m.examples.size+m.appConfigs.size+m.workspaceConfigs.size};return A.info(`Discovered ${w.features} features, ${w.examples} examples, ${w.appConfigs} app configs, ${w.workspaceConfigs} workspace configs`),{inventory:m,stats:w}}function yV($){let b=[];for(let[n,A]of $.features)b.push({key:n,file:A.filePath,type:"feature"});for(let[n,A]of $.examples)b.push({key:n,version:A.version,file:A.filePath,type:"example"});for(let[n,A]of $.appConfigs)b.push({key:n,version:A.version,file:A.filePath,type:"app-config"});for(let[,n]of $.workspaceConfigs)b.push({key:n.file,file:n.file,type:"workspace-config"});return b}function en($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function g0($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function sn($,b){let n=$.join(b,"config/stability-policy.json");if(!await $.exists(n))return;try{let A=await $.readFile(n),m=JSON.parse(A);return{version:typeof m.version==="number"&&Number.isFinite(m.version)?m.version:1,criticalPackages:g0(m.criticalPackages).map(en),criticalFeatureKeys:g0(m.criticalFeatureKeys),smokePackages:g0(m.smokePackages)}}catch{return}}function Qw($,b){let n=en($);if(b?.criticalPackages.includes(n))return"critical";return"non-critical"}function Zw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function wb($){return en(`${en($)}/config/stability-policy.json`)}async function P0($,b){let n=[],A=await sn($,b.workspaceRoot),m=await an({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return n.push(J9(m.stats.features)),n.push(U9(m.stats.examples)),n.push(K9(m.inventory.features,A,b)),n.push(_9(m.inventory.examples)),n.push(z9(m.inventory.workspaceConfigs)),n}function J9($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function U9($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function K9($,b,n){let A=[],m=[];for(let[y,W]of $)if(!(Boolean(W.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(W.sourceBlock??"")))if(Zw(y,b))m.push(y);else A.push(y);if(m.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:m.length>0?"fail":"warn",message:m.length>0?`${m.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:m.length>0?`Critical features: ${m.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:m,missingFeatures:A}}}function _9($){let b=[];for(let[n,A]of $)if(!A.entrypoints.packageName)b.push(n);if(b.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function z9($){let b=[];for(let[,n]of $)if(!n.valid)b.push(n.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function k0($,b){let n=[];return n.push(await L9($,b)),n.push(await R9($,b)),n.push(await C9($,b)),n}async function L9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(n))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Mb();return await $.writeFile(n,N(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function R9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(n))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let w=Mb(),j=b$(y,w);return await $.writeFile(n,N(j)),{success:!0,message:"Registered MCP server"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function C9($,b){let n=ln();try{if(!await $.exists(n))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let m=await $.readFile(n);if(JSON.parse(m).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var x9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Xw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function I9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[n,A])=>{if(typeof A==="string")b[n]=A;return b},{})}function E9($){return Object.entries($).some(([b,n])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(n)})}async function M9($,b,n){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:Xw}),m=[];for(let y of A){let W=$.dirname(y),w=$.relative(b,W);try{let j=JSON.parse(await $.readFile(y)),B=I9(j.scripts),S=await $.glob({patterns:x9,cwd:W,ignore:Xw});m.push({packageName:j.name??w,packagePath:w.replace(/\\/g,"/"),hasBuildScript:typeof B.build==="string",hasTypecheckScript:typeof B.typecheck==="string",hasLintScript:typeof B.lint==="string"||typeof B["lint:check"]==="string",hasTestScript:typeof B.test==="string",usesPassWithNoTests:E9(B),testFileCount:S.length,tier:Qw(w,n)})}catch{continue}}return m}function T9($){let b=[];if(!$.hasBuildScript)b.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)b.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)b.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)b.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)b.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)b.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return b}function D9($){let b=[];if($.testFileCount>0&&!$.hasTestScript)b.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)b.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return b}async function Yw($,b,n){let A=await M9($,b,n),m=[];for(let W of A){if(W.tier==="critical")m.push(...T9(W));m.push(...D9(W))}let y=A.filter((W)=>W.tier==="critical").map((W)=>({packageName:W.packageName,packagePath:W.packagePath,hasBuildScript:W.hasBuildScript,hasTypecheckScript:W.hasTypecheckScript,hasLintScript:W.hasLintScript,hasTestScript:W.hasTestScript,usesPassWithNoTests:W.usesPassWithNoTests,testFileCount:W.testFileCount}));return{findings:m,criticalPackages:y}}function Hw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Gw($,b,n,A){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||n.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:Hw(b),context:{findings:b}}}async function qw($,b){let n=await sn($,b.workspaceRoot);if(!n)return[];let A=await Yw($,b.workspaceRoot,n),m=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),y=A.findings.filter((j)=>m.has(j.code)),W=A.findings.filter((j)=>j.code==="tests-without-test-script"),w=A.findings.filter((j)=>j.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:y.length>0?"fail":"pass",message:y.length>0?`${y.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?Hw(y):b.verbose?`Policy: ${wb(b.workspaceRoot)}`:void 0,context:{policyPath:wb(b.workspaceRoot),criticalPackages:A.criticalPackages,findings:y}},Gw("Package Test Scripts",W,new Set,"All tested packages expose a test script"),Gw("Buildable Packages Without Tests",w,new Set,"All buildable packages have tests or explicit test scripts")]}var N9=["src/contracts","contracts","src/specs","specs"];async function r0($,b){let n=[];return n.push(F9(b)),n.push(await v9($,b)),n.push(await g9($,b)),n.push(await P9($,b)),n.push(await r9($,b)),n.push(...await qw($,b)),n}function F9($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",n=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${n}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function v9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let A of n){let m=$.join(A,"package.json");if(await $.exists(m))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function g9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],A=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let W of n)for(let w of N9){let j=$.join(W,w);if(await $.exists(j)){let B=W===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${w}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let m=b.isMonorepo?"src/contracts":"src/contracts",y=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${m}/${y} to organize your specs`,fix:{description:`Create ${m}/ directory${y}`,apply:async()=>{try{let W=$.join(A,"src","contracts");return await $.mkdir(W),{success:!0,message:`Created ${m}/`}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}async function P9($,b){try{let n=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=b.isMonorepo?b.packageRoot:b.workspaceRoot,m=await $.glob({patterns:n,ignore:["node_modules/**","dist/**"],cwd:A});if(m.length>0){let W=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${m.length} contract file(s)${W}`,details:b.verbose?m.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:b.isMonorepo?`No contract files found in package "${b.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function k9($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let A=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.packageRoot,level:"package"}}let n=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(n))return{path:n,root:b.workspaceRoot,level:"workspace"};return null}async function r9($,b){try{let n=await k9($,b);if(!n)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(n.path),m=JSON.parse(A),y=m.outputDir??"./src",W=$.join(n.root,y),w=b.isMonorepo?` (${n.level} level)`:"";if(await $.exists(W))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${y}${w}`,details:b.verbose?`Resolved to: ${W}`:void 0};let B=y==="./src"||y==="src",S=Array.isArray(m.packages)&&m.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||n.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${n.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${y}${w}`,details:b.verbose?`Expected at: ${W}`:void 0,fix:{description:`Create ${y} directory`,apply:async()=>{try{return await $.mkdir(W),{success:!0,message:`Created ${y}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var Ow=["cli","config","mcp","deps","docs","workspace","ai","layers"],Vw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var f9={checks:{runCliChecks:M0,runConfigChecks:N0,runMcpChecks:k0,runDepsChecks:F0,runDocChecks:v0,runWorkspaceChecks:r0,runAiChecks:E0,runLayerChecks:P0},workspace:{findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$}},c9={confirm:async()=>!1,input:async()=>""};async function Jw($,b,n=c9,A=f9){let{fs:m,logger:y}=$,W=b.categories??Ow,{checks:w,workspace:j}=A,B=j.findWorkspaceRoot(b.workspaceRoot),S=j.findPackageRoot(b.workspaceRoot),Q=j.isMonorepo(B),Z=Q?j.getPackageName(S):void 0,X={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${J}`)}let Y=[];for(let J of W){if(b.skipAi&&J==="ai")continue;y.info(`Checking ${Vw[J]}...`);let U=await h9(J,m,X,n,w);for(let H of U){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await n.confirm(`Fix "${H.name}"? ${H.fix.description}`)){y.info(`Applying fix: ${H.fix.description}`);let _=await H.fix.apply();if(_.success)y.info(`✓ ${_.message}`),H.status="pass",H.message=`Fixed: ${_.message}`,H.fix=void 0;else y.warn(`✗ ${_.message}`)}}Y.push(H)}}let G=Y.filter((J)=>J.status==="pass").length,V=Y.filter((J)=>J.status==="warn").length,O=Y.filter((J)=>J.status==="fail").length,K=Y.filter((J)=>J.status==="skip").length;return{checks:Y,passed:G,warnings:V,failures:O,skipped:K,healthy:O===0}}async function h9($,b,n,A,m){switch($){case"cli":return m.runCliChecks(b,n);case"config":return m.runConfigChecks(b,n);case"mcp":return m.runMcpChecks(b,n);case"deps":return m.runDepsChecks(b,n);case"docs":return m.runDocChecks(b,n);case"workspace":return m.runWorkspaceChecks(b,n);case"ai":return m.runAiChecks(b,n,A);case"layers":return m.runLayerChecks(b,n);default:return[]}}function NV($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("✓ All checks passed!");else b.push("✗ Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1934
|
-
`)}function
|
|
1935
|
-
${$.details}`;if($.fix)
|
|
1936
|
-
Fix available: ${$.fix.description}`;return
|
|
1937
|
-
|
|
1938
|
-
${$.body}`;await m.writeFile(w,j)}async function
|
|
1939
|
-
`).length},W,w=new RegExp(Db.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Db.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Db.namedImport);while((W=B.exec($))!==null){let X=W[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(X)for(let Y of X)m(Y,"import",y(W.index))}let S=new RegExp(Db.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Db.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return n}var Cw=["**/*.ts(x)"];async function AA($,b,n={}){let{fs:A}=b,m=n.includePatterns??Cw,y=n.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await A.glob({pattern:w,ignore:y});for(let B of j)try{let S=await A.readFile(B),Z=Rw(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function qJ($,b={}){let{fs:n}=$,A=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of A){let w=await n.glob({pattern:W,ignore:m});for(let j of w)try{let B=await n.readFile(j),S=Rw(B,j);for(let Q of S){let Z=y.get(Q.specKey)??[];Z.push(Q),y.set(Q.specKey,Z)}}catch{}}return y}function ZQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,n){let A=ZQ(b),m=[];if($==="operation")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")m.push({path:`${n}/components/${A}.tsx`,type:"component"}),m.push({path:`${n}/components/${A}.test.tsx`,type:"test"});if($==="form")m.push({path:`${n}/forms/${A}.form.tsx`,type:"form"}),m.push({path:`${n}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});return m}import{Node as p,Project as XQ,SyntaxKind as YQ}from"ts-morph";function Iw($){let b=[],A=new XQ({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),m=(j)=>{if(!p.isObjectLiteralExpression(j))return;let B=j.getProperty("implementations");if(B&&p.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&p.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(p.isObjectLiteralExpression(Q)){let Z,X,Y,G=Q.getProperty("path");if(G&&p.isPropertyAssignment(G)){let K=G.getInitializer();if(p.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&p.isPropertyAssignment(V)){let K=V.getInitializer();if(p.isStringLiteral(K))X=K.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let K=O.getInitializer();if(p.isStringLiteral(K))Y=K.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=A.getDescendantsOfKind(YQ.CallExpression);for(let j of y){let B=j.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=j.getArguments();if(S.length>0&&p.isObjectLiteralExpression(S[0]))return m(S[0]),b}}let W=A.getVariableStatements();for(let j of W)if(j.isExported())for(let B of j.getDeclarations()){let S=B.getInitializer();if(S&&p.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return m(S),b}}let w=A.getExportAssignment((j)=>!j.isExportEquals());if(w){let j=w.getExpression();if(p.isObjectLiteralExpression(j))m(j);else if(p.isAsExpression(j)&&p.isObjectLiteralExpression(j.getExpression()))m(j.getExpression())}return b}function Ew($){if($.length===0)return"missing";let b=$.filter((m)=>m.exists),n=$.filter((m)=>m.type!=="test");if(b.filter((m)=>m.type!=="test").length===0)return"missing";if($.every((m)=>m.exists))return"implemented";return"partial"}function KJ($){let b=$.filter((m)=>m.status==="implemented").length,n=$.filter((m)=>m.status==="partial").length,A=$.filter((m)=>m.status==="missing").length;return{total:$.length,implemented:b,partial:n,missing:A,coverage:$.length>0?Math.round(b/$.length*100):100}}var qQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Mw($){return GQ("sha256").update($).digest("hex")}async function OQ($,b,n,A={},m){let y={...qQ,...A},W=y.computeHashes?Mw($.sourceBlock||""):void 0,w=$.key??HQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,G,V,O)=>{if(Q.has(Y))return;Q.add(Y);let K=await B.exists(Y),J=void 0,U=void 0;if(K&&y.computeHashes)try{J=await B.readFile(Y),U=Mw(J)}catch{}S.push({path:Y,type:G,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:U,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Iw($.sourceBlock);for(let G of Y)await Z(G.path,G.type,"explicit",G.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await AA(w,b,y);for(let G of Y){if(G.filePath===$.filePath)continue;await Z(G.filePath,G.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??n.outputDir??"./src",G=xw($.specType,w,Y);for(let{path:V,type:O}of G)await Z(V,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Ew(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function Tw($,b,n,A={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await OQ(W,b,n,A,m);y.push(w)}catch(w){console.error(`Failed to resolve implementations for ${W}:`,w)}}return y}async function i0($,b,n){let{fs:A}=$,m=[],y=await P(A),W=n.implementation??{},w=b.filter((B)=>B.specType==="operation"),j=await Tw(w,{fs:A},y,{computeHashes:W.useCache??!0});for(let B of j){if(W.requireImplemented&&B.status==="missing")m.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")m.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!W.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);m.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)m.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return m}$$();import{isFeatureFile as UQ,scanAllSpecsFromSource as KQ,scanFeatureSource as _Q}from"@contractspec/module.workspace";function VQ($,b){return`${$}.v${b}`}function t0($,b,n,A,m,y={}){let{treatMissingAsError:W=!0}=y;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let w=[],j=[],B=[];for(let S of A){let Q=VQ(S.key,S.version);if(m.has(Q))w.push(S);else if(j.push(S),W)B.push(`Spec ${b}.v${n} references test ${S.key}.v${S.version} which does not exist`)}return{valid:j.length===0,foundTests:w,missingTests:j,errors:B,specFile:$}}function Dw($,b){return`${$}.v${b}`}function Nw($,b){let n=new Map,A=new Map,m=[],y=[];for(let W of $){if(!W.key||!W.version)continue;let w=Dw(W.key,W.version);if(!W.testTarget){y.push(w);continue}let{type:j,key:B,version:S}=W.testTarget,Q=S??W.version,Z=Dw(B,Q),X=JQ(b,j);if(!X||!X.has(Z)){m.push(w);continue}if(A.set(w,Z),!n.has(Z))n.set(Z,new Set);n.get(Z)?.add(w)}return{targetToTests:n,testToTarget:A,orphanedTests:m,testsWithoutTarget:y}}function JQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function zQ(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function l0($,b){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[b]}async function mA($,b={}){let{fs:n,logger:A}=$;A.info("Starting integrity analysis...",{options:b});let m=await c$(n,{config:b.config,cwd:b.cwd,pattern:b.pattern}),y=zQ(),W=[],w=[];for(let H of m){if((await n.stat(H)).isDirectory)continue;let _=await n.readFile(H);if(UQ(H)){let z=_Q(_,H);W.push(z)}else{let z=KQ(_,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let C=l0(y,L.specType);if(C&&L.key&&L.version!==void 0){let D=n$(L.key,L.version);C.set(D,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let j=b.featureKey?W.filter((H)=>H.key===b.featureKey):W,B=new Set;for(let H of j){for(let q of H.operations){let _=n$(q.key,q.version);if(B.add(`operation:${_}`),!y.operations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let _=n$(q.key,q.version);if(B.add(`event:${_}`),!y.events.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let _=n$(q.key,q.version);if(B.add(`presentation:${_}`),!y.presentations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let _=n$(q.key,q.version);if(B.add(`experiment:${_}`),!y.experiments.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let _=n$(q.key,q.version);if(B.add(`capability:${_}`),!y.capabilities.has(_))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let _=n$(q.key,q.version);B.add(`capability:${_}`)}for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=n$(q.pres.key,q.pres.version);if(!y.operations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let _=n$(q.key,q.version);if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=l0(y,H);if(!q)continue;for(let[_,z]of q)if(!B.has(`${H}:${_}`))S.push(z),w.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of y.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let X=Nw(Z,y);for(let H of j)for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=X.targetToTests.get(_),L=!1,C=!1;if(z)for(let D of z){let F=y.testSpecs.get(D);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)C=!0}}if(!z||!L||!C){let D=[];if(!L)D.push("success scenario");if(!C)D.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${D.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let Y={},G=0;for(let H of Q){let q=l0(y,H);if(!q)continue;let _=q.size,z=0,L=0,C=b.requireTestsFor?.includes(H);for(let[D,F]of q){if(B.has(`${H}:${D}`))z++;if(C){let E=n$(F.key,F.version),r=X.targetToTests.has(E),g=`${F.key}.test`,iA=y.testSpecs.has(n$(g,F.version));if(!r&&!iA)L++,G++,w.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}Y[H]={total:_,covered:z,orphaned:_-z,missingTest:C?L:0}}let V=Object.values(Y).reduce((H,q)=>H+q.total,0),O=Object.values(Y).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:G,byType:Y},U=!w.some((H)=>H.severity==="error");return A.info("Integrity analysis complete",{features:W.length,totalSpecs:V,orphaned:S.length,issues:w.length,healthy:U}),{inventory:y,features:j,coverage:K,issues:w,orphanedSpecs:S,healthy:U}}function hJ($){let b=[];for(let n of Object.values($))for(let A of n.values())b.push(A);return b}function dJ($,b){return $.filter((n)=>n.type===b)}function uJ($,b){return $.filter((n)=>n.severity===b)}async function p0($,b){let n=[],A=await P($.fs),m=await mA($,{config:A,pattern:b.pattern,all:!0});for(let y of m.issues)n.push({ruleId:`integrity-${y.type}`,severity:y.severity==="error"?"error":"warning",message:y.message,category:"integrity",file:y.file,context:{specKey:y.specKey,specType:y.specType,featureKey:y.featureKey,ref:y.ref}});return n}async function a0($,b){let n=[],A=await an($,{});for(let[m,y]of A.inventory.features){if(!y.key)n.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:y.filePath,context:{key:m}});if(!y.owners?.length)n.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${m}' missing 'owners' field`,category:"layers",file:y.filePath,context:{key:m}});if(y.operations.length===0&&y.events.length===0&&y.presentations.length===0)n.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${m}' has no operations, events, or presentations`,category:"layers",file:y.filePath,context:{key:m}})}for(let[m,y]of A.inventory.examples){if(!y.entrypoints.packageName)n.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${m}' missing 'packageName' in entrypoints`,category:"layers",file:y.filePath,context:{key:m}});if(!y.surfaces.templates&&!y.surfaces.sandbox.enabled&&!y.surfaces.studio.enabled&&!y.surfaces.mcp.enabled)n.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${m}' has no enabled surfaces`,category:"layers",file:y.filePath,context:{key:m}})}for(let m of A.inventory.workspaceConfigs.values())if(!m.valid)for(let y of m.errors)n.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${y}`,category:"layers",file:m.file});return n}$$();import{ContractsrcSchema as dQ,DEFAULT_CONTRACTSRC as WA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as LQ}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:n,scan:A=LQ}=$,m=await c$(n,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(zb(w,b.config))continue;if(Lb(w))continue;try{let j=await n.readFile(w),B=A(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function bU($){let b=new Map;for(let n of $){let A=b.get(n.specType)??[];A.push(n),b.set(n.specType,A)}return b}var cw={};f(cw,{toPascalCase:()=>yA,syncPackageDeclarations:()=>rQ,resolvePackageDeclarationConfig:()=>Nb,renderPackageDeclaration:()=>Wm,normalizePath:()=>C$,matchesAllowMissing:()=>ym,inferWorkspacePackageKind:()=>s0,getIndexExportPath:()=>bm,getCanonicalDeclarationRelativePath:()=>$m,discoverWorkspacePackages:()=>gw,createPackageDeclarationIssue:()=>wm,buildPackageTitle:()=>Fb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>G$,buildDomain:()=>Am,buildDeclarationTags:()=>mm,auditPackageDeclarations:()=>vb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>e0,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>Fw});var Fw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},e0={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function Nb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...Fw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function s0($){let b=C$($);for(let[n,A]of Object.entries(e0))if(b.startsWith(n))return A;return null}function $m($,b){switch($){case"libs":case"modules":return`src/${b}.feature.ts`;case"integrations":return"src/integration.ts";case"apps":case"appsRegistry":return"src/blueprint.ts";case"bundles":return`src/bundles/${yA(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function bm($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${yA(b)}Bundle`;case"examples":return"./example"}}function nm($){return C$($).replace(/^packages\//,"").replace(/\//g,".")}function Fb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Am($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function mm($,b,n){return[...new Set([...n,"package",b,$])]}function ym($,b,n){return $.some((A)=>{let m=C$(A);return m===C$(b)||m===n})}function C$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function yA($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function G$($,b){let n=yA(b);switch($){case"feature":return`${n}Feature`;case"integration":return`${n}IntegrationSpec`;case"app-config":return`${n}Blueprint`;case"module-bundle":return`${n}Bundle`;case"example":return`${n}Example`}}import{scanAllSpecsFromSource as RQ,scanSpecSource as CQ}from"@contractspec/module.workspace";var xQ=["packages/libs/*/package.json","packages/modules/*/package.json","packages/integrations/*/package.json","packages/bundles/*/package.json","packages/apps/*/package.json","packages/apps-registry/*/package.json","packages/examples/*/package.json"];async function gw($,b={}){let n=C$(b.workspaceRoot??process.cwd()),A=await IQ($,n,b.config),m=await $.glob({cwd:n,patterns:A,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=Nb(b.config),W=[];for(let w of m){let j=C$($.dirname(w)),B=s0(j);if(!B)continue;let S=await Pw($,$.join(n,w)),Q=$.basename(j),Z=$.join(n,j),X=y.requiredByKind?.[MQ(B)];if(!X)continue;let Y=$m(B,Q);W.push({workspaceRoot:n,relativePackageRoot:j,packageRoot:Z,packageName:typeof S.name==="string"?S.name:j,packageDirName:Q,description:typeof S.description==="string"?S.description:void 0,kind:B,target:X,canonicalDeclarationRelativePath:Y,canonicalDeclarationPath:$.join(Z,Y),indexPath:$.join(Z,"src/index.ts"),indexExportPath:bm(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function vb($,b={}){let n=await gw($,b),A=[];for(let m of n){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=RQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[CQ(j,m.canonicalDeclarationPath)]).find((Q)=>Q.specType!=="unknown")?.specType,w=W===m.target}A.push({...m,exists:y,matchesExpectedTarget:w,detectedSpecType:W})}return A}async function IQ($,b,n){let A=$.join(b,"package.json");if(await $.exists(A)){let m=await Pw($,A),y=EQ(m);if(y.length>0)return y.map((W)=>`${vw(W)}/package.json`)}if(n?.packages?.length)return n.packages.map((m)=>`${vw(m)}/package.json`);return xQ}function EQ($){if(Array.isArray($.workspaces))return $.workspaces.filter((n)=>typeof n==="string");let b=$.workspaces;if(Array.isArray(b?.packages))return b.packages.filter((n)=>typeof n==="string");return[]}function MQ($){return $==="appsRegistry"?"appsRegistry":$}function vw($){return $.replace(/\/+$/,"")}async function Pw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function Wm($){let{pkg:b,refs:n,owners:A,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:Fb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:Am(b.packageDirName),owners:A,tags:mm(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return TQ(b,n,y);case"integration":return DQ(b,n,y);case"app-config":return NQ(b,n,y);case"module-bundle":return rn({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:G$("module-bundle",b.packageDirName)});case"example":return In({key:y.key,version:y.version,description:y.description,title:y.title,domain:y.domain,owners:y.owners,tags:y.tags,stability:y.stability,packageName:b.packageName})}}function TQ($,b,n){let A=[jb("operations",b.operations),jb("events",b.events),jb("presentations",b.presentations),jb("experiments",b.experiments),jb("workflows",b.workflows),jb("dataViews",b.dataViews)].filter(Boolean);return`${$.packageName==="@contractspec/lib.contracts-spec"?"import { defineFeature } from './features';":"import { defineFeature } from '@contractspec/lib.contracts-spec/features';"}
|
|
1940
|
-
|
|
1941
|
-
export const ${
|
|
1942
|
-
meta: ${
|
|
1943
|
-
${
|
|
1964
|
+
`}function y9($){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 W9($){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)+`
|
|
1965
|
+
`}async function Nn($,b){let A=[];return 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.push(await X9($,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 j9($,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 B9($,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 S9($,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 Q9($,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 Z9($,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 X9($,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 Y9}from"node:child_process";import{promisify as H9}from"node:util";var u$=H9(Y9);async function Fn($,b){let A=[];return A.push(await G9(b)),A.push(await q9(b)),A.push(await O9($,b)),A.push(await J9($,b)),A.push(await U9($,b)),A}async function G9($){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 q9($){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 O9($,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 J9($,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 U9($,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 V9,isFeatureFile as K9,scanAllSpecsFromSource as _9,scanExampleSource as z9,scanFeatureSource as L9}from"@contractspec/module.workspace";function R9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function pA($,b={}){let{fs:A,logger:n}=$,m=R9(),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(K9(j)){let S=L9(B,j);m.features.set(S.key,S);continue}if(V9(j)){let S=z9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=_9(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 qJ($){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(I9(m.stats.features)),A.push(C9(m.stats.examples)),A.push(x9(m.inventory.features,n,b)),A.push(M9(m.inventory.examples)),A.push(E9(m.inventory.workspaceConfigs)),A}function I9($){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 C9($){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 x9($,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 M9($){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 E9($){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 T9($,b)),A.push(await D9($,b)),A.push(await N9($,b)),A}async function T9($,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 D9($,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 N9($,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 F9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Yw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function v9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,n])=>{if(typeof n==="string")b[A]=n;return b},{})}function g9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function P9($,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=v9(j.scripts),S=await $.glob({patterns:F9,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:g9(B),testFileCount:S.length,tier:Zw(w,A)})}catch{continue}}return m}function k9($){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 r9($){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 P9($,b,A),m=[];for(let W of n){if(W.tier==="critical")m.push(...k9(W));m.push(...r9(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 f9=["src/contracts","contracts","src/specs","specs"];async function rn($,b){let A=[];return A.push(c9(b)),A.push(await h9($,b)),A.push(await d9($,b)),A.push(await u9($,b)),A.push(await i9($,b)),A.push(...await Ow($,b)),A}function c9($){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 h9($,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 d9($,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 f9){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 u9($,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 o9($,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 i9($,b){try{let A=await o9($,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 l9={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$}},t9={confirm:async()=>!1,input:async()=>""};async function Vw($,b,A=t9,n=l9){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 p9(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(`✓ ${z.message}`),q.status="pass",q.message=`Fixed: ${z.message}`,q.fix=void 0;else y.warn(`✗ ${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 p9($,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 oJ($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("✓ All checks passed!");else b.push("✗ Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1966
|
+
`)}function iJ($){let A=`${$.status==="pass"?"✓":$.status==="warn"?"⚠":$.status==="fail"?"✗":"○"} ${$.name}: ${$.message}`;if($.details)A+=`
|
|
1967
|
+
${$.details}`;if($.fix)A+=`
|
|
1968
|
+
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 ZQ,rm as XQ}from"node:fs/promises";import{tmpdir as YQ}from"node:os";import Nb from"path";import{DEFAULT_CONTRACTSRC as mQ}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as yQ}from"@contractspec/module.workspace";import WQ from"path";import{packageDocBlocks as a9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as e9,convertSpecToDocBlock as s9,extractModuleDocData as $Q,loadSpecFromSource as bQ,scanAllSpecsFromSource as AQ,scanSpecSource as nQ}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=AQ(S,B);if(Q.length>0)w.push(...Q);else{let Z=nQ(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 bQ(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=s9(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 nU($,b){return(await Lw($,b)).map(({entry:n})=>n.block)}function mU($,b){return a9(e9({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=$Q(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. -->
|
|
1969
|
+
|
|
1970
|
+
${$.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??jQ(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=WQ.join(BQ(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??mQ,{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 yQ($.specType)}function jQ($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${dn($)}/**/*.ts`:void 0}function BQ($,b){let A=(b?.connect?.policy?.generatedPaths??[]).map(QQ).filter(Boolean);if(A.length>0)return A[0];if(b?.outputDir&&b.outputDir!=="./src")return dn(b.outputDir);return $}function SQ($){return dn($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function QQ($){let b=SQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function dn($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function $0($,b,A,n={}){let m=await ZQ(Nb.join(YQ(),"contractspec-drift-"));try{await Rw($,b,m,n.rootPath,n.generation);let y=[],W=await import("node: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 XQ(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 HQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function GQ($){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=HQ(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=`${GQ(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 KQ}from"crypto";import _Q 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},qQ={".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 OQ($){let b=$.toLowerCase();for(let[A,n]of Object.entries(qQ))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:OQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1971
|
+
`).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 xU($,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 JQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,A){let n=JQ(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 UQ,SyntaxKind as VQ}from"ts-morph";function Mw($){let b=[],n=new UQ({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(VQ.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 NU($){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 zQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Tw($){return KQ("sha256").update($).digest("hex")}async function LQ($,b,A,n={},m){let y={...zQ,...n},W=y.computeHashes?Tw($.sourceBlock||""):void 0,w=$.key??_Q.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 LQ(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 CQ,scanAllSpecsFromSource as xQ,scanFeatureSource as MQ}from"@contractspec/module.workspace";function RQ($,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=RQ(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=IQ(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 IQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function EQ(){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=EQ(),W=[],w=[];for(let q of m){if((await A.stat(q)).isDirectory)continue;let z=await A.readFile(q);if(CQ(q)){let _=MQ(z,q);W.push(_)}else{let _=xQ(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 bV($){let b=[];for(let A of Object.values($))for(let n of A.values())b.push(n);return b}function AV($,b){return $.filter((A)=>A.type===b)}function nV($,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 aQ,DEFAULT_CONTRACTSRC as y0}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as TQ}from"@contractspec/module.workspace";async function B$($,b={}){let{fs:A,scan:n=TQ}=$,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 XV($){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:()=>iQ,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 DQ,scanSpecSource as NQ}from"@contractspec/module.workspace";var FQ=["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 vQ($,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?.[PQ(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=DQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[NQ(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 vQ($,b,A){let n=$.join(b,"package.json");if(await $.exists(n)){let m=await kw($,n),y=gQ(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 FQ}function gQ($){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 PQ($){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 kQ(b,A,y);case"integration":return rQ(b,A,y);case"app-config":return fQ(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 kQ($,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';"}
|
|
1972
|
+
|
|
1973
|
+
export const ${H$("feature",$.packageDirName)} = defineFeature({
|
|
1974
|
+
meta: ${cQ(A)},
|
|
1975
|
+
${n.length>0?`${n.join(`
|
|
1944
1976
|
`)}
|
|
1945
1977
|
`:""}});
|
|
1946
|
-
`}function
|
|
1978
|
+
`}function rQ($,b,A){let n=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1947
1979
|
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1948
1980
|
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1949
1981
|
|
|
1950
|
-
const ${
|
|
1951
|
-
name: '${
|
|
1982
|
+
const ${H$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1983
|
+
name: '${gb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1952
1984
|
description: 'Managed configuration for ${$.packageName}.',
|
|
1953
1985
|
fields: {},
|
|
1954
1986
|
});
|
|
1955
1987
|
|
|
1956
|
-
const ${
|
|
1957
|
-
name: '${
|
|
1988
|
+
const ${H$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1989
|
+
name: '${gb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1958
1990
|
description: 'Secret material for ${$.packageName}.',
|
|
1959
1991
|
fields: {},
|
|
1960
1992
|
});
|
|
1961
1993
|
|
|
1962
|
-
export const ${
|
|
1994
|
+
export const ${H$("integration",$.packageDirName)} = defineIntegration({
|
|
1963
1995
|
meta: {
|
|
1964
|
-
...${
|
|
1996
|
+
...${fw(A)},
|
|
1965
1997
|
category: 'custom',
|
|
1966
1998
|
},
|
|
1967
1999
|
supportedModes: ['managed'],
|
|
1968
2000
|
capabilities: {
|
|
1969
2001
|
provides: [
|
|
1970
|
-
${
|
|
2002
|
+
${n||" // Add capability refs here"}
|
|
1971
2003
|
],
|
|
1972
2004
|
},
|
|
1973
|
-
configSchema: { schema: ${
|
|
1974
|
-
secretSchema: { schema: ${
|
|
2005
|
+
configSchema: { schema: ${H$("integration",$.packageDirName)}Config, example: {} },
|
|
2006
|
+
secretSchema: { schema: ${H$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1975
2007
|
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1976
2008
|
});
|
|
1977
|
-
`}function
|
|
1978
|
-
`),m=
|
|
2009
|
+
`}function fQ($,b,A){let n=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
2010
|
+
`),m=rw(b.workflows),y=rw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1979
2011
|
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1980
2012
|
|
|
1981
|
-
export const ${
|
|
2013
|
+
export const ${H$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1982
2014
|
meta: {
|
|
1983
|
-
...${
|
|
2015
|
+
...${fw(A)},
|
|
1984
2016
|
appId: '${Q$($.packageDirName)}',
|
|
1985
2017
|
},
|
|
1986
2018
|
capabilities: {
|
|
1987
2019
|
enabled: [
|
|
1988
2020
|
${W||" // Add capability refs here"}
|
|
1989
2021
|
],
|
|
1990
|
-
},${
|
|
2022
|
+
},${n?`
|
|
1991
2023
|
features: {
|
|
1992
2024
|
include: [
|
|
1993
|
-
${
|
|
2025
|
+
${n}
|
|
1994
2026
|
],
|
|
1995
2027
|
},`:""}${y?`
|
|
1996
2028
|
dataViews: {
|
|
@@ -2000,14 +2032,14 @@ ${y}
|
|
|
2000
2032
|
${m}
|
|
2001
2033
|
},`:""}
|
|
2002
2034
|
});
|
|
2003
|
-
`}function
|
|
2004
|
-
${b.map((
|
|
2035
|
+
`}function Sb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2036
|
+
${b.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
2005
2037
|
`)}
|
|
2006
|
-
],`}function
|
|
2038
|
+
],`}function rw($){return $.map((b,A)=>` ${A===0?"primary":`item${A+1}`}: {
|
|
2007
2039
|
key: '${b.key}',
|
|
2008
2040
|
version: '${b.version}',
|
|
2009
2041
|
},`).join(`
|
|
2010
|
-
`)}function
|
|
2042
|
+
`)}function cQ($){return`{
|
|
2011
2043
|
key: '${$.key}',
|
|
2012
2044
|
version: '${$.version}',
|
|
2013
2045
|
title: '${Q$($.title)}',
|
|
@@ -2016,13 +2048,13 @@ ${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
|
2016
2048
|
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2017
2049
|
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
2050
|
stability: '${$.stability}',
|
|
2019
|
-
}`}function
|
|
2020
|
-
`);let B=await
|
|
2051
|
+
}`}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 hQ}from"@contractspec/module.workspace";var dQ={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 uQ($){return $.packageName!=="@contractspec/lib.schema"}function oQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function iQ($,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 lQ($,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()}
|
|
2052
|
+
`);let B=await tQ($,W,b.dryRun,uQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await pQ($,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 lQ($,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=hQ(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 tQ($,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()}
|
|
2021
2053
|
${m}
|
|
2022
|
-
`.trimStart(),!
|
|
2023
|
-
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function
|
|
2024
|
-
`).map((n)=>n.trim()).filter((n)=>n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")&&!n.startsWith("*/"));return b.length>0&&b.every((n)=>n.startsWith("import ")||n.startsWith("export *")||n.startsWith("export {")||n.startsWith("export type {")||n==="'use client';"||n==='"use client";'||n==="'use server';"||n==='"use server";')}function b4($){if(!$)return WA;let b=dQ.safeParse($),n=b.success?b.data:{};return{...WA,...n,conventions:{...WA.conventions,...n.conventions??{}},ci:{...WA.ci,...n.ci??{}}}}async function jm($,b){let{fs:n,logger:A}=$,m=[],y=b.config?b4(b.config):await P(n),W=Nb(y),w=await j$({fs:n},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>hw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await n.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!sQ(Q,j,y))continue;try{let Z=await n.readFile(Q);if($4(Z))continue;let X=hw(Q);if(!(X!==null&&aQ.test(X)&&B.has(X))&&!iQ.test(Z))continue;if(oQ.test(Z))continue;m.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:Q})}catch(Z){A.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await vb(n,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=wm(Z,W.allowMissing??[]);m.push({ruleId:"policy-package-declaration",severity:X.allowlisted||W.severity==="warning"?"warning":"error",message:X.message,category:"policy",file:Z.canonicalDeclarationPath,context:{allowlisted:X.allowlisted,expectedTarget:Z.target,packageName:Z.packageName,packageRoot:Z.relativePackageRoot}})}}return m}import{validateSpecStructure as n4}from"@contractspec/module.workspace";async function Bm($){let b=[];for(let n of $){let A=n4(n);for(let m of A.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:m,category:"structure",file:n.filePath});for(let m of A.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:m,category:"structure",file:n.filePath})}return b}async function Sm($){let b=[],n=new Map,A=new Map;for(let m of $){if(!m.key||!m.version)continue;if(m.specType==="test-spec"){let y=`${m.key}.v${m.version}`;n.set(y,{key:m.key,version:m.version,file:m.filePath,type:"test-spec"})}if(m.testRefs&&m.testRefs.length>0){if(!A.has(m.filePath))A.set(m.filePath,[]);A.get(m.filePath)?.push({key:m.key,version:m.version,testRefs:m.testRefs})}}for(let[m,y]of A)for(let W of y){if(!W.testRefs)continue;let w=t0(m,W.key,W.version,W.testRefs,n,{treatMissingAsError:!0});for(let j of w.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:j,category:"test-refs",file:m,context:{specKey:W.key,specVersion:W.version,missingTests:w.missingTests}})}return b}$$();async function Qm($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkTests:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"test-missing",severity:"warning",message:w,category:"tests",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"test-warning",severity:"warning",message:w,category:"tests",file:y.filePath})}return A}function e($,b,n){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},m=b.filter((w)=>w.severity==="error").length,y=b.filter((w)=>w.severity==="warning").length,W=b.filter((w)=>w.severity==="note").length;return{category:$,label:A[$],errors:m,warnings:y,notes:W,passed:m===0,durationMs:n}}async function dw($){try{if(!await $.exists(".git/HEAD"))return{};let n=await $.readFile(".git/HEAD"),A=n.match(/^ref: (.+)$/m);if(A){let y=A[1]?.replace("refs/heads/",""),W=`.git/${A[1]}`;if(await $.exists(W))return{commitSha:(await $.readFile(W)).trim(),branch:y};return{branch:y}}return{commitSha:n.trim()}}catch{return{}}}function uw($){let b=$.config?.ci?.checks,n=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)n.push("handlers");if($.checkTests)n.push("tests");if($.implementation)n.push("implementation");if($.checkDrift)n.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return n.filter((A)=>!$.skip?.includes(A));return n}async function bK($,b={}){let n=Date.now(),{fs:A,logger:m}=$,y=[],W=[],w=uw(b);m.info("Starting CI checks...",{checks:w});let j=await P(A),B=await cn($,{config:j,pattern:b.pattern});if(w.includes("structure")){let V=Date.now(),O=await Bm(B);y.push(...O),W.push(e("structure",O,Date.now()-V))}if(w.includes("integrity")){let V=Date.now(),O=await p0($,b);y.push(...O),W.push(e("integrity",O,Date.now()-V))}if(w.includes("deps")){let V=Date.now(),O=await x0($,b);y.push(...O),W.push(e("deps",O,Date.now()-V))}if(w.includes("doctor")){let V=Date.now(),O=await f0($,b);y.push(...O),W.push(e("doctor",O,Date.now()-V))}if(w.includes("docs")){let V=Date.now(),O=await I0($,b);y.push(...O),W.push(e("docs",O,Date.now()-V))}if(w.includes("policy")){let V=Date.now(),O=await jm($,b);y.push(...O),W.push(e("policy",O,Date.now()-V))}if(w.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await o0($,B);y.push(...O),W.push(e("handlers",O,Date.now()-V))}if(w.includes("tests")||b.checkTests){let V=Date.now(),O=await Qm($,B);y.push(...O),W.push(e("tests",O,Date.now()-V))}if(w.includes("test-refs")){let V=Date.now(),O=await Sm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-V))}if(w.includes("coverage")){let V=Date.now(),O=await C0($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-V))}if(w.includes("implementation")){let V=Date.now(),O=await i0($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-V))}if(w.includes("layers")){let V=Date.now(),O=await a0($,b);y.push(...O),W.push(e("layers",O,Date.now()-V))}if(w.includes("drift")){let V=Date.now(),O=await u0($,b);y.push(...O),W.push(e("drift",O,Date.now()-V))}let S=y.filter((V)=>V.severity==="error").length,Q=y.filter((V)=>V.severity==="warning").length,Z=y.filter((V)=>V.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await dw(A),G={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:G.durationMs}),G}var AK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],mK={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function BK($,b={}){let{fs:n,logger:A}=$,m=(b.outputDir??"./src").replace(/\\/g,"/"),y=["generated/**","dist/**",".turbo/**"],W=[`${m}/handlers/**/*.handler.ts`,`${m}/handlers/**/*.handler.test.ts`,`${m}/components/**/*.tsx`,`${m}/components/**/*.test.tsx`,`${m}/forms/**/*.form.tsx`,`${m}/forms/**/*.form.test.tsx`,`${m}/**/*.runner.ts`,`${m}/**/*.renderer.tsx`],w=b.generatedOnly?[...y,...W]:[...y,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...W],j=await n.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await n.stat(Q),X=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&X<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)A.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await n.remove(Q),A.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}$$();var Vj={};f(Vj,{writeReviewPacket:()=>Rm,writeDecisionEnvelope:()=>db,withBranch:()=>o$,verifyConnectMutation:()=>B6,resolveWorkspace:()=>i,resolveStoragePaths:()=>X$,replayConnectDecision:()=>f4,persistLatestArtifacts:()=>zm,persistDecisionArtifacts:()=>hb,normalizeEvalInput:()=>T4,matchConfiguredPath:()=>gb,loadStoredDecision:()=>ub,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>c4,isReviewCommand:()=>Zm,isDeniedCommand:()=>Xm,isAllowedCommand:()=>jA,initConnectWorkspace:()=>g4,inferSurfaces:()=>rb,evaluateConnectDecision:()=>E4,ensureStorage:()=>cb,defaultActor:()=>kb,decisionArtifactRefs:()=>Sb,createConnectControlPlaneRuntime:()=>e4,connectVerdictToPolicy:()=>I$,configuredThreshold:()=>u$,compileConnectPlanPacket:()=>ob,buildConnectContextPack:()=>fb,assessConnectPolicy:()=>Pb,assertConnectEnabled:()=>A$,artifactRef:()=>_$,appendAuditRecord:()=>Lm,analyzeConnectImpact:()=>i$,CONTROL_PLANE_TRACE_GET_REF:()=>BA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>SA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>qm,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Hm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>U$,AGENT_APPROVALS_REF:()=>QA,ACP_TERMINAL_EXEC_REF:()=>W4,ACP_FS_ACCESS_REF:()=>y4});import A4 from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function gb($,b,n){if(!n||n.length===0)return!1;let A=b.replaceAll("\\","/");return A4.isMatch(A,n,{contains:!0})}function u$($,b,n){return $.config.connect?.policy?.reviewThresholds?.[b]??n}function jA($,b){return Ym($.config.connect?.commands?.allow,b)}function Zm($,b){return Ym($.config.connect?.commands?.review,b)}function Xm($,b){return Ym($.config.connect?.commands?.deny,b)}function Ym($,b){if(!$||$.length===0)return!1;return $.some((n)=>b===n||b.startsWith(`${n} `))}function iw($,b){if(b.length===0)return{state:"none"};for(let A of b)if(Xm($,A))return{commandMatch:A,state:"deny"};for(let A of b)if(Zm($,A))return{commandMatch:A,state:"review"};if(b.every((A)=>jA($,A)))return{state:"allow"};let n=b.find(m4);if(n)return{commandMatch:n,state:"destructive"};return{commandMatch:b.find((A)=>!jA($,A)),state:"unknown"}}function m4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return ow(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return ow(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function ow($,b){return b.every((n)=>$.includes(n)||$.includes(n.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Hm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},BA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},SA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},U$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},y4={key:"acp.fs.access",version:"1.0.0",kind:"command"},W4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},QA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Pb($,b){let n=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.immutablePaths)),A=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=iw($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=w4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(n),protectedPath:Boolean(A),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=j4({breakingChange:b.impactAnalysis.breakingChange,commandMatch:y,commandState:W,contractDrift:j,protectedPath:A,unknownPaths:b.impactAnalysis.unknownPaths}),Q=I$(B);return{commandMatch:y,commandState:W,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:m,immutablePath:n,protectedPath:A,requiredApprovals:Q.requiresApproval?[{capability:U$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function I$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function w4($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(u$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(u$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(u$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(u$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(u$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(B4)[0]??"permit"}function j4($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function B4($,b){return tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as x4}from"crypto";var sw={};f(sw,{formatPrComment:()=>lw,formatMinimalComment:()=>Om,formatJson:()=>aw,formatCheckRun:()=>pw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>G4});function lw($,b={template:"detailed"}){let n=[];if(n.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),n.push(""),$.hasBreaking)n.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)n.push("⚠️ **Contract changed (non-breaking)**");else n.push("✅ **No contract impact**");if(n.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(n.push("### Summary"),n.push(""),n.push("| Type | Count |"),n.push("|------|-------|"),$.summary.breaking>0)n.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)n.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)n.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)n.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)n.push(`| ➖ Removed | ${$.summary.removed} |`);n.push("")}if(b.template==="detailed"&&$.deltas.length>0){n.push("### Changes"),n.push("");let A=$.deltas.filter((y)=>y.severity==="breaking"),m=$.deltas.filter((y)=>y.severity==="non_breaking");if(A.length>0){n.push("#### \uD83D\uDD34 Breaking Changes"),n.push("");for(let y of A)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}if(m.length>0){n.push("#### \uD83D\uDFE1 Non-breaking Changes"),n.push("");for(let y of m)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}}if($.addedSpecs.length>0){n.push("### Added Specs"),n.push("");for(let A of $.addedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if($.removedSpecs.length>0){n.push("### Removed Specs"),n.push("");for(let A of $.removedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if(b.drift)if(b.drift.hasDrift){n.push("### ⚠️ Drift Detected"),n.push(""),n.push("The following generated files are out of sync with their specs:"),n.push("");for(let A of b.drift.files)n.push(`- \`${A}\``);n.push(""),n.push("Run `contractspec generate` to regenerate artifacts."),n.push("")}else n.push("### ✅ No Drift Detected"),n.push("");return n.push("---"),n.push(`*Generated by ContractSpec at ${$.timestamp}*`),n.join(`
|
|
2025
|
-
`)}function
|
|
2054
|
+
`.trimStart(),!A)await $.writeFile(b.indexPath,W);return!0}async function pQ($,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 dQ[b.target]){if(!oQ(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")}
|
|
2055
|
+
`);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 eQ=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,sQ=/@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?)?['"]/,$4=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,b4=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,A4=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,n4=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,m4=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function W0($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function y4($,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 W4($,b,A){let n=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(n))return!1;if(n.includes("/node_modules/")||n.includes("/dist/")||A4.test(n)||b4.test(n)||n.endsWith(".d.ts")||n.endsWith(".test.ts")||n.endsWith(".spec.ts"))return!1;if(b.has(n))return!1;if(y4(n,A))return!1;return eQ.test(n)}function dw($){return $.replaceAll("\\","/").match(n4)?.[1]??null}function w4($){let b=$.split(`
|
|
2056
|
+
`).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 j4($){if(!$)return y0;let b=aQ.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?j4(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(!W4(Q,j,y))continue;try{let Z=await A.readFile(Q);if(w4(Z))continue;let X=dw(Q);if(!(X!==null&&m4.test(X)&&B.has(X))&&!$4.test(Z))continue;if(sQ.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 B4}from"@contractspec/module.workspace";async function Sm($){let b=[];for(let A of $){let n=B4(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 XK($,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 HK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],GK={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 VK($,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:()=>G6,resolveWorkspace:()=>l,resolveStoragePaths:()=>X$,replayConnectDecision:()=>l4,persistLatestArtifacts:()=>Lm,persistDecisionArtifacts:()=>ub,normalizeEvalInput:()=>k4,matchConfiguredPath:()=>kb,loadStoredDecision:()=>ib,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>t4,isReviewCommand:()=>Xm,isDeniedCommand:()=>Ym,isAllowedCommand:()=>w0,initConnectWorkspace:()=>d4,inferSurfaces:()=>cb,evaluateConnectDecision:()=>g4,ensureStorage:()=>db,defaultActor:()=>fb,decisionArtifactRefs:()=>Zb,createConnectControlPlaneRuntime:()=>y6,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:()=>X4,ACP_FS_ACCESS_REF:()=>Z4});import S4 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 S4.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(Q4);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((n)=>!w0($,n)),state:"unknown"}}function Q4($){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"},Z4={key:"acp.fs.access",version:"1.0.0",kind:"command"},X4={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=Y4({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=H4({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 Y4($){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(G4)[0]??"permit"}function H4($){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 G4($,b){return tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as F4}from"crypto";var $j={};f($j,{formatPrComment:()=>pw,formatMinimalComment:()=>Jm,formatJson:()=>ew,formatCheckRun:()=>aw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>K4});function pw($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)A.push("⚠️ **Contract changed (non-breaking)**");else A.push("✅ **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| ➖ Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let 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("### ⚠️ 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("### ✅ No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
2057
|
+
`)}function Jm($){if($.hasBreaking)return`❌ **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`⚠️ **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"✅ **No contract impact**"}function 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 q4,computeIoDiff as O4,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 J4(A,w,y),B=sw(j),S;if(b.baseline){let X=await U4(A,n,w,b.baseline,y);S=sw(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=V4(S.specs,B.specs),Z=q4(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 J4($,b,A){let n=[];for(let m of b){let y=await $.readFile(m);n.push({path:m,content:y})}return n}async function U4($,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 V4($,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=O4(w.io,W.io);A.push(...j)}}return A}var K4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
2026
2058
|
# Contract Impact Detection
|
|
2027
2059
|
|
|
2028
2060
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -2068,49 +2100,49 @@ The system consists of three layers:
|
|
|
2068
2100
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
2069
2101
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
2070
2102
|
3. **Integrations**: CLI command + GitHub Action
|
|
2071
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
2072
|
-
`;await $.writeFile(b.auditFile,`${
|
|
2073
|
-
`)}async function
|
|
2074
|
-
`);if(
|
|
2103
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as Aj,readFileSync as nj}from"node:fs";import{basename as _4,join as Um,resolve as z4}from"node:path";import{ContractsrcSchema as L4,DEFAULT_CONTRACTSRC as R4}from"@contractspec/lib.contracts-spec/workspace-config";function l($={}){let b=z4($.cwd??process.cwd()),A=$.workspaceRoot??x(b),n=$.packageRoot??c(b),m=$.config??I4(A,n),y=C4(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 I4($,b){let A={...R4};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=L4.safeParse(n);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function C4($,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 _4(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)=>x4($.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 M4($,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 x4($,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:D4(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 M4($,b,A){let n=E4($.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 E4($,b,A){let n=(b.config.connect?.policy?.generatedPaths??[]).map(N4).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=T4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function T4($,b,A){if(b&&A.startsWith(b))return b;return $.basename(A)==="docs"?y$($.dirname(A)):A}function D4($,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 N4($){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 v4($,A.workspaceRoot,b),y=await l$($,{baseline:b.baseline,touchedPaths:m,workspace:A}),W=A.config.connect?.canonPacks??[];return{id:`connect.ctx_${F4()}`,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 v4($,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"node: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)}
|
|
2104
|
+
`;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)}
|
|
2105
|
+
`)}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 g4($,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=P4(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 P4($,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 k4($){return $}import{DEFAULT_CONTRACTSRC as h4}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=r4(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 r4($,b){let A=f4(b),n=c4(),m=$.replace(/\r\n/g,`
|
|
2106
|
+
`);if(n.test(m))return m.replace(n,A);if(m.trim().length===0)return A;return`${m.endsWith(`
|
|
2075
2107
|
`)?m:`${m}
|
|
2076
2108
|
`}
|
|
2077
|
-
${
|
|
2109
|
+
${A}`}function f4($){return`# contractspec:init:gitignore:start
|
|
2078
2110
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
2079
|
-
${
|
|
2111
|
+
${Sj($).join(`
|
|
2080
2112
|
`)}
|
|
2081
2113
|
# contractspec:init:gitignore:end
|
|
2082
|
-
`}function
|
|
2083
|
-
`).trimEnd()}function Bj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function g4($,b={}){let n=i(b),A=b.scope==="package"?n.packageRoot:n.workspaceRoot,m=$.join(A,".contractsrc.json"),y={connect:{...v4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=b$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,N(S)),W="merged"}else await $.writeFile(m,N(y));let w=X$(i({...b,workspaceRoot:A,packageRoot:A}));await cb($,w);let j=await ZA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ib.connect,Ib.verificationCache],prompts:b.prompts,root:n.workspaceRoot});return{configPath:m,targetRoot:A,action:W,gitignore:j}}import{randomUUID as XA}from"crypto";async function ob($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let{commands:A,touchedPaths:m}=P4(b.candidate),y=await fb($,{...b,paths:m}),W=kb(b.taskId,b.actor),w=k4(b.candidate.steps,b.candidate),j=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),B=Pb(n,{commands:A,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${XA()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:n.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:r4(m.length,A.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:Hm,planVerify:qm,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function P4($){let b=new Set($.touchedPaths??[]),n=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let m of A.paths??[])b.add(m);for(let m of A.commands??[])n.add(m)}return{commands:[...n],touchedPaths:[...b]}}function k4($,b){if(!$||$.length===0)return[{id:`step_${XA()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((n)=>typeof n==="string"?{id:`step_${XA()}`,summary:n}:{id:`step_${XA()}`,summary:n.summary,paths:n.paths,commands:n.commands,contractRefs:n.contractRefs})}function r4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function f4($,b,n){let A=i(b);A$(A);let m=X$(A),y=await ub($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=n&&(W.decisionId||W.traceId)?await n.getExecutionTrace(W):null,j=n&&w?await n.replayExecutionTrace(W):null;return{decisionId:b.decisionId,historyDir:y.historyDir,contextPack:y.contextPack,planPacket:y.planPacket,patchVerdict:y.patchVerdict,reviewPacket:y.reviewPacket,trace:w??void 0,replay:j??void 0,source:w?"local+control-plane":"local"}}async function c4($,b={}){let n=i(b);return A$(n),Cm($.fs,X$(n))}import{buildChannelPlanTrace as h4,compileChannelPlan as d4,finalizeChannelPlan as u4,replayExecutionTrace as o4,resolveChannelExecutionActor as i4}from"@contractspec/integration.runtime/channel";import{createHash as t4}from"crypto";var ib="connect.local",l4="connect.runtime-link.v1",p4="connect.adapter.v1",a4="connect-control-plane-bridge";function e4($){return{linkDecision:async({connectDecisionId:b,createdAt:n,input:A,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(n),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:A.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:ib,externalEventId:b,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:n6(y.objective,A)},metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`}),rawPayload:j},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:A6(j),traceId:B.traceId});if(S.duplicate)return s4($.store,W.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:w}),Z=i4(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:b6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=d4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=u4({plan:X,decision:$6(m),approvalTimeoutMs:900000,now:w}),G=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:Y.policy?.verdict??"blocked",riskTier:Y.policy?.riskTier??"blocked",confidence:Y.policy?.confidence??0.5,modelName:a4,promptVersion:l4,policyVersion:p4,toolTrace:h4(Y),actionPlan:Y,requiresApproval:Y.approval.required,approvalStatus:Y.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:Y.approval.required?"pending":"processed",decisionId:G.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:ib,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,tool:A.tool})}),{approvalStatus:G.approvalStatus,decisionId:G.id,planId:Y.id,providerKey:ib,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Sj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let n=await Sj($.traceService,b);return n?o4(n):null}}}async function s4($,b,n){let m=(await $.listDecisions({externalEventId:n,limit:1,providerKey:ib,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:ib,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Sj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function $6($){let b=I$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((n)=>`${n.status}:${n.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function b6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function n6($,b){return`${$} [${b.tool}]`}function A6($){return t4("sha256").update($).digest("hex")}function Qj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as j6}from"crypto";async function Zj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let n=m6(b);if(!n)return{};let A=await Jb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:n,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:n==="ui"?y6(b):void 0,query:xm(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:A.verdict==="permit"?"pass":A.verdict==="rewrite"?"warn":"fail",detail:A.reason},reason:A.reason,remediation:A.selected!=null?[`Prefer ${A.selected.candidate.source} candidate ${A.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:A,verdict:A.verdict}}function m6($){let b=xm($).toLowerCase();if(/\b(contract|operation|event|spec|presentation|form)\b/.test(b))return"contracts";if(/\b(integration|provider|sdk|adapter|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render)\b/.test(b))return"runtime";if(/\b(component|ui|screen|view|page|tsx|jsx)\b/.test(b))return"ui";if(/\b(module|bundle|example|template)\b/.test(b))return"solutions";if(/\b(logger|schema|testing|observability|identity|utility|shared|lib)\b/.test(b))return"sharedLibs";return null}function xm($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function y6($){let b=xm($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function Xj($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as W6}from"crypto";function Yj($,b,n){let A=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:n?`Generated path: ${n}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||n?"warn":"pass",detail:A}}function Gj($,b){let n=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:n,detail:A}}function Hj($,b,n){return{id:"impact-analysis",status:$?"fail":b||n?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":n?"Impact could not be resolved.":"Impact resolved."}}function qj($,b,n,A,m,y){let W=y.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${y.runtimeLink.decisionId}`:y.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${y.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${W6()}`,sourceDecisionId:b,objective:A.objective,reason:y.reason,summary:{paths:m,impactedContracts:n.impactedContracts,affectedSurfaces:n.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:y.artifactRefs.contextPack},{type:"plan-packet",ref:y.artifactRefs.planPacket},{type:"patch-verdict",ref:y.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:W}],requiredApprovals:[{capability:U$.key,reason:y.reason}],controlPlane:{traceQuery:BA,policyExplain:SA,approvalStatus:y.runtimeLink?.approvalStatus,decisionId:y.runtimeLink?.decisionId,traceId:y.runtimeLink?.traceId??n.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Im($,b,n,A,m,y,W,w,j){let B=I$(W);return{decisionId:$,summary:A.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:m,checks:y,verdict:W,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:j?.approvalStatus,decisionId:j?.decisionId,traceId:j?.traceId??n.actor.traceId},approvalOperationRefs:W==="require_review"?[`${U$.key}@${U$.version}`,`${QA.key}@${QA.version}`]:void 0,remediation:w6(W),reviewPacketRef:w,replay:{traceQuery:BA,policyExplain:SA}}}function w6($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function B6($,b,n={}){let A=i(b);A$(A),A=o$(A,await $.git.currentBranch());let m=`connect.dec_${j6()}`,y=(n.now??(()=>new Date))().toISOString(),W=X$(A);await cb($.fs,W);let{contextPack:w,planPacket:j}=await ob($,{...b,candidate:Z6(b)}),B=X6(b),S=await i$($,{baseline:b.baseline,touchedPaths:B,workspace:A}),Q=await Y6(n,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=Pb(A,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await Zj($,b),G=[Yj(X.immutablePath,X.protectedPath,X.generatedPath),Gj(X.commandState,X.commandMatch),Hj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],V=S6(X,Y.verdict),O=I$(V),K=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:U$.key,reason:K}]:[],U={...j,requiredApprovals:J,verificationStatus:O.verificationStatus},H=Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((r)=>({file:r.path,contracts:r.contracts,policies:r.policies,surfaces:r.surfaces})):B.map((r)=>({file:r,contracts:w.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:w.affectedSurfaces})),_=Im(m,b,w,U,q,G,V,void 0),z=n.controlPlane?await n.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:_,planPacket:U,workspace:A}):null,L=z?{...j,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:z.decisionId,traceId:z.traceId??j.controlPlane.traceId}}:U,C=V==="require_review"?qj(A,m,w,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,D=Im(m,b,w,L,q,G,V,C?_$($.fs,A,$.fs.join(W.reviewPacketsDir,`${C.id}.json`)):void 0,z);if(Y.remediation?.length)D.remediation=Y.remediation;if(await zm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:D}),C)await Rm($.fs,W,C);let F=await hb($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C}),E={artifacts:Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(C)}),connectDecisionId:m,createdAt:y,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await db($.fs,W,m,E),await Lm($.fs,W,Xj({contextPack:w,createdAt:y,envelope:E,reviewPacket:C,verifyInput:b,workspace:A})),{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C,historyDir:F}}function S6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return Q6($.verdict,b)}function Q6($,b){if(!b)return $;return Oj($)<=Oj(b)?$:b}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Z6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function X6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function Y6($,b,n){if(!$.runCommand)return[];let A=[];for(let m of b){let y=await $.runCommand(m,{cwd:n});A.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return A}HA();var Tm={};f(Tm,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});HA();class Uj{ai;templates=Tm;constructor($){this.ai=new GA($)}}function wz($){return new Uj($)}import{scanSpecSource as z6}from"@contractspec/module.workspace";function Kj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Xz($,b,n={}){let{fs:A,logger:m}=b,y=await A.exists($);if(!y&&!n.force)return{specPath:$,specInfo:Kj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let W=Kj($),w;if(y)try{let B=await A.readFile($);W=z6(B,$),w=W.key}catch{}let j=[];if(n.clean&&w)try{let B=await AA(w,{fs:A});for(let S of B)try{await A.remove(S.filePath),j.push(S.filePath),m.info(`Removed artifact: ${S.filePath}`)}catch{m.warn(`Could not remove artifact: ${S.filePath}`)}}catch{m.warn("Could not discover implementations for cleanup")}if(y)await A.remove($),m.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:W,deleted:!0,cleanedFiles:j,errors:[]}}import{computeSemanticDiff as L6}from"@contractspec/module.workspace";async function Hz($,b,n,A={}){let{fs:m,git:y}=n;if(!await m.exists($))throw Error(`Spec file not found: ${$}`);let w=await m.readFile($),j,B;if(A.baseline)j=await y.showFile(A.baseline,$),B=`${A.baseline}:${$}`;else{if(!await m.exists(b))throw Error(`Spec file not found: ${b}`);j=await m.readFile(b),B=b}let S=L6(w,$,j,B,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:B,differences:S}}$$();import{openApiForRegistry as R6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Dm}from"@contractspec/lib.contracts-spec/operations";async function C6($,b){let{fs:n,logger:A}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;A.info("Loading registry...",{registryPath:m});let W=await x6(m,n);A.info("Generating OpenAPI document...");let w=R6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2084
|
-
`,B=
|
|
2114
|
+
`}function c4(){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,`
|
|
2115
|
+
`).trimEnd()}function Sj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function d4($,b={}){let A=l(b),n=b.scope==="package"?A.packageRoot:A.workspaceRoot,m=$.join(n,".contractsrc.json"),y={connect:{...h4.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}=u4(b.candidate),y=await hb($,{...b,paths:m}),W=fb(b.taskId,b.actor),w=o4(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:i4(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 u4($){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 o4($,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 i4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function l4($,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 t4($,b={}){let A=l(b);return m$(A),Cm($.fs,X$(A))}import{buildChannelPlanTrace as p4,compileChannelPlan as a4,finalizeChannelPlan as e4,replayExecutionTrace as s4,resolveChannelExecutionActor as $6}from"@contractspec/integration.runtime/channel";import{createHash as b6}from"crypto";var tb="connect.local",A6="connect.runtime-link.v1",n6="connect.adapter.v1",m6="connect-control-plane-bridge";function y6($){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:B6(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:S6(j),traceId:B.traceId});if(S.duplicate)return W6($.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=$6(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:j6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=a4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=e4({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:m6,promptVersion:A6,policyVersion:n6,toolTrace:p4(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?s4(A):null}}}async function W6($,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 j6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function B6($,b){return`${$} [${b.tool}]`}function S6($){return b6("sha256").update($).digest("hex")}function Zj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as H6}from"crypto";async function Xj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=Q6(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"?Z6(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 Q6($){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 Z6($){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 X6}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_${X6()}`,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:Y6(W),reviewPacketRef:w,replay:{traceQuery:j0,policyExplain:B0}}}function Y6($){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 G6($,b,A={}){let n=l(b);m$(n),n=i$(n,await $.git.currentBranch());let m=`connect.dec_${H6()}`,y=(A.now??(()=>new Date))().toISOString(),W=X$(n);await db($.fs,W);let{contextPack:w,planPacket:j}=await lb($,{...b,candidate:J6(b)}),B=U6(b),S=await l$($,{baseline:b.baseline,touchedPaths:B,workspace:n}),Q=await V6(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=q6(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 q6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return O6($.verdict,b)}function O6($,b){if(!b)return $;return Jj($)<=Jj(b)?$:b}function Jj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function J6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function U6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function V6($,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 Jz($){return new Kj($)}import{scanSpecSource as E6}from"@contractspec/module.workspace";function _j($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Lz($,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=E6(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 T6}from"@contractspec/module.workspace";async function Cz($,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=T6(w,$,j,B,{breakingOnly:n.breakingOnly});return{spec1:$,spec2:B,differences:S}}b$();import{openApiForRegistry as D6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Nm}from"@contractspec/lib.contracts-spec/operations";async function N6($,b){let{fs:A,logger:n}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;n.info("Loading registry...",{registryPath:m});let W=await F6(m,A);n.info("Generating OpenAPI document...");let w=D6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2116
|
+
`,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 F6($,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 v6,parseOpenApi as g6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Fm,dirname as zj,join as Xb}from"path";function P6($,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 g6(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=v6(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=P6(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=`/**
|
|
2085
2117
|
* Auto-generated registry file.
|
|
2086
2118
|
*/
|
|
2087
|
-
`;
|
|
2119
|
+
`;K.forEach((M)=>{let r=`./${Fm(M.file,".ts")}`;L+=`import { ${M.name} } from '${r}';
|
|
2088
2120
|
`}),L+=`
|
|
2089
|
-
`;let
|
|
2121
|
+
`;let I=!1;if(G)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
2090
2122
|
|
|
2091
2123
|
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
2092
|
-
`,
|
|
2093
|
-
`}),
|
|
2124
|
+
`,K.forEach((M)=>{L+=`operationRegistry.register(${M.name});
|
|
2125
|
+
`}),I=!0;else if(z)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
2094
2126
|
|
|
2095
2127
|
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2096
|
-
`,
|
|
2097
|
-
`}),
|
|
2128
|
+
`,K.forEach((M)=>{L+=`eventRegistry.register(${M.name});
|
|
2129
|
+
`}),I=!0;else if(_)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
2098
2130
|
|
|
2099
2131
|
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2100
|
-
`,
|
|
2101
|
-
`}),
|
|
2132
|
+
`,K.forEach((M)=>{L+=`modelRegistry.register(${M.name});
|
|
2133
|
+
`}),I=!0;if(I){let M=Xb(U,"registry.ts");await n.writeFile(M,L),m.info(`Created/Updated registry: ${M}`)}let E=`/**
|
|
2102
2134
|
* Auto-generated barrel file.
|
|
2103
2135
|
*/
|
|
2104
2136
|
|
|
2105
|
-
`;if(
|
|
2106
|
-
`}),
|
|
2107
|
-
`;let
|
|
2108
|
-
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function
|
|
2137
|
+
`;if(K.forEach((M)=>{let r=`./${Fm(M.file,".ts")}`;E+=`export * from '${r}';
|
|
2138
|
+
`}),I)E+=`export * from './registry';
|
|
2139
|
+
`;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 k6,parseOpenApi as r6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as f6,join as c6}from"path";async function fz($,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 r6(Y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});m.info(`Parsed ${H.operations.length} operations from ${X.name}`);let J=k6(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=c6(S,O.fileName);if(!await n.exists(V)){if(!B){let K=f6(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 h6}from"@contractspec/lib.contracts-transformers/openapi";async function dz($,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 h6(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 $L($,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:()=>o6,getArrayNameForSpecType:()=>Rj,detectFeatureContext:()=>d6,computeAddSpecEdit:()=>u6});function d6($,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 u6($,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=`
|
|
2140
|
+
{ 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 o6($,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:()=>i6,FixService:()=>Mj,FIX_STRATEGY_STABILITY:()=>bA,FIX_STRATEGY_LABELS:()=>s6,CiOutputSchema:()=>S7});function i6($,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}\`:
|
|
2109
2141
|
|
|
2110
2142
|
> ${$.message}
|
|
2111
2143
|
|
|
2112
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
2113
|
-
`)}function
|
|
2144
|
+
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 $7 from"node: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(`,
|
|
2145
|
+
`)}function ab($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"Spec",n=E$($,{kind:"'api'"});return`/**
|
|
2114
2146
|
* Capability: ${$.key}
|
|
2115
2147
|
*
|
|
2116
2148
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2121,9 +2153,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",labe
|
|
|
2121
2153
|
|
|
2122
2154
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
2123
2155
|
|
|
2124
|
-
export const ${
|
|
2156
|
+
export const ${A} = defineCapability({
|
|
2125
2157
|
meta: {
|
|
2126
|
-
${
|
|
2158
|
+
${n}
|
|
2127
2159
|
},
|
|
2128
2160
|
|
|
2129
2161
|
provides: [
|
|
@@ -2147,7 +2179,7 @@ export const ${n} = defineCapability({
|
|
|
2147
2179
|
// }
|
|
2148
2180
|
],
|
|
2149
2181
|
});
|
|
2150
|
-
`}function
|
|
2182
|
+
`}function eb($){let b=$.key.split(".").pop()||"Unknown",A=M$(b)+"EventSpec",n=A.replace("Spec","Payload"),m=E$($);return`/**
|
|
2151
2183
|
* Event: ${$.key}
|
|
2152
2184
|
*
|
|
2153
2185
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2160,8 +2192,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
2160
2192
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2161
2193
|
|
|
2162
2194
|
// TODO: Define event payload schema
|
|
2163
|
-
export const ${
|
|
2164
|
-
name: '${
|
|
2195
|
+
export const ${n} = new SchemaModel({
|
|
2196
|
+
name: '${n}',
|
|
2165
2197
|
description: 'Payload for ${$.key} event',
|
|
2166
2198
|
fields: {
|
|
2167
2199
|
// Add your payload fields here
|
|
@@ -2171,12 +2203,12 @@ export const ${A} = new SchemaModel({
|
|
|
2171
2203
|
},
|
|
2172
2204
|
});
|
|
2173
2205
|
|
|
2174
|
-
export const ${
|
|
2206
|
+
export const ${A} = defineEvent({
|
|
2175
2207
|
meta: {
|
|
2176
2208
|
${m}
|
|
2177
2209
|
},
|
|
2178
2210
|
|
|
2179
|
-
payload: ${
|
|
2211
|
+
payload: ${n},
|
|
2180
2212
|
|
|
2181
2213
|
// TODO: Specify PII fields if any
|
|
2182
2214
|
// piiFields: ['user.email'],
|
|
@@ -2187,7 +2219,7 @@ export const ${n} = defineEvent({
|
|
|
2187
2219
|
// policy: 'archive',
|
|
2188
2220
|
// },
|
|
2189
2221
|
});
|
|
2190
|
-
`}function
|
|
2222
|
+
`}function l6($){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=l6($.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`/**
|
|
2191
2223
|
* Operation: ${$.key}
|
|
2192
2224
|
*
|
|
2193
2225
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2200,8 +2232,8 @@ import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
|
2200
2232
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
2201
2233
|
|
|
2202
2234
|
// TODO: Define input schema
|
|
2203
|
-
export const ${
|
|
2204
|
-
name: '${
|
|
2235
|
+
export const ${n} = new SchemaModel({
|
|
2236
|
+
name: '${n}',
|
|
2205
2237
|
description: 'Input for ${$.key}',
|
|
2206
2238
|
fields: {
|
|
2207
2239
|
// Add your input fields here
|
|
@@ -2219,13 +2251,13 @@ export const ${m} = new SchemaModel({
|
|
|
2219
2251
|
},
|
|
2220
2252
|
});
|
|
2221
2253
|
|
|
2222
|
-
export const ${
|
|
2254
|
+
export const ${A} = ${W}({
|
|
2223
2255
|
meta: {
|
|
2224
2256
|
${B}
|
|
2225
2257
|
},
|
|
2226
2258
|
|
|
2227
2259
|
io: {
|
|
2228
|
-
input: ${
|
|
2260
|
+
input: ${n},
|
|
2229
2261
|
output: ${m},
|
|
2230
2262
|
errors: {
|
|
2231
2263
|
// TODO: Define possible errors
|
|
@@ -2265,7 +2297,7 @@ export const ${n} = ${W}({
|
|
|
2265
2297
|
examples: [],
|
|
2266
2298
|
},
|
|
2267
2299
|
});
|
|
2268
|
-
`}function
|
|
2300
|
+
`}function t6($){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=t6($.key),m=E$($);return`/**
|
|
2269
2301
|
* Presentation: ${$.key}
|
|
2270
2302
|
*
|
|
2271
2303
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -2276,12 +2308,12 @@ export const ${n} = ${W}({
|
|
|
2276
2308
|
|
|
2277
2309
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
2278
2310
|
|
|
2279
|
-
export const ${
|
|
2311
|
+
export const ${A} = definePresentation({
|
|
2280
2312
|
meta: {
|
|
2281
2313
|
${m}
|
|
2282
2314
|
},
|
|
2283
2315
|
|
|
2284
|
-
kind: '${
|
|
2316
|
+
kind: '${n}',
|
|
2285
2317
|
|
|
2286
2318
|
// TODO: Define content structure
|
|
2287
2319
|
content: {
|
|
@@ -2305,7 +2337,7 @@ export const ${n} = definePresentation({
|
|
|
2305
2337
|
// focusable: true,
|
|
2306
2338
|
// },
|
|
2307
2339
|
});
|
|
2308
|
-
`}import H$ from"node:path";function qA($,b){if(b.outputDir)return Fm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let n=h6($.featureFile);if(n)return Fm(n,$.ref.key,$.specType)}return Fm(H$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function h6($){let b=H$.dirname($),n=H$.parse($).root,A=0;while(b!==n&&A<50){if(H$.basename(b)==="src")return b;b=H$.dirname(b),A++}b=H$.dirname($),A=0;while(b!==n&&A<50)b=H$.dirname(b),A++;let m=$.lastIndexOf(`${H$.sep}src${H$.sep}`);if(m!==-1)return $.substring(0,m+5);return null}function Fm($,b,n){let A=b.replace(/\./g,"-").toLowerCase(),m=d6(n),y=u6(n);return H$.join($,y,`${A}${m}`)}function d6($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function u6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var o6={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},sb={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function OA($,b,n){let{fs:A,logger:m}=n,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:sb["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await t6(j,b,m)}catch(X){m.warn("AI enrichment failed, falling back to skeleton",{error:X instanceof Error?X.message:String(X)})}else m.info("No AI config provided, using skeleton with experimental stability");let S=a6(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=qA($,b),Z=[];if(!b.dryRun){let X=i6.dirname(Q);await A.mkdir(X),await A.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(j){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}async function t6($,b,n){if(n.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:m}=await Promise.resolve().then(() => (HA(),Jj)),y=l6(b),W=new m(y),w=$.specType==="operation"?"command":$.specType,j=`${Cj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await W.generateOperationSpec(j,w);return{...$,description:B.description,enrichment:{goal:B.goal,context:B.context,owners:B.owners,tags:B.tags}}}if($.specType==="event"){let B=await W.generateEventSpec(j);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(m){n.warn("AIGenerator call failed, falling back to heuristics",{error:m instanceof Error?m.message:String(m)})}let A=p6($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function l6($){let b=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[b?.provider??"openai"]??"openai",aiModel:b?.model??"gpt-4-turbo",customApiKey:b?.apiKey??"",customEndpoint:b?.endpoint??""}}function p6($,b){let n=$.split("."),A=n[0]||"unknown",m=n.slice(1).join(" ").replace(/_/g," "),y=[A],W=m.toLowerCase().split(" "),j=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>W.some((S)=>S.includes(B)));return{description:`${Cj(b)} for ${A} ${m}`,goal:`Enable ${m} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...y,...j]}}function a6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import e6 from"node:path";async function VA($,b,n){let{fs:A}=n,{ref:m,specType:y,featureKey:W}=$;try{let w={key:m.key,version:m.version,specType:y,stability:sb["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=s6(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=qA($,b),S=[];if(!b.dryRun){let Q=e6.dirname(B);await A.mkdir(Q),await A.writeFile(B,j),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function s6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}async function JA($,b,n){let{fs:A}=n,{ref:m,featureFile:y,specType:W}=$;try{let w=await A.readFile(y),j=w,B=$7(w,m,W);if(B===w)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${m.key}.v${m.version} in ${y}`};let S=[];if(!b.dryRun)await A.writeFile(y,B),S.push({path:y,action:"modified",previousContent:j});else S.push({path:y,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function $7($,b,n){if(!b7(n))return $;let m=xj(b.key),y=xj(b.version),W=[new RegExp(`\\{\\s*key:\\s*['"]${m}['"],\\s*version:\\s*['"]${y}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${y}['"],\\s*key:\\s*['"]${m}['"]\\s*\\},?\\s*`,"g")],w=$;for(let j of W)w=w.replace(j,"");return w=n7(w),w}function b7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n7($){return $.replace(/,(\s*)\]/g,"$1]")}class Ij{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,n)=>JA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,n)=>VA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,n)=>OA(b,n,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let n=this.strategies.get(b.strategy);if(!n)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),n.fix($,b)}async batchFix($){let b=[],n=0,A=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)n++;else A++}catch(y){A++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:n,failed:A,results:b}}async scanAndGetFixables($={}){return(await mA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((n)=>this.getToFix(n)).filter((n)=>n!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let n=this.parseFixableIssue($);if(!n)return null;return{...n,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:n,preferAi:A,select:m}=b;if(n)return Promise.resolve(n);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof m==="function")return m($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as Zb}from"zod";var A7=Zb.union([Zb.array(Zb.unknown()),Zb.object({issues:Zb.array(Zb.unknown())}).transform(($)=>$.issues)]);import{exec as m7}from"node:child_process";import{promisify as y7}from"node:util";var W7=y7(m7),Mj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function fL($,b,n={}){if($.length===0)return;let A=n.cwd??process.cwd(),m=Mj[n.type??"biome"]??Mj.biome,y=50;for(let W=0;W<$.length;W+=y){let j=$.slice(W,W+y).map((B)=>`"${B}"`).join(" ");try{await W7(`${m} ${j}`,{cwd:A})}catch(B){}}}import T$ from"path";async function uL($,b){let n=T$.join(b,"contracts"),A=T$.join(b,"generated"),m=T$.join(A,"docs"),y=await $.fs.exists(n),W=await $.fs.exists(A);if(!y)return{hasContracts:!1,hasGenerated:W,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let w=await j$($,{pattern:"contracts/**/*.ts"}),j=[];if(W)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts"),G=T$.join(m,`${Y}.md`);if(!await $.fs.exists(G))j.push(Y)}else if(w.length>0)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts");j.push(Y)}let B=T$.join(n,"index.ts"),S=T$.join(n,"registry.ts"),Q=w.length>0&&!await $.fs.exists(B),Z=w.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:W,missingDocs:j,missingIndex:Q,missingRegistry:Z,totalSpecs:w.length}}var Fj={};f(Fj,{runHook:()=>Tj,getAvailableHooks:()=>Dj});import{exec as w7}from"node:child_process";import{promisify as j7}from"node:util";var B7=j7(w7);async function Tj($,b){let{fs:n,logger:A}=$,{hookName:m,dryRun:y=!1}=b,W=I(b.workspaceRoot);A.info(`Running hook: ${m}`,{workspaceRoot:W,dryRun:y});let w=await Nj(n,W);if(!w)return{hookName:m,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let j=w[m];if(!j||j.length===0)return{hookName:m,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${m}`};A.info(`Found ${j.length} command(s) for ${m}`);let B=[],S=!0;for(let Z of j){if(y){A.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${Z}`);try{let{stdout:X,stderr:Y}=await B7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),A.info(`✓ ${Z}`)}catch(X){S=!1;let Y=X;B.push({command:Z,success:!1,exitCode:Y.code??1,stdout:Y.stdout??"",stderr:Y.stderr??Y.message??String(X)}),A.error(`✗ ${Z}`,{exitCode:Y.code,stderr:Y.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:m,success:S,commandResults:B,totalCommands:j.length,successfulCommands:Q,summary:S?`✓ All ${j.length} command(s) passed`:`✗ ${Q}/${j.length} command(s) passed`}}async function Dj($,b){let n=await Nj($.fs,b);return n?Object.keys(n):[]}async function Nj($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return null;try{let A=await $.readFile(n);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as S7,extractFromProject as Q7}from"@contractspec/lib.source-extractors";import{generateOperations as Z7,generateRegistry as X7,generateSchemas as Y7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as G7}from"@contractspec/lib.source-extractors/extractors";import{dirname as H7,join as vm}from"path";async function q7($,b,n,A){let{fs:m,logger:y}=n,W=A??process.cwd();G7(),y.info(`Scanning source code in ${W}...`);let w={readFile:(U)=>m.readFile(U),glob:(U,H)=>m.glob({pattern:U,cwd:H?.cwd}),exists:(U)=>m.exists(U)},j=await S7(W,{readFile:(U)=>m.readFile(U),glob:(U)=>m.glob({pattern:U})});if(j.frameworks.length===0)return y.warn("No supported frameworks detected"),{success:!1,report:O7(),errors:["No supported frameworks detected in project"]};y.info(`Detected frameworks: ${j.frameworks.map((U)=>U.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let U of B.getAll())if("setFs"in U&&typeof U.setFs==="function")U.setFs(w);let S={scope:b.scope,framework:b.framework},Q=await Q7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:V7(Q.errors??[]),errors:Q.errors?.map((U)=>U.message)};let Z=Q.ir;if(y.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:J7(Z)};let X=b.outputDir??vm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},G=Z7(Z,Y),V=Y7(Z,Y),O=X7(G),K=[...G,...V,O];if(!b.dryRun)for(let U of K){let H=vm(X,U.path),q=H7(H);if(!await m.exists(q))await m.mkdir(q);await m.writeFile(H,U.content),y.info(`Created: ${H}`)}else for(let U of K)y.info(`[DRY RUN] Would create: ${vm(X,U.path)}`);let J={files:K,operationsGenerated:G.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:U7(Z,J,b)}}function O7(){return`# Import Report
|
|
2340
|
+
`}import G$ from"node:path";function G0($,b){if(b.outputDir)return vm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=p6($.featureFile);if(A)return vm(A,$.ref.key,$.specType)}return vm(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function p6($){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=a6(A),y=e6(A);return G$.join($,y,`${n}${m}`)}function a6($){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 e6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var s6={"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 b7(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=m7(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=$7.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 b7($,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=A7(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=n7($.key,$.specType);return{...$,description:n.description,enrichment:{goal:n.goal,context:n.context,owners:["@team"],tags:n.tags}}}function A7($){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 n7($,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 m7($){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 y7 from"node: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=W7(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=y7.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 W7($){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(!j7(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=B7(w),w}function j7($){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 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 S7=Yb.union([Yb.array(Yb.unknown()),Yb.object({issues:Yb.array(Yb.unknown())}).transform(($)=>$.issues)]);import{exec as Q7}from"node:child_process";import{promisify as Z7}from"node:util";var X7=Z7(Q7),Tj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function sL($,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 X7(`${m} ${j}`,{cwd:n})}catch(B){}}}import T$ from"path";async function nR($,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 Y7}from"node:child_process";import{promisify as H7}from"node:util";var G7=H7(Y7);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 G7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),n.info(`✓ ${Z}`)}catch(X){S=!1;let Y=X;B.push({command:Z,success:!1,exitCode:Y.code??1,stdout:Y.stdout??"",stderr:Y.stderr??Y.message??String(X)}),n.error(`✗ ${Z}`,{exitCode:Y.code,stderr:Y.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:m,success:S,commandResults:B,totalCommands:j.length,successfulCommands:Q,summary:S?`✓ All ${j.length} command(s) passed`:`✗ ${Q}/${j.length} command(s) passed`}}async function 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 q7,extractFromProject as O7}from"@contractspec/lib.source-extractors";import{generateOperations as J7,generateRegistry as U7,generateSchemas as V7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as K7}from"@contractspec/lib.source-extractors/extractors";import{dirname as _7,join as gm}from"path";async function z7($,b,A,n){let{fs:m,logger:y}=A,W=n??process.cwd();K7(),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 q7(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:L7(),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 O7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:R7(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:I7(Z)};let X=b.outputDir??gm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},H=J7(Z,Y),J=V7(Z,Y),O=U7(H),V=[...H,...J,O];if(!b.dryRun)for(let K of V){let q=gm(X,K.path),G=_7(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:C7(Z,U,b)}}function L7(){return`# Import Report
|
|
2309
2341
|
|
|
2310
2342
|
## ❌ No Supported Frameworks Detected
|
|
2311
2343
|
|
|
@@ -2322,13 +2354,13 @@ No supported frameworks were detected in the project.
|
|
|
2322
2354
|
- Next.js API Routes
|
|
2323
2355
|
|
|
2324
2356
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
2325
|
-
`}function
|
|
2357
|
+
`}function R7($){return`# Import Report
|
|
2326
2358
|
|
|
2327
2359
|
## ❌ Extraction Failed
|
|
2328
2360
|
|
|
2329
2361
|
${$.map((b)=>`- ${b.message}`).join(`
|
|
2330
2362
|
`)}
|
|
2331
|
-
`}function
|
|
2363
|
+
`}function I7($){return`# Import Analysis Report
|
|
2332
2364
|
|
|
2333
2365
|
## Summary
|
|
2334
2366
|
|
|
@@ -2360,7 +2392,7 @@ ${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).jo
|
|
|
2360
2392
|
|
|
2361
2393
|
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
2362
2394
|
`):"None"}
|
|
2363
|
-
`}function
|
|
2395
|
+
`}function C7($,b,A){return`# Import Report${A.dryRun?" (Dry Run)":""}
|
|
2364
2396
|
|
|
2365
2397
|
## ✅ Import Successful
|
|
2366
2398
|
|
|
@@ -2386,42 +2418,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
|
2386
2418
|
|
|
2387
2419
|
### Next Steps
|
|
2388
2420
|
|
|
2389
|
-
1. Review generated contracts in \`${
|
|
2421
|
+
1. Review generated contracts in \`${A.outputDir??"generated/"}\`
|
|
2390
2422
|
2. Fill in TODO placeholders with business context
|
|
2391
2423
|
3. Run \`contractspec validate\` to verify contracts
|
|
2392
2424
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
2393
|
-
`}function
|
|
2394
|
-
`)}function
|
|
2395
|
-
`)}async function
|
|
2396
|
-
`)}function
|
|
2397
|
-
`)}function
|
|
2398
|
-
`)}function
|
|
2399
|
-
`);
|
|
2400
|
-
`)}function
|
|
2401
|
-
`)}async function
|
|
2425
|
+
`}function x7($,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"?"❌":W.severity==="warning"?"⚠️":"ℹ️";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(`
|
|
2426
|
+
`)}function M7($,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(` • ${n.name}`);if(A.push(""),b)A.push("✅ Verification"),A.push(` Valid: ${b.summary.validEndpoints}`),A.push(` Warnings: ${b.summary.warningEndpoints}`),A.push(` Errors: ${b.summary.errorEndpoints}`),A.push("");return A.join(`
|
|
2427
|
+
`)}async function E7($,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=T7(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 T7($,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 RR($,b="feature-map",A={}){switch(b){case"feature-map":return rm($,A);case"orphans":return D7($,A);case"dependencies":return N7($,A);case"full":return F7($,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(`
|
|
2428
|
+
`)}function D7($,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(`
|
|
2429
|
+
`)}function N7($,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(`
|
|
2430
|
+
`)}function F7($,b){let A=rm($,b);if($.orphanedSpecs.length===0)return A;let n=A.split(`
|
|
2431
|
+
`);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(`
|
|
2432
|
+
`)}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 v7,specToMarkdown as D$}from"@contractspec/module.workspace";function CR($,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 xR($,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(`- ❌ **${W.category}**: ${W.message}`);A.push("")}if(m.length>0){A.push("## Warnings"),A.push("");for(let W of m)A.push(`- ⚠️ **${W.category}**: ${W.message}`);A.push("")}if(y.length>0){A.push("## Info"),A.push("");for(let W of y)A.push(`- ℹ️ **${W.category}**: ${W.message}`);A.push("")}return A.join(`
|
|
2433
|
+
`)}async function DR($,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 v7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){A.push(`
|
|
2402
2434
|
## Operations (${$.operations.length})
|
|
2403
|
-
`);for(let y of $.operations){let W=await m(y);if(W)
|
|
2435
|
+
`);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})
|
|
2404
2436
|
|
|
2405
|
-
*Spec not found*`);
|
|
2437
|
+
*Spec not found*`);A.push("---")}}if($.events?.length){A.push(`
|
|
2406
2438
|
## Events (${$.events.length})
|
|
2407
|
-
`);for(let y of $.events){let W=await m(y);if(W)
|
|
2439
|
+
`);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})
|
|
2408
2440
|
|
|
2409
|
-
*Spec not found*`);
|
|
2441
|
+
*Spec not found*`);A.push("---")}}if($.presentations?.length){A.push(`
|
|
2410
2442
|
## Presentations (${$.presentations.length})
|
|
2411
|
-
`);for(let y of $.presentations){let W=await m(y);if(W)
|
|
2412
|
-
|
|
2413
|
-
*Spec not found*`);
|
|
2414
|
-
`)}function
|
|
2415
|
-
`)}function
|
|
2416
|
-
`)}function
|
|
2417
|
-
`)}function
|
|
2418
|
-
`)}function
|
|
2419
|
-
`)}import{RegeneratorService as
|
|
2443
|
+
`);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})
|
|
2444
|
+
|
|
2445
|
+
*Spec not found*`);A.push("---")}}return A.join(`
|
|
2446
|
+
`)}function g7($,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(`
|
|
2447
|
+
`)}function P7($){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(`
|
|
2448
|
+
`)}function NR($,b,A="generic-mcp"){switch(b){case"guide":return g7($,A);case"rules":return P7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as k7}from"node:fs/promises";import{createRequire as r7}from"node:module";import{dirname as f7,resolve as Pj}from"node:path";import{pathToFileURL as c7}from"node:url";import gj from"node:vm";import fm from"typescript";async function W$($,b={}){let A=Pj(process.cwd(),$),n=b.runtime??u7();try{let m=n==="bun"?await h7(A):await d7(A);return{modulePath:A,exports:m}}catch(m){throw Error(rj(A,m))}}async function hR($,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 h7($){return await import(c7($).href)}async function d7($){return await o7($)??{}}function u7(){return typeof globalThis.Bun<"u"?"bun":"node"}var dR={formatModuleLoadError:rj,resolveAuthoredModuleValue:fj};async function o7($){let b=await k7($,"utf-8"),A=fm.transpileModule(b,{compilerOptions:{module:fm.ModuleKind.CommonJS,target:fm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),n={},m={exports:n},y=r7($),W=gj.createContext({module:m,exports:n,require:y,__dirname:f7($),__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:()=>nZ,buildOnboardingPlan:()=>AZ,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:i7($),humanGuide:t7($)}}function i7($){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(...l7(A.track,A.reason));return b.join(`
|
|
2449
|
+
`)}function l7($,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 t7($){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(...p7(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(`
|
|
2450
|
+
`)}function p7($,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 a7}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as e7}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as s7}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function cj($,b,A,n){let m=a7({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 e7(s7($Z(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 bZ($,b.flatMap((A)=>A.track.connectSurfaces))}function $Z($){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 bZ($,b){return[...new Set([...$,...b])].sort()}async function AZ($,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=mZ(["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 nZ($,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 mZ($){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)"}],yZ=[...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:yZ}function im($){return $.filter((b)=>!b.dev)}function lm($){return $.filter((b)=>b.dev)}import{exec as WZ}from"node:child_process";import{promisify as wZ}from"node:util";var jZ=wZ(WZ),BZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function XI($,b,A=BZ){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 jZ(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 YI($,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 HI($){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(` • ${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(` • ${y.name} - ${y.description}`)}return A.join(`
|
|
2451
|
+
`)}import{RegeneratorService as SZ}from"@contractspec/lib.contracts-spec/regenerator";function KI($){return new SZ({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 zI($,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 LI($,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 RI($,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 QZ{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=ZZ(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}
|
|
2420
2452
|
${b.note}
|
|
2421
|
-
${
|
|
2453
|
+
${A}
|
|
2422
2454
|
${b.endMarker}
|
|
2423
|
-
`}function
|
|
2424
|
-
`).trimEnd()}function yZ($){return new RegExp(`${lj($.startMarker)}[\\s\\S]*?${lj($.endMarker)}(?:\\r?\\n)?`)}function lj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var WZ="<!-- contractspec:init:agents:start -->",wZ="<!-- contractspec:init:agents:end -->",jZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",pj={endMarker:wZ,note:jZ,startMarker:WZ};async function pm($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"AGENTS.md");try{let y=await $.exists(m),W=Bw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:m,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(m,zA(w,W,pj,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,$n(W,pj)),{target:"agents-md",filePath:m,action:"created",message:"Created AI agent guide"}}catch(y){return{target:"agents-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}import{generateArtifactsForAudience as BZ,generateBiomePreset as SZ}from"@contractspec/biome-config";async function am($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"biome.jsonc"),y=$.join(A,".contractspec","biome"),W=$.join(y,"plugins"),w=$.join(y,"ai"),j=BZ("consumer");try{let B=await $.exists(m);if(B&&b.interactive){if(!await n.confirm(`${m} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:m,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(W),await $.mkdir(w),await $.writeFile(m,SZ("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(j.plugins))await $.writeFile($.join(W,S),Q);return await $.writeFile($.join(w,"consumer.md"),j.aiRules),{target:"biome-config",filePath:m,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:m,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function em($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".contractsrc.json");try{let y=await $.exists(m),W=Wb(b);if(y){let w=await $.readFile(m),j=a(w);if(!j)return{target:"cli-config",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=b$(j,W);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof W==="object"&&W!==null){let S={};if("connect"in W)S.connect=W.connect;if("builder"in W)S.builder=W.builder;await $.writeFile(m,N(D0(B,S)))}else await $.writeFile(m,N(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,N(W)),{target:"cli-config",filePath:m,action:"created",message:"Created CLI configuration"}}catch(y){return{target:"cli-config",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function sm($,b,n){let A=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(A,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=jw(b);if(W)if(b.interactive){if(!await n.confirm(`${m} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:m,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:m,action:"skipped",message:"File already exists"};return await $.writeFile(m,w),{target:"cursor-rules",filePath:m,action:W?"merged":"created",message:W?"Updated Cursor rules":"Created Cursor rules"}}catch(y){return{target:"cursor-rules",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function $y($,b,n){let A=ln();try{let m=await $.exists(A),y=ww();if(b.interactive){if(!await n.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(A),B=a(j);if(!B)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let S=b$(B,y);return await $.writeFile(A,N(S)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(A,N(y)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:A,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function by($,b,n){let A=$.join(b.workspaceRoot,".cursor"),m=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=Mb();if(W){let j=await $.readFile(m),B=a(j);if(!B)return{target:"mcp-cursor",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=b$(B,w);return await $.writeFile(m,N(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,N(w)),{target:"mcp-cursor",filePath:m,action:"created",message:"Created Cursor MCP configuration"}}catch(y){return{target:"mcp-cursor",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}var QZ="<!-- contractspec:init:usage:start -->",ZZ="<!-- contractspec:init:usage:end -->",XZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:ZZ,note:XZ,startMarker:QZ};async function ny($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"USAGE.md");try{let y=await $.exists(m),W=Sw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:m,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(m,zA(w,W,aj,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,$n(W,aj)),{target:"usage-md",filePath:m,action:"created",message:"Created usage guide"}}catch(y){return{target:"usage-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function Ay($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=tn(b);if(w){let B=await $.readFile(y),S=a(B);if(!S)return{target:"vscode-settings",filePath:y,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=b$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,N(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,N(j)),{target:"vscode-settings",filePath:y,action:"created",message:"Created VS Code settings"}}catch(W){return{target:"vscode-settings",filePath:y,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var YZ={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((n)=>n.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((n)=>n.selected!==!1).map((n)=>n.value),input:async($,b)=>b??""},GZ={"agents-md":pm,"biome-config":am,"cli-config":em,"cursor-rules":sm,"mcp-claude":$y,"mcp-cursor":by,"usage-md":ny,"vscode-settings":Ay},HZ={findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$};async function bx($,b,n=YZ,A={}){let m=[],y=b.targets.length>0?b.targets:xb,W={...HZ,...A.workspace},w={...GZ,...A.targets},j=A.setupGitignore??ZA,B=b.workspaceRoot,S=W.findWorkspaceRoot(B),Q=b.packageRoot??W.findPackageRoot(B),Z=b.isMonorepo??W.isMonorepo(S),X=b.packageName??(Z?W.getPackageName(Q):void 0),Y=await ej($,[Q,S]),G=b.preset??Eb(Y);if(b.interactive&&!b.preset)G=await n.select("Select initialization preset:",$w.map((g)=>({value:g,label:bw[g],description:nw[g],selected:g===G})));let V=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)V=await n.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${X??Q})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${S})`,description:"Create config files at the workspace root"}]);let K=Z&&V==="package"?Q:S,J=await ej($,[K]),U={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:V,packageName:X,preset:G,builderApiBaseUrl:b.builderApiBaseUrl??J?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??J?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??J?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??J?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??J?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??J?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??J?.connect?.studio?.queue},H=Aw(G,y);if(b.interactive)H=await n.multiSelect("Select components to configure:",xb.map((g)=>({value:g,label:sW[g],selected:H.includes(g)})));let q=U.projectName;if(b.interactive&&!q){let g=V==="package"&&X?X:K.split("/").pop()??"my-project";q=await n.input("Project name:",g)}let _=U.builderApiBaseUrl;if(b.interactive&&G.startsWith("builder-"))_=await n.input("Builder API base URL:",_??"https://api.contractspec.io");let{builderLocalRuntimeId:z,builderLocalGrantedTo:L}=U;if(b.interactive&&(G==="builder-local"||G==="builder-hybrid"))z=await n.input("Default local runtime target id:",z??"rt_local_daemon"),L=await n.input("Default local runtime grant target:",L??"local:operator");let C={...U,projectName:q,targets:H,builderApiBaseUrl:_,builderLocalRuntimeId:z,builderLocalGrantedTo:L};for(let g of H){let iA=await qZ($,g,C,n,w);m.push(iA)}let D=await j($,{behavior:C.gitignoreBehavior,interactive:C.interactive,patterns:Ww({preset:G}),prompts:n,root:S});if(C.gitignoreBehavior!=="skip"||D.action!=="skipped")m.push(D);let F=m.filter((g)=>g.action!=="error").length,E=m.filter((g)=>g.action==="error").length,r=Z?` (${V} level)`:"";return{success:E===0,preset:G,files:m,summary:`Setup complete${r}: ${F} configured, ${E} failed.`,nextSteps:yw(C)}}async function qZ($,b,n,A,m){let y=m[b];if(y)return y($,n,A);return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}async function ej($,b){for(let n of b){let A=$.join(n,".contractsrc.json");if(!await $.exists(A))continue;let m=a(await $.readFile(A));if(m)return m}return null}import{validateBlueprint as OZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as VZ}from"path";async function Hx($,b){let{fs:n}=b,A=VZ(process.cwd(),$);if(!await n.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let m=await y$(A),y=JZ(m.exports),W=OZ(y);return{spec:y,report:W,valid:W.valid,errors:W.errors.map((w)=>`[${w.code}] ${w.path}: ${w.message}`)}}catch(m){return{valid:!1,errors:[m instanceof Error?m.message:String(m)]}}}function JZ($){let b=Object.values($).filter(UZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function UZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as KZ,dirname as my,join as bn}from"path";async function Jx($,b,n,A,m){let{fs:y}=m,W=A.implementationPath;if(!W){let S=my($),Q=KZ($,".ts"),Z=[bn(S,Q.replace(".contracts",".handler")+".ts"),bn(S,Q.replace(".presentation","")+".tsx"),bn(S,Q.replace(".form",".form")+".tsx"),bn(my(S),"handlers",Q.replace(".contracts",".handler")+".ts"),bn(my(S),"components",Q.replace(".presentation","")+".tsx")];for(let X of Z)if(await y.exists(X)){W=X;break}}if(!W||!await y.exists(W))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let w=await y.readFile(W),B=await new On(n).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as _Z,validateBuilderReadinessReport as zZ,validateBuilderWorkspace as LZ,validateBuilderWorkspaceSnapshot as RZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as CZ,validateExternalPatchProposal as xZ,validateProviderRoutingPolicy as IZ,validateRuntimeTarget as EZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as MZ,validateLayoutSlots as TZ}from"@contractspec/lib.surface-runtime/spec";async function Rx($,b){if(!gZ($.specType))return{valid:!0,errors:[],warnings:[]};let n=iZ($.filePath),A=[`${n}/package.json`,`${n}/README.md`,`${n}/src/index.ts`,$.filePath],m=[];for(let w of A)if(!await b.exists(w))m.push(`Missing package scaffold file: ${w}`);if(m.length>0)return{valid:!1,errors:m,warnings:[]};let y;try{y=(await y$($.filePath)).exports}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)],warnings:[]}}let W=$.specType==="module-bundle"?DZ(y):$.specType==="builder-spec"?NZ(y):FZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function DZ($){let b=[],n=[],A=vZ($,PZ);if(A.length===0)return n.push(yy("module-bundle","bundle")),{errors:b,warnings:n};for(let m of A){let y=Object.values(m.value.surfaces);for(let W of y){try{TZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of MZ(W).warnings)n.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:n}}function NZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(kZ(y)){A+=1,b.push(...LA(m,LZ(y)));continue}if(rZ(y)){A+=1,b.push(...LA(m,_Z(y)));continue}if(fZ(y)){A+=1,b.push(...LA(m,zZ(y)));continue}if(cZ(y))A+=1,b.push(...LA(m,RZ(y)))}if(A===0)n.push(yy("builder-spec","builder"));return{errors:b,warnings:n}}function FZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(hZ(y)){A+=1,b.push(...RA(m,EZ(y)));continue}if(dZ(y)){A+=1,b.push(...RA(m,IZ(y)));continue}if(uZ(y)){A+=1,b.push(...RA(m,CZ(y)));continue}if(oZ(y))A+=1,b.push(...RA(m,xZ(y)))}if(A===0)n.push(yy("provider-spec","provider"));return{errors:b,warnings:n}}function vZ($,b){return Object.entries($).filter(([n,A])=>n!=="__esModule"&&b(A)).map(([n,A])=>({exportName:n,value:A}))}function LA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function RA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function gZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function PZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function kZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function rZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function fZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function cZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function hZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function dZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function uZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function oZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function iZ($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function yy($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as tZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as lZ}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as pZ}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as aZ}from"@contractspec/module.workspace";async function $1($,b={}){let n=[],A=[],m;if(!b.skipStructure){m=aZ($),n.push(...m.errors),A.push(...m.warnings);let y=await eZ($);n.push(...y.errors),A.push(...y.warnings)}return{valid:n.length===0,structureResult:m,errors:n,warnings:A,code:$.sourceBlock}}async function Nx($,b={}){return Promise.all($.map(async(n)=>({spec:n,...await $1(n,b)})))}async function l$($,b,n={}){let{fs:A}=b;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let y=await A.readFile($),W=[],w=[],j=void 0;if(!n.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await $1(S,n);j=Q.structureResult,W.push(...Q.errors),w.push(...Q.warnings)}}return{valid:W.length===0,structureResult:j,errors:W,warnings:w,code:y}}async function Fx($,b,n={}){let A=new Map;for(let m of $){let y=await l$(m,b,n);A.set(m,y)}return A}async function eZ($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await y$($.filePath);if($.specType==="app-config"){let m=sZ(b.exports,$),y=tZ(m);return{errors:y.errors.map((W)=>sj(W)),warnings:[...y.warnings,...y.info].map((W)=>sj(W))}}if($.specType==="feature"){let m=$2(b.exports,$),y=lZ(m);return{errors:y.issues.filter((W)=>W.level==="error").map((W)=>CA(W)),warnings:y.issues.filter((W)=>W.level!=="error").map((W)=>CA(W))}}let n=b2(b.exports,$),A=pZ(n);return{errors:A.issues.filter((m)=>m.level==="error").map((m)=>CA(m)),warnings:A.issues.filter((m)=>m.level!=="error").map((m)=>CA(m))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function sZ($,b){return Wy($,b.exportName,n2)}function $2($,b){return Wy($,b.exportName,A2)}function b2($,b){return Wy($,b.exportName,m2)}function Wy($,b,n){if(b&&n($[b]))return $[b];let A=Object.values($).find(n);if(!A)throw Error("Expected authored module to export a compatible spec value.");return A}function n2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function A2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function m2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function sj($){let b=$.code?`[${$.code}] `:"",n=$.path?`${$.path}: `:"";return`${b}${n}${$.message}`}function CA($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as y2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as jy}from"fs/promises";import{resolve as xA}from"path";async function fx($,b,n,A){let{fs:m}=A,y=xA(process.cwd(),b);if(!await m.exists(y))return{valid:!1,errors:[`Tenant config file not found: ${y}`]};try{let W=await W2(y),w=await w2(n.connections,m),j=await j2(n.translationCatalog,m),B=await B2(n.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=y2($,W,S);return{config:W,report:Q,valid:Q.valid,errors:Q.errors.map((Z)=>`[${Z.code}] ${Z.path}: ${Z.message}`)}}catch(W){return{valid:!1,errors:[W instanceof Error?W.message:String(W)]}}}async function W2($){if($.endsWith(".json")){let A=await jy($,"utf-8"),m=JSON.parse(A);if(!b1(m))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return m}let b=await y$($),n=Object.values(b.exports).filter(b1);if(n.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return n[0]}function b1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function y1($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((n)=>n.trim()).filter(Boolean)}async function w2($,b){let n=y1($);if(!n.length)return[];let A=[];for(let m of n){let y=xA(process.cwd(),m);if(!await b.exists(y)){console.warn(`Warning: Connection file not found: ${y}`);continue}if(y.endsWith(".json")){let w=await jy(y,"utf-8"),j=JSON.parse(w);A.push(...wy(j));continue}let W=await y$(y);A.push(...wy(W.exports))}return A}function wy($){if(Array.isArray($)){let b=$.filter(n1);if(b.length)return b}if(n1($))return[$];if($&&typeof $==="object"){let n=Object.values($).flatMap((A)=>wy(A));if(n.length)return n}return[]}function n1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function j2($,b){if(!$)return;let n=xA(process.cwd(),$);if(!await b.exists(n))return;if(n.endsWith(".json")){let y=await jy(n,"utf-8"),W=JSON.parse(y);if(A1(W))return m1(W);return}let A=await y$(n),m=Object.values(A.exports).filter(A1);if(m.length===0)return;return m1(m[0])}function A1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function m1($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function B2($){let b=y1($);if(!b.length)return;let{IntegrationSpecRegistry:n}=await import("@contractspec/lib.contracts-integrations"),A=new n;for(let m of b){let{modulePath:y,exportName:W}=S2(m);if(!y)continue;let w=xA(process.cwd(),y);try{let j=await y$(w),B=Q2(j.exports,W);if(B)await B(A)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return A}function S2($){if(!$)return{modulePath:null};let[b,n]=$.split("#"),A=b?.trim()??null,m=n?.trim();return{modulePath:A,exportName:m}}function Q2($,b){if(b){let n=$[b];if(typeof n==="function")return n;return}if(typeof $.default==="function")return $.default;for(let n of Object.values($))if(typeof n==="function")return n;return}async function ex($,b,n={},A){let{fs:m,logger:y}=$,W=await m.glob({pattern:n.pattern}),w=n.outputDirs?.length?n.outputDirs:[void 0],j=[],B=A?.validate??((Q)=>l$(Q,{fs:m,logger:y})),S=A?.build??((Q,Z)=>yb(Q,{fs:m,logger:y},Z?{...b,outputDir:Z}:b,{...n.buildOptions??{},outputDir:Z}));for(let Q of W)for(let Z of w){let X={specPath:Q,outputDir:Z};if(n.validate)try{X.validation=await B(Q)}catch(Y){X.error={phase:"validate",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}if(!n.dryRun)try{X.build=await S(Q,Z)}catch(Y){X.error={phase:"build",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}else y.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});j.push(X)}return{specs:W,runs:j}}import{generateText as Z2}from"ai";var X2=`
|
|
2455
|
+
`}function pm($){return $.replace(/\r\n/g,`
|
|
2456
|
+
`).trimEnd()}function ZZ($){return new RegExp(`${pj($.startMarker)}[\\s\\S]*?${pj($.endMarker)}(?:\\r?\\n)?`)}function pj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var XZ="<!-- contractspec:init:agents:start -->",YZ="<!-- contractspec:init:agents:end -->",HZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:YZ,note:HZ,startMarker:XZ};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 GZ,generateBiomePreset as qZ}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=GZ("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,qZ("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 OZ="<!-- contractspec:init:usage:start -->",JZ="<!-- contractspec:init:usage:end -->",UZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",ej={endMarker:JZ,note:UZ,startMarker:OZ};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 VZ={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??""},KZ={"agents-md":am,"biome-config":em,"cli-config":sm,"cursor-rules":$y,"mcp-claude":by,"mcp-cursor":Ay,"usage-md":ny,"vscode-settings":my},_Z={findWorkspaceRoot:x,findPackageRoot:c,isMonorepo:Ub,getPackageName:P$};async function XC($,b,A=VZ,n={}){let m=[],y=b.targets.length>0?b.targets:Mb,W={..._Z,...n.workspace},w={...KZ,...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 zZ($,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 zZ($,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 LZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as RZ}from"path";async function CC($,b){let{fs:A}=b,n=RZ(process.cwd(),$);if(!await A.exists(n))return{valid:!1,errors:[`Blueprint file not found: ${n}`]};try{let m=await W$(n),y=IZ(m.exports),W=LZ(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 IZ($){let b=Object.values($).filter(CZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function CZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as xZ,dirname as yy,join as nA}from"path";async function TC($,b,A,n,m){let{fs:y}=m,W=n.implementationPath;if(!W){let S=yy($),Q=xZ($,".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 MZ,validateBuilderReadinessReport as EZ,validateBuilderWorkspace as TZ,validateBuilderWorkspaceSnapshot as DZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as NZ,validateExternalPatchProposal as FZ,validateProviderRoutingPolicy as vZ,validateRuntimeTarget as gZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as PZ,validateLayoutSlots as kZ}from"@contractspec/lib.surface-runtime/spec";async function PC($,b){if(!dZ($.specType))return{valid:!0,errors:[],warnings:[]};let A=$2($.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"?rZ(y):$.specType==="builder-spec"?fZ(y):cZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function rZ($){let b=[],A=[],n=hZ($,uZ);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{kZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of PZ(W).warnings)A.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:A}}function fZ($){let b=[],A=[],n=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(oZ(y)){n+=1,b.push(...z0(m,TZ(y)));continue}if(iZ(y)){n+=1,b.push(...z0(m,MZ(y)));continue}if(lZ(y)){n+=1,b.push(...z0(m,EZ(y)));continue}if(tZ(y))n+=1,b.push(...z0(m,DZ(y)))}if(n===0)A.push(Wy("builder-spec","builder"));return{errors:b,warnings:A}}function cZ($){let b=[],A=[],n=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(pZ(y)){n+=1,b.push(...L0(m,gZ(y)));continue}if(aZ(y)){n+=1,b.push(...L0(m,vZ(y)));continue}if(eZ(y)){n+=1,b.push(...L0(m,NZ(y)));continue}if(sZ(y))n+=1,b.push(...L0(m,FZ(y)))}if(n===0)A.push(Wy("provider-spec","provider"));return{errors:b,warnings:A}}function hZ($,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 dZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function uZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function oZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function iZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function lZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function tZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function pZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function aZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function eZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function sZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function $2($){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 b2}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as A2}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as n2}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as m2}from"@contractspec/module.workspace";async function b1($,b={}){let A=[],n=[],m;if(!b.skipStructure){m=m2($),A.push(...m.errors),n.push(...m.warnings);let y=await y2($);A.push(...y.errors),n.push(...y.warnings)}return{valid:A.length===0,structureResult:m,errors:A,warnings:n,code:$.sourceBlock}}async function oC($,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 iC($,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 y2($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await W$($.filePath);if($.specType==="app-config"){let m=W2(b.exports,$),y=b2(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=A2(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=j2(b.exports,$),n=n2(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 W2($,b){return wy($,b.exportName,B2)}function w2($,b){return wy($,b.exportName,S2)}function j2($,b){return wy($,b.exportName,Q2)}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 B2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function S2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function Q2($){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 Z2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as By}from"fs/promises";import{resolve as I0}from"path";async function sC($,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 X2(y),w=await Y2(A.connections,m),j=await H2(A.translationCatalog,m),B=await G2(A.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=Z2($,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 X2($){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 Y2($,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 H2($,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 G2($){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}=q2(m);if(!y)continue;let w=I0(process.cwd(),y);try{let j=await W$(w),B=O2(j.exports,W);if(B)await B(n)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return n}function q2($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),n=b?.trim()??null,m=A?.trim();return{modulePath:n,exportName:m}}function O2($,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 Sx($,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 J2}from"ai";var U2=`
|
|
2425
2457
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2426
2458
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2427
2459
|
|
|
@@ -2439,7 +2471,7 @@ Generate scenarios covering:
|
|
|
2439
2471
|
- Happy path (valid input, successful execution)
|
|
2440
2472
|
- Edge cases (boundary values, optional fields)
|
|
2441
2473
|
- Error cases (invalid input, business rule violations)
|
|
2442
|
-
`.trim();class
|
|
2474
|
+
`.trim();class V2{logger;defaultModel;generateTextImpl;constructor($,b,A=J2){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=`
|
|
2443
2475
|
Generate a TestSpec for the following Operation:
|
|
2444
2476
|
|
|
2445
2477
|
\`\`\`json
|
|
@@ -2448,23 +2480,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2448
2480
|
|
|
2449
2481
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2450
2482
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2451
|
-
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:
|
|
2452
|
-
`)}function
|
|
2453
|
-
`)}function
|
|
2454
|
-
`);for(let
|
|
2455
|
-
`)}function
|
|
2483
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:A,system:U2,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 Ox($,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 Jx($,b,A){let{logger:n}=A,m;if(b.registry)m=await _2(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 Ux($,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(K2(A))b.push(A);return b}function K2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function _2($){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 z2,Node as Hb,Project as L2,QuoteKind as R2,SyntaxKind as I2}from"ts-morph";function C2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Cx($,b,A={}){let{fs:n,logger:m}=b;if(!await n.exists($))return{specPath:$,specInfo:C2($),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=x2(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 x2($,b){let n=new L2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:z2.TwoSpaces,quoteKind:R2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=E2(n);if(!m)return $;for(let y of b)M2(m,y);return n.getFullText()}function M2($,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(I2.ObjectLiteralExpression);if(!Q)return;n=Q}let m=A[A.length-1];if(!m)return;let y=T2(b.value),W=n.getProperty(m);if(W&&Hb.isPropertyAssignment(W)){W.setInitializer(y);return}n.addPropertyAssignment({name:m,initializer:y})}function E2($){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 T2($){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 f2,DEFAULT_CONTRACTSRC as c2}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)=>`- ${D2(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(`
|
|
2484
|
+
`)}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(`
|
|
2485
|
+
`)}function Y1($){let b=[`### ${$.summary}`,...Qy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2486
|
+
`);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(`
|
|
2487
|
+
`)}function Zy($){return["# Patch Notes","",...$.releases.map(Z1)].join(`
|
|
2456
2488
|
|
|
2457
|
-
`)}function
|
|
2489
|
+
`)}function Xy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[X1(b),"",Y1(b)])].join(`
|
|
2458
2490
|
|
|
2459
|
-
`)}function
|
|
2491
|
+
`)}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(`
|
|
2460
2492
|
`)).join(`
|
|
2461
|
-
`)}function
|
|
2462
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2463
|
-
`)}function
|
|
2464
|
-
`),
|
|
2465
|
-
`),!0}async function
|
|
2466
|
-
`),!0}async function
|
|
2467
|
-
`),m="info";for(let j of
|
|
2493
|
+
`)}function Gb($,b){let A=b.targetPackages.map((n)=>`${n.name}: ${n.currentVersion??"unknown"} -> ${n.targetVersion??"latest"}`).join(`
|
|
2494
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",A||"- No package version targets were inferred.","","Required steps:",H1(b)].join(`
|
|
2495
|
+
`)}function D2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as q1,countUpgradePlanStepLevels as N2,createAgentPromptBundles as F2,dedupeUpgradePlanSteps as v2,sortReleaseManifest as G1}from"@contractspec/lib.contracts-spec";function g2($,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=g2($,b),y=P2(m,b),W=v2(m.flatMap((S)=>S.upgradeSteps)),w=N2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=F2(j,A,n);return{...j,agentPrompts:B}}function P2($,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 k2(A,m),j=await r2(A,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function k2($,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 r2($,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)+`
|
|
2496
|
+
`),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 h2="**/*.{ts,tsx,js,jsx,mjs,cjs}",_1=c2.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 u2(A,n,m),W=await d2(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=o2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:i2(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 l2(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 d2($,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 u2($,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=f2.safeParse(m);if(y.success)return{..._1,...y.data.upgrade}}catch{continue}}return _1}function o2($,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 i2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function l2($,b,A){switch(A.kind){case"package-json":return t2($,b,A);case"contractsrc":return p2($,b,A);case"import-rewrite":return a2($,b,A);case"codemod":return!1}}async function t2($,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)+`
|
|
2497
|
+
`),!0}async function p2($,b,A){let n=$.join(b,".contractsrc.json"),m=await $.exists(n)?JSON.parse(await $.readFile(n)):{};if(!A.configPath)return!1;return e2(m,A.configPath,A.value),await $.writeFile(n,JSON.stringify(m,null,2)+`
|
|
2498
|
+
`),!0}async function a2($,b,A){if(!A.from||!A.to)return!1;let n=await $.glob({pattern:A.path??h2,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 e2($,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 s2,readFileSync as $X,renameSync as bX,statSync as AX,writeFileSync as nX}from"fs";import{dirname as mX,join as yX}from"path";var WX=".contractspec/verification-cache.json",R1=1;class I1{filePath;cache;isDirty=!1;constructor($,b){let A=b??process.cwd();this.filePath=$??yX(A,WX),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Hy(this.filePath))return;let $=$X(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 $=mX(this.filePath);if(!Hy($))s2($,{recursive:!0});let b={version:R1,entries:Object.fromEntries(this.cache.entries())},A=`${this.filePath}.tmp`;nX(A,JSON.stringify(b,null,2),"utf-8"),bX(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))$=AX(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function lx($,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 px(){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 ex($){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 jX($){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 BX($,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=BX($.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=jX(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 wM($,b){return new D1($,b)}import{generateVerificationPrompt as SX}from"@contractspec/lib.contracts-spec/llm";function QX($){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(`
|
|
2499
|
+
`),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(/^[-*•]\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
|
|
2468
2500
|
{
|
|
2469
2501
|
"passed": true,
|
|
2470
2502
|
"score": 50,
|
|
@@ -2481,16 +2513,16 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2481
2513
|
],
|
|
2482
2514
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2483
2515
|
}
|
|
2484
|
-
\`\`\``;try{let
|
|
2516
|
+
\`\`\``;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
|
|
2485
2517
|
{
|
|
2486
2518
|
"passed": false,
|
|
2487
2519
|
"score": 0,
|
|
2488
2520
|
"issues": [
|
|
2489
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2521
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${A instanceof Error?A.message:"Unknown error"}" }
|
|
2490
2522
|
],
|
|
2491
2523
|
"summary": "AI verification encountered an error"
|
|
2492
2524
|
}
|
|
2493
|
-
\`\`\``}}async function
|
|
2525
|
+
\`\`\``}}async function WA($,b={}){let{spec:A,implementationCode:n,implementationPath:m}=$,y=Date.now(),W=SX(A,n),w=await N1(W.taskPrompt,b),j=QX(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 ZX($,b){return`You are analyzing a code implementation against its specification.
|
|
2494
2526
|
|
|
2495
2527
|
## Spec Schema Fields
|
|
2496
2528
|
${$}
|
|
@@ -2537,43 +2569,43 @@ Match types:
|
|
|
2537
2569
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2538
2570
|
- "mismatch": Different meaning despite similar naming
|
|
2539
2571
|
- "missing": Spec field not found in implementation
|
|
2540
|
-
`}function
|
|
2541
|
-
`)}function
|
|
2542
|
-
`),
|
|
2543
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let
|
|
2544
|
-
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function
|
|
2545
|
-
`)}function
|
|
2546
|
-
`)}function
|
|
2547
|
-
`),
|
|
2548
|
-
`).trim()||void 0,B=j?.match(
|
|
2549
|
-
${b.map((
|
|
2572
|
+
`}function XX($){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(`
|
|
2573
|
+
`)}function YX($){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=XX(A),y=ZX(m,n),W=await N1(y,b);return YX(W)}async function HX($,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 GX}from"@contractspec/lib.contracts-spec/operations";function qX($,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 OX($,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 JX($,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 UX($,b){let A=b.sideEffects?.emits??[],n=[];for(let m of A){let y=GX(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 VX($,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(qX(A,Y));for(let Y of b.acceptance?.examples??[])y.push(OX(A,Y));for(let[Y,H]of Object.entries(b.io.errors??{}))y.push(JX(A,Y,H));y.push(...UX(A,b));let W=VX(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 KX}from"@contractspec/lib.contracts-spec/operations";function _X($){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 zX($){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 LX($,b){if(zX(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 RX($,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 IX($){let b=/:\s*any\b|as\s+any\b|<any>/,A=$.split(`
|
|
2574
|
+
`),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 CX($,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 xX($,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(KX(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 MX($,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 EX($,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=[_X(A),LX(A,n),RX(A,b),IX(A),CX(A,b),xX(A,b),MX(A,b),EX(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 TX={verbose:!1},DX=["structure","behavior","ai_review"];class D0{config;constructor($={}){this.config={...TX,...$}}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 DX){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?"✓ Passed":"✗ 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?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${m.score}/100`),b.push(""),m.issues.length>0){b.push("### Issues"),b.push("");for(let y of m.issues){let W=y.severity==="error"?"❌":y.severity==="warning"?"⚠️":"ℹ️";if(b.push(`${W} **${y.category}**: ${y.message}`),y.suggestion)b.push(` - Suggestion: ${y.suggestion}`)}b.push("")}if(m.coverage.scenarios.total>0)b.push(`**Scenarios:** ${m.coverage.scenarios.covered}/${m.coverage.scenarios.total}`);if(m.coverage.errors.total>0)b.push(`**Errors handled:** ${m.coverage.errors.handled}/${m.coverage.errors.total}`);b.push("")}let 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(`
|
|
2575
|
+
`)}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?"✓ Verification passed":"✗ Verification failed"),A.push(`Score: ${m}/100`),A.push("");for(let j of $){let B=j.passed?"✓":"✗";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(`
|
|
2576
|
+
`)}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 NX($){return new D0($)}var FX=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:()=>cX,initReleaseArtifacts:()=>$B,getHighestBumpType:()=>qy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>i1,formatKeepAChangelog:()=>jA,formatConventionalChangelog:()=>P1,formatChangelogJson:()=>N0,filterCommitsByScope:()=>hX,filterBumpableCommits:()=>dX,commitsToChangeEntries:()=>Oy,commitToChangeEntry:()=>r1,checkReleaseArtifacts:()=>AB,buildReleaseArtifacts:()=>bB,applyVersionBump:()=>o1,analyzeVersionsFromCommits:()=>qb,analyzeVersions:()=>XA,DEFAULT_COMMIT_TYPE_MAP:()=>F0});import{basename as vX,dirname as gX}from"node: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("### ⚠️ 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(`
|
|
2577
|
+
`)}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(`
|
|
2578
|
+
`)}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:kX(A,m)}}function PX($){let b=$.split("/"),A=b.lastIndexOf("packages");if(A>=0&&A+2<b.length)return b.slice(0,A+3).join("/");return gX($)}var g1={major:3,minor:2,patch:1};function kX($,b){let A=new Map;for(let n of $){let m=PX(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:vX(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"},rX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,fX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function v0($){let b=$.split(`
|
|
2579
|
+
`),A=b[0]?.trim();if(!A)return null;let n=A.match(rX);if(!n)return null;let[,m,y,W,w]=n;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2580
|
+
`).trim()||void 0,B=j?.match(fX),S=B?.[1];return{type:m.toLowerCase(),scope:y?.toLowerCase(),breaking:!!W||!!B,description:w.trim(),body:j,breakingDescription:S,raw:$}}function cX($){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 hX($,b){return $.filter((A)=>A.scope?.toLowerCase()===b.toLowerCase())}function dX($,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 uX,load as oX}from"js-yaml";var iX=".changeset/*.md",lX=".changeset/*.release.yaml",tX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,pX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function aX($,b){return(await $.glob({pattern:iX,cwd:b,absolute:!0})).filter((n)=>$.basename(n)!=="README.md")}async function BA($,b){let A=await aX($,b),n=[];for(let m of A){let y=await $.readFile(m);n.push(eX($.basename(m),y))}return n}async function SA($,b,A,n){let m=await $.glob({pattern:lX,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=oX(await $.readFile(j)),Q=sX(S,B,y.get(B)??[]);W.set(B,Q)}catch(S){w.push($Y(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`---
|
|
2581
|
+
${b.map((n)=>`"${n.name}": ${n.releaseType}`).join(`
|
|
2550
2582
|
`)}
|
|
2551
2583
|
---
|
|
2552
2584
|
|
|
2553
2585
|
${$}
|
|
2554
|
-
`}function
|
|
2555
|
-
`)}function
|
|
2556
|
-
`)){let j=w.trim().match(
|
|
2557
|
-
`)}function
|
|
2586
|
+
`}function k0($){return uX(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(`
|
|
2587
|
+
`)}function eX($,b){let A=$.replace(/\.md$/,""),n=b.match(tX);if(!n)return{slug:A,summary:b.trim(),packages:[]};let m=n[1]??"",y=(n[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2588
|
+
`)){let j=w.trim().match(pX);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 sX($,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 $Y($,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 bY}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=AY(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=bY(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=mY(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:yY(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=WY(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 AY($,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=nY($,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 nY($,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 mY($,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 yY($){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(`
|
|
2589
|
+
`)}function WY($){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=`${jY()}.md`,X=A.join(Q,Z),Y=`---
|
|
2558
2590
|
"${B}": ${y}
|
|
2559
2591
|
---
|
|
2560
2592
|
|
|
2561
2593
|
${W}
|
|
2562
|
-
`;if(!w)await n.writeFile(X,Y),A.info("Generated changeset",{filePath:X});else A.info("Would generate changeset",{filePath:X,content:Y})}catch(j){A.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function bY(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],n=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],m=b[Math.floor(Math.random()*b.length)],y=n[Math.floor(Math.random()*n.length)],W=Math.floor(Math.random()*1000);return`${A}-${m}-${y}-${W}`}var nY=M.object({summary:M.string(),maintainerSummary:M.string(),customerSummary:M.string(),integratorSummary:M.string(),deprecations:M.array(M.string()).default([]),migrationInstructions:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),required:M.boolean().default(!1),when:M.string().optional(),steps:M.array(M.string()).default([])})).default([]),upgradeSteps:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),level:M.enum(["auto","assisted","manual"]).default("manual"),instructions:M.array(M.string()).default([])})).default([]),validationCommands:M.array(M.string()).default([]),validationEvidence:M.array(M.string()).default([])});async function i1($,b={}){let{fs:n,git:A,logger:m,ai:y}=$,W=I(b.workspaceRoot),w=await Bn(n,W),j=b.baseline?await A.diffFiles(b.baseline):[],B=await wn(n,W),S=await jn(n,W,B),Q=b.packages&&b.packages.length>0?b.packages:PA(j,w),Z=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??wY(B,S.capsules,Q),G=Y?n.join(W,".changeset",`${Y}.md`):void 0,V=Y?n.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((q)=>q.slug===Y):void 0,K=Y?S.capsules.get(Y):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??jY(Q)),U=(G?await n.exists(G):!1)||(V?await n.exists(V):!1),H=await mY(y,AY({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:w,isBreaking:J==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await A.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},m);return{workspaceRoot:W,source:U?"existing":"created",changesetPath:G??n.join(W,".changeset",`${H.slug}.md`),capsulePath:V??n.join(W,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${Sn(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:n}=$,A=I(b.workspaceRoot),m=Zn(b.draft),y=n.join(A,".changeset",`${m.slug}.md`),W=n.join(A,".changeset",`${m.slug}.release.yaml`),w=await n.exists(y)||await n.exists(W)?"updated":"created",j=kA(m.summary,m.packages),B=rA(WY(m));return await n.writeFile(y,j),await n.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function AY($){if($.existingCapsule)return Zn({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((A)=>({...A,version:$.workspacePackages.find((m)=>m.name===A.name)?.version??A.version})):$.packageNames.map((A)=>({name:A,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===A)?.version})),n=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return Zn({slug:$.selectedSlug??BY(n),summary:n,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:l1(n),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function mY($,b,n,A){if(!$)return b;try{let m=await $.generateStructured({schema:nY,systemPrompt:"You write structured release metadata for a TypeScript monorepo. Be concise, concrete, and safe for public release notes.",prompt:JSON.stringify({draft:b,changedFiles:n.changedFiles.slice(0,40),commitMessages:n.commitMessages.slice(0,20),parseIssues:n.parseIssues})});return yY(b,m.object)}catch(m){return A.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:m instanceof Error?m.message:String(m)}),b}}function yY($,b){let n=[...$.audiences];return Oy(n,"maintainer",b.maintainerSummary),Oy(n,"customer",b.customerSummary),Oy(n,"integrator",b.integratorSummary),Zn({...$,summary:p1($.summary)?b.summary:$.summary,audiences:n,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function Zn($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:l1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function WY($){let{releaseType:b,...n}=Zn($);return{schemaVersion:"1",...n}}function l1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Oy($,b,n){let A=$.find((m)=>m.kind===b);if(A&&!p1(A.summary))return;if(A){A.summary=n;return}$.push({kind:b,summary:n})}function wY($,b,n){let A=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(A.size===1)return Array.from(A)[0];if(n.length===0)return;let m=Array.from(A).filter((y)=>{let W=b.get(y),w=$.find((B)=>B.slug===y);return(W?.packages.map((B)=>B.name)??w?.packages.map((B)=>B.name)??[]).some((B)=>n.includes(B))});return m.length===1?m[0]:void 0}function jY($){return $.length>0?"minor":"patch"}function p1($){return $.trim().startsWith("Describe the ")}function BY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as SY}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as QY,DEFAULT_CONTRACTSRC as ZY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var a1="generated/releases",cA=ZY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function e1($,b={}){let{fs:n,git:A,logger:m}=$,y=I(b.workspaceRoot),W=await Bn(n,y),w=b.baseline?await A.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:PA(w,W),B=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:y}):null,S=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:y}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??XY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??GY(X),G=j.map((H)=>({name:H,releaseType:Z,version:W.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:G,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:X},{kind:"customer",summary:X}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=n.join(y,".changeset",`${Y}.md`),K=n.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await n.exists(O))throw Error(`Changeset already exists: ${O}`);if(await n.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=kA(X,G),U=rA(V);if(!b.dryRun)await n.writeFile(O,J),await n.writeFile(K,U);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:U,packages:G,releaseType:Z,isBreaking:V.isBreaking}}async function s1($,b={}){let{fs:n,logger:A}=$,m=I(b.workspaceRoot),y=await bB(n,m),W=n.join(m,b.outputDir??a1),w=await wn(n,m),j=await jn(n,m,w);if(j.issues.length>0)throw Error(Sn(j.issues));let B=j.capsules,S=await Bn(n,m),Q=await Promise.all(Array.from(B.entries()).map(async([U,H])=>{let q=n.join(m,".changeset",`${U}.release.yaml`),_=await n.stat(q);return{slug:U,version:YY(H,S),summary:H.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:H.isBreaking,packages:H.packages.map((z)=>({...z,version:S.find((L)=>L.name===z.name)?.version??z.version})),affectedRuntimes:[...H.affectedRuntimes],affectedFrameworks:[...H.affectedFrameworks],audiences:[...H.audiences],deprecations:[...H.deprecations],migrationInstructions:[...H.migrationInstructions],upgradeSteps:[...H.upgradeSteps],validation:H.validation}})),Z=SY.parse({generatedAt:new Date().toISOString(),releases:Q}),X=b.agentTargets??y.agentTargets??["codex"],Y=An(Z,[],X,Yb),G=n.join(W,"manifest.json"),V=n.join(W,"upgrade-manifest.json"),O=n.join(W,"patch-notes.md"),K=n.join(W,"customer-guide.md"),J=Object.fromEntries(Y.agentPrompts.map((U)=>[U.agent,n.join(W,"prompts",`${U.agent}.md`)]));if(!b.dryRun){await n.writeFile(G,JSON.stringify(Z,null,2)),await n.writeFile(V,JSON.stringify(Z,null,2)),await n.writeFile(O,Qy(Z)),await n.writeFile(K,Zy(Z));for(let U of Y.agentPrompts)await n.writeFile(J[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:W,releasesBuilt:Z.releases.length}),{outputDir:W,manifestPath:G,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:Y,releasesBuilt:Z.releases.length}}async function $B($,b={}){let{fs:n}=$,A=I(b.workspaceRoot),m=await bB(n,A),y=n.join(A,b.outputDir??a1),W=[],w=[],j=[],B=await wn(n,A),S=await jn(n,A,B),Q=S.capsules,Z=B.length>0,X=!Z&&Q.size>0;j.push(...S.issues.map((Y)=>Sn([Y]))),Hb(W,Z||X,"changesets",Z?`Found ${B.length} release changeset(s).`:X?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let Y of B)if(!Q.has(Y.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${Y.slug}.`);for(let[Y,G]of Q){if(G.isBreaking&&G.migrationInstructions.length===0)j.push(`Breaking release ${Y} is missing migration instructions.`);if(G.validation.commands.length===0)j.push(`Release capsule ${Y} is missing validation commands.`);if(G.validation.evidence.length===0)j.push(`Release capsule ${Y} is missing validation evidence.`)}if(b.baseline){try{let Y=await K$($,{baseline:b.baseline,workspaceRoot:A});if(Hb(W,!0,"impact",`Impact status: ${Y.status}`),Y.summary.breaking>0&&!Array.from(Q.values()).some((G)=>G.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(Y){Hb(W,!1,"impact",hA(Y)),j.push(`Impact detection failed: ${hA(Y)}`)}try{let Y=await Qn($,{baseline:b.baseline,workspaceRoot:A});Hb(W,!0,"versioning",`${Y.specsNeedingBump} spec(s) need version review.`)}catch(Y){Hb(W,!1,"versioning",hA(Y)),j.push(`Version analysis failed: ${hA(Y)}`)}}if(b.strict)for(let Y of m.publishArtifacts??[]){let G=n.join(y,Y);if(!await n.exists(G))j.push(`Missing generated release artifact: ${G}`)}if(Hb(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!Z&&!X)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function bB($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return cA;try{let A=JSON.parse(await $.readFile(n)),m=QY.safeParse(A);return m.success?{...cA,...m.data.release}:cA}catch{return cA}}function XY($){return $.length>0?"minor":"patch"}function YY($,b){return $.packages.map((A)=>b.find((m)=>m.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function GY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Hb($,b,n,A){$.push({name:n,ok:b,message:A})}function hA($){return $ instanceof Error?$.message:String($)}var XB={};f(XB,{silentLogger:()=>yB,runWorkflow:()=>WB,loadWorkflows:()=>Uy,loadVibeConfig:()=>uA,installPack:()=>ZB,getWorkflow:()=>jB,exportContext:()=>mB,consoleLogger:()=>Jy,builtinWorkflows:()=>oA,DEFAULT_VIBE_CONFIG:()=>dA});import{existsSync as HY}from"node:fs";import{readFile as qY}from"node:fs/promises";import{join as Vy}from"node:path";import OY from"js-yaml";var dA={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function uA($){let b=$??process.cwd(),n=I(b)??b,A=[Vy(n,".contractspec","vibe","config.json"),Vy(n,".contractspec","vibe","config.yaml"),Vy(n,".contractspec","vibe","config.yml")],m={};for(let y of A)if(HY(y))try{let W=await qY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=OY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...dA,...m}}import{existsSync as VY}from"node:fs";import{copyFile as JY,mkdir as AB,readFile as UY,writeFile as KY}from"node:fs/promises";import{dirname as _Y,join as qb}from"node:path";import{glob as zY}from"glob";var LY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function mB($){let b=$??process.cwd(),n=I(b)??b,A=await uA(b),m=qb(n,".contractspec","context"),y=qb(m,"files"),W=[...LY],w=qb(n,".gitignore");if(VY(w)){let G=(await UY(w,"utf-8")).split(`
|
|
2563
|
-
`).map((
|
|
2594
|
+
`;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 jY(){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 BY=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??YY(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??HY(Q)),K=(H?await A.exists(H):!1)||(J?await A.exists(J):!1),q=await QY(y,SY({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(XY(m));return await A.writeFile(y,j),await A.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function SY($){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??GY(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 QY($,b,A,n){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:A.changedFiles.slice(0,40),commitMessages:A.commitMessages.slice(0,20),parseIssues:A.parseIssues})});return ZY(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 ZY($,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 XY($){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 YY($,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 HY($){return $.length>0?"minor":"patch"}function a1($){return $.trim().startsWith("Describe the ")}function GY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as e1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as qY,DEFAULT_CONTRACTSRC as OY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var s1="generated/releases",JY="1970-01-01T00:00:00.000Z",f0=OY.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??_Y(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??IY(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 KY(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:zY(L,X,I,H),summary:L.summary,date:I?.date??RY(),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:LY(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=qY.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 UY($.git,b.baseline),n=new Set;for(let m of A){let y=VY(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 UY($,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 VY($){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 KY($,b){if(!await $.exists(b))return;try{return e1.parse(JSON.parse(await $.readFile(b)))}catch{return}}function _Y($){return $.length>0?"minor":"patch"}function zY($,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 LY($){let A=$.map((n)=>n.date).filter(Boolean).sort().at(-1);return A?`${A}T00:00:00.000Z`:JY}function RY(){return new Date().toISOString().split("T")[0]??"1970-01-01"}function IY($){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 CY}from"node:fs";import{readFile as xY}from"node:fs/promises";import{join as Uy}from"node:path";import MY 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(CY(y))try{let W=await xY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=MY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...h0,...m}}import{existsSync as EY}from"node:fs";import{copyFile as TY,mkdir as wB,readFile as DY,writeFile as NY}from"node:fs/promises";import{dirname as FY,join as Jb}from"node:path";import{glob as vY}from"glob";var gY=["**/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=[...gY],w=Jb(A,".gitignore");if(EY(w)){let H=(await DY(w,"utf-8")).split(`
|
|
2595
|
+
`).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 vY(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(FY(J),{recursive:!0}),await TY(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 NY(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.
|
|
2564
2596
|
Please review them and move selected files to contracts/ directory.
|
|
2565
|
-
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"release",label:"Prepare Release",command:"contractspec release prepare"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as
|
|
2566
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2567
|
-
`);let y={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let W of $.steps){let w={id:W.id,name:W.label,status:"skip",command:W.command};if(W.tracks&&!W.tracks.includes(b.track)){y.steps.push(w);continue}if(W.condition){if(!await W.condition(b)){y.steps.push(w);continue}}if(
|
|
2568
|
-
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)
|
|
2597
|
+
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 PY}from"node: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(`
|
|
2598
|
+
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.
|
|
2599
|
+
`);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(`
|
|
2600
|
+
\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(" → Skipped by user."),y.steps.push(w);continue}}}if(!b.dryRun)try{if(W.execute)await W.execute(b);else if(W.command)await kY(W.command,b.root);w.status="pass",y.stepsExecuted.push(W.id),y.steps.push(w),n.log(" ✓ Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return n.error(` ❌ Failed: ${B}`),y.success=!1,y.error=j instanceof Error?j:Error(String(j)),w.status="fail",w.error=B,y.stepsExecuted.push(W.id),y.steps.push(w),y}else y.steps.push(w)}return y}async function kY($,b){let A=$.split(" "),n=A[0],m=A.slice(1);if(!n)throw Error("Invalid command");return new Promise((y,W)=>{let w=PY(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 rY}from"node:fs";import{readdir as fY,readFile as cY}from"node:fs/promises";import{join as QB}from"node:path";import hY from"js-yaml";async function Ky($){let b=[...u0],A=$??process.cwd(),n=x(A)??A,m=QB(n,".contractspec","vibe","workflows");if(rY(m))try{let y=await fY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await cY(QB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=hY.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"node:fs";import{copyFile as XB,mkdir as YB,readdir as HB,stat as dY}from"node:fs/promises";import{join as N$,resolve as uY}from"node: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=uY(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 dY(Z)).isFile())await XB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as oY}from"@contractspec/module.workspace";var OB=["product","eng","qa"];function iY($){return OB.includes($)}async function iE($,b){if(!iY(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 lY($,{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 tY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:n,changedFilesCount:m,status:"success"}}async function lY($,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 tY($,b,A){if(!await A.fs.exists($))throw Error(`File not found: ${$}`);let n=await oY($);if(n.length===0)return`No specs found in ${$} (Parse result empty)`;return n.map((m)=>pY(m,b)).join(`
|
|
2569
2601
|
|
|
2570
2602
|
---
|
|
2571
2603
|
|
|
2572
|
-
`)}function
|
|
2573
|
-
`)}function
|
|
2604
|
+
`)}function pY($,b){let A=[];switch(b){case"product":aY($,A);break;case"eng":eY($,A);break;case"qa":sY($,A);break}return A.join(`
|
|
2605
|
+
`)}function aY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2574
2606
|
${$.meta.goal}
|
|
2575
2607
|
`);if($.meta.context)b.push(`### Context
|
|
2576
2608
|
${$.meta.context}
|
|
2577
|
-
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((
|
|
2578
|
-
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((
|
|
2579
|
-
`)}export{
|
|
2609
|
+
`);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("- ✅ Enforces Business Policies");if($.hasIo)b.push("- ✅ Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((A)=>b.push(`- **${A.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function eY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"✅ Defined":"❌ Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"✅ Defined":"❌ None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((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 sY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2610
|
+
`);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 aE($,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 $T($,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 bT($,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 AT($,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 nT($){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(`
|
|
2611
|
+
`)}export{aE as watchSpecs,qB as vibe,WB as versioning,HX as verifyWithAIEnhanced,WA as verifyWithAI,wA as verifyStructure,FX as verifyService,F1 as verifySemanticFields,E7 as verifyImportedContracts,CR as verifyImplementationAgainstParsedSpec,T0 as verifyBehavior,sC as validateTenantConfig,iC as validateSpecs,p$ as validateSpec,b1 as validateScannedSpec,PC as validatePackageScaffold,TC as validateImplementationWithAgent,b0 as validateImplementationFiles,oC as validateDiscoveredSpecs,CC as validateBlueprint,iY as validateAudience,dz as validateAgainstOpenApiService,eW as utils,L1 as upgrade,Cx as updateSpec,JQ as toKebabCase,uW as templates,fz as syncWithOpenApiService,Sx as syncSpecs,jX as stringToCacheKey,ny as setupUsageMd,Q0 as setupGitignore,am as setupAgentsMd,RI as searchRegistry,a as safeParseJson,Ox as runTests,Jx as runTestSpecs,XC as runSetup,XI as runQuickstart,Vw as runDoctor,XK as runCIChecks,mw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,LQ 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,sH as operationRegistry,ij as onboarding,pm as normalizeMarkdownContent,tT as module,AT as mergeMonorepoConfigs,_0 as mergeManagedMarkdown,r4 as mergeGitignoreContent,P as loadWorkspaceConfig,mU as loadPackageAuthoredDocBlocks,kj as loadAuthoredModuleValue,hR as loadAuthoredModuleIfExists,U0 as loadAuthoredModuleExports,W$ as loadAuthoredModule,nU as loadAuthoredDocBlocksFromSourceFiles,Ux as listTests,lY as listSpecsForView,B$ as listSpecs,LI as listFromRegistry,Yn as listAgentTypes,Ub as isMonorepo,YI as isContractSpecInstalled,sO as isConnectPreset,eO as isBuilderPreset,Tb as inferSetupPresetFromConfig,OQ as inferImplementationType,z7 as importFromSourceService,Lj as importFromOpenApiService,$j as impact,vj as hooks,XV as groupSpecsByType,j5 as getWorkspacePackages,hy as getWorkspaceInfo,k3 as getRunCommand,im as getProductionDependencies,P$ as getPackageName,S5 as getMetaRepoInfo,dy as getInstallCommand,NU as getImplementationSummary,FO as getGraphStats,$T as getExtendedWorkspaceInfo,r3 as getExecCommand,lm as getDevDependencies,om as getDependencies,xw as getConventionPaths,DO as getContractNode,lA as getClaudeDesktopConfigPath,Tn as getBuilderRuntimeModeForPreset,yw as getBuilderBootstrapPresetForSetupPreset,tW as getApiKey,bV as getAllSpecs,qJ 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,iE as generateViews,tY 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,RR as generateMermaidDiagram,x7 as generateMarkdownReport,gW as generateKnowledgeSpaceSpec,GW as generateJobSpec,vW as generateIntegrationSpec,VW as generateHarnessSuiteSpec,UW as generateHarnessScenarioSpec,TW as generateHandlerTemplate,g7 as generateGuideFromParsedSpec,EW as generateFormSpec,MW as generateFeatureSpec,DR as generateFeatureContextMarkdown,xW as generateExperimentSpec,EA as generateExampleSpec,CW as generateEventSpec,zw as generateDocsFromSpecs,IW as generateDataViewSpec,TA as generateDataViewRendererTemplate,P7 as generateCursorRulesFromParsedSpec,Bw as generateCursorRules,Db as generateCursorMcpConfig,jb as generateContractsrcConfig,DW as generateComponentTemplate,M7 as generateCliReport,jw as generateClaudeMcpConfig,ZW as generateCapabilitySpec,Rw as generateArtifacts,RW as generateAppBlueprintSpec,Sw as generateAgentsGuide,OW as generateAgentSpec,AW as formatters,nT as formatWorkspaceInfo,xR as formatVerificationReport,HI as formatQuickstartPreview,rj as formatModuleLoadError,F as formatJson,sL as formatFiles,oJ as formatDoctorSummary,iJ as formatCheckResult,Ej as fix,x as findWorkspaceRoot,c as findPackageRoot,cy as findMetaRepoRoot,bT as findAllConfigFiles,AV as filterIssuesByType,nV as filterIssuesBySeverity,Ij as features,Iw as extractSpecReferences,$L as extractContracts,NR as exportSpecForLLM,N6 as exportOpenApi,NO as exportGraphAsDot,iW as ensurePackageScaffold,cA as discoverSpecs,h$ as discoverSpecFiles,pA as discoverLayers,A0 as discoverImplementationsForSpec,xU as discoverAllImplementations,Ew as determineStatus,Q5 as detectRepositoryType,e$ as detectPackageManager,Lz as deleteSpec,A$ as deepMergePreserve,Dn as deepMergeOverwrite,IA as cursorCLIAdapter,ex as createWorkspaceStateCacheStorage,F5 as createWorkspaceRegistry,NX as createVerifyService,wM as createVerificationCacheService,Jz as createSpecCreator,Ww as createSetupNextSteps,ww as createSetupGitignorePatterns,KI as createRegeneratorService,E0 as createQuickAIReview,rA as createPackageTargetSpecSource,vy as createNoopLoggerAdapter,gy as createNodeWatcherAdapter,Ny as createNodeGitAdapter,Ey as createNodeFsAdapter,Iy as createNodeAiAdapter,C3 as createNodeAdapters,px as createInMemoryCacheStorage,lx as createFileSystemCacheStorage,R9 as createEmptyLayerInventory,Fy as createConsoleLoggerAdapter,N3 as createBunFsAdapter,m9 as createBuilderWorkspaceId,X8 as createAgentGuideService,Uj as connect,E1 as computeContentHash,Cz as compareSpecs,VK as cleanArtifacts,LA as claudeCodeAdapter,T1 as cacheKeyToString,wb as buildSpec,dA as analyzeWorkspaceDocBlocks,n0 as analyzeIntegrity,nR as analyzeGap,sW as analyzeDeps,Y8 as agentGuideService,Xn as agentAdapters,Zn as adoption,zI as addToRegistry,dR as __moduleLoaderInternals,x1 as WorkspaceStateCacheStorage,gH as WorkspaceBundle,D0 as VerifyService,D1 as VerificationCacheService,OB as VALID_AUDIENCES,V2 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,QZ as RuleSyncService,K0 as RegistryClient,P5 as PrActionService,OA as OpenAICodexAgent,lj as MINIMAL_DEPENDENCIES,C1 as InMemoryCacheStorage,CA as GenericMCPAdapter,I1 as FileSystemCacheStorage,yZ as FULL_DEPENDENCIES,v5 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,OZ as CONTRACTSPEC_USAGE_BLOCK_START,JZ as CONTRACTSPEC_USAGE_BLOCK_END,XZ as CONTRACTSPEC_AGENTS_BLOCK_START,YZ as CONTRACTSPEC_AGENTS_BLOCK_END,GK 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,HK as ALL_CI_CHECK_CATEGORIES,Jw as ALL_CHECK_CATEGORIES,Y0 as AIGenerator};
|