@contractspec/bundle.workspace 4.4.0 → 4.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundles/WorkspaceBundle.d.ts +34 -0
- package/dist/contracts/operations/init.operation.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +935 -519
- package/dist/node/index.js +935 -519
- package/dist/services/adoption/catalog-core.d.ts +2 -0
- package/dist/services/adoption/catalog-entry.d.ts +2 -0
- package/dist/services/adoption/catalog-runtime.d.ts +2 -0
- package/dist/services/adoption/catalog-shared.d.ts +2 -0
- package/dist/services/adoption/catalog-solutions.d.ts +2 -0
- package/dist/services/adoption/catalog-ui.d.ts +2 -0
- package/dist/services/adoption/catalog.d.ts +3 -0
- package/dist/services/adoption/index.d.ts +6 -0
- package/dist/services/adoption/resolve.d.ts +6 -0
- package/dist/services/adoption/resolve.test.d.ts +1 -0
- package/dist/services/adoption/tokens.d.ts +6 -0
- package/dist/services/adoption/types.d.ts +99 -0
- package/dist/services/adoption/workspace-scan.d.ts +8 -0
- package/dist/services/adoption/workspace.d.ts +3 -0
- package/dist/services/connect/adoption.d.ts +10 -0
- package/dist/services/connect/types.d.ts +1 -1
- package/dist/services/deps.d.ts +1 -1
- package/dist/services/doctor/checks/config.test.d.ts +1 -0
- package/dist/services/index.d.ts +4 -0
- package/dist/services/integrity.d.ts +1 -1
- package/dist/services/onboarding/catalog.d.ts +4 -0
- package/dist/services/onboarding/index.d.ts +4 -0
- package/dist/services/onboarding/journey.d.ts +11 -0
- package/dist/services/onboarding/render.d.ts +5 -0
- package/dist/services/onboarding/service.d.ts +5 -0
- package/dist/services/onboarding/service.test.d.ts +1 -0
- package/dist/services/onboarding/types.d.ts +71 -0
- package/dist/services/package-declarations/helpers.d.ts +13 -0
- package/dist/services/package-declarations/index.d.ts +5 -0
- package/dist/services/package-declarations/inventory.d.ts +4 -0
- package/dist/services/package-declarations/render.d.ts +41 -0
- package/dist/services/package-declarations/sync.d.ts +8 -0
- package/dist/services/package-declarations/sync.test.d.ts +1 -0
- package/dist/services/package-declarations/types.d.ts +48 -0
- package/dist/services/setup/config-generators.d.ts +4 -0
- package/dist/services/setup/index.d.ts +3 -0
- package/dist/services/setup/managed-markdown.d.ts +8 -0
- package/dist/services/setup/setup-service.d.ts +17 -2
- package/dist/services/setup/targets/agents-md.d.ts +2 -0
- package/dist/services/setup/targets/index.d.ts +1 -0
- package/dist/services/setup/targets/usage-md.d.ts +5 -0
- package/dist/services/setup/targets/usage-md.test.d.ts +1 -0
- package/dist/services/setup/types.d.ts +2 -2
- package/dist/services/test/test-generator-service.d.ts +5 -1
- package/dist/services/validate/spec-validator.d.ts +1 -1
- package/dist/services/validate/spec-validator.test.d.ts +1 -0
- package/dist/services/versioning/index.d.ts +1 -0
- package/dist/services/versioning/release-authoring.d.ts +14 -0
- package/dist/services/versioning/release-authoring.test.d.ts +1 -0
- package/dist/services/versioning/release-files.d.ts +7 -0
- package/dist/services/versioning/release-service.types.d.ts +53 -1
- package/dist/services/workspace-info.d.ts +4 -1
- package/dist/templates/additional-contracts.template.d.ts +40 -0
- package/dist/templates/advanced-contracts.template.d.ts +39 -0
- package/dist/templates/index.d.ts +3 -0
- package/dist/templates/theme.template.d.ts +12 -0
- package/dist/templates/theme.template.test.d.ts +1 -0
- package/dist/types.d.ts +16 -11
- package/package.json +14 -13
package/dist/node/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)){if(!
|
|
3
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
4
|
-
`).map((
|
|
1
|
+
import{createRequire as VB}from"node:module";var HB=Object.defineProperty;var qB=($)=>$;function OB($,b){this[$]=qB.bind(null,b)}var f=($,b)=>{for(var n in b)HB($,n,{get:b[n],enumerable:!0,configurable:!0,set:OB.bind(b,n)})};var _y=($,b)=>()=>($&&(b=$($=0)),b);var F$=VB(import.meta.url);import{ContractsrcSchema as q8,DEFAULT_CONTRACTSRC as fn}from"@contractspec/lib.contracts-spec/workspace-config";async function P($,b){let n=$.join(b??".",".contractsrc.json");if(!await $.exists(n))return fn;try{let m=await $.readFile(n),y=JSON.parse(m),W=q8.safeParse(y);return{...fn,...W.data,conventions:{...fn.conventions,...W.data?.conventions||{}}}}catch{return fn}}function tW($){switch($){case"claude":return process.env.ANTHROPIC_API_KEY;case"openai":return process.env.OPENAI_API_KEY;case"custom":return process.env.CONTRACTSPEC_LLM_API_KEY;case"ollama":return;default:return}}var $$=()=>{};var Jj={};f(Jj,{AIGenerator:()=>GA});import{createProvider as G6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as H6,buildEventSpecPrompt as q6,buildFormPrompt as O6,buildHandlerPrompt as V6,buildOperationSpecPrompt as J6,buildPresentationSpecPrompt as U6,buildTestPrompt as K6,getCodeGenSystemPrompt as tb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Mm,generateText as YA,streamText as _6}from"ai";import*as R from"zod";class GA{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||tW(this.config.aiProvider),n={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return G6(n).getModel()}async generateOperationSpec($,b){let n=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.operation"'),version:R.number().int().positive().default(1),description:R.string().describe("Clear, concise summary"),goal:R.string().describe("Business purpose"),context:R.string().describe("Background and constraints"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).describe("Team/person owners with @ prefix"),tags:R.array(R.string()).describe("Categorization tags"),auth:R.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:R.string().describe("Description of input structure"),outputShape:R.string().describe("Description of output structure"),flags:R.array(R.string()).describe("Feature flags").default([]),possibleEvents:R.array(R.string()).describe("Events this may emit").default([]),analytics:R.array(R.string()).describe("Analytics events to track").default([])}),m=J6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateEventSpec($){let b=this.getModel(),n=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),A=q6($);return(await Mm({model:b,schema:n,prompt:A,system:Em()})).object}async generatePresentationSpec($,b){let n=this.getModel(),A=R.object({name:R.string(),version:R.number().int().positive().default(1),description:R.string(),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),componentKey:R.string().optional(),propsShape:R.string().optional(),content:R.string().optional(),mimeType:R.string().optional(),dataShape:R.string().optional()}),m=U6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateHandler($){let b=this.getModel();return(await YA({model:b,prompt:V6($),system:tb()})).text}async generateComponent($){let b=this.getModel();return(await YA({model:b,prompt:H6($),system:tb()})).text}async generateForm($){let b=this.getModel();return(await YA({model:b,prompt:O6($),system:tb()})).text}async generateTests($,b,n){let A=this.getModel();return(await YA({model:A,prompt:K6($,b,n),system:tb()})).text}async streamCodeGeneration($,b){let n=this.getModel(),A=await _6({model:n,prompt:$,system:tb()}),m="";for await(let y of A.textStream)m+=y,b(y);return m}}var HA=_y(()=>{$$()});import*as gT from"@contractspec/module.workspace";import{anthropic as JB}from"@ai-sdk/anthropic";import{openai as zy}from"@ai-sdk/openai";import{DEFAULT_MODELS as Ly}from"@contractspec/lib.ai-providers/models";import{generateObject as UB,generateText as KB,streamText as _B}from"ai";import{ollama as zB}from"ollama-ai-provider";function Ry($){return{async validateProvider(b){try{let{aiProvider:n}=b;if(n==="ollama")return{success:!0};if(n==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(n==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}},async generateText(b){let n=tA($);return{text:(await KB({model:n,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let A={model:tA($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await UB(A)).object}},async streamText(b,n){let A=tA($),m=await _B({model:A,prompt:b.prompt,system:b.systemPrompt}),y="";for await(let W of m.textStream)y+=W,n(W);return y}}}function tA($){let{aiProvider:b,aiModel:n,customEndpoint:A}=$;switch(b){case"claude":{let m=n??Ly.anthropic;return JB(m)}case"openai":{let m=n??Ly.openai;return zy(m)}case"ollama":return zB(n??"codellama");case"custom":{if(!A)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return zy(n??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as hB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as LB,stat as RB,mkdir as Cy,readFile as CB,rm as xB,writeFile as IB}from"node:fs/promises";import{basename as EB,dirname as xy,isAbsolute as MB,join as TB,relative as DB,resolve as Iy}from"node:path";import{glob as NB}from"glob";var q$=["**/*.command.ts","**/*.query.ts","**/*.operation.ts","**/*.operations.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts","**/*.capability.ts","**/*.workflow.ts","**/*.data-view.ts","**/*.form.ts","**/*.migration.ts","**/*.telemetry.ts","**/*.experiment.ts","**/*.app-config.ts","**/*.integration.ts","**/*.knowledge.ts","**/*.policy.ts","**/*.test-spec.ts","**/blueprint.ts","**/integration.ts","**/example.ts","**/bundles/*Bundle.ts","**/contracts/*.ts","**/contracts/index.ts","**/commands/*.ts","**/commands/index.ts","**/queries/*.ts","**/queries/index.ts","**/operations/*.ts","**/operations/index.ts","**/operations.ts","**/events.ts","**/presentations.ts","**/events/index.ts","**/presentations/index.ts","**/tests/*.ts","**/tests/*.test-spec.ts"],v$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function Ey($){let b=$??process.cwd();return{async exists(A){try{return await LB(n(A)),!0}catch{return!1}},async readFile(A){return CB(n(A),"utf-8")},async writeFile(A,m){let y=n(A),W=xy(y);await Cy(W,{recursive:!0}),await IB(y,m,"utf-8")},async remove(A){await xB(n(A),{recursive:!0,force:!0})},async stat(A){let m=await RB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await Cy(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return(await NB(m,{cwd:W,ignore:y,absolute:w})).sort((B,S)=>B.localeCompare(S))},resolve(...A){let[m,...y]=A;if(!m)return b;return Iy(b,m,...y)},dirname(A){return xy(A)},basename(A){return EB(A)},join(...A){return TB(...A)},relative(A,m){return DB(A,m)}};function n(A){return MB(A)?A:Iy(b,A)}}import{spawnSync as FB}from"node:child_process";import{existsSync as My,readFileSync as Ty}from"node:fs";import{access as vB}from"node:fs/promises";import{resolve as Xn}from"node:path";function Dy($){let b=$??process.cwd();return{async currentBranch(){try{let n=Ob(["rev-parse","--abbrev-ref","HEAD"],b).trim()||gB(b);return n.length>0?n:void 0}catch{return}},async showFile(n,A){try{let m=Ob(["show",`${n}:${A}`],b);if(m.length>0||n!=="HEAD")return m;return PB(b,A)??m}catch(m){throw Error(`Could not load ${A} at ref ${n}: ${m instanceof Error?m.message:String(m)}`)}},async clean(n){let A=[];if(n?.force)A.push("-f");if(n?.directories)A.push("-d");if(n?.ignored)A.push("-x");if(n?.dryRun)A.push("--dry-run");Ob(["clean",...A],b,{inherit:!0})},async isGitRepo(n){let A=n?Xn(b,n):b;try{return await vB(Xn(A,".git")),!0}catch{return!1}},async log(n){let A=n??"HEAD~10",m="--format=%H|||%s|||%an|||%aI";try{let y=Ob(["log",`${A}..HEAD`,"--format=%H|||%s|||%an|||%aI"],b),W=[];for(let w of y.trim().split(`
|
|
2
|
+
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(n,A){try{let m=A&&A.length>0?["--",...A]:[];return Ob(["diff","--name-only",`${n}...HEAD`,...m],b).trim().split(`
|
|
3
|
+
`).filter(Boolean)}catch{return[]}}}}function gB($){let b=Xn($,".git","HEAD");if(!My(b))return"";let n=Ty(b,"utf8").trim(),A="ref: refs/heads/";return n.startsWith(A)?n.slice(A.length):n}function PB($,b){let n=Xn($,b);if(!My(n))return;return Ty(n,"utf8")}function Ob($,b,n={}){let A=FB("git",$,{cwd:b,encoding:"utf-8",stdio:n.inherit?"inherit":["ignore","pipe","pipe"]});if(A.error)throw A.error;if(A.status!==0)throw Error(typeof A.stderr==="string"&&A.stderr.length>0?A.stderr:`git ${$.join(" ")} failed with status ${A.status??"unknown"}`);return typeof A.stdout==="string"?A.stdout:""}function Ny(){return{debug($,b){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,b??"")},info($,b){console.info(`[INFO] ${$}`,b??"")},warn($,b){console.warn(`[WARN] ${$}`,b??"")},error($,b){console.error(`[ERROR] ${$}`,b??"")},createProgress(){return kB()}}}function Fy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:rB}}function kB(){return{start($){console.warn(`⏳ ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`✅ ${$??"Done"}`)},fail($){console.error(`❌ ${$??"Failed"}`)},warn($){console.warn(`⚠️ ${$??"Warning"}`)},stop(){}}}function rB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import fB from"chokidar";var cB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function vy($){let b=$??process.cwd();return{watch(n){let A=[],m,y=fB.watch(n.pattern,{cwd:b,ignored:n.ignore??cB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),W=(w)=>{if(n.debounceMs&&n.debounceMs>0)clearTimeout(m),m=setTimeout(()=>{A.forEach((j)=>j(w))},n.debounceMs);else A.forEach((j)=>j(w))};return y.on("add",(w)=>{W({type:"add",path:w})}),y.on("change",(w)=>{W({type:"change",path:w})}),y.on("unlink",(w)=>{W({type:"unlink",path:w})}),{on(w){A.push(w)},async close(){clearTimeout(m),await y.close()}}}}}function HG($={}){let{cwd:b,config:n,silent:A}=$,m=n??hB;return{fs:Ey(b),git:Dy(b),watcher:vy(b),ai:Ry(m),logger:A?Fy():Ny()}}import{stat as dB,mkdir as uB}from"node:fs/promises";import{basename as oB,dirname as iB,isAbsolute as tB,join as lB,relative as pB,resolve as gy}from"node:path";import{glob as aB}from"glob";function KG($){let b=$??process.cwd();return{async exists(A){let m=Bun.file(n(A));try{return await m.exists(),!0}catch{return!1}},async readFile(A){return Bun.file(n(A)).text()},async writeFile(A,m){let y=n(A);await Bun.write(y,m)},async remove(A){await Bun.file(n(A)).delete()},async stat(A){let m=await dB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await uB(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return await aB(m,{cwd:W,ignore:y,absolute:w})},resolve(...A){let[m,...y]=A;if(!m)return b;return gy(b,m,...y)},dirname(A){return iB(A)},basename(A){return oB(A)},join(...A){return lB(...A)},relative(A,m){return pB(A,m)}};function n(A){return tB(A)?A:gy(b,A)}}import{existsSync as u,readFileSync as z$}from"node:fs";import{tmpdir as eB}from"node:os";import{dirname as lA,isAbsolute as sB,join as d,relative as $S,resolve as p$}from"node:path";var Py={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},ky=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function bS($,b){let n=$S(b,$);return n===""||!n.startsWith("..")&&!sB(n)}function pA($){let b=p$($),n=p$(eB());return bS(b,n)?n:void 0}function c($=process.cwd()){let b=p$($),n=pA($);while(!0){if(u(d(b,"package.json")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return $}function I($=process.cwd()){let b=p$($),n=null,A=pA($);while(!0){for(let W of ky)if(u(d(b,W)))return b;let m=d(b,"package.json");if(u(m)){n=b;try{if(JSON.parse(z$(m,"utf-8")).workspaces)return b}catch{}}for(let W of Object.keys(Py))if(u(d(b,W)))return b;let y=lA(b);if(y===b||b===A)break;b=y}return n??$}function a$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let A of b){let m=Object.entries(Py).filter(([,y])=>y===A);for(let[y]of m)if(u(d($,y)))return A}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(A.packageManager){let m=A.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(m)return m[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Vb($=process.cwd()){for(let n of ky)if(u(d($,n)))return!0;let b=d($,"package.json");if(u(b))try{if(JSON.parse(z$(b,"utf-8")).workspaces)return!0}catch{}return!1}function nS($){let b=d($,"pnpm-workspace.yaml");if(u(b))try{let m=z$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(m?.[1])return m[1].split(`
|
|
4
|
+
`).map((W)=>W.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(Array.isArray(A.workspaces))return A.workspaces;if(A.workspaces?.packages&&Array.isArray(A.workspaces.packages))return A.workspaces.packages}catch{}return}function g$($){let b=d($,"package.json");if(u(b))try{return JSON.parse(z$(b,"utf-8")).name}catch{}return}function ry($){let b=d($,".gitmodules");if(!u(b))return[];try{let n=z$(b,"utf-8"),A=[],m=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,y;while((y=m.exec(n))!==null){let[,W,w,j]=y;if(W&&w&&j){let B=d($,w),S=u(d(B,"package.json"))&&AS(B);A.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return A}catch{return[]}}function AS($){let b=d($,"package.json");if(u(b))try{let n=JSON.parse(z$(b,"utf-8"));return Boolean(n.workspaces)}catch{}return u(d($,"pnpm-workspace.yaml"))}function fy($){let b=p$($),n=pA($);while(!0){if(u(d(b,".gitmodules")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return}function mS($){let b=fy($);if(!b)return;let n=ry(b);if(n.length===0)return;let A=p$($),m=n.find((y)=>A.startsWith(y.absolutePath));return{root:b,submodules:n,activeSubmodule:m}}function yS($,b){let n=fy($);if(n){if(ry(n).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function cy($=process.cwd()){let b=c($),n=I($),A=a$(n),m=Vb(n),y=m?nS(n):void 0,W=g$(b),w=yS($,m),j=w==="meta-repo"?mS($):void 0;return{packageManager:A,workspaceRoot:n,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function CG($,b){switch($){case"bun":return`bun run ${b}`;case"pnpm":return`pnpm run ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npm run ${b}`}}function xG($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function hy($,b=!1){let n=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${n}`.trim();case"pnpm":return`pnpm add ${n}`.trim();case"yarn":return`yarn add ${n}`.trim();case"npm":return`npm install ${n}`.trim()}}import{anthropic as dy}from"@ai-sdk/anthropic";import{generateText as uy}from"ai";class Yn{name="claude-code";apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set. Claude Code agent requires API access."]};try{let b=dy("claude-3-7-sonnet-20250219"),n=this.buildSystemPrompt($),A=this.buildUserPrompt($),m=await uy({model:b,prompt:A,system:n,temperature:0.2});return{success:!0,code:this.extractCode(m.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:m.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let b=dy("claude-3-7-sonnet-20250219"),n=`
|
|
5
5
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
6
6
|
|
|
7
7
|
SPECIFICATION:
|
|
@@ -30,7 +30,7 @@ Provide a structured validation report:
|
|
|
30
30
|
- Are there any missing edge cases?
|
|
31
31
|
|
|
32
32
|
Be thorough and precise. Use a critical but constructive tone.
|
|
33
|
-
`,A=await
|
|
33
|
+
`,A=await uy({model:b,prompt:n,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),suggestions:this.extractSuggestions(A.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
34
34
|
|
|
35
35
|
Your code is:
|
|
36
36
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -50,7 +50,7 @@ Your code is:
|
|
|
50
50
|
- Following SOLID principles and best practices
|
|
51
51
|
- Modular and testable
|
|
52
52
|
|
|
53
|
-
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let
|
|
53
|
+
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let b={generate:`Generate a complete, production-ready implementation for this specification:
|
|
54
54
|
|
|
55
55
|
${$.specCode}
|
|
56
56
|
|
|
@@ -73,10 +73,10 @@ Spec:
|
|
|
73
73
|
${$.specCode}
|
|
74
74
|
|
|
75
75
|
Code:
|
|
76
|
-
${$.existingCode}`};return
|
|
77
|
-
`);for(let A of
|
|
78
|
-
`);for(let A of
|
|
79
|
-
`);for(let A of
|
|
76
|
+
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
77
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("error")||m.includes("bug")||m.includes("incorrect")||m.includes("missing"))b.push(A.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],n=$.split(`
|
|
78
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("warning")||m.includes("should")||m.includes("consider"))b.push(A.trim())}return b}extractSuggestions($){let b=[],n=$.split(`
|
|
79
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("suggest")||m.includes("recommend")||m.includes("could")||m.includes("improvement"))b.push(A.trim())}return b}}import{spawn as WS}from"child_process";import{existsSync as oy}from"fs";import{mkdir as iy,readFile as wS,rm as jS,writeFile as Y$}from"fs/promises";import{homedir as aA,tmpdir as ty}from"os";import{join as o}from"path";class Gn{name="cursor";cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||"3000",this.detectEnvironment()}canHandle($){return this.isCursorAvailable()}async generate($){try{let b=o(ty(),`cursor-agent-${Date.now()}`);await iy(b,{recursive:!0});let n=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=o(ty(),`cursor-validate-${Date.now()}`);await iy(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let n=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",o(aA(),".cursor","cursor"),o(aA(),"AppData","Local","Programs","cursor","Cursor.exe"),o(aA(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let b of $)if(b.includes("cursor")||b.includes("Cursor")||b.includes("windsurf")||b.includes("Windsurf"))try{if(oy(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let n=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let A of n)try{let m=await A.fn();if(m.success)return m}catch(m){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,b){if(!this.cursorPath)throw Error("Cursor executable not found");let n=o(b,"spec.ts"),A=o(b,"output.ts"),m=o(b,"INSTRUCTIONS.md");if(await Y$(n,$.specCode),await Y$(m,this.buildDetailedPrompt($)),$.existingCode)await Y$(o(b,"existing.ts"),$.existingCode);return new Promise((y,W)=>{let w=["--wait","--new-window",b],j=WS(this.cursorPath,w,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";j.stdout?.on("data",(Q)=>{B+=Q.toString()}),j.stderr?.on("data",(Q)=>{S+=Q.toString()}),j.on("error",(Q)=>{W(Q)}),j.on("close",async(Q)=>{if(oy(A))try{let Z=await wS(A,"utf-8");y({success:!0,code:Z,metadata:{agentMode:"cursor",method:"cli",exitCode:Q}})}catch(Z){W(Error("Failed to read generated output"))}else W(Error(`Cursor CLI exited with code ${Q}. No output generated.`))}),setTimeout(()=>{j.kill(),W(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let n=o(b,"SPECIFICATION.ts"),A=o(b,"INSTRUCTIONS.md"),m=o(b,"template.ts");return await Y$(n,$.specCode),await Y$(A,this.buildDetailedPrompt($)),await Y$(m,this.generateTemplate($)),await Y$(o(b,"README.md"),`# Cursor Agent Workspace
|
|
80
80
|
|
|
81
81
|
This workspace was prepared for Cursor AI code generation.
|
|
82
82
|
|
|
@@ -91,13 +91,13 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
91
91
|
3. Use Cursor AI to generate code based on the spec
|
|
92
92
|
4. Save the result as output.ts
|
|
93
93
|
|
|
94
|
-
Workspace path: ${
|
|
95
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${
|
|
94
|
+
Workspace path: ${b}
|
|
95
|
+
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Y$(o(b,"specification.ts"),$.specCode),await Y$(o(b,"implementation.ts"),$.existingCode||"// No implementation"),await Y$(o(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let n=[{path:"spec.ts",content:$.specCode}];if($.existingCode)n.push({path:"existing.ts",content:$.existingCode});return n}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
96
96
|
|
|
97
97
|
**Task Type:** ${$.type}
|
|
98
98
|
**Generated:** ${new Date().toISOString()}
|
|
99
99
|
|
|
100
|
-
`,
|
|
100
|
+
`,n=`## Specification
|
|
101
101
|
|
|
102
102
|
\`\`\`typescript
|
|
103
103
|
${$.specCode}
|
|
@@ -196,7 +196,7 @@ ${$.existingCode||""}
|
|
|
196
196
|
- Enhance error messages
|
|
197
197
|
|
|
198
198
|
### Output Format:
|
|
199
|
-
Refactored code that maintains functionality while improving quality.`};return
|
|
199
|
+
Refactored code that maintains functionality while improving quality.`};return b+n+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
200
200
|
|
|
201
201
|
## Specification
|
|
202
202
|
\`\`\`typescript
|
|
@@ -244,7 +244,7 @@ Provide detailed feedback for each failed item.
|
|
|
244
244
|
Suggest specific improvements with code examples where applicable.`}generateTemplate($){return`// Auto-generated template for ${$.type} task
|
|
245
245
|
// Specification:
|
|
246
246
|
${$.specCode.split(`
|
|
247
|
-
`).map((
|
|
247
|
+
`).map((b)=>`// ${b}`).join(`
|
|
248
248
|
`)}
|
|
249
249
|
|
|
250
250
|
// TODO: Implement according to specification
|
|
@@ -254,7 +254,7 @@ export function implementation() {
|
|
|
254
254
|
// Implementation goes here
|
|
255
255
|
throw new Error('Not implemented');
|
|
256
256
|
}
|
|
257
|
-
`}async cleanupWorkDir($){try{await
|
|
257
|
+
`}async cleanupWorkDir($){try{await jS($,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}}import{openai as ly}from"@ai-sdk/openai";import{generateText as py}from"ai";class Hn{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let n=this.isComplexTask($)?"o1":"gpt-5.4",A=ly(n),m=this.buildSystemPrompt($),y=this.buildUserPrompt($),W=await py({model:A,prompt:y,system:m,temperature:0.2});return{success:!0,code:this.extractCode(W.text),metadata:{model:n,agentMode:"openai-codex",usage:W.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=ly("gpt-5.4"),n=`
|
|
258
258
|
Review this code implementation against its specification.
|
|
259
259
|
|
|
260
260
|
SPECIFICATION:
|
|
@@ -274,7 +274,7 @@ Provide a detailed validation report including:
|
|
|
274
274
|
4. Recommendations for improvement
|
|
275
275
|
|
|
276
276
|
Format as a structured report.
|
|
277
|
-
`,A=await
|
|
277
|
+
`,A=await py({model:b,prompt:n,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],n=($.specCode+($.existingCode||"")).toLowerCase();return b.some((A)=>n.includes(A))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
278
278
|
|
|
279
279
|
Generate production-quality code that is:
|
|
280
280
|
- Type-safe and well-typed
|
|
@@ -311,9 +311,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
311
311
|
${$.existingCode}
|
|
312
312
|
|
|
313
313
|
Spec:
|
|
314
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let
|
|
315
|
-
`);for(let A of
|
|
316
|
-
`);for(let A of
|
|
314
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
315
|
+
`);for(let A of n)if(A.toLowerCase().includes("error")||A.toLowerCase().includes("bug")||A.toLowerCase().includes("fails"))b.push(A.trim());return b}extractWarnings($){let b=[],n=$.split(`
|
|
316
|
+
`);for(let A of n)if(A.toLowerCase().includes("warning")||A.toLowerCase().includes("should")||A.toLowerCase().includes("consider"))b.push(A.trim());return b}}import P$ from"chalk";import QS from"ora";import{generateText as ay}from"ai";var A0={};f(A0,{getCodeGenSystemPrompt:()=>n0,buildTestPrompt:()=>b0,buildHandlerPrompt:()=>eA,buildFormPrompt:()=>$0,buildComponentPrompt:()=>sA});function eA($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
317
317
|
|
|
318
318
|
Here is the contract spec:
|
|
319
319
|
|
|
@@ -332,7 +332,7 @@ Generate a complete handler implementation that:
|
|
|
332
332
|
|
|
333
333
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
334
334
|
|
|
335
|
-
Return only the TypeScript code for the handler function.`}function
|
|
335
|
+
Return only the TypeScript code for the handler function.`}function sA($){return`You are a senior React developer creating a component for a presentation specification.
|
|
336
336
|
|
|
337
337
|
Here is the presentation spec:
|
|
338
338
|
|
|
@@ -351,7 +351,7 @@ Generate a complete React component that:
|
|
|
351
351
|
|
|
352
352
|
The component should follow Atomic Design principles and be reusable.
|
|
353
353
|
|
|
354
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
354
|
+
Return only the TypeScript/TSX code for the component.`}function $0($){return`You are a senior React developer creating a form component from a form specification.
|
|
355
355
|
|
|
356
356
|
Here is the form spec:
|
|
357
357
|
|
|
@@ -371,7 +371,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
371
371
|
|
|
372
372
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
373
373
|
|
|
374
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
374
|
+
Return only the TypeScript/TSX code for the form component.`}function b0($,b,n){return`You are a senior developer writing comprehensive tests.
|
|
375
375
|
|
|
376
376
|
Spec:
|
|
377
377
|
\`\`\`typescript
|
|
@@ -380,11 +380,11 @@ ${$}
|
|
|
380
380
|
|
|
381
381
|
Implementation:
|
|
382
382
|
\`\`\`typescript
|
|
383
|
-
${
|
|
383
|
+
${b}
|
|
384
384
|
\`\`\`
|
|
385
385
|
|
|
386
386
|
Generate complete test suite using Vitest that:
|
|
387
|
-
${
|
|
387
|
+
${n==="handler"?`
|
|
388
388
|
- Test all acceptance scenarios from the spec
|
|
389
389
|
- Test error cases defined in spec.io.errors
|
|
390
390
|
- Verify events are emitted correctly
|
|
@@ -398,7 +398,7 @@ ${j==="handler"?`
|
|
|
398
398
|
|
|
399
399
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
400
400
|
|
|
401
|
-
Return only the TypeScript test code.`}function
|
|
401
|
+
Return only the TypeScript test code.`}function n0(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
402
402
|
- Type-safe API design
|
|
403
403
|
- React and modern hooks
|
|
404
404
|
- Test-driven development
|
|
@@ -412,7 +412,7 @@ Generate production-ready code that is:
|
|
|
412
412
|
- Defensive and error-safe
|
|
413
413
|
- Easy to maintain and extend
|
|
414
414
|
|
|
415
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
415
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as BS}from"@contractspec/lib.ai-providers";function m0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return BS(b)}class qn{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=m0(this.config),n=this.buildPrompt($),A=await ay({model:b,prompt:n,system:n0()});return{success:!0,code:A.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=m0(this.config),n=`
|
|
416
416
|
Review the following implementation against its specification.
|
|
417
417
|
|
|
418
418
|
Specification:
|
|
@@ -426,17 +426,17 @@ Provide a detailed validation report:
|
|
|
426
426
|
2. Are there any missing features?
|
|
427
427
|
3. Are there any bugs or issues?
|
|
428
428
|
4. Suggestions for improvement
|
|
429
|
-
`,A=await
|
|
430
|
-
${$.specCode}`;case"test":return
|
|
431
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
429
|
+
`,A=await ay({model:b,prompt:n,system:"You are a code review expert. Provide thorough, constructive feedback."}),m=A.text.toLowerCase().includes("error")||A.text.toLowerCase().includes("missing")||A.text.toLowerCase().includes("incorrect");return{success:!m,code:A.text,warnings:m?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return eA($.specCode);else if($.specCode.includes(".presentation."))return sA($.specCode);else if($.specCode.includes(".form."))return $0($.specCode);return`Generate implementation for:
|
|
430
|
+
${$.specCode}`;case"test":return b0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
431
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as SS}from"@contractspec/lib.ai-agent/agent/unified-agent";class y0{name;agent;constructor($,b,n={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=SS(n,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),n=await this.agent.run(b);return{success:!0,code:n.text,metadata:{finishReason:n.finishReason,usage:n.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
432
432
|
${$.specCode}
|
|
433
433
|
|
|
434
|
-
`;if($.existingCode)
|
|
434
|
+
`;if($.existingCode)b+=`Existing Code:
|
|
435
435
|
${$.existingCode}
|
|
436
436
|
|
|
437
|
-
`;switch($.type){case"generate":
|
|
437
|
+
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class On{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new qn($),n=new Gn,A=new Yn,m=new Hn;this.agents.set("simple",b),this.agents.set("cursor",n),this.agents.set("claude-code",A),this.agents.set("openai-codex",m),this.defaultAgent=b,this.agents.set("opencode-sdk",new y0("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),n=this.agents.get(b);if(!n)return console.log(P$.yellow(`⚠️ Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!n.canHandle($))return console.log(P$.yellow(`⚠️ Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let A=QS(`Executing with ${b} agent...`).start();try{let m=$.type==="validate"?await n.validate($):await n.generate($);if(m.success)return A.succeed(P$.green(`${b} agent completed successfully`)),m;A.warn(P$.yellow(`${b} agent failed, trying fallback...`));let y=this.getFallbackMode(b);if(y&&y!==b){let W=this.agents.get(y);if(W&&W.canHandle($))return $.type==="validate"?await W.validate($):await W.generate($)}return A.info(P$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(m){return A.fail(P$.red("Agent execution failed")),console.log(P$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,n]of this.agents){let A={type:"generate",specCode:"test"},m=n.canHandle(A);$.push({mode:b,available:m,reason:m?void 0:"Not configured or dependencies missing"})}return $}getAgentMode(){return this.config.agentMode||"simple"}getFallbackMode($){return{cursor:"claude-code","claude-agent-sdk":"claude-code","claude-code":"openai-codex","openai-codex":"simple",opencode:"opencode-sdk","opencode-sdk":"claude-code",simple:"simple"}[$]}}var ey={};f(ey,{specCreation:()=>W0,codeGeneration:()=>A0});var W0={};f(W0,{getSystemPrompt:()=>GS,buildPresentationSpecPrompt:()=>YS,buildOperationSpecPrompt:()=>ZS,buildEventSpecPrompt:()=>XS,addExampleContext:()=>HS});function ZS($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
438
438
|
|
|
439
|
-
The operation is a ${
|
|
439
|
+
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
440
440
|
|
|
441
441
|
User description: ${$}
|
|
442
442
|
|
|
@@ -452,7 +452,7 @@ Create a complete contract specification following these guidelines:
|
|
|
452
452
|
8. **Feature Flags**: Any flags that gate this operation
|
|
453
453
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
454
454
|
|
|
455
|
-
Respond with a structured spec.`}function
|
|
455
|
+
Respond with a structured spec.`}function XS($){return`You are a senior software architect creating an event specification.
|
|
456
456
|
|
|
457
457
|
User description: ${$}
|
|
458
458
|
|
|
@@ -466,9 +466,9 @@ Create a complete event specification following these guidelines:
|
|
|
466
466
|
|
|
467
467
|
Events represent things that have already happened and should use past tense.
|
|
468
468
|
|
|
469
|
-
Respond with a structured spec.`}function
|
|
469
|
+
Respond with a structured spec.`}function YS($,b){return`You are a senior software architect creating a presentation specification.
|
|
470
470
|
|
|
471
|
-
This is a ${
|
|
471
|
+
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
472
472
|
|
|
473
473
|
User description: ${$}
|
|
474
474
|
|
|
@@ -478,13 +478,13 @@ Create a complete presentation specification following these guidelines:
|
|
|
478
478
|
2. **Version**: Start at 1
|
|
479
479
|
3. **Description**: What this presentation shows/provides
|
|
480
480
|
4. **Kind-specific details**:
|
|
481
|
-
${
|
|
481
|
+
${b==="web_component"?`- Component key (symbolic, resolved by host app)
|
|
482
482
|
- Props structure
|
|
483
|
-
- Analytics events to track`:
|
|
483
|
+
- Analytics events to track`:b==="markdown"?`- Content or resource URI
|
|
484
484
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
485
485
|
- Data structure description`}
|
|
486
486
|
|
|
487
|
-
Respond with a structured spec.`}function
|
|
487
|
+
Respond with a structured spec.`}function GS(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
488
488
|
|
|
489
489
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
490
490
|
|
|
@@ -494,111 +494,362 @@ Your specs are:
|
|
|
494
494
|
- Business-oriented (capturing the "why" not just "what")
|
|
495
495
|
- Designed for both humans and AI agents to understand
|
|
496
496
|
|
|
497
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
497
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function HS($,b){if(b.length===0)return $;return`${$}
|
|
498
498
|
|
|
499
499
|
Here are some good examples for reference:
|
|
500
500
|
|
|
501
|
-
${
|
|
501
|
+
${b.join(`
|
|
502
502
|
|
|
503
503
|
`)}
|
|
504
504
|
|
|
505
|
-
Follow this structure and quality level.`}var
|
|
506
|
-
`)}function
|
|
505
|
+
Follow this structure and quality level.`}import{defineModuleBundle as qS}from"@contractspec/lib.surface-runtime/spec";var L3=qS({meta:{key:"bundles.workspace",version:"1.0.0",title:"Workspace",description:"Workspace utilities for monorepo development"},routes:[{routeId:"default",path:"/",defaultSurface:"main"}],surfaces:{main:{surfaceId:"main",kind:"workbench",title:"Workspace",slots:[],layouts:[],data:[],verification:{dimensions:{guidance:"Scaffolded guidance profile for Workspace.",density:"Scaffolded density profile for Workspace.",dataDepth:"Scaffolded data-depth profile for Workspace.",control:"Scaffolded control profile for Workspace.",media:"Scaffolded media profile for Workspace.",pace:"Scaffolded pace profile for Workspace.",narrative:"Scaffolded narrative profile for Workspace."}}}}});var bW={};f(bW,{sarifToJson:()=>_S,formatAsTextLines:()=>$W,formatAsText:()=>zS,formatAsSarif:()=>JS,formatAsJson:()=>OS});function OS($,b={}){let{pretty:n=!0,driftResult:A}=b,m=$.issues.map((S)=>({name:S.ruleId,status:S.severity==="error"?"fail":S.severity==="warning"?"warn":"pass",category:S.category,message:S.message,file:S.file,line:S.line,details:S.context})),y=$.categories.filter((S)=>S.passed).length,W=$.totalErrors,w=$.totalWarnings,j=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:m,categories:$.categories.map((S)=>({category:S.category,label:S.label,passed:S.passed,errors:S.errors,warnings:S.warnings,notes:S.notes,durationMs:S.durationMs})),drift:{status:A?.hasDrift?"detected":"none",files:A?.files??[]},summary:{pass:y,fail:W,warn:w,note:j,total:y+W+w+j,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return n?JSON.stringify(B,null,2):JSON.stringify(B)}var VS={"spec-structure-error":{name:"Spec Structure Error",description:"Contract specification is missing required structure elements"},"spec-structure-warning":{name:"Spec Structure Warning",description:"Contract specification has recommended but missing elements"},"integrity-orphaned":{name:"Orphaned Spec",description:"Contract specification is not linked to any feature"},"integrity-unresolved-ref":{name:"Unresolved Reference",description:"Contract specification references a non-existent spec"},"integrity-missing-feature":{name:"Missing Feature",description:"Feature referenced by spec does not exist"},"integrity-broken-link":{name:"Broken Link",description:"Link between specs is broken"},"deps-circular":{name:"Circular Dependency",description:"Circular dependency detected between contracts"},"deps-missing":{name:"Missing Dependency",description:"Contract depends on a non-existent contract"},"handler-missing":{name:"Missing Handler",description:"Handler implementation file does not exist for this contract"},"handler-warning":{name:"Handler Warning",description:"Handler implementation has potential issues"},"test-missing":{name:"Missing Test",description:"Test file does not exist for this contract"},"test-warning":{name:"Test Warning",description:"Test implementation has potential issues"}};function JS($,b={}){let{toolName:n="ContractSpec",toolVersion:A="1.0.0",toolUri:m="https://contractspec.io",repositoryUri:y,workingDirectory:W}=b,w=new Map,j=new Map,B=$.issues.filter((X)=>X.file);for(let X of B)if(!w.has(X.ruleId)){let Y=VS[X.ruleId]??{name:X.ruleId,description:`Rule: ${X.ruleId}`},G={id:X.ruleId,name:Y.name,shortDescription:{text:Y.description},defaultConfiguration:{level:sy(X.severity)}};if(Y.helpUri)G.helpUri=Y.helpUri;j.set(X.ruleId,w.size),w.set(X.ruleId,G)}let S=B.map((X)=>{let Y={ruleId:X.ruleId,ruleIndex:j.get(X.ruleId)??0,level:sy(X.severity),message:{text:X.message}},G={physicalLocation:{artifactLocation:{uri:US(X.file),uriBaseId:"%SRCROOT%"}}};if(X.line!==void 0)G.physicalLocation.region={startLine:X.line,startColumn:X.column??1,endLine:X.endLine??X.line,endColumn:X.endColumn};return Y.locations=[G],Y.partialFingerprints={primaryLocationLineHash:KS(X)},Y}),Q=[];if(y)Q.push({repositoryUri:y,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:n,version:A,informationUri:m,rules:Array.from(w.values())}},results:S,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...W&&{workingDirectory:{uri:W}}}]};if(Q.length>0)Z.versionControlProvenance=Q;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[Z]}}function sy($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function US($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function KS($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function _S($){return JSON.stringify($,null,2)}function $W($,b={}){let n=[],{verbose:A=!1,showTiming:m=!0,groupByFile:y=!1}=b;if(n.push({text:"",style:"normal"}),n.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),n.push({text:"",style:"normal"}),$.commitSha||$.branch){let w=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");n.push({text:`Git: ${w}`,style:"muted"})}n.push({text:"",style:"normal"}),n.push({text:"Check Results:",style:"bold"});for(let w of $.categories){let j=w.passed?"✓":"✗",B=w.passed?"success":"error",S=LS(w),Q=m?` (${w.durationMs}ms)`:"";n.push({text:` ${j} ${w.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(n.push({text:"",style:"normal"}),n.push({text:"Issues:",style:"bold"}),y){let w=RS($.issues);for(let[j,B]of w){n.push({text:"",style:"normal"}),n.push({text:` ${j||"(no file)"}`,style:"bold",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}else{let w=$.issues.filter((S)=>S.severity==="error"),j=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(w.length>0){n.push({text:"",style:"normal"}),n.push({text:" Errors:",style:"error",indent:1});for(let S of w)n.push(...Vn(S,A,2))}if(j.length>0){n.push({text:"",style:"normal"}),n.push({text:" Warnings:",style:"warning",indent:1});for(let S of j)n.push(...Vn(S,A,2))}if(B.length>0&&A){n.push({text:"",style:"normal"}),n.push({text:" Notes:",style:"muted",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}n.push({text:"",style:"normal"}),n.push({text:"─".repeat(50),style:"muted"});let W=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&A?`${$.totalNotes} note(s)`:null].filter(Boolean);if(W.length>0)n.push({text:`Found: ${W.join(", ")}`,style:$.success?"warning":"error"});if(m)n.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(n.push({text:"",style:"normal"}),$.success)n.push({text:"✅ All CI checks passed!",style:"success"});else n.push({text:"❌ CI checks failed",style:"error"});return n.push({text:"",style:"normal"}),n}function zS($,b={}){return $W($,b).map((A)=>" ".repeat(A.indent??0)+A.text).join(`
|
|
506
|
+
`)}function LS($){let b=[];if($.errors>0)b.push(`${$.errors} error(s)`);if($.warnings>0)b.push(`${$.warnings} warning(s)`);if(b.length===0)return"passed";return b.join(", ")}function Vn($,b,n){let A=[],m=$.severity==="error"?"✗":$.severity==="warning"?"⚠":"○",y=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",W=`${m} ${$.message}`;if($.file){let w=$.line?`:${$.line}`:"";W+=` (${$.file}${w})`}if(A.push({text:W,style:y,indent:n}),b&&$.context){let w=JSON.stringify($.context);if(w!=="{}")A.push({text:`Context: ${w}`,style:"muted",indent:n+1})}return A}function RS($){let b=new Map;for(let n of $){let A=n.file??"";if(!b.has(A))b.set(A,[]);let m=b.get(A);if(m)m.push(n)}return new Map([...b.entries()].sort(([n],[A])=>n.localeCompare(A)))}import{OperationSpecRegistry as CS}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as xS}from"@contractspec/lib.contracts-spec/operations/report";function IS(){let $=new CS;return xS($),$}var f3=IS();class ES{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let n=$.drift?.status==="fail",A=!1;if(n&&b==="fail")A=!0;return{driftDetected:n,shouldFail:A}}}function MS($){if(!$)return"—";let b=new Date($),A=new Date().getTime()-b.getTime(),m=Math.floor(A/86400000);if(m<1)return"today";if(m===1)return"yesterday";return`${m} days ago`}class TS{collectChanges($,b,n){if($){let A=$.endsWith("/")?$:`${$}/`;return n.filter((m)=>m.startsWith(A))}if(b){let A=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return n.filter((m)=>A.test(m))}return n}detectDrift($){let b=$.map((n)=>n.slice(3)).filter((n)=>n&&n.trim().length>0).filter((n)=>n!==".contractspec-ci"&&!n.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},n=b.breaking||0,A=b.nonBreaking||0,m=b.total;if(m===void 0)m=n+A;let y=$?.breaking||!1,W="unknown";if($){if(y||n>0)W="breaking",y=!0;else if(A>0)W="non-breaking";else if(m===0)W="no-impact"}return{status:W,breaking:y,breakingCount:n,nonBreakingCount:A,total:m||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,n=this.deriveImpactStatus($.impactJson),A={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:n.status,breaking:n.breakingCount,nonBreaking:n.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(A.validation?.status==="fail")A.nextSteps?.push("Fix validation errors and rerun the workflow.");if(A.risk?.status==="breaking")A.nextSteps?.push("Review breaking changes and plan a migration.");if(A.risk?.status==="unknown")A.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(A.drift?.status==="fail")A.nextSteps?.push("Run the generate command locally and commit drift fixes.");let m=this.finalizeResults(A,$.failOn);if(m.shouldFail)A.nextSteps?.unshift(`CI failed: ${m.failReasons.join(", ")} (fail_on=${$.failOn}).`);return A}finalizeResults($,b){let n=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,A=$.drift?.status==="fail",m=$.validation?.status==="fail",y=$.risk?.status==="unknown",W=[],w=!1;if(b!=="never"){if(b==="breaking"){if(n)W.push("breaking changes detected");if(y)W.push("impact status unknown")}else if(b==="drift"){if(A)W.push("drift detected");if(y)W.push("impact status unknown")}else if(b==="any"){if(n)W.push("breaking changes detected");if(A)W.push("drift detected");if(m)W.push("validation failed");if(y)W.push("impact status unknown")}else W.push(`invalid fail_on value (${b})`);if(W.length>0)w=!0}return{driftDetected:A,breakingChangeDetected:n,validationFailed:m,shouldFail:w,failReasons:W}}generateReportMarkdown($,b){let n=(j,B=60000)=>{if(j.length<=B)return j;return`${j.slice(0,B)}
|
|
507
507
|
|
|
508
|
-
*(output truncated)*`},A=(
|
|
509
|
-
`)},
|
|
508
|
+
*(output truncated)*`},A=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
509
|
+
`)},m=n($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),y=n($.validation?.outputPath?b($.validation.outputPath):""),W=$.drift?.files??[],w=[];if(w.push("## ContractSpec Report"),w.push(""),$.contracts&&$.contracts.length>0){w.push("### Overall verification status"),w.push(""),w.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),w.push("| --- | --- | --- | --- | --- |");for(let j of $.contracts){let B=j.lastVerifiedSha??"—",S=MS(j.lastVerifiedDate),Q=j.surfaces.join(", ");w.push(`| ${j.name} | ${S} | ${j.driftMismatches} | ${Q} | ${B} |`)}w.push("")}if(w.push("### 1) What changed"),$.whatChanged?.summary)w.push($.whatChanged.summary);else w.push("No contract changes detected.");if(m.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Contract view (product)</summary>"),w.push(""),w.push(m),w.push(""),w.push("</details>");if(w.push(""),w.push("### 2) Risk classification"),$.risk?.status){let j=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);w.push(j.join(" | "))}else w.push("Impact analysis unavailable.");if(w.push(""),w.push("### 3) Validation results"),$.validation?.status){if(w.push(`Status: ${$.validation.status}`),y.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Validation output</summary>"),w.push(""),w.push(y),w.push(""),w.push("</details>")}else w.push("Validation step not run.");if(w.push(""),w.push("### 4) Drift results"),$.drift?.status){if(w.push(`Status: ${$.drift.status}`),W.length>0)w.push(""),w.push("<details>"),w.push("<summary>Drifted files</summary>"),w.push(""),w.push(A(W)),w.push(""),w.push("</details>")}else w.push("Drift check not run.");if(w.push(""),w.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)w.push(A($.nextSteps));else w.push("- No action required.");return`${w.join(`
|
|
510
510
|
`)}
|
|
511
|
-
`}}import{AGENT_SYSTEM_PROMPTS as xQ}from"@contractspec/lib.contracts-spec/llm";class u0{agentType="claude-code";formatPlan($){let W=[];if(W.push(`# Implement: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files to Create/Modify"),W.push("");for(let j of $.fileStructure){let A=j.type==="create"?"\uD83D\uDCDD":"✏️";W.push(`${A} \`${j.path}\``),W.push(` ${j.purpose}`),W.push("")}}W.push("## Implementation Steps"),W.push("");for(let j of $.steps){W.push(`### ${j.order}. ${j.title}`),W.push(""),W.push(j.description),W.push(""),W.push("**Acceptance Criteria:**");for(let A of j.acceptanceCriteria)W.push(`- [ ] ${A}`);W.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("### Policy");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("### Security");for(let j of $.constraints.security)W.push(`- ⚠️ ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("### PII Handling"),W.push("The following fields contain personally identifiable information:");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}}W.push("## Verification Checklist"),W.push(""),W.push("Before submitting, verify:");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),W.push("## Instructions"),W.push(""),W.push("1. Implement each step in order"),W.push("2. Use TypeScript with strict typing (no `any`)"),W.push("3. Include JSDoc comments for public APIs"),W.push("4. Handle all error cases defined in the spec"),W.push("5. Emit events as specified"),W.push("6. Mark checklist items as you complete them"),W.push(""),{agent:"claude-code",systemPrompt:xQ["claude-code"],taskPrompt:W.join(`
|
|
512
|
-
`)}}
|
|
513
|
-
`)}
|
|
514
|
-
`)}
|
|
515
|
-
`)}
|
|
516
|
-
`)}}
|
|
517
|
-
`)}
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
export const ${
|
|
511
|
+
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>$5,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>Un,normalizeText:()=>wW,inferFamilyFromPath:()=>Z0,hasLocalShadcnRegistry:()=>Q0,getContractSpecAdoptionCatalog:()=>Jn,createAdoptionCatalogDocument:()=>w0,candidateTokens:()=>j0});function x($,b,n,A,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:n,packageKind:A,title:j.title??b,description:w,capabilityTags:y,preferredUseCases:W,avoidWhen:j.avoidWhen,platforms:j.platforms,replacementImportHints:j.replacementImportHints,resolutionPriority:m,runtimes:j.runtimes}}var nW=[x("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),x("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),x("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),x("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),x("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var AW=[x("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),x("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),x("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),x("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),x("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),x("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),x("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),x("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var mW=[x("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),x("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),x("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),x("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),x("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),x("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),x("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),x("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),x("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var yW=[x("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),x("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),x("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),x("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),x("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),x("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var WW=[x("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),x("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),x("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var DS=[...WW,...nW,...AW,...mW,...yW];function Jn(){return[...DS].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function w0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:Jn()}}import{DEFAULT_CONTRACTSRC as cS}from"@contractspec/lib.contracts-spec/workspace-config";function wW($){return $.toLowerCase().trim()}function e$($){return wW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function k$($){return[...new Set($.flatMap((b)=>e$(b)))]}function j0($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return k$(b)}function Un($,b){let n=new Set(b);return $.filter((A)=>n.has(A)).length}import{resolve as NS}from"node:path";import{ContractsrcSchema as FS,DEFAULT_CONTRACTSRC as B0}from"@contractspec/lib.contracts-spec/workspace-config";async function s$($,b={}){let n=NS(b.cwd??process.cwd()),A=b.workspaceRoot??I(n),m=b.packageRoot??c(n),y=b.config?BW(B0,b.config):await vS($,A,m);return{adoption:y.connect?.adoption??B0.connect.adoption,config:y,cwd:n,packageRoot:m,workspaceRoot:A}}async function vS($,b,n){let A=B0;if(b!==n)A=await jW($,A,$.join(b,".contractsrc.json"));return jW($,A,$.join(n,".contractsrc.json"))}async function jW($,b,n){if(!await $.exists(n))return b;try{let A=JSON.parse(await $.readFile(n)),m=FS.safeParse(A);if(!m.success)return b;return BW(b,m.data)}catch{return b}}function BW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var gS=["package.json","packages/*/package.json"];async function S0($,b){let[n,A]=await Promise.all([PS($,b),kS($,b)]);return{fileCandidates:A,packageCandidates:n}}async function Q0($,b){let n=$.join(b.workspaceRoot,"components.json");if(await $.exists(n))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function PS($,b){let n=await $.glob({patterns:gS,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),A=[];for(let m of n)try{let y=JSON.parse(await $.readFile($.join(b.workspaceRoot,m))),W=Z0(m);if(!W)continue;let w=y.name??$.dirname(m);A.push({id:`workspace.package.${w}`,source:"workspace",family:W,title:w,description:y.description??`Local reusable package at ${m}.`,packageKind:fS(m),packageRef:w,capabilityTags:k$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return A}async function kS($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((A)=>{let m=Z0(A);if(!m)return[];let y=A.split("/").pop()?.replace(/\.[^.]+$/,"")??A;return[{id:`workspace.file.${A}`,source:"workspace",family:m,title:y,description:`Local reusable source at ${A}.`,filePath:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:rS(m,A)}]})}function Z0($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function rS($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function fS($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Jb($,b){let n=await s$($.fs,b),A=aS(b),m=k$([A,b.symbol??"",...b.paths??[]]),y=await S0($.fs,n),W=await eS($,n),w=await Q0($.fs,n),j=hS(n,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...sS(b.family,b.platform,w)]),B=j[0]??null,S=j.length>1&&B!=null&&B.candidate.source===j[1].candidate.source&&Math.abs(B.score-j[1].score)<=40,Q=tS(n,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:A,reason:pS(B,S),selected:B,verdict:Q}}function hS($,b,n,A){return A.filter((m)=>m.family===n.family&&oS($,m.family)).filter((m)=>iS(m,n.platform)).map((m)=>dS(m,b,n.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function dS($,b,n){let A=j0($),m=k$(n??[]),y=[],W=Un(b,A)*25,w=Un(m,A)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:uS($.source)+($.resolutionPriority??0)+W+w}}function uS($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function oS($,b){return $.adoption.families?.[b]??!0}function iS($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function tS($,b,n,A){let m=$.adoption.thresholds??cS.connect.adoption.thresholds;if(n)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return lS(b.candidate,A)?"permit":m.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return m.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return m.newImplementation??"require_review";return m.newExternalDependency??"require_review"}function lS($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function pS($,b){if(b)return"Multiple similarly strong adoption candidates were found.";if(!$)return"No reusable workspace or ContractSpec candidate matched the request.";return`Selected ${$.candidate.source} candidate ${$.candidate.title}.`}function aS($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function eS($,b){let n=Jn(),A=b.adoption.catalog?.overrideManifestPath;if(!A||!await $.fs.exists($.fs.join(b.workspaceRoot,A)))return n;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,A)),y=JSON.parse(m);return[...n,...Array.isArray(y)?y:y.entries??[]]}catch{return n}}function sS($,b,n){if($==="ui"&&b==="web"&&n)return[$b("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[$b("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[$b("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[$b("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[$b("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[$b("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function $b($,b,n,A,m){return{id:$,source:"ecosystem",packageRef:n,family:b,packageKind:"primitive",title:A,description:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:m}}async function $5($,b={}){let n=await s$($.fs,b),A=w0(),m=$.fs.join(n.workspaceRoot,n.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(m,`${JSON.stringify(A,null,2)}
|
|
512
|
+
`),{catalog:A,catalogPath:m}}import{AGENT_SYSTEM_PROMPTS as b5}from"@contractspec/lib.contracts-spec/llm";class Kn{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let n of $.fileStructure){let A=n.type==="create"?"\uD83D\uDCDD":"✏️";b.push(`${A} \`${n.path}\``),b.push(` ${n.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let n of $.steps){b.push(`### ${n.order}. ${n.title}`),b.push(""),b.push(n.description),b.push(""),b.push("**Acceptance Criteria:**");for(let A of n.acceptanceCriteria)b.push(`- [ ] ${A}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let n of $.constraints.security)b.push(`- ⚠️ ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:b5["claude-code"],taskPrompt:b.join(`
|
|
513
|
+
`)}}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 n=[],A=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let m of A){let y=$.matchAll(m);for(let W of y)if(W[1])n.push(W[1])}if(n.length>0)return{errors:n};return{code:$}}}var _n=new Kn;import{AGENT_SYSTEM_PROMPTS as n5}from"@contractspec/lib.contracts-spec/llm";class zn{agentType="cursor-cli";formatPlan($){let b=[];if(b.push(`# ${$.target.key}.v${$.target.version}`),b.push(""),b.push(`> ${$.context.goal}`),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push("");for(let A of $.fileStructure)b.push(`- ${A.type}: \`${A.path}\` - ${A.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let A of $.steps)b.push(`${A.order}. **${A.title}**: ${A.description}`);b.push("");let n=[...$.constraints.policy,...$.constraints.security.map((A)=>`⚠️ ${A}`)];if(n.length>0){b.push("## Constraints"),b.push("");for(let A of n)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((A)=>`\`${A}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:n5["cursor-cli"],taskPrompt:b.join(`
|
|
515
|
+
`)}}generateConfig($){let b=$.meta,n=[];if(n.push("---"),n.push(`description: Implementation rules for ${b.key}.v${b.version}`),n.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),n.push("alwaysApply: false"),n.push("---"),n.push(""),n.push(`# ${b.key} Implementation Rules`),n.push(""),n.push(`This ${b.kind} operation must follow the ContractSpec specification.`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Requirements"),n.push(""),n.push("1. Input/output types MUST match the spec schema exactly"),n.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)n.push("3. Events MUST be emitted as specified");if(n.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)n.push(`5. Idempotency: ${$.policy.idempotent}`);if(n.push(""),$.io.errors&&Object.keys($.io.errors).length>0){n.push("## Error Cases"),n.push("");for(let[A,m]of Object.entries($.io.errors))n.push(`- \`${A}\` (HTTP ${m.http??400}): ${m.when}`);n.push("")}if($.sideEffects?.emits?.length){n.push("## Events to Emit"),n.push("");for(let A of $.sideEffects.emits)if("ref"in A)n.push(`- \`${A.ref.key}.v${A.ref.version}\`: ${A.when}`);else n.push(`- \`${A.key}.v${A.version}\`: ${A.when}`);n.push("")}if($.policy.pii?.length){n.push("## PII Handling"),n.push(""),n.push("These fields contain PII and must be handled with care:");for(let A of $.policy.pii)n.push(`- \`${A}\``);n.push("")}if($.acceptance?.scenarios?.length){n.push("## Acceptance Scenarios"),n.push("");for(let A of $.acceptance.scenarios)n.push(`### ${A.key}`),n.push(`- Given: ${A.given.join("; ")}`),n.push(`- When: ${A.when.join("; ")}`),n.push(`- Then: ${A.then.join("; ")}`),n.push("")}return n.join(`
|
|
516
|
+
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var Ln=new zn;import{AGENT_SYSTEM_PROMPTS as A5}from"@contractspec/lib.contracts-spec/llm";class Rn{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let n of $.fileStructure)b.push(`| \`${n.path}\` | ${n.type} | ${n.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let n of $.steps)if(b.push(`### Step ${n.order}: ${n.title}`),b.push(""),b.push(n.description),b.push(""),n.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let A of n.acceptanceCriteria)b.push(`- ${A}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let n of $.constraints.security)b.push(`- ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),{agent:"generic-mcp",systemPrompt:A5["generic-mcp"],taskPrompt:b.join(`
|
|
517
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,n=[];return n.push(`# ${b.key} v${b.version}`),n.push(""),n.push(`**Type:** ${b.kind}`),n.push(`**Stability:** ${b.stability}`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Description"),n.push(""),n.push(b.description),n.push(""),n.join(`
|
|
518
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let n=JSON.parse($);if(typeof n.code==="string")return{code:n.code};if(typeof n.errors==="object")return{errors:Array.isArray(n.errors)?n.errors:[String(n.errors)]}}catch{}return{code:$}}}var Cn=new Rn;var Y0={"claude-code":_n,"cursor-cli":Ln,"generic-mcp":Cn};function Ub($){let b=Y0[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function G0(){return Object.keys(Y0)}import{featureToMarkdown as H0,generateImplementationPlan as SW,operationSpecToAgentPrompt as m5,operationSpecToFullMarkdown as y5}from"@contractspec/lib.contracts-spec/llm";var W5={defaultAgent:"generic-mcp",verbose:!1};class xn{config;constructor($={}){this.config={...W5,...$}}generateGuide($,b={}){let n=b.agent??this.config.defaultAgent,A=Ub(n),m=SW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),y=A.formatPlan(m),W=y5($);return{plan:m,prompt:y,markdown:W}}generateFeatureGuide($,b,n={}){let A=n.agent??this.config.defaultAgent,m=Ub(A),y=$.operations?.[0],W=y?b.specs?.get(y.key,y.version):void 0,w;if(W)w=SW(W,{projectRoot:this.config.projectRoot}),w.target={type:"feature",key:$.meta.key,version:"1.0.0"},w.context.goal=$.meta.description??w.context.goal;else w={target:{type:"feature",key:$.meta.key,version:"1.0.0"},context:{goal:$.meta.description??`Implement feature ${$.meta.key}`,description:$.meta.title??$.meta.key,background:""},specMarkdown:H0($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(w.specMarkdown=H0($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)w.steps=$.operations.map((S,Q)=>({order:Q+1,title:`Implement ${S.key}`,description:`Implement operation ${S.key}.v${S.version}`,acceptanceCriteria:[`Operation ${S.key} works as specified`]}));let j=m.formatPlan(w),B=H0($,b);return{plan:w,prompt:j,markdown:B}}generateAgentConfig($,b){return Ub(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,n="implement",A){return m5($,{taskType:n,existingCode:A})}listAgentTypes(){return G0()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function w5($){return new xn($)}var j5=new xn;import{detectAuthoringTarget as $8,generateComponentTemplate as b8,generateHandlerTemplate as n8,generateTestTemplate as A8,getAuthoringTargetDefinition as m8,inferSpecTypeFromFilePath as y8,scanSpecSource as W8}from"@contractspec/module.workspace";var dW={};f(dW,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});function QW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
519
|
+
|
|
520
|
+
export const ${nb($.key)}Capability = defineCapability({
|
|
521
521
|
meta: {
|
|
522
|
-
key: '${
|
|
523
|
-
version: ${$.version},
|
|
522
|
+
key: '${$.key}',
|
|
523
|
+
version: '${$.version}',
|
|
524
|
+
kind: '${$.kind??"api"}',
|
|
525
|
+
title: '${k(bb($))}',
|
|
526
|
+
description: '${k($.description)}',
|
|
527
|
+
domain: '${k(r$($))}',
|
|
528
|
+
owners: [${W$($.owners)}],
|
|
529
|
+
tags: [${W$($.tags)}],
|
|
530
|
+
stability: '${$.stability}',
|
|
531
|
+
},
|
|
532
|
+
provides: [],
|
|
533
|
+
requires: [],
|
|
534
|
+
});
|
|
535
|
+
`}function ZW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
536
|
+
|
|
537
|
+
export const ${nb($.key)}Policy = definePolicy({
|
|
538
|
+
meta: {
|
|
539
|
+
key: '${$.key}',
|
|
540
|
+
version: '${$.version}',
|
|
541
|
+
title: '${k(bb($))}',
|
|
542
|
+
description: '${k($.description)}',
|
|
543
|
+
domain: '${k(r$($))}',
|
|
544
|
+
owners: [${W$($.owners)}],
|
|
545
|
+
tags: [${W$($.tags)}],
|
|
546
|
+
stability: '${$.stability}',
|
|
547
|
+
scope: '${$.scope??"feature"}',
|
|
548
|
+
},
|
|
549
|
+
rules: [
|
|
550
|
+
{
|
|
551
|
+
effect: 'allow',
|
|
552
|
+
actions: ['read'],
|
|
553
|
+
resource: { type: '${k(r$($))}' },
|
|
554
|
+
reason: 'TODO: replace with real access rules',
|
|
555
|
+
},
|
|
556
|
+
],
|
|
557
|
+
});
|
|
558
|
+
`}function XW($){let b=$.targetVersion??"1.0.0",n=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
559
|
+
|
|
560
|
+
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
561
|
+
meta: {
|
|
562
|
+
key: '${$.key}',
|
|
563
|
+
version: '${$.version}',
|
|
564
|
+
title: '${k(bb($))}',
|
|
565
|
+
description: '${k($.description)}',
|
|
566
|
+
domain: '${k(r$($))}',
|
|
567
|
+
owners: [${W$($.owners)}],
|
|
568
|
+
tags: [${W$($.tags)}],
|
|
569
|
+
stability: '${$.stability}',
|
|
570
|
+
},
|
|
571
|
+
target: {
|
|
572
|
+
type: '${$.targetType}',
|
|
573
|
+
${$.targetType}: ${n},
|
|
574
|
+
},
|
|
575
|
+
scenarios: [
|
|
576
|
+
{
|
|
577
|
+
key: 'success',
|
|
578
|
+
when: { ${$.targetType}: { key: '${$.targetKey}' } },
|
|
579
|
+
then: [{ type: 'expectOutput', match: {} }],
|
|
580
|
+
},
|
|
581
|
+
],
|
|
582
|
+
});
|
|
583
|
+
`}function YW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
584
|
+
|
|
585
|
+
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
586
|
+
meta: {
|
|
587
|
+
key: '${$.key}',
|
|
588
|
+
version: '${$.version}',
|
|
589
|
+
domain: '${k(r$($))}',
|
|
590
|
+
description: '${k($.description)}',
|
|
591
|
+
owners: [${W$($.owners)}],
|
|
592
|
+
tags: [${W$($.tags)}],
|
|
593
|
+
stability: '${$.stability}',
|
|
594
|
+
},
|
|
595
|
+
locale: '${$.locale}',
|
|
596
|
+
fallback: '${$.fallback??$.locale}',
|
|
597
|
+
messages: {
|
|
598
|
+
'${$.key}.title': {
|
|
599
|
+
value: '${k(bb($))}',
|
|
600
|
+
description: 'TODO: replace with a real localized message',
|
|
601
|
+
},
|
|
602
|
+
},
|
|
603
|
+
});
|
|
604
|
+
`}function GW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
|
|
605
|
+
|
|
606
|
+
export const ${nb($.key)}Job = defineJob({
|
|
607
|
+
meta: {
|
|
608
|
+
key: '${$.key}',
|
|
609
|
+
version: '${$.version}',
|
|
610
|
+
title: '${k(bb($))}',
|
|
611
|
+
description: '${k($.description)}',
|
|
612
|
+
domain: '${k(r$($))}',
|
|
613
|
+
owners: [${W$($.owners)}],
|
|
614
|
+
tags: [${W$($.tags)}],
|
|
615
|
+
stability: '${$.stability}',
|
|
616
|
+
},
|
|
617
|
+
payload: { schema: {} },
|
|
618
|
+
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
619
|
+
});
|
|
620
|
+
`}function HW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
621
|
+
|
|
622
|
+
export const ${nb($.key)}Visualization = defineVisualization({
|
|
623
|
+
meta: {
|
|
624
|
+
key: '${$.key}',
|
|
625
|
+
version: '${$.version}',
|
|
626
|
+
title: '${k(bb($))}',
|
|
627
|
+
description: '${k($.description)}',
|
|
628
|
+
goal: 'TODO: describe the decision this visualization supports',
|
|
629
|
+
context: 'TODO: describe where this visualization appears',
|
|
630
|
+
domain: '${k(r$($))}',
|
|
631
|
+
owners: [${W$($.owners)}],
|
|
632
|
+
tags: [${W$($.tags)}],
|
|
633
|
+
stability: '${$.stability}',
|
|
634
|
+
},
|
|
635
|
+
source: {
|
|
636
|
+
primary: {
|
|
637
|
+
key: '${$.sourceOperationKey}',
|
|
638
|
+
version: '${$.sourceOperationVersion??"1.0.0"}',
|
|
639
|
+
},
|
|
640
|
+
resultPath: 'data',
|
|
641
|
+
},
|
|
642
|
+
visualization: {
|
|
643
|
+
kind: 'metric',
|
|
644
|
+
measures: [{ key: 'value', label: 'Value', dataPath: 'value', format: 'number' }],
|
|
645
|
+
measure: 'value',
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
`}function bb($){return $.title??B5($.key.split(".").at(-1)??$.key)}function r$($){return $.domain??$.key.split(".")[0]??"contractspec"}function W$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function nb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function B5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function In($){let b=$.packageName??`@contractspec/example.${Q5($.key.split(".").at(-1)??$.key)}`,n=`${Kb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
649
|
+
|
|
650
|
+
const ${n} = defineExample({
|
|
651
|
+
meta: {
|
|
652
|
+
key: '${$.key}',
|
|
653
|
+
version: '${$.version}',
|
|
654
|
+
title: '${t(En($))}',
|
|
655
|
+
description: '${t($.description)}',
|
|
656
|
+
kind: 'template',
|
|
657
|
+
visibility: 'experimental',
|
|
658
|
+
stability: '${$.stability}',
|
|
659
|
+
owners: [${S$($.owners)}],
|
|
660
|
+
tags: [${S$($.tags)}],
|
|
661
|
+
},
|
|
662
|
+
surfaces: {
|
|
663
|
+
templates: true,
|
|
664
|
+
sandbox: { enabled: true, modes: ['playground', 'specs'] },
|
|
665
|
+
studio: { enabled: false, installable: false },
|
|
666
|
+
mcp: { enabled: false },
|
|
667
|
+
},
|
|
668
|
+
entrypoints: {
|
|
669
|
+
packageName: '${b}',
|
|
670
|
+
},
|
|
671
|
+
});
|
|
672
|
+
|
|
673
|
+
export default ${n};
|
|
674
|
+
export { ${n} };
|
|
675
|
+
`}function qW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
676
|
+
|
|
677
|
+
export const ${Kb($.key)}Agent = defineAgent({
|
|
678
|
+
meta: {
|
|
679
|
+
key: '${$.key}',
|
|
680
|
+
version: '${$.version}',
|
|
681
|
+
description: '${t($.description)}',
|
|
682
|
+
owners: [${S$($.owners)}],
|
|
683
|
+
tags: [${S$($.tags)}],
|
|
684
|
+
stability: '${$.stability}',
|
|
685
|
+
},
|
|
686
|
+
instructions: '${t($.instructions)}',
|
|
687
|
+
tools: [{ name: 'todo' }],
|
|
688
|
+
});
|
|
689
|
+
`}function OW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
690
|
+
|
|
691
|
+
export const ${Kb($.key)}ProductIntent = defineProductIntentSpec({
|
|
692
|
+
id: '${$.id??`${$.key}-run`}',
|
|
693
|
+
meta: {
|
|
694
|
+
key: '${$.key}',
|
|
695
|
+
version: '${$.version}',
|
|
696
|
+
title: '${t(En($))}',
|
|
697
|
+
description: '${t($.description)}',
|
|
698
|
+
goal: 'TODO: capture the desired product outcome',
|
|
699
|
+
context: 'TODO: capture the decision context',
|
|
700
|
+
stability: '${$.stability}',
|
|
701
|
+
owners: [${S$($.owners)}],
|
|
702
|
+
tags: [${S$($.tags)}],
|
|
703
|
+
},
|
|
704
|
+
question: '${t($.question)}',
|
|
705
|
+
insights: { insights: [] },
|
|
706
|
+
});
|
|
707
|
+
`}function VW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
708
|
+
|
|
709
|
+
export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
710
|
+
meta: {
|
|
711
|
+
key: '${$.key}',
|
|
712
|
+
version: '${$.version}',
|
|
713
|
+
title: '${t(En($))}',
|
|
714
|
+
description: '${t($.description)}',
|
|
715
|
+
domain: '${t(UW($))}',
|
|
716
|
+
owners: [${S$($.owners)}],
|
|
717
|
+
tags: [${S$($.tags)}],
|
|
718
|
+
stability: '${$.stability}',
|
|
719
|
+
},
|
|
720
|
+
target: {
|
|
721
|
+
isolation: 'preview',
|
|
722
|
+
preferredTargets: ['preview'],
|
|
723
|
+
},
|
|
724
|
+
allowedModes: ['deterministic-browser'],
|
|
725
|
+
steps: [
|
|
726
|
+
{
|
|
727
|
+
key: 'open-home',
|
|
728
|
+
description: 'Open the target application',
|
|
729
|
+
actionClass: 'navigate',
|
|
730
|
+
intent: 'Navigate to the primary page under test.',
|
|
731
|
+
},
|
|
732
|
+
],
|
|
733
|
+
assertions: [
|
|
734
|
+
{
|
|
735
|
+
key: 'step-completes',
|
|
736
|
+
type: 'step-status',
|
|
737
|
+
description: 'TODO: replace with a real scenario assertion',
|
|
738
|
+
match: 'completed',
|
|
739
|
+
},
|
|
740
|
+
],
|
|
741
|
+
});
|
|
742
|
+
`}function JW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
743
|
+
|
|
744
|
+
export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
745
|
+
meta: {
|
|
746
|
+
key: '${$.key}',
|
|
747
|
+
version: '${$.version}',
|
|
748
|
+
title: '${t(En($))}',
|
|
749
|
+
description: '${t($.description)}',
|
|
750
|
+
domain: '${t(UW($))}',
|
|
751
|
+
owners: [${S$($.owners)}],
|
|
752
|
+
tags: [${S$($.tags)}],
|
|
753
|
+
stability: '${$.stability}',
|
|
754
|
+
},
|
|
755
|
+
scenarios: [
|
|
756
|
+
{
|
|
757
|
+
scenario: {
|
|
758
|
+
key: '${$.scenarioKey}',
|
|
759
|
+
version: '${$.scenarioVersion??"1.0.0"}',
|
|
760
|
+
},
|
|
761
|
+
required: true,
|
|
762
|
+
weight: 1,
|
|
763
|
+
},
|
|
764
|
+
],
|
|
765
|
+
summary: '${t($.description)}',
|
|
766
|
+
tags: [${S$($.tags)}],
|
|
767
|
+
});
|
|
768
|
+
`}function En($){return $.title??S5($.key.split(".").at(-1)??$.key)}function UW($){return $.domain??$.key.split(".")[0]??"contractspec"}function S$($){return $.map((b)=>`'${t(b)}'`).join(", ")}function Kb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function S5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Q5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function LW($){let b=J5($.key.split(".").pop()??"App")+"AppConfig",n=Z5($),A=X5($),m=KW("dataViews",$.dataViews),y=KW("workflows",$.workflows),W=Y5($),w=G5($),j=H5($),B=q5($),S=O5($),Q=V5($),Z=$.notes?` notes: '${T($.notes)}',
|
|
769
|
+
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
770
|
+
|
|
771
|
+
export const ${b} = defineAppConfig({
|
|
772
|
+
meta: {
|
|
773
|
+
key: '${T($.key)}',
|
|
774
|
+
version: '${$.version}',
|
|
524
775
|
title: '${T($.title)}',
|
|
525
776
|
description: '${T($.description)}',
|
|
526
777
|
domain: '${T($.domain)}',
|
|
527
|
-
owners: [${$.owners.map((
|
|
528
|
-
tags: [${$.tags.map((
|
|
778
|
+
owners: [${$.owners.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
779
|
+
tags: [${$.tags.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
529
780
|
stability: '${$.stability}',
|
|
530
781
|
appId: '${T($.appId)}',
|
|
531
782
|
},
|
|
532
|
-
${
|
|
533
|
-
`}function
|
|
534
|
-
`:"",
|
|
783
|
+
${n}${A}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
784
|
+
`}function Z5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((A)=>_W(A)).join(", ")}],
|
|
785
|
+
`:"",n=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((A)=>_W(A)).join(", ")}],
|
|
535
786
|
`:"";return` capabilities: {
|
|
536
|
-
${
|
|
537
|
-
`}function
|
|
538
|
-
`:"",
|
|
787
|
+
${b}${n} },
|
|
788
|
+
`}function X5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
789
|
+
`:"",n=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
539
790
|
`:"";return` features: {
|
|
540
|
-
${
|
|
541
|
-
`}function
|
|
542
|
-
|
|
543
|
-
|
|
791
|
+
${b}${n} },
|
|
792
|
+
`}function KW($,b){if(b.length===0)return"";let n=b.map((A)=>` ${A.slot}: {
|
|
793
|
+
key: '${T(A.key)}'${A.version?`,
|
|
794
|
+
version: '${A.version}'`:""}
|
|
544
795
|
}`).join(`,
|
|
545
796
|
`);return` ${$}: {
|
|
546
|
-
${
|
|
797
|
+
${n}
|
|
547
798
|
},
|
|
548
|
-
`}function
|
|
549
|
-
${$.policyRefs.map((
|
|
550
|
-
|
|
551
|
-
version: '${
|
|
799
|
+
`}function Y5($){if($.policyRefs.length===0)return"";return` policies: [
|
|
800
|
+
${$.policyRefs.map((n)=>` {
|
|
801
|
+
key: '${T(n.key)}'${n.version?`,
|
|
802
|
+
version: '${n.version}'`:""}
|
|
552
803
|
}`).join(`,
|
|
553
804
|
`)}
|
|
554
805
|
],
|
|
555
|
-
`}function
|
|
556
|
-
`,
|
|
806
|
+
`}function G5($){if(!$.theme)return"";let b=` primary: { key: '${T($.theme.key)}', version: '${$.theme.version}' },
|
|
807
|
+
`,n=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((A)=>`{ key: '${T(A.key)}', version: '${A.version}' }`).join(", ")}],
|
|
557
808
|
`:"";return` theme: {
|
|
558
|
-
${
|
|
559
|
-
`}function
|
|
809
|
+
${b}${n} },
|
|
810
|
+
`}function H5($){if(!$.telemetry)return"";return` telemetry: {
|
|
560
811
|
spec: {
|
|
561
|
-
|
|
812
|
+
key: '${T($.telemetry.key)}'${$.telemetry.version?`,
|
|
562
813
|
version: '${$.telemetry.version}'`:""}
|
|
563
814
|
},
|
|
564
815
|
},
|
|
565
|
-
`}function
|
|
566
|
-
`:"",
|
|
816
|
+
`}function q5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((A)=>zW(A)).join(", ")}],
|
|
817
|
+
`:"",n=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((A)=>zW(A)).join(", ")}],
|
|
567
818
|
`:"";return` experiments: {
|
|
568
|
-
${
|
|
569
|
-
`}function
|
|
570
|
-
${$.featureFlags.map((
|
|
571
|
-
key: '${T(
|
|
572
|
-
enabled: ${
|
|
573
|
-
${
|
|
574
|
-
${
|
|
819
|
+
${b}${n} },
|
|
820
|
+
`}function O5($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
821
|
+
${$.featureFlags.map((n)=>` {
|
|
822
|
+
key: '${T(n.key)}',
|
|
823
|
+
enabled: ${n.enabled},
|
|
824
|
+
${n.variant?`variant: '${T(n.variant)}',`:""}
|
|
825
|
+
${n.description?`description: '${T(n.description)}',`:""}
|
|
575
826
|
}`).join(`,
|
|
576
827
|
`)}
|
|
577
828
|
],
|
|
578
|
-
`}function
|
|
579
|
-
${$.routes.map((
|
|
829
|
+
`}function V5($){if($.routes.length===0)return"";return` routes: [
|
|
830
|
+
${$.routes.map((n)=>{return` { ${[`path: '${T(n.path)}'`,n.label?`label: '${T(n.label)}'`:null,n.dataView?`dataView: '${T(n.dataView)}'`:null,n.workflow?`workflow: '${T(n.workflow)}'`:null,n.guardKey?`guard: { key: '${T(n.guardKey)}'${n.guardVersion?`, version: '${n.guardVersion}'`:""} }`:null,n.featureFlag?`featureFlag: '${T(n.featureFlag)}'`:null,n.experimentKey?`experiment: { key: '${T(n.experimentKey)}'${n.experimentVersion?`, version: '${n.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
580
831
|
`)}
|
|
581
832
|
],
|
|
582
|
-
`}function
|
|
583
|
-
key: '${
|
|
584
|
-
label: '${
|
|
585
|
-
dataPath: '${
|
|
586
|
-
${
|
|
587
|
-
${
|
|
588
|
-
${
|
|
833
|
+
`}function _W($){return`{ key: '${T($)}' }`}function zW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${T($.key)}'${b} }`}function J5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=U5($.name.split(".").pop()??"DataView")+"DataView",n=$.fields.map((y)=>` {
|
|
834
|
+
key: '${y.key}',
|
|
835
|
+
label: '${Mn(y.label)}',
|
|
836
|
+
dataPath: '${y.dataPath}',
|
|
837
|
+
${y.format?`format: '${y.format}',`:""}
|
|
838
|
+
${y.sortable?"sortable: true,":""}
|
|
839
|
+
${y.filterable?"filterable: true,":""}
|
|
589
840
|
}`).join(`,
|
|
590
|
-
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((
|
|
841
|
+
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((y)=>`'${y}'`).join(", ")}],`:"",m=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
591
842
|
|
|
592
|
-
export const ${
|
|
843
|
+
export const ${b}: DataViewSpec = {
|
|
593
844
|
meta: {
|
|
594
845
|
key: '${$.name}',
|
|
595
846
|
version: ${$.version},
|
|
596
847
|
entity: '${$.entity}',
|
|
597
|
-
title: '${
|
|
598
|
-
description: '${
|
|
599
|
-
domain: '${
|
|
600
|
-
owners: [${$.owners.map((
|
|
601
|
-
tags: [${$.tags.map((
|
|
848
|
+
title: '${Mn($.title)}',
|
|
849
|
+
description: '${Mn($.description||"Describe the purpose of this data view.")}',
|
|
850
|
+
domain: '${Mn($.domain||$.entity)}',
|
|
851
|
+
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
852
|
+
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
602
853
|
stability: '${$.stability}',
|
|
603
854
|
},
|
|
604
855
|
source: {
|
|
@@ -606,7 +857,7 @@ export const ${W}: DataViewSpec = {
|
|
|
606
857
|
name: '${$.primaryOperation.name}',
|
|
607
858
|
version: ${$.primaryOperation.version},
|
|
608
859
|
},
|
|
609
|
-
${
|
|
860
|
+
${m}
|
|
610
861
|
refreshEvents: [
|
|
611
862
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
612
863
|
],
|
|
@@ -614,7 +865,7 @@ export const ${W}: DataViewSpec = {
|
|
|
614
865
|
view: {
|
|
615
866
|
kind: '${$.kind}',
|
|
616
867
|
fields: [
|
|
617
|
-
${
|
|
868
|
+
${n}
|
|
618
869
|
],
|
|
619
870
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
620
871
|
${A}
|
|
@@ -632,13 +883,13 @@ ${j}
|
|
|
632
883
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
633
884
|
},
|
|
634
885
|
};
|
|
635
|
-
`}function
|
|
886
|
+
`}function U5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Mn($){return $.replace(/'/g,"\\'")}function Tn({exportName:$,specImportPath:b,rendererName:n,viewKind:A}){return`'use client';
|
|
636
887
|
|
|
637
888
|
import * as React from 'react';
|
|
638
889
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
639
|
-
import { ${$} } from '${
|
|
890
|
+
import { ${$} } from '${b}';
|
|
640
891
|
|
|
641
|
-
export interface ${
|
|
892
|
+
export interface ${n}Props {
|
|
642
893
|
items?: Record<string, unknown>[];
|
|
643
894
|
item?: Record<string, unknown> | null;
|
|
644
895
|
className?: string;
|
|
@@ -651,14 +902,14 @@ export interface ${j}Props {
|
|
|
651
902
|
* Auto-generated renderer for the "${A}" data view.
|
|
652
903
|
* Customize as needed for app-specific behaviour.
|
|
653
904
|
*/
|
|
654
|
-
export function ${
|
|
905
|
+
export function ${n}({
|
|
655
906
|
items = [],
|
|
656
907
|
item = null,
|
|
657
908
|
className,
|
|
658
909
|
renderActions,
|
|
659
910
|
onSelect,
|
|
660
911
|
onRowClick,
|
|
661
|
-
}: ${
|
|
912
|
+
}: ${n}Props) {
|
|
662
913
|
return (
|
|
663
914
|
<DataViewRenderer
|
|
664
915
|
spec={${$}}
|
|
@@ -671,93 +922,93 @@ export function ${j}({
|
|
|
671
922
|
/>
|
|
672
923
|
);
|
|
673
924
|
}
|
|
674
|
-
`}function
|
|
925
|
+
`}function CW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,piiFields:w}=$,j=K5(b.replace(/\./g,"_"))+"V"+n,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
675
926
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
676
927
|
|
|
677
928
|
// TODO: Define event payload schema
|
|
678
|
-
export const ${
|
|
679
|
-
name: '${
|
|
680
|
-
description: 'Payload for ${
|
|
929
|
+
export const ${B} = new SchemaModel({
|
|
930
|
+
name: '${B}',
|
|
931
|
+
description: 'Payload for ${b}',
|
|
681
932
|
fields: {
|
|
682
933
|
// Add your payload fields here
|
|
683
934
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
684
935
|
},
|
|
685
936
|
});
|
|
686
937
|
|
|
687
|
-
export const ${
|
|
688
|
-
name: '${
|
|
689
|
-
name: '${
|
|
690
|
-
version: '${
|
|
938
|
+
export const ${j} = defineEvent({
|
|
939
|
+
name: '${b}',
|
|
940
|
+
name: '${b}',
|
|
941
|
+
version: '${n}',
|
|
691
942
|
description: '${A}',
|
|
692
943
|
description: '${A}',
|
|
693
|
-
stability: '${
|
|
694
|
-
owners: [${
|
|
695
|
-
tags: [${
|
|
696
|
-
${
|
|
697
|
-
payload: ${
|
|
944
|
+
stability: '${m}',
|
|
945
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
946
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
947
|
+
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
948
|
+
payload: ${B},
|
|
698
949
|
});
|
|
699
|
-
`}function
|
|
700
|
-
${
|
|
701
|
-
type: '${
|
|
702
|
-
target: '${
|
|
703
|
-
${typeof
|
|
950
|
+
`}function K5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function xW($){let b=z5($.name.split(".").pop()??"Experiment")+"Experiment",n=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
951
|
+
${y.overrides.map((w)=>` {
|
|
952
|
+
type: '${w.type}',
|
|
953
|
+
target: '${h(w.target)}',
|
|
954
|
+
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
704
955
|
}`).join(`,
|
|
705
956
|
`)}
|
|
706
957
|
],`:"";return` {
|
|
707
|
-
id: '${
|
|
708
|
-
name: '${
|
|
709
|
-
${
|
|
710
|
-
${typeof
|
|
711
|
-
${
|
|
958
|
+
id: '${h(y.id)}',
|
|
959
|
+
name: '${h(y.name)}',
|
|
960
|
+
${y.description?`description: '${h(y.description)}',`:""}
|
|
961
|
+
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
962
|
+
${W}
|
|
712
963
|
}`}).join(`,
|
|
713
|
-
`),A=
|
|
714
|
-
${$.successMetrics.map((
|
|
715
|
-
name: '${
|
|
716
|
-
telemetryEvent: { name: '${
|
|
717
|
-
aggregation: '${
|
|
718
|
-
${typeof
|
|
964
|
+
`),A=_5($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
965
|
+
${$.successMetrics.map((y)=>` {
|
|
966
|
+
name: '${h(y.name)}',
|
|
967
|
+
telemetryEvent: { name: '${h(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
968
|
+
aggregation: '${y.aggregation}',
|
|
969
|
+
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
719
970
|
}`).join(`,
|
|
720
971
|
`)}
|
|
721
972
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
722
973
|
|
|
723
|
-
export const ${
|
|
974
|
+
export const ${b}: ExperimentSpec = {
|
|
724
975
|
meta: {
|
|
725
|
-
key: '${
|
|
976
|
+
key: '${h($.name)}',
|
|
726
977
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
727
|
-
title: '${
|
|
728
|
-
description: '${
|
|
729
|
-
domain: '${
|
|
730
|
-
owners: [${$.owners.map((
|
|
731
|
-
tags: [${$.tags.map((
|
|
978
|
+
title: '${h($.name)} experiment',
|
|
979
|
+
description: '${h($.description||"Describe the experiment goal.")}',
|
|
980
|
+
domain: '${h($.domain)}',
|
|
981
|
+
owners: [${$.owners.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
982
|
+
tags: [${$.tags.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
732
983
|
stability: '${$.stability}',
|
|
733
984
|
},
|
|
734
|
-
controlVariant: '${
|
|
985
|
+
controlVariant: '${h($.controlVariant)}',
|
|
735
986
|
variants: [
|
|
736
|
-
${
|
|
987
|
+
${n}
|
|
737
988
|
],
|
|
738
989
|
allocation: ${A},
|
|
739
|
-
${
|
|
990
|
+
${m}
|
|
740
991
|
};
|
|
741
|
-
`}function
|
|
992
|
+
`}function _5($){switch($.type){case"random":return`{
|
|
742
993
|
type: 'random',
|
|
743
|
-
${$.salt?`salt: '${
|
|
994
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
744
995
|
}`;case"sticky":return`{
|
|
745
996
|
type: 'sticky',
|
|
746
997
|
attribute: '${$.attribute}',
|
|
747
|
-
${$.salt?`salt: '${
|
|
998
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
748
999
|
}`;case"targeted":return`{
|
|
749
1000
|
type: 'targeted',
|
|
750
1001
|
rules: [
|
|
751
|
-
${$.rules.map((
|
|
752
|
-
variantId: '${
|
|
753
|
-
${typeof
|
|
754
|
-
${
|
|
755
|
-
${
|
|
1002
|
+
${$.rules.map((b)=>` {
|
|
1003
|
+
variantId: '${h(b.variantId)}',
|
|
1004
|
+
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1005
|
+
${b.policy?`policy: { name: '${h(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1006
|
+
${b.expression?`expression: '${h(b.expression)}',`:""}
|
|
756
1007
|
}`).join(`,
|
|
757
1008
|
`)}
|
|
758
1009
|
],
|
|
759
1010
|
fallback: '${$.fallback??"control"}',
|
|
760
|
-
}`;default:return
|
|
1011
|
+
}`;default:return L5($)}}function z5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function L5($){throw Error(`Unsupported allocation type ${$}`)}function R5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function IW($){let b=(n)=>n.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
761
1012
|
`);return`/**
|
|
762
1013
|
* ${$.title} Feature
|
|
763
1014
|
*
|
|
@@ -766,35 +1017,35 @@ ${$.rules.map((W)=>` {
|
|
|
766
1017
|
|
|
767
1018
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
768
1019
|
|
|
769
|
-
export const ${
|
|
1020
|
+
export const ${R5($.key)}Feature = defineFeature({
|
|
770
1021
|
meta: {
|
|
771
1022
|
key: '${$.key}',
|
|
772
1023
|
version: '${$.version}',
|
|
773
1024
|
title: '${$.title}',
|
|
774
1025
|
description: '${$.description||"TODO: Add description"}',
|
|
775
1026
|
domain: '${$.domain}',
|
|
776
|
-
owners: [${$.owners.map((
|
|
777
|
-
tags: [${$.tags.map((
|
|
1027
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1028
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
778
1029
|
stability: '${$.stability||"beta"}',
|
|
779
1030
|
},
|
|
780
1031
|
|
|
781
1032
|
operations: [
|
|
782
|
-
${
|
|
1033
|
+
${b($.operations)||" // Add operations here"}
|
|
783
1034
|
],
|
|
784
1035
|
|
|
785
1036
|
events: [
|
|
786
|
-
${
|
|
1037
|
+
${b($.events)||" // Add events here"}
|
|
787
1038
|
],
|
|
788
1039
|
|
|
789
1040
|
presentations: [
|
|
790
|
-
${
|
|
1041
|
+
${b($.presentations)||" // Add presentations here"}
|
|
791
1042
|
],
|
|
792
1043
|
|
|
793
1044
|
experiments: [
|
|
794
|
-
${
|
|
1045
|
+
${b($.experiments)||" // Add experiments here"}
|
|
795
1046
|
],
|
|
796
1047
|
});
|
|
797
|
-
`}function
|
|
1048
|
+
`}function C5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function EW($){let b=C5($.key),n=`${b}FormModel`,A=`${b}Form`;return`/**
|
|
798
1049
|
* ${$.title} Form
|
|
799
1050
|
*
|
|
800
1051
|
* Auto-generated form spec.
|
|
@@ -803,8 +1054,8 @@ ${W($.experiments)||" // Add experiments here"}
|
|
|
803
1054
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
804
1055
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
805
1056
|
|
|
806
|
-
const ${
|
|
807
|
-
name: '${
|
|
1057
|
+
const ${n} = defineSchemaModel({
|
|
1058
|
+
name: '${n}',
|
|
808
1059
|
description: '${$.description||"TODO: Add form model description"}',
|
|
809
1060
|
fields: {
|
|
810
1061
|
${$.primaryFieldKey}: {
|
|
@@ -821,11 +1072,11 @@ export const ${A} = defineFormSpec({
|
|
|
821
1072
|
title: '${$.title}',
|
|
822
1073
|
description: '${$.description||"TODO: Add description"}',
|
|
823
1074
|
domain: '${$.domain}',
|
|
824
|
-
owners: [${$.owners.map((
|
|
825
|
-
tags: [${$.tags.map((
|
|
1075
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1076
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
826
1077
|
stability: '${$.stability||"beta"}',
|
|
827
1078
|
},
|
|
828
|
-
model: ${
|
|
1079
|
+
model: ${n},
|
|
829
1080
|
fields: [
|
|
830
1081
|
{
|
|
831
1082
|
kind: 'text',
|
|
@@ -850,17 +1101,17 @@ export const ${A} = defineFormSpec({
|
|
|
850
1101
|
form: 'react-hook-form',
|
|
851
1102
|
},
|
|
852
1103
|
});
|
|
853
|
-
`}function
|
|
854
|
-
import { ${A} } from '../contracts/${
|
|
1104
|
+
`}function MW($,b){let n=x5($.split(".").pop()||"unknown")+"Handler",A=Dn($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1105
|
+
import { ${A} } from '../contracts/${NW($)}.contracts';
|
|
855
1106
|
|
|
856
1107
|
/**
|
|
857
1108
|
* Handler for ${$}
|
|
858
1109
|
*/
|
|
859
|
-
export const ${
|
|
1110
|
+
export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
860
1111
|
input,
|
|
861
1112
|
context
|
|
862
1113
|
) => {
|
|
863
|
-
// TODO: Implement ${
|
|
1114
|
+
// TODO: Implement ${b} logic
|
|
864
1115
|
|
|
865
1116
|
try {
|
|
866
1117
|
// 1. Validate prerequisites
|
|
@@ -876,28 +1127,28 @@ export const ${j}: ContractHandler<typeof ${A}> = async (
|
|
|
876
1127
|
throw error;
|
|
877
1128
|
}
|
|
878
1129
|
};
|
|
879
|
-
`}function
|
|
1130
|
+
`}function TW($,b){let n=Dn($);return`import React from 'react';
|
|
880
1131
|
|
|
881
|
-
interface ${
|
|
1132
|
+
interface ${n}Props {
|
|
882
1133
|
// TODO: Define props based on presentation spec
|
|
883
1134
|
}
|
|
884
1135
|
|
|
885
1136
|
/**
|
|
886
|
-
* ${
|
|
1137
|
+
* ${b}
|
|
887
1138
|
*/
|
|
888
|
-
export const ${
|
|
1139
|
+
export const ${n}: React.FC<${n}Props> = (props) => {
|
|
889
1140
|
return (
|
|
890
1141
|
<div>
|
|
891
1142
|
{/* TODO: Implement component UI */}
|
|
892
|
-
<p>Component: ${
|
|
1143
|
+
<p>Component: ${n}</p>
|
|
893
1144
|
</div>
|
|
894
1145
|
);
|
|
895
1146
|
};
|
|
896
|
-
`}function
|
|
897
|
-
import { ${A} } from '${
|
|
1147
|
+
`}function DW($,b){let n=b==="handler"?"../handlers":"../components",A=Dn($);return`import { describe, it, expect } from 'bun:test';
|
|
1148
|
+
import { ${A} } from '${n}/${NW($)}';
|
|
898
1149
|
|
|
899
1150
|
describe('${A}', () => {
|
|
900
|
-
it('should ${
|
|
1151
|
+
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
901
1152
|
// TODO: Implement test
|
|
902
1153
|
expect(true).toBe(true);
|
|
903
1154
|
});
|
|
@@ -906,50 +1157,50 @@ describe('${A}', () => {
|
|
|
906
1157
|
// TODO: Test edge cases
|
|
907
1158
|
});
|
|
908
1159
|
|
|
909
|
-
${
|
|
1160
|
+
${b==="handler"?`it('should handle errors appropriately', async () => {
|
|
910
1161
|
// TODO: Test error scenarios
|
|
911
1162
|
});`:`it('should be accessible', async () => {
|
|
912
1163
|
// TODO: Test accessibility
|
|
913
1164
|
});`}
|
|
914
1165
|
});
|
|
915
|
-
`}function
|
|
916
|
-
`),
|
|
917
|
-
${$.capabilitiesRequired.map((
|
|
1166
|
+
`}function x5($){let b=Dn($);return b.charAt(0).toLowerCase()+b.slice(1)}function Dn($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function NW($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function FW($){let b=g5($.name.split(".").pop()??"Integration"),n=`${b}IntegrationSpec`,A=`register${b}Integration`,m=$.supportedModes.length?$.supportedModes:["managed"],y=m.map((G)=>`'${G}'`).join(", "),W=$.capabilitiesProvided.map((G)=>` { key: '${G.key}', version: '${G.version}' }`).join(`,
|
|
1167
|
+
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1168
|
+
${$.capabilitiesRequired.map((G)=>{let V=G.version!==void 0?`, version: '${G.version}'`:"",O=G.optional?", optional: true":"",K=G.reason?`, reason: '${w$(G.reason)}'`:"";return` { key: '${G.key}'${V}${O}${K} }`}).join(`,
|
|
918
1169
|
`)}
|
|
919
|
-
],`:"",
|
|
920
|
-
`:"",
|
|
1170
|
+
],`:"",j=I5($.configFields),B=M5($.configFields),S=E5($.secretFields),Q=T5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
|
|
1171
|
+
`:"",X=D5($.rateLimitRpm,$.rateLimitRph),Y=N5(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
921
1172
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
922
1173
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
923
1174
|
|
|
924
|
-
export const ${
|
|
1175
|
+
export const ${n}: IntegrationSpec = {
|
|
925
1176
|
meta: {
|
|
926
1177
|
key: '${$.name}',
|
|
927
1178
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
928
1179
|
category: '${$.category}',
|
|
929
|
-
displayName: '${
|
|
930
|
-
title: '${
|
|
931
|
-
description: '${
|
|
932
|
-
domain: '${
|
|
933
|
-
owners: [${$.owners.map((
|
|
934
|
-
tags: [${$.tags.map((
|
|
935
|
-
stability: StabilityEnum.${
|
|
936
|
-
},
|
|
937
|
-
supportedModes: [${
|
|
1180
|
+
displayName: '${w$($.displayName)}',
|
|
1181
|
+
title: '${w$($.title)}',
|
|
1182
|
+
description: '${w$($.description)}',
|
|
1183
|
+
domain: '${w$($.domain)}',
|
|
1184
|
+
owners: [${$.owners.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1185
|
+
tags: [${$.tags.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1186
|
+
stability: StabilityEnum.${v5($.stability)},
|
|
1187
|
+
},
|
|
1188
|
+
supportedModes: [${y}],
|
|
938
1189
|
capabilities: {
|
|
939
1190
|
provides: [
|
|
940
|
-
${
|
|
1191
|
+
${W}
|
|
941
1192
|
],
|
|
942
|
-
${
|
|
1193
|
+
${w.length>0?`${w}
|
|
943
1194
|
`:""} },
|
|
944
1195
|
configSchema: {
|
|
945
|
-
${
|
|
946
|
-
example: ${
|
|
1196
|
+
${j}
|
|
1197
|
+
example: ${B},
|
|
947
1198
|
},
|
|
948
1199
|
secretSchema: {
|
|
949
|
-
${
|
|
950
|
-
example: ${
|
|
1200
|
+
${S}
|
|
1201
|
+
example: ${Q},
|
|
951
1202
|
},
|
|
952
|
-
${
|
|
1203
|
+
${Z}${X}${Y} healthCheck: {
|
|
953
1204
|
method: '${$.healthCheckMethod}',
|
|
954
1205
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
955
1206
|
},
|
|
@@ -958,118 +1209,118 @@ ${G}${J}${b} healthCheck: {
|
|
|
958
1209
|
export function ${A}(
|
|
959
1210
|
registry: IntegrationSpecRegistry
|
|
960
1211
|
): IntegrationSpecRegistry {
|
|
961
|
-
return registry.register(${
|
|
1212
|
+
return registry.register(${n});
|
|
962
1213
|
}
|
|
963
|
-
`}function
|
|
964
|
-
`:"",A=$.length?$.map((
|
|
1214
|
+
`}function I5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1215
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: '${F5(m.type)}'${y} }`}).join(`,
|
|
965
1216
|
`):"";return` schema: {
|
|
966
1217
|
type: 'object',
|
|
967
|
-
${
|
|
1218
|
+
${n} properties: {
|
|
968
1219
|
${A||" "}
|
|
969
1220
|
},
|
|
970
1221
|
},
|
|
971
|
-
`}function
|
|
972
|
-
`:"",A=$.length?$.map((
|
|
1222
|
+
`}function E5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1223
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
973
1224
|
`):"";return` schema: {
|
|
974
1225
|
type: 'object',
|
|
975
|
-
${
|
|
1226
|
+
${n} properties: {
|
|
976
1227
|
${A||" "}
|
|
977
1228
|
},
|
|
978
1229
|
},
|
|
979
|
-
`}function
|
|
980
|
-
${$.map((
|
|
1230
|
+
`}function M5($){if($.length===0)return"{}";return`{
|
|
1231
|
+
${$.map((n)=>{switch(n.type){case"number":return` ${n.key}: 0`;case"boolean":return` ${n.key}: true`;case"string":default:return` ${n.key}: '${n.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
981
1232
|
`)}
|
|
982
|
-
}`}function
|
|
983
|
-
${$.map((
|
|
1233
|
+
}`}function T5($){if($.length===0)return"{}";return`{
|
|
1234
|
+
${$.map((n)=>` ${n.key}: '${n.key.toUpperCase()}_SECRET'`).join(`,
|
|
984
1235
|
`)}
|
|
985
|
-
}`}function
|
|
1236
|
+
}`}function D5($,b){if($==null&&b==null)return"";let n=[];if($!=null)n.push(` rpm: ${$}`);if(b!=null)n.push(` rph: ${b}`);return` constraints: {
|
|
986
1237
|
rateLimit: {
|
|
987
|
-
${
|
|
1238
|
+
${n.join(`,
|
|
988
1239
|
`)}
|
|
989
1240
|
},
|
|
990
1241
|
},
|
|
991
|
-
`}function
|
|
992
|
-
`:"",
|
|
993
|
-
`:"";if(!A&&!
|
|
994
|
-
${A}${
|
|
995
|
-
`}function
|
|
1242
|
+
`}function N5($,b,n){if(!$.includes("byok"))return"";let A=b?` setupInstructions: '${w$(b)}',
|
|
1243
|
+
`:"",m=n&&n.length?` requiredScopes: [${n.map((y)=>`'${w$(y)}'`).join(", ")}],
|
|
1244
|
+
`:"";if(!A&&!m)return"";return` byokSetup: {
|
|
1245
|
+
${A}${m} },
|
|
1246
|
+
`}function F5($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function v5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function g5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function w$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function vW($){let b=c5($.name.split(".").pop()??"KnowledgeSpace"),n=`${b}KnowledgeSpace`,A=`register${b}KnowledgeSpace`,m=P5($),y=k5($),W=r5($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
996
1247
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
997
1248
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
998
1249
|
|
|
999
|
-
export const ${
|
|
1250
|
+
export const ${n}: KnowledgeSpaceSpec = {
|
|
1000
1251
|
meta: {
|
|
1001
1252
|
key: '${$.name}',
|
|
1002
1253
|
version: ${$.version},
|
|
1003
1254
|
category: '${$.category}',
|
|
1004
|
-
displayName: '${
|
|
1005
|
-
title: '${
|
|
1006
|
-
description: '${
|
|
1007
|
-
domain: '${
|
|
1008
|
-
owners: [${$.owners.map((
|
|
1009
|
-
tags: [${$.tags.map((
|
|
1010
|
-
stability: StabilityEnum.${
|
|
1011
|
-
},
|
|
1012
|
-
retention: ${
|
|
1255
|
+
displayName: '${O$($.displayName)}',
|
|
1256
|
+
title: '${O$($.title)}',
|
|
1257
|
+
description: '${O$($.description)}',
|
|
1258
|
+
domain: '${O$($.domain)}',
|
|
1259
|
+
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1260
|
+
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1261
|
+
stability: StabilityEnum.${f5($.stability)},
|
|
1262
|
+
},
|
|
1263
|
+
retention: ${m},
|
|
1013
1264
|
access: {
|
|
1014
|
-
${
|
|
1265
|
+
${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${w}
|
|
1015
1266
|
`:""} },
|
|
1016
|
-
${
|
|
1267
|
+
${W} description: '${O$($.description||$.displayName)}',
|
|
1017
1268
|
};
|
|
1018
1269
|
|
|
1019
1270
|
export function ${A}(
|
|
1020
1271
|
registry: KnowledgeSpaceRegistry
|
|
1021
1272
|
): KnowledgeSpaceRegistry {
|
|
1022
|
-
return registry.register(${
|
|
1273
|
+
return registry.register(${n});
|
|
1023
1274
|
}
|
|
1024
|
-
`}function
|
|
1025
|
-
`,
|
|
1026
|
-
`;return`${
|
|
1027
|
-
${
|
|
1275
|
+
`}function P5($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",n=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${n} }`}function k5($){let b=` trustLevel: '${$.trustLevel}',
|
|
1276
|
+
`,n=` automationWritable: ${$.automationWritable},
|
|
1277
|
+
`;return`${b}${n}`}function r5($){let b=[];if($.embeddingModel)b.push(` embeddingModel: '${O$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")b.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)b.push(` vectorDbIntegration: '${O$($.vectorDbIntegration)}'`);if(b.length===0)return"";return` indexing: {
|
|
1278
|
+
${b.join(`,
|
|
1028
1279
|
`)}
|
|
1029
1280
|
},
|
|
1030
|
-
`}function
|
|
1281
|
+
`}function f5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function c5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function O$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function PW($){let n=`${h5($.name.split(".").pop()??"Migration")}Migration`,A=$.dependencies.length>0?`dependencies: [${$.dependencies.map((m)=>`'${m}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1031
1282
|
|
|
1032
|
-
export const ${
|
|
1283
|
+
export const ${n}: MigrationSpec = {
|
|
1033
1284
|
meta: {
|
|
1034
1285
|
key: '${$.name}',
|
|
1035
1286
|
version: ${$.version},
|
|
1036
|
-
title: '${
|
|
1037
|
-
description: '${
|
|
1038
|
-
domain: '${
|
|
1039
|
-
owners: [${$.owners.map((
|
|
1040
|
-
tags: [${$.tags.map((
|
|
1287
|
+
title: '${f$($.title)}',
|
|
1288
|
+
description: '${f$($.description??"")}',
|
|
1289
|
+
domain: '${f$($.domain)}',
|
|
1290
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1291
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1041
1292
|
stability: '${$.stability}',
|
|
1042
1293
|
},
|
|
1043
1294
|
plan: {
|
|
1044
1295
|
up: [
|
|
1045
|
-
${
|
|
1296
|
+
${gW($.up)}
|
|
1046
1297
|
],${$.down&&$.down.length?`
|
|
1047
1298
|
down: [
|
|
1048
|
-
${
|
|
1299
|
+
${gW($.down)}
|
|
1049
1300
|
],`:""}
|
|
1050
1301
|
},
|
|
1051
1302
|
${A}
|
|
1052
1303
|
};
|
|
1053
|
-
`}function
|
|
1304
|
+
`}function gW($){return $.map((b)=>{let n=b.description?`description: '${f$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1054
1305
|
kind: 'schema',
|
|
1055
|
-
${
|
|
1056
|
-
sql: \`${
|
|
1306
|
+
${n}
|
|
1307
|
+
sql: \`${f$(b.sql??"")}\`,
|
|
1057
1308
|
}`;case"data":return` {
|
|
1058
1309
|
kind: 'data',
|
|
1059
|
-
${
|
|
1060
|
-
script: \`${
|
|
1310
|
+
${n}
|
|
1311
|
+
script: \`${f$(b.script??"")}\`,
|
|
1061
1312
|
}`;case"validation":default:return` {
|
|
1062
1313
|
kind: 'validation',
|
|
1063
|
-
${
|
|
1064
|
-
assertion: \`${
|
|
1314
|
+
${n}
|
|
1315
|
+
assertion: \`${f$(b.assertion??"")}\`,
|
|
1065
1316
|
}`}}).join(`,
|
|
1066
|
-
`)}function
|
|
1317
|
+
`)}function h5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function kW($){let{name:b,version:n,kind:A,description:m,goal:y,context:W,stability:w,owners:j,tags:B,auth:S,flags:Q}=$,Z=d5(b.split(".").pop()||"Unknown")+"Spec",X=Z.replace("Spec","Input"),Y=Z.replace("Spec","Output");return`import { define${q0(A)} } from '@contractspec/lib.contracts-spec';
|
|
1067
1318
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1068
1319
|
|
|
1069
1320
|
// TODO: Define input schema
|
|
1070
|
-
export const ${
|
|
1071
|
-
name: '${
|
|
1072
|
-
description: 'Input for ${
|
|
1321
|
+
export const ${X} = new SchemaModel({
|
|
1322
|
+
name: '${X}',
|
|
1323
|
+
description: 'Input for ${b}',
|
|
1073
1324
|
fields: {
|
|
1074
1325
|
// Add your fields here
|
|
1075
1326
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
@@ -1077,32 +1328,32 @@ export const ${J} = new SchemaModel({
|
|
|
1077
1328
|
});
|
|
1078
1329
|
|
|
1079
1330
|
// TODO: Define output schema
|
|
1080
|
-
export const ${
|
|
1081
|
-
name: '${
|
|
1082
|
-
description: 'Output for ${
|
|
1331
|
+
export const ${Y} = new SchemaModel({
|
|
1332
|
+
name: '${Y}',
|
|
1333
|
+
description: 'Output for ${b}',
|
|
1083
1334
|
fields: {
|
|
1084
1335
|
// Add your fields here
|
|
1085
1336
|
ok: { type: ScalarTypeEnum.Boolean(), isOptional: false },
|
|
1086
1337
|
},
|
|
1087
1338
|
});
|
|
1088
1339
|
|
|
1089
|
-
export const ${
|
|
1340
|
+
export const ${Z} = define${q0(A)}({
|
|
1090
1341
|
meta: {
|
|
1091
|
-
key: '${
|
|
1092
|
-
key: '${
|
|
1093
|
-
version: '${
|
|
1094
|
-
stability: '${
|
|
1095
|
-
stability: '${
|
|
1096
|
-
owners: [${
|
|
1097
|
-
tags: [${
|
|
1098
|
-
description: '${
|
|
1099
|
-
goal: '${
|
|
1100
|
-
context: '${
|
|
1342
|
+
key: '${b}',
|
|
1343
|
+
key: '${b}',
|
|
1344
|
+
version: '${n}',
|
|
1345
|
+
stability: '${w}',
|
|
1346
|
+
stability: '${w}',
|
|
1347
|
+
owners: [${j.map((G)=>`'${G}'`).join(", ")}],
|
|
1348
|
+
tags: [${B.map((G)=>`'${G}'`).join(", ")}],
|
|
1349
|
+
description: '${m}',
|
|
1350
|
+
goal: '${y}',
|
|
1351
|
+
context: '${W}',
|
|
1101
1352
|
},
|
|
1102
1353
|
|
|
1103
1354
|
io: {
|
|
1104
|
-
input: ${
|
|
1105
|
-
output: ${
|
|
1355
|
+
input: ${X},
|
|
1356
|
+
output: ${Y},
|
|
1106
1357
|
errors: {
|
|
1107
1358
|
// Define possible errors
|
|
1108
1359
|
// EXAMPLE_ERROR: {
|
|
@@ -1114,8 +1365,8 @@ export const ${G} = define${_1(A)}({
|
|
|
1114
1365
|
},
|
|
1115
1366
|
|
|
1116
1367
|
policy: {
|
|
1117
|
-
auth: '${
|
|
1118
|
-
${
|
|
1368
|
+
auth: '${S}',
|
|
1369
|
+
${Q.length>0?`flags: [${Q.map((G)=>`'${G}'`).join(", ")}],`:"// flags: [],"}
|
|
1119
1370
|
},
|
|
1120
1371
|
|
|
1121
1372
|
sideEffects: {
|
|
@@ -1130,8 +1381,8 @@ export const ${G} = define${_1(A)}({
|
|
|
1130
1381
|
|
|
1131
1382
|
transport: {
|
|
1132
1383
|
rest: { method: '${A==="command"?"POST":"GET"}' },
|
|
1133
|
-
gql: { field: '${
|
|
1134
|
-
mcp: { toolName: '${
|
|
1384
|
+
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1385
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(n).replace(/\./g,"_")}' },
|
|
1135
1386
|
},
|
|
1136
1387
|
|
|
1137
1388
|
acceptance: {
|
|
@@ -1152,13 +1403,13 @@ export const ${G} = define${_1(A)}({
|
|
|
1152
1403
|
],
|
|
1153
1404
|
},
|
|
1154
1405
|
});
|
|
1155
|
-
`}function
|
|
1406
|
+
`}function q0($){return $.charAt(0).toUpperCase()+$.slice(1)}function d5($){return $.split(/[-_.]/).map(q0).join("")}function rW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,presentationKind:w}=$,j=u5(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1156
1407
|
kind: 'web_component',
|
|
1157
1408
|
framework: 'react',
|
|
1158
|
-
componentKey: '${
|
|
1409
|
+
componentKey: '${b.replace(/\./g,"_")}',
|
|
1159
1410
|
props: new SchemaModel({
|
|
1160
|
-
name: '${
|
|
1161
|
-
description: 'Props for ${
|
|
1411
|
+
name: '${j}Props',
|
|
1412
|
+
description: 'Props for ${b}',
|
|
1162
1413
|
fields: {
|
|
1163
1414
|
// TODO: Define component props
|
|
1164
1415
|
},
|
|
@@ -1166,20 +1417,20 @@ export const ${G} = define${_1(A)}({
|
|
|
1166
1417
|
analytics: [
|
|
1167
1418
|
// TODO: Define analytics events
|
|
1168
1419
|
],
|
|
1169
|
-
},`;break;case"markdown":
|
|
1420
|
+
},`;break;case"markdown":B=` content: {
|
|
1170
1421
|
kind: 'markdown',
|
|
1171
1422
|
content: \`
|
|
1172
1423
|
# ${A}
|
|
1173
1424
|
|
|
1174
1425
|
TODO: Add markdown content here
|
|
1175
1426
|
\`,
|
|
1176
|
-
// Or use resourceUri: 'feature://${
|
|
1177
|
-
},`;break;case"data":
|
|
1427
|
+
// Or use resourceUri: 'feature://${b}/guide.md'
|
|
1428
|
+
},`;break;case"data":B=` content: {
|
|
1178
1429
|
kind: 'data',
|
|
1179
1430
|
mimeType: 'application/json',
|
|
1180
1431
|
model: new SchemaModel({
|
|
1181
|
-
name: '${
|
|
1182
|
-
description: 'Data structure for ${
|
|
1432
|
+
name: '${j}Data',
|
|
1433
|
+
description: 'Data structure for ${b}',
|
|
1183
1434
|
fields: {
|
|
1184
1435
|
// TODO: Define data structure
|
|
1185
1436
|
},
|
|
@@ -1187,13 +1438,13 @@ TODO: Add markdown content here
|
|
|
1187
1438
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1188
1439
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1189
1440
|
|
|
1190
|
-
export const ${
|
|
1441
|
+
export const ${j}: PresentationSpec = {
|
|
1191
1442
|
meta: {
|
|
1192
|
-
key: '${
|
|
1193
|
-
version: ${
|
|
1194
|
-
stability: '${
|
|
1195
|
-
owners: [${
|
|
1196
|
-
tags: [${
|
|
1443
|
+
key: '${b}',
|
|
1444
|
+
version: ${n},
|
|
1445
|
+
stability: '${m}',
|
|
1446
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1447
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1197
1448
|
description: '${A}',
|
|
1198
1449
|
},
|
|
1199
1450
|
|
|
@@ -1202,81 +1453,109 @@ export const ${B}: PresentationSpec = {
|
|
|
1202
1453
|
// pii: [],
|
|
1203
1454
|
},
|
|
1204
1455
|
|
|
1205
|
-
${
|
|
1456
|
+
${B}
|
|
1206
1457
|
};
|
|
1207
|
-
`}function
|
|
1208
|
-
${$.providers.map((
|
|
1209
|
-
type: '${
|
|
1210
|
-
config: ${
|
|
1458
|
+
`}function u5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function fW($){let b=o5($.name.split(".").pop()??"Telemetry")+"Telemetry",n=$.providers?.length?`providers: [
|
|
1459
|
+
${$.providers.map((m)=>` {
|
|
1460
|
+
type: '${m.type}',
|
|
1461
|
+
config: ${i5(m.config)},
|
|
1211
1462
|
}`).join(`,
|
|
1212
1463
|
`)}
|
|
1213
|
-
],`:"",A=$.events.map((
|
|
1214
|
-
type: '${
|
|
1215
|
-
${
|
|
1216
|
-
${
|
|
1217
|
-
${
|
|
1218
|
-
${
|
|
1464
|
+
],`:"",A=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1465
|
+
type: '${w.type}',
|
|
1466
|
+
${w.required?"required: true,":""}
|
|
1467
|
+
${w.pii?"pii: true,":""}
|
|
1468
|
+
${w.redact?"redact: true,":""}
|
|
1469
|
+
${w.description?`description: '${l(w.description)}',`:""}
|
|
1219
1470
|
}`).join(`,
|
|
1220
|
-
`),
|
|
1471
|
+
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1221
1472
|
enabled: true,
|
|
1222
|
-
${typeof
|
|
1473
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1223
1474
|
thresholds: [
|
|
1224
|
-
${
|
|
1225
|
-
metric: '${
|
|
1226
|
-
${typeof
|
|
1227
|
-
${typeof
|
|
1475
|
+
${m.anomalyRules.map((w)=>` {
|
|
1476
|
+
metric: '${l(w.metric)}',
|
|
1477
|
+
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1478
|
+
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1228
1479
|
}`).join(`,
|
|
1229
1480
|
`)}
|
|
1230
1481
|
],
|
|
1231
|
-
actions: [${(
|
|
1232
|
-
},`:
|
|
1482
|
+
actions: [${(m.anomalyActions??[]).map((w)=>`'${w}'`).join(", ")}],
|
|
1483
|
+
},`:m.anomalyEnabled?` anomalyDetection: {
|
|
1233
1484
|
enabled: true,
|
|
1234
|
-
${typeof
|
|
1485
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1235
1486
|
},`:"";return` {
|
|
1236
|
-
name: '${
|
|
1237
|
-
version: ${
|
|
1487
|
+
name: '${l(m.name)}',
|
|
1488
|
+
version: ${m.version},
|
|
1238
1489
|
semantics: {
|
|
1239
|
-
what: '${
|
|
1240
|
-
${
|
|
1241
|
-
${
|
|
1490
|
+
what: '${l(m.what)}',
|
|
1491
|
+
${m.who?`who: '${l(m.who)}',`:""}
|
|
1492
|
+
${m.why?`why: '${l(m.why)}',`:""}
|
|
1242
1493
|
},
|
|
1243
|
-
privacy: '${
|
|
1494
|
+
privacy: '${m.privacy}',
|
|
1244
1495
|
properties: {
|
|
1245
|
-
${
|
|
1496
|
+
${y}
|
|
1246
1497
|
},
|
|
1247
|
-
${typeof
|
|
1248
|
-
${typeof
|
|
1249
|
-
${
|
|
1250
|
-
${
|
|
1498
|
+
${typeof m.retentionDays==="number"?`retention: { days: ${m.retentionDays}, ${m.retentionPolicy?`policy: '${m.retentionPolicy}'`:""} },`:""}
|
|
1499
|
+
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${l(m.samplingConditions)}']`:""} },`:""}
|
|
1500
|
+
${W}
|
|
1501
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${l(w)}'`).join(", ")}],`:""}
|
|
1251
1502
|
}`}).join(`,
|
|
1252
1503
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1253
1504
|
|
|
1254
|
-
export const ${
|
|
1505
|
+
export const ${b}: TelemetrySpec = {
|
|
1255
1506
|
meta: {
|
|
1256
|
-
key: '${
|
|
1507
|
+
key: '${l($.name)}',
|
|
1257
1508
|
version: ${$.version},
|
|
1258
|
-
title: '${
|
|
1259
|
-
description: '${
|
|
1260
|
-
domain: '${
|
|
1261
|
-
owners: [${$.owners.map((
|
|
1262
|
-
tags: [${$.tags.map((
|
|
1509
|
+
title: '${l($.name)} telemetry',
|
|
1510
|
+
description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1511
|
+
domain: '${l($.domain)}',
|
|
1512
|
+
owners: [${$.owners.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1513
|
+
tags: [${$.tags.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1263
1514
|
stability: '${$.stability}',
|
|
1264
1515
|
},
|
|
1265
1516
|
config: {
|
|
1266
1517
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1267
1518
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1268
1519
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1269
|
-
${
|
|
1520
|
+
${n}
|
|
1270
1521
|
},
|
|
1271
1522
|
events: [
|
|
1272
1523
|
${A}
|
|
1273
1524
|
],
|
|
1274
1525
|
};
|
|
1275
|
-
`}function
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1526
|
+
`}function o5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function i5($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function t5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function cW($){return`/**
|
|
1527
|
+
* ${$.title} Theme
|
|
1528
|
+
*
|
|
1529
|
+
* Auto-generated theme spec.
|
|
1530
|
+
*/
|
|
1531
|
+
|
|
1532
|
+
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1533
|
+
|
|
1534
|
+
export const ${t5($.key)}Theme = defineTheme({
|
|
1535
|
+
meta: {
|
|
1536
|
+
key: '${$.key}',
|
|
1537
|
+
version: '${$.version}',
|
|
1538
|
+
title: '${$.title}',
|
|
1539
|
+
description: '${$.description}',
|
|
1540
|
+
domain: '${$.domain}',
|
|
1541
|
+
owners: [${$.owners.map((b)=>`'${b}'`).join(", ")}],
|
|
1542
|
+
tags: [${$.tags.map((b)=>`'${b}'`).join(", ")}],
|
|
1543
|
+
stability: '${$.stability}',
|
|
1544
|
+
scopes: [${$.scopes.map((b)=>`'${b}'`).join(", ")}],
|
|
1545
|
+
},
|
|
1546
|
+
tokens: {
|
|
1547
|
+
colors: {
|
|
1548
|
+
primary: { value: '#2563eb' },
|
|
1549
|
+
background: { value: '#ffffff' },
|
|
1550
|
+
foreground: { value: '#111827' },
|
|
1551
|
+
},
|
|
1552
|
+
},
|
|
1553
|
+
});
|
|
1554
|
+
`}function hW($){let b=p5($.name.split(".").pop()??"Workflow")+"Workflow",n=$.steps.map((m)=>l5(m)).join(`,
|
|
1555
|
+
`),A=$.transitions.map((m)=>` {
|
|
1556
|
+
from: '${m.from}',
|
|
1557
|
+
to: '${m.to}',
|
|
1558
|
+
${m.condition?` condition: '${Ab(m.condition)}',`:""}
|
|
1280
1559
|
}`).join(`,
|
|
1281
1560
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1282
1561
|
|
|
@@ -1288,36 +1567,36 @@ ${Q.condition?` condition: '${h$(Q.condition)}',`:""}
|
|
|
1288
1567
|
* - Provide form renderers for human steps.
|
|
1289
1568
|
* - Add guards/conditions as needed.
|
|
1290
1569
|
*/
|
|
1291
|
-
export const ${
|
|
1570
|
+
export const ${b}: WorkflowSpec = {
|
|
1292
1571
|
meta: {
|
|
1293
1572
|
key: '${$.name}',
|
|
1294
1573
|
version: ${$.version},
|
|
1295
|
-
title: '${
|
|
1296
|
-
description: '${
|
|
1297
|
-
domain: '${
|
|
1574
|
+
title: '${Ab($.title)}',
|
|
1575
|
+
description: '${Ab($.description)}',
|
|
1576
|
+
domain: '${Ab($.domain)}',
|
|
1298
1577
|
stability: '${$.stability}',
|
|
1299
|
-
owners: [${$.owners.map((
|
|
1300
|
-
tags: [${$.tags.map((
|
|
1578
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1579
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1301
1580
|
},
|
|
1302
1581
|
definition: {
|
|
1303
1582
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1304
1583
|
`:""} steps: [
|
|
1305
|
-
${
|
|
1584
|
+
${n}
|
|
1306
1585
|
],
|
|
1307
1586
|
transitions: [
|
|
1308
1587
|
${A}
|
|
1309
1588
|
],
|
|
1310
1589
|
},
|
|
1311
1590
|
${$.policyFlags.length>0?`policy: {
|
|
1312
|
-
flags: [${$.policyFlags.map((
|
|
1591
|
+
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1313
1592
|
},`:"// policy: { flags: [] },"}
|
|
1314
1593
|
};
|
|
1315
|
-
`}function
|
|
1316
|
-
`)}function
|
|
1594
|
+
`}function l5($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${Ab($.label)}',`];if($.description)b.push(` description: '${Ab($.description)}',`);let n=[];if($.operation)n.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)n.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(n.length)b.push(` action: { ${n.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1595
|
+
`)}function p5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ab($){return $.replace(/'/g,"\\'")}function Nn({exportName:$,specImportPath:b,workflowFunctionName:n}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1317
1596
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1318
|
-
import { ${$} } from '${
|
|
1597
|
+
import { ${$} } from '${b}';
|
|
1319
1598
|
|
|
1320
|
-
export async function ${
|
|
1599
|
+
export async function ${n}(input = {}, bridge = {}) {
|
|
1321
1600
|
"use workflow";
|
|
1322
1601
|
|
|
1323
1602
|
// Keep the workflow function deterministic.
|
|
@@ -1334,29 +1613,29 @@ export async function ${j}(input = {}, bridge = {}) {
|
|
|
1334
1613
|
},
|
|
1335
1614
|
});
|
|
1336
1615
|
}
|
|
1337
|
-
`}function
|
|
1338
|
-
import { ${
|
|
1616
|
+
`}function Fn($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1617
|
+
import { ${b} } from '${$}';
|
|
1339
1618
|
|
|
1340
1619
|
export const POST = createWorkflowDevkitStartRoute({
|
|
1341
|
-
workflow: ${
|
|
1620
|
+
workflow: ${b},
|
|
1342
1621
|
async buildArgs(body) {
|
|
1343
1622
|
return [body];
|
|
1344
1623
|
},
|
|
1345
1624
|
});
|
|
1346
|
-
`}function
|
|
1625
|
+
`}function vn(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1347
1626
|
|
|
1348
1627
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1349
1628
|
resolveToken({ runId }) {
|
|
1350
1629
|
return \`workflow-session:\${runId}\`;
|
|
1351
1630
|
},
|
|
1352
1631
|
});
|
|
1353
|
-
`}function
|
|
1632
|
+
`}function gn(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1354
1633
|
|
|
1355
1634
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1356
|
-
`}function
|
|
1635
|
+
`}function Pn($,b){return`import { ${b} } from '${$}';
|
|
1357
1636
|
|
|
1358
1637
|
export const workflowDevkitBootstrap = {
|
|
1359
|
-
workflow: ${
|
|
1638
|
+
workflow: ${b},
|
|
1360
1639
|
createBridge() {
|
|
1361
1640
|
return {
|
|
1362
1641
|
executeAutomationStep: async () => {
|
|
@@ -1365,10 +1644,10 @@ export const workflowDevkitBootstrap = {
|
|
|
1365
1644
|
};
|
|
1366
1645
|
},
|
|
1367
1646
|
};
|
|
1368
|
-
`}function
|
|
1647
|
+
`}function kn({exportName:$,specImportPath:b,runnerName:n,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1369
1648
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1370
1649
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1371
|
-
import { ${$} } from '${
|
|
1650
|
+
import { ${$} } from '${b}';
|
|
1372
1651
|
|
|
1373
1652
|
/**
|
|
1374
1653
|
* Runner wiring for ${A}.
|
|
@@ -1383,7 +1662,7 @@ registry.register(${$});
|
|
|
1383
1662
|
|
|
1384
1663
|
const stateStore = new InMemoryStateStore();
|
|
1385
1664
|
|
|
1386
|
-
export const ${
|
|
1665
|
+
export const ${n} = new WorkflowRunner({
|
|
1387
1666
|
registry,
|
|
1388
1667
|
stateStore,
|
|
1389
1668
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1405,12 +1684,12 @@ export const ${j} = new WorkflowRunner({
|
|
|
1405
1684
|
// console.log(event, payload);
|
|
1406
1685
|
},
|
|
1407
1686
|
});
|
|
1408
|
-
`}import{getAuthoringTargetDefinition as
|
|
1409
|
-
`],[
|
|
1687
|
+
`}import{getAuthoringTargetDefinition as a5}from"@contractspec/module.workspace";var uW={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function oW($,b){let n=e5($,b.specPath),A=s5($,b.target,n),m=$.join(n,"package.json"),y=$.join(n,"README.md"),W=$.join(n,"src"),w=$.join(W,"index.ts"),j=O0($.relative(W,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(W);let B=[[m,JSON.stringify({name:A,version:"0.1.0",description:uW[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1688
|
+
`],[y,`# ${A}
|
|
1410
1689
|
|
|
1411
|
-
${
|
|
1412
|
-
`],[
|
|
1413
|
-
`],[
|
|
1690
|
+
${uW[b.target]}.
|
|
1691
|
+
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1692
|
+
`],[b.specPath,b.specCode]],S={packageRoot:n,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function rn($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1414
1693
|
|
|
1415
1694
|
export const ${$.exportName} = defineModuleBundle({
|
|
1416
1695
|
meta: {
|
|
@@ -1435,7 +1714,15 @@ export const ${$.exportName} = defineModuleBundle({
|
|
|
1435
1714
|
layouts: [],
|
|
1436
1715
|
data: [],
|
|
1437
1716
|
verification: {
|
|
1438
|
-
|
|
1717
|
+
dimensions: {
|
|
1718
|
+
guidance: "Scaffolded guidance profile for ${$.title}.",
|
|
1719
|
+
density: "Scaffolded density profile for ${$.title}.",
|
|
1720
|
+
dataDepth: "Scaffolded data-depth profile for ${$.title}.",
|
|
1721
|
+
control: "Scaffolded control profile for ${$.title}.",
|
|
1722
|
+
media: "Scaffolded media profile for ${$.title}.",
|
|
1723
|
+
pace: "Scaffolded pace profile for ${$.title}.",
|
|
1724
|
+
narrative: "Scaffolded narrative profile for ${$.title}.",
|
|
1725
|
+
},
|
|
1439
1726
|
},
|
|
1440
1727
|
},
|
|
1441
1728
|
},
|
|
@@ -1471,22 +1758,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1471
1758
|
supportedArtifactTypes: ["patch"],
|
|
1472
1759
|
knownConstraints: [],
|
|
1473
1760
|
};
|
|
1474
|
-
`}}function
|
|
1761
|
+
`}}function e5($,b){let n=O0(b),A="/src/",m=n.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return n.slice(0,m)}function s5($,b,n){let A=a5(b),m=O0($.basename(n));return`${A.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${m}`}function O0($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function yb($,b,n,A={}){let{fs:m,logger:y,workspace:W}=b,w=W?.scanSpecSource??W8,j=W?.inferSpecTypeFromFilePath??y8,B=W?.generateHandlerTemplate??n8,S=W?.generateComponentTemplate??b8,Q=W?.generateTestTemplate??A8,{targets:Z=void 0,outputDir:X=n.outputDir,overwrite:Y=!1,dryRun:G=!1,includeTests:V=!1,runtimeGeneration:O}=A,K=await m.readFile($),J=w(K,$),U=$8(K,$),H=U==="unknown"?j($):U,q=Z??J0(H,{includeTests:V});y.info(`Building from spec: ${$}`,{targetId:H});let _=[],z={};for(let L of q)try{let C=await w8(L,$,K,J,H,{fs:m,logger:y},X,Y,G,O,z,{genHandler:B,genComponent:S,genTest:Q});if(_.push(C),C.success&&C.generatedCode)z[L]=C.generatedCode}catch(C){_.push({target:L,outputPath:"",success:!1,error:C instanceof Error?C.message:String(C),skipped:!1})}return{specPath:$,specInfo:J,targetId:H,results:_}}async function w8($,b,n,A,m,y,W,w,j,B,S,Q){let{fs:Z,logger:X}=y,{genHandler:Y,genComponent:G,genTest:V}=Q,O,K,J=[];switch($){case"handler":{if(m!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${m})`};let q=A.kind==="command"||A.kind==="query"?A.kind:"command",_=Y(s(n,A,b),q);K=mb(b,W,"handlers",s(n,A,b),".handler.ts",y.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:n,outputPath:K,fallbackCode:_})??_;break}case"component":{if(m!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${m})`};let q=G(s(n,A,b),A.description??"");K=mb(b,W,"components",s(n,A,b),".tsx",y.fs),O=await B?.generateArtifact?.({kind:"component",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"test":{let q=m==="operation"?"handler":"component",_=m==="operation"?S.handler??"":m==="presentation"?S.component??"":m==="form"?S.form??"":"",z=V(s(n,A,b),q);K=mb(b,W,"__tests__",s(n,A,b),".test.ts",y.fs),O=await B?.generateTest?.({kind:q,specCode:n,outputPath:K,existingCode:_,fallbackCode:z})??z;break}case"form":{if(m!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${m})`};let q=`import * as React from "react";
|
|
1475
1762
|
|
|
1476
|
-
export interface ${
|
|
1763
|
+
export interface ${V$(s(n,A,b))}Props {
|
|
1477
1764
|
className?: string;
|
|
1478
1765
|
}
|
|
1479
1766
|
|
|
1480
|
-
export function ${
|
|
1767
|
+
export function ${V$(s(n,A,b))}Form({
|
|
1481
1768
|
className,
|
|
1482
|
-
}: ${
|
|
1483
|
-
return <form className={className}>TODO: implement ${
|
|
1769
|
+
}: ${V$(s(n,A,b))}Props) {
|
|
1770
|
+
return <form className={className}>TODO: implement ${s(n,A,b)}</form>;
|
|
1484
1771
|
}
|
|
1485
|
-
`;
|
|
1772
|
+
`;K=mb(b,W,"forms",s(n,A,b),".form.tsx",y.fs),O=await B?.generateArtifact?.({kind:"form",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"workflow-runner":{if(m!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${m})`};let q=s(n,A,b),_=Q8(n)??`${V$(q)}Workflow`,z=`${V$(q)}Runner`,L=U0(q);if(K=mb(b,W,"workflows",q,".runner.ts",y.fs),O=kn({exportName:_,specImportPath:V0(y.fs,K,b),runnerName:z,workflowName:q}),Y8(n)){let C=`${V$(q)}WorkflowDevkit`,D=_b(y.fs,K,`${L}.workflow-devkit.ts`),F=_b(y.fs,K,`${L}.workflow-devkit.start.route.ts`),E=_b(y.fs,K,`${L}.workflow-devkit.follow-up.route.ts`),r=_b(y.fs,K,`${L}.workflow-devkit.stream.route.ts`),g=_b(y.fs,K,`${L}.workflow-devkit.generic.ts`);J=[{path:D,code:Nn({exportName:_,specImportPath:V0(y.fs,D,b),workflowFunctionName:C})},{path:F,code:Fn(iW(y.fs,F,D),C)},{path:E,code:vn()},{path:r,code:gn()},{path:g,code:Pn(iW(y.fs,g,D),C)}]}break}case"data-view-renderer":{if(m!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${m})`};let q=s(n,A,b),_=Z8(n)??`${V$(q)}DataView`,z=`${V$(q)}Renderer`;K=mb(b,W,"data-views",q,".renderer.tsx",y.fs),O=Tn({exportName:_,specImportPath:V0(y.fs,K,b),rendererName:z,viewKind:X8(n)??"table"});break}case"package-scaffold":{if(m!=="module-bundle"&&m!=="builder-spec"&&m!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${m})`};if(j){let z=B8(b);return X.info(`[dry-run] Would scaffold package: ${z}`),{target:$,outputPath:z,success:!0}}let q=n.trim().length>0?n:rn({target:m,key:A.key??y.fs.basename(b),title:A.key??y.fs.basename(b),description:A.description??m8(m).title,exportName:V$(A.key??y.fs.basename(b))});return K=(await oW(y.fs,{target:m,specPath:b,specCode:q,overwrite:w})).packageRoot,X.info(`Generated package scaffold: ${K}`),{target:$,outputPath:K,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let U=[{path:K,code:O},...J],H=w?void 0:await j8(U,Z);if(H)return{target:$,outputPath:H,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(j){for(let q of U)X.info(`[dry-run] Would write: ${q.path}`);return{target:$,outputPath:K,success:!0,generatedCode:U[0]?.code}}for(let q of U)await Z.mkdir(Z.dirname(q.path)),await Z.writeFile(q.path,G8(q.code)),X.info(`Generated: ${q.path}`);return{target:$,outputPath:K,success:!0}}function J0($,b){switch($){case"operation":return b.includeTests?["handler","test"]:["handler"];case"presentation":return b.includeTests?["component","test"]:["component"];case"form":return b.includeTests?["form","test"]:["form"];case"workflow":return["workflow-runner"];case"data-view":return["data-view-renderer"];case"module-bundle":case"builder-spec":case"provider-spec":return["package-scaffold"];default:return[]}}function mb($,b,n,A,m,y){let W=U0(A.split(".").pop()??"unknown"),w;if(b.startsWith("."))w=y.resolve(y.dirname($),"..",b,n);else w=y.resolve(b,n);return y.join(w,`${W}${m}`)}async function j8($,b){for(let n of $)if(await b.exists(n.path))return n.path;return}function U0($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function V$($){return U0($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function K0($){return $.replace(/\.[^.]+$/,"")}function B8($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function V0($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function iW($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function _b($,b,n){return $.join($.dirname(b),n)}function s($,b,n){return S8($,"name")??b.key??K0(H8(n))}function S8($,b){let n=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(n)?.[1]??null}function Q8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function Z8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function X8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function Y8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function G8($){return $.endsWith(`
|
|
1486
1773
|
`)?$:`${$}
|
|
1487
|
-
`}function nZ($){return $.replaceAll("\\","/").split("/").pop()??$}i();import{scanAllSpecsFromSource as pZ,scanSpecSource as tZ}from"@contractspec/module.workspace";import aZ from"micromatch";var K8={};h(K8,{validators:()=>iZ,urlSchema:()=>oZ,isValidVersion:()=>rZ,isValidIdentifier:()=>b8,isValidDotName:()=>w8,isTestFile:()=>j0,isLibraryDefinitionFile:()=>A0,emailSchema:()=>lZ});import I1 from"micromatch";function j0($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return I1.isMatch($,j)}function A0($){let W=["**/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(I1.isMatch($,W))return!1;let j=["**/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 I1.isMatch($,j)}import*as H$ from"zod";function b8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function w8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function rZ($){return Number.isInteger($)&&$>0}var lZ=H$.string().email(),oZ=H$.string().url(),iZ={specName:H$.string().refine(w8,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:H$.number().int().positive(),identifier:H$.string().refine(b8,{message:"Must be a valid TypeScript identifier"}),owner:H$.string().startsWith("@"),tag:H$.string().min(1)};function Q0($){return($??"").split("|").map((W)=>W.trim().replace(/^\.?\//,"")).filter(Boolean)}function sZ($){let W=$?.packages&&$.packages.length>0?$.packages:["**"],j=[...Q0($?.conventions.models),...Q0($?.conventions.operations),...Q0($?.conventions.events),...Q0($?.conventions.presentations),...Q0($?.conventions.forms)];return[...new Set(W.flatMap((A)=>{let Q=A==="**"?"":`${A}/`,Z=Y$.map((Y)=>`${Q}${Y}`),X=j.map((Y)=>`${Q}${Y}/**/*.ts`);return[...Z,...X]}))]}function eZ($,W,j){if($.specType==="unknown")return!1;if(W.type&&!j.includes($.specType))return!1;return!0}function $6($,W){let j=$.filePath.localeCompare(W.filePath);if(j!==0)return j;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(W.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(W.discoveryId??W.key??"")}async function N$($,W={}){if(W.paths&&W.paths.length>0)return[...new Set(W.paths)].sort((j,A)=>j.localeCompare(A));if(W.pattern)return $.glob({cwd:W.cwd,pattern:W.pattern});return $.glob({cwd:W.cwd,patterns:sZ(W.config)})}async function QW($,W={}){let j=await N$($.fs,W),A=W.type?Array.isArray(W.type)?W.type:[W.type]:[],Q=[];for(let Z of j){if(W.config?.excludePackages&&aZ.isMatch(Z,W.config.excludePackages,{contains:!0}))continue;if(Z.includes("node_modules")||Z.includes("/dist/")||j0(Z,W.config)||A0(Z))continue;try{let X=await $.fs.readFile(Z),Y=pZ(X,Z),B=Y.length>0?Y:[tZ(X,Z)];for(let q of B)if(eZ(q,W,A))Q.push(q)}catch{}}return Q.sort($6)}function J$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function ZW($){let W=JSON.parse($),j=new Map,A=0,Q=0,Z=0,X=0,Y=0,B=0,q=0,H=0;for(let[G,J]of Object.entries(W)){let b=W6(G,J);j.set(G,b),A+=b.statements.total,Q+=b.statements.covered,Z+=b.branches.total,X+=b.branches.covered,Y+=b.functions.total,B+=b.functions.covered,q+=b.lines.total,H+=b.lines.covered}let V={statements:{covered:Q,total:A,pct:J$(Q,A)},branches:{covered:X,total:Z,pct:J$(X,Z)},functions:{covered:B,total:Y,pct:J$(B,Y)},lines:{covered:H,total:q,pct:J$(H,q)}};return{files:j,total:V}}function W6($,W){let j=Object.keys(W.statementMap).length,A=Object.values(W.s).filter((H)=>H>0).length,Q=Object.keys(W.fnMap).length,Z=Object.values(W.f).filter((H)=>H>0).length,X=0,Y=0;for(let H of Object.values(W.b))X+=H.length,Y+=H.filter((V)=>V>0).length;let B=new Set,q=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(B.add(G),(W.s[H]??0)>0)q.add(G);return{path:$,statements:{covered:A,total:j,pct:J$(A,j)},branches:{covered:Y,total:X,pct:J$(Y,X)},functions:{covered:Z,total:Q,pct:J$(Z,Q)},lines:{covered:q.size,total:B.size,pct:J$(q.size,B.size)}}}function M1($){switch($){case"istanbul":return{parse:ZW};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 E1($,W){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&W?.includes("cobertura"))return"cobertura";return"istanbul"}function N1($,W,j,A){let Q=[];if(j.statements!==void 0&&A.statements.pct<j.statements)Q.push({metric:"statements",required:j.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&A.branches.pct<j.branches)Q.push({metric:"branches",required:j.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&A.functions.pct<j.functions)Q.push({metric:"functions",required:j.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&A.lines.pct<j.lines)Q.push({metric:"lines",required:j.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Q.push({metric:"mutations",required:j.mutations,actual:0,message:`Mutation coverage required (${j.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:W,requirement:j,actual:A,passed:Q.length===0,failures:Q}}async function R1($,W,j){let{fs:A,logger:Q}=$,Z=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],B,q;for(let J of Y)if(await A.exists(J)){B=await A.readFile(J),q=J;break}if(!B)return Q.info("No coverage report found, skipping coverage checks"),Z;let H=E1(q??"coverage.json"),G=M1(H).parse(B);for(let J of W){if(J.specType!=="test-spec"||!J.key||!J.version||!J.sourceBlock)continue;let b=J.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!b||!b[1])continue;let w=b[1],L={},z=w.match(/statements\s*:\s*(\d+)/);if(z&&z[1])L.statements=parseInt(z[1],10);let S=w.match(/branches\s*:\s*(\d+)/);if(S&&S[1])L.branches=parseInt(S[1],10);let U=w.match(/functions\s*:\s*(\d+)/);if(U&&U[1])L.functions=parseInt(U[1],10);let O=w.match(/lines\s*:\s*(\d+)/);if(O&&O[1])L.lines=parseInt(O[1],10);if(Object.keys(L).length===0)continue;let K=N1(J.key,J.version,L,G.total);for(let _ of K.failures)Z.push({ruleId:"coverage-below-threshold",severity:"error",message:_.message,category:"coverage",file:J.filePath,context:{specKey:J.key,specVersion:J.version,metric:_.metric,required:_.required,actual:_.actual}})}return Z}import{addContractNode as j6,buildReverseEdges as A6,createContractGraph as Q6,detectCycles as Z6,findMissingDependencies as X6,parseImportedSpecNames as Y6,toDot as B6}from"@contractspec/module.workspace";async function _8($,W={}){let{fs:j}=$,A=await N$(j,{config:W.config,pattern:W.pattern}),Q=Q6();for(let Y of A){let B=await j.readFile(Y),q=j.relative(".",Y),H=j.basename(Y).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",V=Y6(B,Y);j6(Q,H,q,V)}A6(Q);let Z=Z6(Q),X=X6(Q);return{graph:Q,total:Q.size,cycles:Z,missing:X}}function aJ($,W){return $.get(W)}function sJ($){return B6($)}function eJ($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),A=W.filter((X)=>X.dependencies.length===0),Q=W.filter((X)=>X.dependents.length>0),Z=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:A.length,used:Q.length,unused:Z.length}}i();async function C1($,W){let j=[],A=await m($.fs),Q=await _8($,{config:A,pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" → ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let X of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${X}`,category:"deps",context:{contract:Z.contract,missing:X}});return j}import{analyzePackageDocBlocks as q6}from"@contractspec/module.workspace";var H6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function V6($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:H6}),A=new Map;for(let X of j){let Y=$.dirname(X),B=$.join(Y,"src");if(!await $.exists(B))continue;try{let q=JSON.parse(await $.readFile(X));A.set(Y,{packageName:q.name??$.relative(W,Y),packageRoot:Y,srcRoot:B})}catch{continue}}let Q=$.join(W,"package.json"),Z=$.join(W,"src");if(await $.exists(Q)&&await $.exists(Z))try{let X=JSON.parse(await $.readFile(Q));A.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:Z})}catch{}return[...A.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function XW($,W){let j=[],A=await V6($,W);for(let Q of A){let Z=q6({packageName:Q.packageName,srcRoot:Q.srcRoot});for(let X of Z.diagnostics)j.push({...X,packageName:Q.packageName,packageRoot:Q.packageRoot,srcRoot:Q.srcRoot})}return j}async function D1($,W){let j=W.workspaceRoot??process.cwd();return(await XW($.fs,j)).map((Q)=>({ruleId:Q.ruleId,severity:Q.severity==="warning"?"warning":"error",message:Q.message,category:"docs",file:Q.file,line:Q.line,column:Q.column,context:{packageName:Q.packageName,packageRoot:Q.packageRoot,...Q.context}}))}async function T1($,W,j){let A=[],Q=await G6($,W);if(A.push(Q),Q.status==="pass")A.push(await J6($,W,j));return A}async function G6($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");try{if(!await $.exists(j))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let Q=await $.readFile(j),Z=JSON.parse(Q),X=Z.aiProvider??"claude",Y=Z.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${X}, Model: ${Y}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function J6($,W,j){let A=$.join(W.workspaceRoot,".contractsrc.json");try{let Q=await $.readFile(A),X=JSON.parse(Q).aiProvider??"claude",B={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!B)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[B])return{category:"ai",name:"API Key",status:"pass",message:`${B} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${B} not set`,details:`Set ${B} in your environment to use AI features`,fix:j?{description:`Set ${B} environment variable`,apply:async()=>{let H=await j.input(`Enter your ${X} API key:`,{password:!0});if(!H)return{success:!1,message:"No API key provided"};let V=$.join(W.workspaceRoot,".env");try{let G="";if(await $.exists(V)){if(G=await $.readFile(V),G.includes(`${B}=`))return{success:!1,message:`${B} already in .env, update manually`};G+=`
|
|
1488
|
-
`}return
|
|
1489
|
-
`,await $.writeFile(
|
|
1774
|
+
`}function H8($){return $.replaceAll("\\","/").split("/").pop()??$}$$();import{scanAllSpecsFromSource as K8,scanSpecSource as _8}from"@contractspec/module.workspace";import z8 from"micromatch";var aW={};f(aW,{validators:()=>U8,urlSchema:()=>J8,isValidVersion:()=>O8,isValidIdentifier:()=>lW,isValidDotName:()=>pW,isTestFile:()=>zb,isLibraryDefinitionFile:()=>Lb,emailSchema:()=>V8});import _0 from"micromatch";function zb($,b){let n=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _0.isMatch($,n)}function Lb($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(_0.isMatch($,b))return!1;let n=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return _0.isMatch($,n)}import*as J$ from"zod";function lW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function pW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function O8($){return Number.isInteger($)&&$>0}var V8=J$.string().email(),J8=J$.string().url(),U8={specName:J$.string().refine(pW,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:J$.number().int().positive(),identifier:J$.string().refine(lW,{message:"Must be a valid TypeScript identifier"}),owner:J$.string().startsWith("@"),tag:J$.string().min(1)};function Rb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function L8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],n=[...Rb($?.conventions.models),...Rb($?.conventions.operations),...Rb($?.conventions.events),...Rb($?.conventions.presentations),...Rb($?.conventions.forms)];return[...new Set(b.flatMap((A)=>{let m=A==="**"?"":`${A}/`,y=q$.map((w)=>`${m}${w}`),W=n.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function R8($,b,n){if($.specType==="unknown")return!1;if(b.type&&!n.includes($.specType))return!1;return!0}function C8($,b){let n=$.filePath.localeCompare(b.filePath);if(n!==0)return n;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function c$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((n,A)=>n.localeCompare(A));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:L8(b.config)})}async function cn($,b={}){let n=await c$($.fs,b),A=b.type?Array.isArray(b.type)?b.type:[b.type]:[],m=[];for(let y of n){if(b.config?.excludePackages&&z8.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||zb(y,b.config)||Lb(y))continue;try{let W=await $.fs.readFile(y),w=K8(W,y),j=w.length>0?w:[_8(W,y)];for(let B of j)if(R8(B,b,A))m.push(B)}catch{}}return m.sort(C8)}function L$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function hn($){let b=JSON.parse($),n=new Map,A=0,m=0,y=0,W=0,w=0,j=0,B=0,S=0;for(let[Z,X]of Object.entries(b)){let Y=x8(Z,X);n.set(Z,Y),A+=Y.statements.total,m+=Y.statements.covered,y+=Y.branches.total,W+=Y.branches.covered,w+=Y.functions.total,j+=Y.functions.covered,B+=Y.lines.total,S+=Y.lines.covered}let Q={statements:{covered:m,total:A,pct:L$(m,A)},branches:{covered:W,total:y,pct:L$(W,y)},functions:{covered:j,total:w,pct:L$(j,w)},lines:{covered:S,total:B,pct:L$(S,B)}};return{files:n,total:Q}}function x8($,b){let n=Object.keys(b.statementMap).length,A=Object.values(b.s).filter((S)=>S>0).length,m=Object.keys(b.fnMap).length,y=Object.values(b.f).filter((S)=>S>0).length,W=0,w=0;for(let S of Object.values(b.b))W+=S.length,w+=S.filter((Q)=>Q>0).length;let j=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(j.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:A,total:n,pct:L$(A,n)},branches:{covered:w,total:W,pct:L$(w,W)},functions:{covered:y,total:m,pct:L$(y,m)},lines:{covered:B.size,total:j.size,pct:L$(B.size,j.size)}}}function z0($){switch($){case"istanbul":return{parse:hn};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function L0($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function R0($,b,n,A){let m=[];if(n.statements!==void 0&&A.statements.pct<n.statements)m.push({metric:"statements",required:n.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${n.statements}%`});if(n.branches!==void 0&&A.branches.pct<n.branches)m.push({metric:"branches",required:n.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${n.branches}%`});if(n.functions!==void 0&&A.functions.pct<n.functions)m.push({metric:"functions",required:n.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${n.functions}%`});if(n.lines!==void 0&&A.lines.pct<n.lines)m.push({metric:"lines",required:n.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${n.lines}%`});if(n.mutations!==void 0)m.push({metric:"mutations",required:n.mutations,actual:0,message:`Mutation coverage required (${n.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:n,actual:A,passed:m.length===0,failures:m}}async function C0($,b,n){let{fs:A,logger:m}=$,y=[],W=n.workspaceRoot?`${n.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await A.exists(X)){j=await A.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=L0(B??"coverage.json"),Z=z0(S).parse(j);for(let X of b){if(X.specType!=="test-spec"||!X.key||!X.version||!X.sourceBlock)continue;let Y=X.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!Y||!Y[1])continue;let G=Y[1],V={},O=G.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=G.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=G.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let U=G.match(/lines\s*:\s*(\d+)/);if(U&&U[1])V.lines=parseInt(U[1],10);if(Object.keys(V).length===0)continue;let H=R0(X.key,X.version,V,Z.total);for(let q of H.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:q.metric,required:q.required,actual:q.actual}})}return y}$$();import{addContractNode as I8,buildReverseEdges as E8,createContractGraph as M8,detectCycles as T8,findMissingDependencies as D8,parseImportedSpecNames as N8,toDot as F8}from"@contractspec/module.workspace";async function eW($,b={}){let{fs:n}=$,A=await c$(n,{config:b.config,pattern:b.pattern}),m=M8();for(let w of A){let j=await n.readFile(w),B=n.relative(".",w),S=n.basename(w).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=N8(j,w);I8(m,S,B,Q)}E8(m);let y=T8(m),W=D8(m);return{graph:m,total:m.size,cycles:y,missing:W}}function UO($,b){return $.get(b)}function KO($){return F8($)}function _O($){let b=Array.from($.values()),n=b.filter((W)=>W.dependencies.length>0),A=b.filter((W)=>W.dependencies.length===0),m=b.filter((W)=>W.dependents.length>0),y=b.filter((W)=>W.dependents.length===0);return{total:$.size,withDeps:n.length,withoutDeps:A.length,used:m.length,unused:y.length}}async function x0($,b){let n=[],A=await P($.fs),m=await eW($,{config:A,pattern:b.pattern});for(let y of m.cycles)n.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${y.join(" → ")}`,category:"deps",context:{cycle:y}});for(let y of m.missing)for(let W of y.missing)n.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${y.contract} requires ${W}`,category:"deps",context:{contract:y.contract,missing:W}});return n}import{analyzePackageDocBlocks as v8}from"@contractspec/module.workspace";var g8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function P8($,b){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:g8}),A=new Map;for(let W of n){let w=$.dirname(W),j=$.join(w,"src");if(!await $.exists(j))continue;try{let B=JSON.parse(await $.readFile(W));A.set(w,{packageName:B.name??$.relative(b,w),packageRoot:w,srcRoot:j})}catch{continue}}let m=$.join(b,"package.json"),y=$.join(b,"src");if(await $.exists(m)&&await $.exists(y))try{let W=JSON.parse(await $.readFile(m));A.set(b,{packageName:W.name??b,packageRoot:b,srcRoot:y})}catch{}return[...A.values()].sort((W,w)=>W.packageRoot.localeCompare(w.packageRoot))}async function dn($,b){let n=[],A=await P8($,b);for(let m of A){let y=v8({packageName:m.packageName,srcRoot:m.srcRoot});for(let W of y.diagnostics)n.push({...W,packageName:m.packageName,packageRoot:m.packageRoot,srcRoot:m.srcRoot})}return n}async function I0($,b){let n=b.workspaceRoot??process.cwd();return(await dn($.fs,n)).map((m)=>({ruleId:m.ruleId,severity:m.severity==="warning"?"warning":"error",message:m.message,category:"docs",file:m.file,line:m.line,column:m.column,context:{packageName:m.packageName,packageRoot:m.packageRoot,...m.context}}))}async function E0($,b,n){let A=[],m=await k8($,b);if(A.push(m),m.status==="pass")A.push(await r8($,b,n));return A}async function k8($,b){let n=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(n))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let m=await $.readFile(n),y=JSON.parse(m),W=y.aiProvider??"claude",w=y.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${W}, Model: ${w}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function r8($,b,n){let A=$.join(b.workspaceRoot,".contractsrc.json");try{let m=await $.readFile(A),W=JSON.parse(m).aiProvider??"claude",j={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[W];if(!j)return{category:"ai",name:"API Key",status:"pass",message:`${W} does not require an API key`};if(!!process.env[j])return{category:"ai",name:"API Key",status:"pass",message:`${j} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${j} not set`,details:`Set ${j} in your environment to use AI features`,fix:n?{description:`Set ${j} environment variable`,apply:async()=>{let S=await n.input(`Enter your ${W} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${j}=`))return{success:!1,message:`${j} already in .env, update manually`};Z+=`
|
|
1775
|
+
`}return Z+=`${j}=${S}
|
|
1776
|
+
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${j} to .env (restart required)`}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as f8}from"node:child_process";import{promisify as c8}from"node:util";var un=c8(f8);async function M0($,b){let n=[];return n.push(await h8(b)),n.push(await d8(b)),n.push(await u8($,b)),n}async function h8($){try{return await un("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4}),{category:"cli",name:"CLI Accessible",status:"pass",message:"ContractSpec CLI is accessible"}}catch{return{category:"cli",name:"CLI Accessible",status:"fail",message:"ContractSpec CLI is not accessible",details:'Could not run "bunx contractspec --version"',fix:{description:"Install ContractSpec CLI globally",apply:async()=>{try{return await un("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(b){return{success:!1,message:`Failed to install: ${b instanceof Error?b.message:String(b)}`}}}}}}}async function d8($){try{let{stdout:b}=await un("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${b.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function u8($,b){let n=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(n))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let w=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(w))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let m=await $.readFile(n),y=JSON.parse(m);if(y.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||y.devDependencies?.["@contractspec/app.cli-contractspec"]!==void 0)return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is installed as a project dependency"};return{category:"cli",name:"Local Installation",status:"warn",message:"CLI is not installed as a project dependency",details:"Consider adding @contractspec/app.cli-contractspec to devDependencies",fix:{description:"Add CLI as a dev dependency",apply:async()=>{try{return await un("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(w){return{success:!1,message:`Failed to install: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}$$();import{DEFAULT_CONTRACTSRC as on}from"@contractspec/lib.contracts-spec/workspace-config";import{join as o8,relative as i8}from"node:path";var t8="contractspec",l8="contractsrc.schema.json";function p8($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Cb($){return p8(i8($.configRoot,o8($.workspaceRoot,"node_modules",t8,l8)))}var xb=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],sW={"cli-config":"CLI Configuration (.contractsrc.json)","biome-config":"Biome Configuration (biome.jsonc + plugins)","vscode-settings":"VS Code Settings (.vscode/settings.json)","mcp-cursor":"MCP for Cursor (.cursor/mcp.json)","mcp-claude":"MCP for Claude Desktop","cursor-rules":"Cursor AI Rules (.cursor/rules/)","agents-md":"AI Agent Guide (AGENTS.md)","usage-md":"Usage Guide (USAGE.md)"},$w=["core","connect","builder-managed","builder-local","builder-hybrid"],bw={core:"Core workspace setup",connect:"Connect-enabled setup","builder-managed":"Builder setup (managed runtime)","builder-local":"Builder setup (local runtime)","builder-hybrid":"Builder setup (hybrid runtime)"},nw={core:"Generic ContractSpec workspace files and editor wiring.",connect:"Core workspace setup plus Connect config, artifact storage, and adapter defaults.","builder-managed":"Core workspace setup plus Builder config for managed runtime and API-based next steps.","builder-local":"Core workspace setup plus Builder config for local runtime registration and control-plane-backed next steps.","builder-hybrid":"Core workspace setup plus Builder config for hybrid runtime with API and local defaults."};var Ib={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function Eb($){if($?.builder?.enabled)switch($.builder.runtimeMode){case"local":return"builder-local";case"hybrid":return"builder-hybrid";default:return"builder-managed"}if($?.connect?.enabled)return"connect";return"core"}function R$($){return $.preset??"core"}function Aw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return xb}}function T0($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function mw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function rO($){return $.startsWith("builder-")}function fO($){return $==="connect"}function yw($){let b=R$($),n=a8($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset managed-mvp`,`contractspec builder status --workspace-id ${n}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function a8($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function Ww($){let b=R$($),n=[Ib.verificationCache];if(b==="connect")n.unshift(Ib.connect);return n}function Wb($){let b=$.isMonorepo&&$.scope==="package",n=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,A=e8($),m=s8($);return{$schema:Cb({configRoot:n,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...A?{connect:A}:{},...m?{builder:m}:{},...b&&$.packageName?{package:$.packageName}:{}}}function tn($){let b=R$($),n={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(T0(b))n["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return n}function Mb(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function ww(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function jw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1490
1777
|
|
|
1491
1778
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1492
1779
|
|
|
@@ -1519,6 +1806,14 @@ Contracts are located in:
|
|
|
1519
1806
|
3. **If no contract**: Create a new contract using \`contractspec create\`.
|
|
1520
1807
|
4. **After changes**: Validate with \`contractspec validate\`.
|
|
1521
1808
|
|
|
1809
|
+
## Adoption Engine
|
|
1810
|
+
|
|
1811
|
+
- Reuse existing workspace code before inventing a new local surface.
|
|
1812
|
+
- Prefer ContractSpec OSS packages before reaching for raw framework or vendor primitives.
|
|
1813
|
+
- Use \`contractspec connect adoption sync\` to mirror the local catalog.
|
|
1814
|
+
- Use \`contractspec connect adoption resolve --family <family> --stdin\` to resolve the recommended reuse target.
|
|
1815
|
+
- If Connect says \`rewrite\`, reuse the existing workspace or ContractSpec candidate instead of creating a duplicate.
|
|
1816
|
+
|
|
1522
1817
|
## Key Commands
|
|
1523
1818
|
|
|
1524
1819
|
- \`contractspec create\` - Scaffold new specs
|
|
@@ -1538,13 +1833,13 @@ defineCommand({
|
|
|
1538
1833
|
});
|
|
1539
1834
|
\`\`\`
|
|
1540
1835
|
|
|
1541
|
-
## Rules for ${
|
|
1836
|
+
## Rules for ${b}
|
|
1542
1837
|
|
|
1543
1838
|
- All API endpoints must have a corresponding operation contract.
|
|
1544
1839
|
- Events must be declared in contracts before being emitted.
|
|
1545
1840
|
- UI components should reference presentation contracts.
|
|
1546
1841
|
- Feature flags should be defined in feature modules.
|
|
1547
|
-
`}function
|
|
1842
|
+
`}function Bw($){let b=$.projectName??"this project",n=$.isMonorepo&&$.scope==="package",A=R$($),m=n&&$.packageName?`${$.packageName} package`:b,y="src/contracts",W=$.isMonorepo?n?`
|
|
1548
1843
|
## Monorepo Scope
|
|
1549
1844
|
|
|
1550
1845
|
This guide is scoped to the current package.
|
|
@@ -1558,7 +1853,7 @@ This guide is scoped to the workspace root.
|
|
|
1558
1853
|
- Prefer the nearest package guide when working inside a specific package.
|
|
1559
1854
|
`:"";return`# ContractSpec AI Guide
|
|
1560
1855
|
|
|
1561
|
-
Scope: \`${
|
|
1856
|
+
Scope: \`${m}\`
|
|
1562
1857
|
|
|
1563
1858
|
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1564
1859
|
|
|
@@ -1568,7 +1863,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
|
|
|
1568
1863
|
- Validate contracts after changes with \`contractspec validate\`.
|
|
1569
1864
|
- Regenerate derived artifacts before considering the work complete.
|
|
1570
1865
|
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1571
|
-
${
|
|
1866
|
+
${W}
|
|
1572
1867
|
## Contract Locations
|
|
1573
1868
|
|
|
1574
1869
|
- \`src/contracts/operations/\` - command and query specs
|
|
@@ -1595,20 +1890,139 @@ ${X}
|
|
|
1595
1890
|
- Keep changes spec-first, deterministic, and reviewable.
|
|
1596
1891
|
- Do not change generated outputs without updating their source contract.
|
|
1597
1892
|
- When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
|
|
1893
|
+
- Reuse existing workspace code before creating new files, packages, or dependencies.
|
|
1894
|
+
- Prefer ContractSpec OSS packages by family:
|
|
1895
|
+
- UI: local reusable UI -> \`@contractspec/lib.design-system\` -> platform ui-kit -> shadcn/web fallback
|
|
1896
|
+
- Contracts: existing local spec -> \`@contractspec/lib.contracts-spec\` / \`@contractspec/lib.schema\`
|
|
1897
|
+
- Integrations/runtime/shared libs: existing workspace surface -> ContractSpec OSS catalog -> reviewed fallback
|
|
1898
|
+
- Use \`contractspec connect adoption sync\` and \`contractspec connect adoption resolve --family <family>\` when the right reusable surface is unclear.
|
|
1598
1899
|
|
|
1599
1900
|
## Initialization Preset
|
|
1600
1901
|
|
|
1601
1902
|
- This workspace was initialized with the \`${A}\` setup preset.
|
|
1602
|
-
`}function
|
|
1603
|
-
`}async function v1($,W){let j=[];return j.push(await R6($,W)),j.push(await C6($,W)),j.push(await D6($,W)),j.push(await T6($,W)),j.push(await F6($,W)),j.push(await x6($,W)),j.push(await y6($,W)),j}async function R$($,W){if(W.packageRoot&&W.packageRoot!==W.workspaceRoot&&await $.exists($.join(W.packageRoot,".contractsrc.json")))return W.packageRoot;return W.workspaceRoot}async function R6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(await $.exists(j))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 Q=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(Q)),{success:!0,message:"Created .contractsrc.json"}}catch(Q){return{success:!1,message:`Failed to create: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function C6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j);return JSON.parse(Q),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Q){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Q instanceof Error?Q.message:String(Q),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function D6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=[];if(!Z.outputDir)X.push("outputDir");if(!Z.conventions)X.push("conventions");if(X.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: ${X.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let Y=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let B of X)if(Y[B]!==void 0)Z[B]=Y[B];return await $.writeFile(j,F(Z)),{success:!0,message:"Added missing fields"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function T6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:Z.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 Z.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,F(Z)),{success:!0,message:"Added versioning configuration"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function F6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.hooks){let B=Z.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(B).length} git hook(s) configured`}}let X=$.join(W.workspaceRoot,".husky");if(await $.exists(X))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 Z.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,F(Z)),{success:!0,message:"Added hooks configuration"}}catch(B){return{success:!1,message:`Failed: ${B instanceof Error?B.message:String(B)}`}}}}};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 x6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(Q==="connect"){let Y=[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((H)=>H!==null),B=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(Y.length===0&&!B)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: ${[...Y,...B?["connect.studio.endpoint"]:[]].join(", ")}`}}let Z=[],X=A.builder?.api?.controlPlaneTokenEnvVar;if((Q==="builder-managed"||Q==="builder-hybrid")&&!A.builder?.api?.baseUrl)Z.push("builder.api.baseUrl");if((Q==="builder-managed"||Q==="builder-hybrid")&&!X)Z.push("builder.api.controlPlaneTokenEnvVar");if((Q==="builder-managed"||Q==="builder-hybrid")&&X&&!process.env[X])Z.push(`env:${X}`);if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)Z.push("builder.localRuntime.runtimeId");if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)Z.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:Z.length===0?"pass":"warn",message:Z.length===0?`Builder preset inferred (${Q}) and required config is present`:`Builder preset inferred (${Q}) but setup is missing ${Z.join(", ")}`}}async function y6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q!=="builder-managed"&&Q!=="builder-hybrid")return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder managed/hybrid preset is not enabled"};let Z=$.join(j,".vscode","settings.json"),X=A.builder?.api?.baseUrl;if(!X)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let Y=await $.readFile(Z).catch(()=>""),B=Y?r(Y):void 0;if(B?.["contractspec.api.baseUrl"]===X)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 H=$.join(j,".vscode");if(!await $.exists(H))await $.mkdir(H);let V={...B??{},...BW({workspaceRoot:W.workspaceRoot,packageRoot:W.packageRoot,isMonorepo:W.isMonorepo,packageName:W.packageName,interactive:!1,preset:Q,targets:[],builderApiBaseUrl:X})};return await $.writeFile(Z,F(V)),{success:!0,message:"Updated VS Code settings mirror"}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}}}import{exec as v6}from"node:child_process";import{promisify as m6}from"node:util";var C$=m6(v6);async function m1($,W){let j=[];return j.push(await P6(W)),j.push(await k6(W)),j.push(await h6($,W)),j.push(await g6($,W)),j.push(await f6($,W)),j}async function P6($){try{let{stdout:W}=await C$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${W.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 k6($){try{let{stdout:W}=await C$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${W.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 h6($,W){let j=[{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:Q,name:Z}of j){let X=$.join(W.workspaceRoot,Q);if(await $.exists(X)){A=Z;break}}if(!A){let Q=$.join(W.workspaceRoot,".."),Z=$.join(W.workspaceRoot,"../.."),X=[Q,Z];for(let Y of X){for(let{file:B,name:q}of j){let H=$.join(Y,B);if(await $.exists(H)){A=q;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 C$(`${A} --version`,{cwd:W.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 g6($,W){let j=$.join(W.workspaceRoot,"node_modules");if(await $.exists(j))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 C$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function f6($,W){let j=$.join(W.workspaceRoot,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A),Z={...Q.dependencies,...Q.devDependencies};if("@contractspec/lib.contracts-spec"in Z)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${Z["@contractspec/lib.contracts-spec"]})`};if(W.isMonorepo&&W.packageRoot===W.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 C$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function P1($,W){let j=await XW($,W.workspaceRoot);if(j.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return j.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(W.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as u6,isFeatureFile as d6,scanAllSpecsFromSource as n6,scanExampleSource as c6,scanFeatureSource as r6}from"@contractspec/module.workspace";function l6(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function VW($,W={}){let{fs:j,logger:A}=$,Q=l6(),Z=W.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let X=await j.glob({pattern:Z});for(let B of X){if(B.includes("node_modules")||B.includes("/dist/"))continue;try{let q=await j.readFile(B);if(d6(B)){let H=r6(q,B);Q.features.set(H.key,H);continue}if(u6(B)){let H=c6(q,B);Q.examples.set(H.key,H);continue}if(B.includes(".app-config.")||B.includes(".blueprint.")){let H=n6(q,B);for(let V of H)if(V.specType==="app-config"&&V.key)Q.appConfigs.set(V.key,V)}}catch{}}try{let B=await j.glob({pattern:"**/.contractsrc.json"});for(let q of B){if(q.includes("node_modules"))continue;try{let H=await j.readFile(q),V=JSON.parse(H);Q.workspaceConfigs.set(q,{file:q,config:V,valid:!0,errors:[]})}catch(H){Q.workspaceConfigs.set(q,{file:q,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Q.features.size,examples:Q.examples.size,appConfigs:Q.appConfigs.size,workspaceConfigs:Q.workspaceConfigs.size,total:Q.features.size+Q.examples.size+Q.appConfigs.size+Q.workspaceConfigs.size};return A.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Q,stats:Y}}function mb($){let W=[];for(let[j,A]of $.features)W.push({key:j,file:A.filePath,type:"feature"});for(let[j,A]of $.examples)W.push({key:j,version:A.version,file:A.filePath,type:"example"});for(let[j,A]of $.appConfigs)W.push({key:j,version:A.version,file:A.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function GW($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function k1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function JW($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let A=await $.readFile(j),Q=JSON.parse(A);return{version:typeof Q.version==="number"&&Number.isFinite(Q.version)?Q.version:1,criticalPackages:k1(Q.criticalPackages).map(GW),criticalFeatureKeys:k1(Q.criticalFeatureKeys),smokePackages:k1(Q.smokePackages)}}catch{return}}function T8($,W){let j=GW($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function F8($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function d$($){return GW(`${GW($)}/config/stability-policy.json`)}async function h1($,W){let j=[],A=await JW($,W.workspaceRoot),Q=await VW({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(o6(Q.stats.features)),j.push(i6(Q.stats.examples)),j.push(p6(Q.inventory.features,A,W)),j.push(t6(Q.inventory.examples)),j.push(a6(Q.inventory.workspaceConfigs)),j}function o6($){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 i6($){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 p6($,W,j){let A=[],Q=[];for(let[Z,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(F8(Z,W))Q.push(Z);else A.push(Z);if(Q.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:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Q.length>0?"fail":"warn",message:Q.length>0?`${Q.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:Q.length>0?`Critical features: ${Q.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:Q,missingFeatures:A}}}function t6($){let W=[];for(let[j,A]of $)if(!A.entrypoints.packageName)W.push(j);if(W.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:`${W.length} example(s) missing packageName`,details:`Examples: ${W.join(", ")}`}}function a6($){let W=[];for(let[,j]of $)if(!j.valid)W.push(j.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(W.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:`${W.length} workspace config(s) invalid`,details:`Files: ${W.join(", ")}`}}async function g1($,W){let j=[];return j.push(await s6($,W)),j.push(await e6($,W)),j.push(await $7($,W)),j}async function s6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(await $.exists(j))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 Q=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Q))await $.mkdir(Q);let Z=q0();return await $.writeFile(j,F(Z)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function e6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(!await $.exists(j))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.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 Y=q0(),B=p(Z,Y);return await $.writeFile(j,F(B)),{success:!0,message:"Registered MCP server"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function $7($,W){let j=qW();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Q=await $.readFile(j);if(JSON.parse(Q).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 W7=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],x8=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function j7($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,A])=>{if(typeof A==="string")W[j]=A;return W},{})}function A7($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function Q7($,W,j){let A=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:x8}),Q=[];for(let Z of A){let X=$.dirname(Z),Y=$.relative(W,X);try{let B=JSON.parse(await $.readFile(Z)),q=j7(B.scripts),H=await $.glob({patterns:W7,cwd:X,ignore:x8});Q.push({packageName:B.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof q.build==="string",hasTypecheckScript:typeof q.typecheck==="string",hasLintScript:typeof q.lint==="string"||typeof q["lint:check"]==="string",hasTestScript:typeof q.test==="string",usesPassWithNoTests:A7(q),testFileCount:H.length,tier:T8(Y,j)})}catch{continue}}return Q}function Z7($){let W=[];if(!$.hasBuildScript)W.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)W.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)W.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)W.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)W.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)W.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return W}function X7($){let W=[];if($.testFileCount>0&&!$.hasTestScript)W.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)W.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return W}async function y8($,W,j){let A=await Q7($,W,j),Q=[];for(let X of A){if(X.tier==="critical")Q.push(...Z7(X));Q.push(...X7(X))}let Z=A.filter((X)=>X.tier==="critical").map((X)=>({packageName:X.packageName,packagePath:X.packagePath,hasBuildScript:X.hasBuildScript,hasTypecheckScript:X.hasTypecheckScript,hasLintScript:X.hasLintScript,hasTestScript:X.hasTestScript,usesPassWithNoTests:X.usesPassWithNoTests,testFileCount:X.testFileCount}));return{findings:Q,criticalPackages:Z}}function m8($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function v8($,W,j,A){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let Q=W.filter((Z)=>{return Z.tier==="critical"||j.has(Z.code)});return{category:"workspace",name:$,status:Q.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:m8(W),context:{findings:W}}}async function P8($,W){let j=await JW($,W.workspaceRoot);if(!j)return[];let A=await y8($,W.workspaceRoot,j),Q=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"]),Z=A.findings.filter((B)=>Q.has(B.code)),X=A.findings.filter((B)=>B.code==="tests-without-test-script"),Y=A.findings.filter((B)=>B.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:Z.length>0?"fail":"pass",message:Z.length>0?`${Z.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:Z.length>0?m8(Z):W.verbose?`Policy: ${d$(W.workspaceRoot)}`:void 0,context:{policyPath:d$(W.workspaceRoot),criticalPackages:A.criticalPackages,findings:Z}},v8("Package Test Scripts",X,new Set,"All tested packages expose a test script"),v8("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var Y7=["src/contracts","contracts","src/specs","specs"];async function f1($,W){let j=[];return j.push(B7(W)),j.push(await q7($,W)),j.push(await H7($,W)),j.push(await V7($,W)),j.push(await J7($,W)),j.push(...await P8($,W)),j}function B7($){if($.isMonorepo){let W=$.packageName?` in package "${$.packageName}"`:"",j=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${W}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${j}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function q7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let A of j){let Q=$.join(A,"package.json");if(await $.exists(Q))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.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 H7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],A=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of Y7){let B=$.join(X,Y);if(await $.exists(B)){let q=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${q} level`:void 0}}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let Q=W.isMonorepo?"src/contracts":"src/contracts",Z=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Q}/${Z} to organize your specs`,fix:{description:`Create ${Q}/ directory${Z}`,apply:async()=>{try{let X=$.join(A,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Q}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function V7($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=W.isMonorepo?W.packageRoot:W.workspaceRoot,Q=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:A});if(Q.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Q.length} contract file(s)${X}`,details:W.verbose?Q.slice(0,5).join(", "):void 0}}if(W.isMonorepo&&W.packageRoot===W.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:W.isMonorepo?`No contract files found in package "${W.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 G7($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let A=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:W.packageRoot,level:"package"}}let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{path:j,root:W.workspaceRoot,level:"workspace"};return null}async function J7($,W){try{let j=await G7($,W);if(!j)return{category:"workspace",name:"Output Directory",status:"skip",message:W.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(j.path),Q=JSON.parse(A),Z=Q.outputDir??"./src",X=$.join(j.root,Z),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${Z}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let q=Z==="./src"||Z==="src",H=Array.isArray(Q.packages)&&Q.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&q&&(H||j.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:W.verbose?`Resolved default output to packages via ${j.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${Z}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${Z} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${Z}`}}catch(V){return{success:!1,message:`Failed: ${V instanceof Error?V.message:String(V)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var k8=["cli","config","mcp","deps","docs","workspace","ai","layers"],h8={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var b7={checks:{runCliChecks:F1,runConfigChecks:v1,runMcpChecks:g1,runDepsChecks:m1,runDocChecks:P1,runWorkspaceChecks:f1,runAiChecks:T1,runLayerChecks:h1},workspace:{findWorkspaceRoot:D,findPackageRoot:f,isMonorepo:e$,getPackageName:I$}},w7={confirm:async()=>!1,input:async()=>""};async function g8($,W,j=w7,A=b7){let{fs:Q,logger:Z}=$,X=W.categories??k8,{checks:Y,workspace:B}=A,q=B.findWorkspaceRoot(W.workspaceRoot),H=B.findPackageRoot(W.workspaceRoot),V=B.isMonorepo(q),G=V?B.getPackageName(H):void 0,J={workspaceRoot:q,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let U=G?` (package: ${G})`:"";Z.info(`Detected monorepo${U}`)}let b=[];for(let U of X){if(W.skipAi&&U==="ai")continue;Z.info(`Checking ${h8[U]}...`);let O=await K7(U,Q,J,j,Y);for(let K of O){if(K.fix&&(K.status==="fail"||K.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${K.name}"? ${K.fix.description}`)){Z.info(`Applying fix: ${K.fix.description}`);let I=await K.fix.apply();if(I.success)Z.info(`✓ ${I.message}`),K.status="pass",K.message=`Fixed: ${I.message}`,K.fix=void 0;else Z.warn(`✗ ${I.message}`)}}b.push(K)}}let w=b.filter((U)=>U.status==="pass").length,L=b.filter((U)=>U.status==="warn").length,z=b.filter((U)=>U.status==="fail").length,S=b.filter((U)=>U.status==="skip").length;return{checks:b,passed:w,warnings:L,failures:z,skipped:S,healthy:z===0}}async function K7($,W,j,A,Q){switch($){case"cli":return Q.runCliChecks(W,j);case"config":return Q.runConfigChecks(W,j);case"mcp":return Q.runMcpChecks(W,j);case"deps":return Q.runDepsChecks(W,j);case"docs":return Q.runDocChecks(W,j);case"workspace":return Q.runWorkspaceChecks(W,j);case"ai":return Q.runAiChecks(W,j,A);case"layers":return Q.runLayerChecks(W,j);default:return[]}}function Hw($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("✓ All checks passed!");else W.push("✗ Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
`).length},X,Y=new RegExp(V0.contractHandler);while((X=Y.exec($))!==null)if(X[1])Q(X[1],"handler",Z(X.index));let B=new RegExp(V0.typeofSpec);while((X=B.exec($))!==null)if(X[1])Q(X[1],"typeof",Z(X.index));let q=new RegExp(V0.namedImport);while((X=q.exec($))!==null){let J=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(J)for(let b of J)Q(b,"import",Z(X.index))}let H=new RegExp(V0.defaultImport);while((X=H.exec($))!==null)if(X[1])Q(X[1],"import",Z(X.index));let V=new RegExp(V0.specAssignment);while((X=V.exec($))!==null)if(X[1])Q(X[1],"unknown",Z(X.index));return j}var l8=["**/*.ts(x)"];async function _W($,W,j={}){let{fs:A}=W,Q=j.includePatterns??l8,Z=j.excludePatterns??[...new Set([...S$,...Y$])],X=[];for(let Y of Q){let B=await A.glob({pattern:Y,ignore:Z});for(let q of B)try{let H=await A.readFile(q),G=r8(H,q).filter((J)=>J.specKey===$);X.push(...G)}catch{}}return X}async function ow($,W={}){let{fs:j}=$,A=W.includePatterns??l8,Q=W.excludePatterns??[...new Set([...S$,...Y$])],Z=new Map;for(let X of A){let Y=await j.glob({pattern:X,ignore:Q});for(let B of Y)try{let q=await j.readFile(B),H=r8(q,B);for(let V of H){let G=Z.get(V.specKey)??[];G.push(V),Z.set(V.specKey,G)}}catch{}}return Z}function g7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o8($,W,j){let A=g7(W),Q=[];if($==="operation")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")Q.push({path:`${j}/components/${A}.tsx`,type:"component"}),Q.push({path:`${j}/components/${A}.test.tsx`,type:"test"});if($==="form")Q.push({path:`${j}/forms/${A}.form.tsx`,type:"form"}),Q.push({path:`${j}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});return Q}import{Node as c,Project as f7,SyntaxKind as u7}from"ts-morph";function i8($){let W=[],A=new f7({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Q=(B)=>{if(!c.isObjectLiteralExpression(B))return;let q=B.getProperty("implementations");if(q&&c.isPropertyAssignment(q)){let H=q.getInitializer();if(H&&c.isArrayLiteralExpression(H)){for(let V of H.getElements())if(c.isObjectLiteralExpression(V)){let G,J,b,w=V.getProperty("path");if(w&&c.isPropertyAssignment(w)){let S=w.getInitializer();if(c.isStringLiteral(S))G=S.getLiteralText()}let L=V.getProperty("type");if(L&&c.isPropertyAssignment(L)){let S=L.getInitializer();if(c.isStringLiteral(S))J=S.getLiteralText()}let z=V.getProperty("description");if(z&&c.isPropertyAssignment(z)){let S=z.getInitializer();if(c.isStringLiteral(S))b=S.getLiteralText()}if(G&&J)W.push({path:G,type:J,description:b})}}}},Z=A.getDescendantsOfKind(u7.CallExpression);for(let B of Z){let q=B.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(q)){let H=B.getArguments();if(H.length>0&&c.isObjectLiteralExpression(H[0]))return Q(H[0]),W}}let X=A.getVariableStatements();for(let B of X)if(B.isExported())for(let q of B.getDeclarations()){let H=q.getInitializer();if(H&&c.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Q(H),W}}let Y=A.getExportAssignment((B)=>!B.isExportEquals());if(Y){let B=Y.getExpression();if(c.isObjectLiteralExpression(B))Q(B);else if(c.isAsExpression(B)&&c.isObjectLiteralExpression(B.getExpression()))Q(B.getExpression())}return W}function p8($){if($.length===0)return"missing";let W=$.filter((Q)=>Q.exists),j=$.filter((Q)=>Q.type!=="test");if(W.filter((Q)=>Q.type!=="test").length===0)return"missing";if($.every((Q)=>Q.exists))return"implemented";return"partial"}function sw($){let W=$.filter((Q)=>Q.status==="implemented").length,j=$.filter((Q)=>Q.status==="partial").length,A=$.filter((Q)=>Q.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:A,coverage:$.length>0?Math.round(W/$.length*100):100}}var c7={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function t8($){return d7("sha256").update($).digest("hex")}async function r7($,W,j,A={},Q){let Z={...c7,...A},X=Z.computeHashes?t8($.sourceBlock||""):void 0,Y=$.key??n7.basename($.filePath).replace(/\.[jt]s$/,""),B=$.version??"1.0.0",{fs:q}=W,H=[],V=new Set,G=async(b,w,L,z)=>{if(V.has(b))return;V.add(b);let S=await q.exists(b),U=void 0,O=void 0;if(S&&Z.computeHashes)try{U=await q.readFile(b),O=t8(U)}catch{}H.push({path:b,type:w,source:L,exists:S,implementationSourceContent:U,implementationSourceHash:O,description:z})};if(Z.includeExplicit&&$.sourceBlock){if(Q)Q.suffixText="Discover explicit implementations";let b=i8($.sourceBlock);for(let w of b)await G(w.path,w.type,"explicit",w.description)}if(Z.includeDiscovered){if(Q)Q.suffixText="Discover implementations";let b=await _W(Y,W,Z);for(let w of b){if(w.filePath===$.filePath)continue;await G(w.filePath,w.inferredType,"discovered")}}if(Z.includeConvention){if(Q)Q.suffixText="Discover implementations based on conventions";let b=Z.outputDir??j.outputDir??"./src",w=o8($.specType,Y,b);for(let{path:L,type:z}of w)await G(L,z,"convention")}if(Q)Q.suffixText="Determine implementation status";let J=p8(H);return{specKey:Y,specVersion:B,specPath:$.filePath,specType:$.specType,implementations:H,status:J,specHash:X}}async function a8($,W,j,A={},Q){let Z=[];for(let X of $){if(Q)Q.text=`Resolving implementation... (${Z.length}/${$.length})`;try{let Y=await r7(X,W,j,A,Q);Z.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return Z}async function o1($,W,j){let{fs:A}=$,Q=[],Z=await m(A),X=j.implementation??{},Y=W.filter((q)=>q.specType==="operation"),B=await a8(Y,{fs:A},Z,{computeHashes:X.useCache??!0});for(let q of B){if(X.requireImplemented&&q.status==="missing")Q.push({ruleId:"impl-missing",severity:"error",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});else if(q.status==="missing")Q.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});if(!X.allowPartial&&q.status==="partial"){let V=q.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Q.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${q.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status,missingFiles:V}})}let H=q.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Q.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${q.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,missingTests:H.map((V)=>V.path)}})}return Q}import{isFeatureFile as i7,scanAllSpecsFromSource as p7,scanFeatureSource as t7}from"@contractspec/module.workspace";function l7($,W){return`${$}.v${W}`}function i1($,W,j,A,Q,Z={}){let{treatMissingAsError:X=!0}=Z;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],B=[],q=[];for(let H of A){let V=l7(H.key,H.version);if(Q.has(V))Y.push(H);else if(B.push(H),X)q.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:B.length===0,foundTests:Y,missingTests:B,errors:q,specFile:$}}function s8($,W){return`${$}.v${W}`}function e8($,W){let j=new Map,A=new Map,Q=[],Z=[];for(let X of $){if(!X.key||!X.version)continue;let Y=s8(X.key,X.version);if(!X.testTarget){Z.push(Y);continue}let{type:B,key:q,version:H}=X.testTarget,V=H??X.version,G=s8(q,V),J=o7(W,B);if(!J||!J.has(G)){Q.push(Y);continue}if(A.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:A,orphanedTests:Q,testsWithoutTarget:Z}}function o7($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function t($,W){return`${$}.v${W}`}function a7(){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 p1($,W){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}[W]}async function zW($,W={}){let{fs:j,logger:A}=$;A.info("Starting integrity analysis...",{options:W});let Q=await N$(j,{config:W.config,cwd:W.cwd,pattern:W.pattern}),Z=a7(),X=[],Y=[];for(let K of Q){if((await j.stat(K)).isDirectory)continue;let I=await j.readFile(K);if(i7(K)){let M=t7(I,K);X.push(M)}else{let M=p7(I,K);for(let E of M)if(E.specType!=="unknown"&&E.specType!=="feature"){let C=p1(Z,E.specType);if(C&&E.key&&E.version!==void 0){let R=t(E.key,E.version);C.set(R,{key:E.key,version:E.version,file:E.filePath,type:E.specType,stability:E.stability,testTarget:E.testTarget,testCoverage:E.testCoverage})}}}}let B=W.featureKey?X.filter((K)=>K.key===W.featureKey):X,q=new Set;for(let K of B){for(let _ of K.operations){let I=t(_.key,_.version);if(q.add(`operation:${I}`),!Z.operations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_})}for(let _ of K.events){let I=t(_.key,_.version);if(q.add(`event:${I}`),!Z.events.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"event",ref:_})}for(let _ of K.presentations){let I=t(_.key,_.version);if(q.add(`presentation:${I}`),!Z.presentations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_})}for(let _ of K.experiments){let I=t(_.key,_.version);if(q.add(`experiment:${I}`),!Z.experiments.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"experiment",ref:_})}for(let _ of K.capabilities.provides){let I=t(_.key,_.version);if(q.add(`capability:${I}`),!Z.capabilities.has(I))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"capability",ref:_})}for(let _ of K.capabilities.requires){let I=t(_.key,_.version);q.add(`capability:${I}`)}for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=t(_.pres.key,_.pres.version);if(!Z.operations.has(I))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${_.op.key}.v${_.op.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op});if(!Z.presentations.has(M))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${_.pres.key}.v${_.pres.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_.pres})}if(K.presentationsTargets)for(let _ of K.presentationsTargets){let I=t(_.key,_.version);if(!Z.presentations.has(I))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:{key:_.key,version:_.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let K of V){let _=p1(Z,K);if(!_)continue;for(let[I,M]of _)if(!q.has(`${K}:${I}`))H.push(M),Y.push({severity:"warning",type:"orphaned",message:`${K} ${M.key}.v${M.version} is not linked to any feature`,file:M.file,specKey:M.key,specType:M.type})}let G=[];for(let[,K]of Z.testSpecs)G.push({filePath:K.file,specType:"test-spec",key:K.key,version:K.version,testTarget:K.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let J=e8(G,Z);for(let K of B)for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=J.targetToTests.get(I),E=!1,C=!1;if(M)for(let R of M){let v=Z.testSpecs.get(R);if(v?.testCoverage){if(v.testCoverage.hasSuccess)E=!0;if(v.testCoverage.hasError)C=!0}}if(!M||!E||!C){let R=[];if(!E)R.push("success scenario");if(!C)R.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${_.op.key}.v${_.op.version} linked to presentation requires tests covering: ${R.join(", ")}`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op})}}let b={},w=0;for(let K of V){let _=p1(Z,K);if(!_)continue;let I=_.size,M=0,E=0,C=W.requireTestsFor?.includes(K);for(let[R,v]of _){if(q.has(`${K}:${R}`))M++;if(C){let x=t(v.key,v.version),L$=J.targetToTests.has(x),v0=`${v.key}.test`,zA=Z.testSpecs.has(t(v0,v.version));if(!L$&&!zA)E++,w++,Y.push({severity:"warning",type:"missing-test",message:`${K} ${v.key}.v${v.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:v.file,specKey:v.key,specType:v.type})}}b[K]={total:I,covered:M,orphaned:I-M,missingTest:C?E:0}}let L=Object.values(b).reduce((K,_)=>K+_.total,0),z=Object.values(b).reduce((K,_)=>K+_.covered,0),S={total:L,linkedToFeature:z,orphaned:L-z,missingTest:w,byType:b},O=!Y.some((K)=>K.severity==="error");return A.info("Integrity analysis complete",{features:X.length,totalSpecs:L,orphaned:H.length,issues:Y.length,healthy:O}),{inventory:Z,features:B,coverage:S,issues:Y,orphanedSpecs:H,healthy:O}}function UK($){let W=[];for(let j of Object.values($))for(let A of j.values())W.push(A);return W}function LK($,W){return $.filter((j)=>j.type===W)}function OK($,W){return $.filter((j)=>j.severity===W)}i();async function t1($,W){let j=[],A=await m($.fs),Q=await zW($,{config:A,pattern:W.pattern,all:!0});for(let Z of Q.issues)j.push({ruleId:`integrity-${Z.type}`,severity:Z.severity==="error"?"error":"warning",message:Z.message,category:"integrity",file:Z.file,context:{specKey:Z.specKey,specType:Z.specType,featureKey:Z.featureKey,ref:Z.ref}});return j}async function a1($,W){let j=[],A=await VW($,{});for(let[Q,Z]of A.inventory.features){if(!Z.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Q}' missing 'owners' field`,category:"layers",file:Z.filePath,context:{key:Q}});if(Z.operations.length===0&&Z.events.length===0&&Z.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Q}' has no operations, events, or presentations`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let[Q,Z]of A.inventory.examples){if(!Z.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Q}' missing 'packageName' in entrypoints`,category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.surfaces.templates&&!Z.surfaces.sandbox.enabled&&!Z.surfaces.studio.enabled&&!Z.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Q}' has no enabled surfaces`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let Q of A.inventory.workspaceConfigs.values())if(!Q.valid)for(let Z of Q.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${Z}`,category:"layers",file:Q.file});return j}i();import{ContractsrcSchema as e7,DEFAULT_CONTRACTSRC as UW}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as s7}from"@contractspec/module.workspace";async function $$($,W={}){let{fs:j,scan:A=s7}=$,Q=await N$(j,W),Z=[],X=Array.isArray(W.type)?W.type:[W.type];for(let Y of Q){if(j0(Y,W.config))continue;if(A0(Y))continue;try{let B=await j.readFile(Y),q=A(B,Y);if(q.specType==="unknown")continue;if(W.type&&!X.includes(q.specType))continue;Z.push(q)}catch{}}return Z}function FK($){let W=new Map;for(let j of $){let A=W.get(j.specType)??[];A.push(j),W.set(j.specType,A)}return W}var $X=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,WX=/@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?)?['"]/,jX=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,AX=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,QX=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,ZX=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,XX=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function LW($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function YX($,W){let j=$.replaceAll("\\","/"),A=new Set(["contracts","features",...LW(W?.conventions?.operations),...LW(W?.conventions?.events),...LW(W?.conventions?.presentations),...LW(W?.conventions?.forms)]);return j.split("/").some((Q)=>A.has(Q))}function BX($,W,j){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||QX.test(A)||AX.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(W.has(A))return!1;if(YX(A,j))return!1;return $X.test(A)}function $4($){return $.replaceAll("\\","/").match(ZX)?.[1]??null}function qX($){let W=$.split(`
|
|
1610
|
-
`).map((j)=>j.trim()).filter((j)=>j.length>0&&!j.startsWith("//")&&!j.startsWith("/*")&&!j.startsWith("*")&&!j.startsWith("*/"));return W.length>0&&W.every((j)=>j.startsWith("import ")||j.startsWith("export *")||j.startsWith("export {")||j.startsWith("export type {")||j==="'use client';"||j==='"use client";'||j==="'use server';"||j==='"use server";')}function HX($){if(!$)return UW;let W=e7.safeParse($),j=W.success?W.data:{};return{...UW,...j,conventions:{...UW.conventions,...j.conventions??{}},ci:{...UW.ci,...j.ci??{}}}}async function s1($,W){let{fs:j,logger:A}=$,Q=[],Z=W.config?HX(W.config):await m(j),X=await $$({fs:j},{config:Z}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),B=new Set(X.map((H)=>$4(H.filePath)).filter((H)=>Boolean(H))),q=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of q){if(!BX(H,Y,Z))continue;try{let V=await j.readFile(H);if(qX(V))continue;let G=$4(H);if(!(G!==null&&XX.test(G)&&B.has(G))&&!jX.test(V))continue;if(WX.test(V))continue;Q.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:H})}catch(V){A.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Q}import{validateSpecStructure as VX}from"@contractspec/module.workspace";async function e1($){let W=[];for(let j of $){let A=VX(j);for(let Q of A.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Q,category:"structure",file:j.filePath});for(let Q of A.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Q,category:"structure",file:j.filePath})}return W}async function $j($){let W=[],j=new Map,A=new Map;for(let Q of $){if(!Q.key||!Q.version)continue;if(Q.specType==="test-spec"){let Z=`${Q.key}.v${Q.version}`;j.set(Z,{key:Q.key,version:Q.version,file:Q.filePath,type:"test-spec"})}if(Q.testRefs&&Q.testRefs.length>0){if(!A.has(Q.filePath))A.set(Q.filePath,[]);A.get(Q.filePath)?.push({key:Q.key,version:Q.version,testRefs:Q.testRefs})}}for(let[Q,Z]of A)for(let X of Z){if(!X.testRefs)continue;let Y=i1(Q,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let B of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:B,category:"test-refs",file:Q,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}i();async function Wj($,W){let{fs:j}=$,A=[],Q=await m(j);for(let Z of W){if(Z.specType!=="operation")continue;let X=await KW(Z,{fs:j},Q,{checkTests:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:Z.filePath})}return A}function l($,W,j){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"},Q=W.filter((Y)=>Y.severity==="error").length,Z=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:A[$],errors:Q,warnings:Z,notes:X,passed:Q===0,durationMs:j}}async function W4($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),A=j.match(/^ref: (.+)$/m);if(A){let Z=A[1]?.replace("refs/heads/",""),X=`.git/${A[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:Z};return{branch:Z}}return{commitSha:j.trim()}}catch{return{}}}function j4($){let W=$.config?.ci?.checks,j=W&&W.length>0?[...W]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)j.push("handlers");if($.checkTests)j.push("tests");if($.implementation)j.push("implementation");if($.checkDrift)j.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return j.filter((A)=>!$.skip?.includes(A));return j}async function q_($,W={}){let j=Date.now(),{fs:A,logger:Q}=$,Z=[],X=[],Y=j4(W);Q.info("Starting CI checks...",{checks:Y});let B=await m(A),q=await QW($,{config:B,pattern:W.pattern});if(Y.includes("structure")){let L=Date.now(),z=await e1(q);Z.push(...z),X.push(l("structure",z,Date.now()-L))}if(Y.includes("integrity")){let L=Date.now(),z=await t1($,W);Z.push(...z),X.push(l("integrity",z,Date.now()-L))}if(Y.includes("deps")){let L=Date.now(),z=await C1($,W);Z.push(...z),X.push(l("deps",z,Date.now()-L))}if(Y.includes("doctor")){let L=Date.now(),z=await u1($,W);Z.push(...z),X.push(l("doctor",z,Date.now()-L))}if(Y.includes("docs")){let L=Date.now(),z=await D1($,W);Z.push(...z),X.push(l("docs",z,Date.now()-L))}if(Y.includes("policy")){let L=Date.now(),z=await s1($,W);Z.push(...z),X.push(l("policy",z,Date.now()-L))}if(Y.includes("handlers")||W.checkHandlers){let L=Date.now(),z=await l1($,q);Z.push(...z),X.push(l("handlers",z,Date.now()-L))}if(Y.includes("tests")||W.checkTests){let L=Date.now(),z=await Wj($,q);Z.push(...z),X.push(l("tests",z,Date.now()-L))}if(Y.includes("test-refs")){let L=Date.now(),z=await $j(q);Z.push(...z),X.push(l("test-refs",z,Date.now()-L))}if(Y.includes("coverage")){let L=Date.now(),z=await R1($,q,W);Z.push(...z),X.push(l("coverage",z,Date.now()-L))}if(Y.includes("implementation")){let L=Date.now(),z=await o1($,q,W);Z.push(...z),X.push(l("implementation",z,Date.now()-L))}if(Y.includes("layers")){let L=Date.now(),z=await a1($,W);Z.push(...z),X.push(l("layers",z,Date.now()-L))}if(Y.includes("drift")){let L=Date.now(),z=await r1($,W);Z.push(...z),X.push(l("drift",z,Date.now()-L))}let H=Z.filter((L)=>L.severity==="error").length,V=Z.filter((L)=>L.severity==="warning").length,G=Z.filter((L)=>L.severity==="note").length,J=W.failOnWarnings?H===0&&V===0:H===0,b=await W4(A),w={success:J,totalErrors:H,totalWarnings:V,totalNotes:G,issues:Z,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...b};return Q.info("CI checks complete",{success:J,errors:H,warnings:V,durationMs:w.durationMs}),w}var V_=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],G_={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 __($,W={}){let{fs:j,logger:A}=$,Q=(W.outputDir??"./src").replace(/\\/g,"/"),Z=["generated/**","dist/**",".turbo/**"],X=[`${Q}/handlers/**/*.handler.ts`,`${Q}/handlers/**/*.handler.test.ts`,`${Q}/components/**/*.tsx`,`${Q}/components/**/*.test.tsx`,`${Q}/forms/**/*.form.tsx`,`${Q}/forms/**/*.form.test.tsx`,`${Q}/**/*.runner.ts`,`${Q}/**/*.renderer.tsx`],Y=W.generatedOnly?[...Z,...X]:[...Z,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],B=await j.glob({patterns:Y,ignore:["node_modules/**"]}),q=[],H=[];for(let V of B)try{let G=await j.stat(V),J=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&J<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)A.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),A.info("clean.removed",{path:V,size:G.size});q.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:q,skipped:H}}i();var C4={};h(C4,{writeReviewPacket:()=>_j,writeDecisionEnvelope:()=>z0,withBranch:()=>x$,verifyConnectMutation:()=>K2,resolveWorkspace:()=>d,resolveStoragePaths:()=>A$,replayConnectDecision:()=>tX,persistLatestArtifacts:()=>wj,persistDecisionArtifacts:()=>_0,normalizeEvalInput:()=>uX,matchConfiguredPath:()=>G0,loadStoredDecision:()=>U0,listStoredReviewPackets:()=>zj,listConnectReviewPackets:()=>aX,isReviewCommand:()=>jj,isDeniedCommand:()=>Aj,isAllowedCommand:()=>OW,initConnectWorkspace:()=>lX,inferSurfaces:()=>w0,evaluateConnectDecision:()=>gX,ensureStorage:()=>K0,defaultActor:()=>b0,decisionArtifactRefs:()=>r$,createConnectControlPlaneRuntime:()=>Y2,connectVerdictToPolicy:()=>n$,configuredThreshold:()=>D$,compileConnectPlanPacket:()=>Uj,buildConnectContextPack:()=>bj,assessConnectPolicy:()=>J0,assertConnectEnabled:()=>a,artifactRef:()=>V$,appendAuditRecord:()=>Kj,analyzeConnectImpact:()=>y$,CONTROL_PLANE_TRACE_GET_REF:()=>SW,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>IW,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Yj,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Xj,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Zj,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>T$,AGENT_APPROVALS_REF:()=>MW,ACP_TERMINAL_EXEC_REF:()=>wX,ACP_FS_ACCESS_REF:()=>bX});import GX from"micromatch";function a($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function G0($,W,j){if(!j||j.length===0)return!1;let A=W.replaceAll("\\","/");return GX.isMatch(A,j,{contains:!0})}function D$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function OW($,W){return Qj($.config.connect?.commands?.allow,W)}function jj($,W){return Qj($.config.connect?.commands?.review,W)}function Aj($,W){return Qj($.config.connect?.commands?.deny,W)}function Qj($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function Q4($,W){if(W.length===0)return{state:"none"};for(let A of W)if(Aj($,A))return{commandMatch:A,state:"deny"};for(let A of W)if(jj($,A))return{commandMatch:A,state:"review"};if(W.every((A)=>OW($,A)))return{state:"allow"};let j=W.find(JX);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((A)=>!OW($,A)),state:"unknown"}}function JX($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return A4(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return A4(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function A4($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var Zj={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Xj={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Yj={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},SW={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},IW={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},T$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},bX={key:"acp.fs.access",version:"1.0.0",kind:"command"},wX={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},MW={key:"agent.approvals",version:"1.0.0",kind:"command"};function J0($,W){let j=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.immutablePaths)),A=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.protectedPaths)),Q=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:Z,state:X}=Q4($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,B=W.impactAnalysis.driftFiles.length>0,q=KX({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:B,generatedPath:Boolean(Q),immutable:Boolean(j),protectedPath:Boolean(A),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=_X({breakingChange:W.impactAnalysis.breakingChange,commandMatch:Z,commandState:X,contractDrift:B,protectedPath:A,unknownPaths:W.impactAnalysis.unknownPaths}),V=n$(q);return{commandMatch:Z,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Q,immutablePath:j,protectedPath:A,requiredApprovals:V.requiresApproval?[{capability:T$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:q}}function n$($){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 KX($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(D$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(D$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(D$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(D$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(D$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(zX)[0]??"permit"}function _X($){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 zX($,W){return Z4($)-Z4(W)}function Z4($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as kX}from"crypto";var H4={};h(H4,{formatPrComment:()=>X4,formatMinimalComment:()=>Bj,formatJson:()=>B4,formatCheckRun:()=>Y4,detectImpact:()=>F$,ImpactDetectionOverviewDocBlock:()=>MX});function X4($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)j.push("⚠️ **Contract changed (non-breaking)**");else j.push("✅ **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| ➖ Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let A=$.deltas.filter((Z)=>Z.severity==="breaking"),Q=$.deltas.filter((Z)=>Z.severity==="non_breaking");if(A.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let Z of A)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}if(Q.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let Z of Q)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let A of $.addedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let A of $.removedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### ⚠️ Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let A of W.drift.files)j.push(`- \`${A}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### ✅ No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
|
|
1611
|
-
|
|
1903
|
+
`}function Sw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1904
|
+
|
|
1905
|
+
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1906
|
+
|
|
1907
|
+
This workspace uses ContractSpec to keep contracts, generated artifacts, and AI guidance aligned.
|
|
1908
|
+
|
|
1909
|
+
## Start Here
|
|
1910
|
+
|
|
1911
|
+
1. Run \`contractspec onboard\` to generate a track-aware onboarding guide for this repo.
|
|
1912
|
+
2. Run \`contractspec validate\` after changing contracts or generated outputs.
|
|
1913
|
+
3. Run \`contractspec doctor\` if local setup or tooling looks unhealthy.
|
|
1914
|
+
|
|
1915
|
+
## Recommended Commands
|
|
1916
|
+
|
|
1917
|
+
- \`contractspec onboard\` - generate repo-local onboarding guidance and next steps
|
|
1918
|
+
- \`contractspec create\` - scaffold a new contract or package target
|
|
1919
|
+
- \`contractspec generate\` - refresh derived docs and artifacts
|
|
1920
|
+
- \`contractspec validate\` - validate contracts, package scaffolds, and integrity
|
|
1921
|
+
- \`contractspec connect adoption resolve --family <family> --stdin\` - reuse existing ContractSpec or workspace surfaces before building new ones
|
|
1922
|
+
|
|
1923
|
+
## Builder / Connect
|
|
1924
|
+
|
|
1925
|
+
- Use \`contractspec init --preset connect\` when you want local Connect artifacts and reuse guidance in the repo.
|
|
1926
|
+
- Use \`contractspec init --preset builder-managed\`, \`builder-local\`, or \`builder-hybrid\` when you want Builder control-plane defaults.
|
|
1927
|
+
|
|
1928
|
+
## Notes
|
|
1929
|
+
|
|
1930
|
+
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1931
|
+
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1932
|
+
`}function e8($){if(R$($)!=="connect")return;return{...on.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin",packageRef:"contractspec-adoption"},codex:{enabled:!0,mode:"wrapper",packageRef:"contractspec-adoption"},"claude-code":{enabled:!0,mode:"rule",packageRef:"contractspec-adoption"}},adoption:{...on.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:on.connect?.studio}}function s8($){let b=T0(R$($)),n=mw(R$($));if(!b||!n)return;let A=!0,m=b==="local"||b==="hybrid";return{...on.builder,enabled:!0,runtimeMode:b,bootstrapPreset:n,api:A?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:m?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function ln(){let $=process.platform,b=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${b}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??b}/Claude/claude_desktop_config.json`;default:return`${b}/.config/claude/claude_desktop_config.json`}}function b$($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(m===void 0)n[A]=y;else if(pn(m)&&pn(y))n[A]=b$(m,y)}return n}function D0($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(y===void 0)continue;if(pn(m)&&pn(y))n[A]=D0(m,y);else n[A]=y}return n}function pn($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function a($){try{return JSON.parse($)}catch{return null}}function N($){return JSON.stringify($,null,2)+`
|
|
1933
|
+
`}async function N0($,b){let n=[];return n.push(await $9($,b)),n.push(await b9($,b)),n.push(await n9($,b)),n.push(await A9($,b)),n.push(await m9($,b)),n.push(await y9($,b)),n.push(await W9($,b)),n}async function h$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function $9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(await $.exists(n))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let m=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(m)),{success:!0,message:"Created .contractsrc.json"}}catch(m){return{success:!1,message:`Failed to create: ${m instanceof Error?m.message:String(m)}`}}}}}}async function b9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n);return JSON.parse(m),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(m){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:m instanceof Error?m.message:String(m),fix:{description:"Replace with valid default config",apply:async()=>{try{let W=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(W)),{success:!0,message:"Replaced with valid config"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function n9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m),W=[];if(!y.outputDir)W.push("outputDir");if(!y.conventions)W.push("conventions");if(W.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${W.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let w=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let j of W)if(w[j]!==void 0)y[j]=w[j];return await $.writeFile(n,N(y)),{success:!0,message:"Added missing fields"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function A9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:y.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return y.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(n,N(y)),{success:!0,message:"Added versioning configuration"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function m9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.hooks){let j=y.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(j).length} git hook(s) configured`}}let W=$.join(b.workspaceRoot,".husky");if(await $.exists(W))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return y.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(n,N(y)),{success:!0,message:"Added hooks configuration"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function y9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),j=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(w.length===0&&!j)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...w,...j?["connect.studio.endpoint"]:[]].join(", ")}`}}let y=[],W=A.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!A.builder?.api?.baseUrl)y.push("builder.api.baseUrl");if(m.startsWith("builder-")&&!W)y.push("builder.api.controlPlaneTokenEnvVar");if(m.startsWith("builder-")&&W&&!process.env[W])y.push(`env:${W}`);if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)y.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:y.length===0?"pass":"warn",message:y.length===0?`Builder preset inferred (${m}) and required config is present`:`Builder preset inferred (${m}) but setup is missing ${y.join(", ")}`}}async function W9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(n,".vscode","settings.json"),W=A.builder?.api?.baseUrl;if(!W)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let w=await $.readFile(y).catch(()=>""),j=w?a(w):void 0;if(j?.["contractspec.api.baseUrl"]===W)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(n,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...tn({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as w9}from"node:child_process";import{promisify as j9}from"node:util";var d$=j9(w9);async function F0($,b){let n=[];return n.push(await B9(b)),n.push(await S9(b)),n.push(await Q9($,b)),n.push(await Z9($,b)),n.push(await X9($,b)),n}async function B9($){try{let{stdout:b}=await d$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function S9($){try{let{stdout:b}=await d$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function Q9($,b){let n=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:m,name:y}of n){let W=$.join(b.workspaceRoot,m);if(await $.exists(W)){A=y;break}}if(!A){let m=$.join(b.workspaceRoot,".."),y=$.join(b.workspaceRoot,"../.."),W=[m,y];for(let w of W){for(let{file:j,name:B}of n){let S=$.join(w,j);if(await $.exists(S)){A=B;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await d$(`${A} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function Z9($,b){let n=$.join(b.workspaceRoot,"node_modules");if(await $.exists(n))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await d$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function X9($,b){let n=$.join(b.workspaceRoot,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A),y={...m.dependencies,...m.devDependencies};if("@contractspec/lib.contracts-spec"in y)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${y["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await d$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function v0($,b){let n=await dn($,b.workspaceRoot);if(n.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return n.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(b.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as Y9,isFeatureFile as G9,scanAllSpecsFromSource as H9,scanExampleSource as q9,scanFeatureSource as O9}from"@contractspec/module.workspace";function V9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function an($,b={}){let{fs:n,logger:A}=$,m=V9(),y=b.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let W=await n.glob({pattern:y});for(let j of W){if(j.includes("node_modules")||j.includes("/dist/"))continue;try{let B=await n.readFile(j);if(G9(j)){let S=O9(B,j);m.features.set(S.key,S);continue}if(Y9(j)){let S=q9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=H9(B,j);for(let Q of S)if(Q.specType==="app-config"&&Q.key)m.appConfigs.set(Q.key,Q)}}catch{}}try{let j=await n.glob({pattern:"**/.contractsrc.json"});for(let B of j){if(B.includes("node_modules"))continue;try{let S=await n.readFile(B),Q=JSON.parse(S);m.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){m.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let w={features:m.features.size,examples:m.examples.size,appConfigs:m.appConfigs.size,workspaceConfigs:m.workspaceConfigs.size,total:m.features.size+m.examples.size+m.appConfigs.size+m.workspaceConfigs.size};return A.info(`Discovered ${w.features} features, ${w.examples} examples, ${w.appConfigs} app configs, ${w.workspaceConfigs} workspace configs`),{inventory:m,stats:w}}function yV($){let b=[];for(let[n,A]of $.features)b.push({key:n,file:A.filePath,type:"feature"});for(let[n,A]of $.examples)b.push({key:n,version:A.version,file:A.filePath,type:"example"});for(let[n,A]of $.appConfigs)b.push({key:n,version:A.version,file:A.filePath,type:"app-config"});for(let[,n]of $.workspaceConfigs)b.push({key:n.file,file:n.file,type:"workspace-config"});return b}function en($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function g0($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function sn($,b){let n=$.join(b,"config/stability-policy.json");if(!await $.exists(n))return;try{let A=await $.readFile(n),m=JSON.parse(A);return{version:typeof m.version==="number"&&Number.isFinite(m.version)?m.version:1,criticalPackages:g0(m.criticalPackages).map(en),criticalFeatureKeys:g0(m.criticalFeatureKeys),smokePackages:g0(m.smokePackages)}}catch{return}}function Qw($,b){let n=en($);if(b?.criticalPackages.includes(n))return"critical";return"non-critical"}function Zw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function wb($){return en(`${en($)}/config/stability-policy.json`)}async function P0($,b){let n=[],A=await sn($,b.workspaceRoot),m=await an({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return n.push(J9(m.stats.features)),n.push(U9(m.stats.examples)),n.push(K9(m.inventory.features,A,b)),n.push(_9(m.inventory.examples)),n.push(z9(m.inventory.workspaceConfigs)),n}function J9($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function U9($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function K9($,b,n){let A=[],m=[];for(let[y,W]of $)if(!(Boolean(W.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(W.sourceBlock??"")))if(Zw(y,b))m.push(y);else A.push(y);if(m.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:m.length>0?"fail":"warn",message:m.length>0?`${m.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:m.length>0?`Critical features: ${m.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:m,missingFeatures:A}}}function _9($){let b=[];for(let[n,A]of $)if(!A.entrypoints.packageName)b.push(n);if(b.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function z9($){let b=[];for(let[,n]of $)if(!n.valid)b.push(n.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function k0($,b){let n=[];return n.push(await L9($,b)),n.push(await R9($,b)),n.push(await C9($,b)),n}async function L9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(n))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Mb();return await $.writeFile(n,N(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function R9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(n))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let w=Mb(),j=b$(y,w);return await $.writeFile(n,N(j)),{success:!0,message:"Registered MCP server"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function C9($,b){let n=ln();try{if(!await $.exists(n))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let m=await $.readFile(n);if(JSON.parse(m).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var x9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Xw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function I9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[n,A])=>{if(typeof A==="string")b[n]=A;return b},{})}function E9($){return Object.entries($).some(([b,n])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(n)})}async function M9($,b,n){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:Xw}),m=[];for(let y of A){let W=$.dirname(y),w=$.relative(b,W);try{let j=JSON.parse(await $.readFile(y)),B=I9(j.scripts),S=await $.glob({patterns:x9,cwd:W,ignore:Xw});m.push({packageName:j.name??w,packagePath:w.replace(/\\/g,"/"),hasBuildScript:typeof B.build==="string",hasTypecheckScript:typeof B.typecheck==="string",hasLintScript:typeof B.lint==="string"||typeof B["lint:check"]==="string",hasTestScript:typeof B.test==="string",usesPassWithNoTests:E9(B),testFileCount:S.length,tier:Qw(w,n)})}catch{continue}}return m}function T9($){let b=[];if(!$.hasBuildScript)b.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)b.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)b.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)b.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)b.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)b.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return b}function D9($){let b=[];if($.testFileCount>0&&!$.hasTestScript)b.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)b.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return b}async function Yw($,b,n){let A=await M9($,b,n),m=[];for(let W of A){if(W.tier==="critical")m.push(...T9(W));m.push(...D9(W))}let y=A.filter((W)=>W.tier==="critical").map((W)=>({packageName:W.packageName,packagePath:W.packagePath,hasBuildScript:W.hasBuildScript,hasTypecheckScript:W.hasTypecheckScript,hasLintScript:W.hasLintScript,hasTestScript:W.hasTestScript,usesPassWithNoTests:W.usesPassWithNoTests,testFileCount:W.testFileCount}));return{findings:m,criticalPackages:y}}function Hw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Gw($,b,n,A){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||n.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:Hw(b),context:{findings:b}}}async function qw($,b){let n=await sn($,b.workspaceRoot);if(!n)return[];let A=await Yw($,b.workspaceRoot,n),m=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),y=A.findings.filter((j)=>m.has(j.code)),W=A.findings.filter((j)=>j.code==="tests-without-test-script"),w=A.findings.filter((j)=>j.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:y.length>0?"fail":"pass",message:y.length>0?`${y.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?Hw(y):b.verbose?`Policy: ${wb(b.workspaceRoot)}`:void 0,context:{policyPath:wb(b.workspaceRoot),criticalPackages:A.criticalPackages,findings:y}},Gw("Package Test Scripts",W,new Set,"All tested packages expose a test script"),Gw("Buildable Packages Without Tests",w,new Set,"All buildable packages have tests or explicit test scripts")]}var N9=["src/contracts","contracts","src/specs","specs"];async function r0($,b){let n=[];return n.push(F9(b)),n.push(await v9($,b)),n.push(await g9($,b)),n.push(await P9($,b)),n.push(await r9($,b)),n.push(...await qw($,b)),n}function F9($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",n=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${n}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function v9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let A of n){let m=$.join(A,"package.json");if(await $.exists(m))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function g9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],A=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let W of n)for(let w of N9){let j=$.join(W,w);if(await $.exists(j)){let B=W===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${w}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let m=b.isMonorepo?"src/contracts":"src/contracts",y=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${m}/${y} to organize your specs`,fix:{description:`Create ${m}/ directory${y}`,apply:async()=>{try{let W=$.join(A,"src","contracts");return await $.mkdir(W),{success:!0,message:`Created ${m}/`}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}async function P9($,b){try{let n=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=b.isMonorepo?b.packageRoot:b.workspaceRoot,m=await $.glob({patterns:n,ignore:["node_modules/**","dist/**"],cwd:A});if(m.length>0){let W=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${m.length} contract file(s)${W}`,details:b.verbose?m.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:b.isMonorepo?`No contract files found in package "${b.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function k9($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let A=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.packageRoot,level:"package"}}let n=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(n))return{path:n,root:b.workspaceRoot,level:"workspace"};return null}async function r9($,b){try{let n=await k9($,b);if(!n)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(n.path),m=JSON.parse(A),y=m.outputDir??"./src",W=$.join(n.root,y),w=b.isMonorepo?` (${n.level} level)`:"";if(await $.exists(W))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${y}${w}`,details:b.verbose?`Resolved to: ${W}`:void 0};let B=y==="./src"||y==="src",S=Array.isArray(m.packages)&&m.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||n.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${n.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${y}${w}`,details:b.verbose?`Expected at: ${W}`:void 0,fix:{description:`Create ${y} directory`,apply:async()=>{try{return await $.mkdir(W),{success:!0,message:`Created ${y}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var Ow=["cli","config","mcp","deps","docs","workspace","ai","layers"],Vw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var f9={checks:{runCliChecks:M0,runConfigChecks:N0,runMcpChecks:k0,runDepsChecks:F0,runDocChecks:v0,runWorkspaceChecks:r0,runAiChecks:E0,runLayerChecks:P0},workspace:{findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$}},c9={confirm:async()=>!1,input:async()=>""};async function Jw($,b,n=c9,A=f9){let{fs:m,logger:y}=$,W=b.categories??Ow,{checks:w,workspace:j}=A,B=j.findWorkspaceRoot(b.workspaceRoot),S=j.findPackageRoot(b.workspaceRoot),Q=j.isMonorepo(B),Z=Q?j.getPackageName(S):void 0,X={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${J}`)}let Y=[];for(let J of W){if(b.skipAi&&J==="ai")continue;y.info(`Checking ${Vw[J]}...`);let U=await h9(J,m,X,n,w);for(let H of U){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await n.confirm(`Fix "${H.name}"? ${H.fix.description}`)){y.info(`Applying fix: ${H.fix.description}`);let _=await H.fix.apply();if(_.success)y.info(`✓ ${_.message}`),H.status="pass",H.message=`Fixed: ${_.message}`,H.fix=void 0;else y.warn(`✗ ${_.message}`)}}Y.push(H)}}let G=Y.filter((J)=>J.status==="pass").length,V=Y.filter((J)=>J.status==="warn").length,O=Y.filter((J)=>J.status==="fail").length,K=Y.filter((J)=>J.status==="skip").length;return{checks:Y,passed:G,warnings:V,failures:O,skipped:K,healthy:O===0}}async function h9($,b,n,A,m){switch($){case"cli":return m.runCliChecks(b,n);case"config":return m.runConfigChecks(b,n);case"mcp":return m.runMcpChecks(b,n);case"deps":return m.runDepsChecks(b,n);case"docs":return m.runDocChecks(b,n);case"workspace":return m.runWorkspaceChecks(b,n);case"ai":return m.runAiChecks(b,n,A);case"layers":return m.runLayerChecks(b,n);default:return[]}}function NV($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("✓ All checks passed!");else b.push("✗ Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1934
|
+
`)}function FV($){let n=`${$.status==="pass"?"✓":$.status==="warn"?"⚠":$.status==="fail"?"✗":"○"} ${$.name}: ${$.message}`;if($.details)n+=`
|
|
1935
|
+
${$.details}`;if($.fix)n+=`
|
|
1936
|
+
Fix available: ${$.fix.description}`;return n}async function f0($,b){let n=[],A=b.workspaceRoot??process.cwd(),m=await Jw($,{workspaceRoot:A,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let y of m.checks)if(y.status==="fail")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});else if(y.status==="warn")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});return n}$$();import{mkdtemp as yQ,rm as WQ}from"node:fs/promises";import{tmpdir as wQ}from"node:os";import Tb from"path";import{DEFAULT_CONTRACTSRC as a9}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as e9}from"@contractspec/module.workspace";import s9 from"path";import{packageDocBlocks as d9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as u9,convertSpecToDocBlock as o9,extractModuleDocData as i9,loadSpecFromSource as t9,scanAllSpecsFromSource as l9,scanSpecSource as p9}from"@contractspec/module.workspace";import h0 from"path";import{dirname as Uw,sep as $A}from"path";class c0{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let n;if(b.specType==="app-config")n="app-config";else if(b.specType==="example")n="example";else if(b.specType==="feature")n="feature";if(n&&b.key){let A=Uw(b.filePath);this.modules.push({type:n,key:b.key,dirPath:A})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=Uw($),n=this.modules.filter((A)=>{let m=A.dirPath.endsWith($A)?A.dirPath:A.dirPath+$A;return(b.endsWith($A)?b:b+$A).startsWith(m)||b===A.dirPath});if(n.length===0)return;return n.sort((A,m)=>{let y={"app-config":3,example:2,feature:1},W=y[A.type],w=y[m.type];if(W!==w)return w-W;return m.dirPath.length-A.dirPath.length}),n[0]}}async function _w($,b,n){let{fs:A,logger:m}=n,y=[];if(m.info(`Generating docs for ${$.length} files...`),b.outputDir)await A.mkdir(b.outputDir);let W=new c0(n),w=[];for(let B of $)try{let S=await A.readFile(B),Q=l9(S,B);if(Q.length>0)w.push(...Q);else{let Z=p9(S,B);if(Z.specType!=="unknown")w.push(Z)}}catch(S){}W.initialize(w);let j=await zw($,n);for(let B of j)if(y.push(B.entry.block),m.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await Kw(B.entry.block,B.filePath,b.outputDir,W,A);for(let B of $)try{let S=await t9(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=o9(Q,{rootPath:b.rootPath});if(y.push(Z),m.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await Kw(Z,B,b.outputDir,W,A)}}catch(S){m.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)m.info(`Wrote ${y.length} doc files to ${b.outputDir}`);return{blocks:y,count:y.length}}async function uV($,b){return(await zw($,b)).map(({entry:A})=>A.block)}function oV($,b){return d9(u9({packageName:$,srcRoot:b}))}async function zw($,b){let n=[...new Set($)].sort((m,y)=>m.localeCompare(y)),A=[];for(let m of n){let y=await b.fs.readFile(m),W=m.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),w=i9(y,m,W);for(let j of w.entries)A.push({entry:j,filePath:m})}return A}async function Kw($,b,n,A,m){let y=A.resolve(b),W=y?h0.join(n,y.key):h0.join(n,"_common");await m.mkdir(W);let w=h0.join(W,`${$.id}.md`),j=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1937
|
+
|
|
1938
|
+
${$.body}`;await m.writeFile(w,j)}async function Lw($,b,n,A,m={}){let y=m.config,W=await cn($,{cwd:m.specSearchRoot,config:y,pattern:m.specPattern??bQ(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=s9.join(nQ(n,y),"docs"),j=await _w(W.map((S)=>S.filePath),{outputDir:w,format:"markdown",rootPath:A},$),B=0;for(let S of W){let Q=$Q(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await yb(S.filePath,$,y??a9,{targets:J0(S.specType,{includeTests:Boolean(m.includeRuntimeTests)}),outputDir:y?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((X)=>X.success).length}return{specsCount:W.length,docsCount:j.count,materializedCount:B}}function $Q($){return e9($.specType)}function bQ($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${d0($)}/**/*.ts`:void 0}function nQ($,b){let n=(b?.connect?.policy?.generatedPaths??[]).map(mQ).filter(Boolean);if(n.length>0)return n[0];if(b?.outputDir&&b.outputDir!=="./src")return d0(b.outputDir);return $}function AQ($){return d0($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function mQ($){let b=AQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function d0($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function bA($,b,n,A={}){let m=await yQ(Tb.join(wQ(),"contractspec-drift-"));try{await Lw($,b,m,A.rootPath,A.generation);let y=[],W=await import("node:fs/promises");async function w(Z){let X=await W.readdir(Z,{withFileTypes:!0}),Y=[];for(let G of X){let V=Tb.resolve(Z,G.name);if(G.isDirectory())Y.push(...await w(V));else Y.push(V)}return Y}let j=async(Z)=>{if(!await W.stat(Z).catch(()=>!1))return[];return(await w(Z)).map((Y)=>Tb.relative(Z,Y)).sort()},B=await j(m),S=await j(n),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){y.push(Z);continue}if(!B.includes(Z)){y.push(Z);continue}let X=await W.readFile(Tb.join(m,Z)),Y=await W.readFile(Tb.join(n,Z));if(!X.equals(Y))y.push(Z)}return{hasDrift:y.length>0,files:y}}finally{await WQ(m,{recursive:!0,force:!0})}}async function u0($,b){let{fs:n,logger:A}=$,m=[],y=await P(n);if(!y.outputDir)return A.info("No outputDir configured, skipping drift checks"),m;let W="./contracts",w=y.outputDir;if(!await n.exists(w))return A.info("Generated directory does not exist, skipping drift checks"),m;try{let j=await bA($,W,w);if(j.hasDrift)for(let B of j.files)m.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${w}/${B}`,context:{file:B}})}catch(j){A.warn("Drift detection failed",{error:j instanceof Error?j.message:String(j)})}return m}$$();function jQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function BQ($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function nA($,b,n,A={}){let{fs:m}=b,y=[],W=[],w=$.key??m.basename($.filePath).replace(/\.[jt]s$/,""),j=A.outputDir??n.outputDir??"./src",B=jQ(w),S={};if($.specType==="operation")S.handlerPath=m.join(j,"handlers",`${B}.handler.ts`),S.handlerTestPath=m.join(j,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=m.join(j,"components",`${B}.tsx`),S.componentTestPath=m.join(j,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=m.join(j,"forms",`${B}.form.tsx`),S.formTestPath=m.join(j,"forms",`${B}.form.test.tsx`);if(A.checkHandlers&&S.handlerPath)if(!await m.exists(S.handlerPath))y.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await m.readFile(S.handlerPath),X=`${BQ(w.split(".").pop()??w)}Spec`,Y=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),G=new RegExp(`typeof\\s+${X}\\b`).test(Z);if(!Y)W.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!G)W.push(`Handler ContractHandler typing does not reference expected spec var (${X}): ${S.handlerPath}`)}if(A.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await m.exists(Z))y.push(`Missing test file: ${Z}`)}return{valid:y.length===0,errors:y,warnings:W,expected:S}}async function o0($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkHandlers:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"handler-missing",severity:"warning",message:w,category:"handlers",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"handler-warning",severity:"warning",message:w,category:"handlers",file:y.filePath})}return A}$$();import{createHash as GQ}from"crypto";import HQ from"path";var Db={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},SQ={".handler.ts":"handler",".handler.tsx":"handler",".service.ts":"service",".service.tsx":"service",".test.ts":"test",".test.tsx":"test",".spec.ts":"test",".spec.tsx":"test",".component.tsx":"component",".tsx":"component",".form.tsx":"form",".hook.ts":"hook",".hook.tsx":"hook"};function QQ($){let b=$.toLowerCase();for(let[n,A]of Object.entries(SQ))if(b.endsWith(n))return A;if(b.includes("/handlers/"))return"handler";if(b.includes("/services/"))return"service";if(b.includes("/components/"))return"component";if(b.includes("/forms/"))return"form";if(b.includes("/hooks/"))return"hook";if(b.includes("/__tests__/"))return"test";return"other"}function Rw($,b){let n=[],A=new Set,m=(Z,X,Y)=>{let G=`${Z}:${X}`;if(A.has(G))return;A.add(G),n.push({filePath:b,specKey:Z,referenceType:X,lineNumber:Y,inferredType:QQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1939
|
+
`).length},W,w=new RegExp(Db.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Db.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Db.namedImport);while((W=B.exec($))!==null){let X=W[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(X)for(let Y of X)m(Y,"import",y(W.index))}let S=new RegExp(Db.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Db.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return n}var Cw=["**/*.ts(x)"];async function AA($,b,n={}){let{fs:A}=b,m=n.includePatterns??Cw,y=n.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await A.glob({pattern:w,ignore:y});for(let B of j)try{let S=await A.readFile(B),Z=Rw(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function qJ($,b={}){let{fs:n}=$,A=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of A){let w=await n.glob({pattern:W,ignore:m});for(let j of w)try{let B=await n.readFile(j),S=Rw(B,j);for(let Q of S){let Z=y.get(Q.specKey)??[];Z.push(Q),y.set(Q.specKey,Z)}}catch{}}return y}function ZQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,n){let A=ZQ(b),m=[];if($==="operation")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")m.push({path:`${n}/components/${A}.tsx`,type:"component"}),m.push({path:`${n}/components/${A}.test.tsx`,type:"test"});if($==="form")m.push({path:`${n}/forms/${A}.form.tsx`,type:"form"}),m.push({path:`${n}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});return m}import{Node as p,Project as XQ,SyntaxKind as YQ}from"ts-morph";function Iw($){let b=[],A=new XQ({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),m=(j)=>{if(!p.isObjectLiteralExpression(j))return;let B=j.getProperty("implementations");if(B&&p.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&p.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(p.isObjectLiteralExpression(Q)){let Z,X,Y,G=Q.getProperty("path");if(G&&p.isPropertyAssignment(G)){let K=G.getInitializer();if(p.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&p.isPropertyAssignment(V)){let K=V.getInitializer();if(p.isStringLiteral(K))X=K.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let K=O.getInitializer();if(p.isStringLiteral(K))Y=K.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=A.getDescendantsOfKind(YQ.CallExpression);for(let j of y){let B=j.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=j.getArguments();if(S.length>0&&p.isObjectLiteralExpression(S[0]))return m(S[0]),b}}let W=A.getVariableStatements();for(let j of W)if(j.isExported())for(let B of j.getDeclarations()){let S=B.getInitializer();if(S&&p.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return m(S),b}}let w=A.getExportAssignment((j)=>!j.isExportEquals());if(w){let j=w.getExpression();if(p.isObjectLiteralExpression(j))m(j);else if(p.isAsExpression(j)&&p.isObjectLiteralExpression(j.getExpression()))m(j.getExpression())}return b}function Ew($){if($.length===0)return"missing";let b=$.filter((m)=>m.exists),n=$.filter((m)=>m.type!=="test");if(b.filter((m)=>m.type!=="test").length===0)return"missing";if($.every((m)=>m.exists))return"implemented";return"partial"}function KJ($){let b=$.filter((m)=>m.status==="implemented").length,n=$.filter((m)=>m.status==="partial").length,A=$.filter((m)=>m.status==="missing").length;return{total:$.length,implemented:b,partial:n,missing:A,coverage:$.length>0?Math.round(b/$.length*100):100}}var qQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Mw($){return GQ("sha256").update($).digest("hex")}async function OQ($,b,n,A={},m){let y={...qQ,...A},W=y.computeHashes?Mw($.sourceBlock||""):void 0,w=$.key??HQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,G,V,O)=>{if(Q.has(Y))return;Q.add(Y);let K=await B.exists(Y),J=void 0,U=void 0;if(K&&y.computeHashes)try{J=await B.readFile(Y),U=Mw(J)}catch{}S.push({path:Y,type:G,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:U,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Iw($.sourceBlock);for(let G of Y)await Z(G.path,G.type,"explicit",G.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await AA(w,b,y);for(let G of Y){if(G.filePath===$.filePath)continue;await Z(G.filePath,G.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??n.outputDir??"./src",G=xw($.specType,w,Y);for(let{path:V,type:O}of G)await Z(V,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Ew(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function Tw($,b,n,A={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await OQ(W,b,n,A,m);y.push(w)}catch(w){console.error(`Failed to resolve implementations for ${W}:`,w)}}return y}async function i0($,b,n){let{fs:A}=$,m=[],y=await P(A),W=n.implementation??{},w=b.filter((B)=>B.specType==="operation"),j=await Tw(w,{fs:A},y,{computeHashes:W.useCache??!0});for(let B of j){if(W.requireImplemented&&B.status==="missing")m.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")m.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!W.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);m.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)m.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return m}$$();import{isFeatureFile as UQ,scanAllSpecsFromSource as KQ,scanFeatureSource as _Q}from"@contractspec/module.workspace";function VQ($,b){return`${$}.v${b}`}function t0($,b,n,A,m,y={}){let{treatMissingAsError:W=!0}=y;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let w=[],j=[],B=[];for(let S of A){let Q=VQ(S.key,S.version);if(m.has(Q))w.push(S);else if(j.push(S),W)B.push(`Spec ${b}.v${n} references test ${S.key}.v${S.version} which does not exist`)}return{valid:j.length===0,foundTests:w,missingTests:j,errors:B,specFile:$}}function Dw($,b){return`${$}.v${b}`}function Nw($,b){let n=new Map,A=new Map,m=[],y=[];for(let W of $){if(!W.key||!W.version)continue;let w=Dw(W.key,W.version);if(!W.testTarget){y.push(w);continue}let{type:j,key:B,version:S}=W.testTarget,Q=S??W.version,Z=Dw(B,Q),X=JQ(b,j);if(!X||!X.has(Z)){m.push(w);continue}if(A.set(w,Z),!n.has(Z))n.set(Z,new Set);n.get(Z)?.add(w)}return{targetToTests:n,testToTarget:A,orphanedTests:m,testsWithoutTarget:y}}function JQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function zQ(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function l0($,b){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[b]}async function mA($,b={}){let{fs:n,logger:A}=$;A.info("Starting integrity analysis...",{options:b});let m=await c$(n,{config:b.config,cwd:b.cwd,pattern:b.pattern}),y=zQ(),W=[],w=[];for(let H of m){if((await n.stat(H)).isDirectory)continue;let _=await n.readFile(H);if(UQ(H)){let z=_Q(_,H);W.push(z)}else{let z=KQ(_,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let C=l0(y,L.specType);if(C&&L.key&&L.version!==void 0){let D=n$(L.key,L.version);C.set(D,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let j=b.featureKey?W.filter((H)=>H.key===b.featureKey):W,B=new Set;for(let H of j){for(let q of H.operations){let _=n$(q.key,q.version);if(B.add(`operation:${_}`),!y.operations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let _=n$(q.key,q.version);if(B.add(`event:${_}`),!y.events.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let _=n$(q.key,q.version);if(B.add(`presentation:${_}`),!y.presentations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let _=n$(q.key,q.version);if(B.add(`experiment:${_}`),!y.experiments.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let _=n$(q.key,q.version);if(B.add(`capability:${_}`),!y.capabilities.has(_))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let _=n$(q.key,q.version);B.add(`capability:${_}`)}for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=n$(q.pres.key,q.pres.version);if(!y.operations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let _=n$(q.key,q.version);if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=l0(y,H);if(!q)continue;for(let[_,z]of q)if(!B.has(`${H}:${_}`))S.push(z),w.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of y.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let X=Nw(Z,y);for(let H of j)for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=X.targetToTests.get(_),L=!1,C=!1;if(z)for(let D of z){let F=y.testSpecs.get(D);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)C=!0}}if(!z||!L||!C){let D=[];if(!L)D.push("success scenario");if(!C)D.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${D.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let Y={},G=0;for(let H of Q){let q=l0(y,H);if(!q)continue;let _=q.size,z=0,L=0,C=b.requireTestsFor?.includes(H);for(let[D,F]of q){if(B.has(`${H}:${D}`))z++;if(C){let E=n$(F.key,F.version),r=X.targetToTests.has(E),g=`${F.key}.test`,iA=y.testSpecs.has(n$(g,F.version));if(!r&&!iA)L++,G++,w.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}Y[H]={total:_,covered:z,orphaned:_-z,missingTest:C?L:0}}let V=Object.values(Y).reduce((H,q)=>H+q.total,0),O=Object.values(Y).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:G,byType:Y},U=!w.some((H)=>H.severity==="error");return A.info("Integrity analysis complete",{features:W.length,totalSpecs:V,orphaned:S.length,issues:w.length,healthy:U}),{inventory:y,features:j,coverage:K,issues:w,orphanedSpecs:S,healthy:U}}function hJ($){let b=[];for(let n of Object.values($))for(let A of n.values())b.push(A);return b}function dJ($,b){return $.filter((n)=>n.type===b)}function uJ($,b){return $.filter((n)=>n.severity===b)}async function p0($,b){let n=[],A=await P($.fs),m=await mA($,{config:A,pattern:b.pattern,all:!0});for(let y of m.issues)n.push({ruleId:`integrity-${y.type}`,severity:y.severity==="error"?"error":"warning",message:y.message,category:"integrity",file:y.file,context:{specKey:y.specKey,specType:y.specType,featureKey:y.featureKey,ref:y.ref}});return n}async function a0($,b){let n=[],A=await an($,{});for(let[m,y]of A.inventory.features){if(!y.key)n.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:y.filePath,context:{key:m}});if(!y.owners?.length)n.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${m}' missing 'owners' field`,category:"layers",file:y.filePath,context:{key:m}});if(y.operations.length===0&&y.events.length===0&&y.presentations.length===0)n.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${m}' has no operations, events, or presentations`,category:"layers",file:y.filePath,context:{key:m}})}for(let[m,y]of A.inventory.examples){if(!y.entrypoints.packageName)n.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${m}' missing 'packageName' in entrypoints`,category:"layers",file:y.filePath,context:{key:m}});if(!y.surfaces.templates&&!y.surfaces.sandbox.enabled&&!y.surfaces.studio.enabled&&!y.surfaces.mcp.enabled)n.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${m}' has no enabled surfaces`,category:"layers",file:y.filePath,context:{key:m}})}for(let m of A.inventory.workspaceConfigs.values())if(!m.valid)for(let y of m.errors)n.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${y}`,category:"layers",file:m.file});return n}$$();import{ContractsrcSchema as dQ,DEFAULT_CONTRACTSRC as WA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as LQ}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:n,scan:A=LQ}=$,m=await c$(n,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(zb(w,b.config))continue;if(Lb(w))continue;try{let j=await n.readFile(w),B=A(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function bU($){let b=new Map;for(let n of $){let A=b.get(n.specType)??[];A.push(n),b.set(n.specType,A)}return b}var cw={};f(cw,{toPascalCase:()=>yA,syncPackageDeclarations:()=>rQ,resolvePackageDeclarationConfig:()=>Nb,renderPackageDeclaration:()=>Wm,normalizePath:()=>C$,matchesAllowMissing:()=>ym,inferWorkspacePackageKind:()=>s0,getIndexExportPath:()=>bm,getCanonicalDeclarationRelativePath:()=>$m,discoverWorkspacePackages:()=>gw,createPackageDeclarationIssue:()=>wm,buildPackageTitle:()=>Fb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>G$,buildDomain:()=>Am,buildDeclarationTags:()=>mm,auditPackageDeclarations:()=>vb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>e0,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>Fw});var Fw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},e0={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function Nb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...Fw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function s0($){let b=C$($);for(let[n,A]of Object.entries(e0))if(b.startsWith(n))return A;return null}function $m($,b){switch($){case"libs":case"modules":return`src/${b}.feature.ts`;case"integrations":return"src/integration.ts";case"apps":case"appsRegistry":return"src/blueprint.ts";case"bundles":return`src/bundles/${yA(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function bm($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${yA(b)}Bundle`;case"examples":return"./example"}}function nm($){return C$($).replace(/^packages\//,"").replace(/\//g,".")}function Fb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Am($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function mm($,b,n){return[...new Set([...n,"package",b,$])]}function ym($,b,n){return $.some((A)=>{let m=C$(A);return m===C$(b)||m===n})}function C$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function yA($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function G$($,b){let n=yA(b);switch($){case"feature":return`${n}Feature`;case"integration":return`${n}IntegrationSpec`;case"app-config":return`${n}Blueprint`;case"module-bundle":return`${n}Bundle`;case"example":return`${n}Example`}}import{scanAllSpecsFromSource as RQ,scanSpecSource as CQ}from"@contractspec/module.workspace";var xQ=["packages/libs/*/package.json","packages/modules/*/package.json","packages/integrations/*/package.json","packages/bundles/*/package.json","packages/apps/*/package.json","packages/apps-registry/*/package.json","packages/examples/*/package.json"];async function gw($,b={}){let n=C$(b.workspaceRoot??process.cwd()),A=await IQ($,n,b.config),m=await $.glob({cwd:n,patterns:A,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=Nb(b.config),W=[];for(let w of m){let j=C$($.dirname(w)),B=s0(j);if(!B)continue;let S=await Pw($,$.join(n,w)),Q=$.basename(j),Z=$.join(n,j),X=y.requiredByKind?.[MQ(B)];if(!X)continue;let Y=$m(B,Q);W.push({workspaceRoot:n,relativePackageRoot:j,packageRoot:Z,packageName:typeof S.name==="string"?S.name:j,packageDirName:Q,description:typeof S.description==="string"?S.description:void 0,kind:B,target:X,canonicalDeclarationRelativePath:Y,canonicalDeclarationPath:$.join(Z,Y),indexPath:$.join(Z,"src/index.ts"),indexExportPath:bm(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function vb($,b={}){let n=await gw($,b),A=[];for(let m of n){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=RQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[CQ(j,m.canonicalDeclarationPath)]).find((Q)=>Q.specType!=="unknown")?.specType,w=W===m.target}A.push({...m,exists:y,matchesExpectedTarget:w,detectedSpecType:W})}return A}async function IQ($,b,n){let A=$.join(b,"package.json");if(await $.exists(A)){let m=await Pw($,A),y=EQ(m);if(y.length>0)return y.map((W)=>`${vw(W)}/package.json`)}if(n?.packages?.length)return n.packages.map((m)=>`${vw(m)}/package.json`);return xQ}function EQ($){if(Array.isArray($.workspaces))return $.workspaces.filter((n)=>typeof n==="string");let b=$.workspaces;if(Array.isArray(b?.packages))return b.packages.filter((n)=>typeof n==="string");return[]}function MQ($){return $==="appsRegistry"?"appsRegistry":$}function vw($){return $.replace(/\/+$/,"")}async function Pw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function Wm($){let{pkg:b,refs:n,owners:A,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:Fb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:Am(b.packageDirName),owners:A,tags:mm(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return TQ(b,n,y);case"integration":return DQ(b,n,y);case"app-config":return NQ(b,n,y);case"module-bundle":return rn({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:G$("module-bundle",b.packageDirName)});case"example":return In({key:y.key,version:y.version,description:y.description,title:y.title,domain:y.domain,owners:y.owners,tags:y.tags,stability:y.stability,packageName:b.packageName})}}function TQ($,b,n){let A=[jb("operations",b.operations),jb("events",b.events),jb("presentations",b.presentations),jb("experiments",b.experiments),jb("workflows",b.workflows),jb("dataViews",b.dataViews)].filter(Boolean);return`${$.packageName==="@contractspec/lib.contracts-spec"?"import { defineFeature } from './features';":"import { defineFeature } from '@contractspec/lib.contracts-spec/features';"}
|
|
1940
|
+
|
|
1941
|
+
export const ${G$("feature",$.packageDirName)} = defineFeature({
|
|
1942
|
+
meta: ${FQ(n)},
|
|
1943
|
+
${A.length>0?`${A.join(`
|
|
1944
|
+
`)}
|
|
1945
|
+
`:""}});
|
|
1946
|
+
`}function DQ($,b,n){let A=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1947
|
+
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1948
|
+
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1949
|
+
|
|
1950
|
+
const ${G$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1951
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1952
|
+
description: 'Managed configuration for ${$.packageName}.',
|
|
1953
|
+
fields: {},
|
|
1954
|
+
});
|
|
1955
|
+
|
|
1956
|
+
const ${G$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1957
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1958
|
+
description: 'Secret material for ${$.packageName}.',
|
|
1959
|
+
fields: {},
|
|
1960
|
+
});
|
|
1961
|
+
|
|
1962
|
+
export const ${G$("integration",$.packageDirName)} = defineIntegration({
|
|
1963
|
+
meta: {
|
|
1964
|
+
...${rw(n)},
|
|
1965
|
+
category: 'custom',
|
|
1966
|
+
},
|
|
1967
|
+
supportedModes: ['managed'],
|
|
1968
|
+
capabilities: {
|
|
1969
|
+
provides: [
|
|
1970
|
+
${A||" // Add capability refs here"}
|
|
1971
|
+
],
|
|
1972
|
+
},
|
|
1973
|
+
configSchema: { schema: ${G$("integration",$.packageDirName)}Config, example: {} },
|
|
1974
|
+
secretSchema: { schema: ${G$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1975
|
+
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1976
|
+
});
|
|
1977
|
+
`}function NQ($,b,n){let A=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
1978
|
+
`),m=kw(b.workflows),y=kw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1979
|
+
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1980
|
+
|
|
1981
|
+
export const ${G$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1982
|
+
meta: {
|
|
1983
|
+
...${rw(n)},
|
|
1984
|
+
appId: '${Q$($.packageDirName)}',
|
|
1985
|
+
},
|
|
1986
|
+
capabilities: {
|
|
1987
|
+
enabled: [
|
|
1988
|
+
${W||" // Add capability refs here"}
|
|
1989
|
+
],
|
|
1990
|
+
},${A?`
|
|
1991
|
+
features: {
|
|
1992
|
+
include: [
|
|
1993
|
+
${A}
|
|
1994
|
+
],
|
|
1995
|
+
},`:""}${y?`
|
|
1996
|
+
dataViews: {
|
|
1997
|
+
${y}
|
|
1998
|
+
},`:""}${m?`
|
|
1999
|
+
workflows: {
|
|
2000
|
+
${m}
|
|
2001
|
+
},`:""}
|
|
2002
|
+
});
|
|
2003
|
+
`}function jb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2004
|
+
${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
2005
|
+
`)}
|
|
2006
|
+
],`}function kw($){return $.map((b,n)=>` ${n===0?"primary":`item${n+1}`}: {
|
|
2007
|
+
key: '${b.key}',
|
|
2008
|
+
version: '${b.version}',
|
|
2009
|
+
},`).join(`
|
|
2010
|
+
`)}function FQ($){return`{
|
|
2011
|
+
key: '${$.key}',
|
|
2012
|
+
version: '${$.version}',
|
|
2013
|
+
title: '${Q$($.title)}',
|
|
2014
|
+
description: '${Q$($.description)}',
|
|
2015
|
+
domain: '${Q$($.domain)}',
|
|
2016
|
+
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2017
|
+
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
|
+
stability: '${$.stability}',
|
|
2019
|
+
}`}function rw($){return`{ key: '${$.key}', version: '${$.version}', title: '${Q$($.title)}', description: '${Q$($.description)}', domain: '${Q$($.domain)}', owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}], tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}], stability: '${$.stability}' }`}function Q$($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{scanAllSpecsFromSource as vQ}from"@contractspec/module.workspace";var gQ={feature:["@contractspec/lib.contracts-spec"],integration:["@contractspec/lib.contracts-integrations","@contractspec/lib.schema"],"app-config":["@contractspec/lib.contracts-spec"],"module-bundle":["@contractspec/lib.surface-runtime"],example:["@contractspec/lib.contracts-spec"]};function PQ($){return $.packageName!=="@contractspec/lib.schema"}function kQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function rQ($,b={}){let n=await vb($,b),A=[],m=[],y=[];for(let W of n){if(!b.force&&W.exists&&W.matchesExpectedTarget){y.push({...W,action:"skipped",declarationCreated:!1,indexUpdated:!1,packageJsonUpdated:!1,dependenciesUpdated:[]});continue}let w=await fQ($,W),j=Wm({pkg:W,refs:w,owners:b.config?.defaultOwners?.length?b.config.defaultOwners:["@contractspec-core"],defaultTags:b.config?.defaultTags??[]});if(!b.dryRun)await $.writeFile(W.canonicalDeclarationPath,`${j.trimEnd()}
|
|
2020
|
+
`);let B=await cQ($,W,b.dryRun,PQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await hQ($,W,b.dryRun);if(W.exists)m.push(W.canonicalDeclarationPath);else A.push(W.canonicalDeclarationPath);if(B)m.push(W.indexPath);if(Q)m.push($.join(W.packageRoot,"package.json"));y.push({...W,action:W.exists?"updated":"created",declarationCreated:!W.exists,indexUpdated:B,packageJsonUpdated:Q,dependenciesUpdated:S})}return{packages:y,createdFiles:A,updatedFiles:m}}function wm($,b){return{allowlisted:ym(b,$.relativePackageRoot,$.packageName),message:$.exists?`Package declaration at ${$.canonicalDeclarationRelativePath} must be a ${$.target} spec.`:`Package ${$.relativePackageRoot} is missing its canonical ${$.target} declaration at ${$.canonicalDeclarationRelativePath}.`}}async function fQ($,b){let n=await $.glob({cwd:b.packageRoot,patterns:["src/**/*.{ts,tsx}"],absolute:!1,ignore:["**/dist/**","**/*.test.*","**/*.spec.*","**/*.stories.*"]}),A={operations:[],events:[],presentations:[],experiments:[],workflows:[],dataViews:[],capabilities:[],features:[]};for(let m of n){if(m===b.canonicalDeclarationRelativePath)continue;let y=await $.readFile($.join(b.packageRoot,m)),W=vQ(y,m);for(let w of W){if(!w.key||!w.version)continue;let j={key:w.key,version:w.version};switch(w.specType){case"operation":x$(A.operations,j);break;case"event":x$(A.events,j);break;case"presentation":x$(A.presentations,j);break;case"experiment":x$(A.experiments,j);break;case"workflow":x$(A.workflows,j);break;case"data-view":x$(A.dataViews,j);break;case"capability":x$(A.capabilities,j);break;case"feature":x$(A.features,j);break}}}return A}function x$($,b){if(!$.some((n)=>n.key===b.key&&n.version===b.version))$.push(b)}async function cQ($,b,n=!1,A=!0){if(!A)return!1;let m=`export * from "${b.indexExportPath}";`,y=new RegExp(`export \\* from ['"]${b.indexExportPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"];`),W=await $.exists(b.indexPath)?await $.readFile(b.indexPath):"";if(y.test(W))return!1;if(W=`${W.trimEnd()}
|
|
2021
|
+
${m}
|
|
2022
|
+
`.trimStart(),!n)await $.writeFile(b.indexPath,W);return!0}async function hQ($,b,n=!1){let A=$.join(b.packageRoot,"package.json"),m=JSON.parse(await $.readFile(A)),y=fw(m,"dependencies"),W=[],w=!1;for(let B of gQ[b.target]){if(!kQ(b,B)){if(B in y)delete y[B],w=!0;continue}if(typeof y[B]!=="string")y[B]="workspace:*",W.push(B)}let j=fw(m,"exports");if(w=w||W.length>0,typeof j["."]!=="string")j["."]="./src/index.ts",w=!0;if(w&&!n)await $.writeFile(A,`${JSON.stringify(m,null,"\t")}
|
|
2023
|
+
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function fw($,b){let n=$[b];if(typeof n==="object"&&n!==null&&!Array.isArray(n))return n;let A={};return $[b]=A,A}var uQ=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,oQ=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,iQ=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,tQ=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,lQ=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,pQ=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,aQ=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function wA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function eQ($,b){let n=$.replaceAll("\\","/"),A=new Set(["contracts","features",...wA(b?.conventions?.operations),...wA(b?.conventions?.events),...wA(b?.conventions?.presentations),...wA(b?.conventions?.forms)]);return n.split("/").some((m)=>A.has(m))}function sQ($,b,n){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||lQ.test(A)||tQ.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(b.has(A))return!1;if(eQ(A,n))return!1;return uQ.test(A)}function hw($){return $.replaceAll("\\","/").match(pQ)?.[1]??null}function $4($){let b=$.split(`
|
|
2024
|
+
`).map((n)=>n.trim()).filter((n)=>n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")&&!n.startsWith("*/"));return b.length>0&&b.every((n)=>n.startsWith("import ")||n.startsWith("export *")||n.startsWith("export {")||n.startsWith("export type {")||n==="'use client';"||n==='"use client";'||n==="'use server';"||n==='"use server";')}function b4($){if(!$)return WA;let b=dQ.safeParse($),n=b.success?b.data:{};return{...WA,...n,conventions:{...WA.conventions,...n.conventions??{}},ci:{...WA.ci,...n.ci??{}}}}async function jm($,b){let{fs:n,logger:A}=$,m=[],y=b.config?b4(b.config):await P(n),W=Nb(y),w=await j$({fs:n},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>hw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await n.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!sQ(Q,j,y))continue;try{let Z=await n.readFile(Q);if($4(Z))continue;let X=hw(Q);if(!(X!==null&&aQ.test(X)&&B.has(X))&&!iQ.test(Z))continue;if(oQ.test(Z))continue;m.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:Q})}catch(Z){A.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await vb(n,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=wm(Z,W.allowMissing??[]);m.push({ruleId:"policy-package-declaration",severity:X.allowlisted||W.severity==="warning"?"warning":"error",message:X.message,category:"policy",file:Z.canonicalDeclarationPath,context:{allowlisted:X.allowlisted,expectedTarget:Z.target,packageName:Z.packageName,packageRoot:Z.relativePackageRoot}})}}return m}import{validateSpecStructure as n4}from"@contractspec/module.workspace";async function Bm($){let b=[];for(let n of $){let A=n4(n);for(let m of A.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:m,category:"structure",file:n.filePath});for(let m of A.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:m,category:"structure",file:n.filePath})}return b}async function Sm($){let b=[],n=new Map,A=new Map;for(let m of $){if(!m.key||!m.version)continue;if(m.specType==="test-spec"){let y=`${m.key}.v${m.version}`;n.set(y,{key:m.key,version:m.version,file:m.filePath,type:"test-spec"})}if(m.testRefs&&m.testRefs.length>0){if(!A.has(m.filePath))A.set(m.filePath,[]);A.get(m.filePath)?.push({key:m.key,version:m.version,testRefs:m.testRefs})}}for(let[m,y]of A)for(let W of y){if(!W.testRefs)continue;let w=t0(m,W.key,W.version,W.testRefs,n,{treatMissingAsError:!0});for(let j of w.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:j,category:"test-refs",file:m,context:{specKey:W.key,specVersion:W.version,missingTests:w.missingTests}})}return b}$$();async function Qm($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkTests:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"test-missing",severity:"warning",message:w,category:"tests",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"test-warning",severity:"warning",message:w,category:"tests",file:y.filePath})}return A}function e($,b,n){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},m=b.filter((w)=>w.severity==="error").length,y=b.filter((w)=>w.severity==="warning").length,W=b.filter((w)=>w.severity==="note").length;return{category:$,label:A[$],errors:m,warnings:y,notes:W,passed:m===0,durationMs:n}}async function dw($){try{if(!await $.exists(".git/HEAD"))return{};let n=await $.readFile(".git/HEAD"),A=n.match(/^ref: (.+)$/m);if(A){let y=A[1]?.replace("refs/heads/",""),W=`.git/${A[1]}`;if(await $.exists(W))return{commitSha:(await $.readFile(W)).trim(),branch:y};return{branch:y}}return{commitSha:n.trim()}}catch{return{}}}function uw($){let b=$.config?.ci?.checks,n=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)n.push("handlers");if($.checkTests)n.push("tests");if($.implementation)n.push("implementation");if($.checkDrift)n.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return n.filter((A)=>!$.skip?.includes(A));return n}async function bK($,b={}){let n=Date.now(),{fs:A,logger:m}=$,y=[],W=[],w=uw(b);m.info("Starting CI checks...",{checks:w});let j=await P(A),B=await cn($,{config:j,pattern:b.pattern});if(w.includes("structure")){let V=Date.now(),O=await Bm(B);y.push(...O),W.push(e("structure",O,Date.now()-V))}if(w.includes("integrity")){let V=Date.now(),O=await p0($,b);y.push(...O),W.push(e("integrity",O,Date.now()-V))}if(w.includes("deps")){let V=Date.now(),O=await x0($,b);y.push(...O),W.push(e("deps",O,Date.now()-V))}if(w.includes("doctor")){let V=Date.now(),O=await f0($,b);y.push(...O),W.push(e("doctor",O,Date.now()-V))}if(w.includes("docs")){let V=Date.now(),O=await I0($,b);y.push(...O),W.push(e("docs",O,Date.now()-V))}if(w.includes("policy")){let V=Date.now(),O=await jm($,b);y.push(...O),W.push(e("policy",O,Date.now()-V))}if(w.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await o0($,B);y.push(...O),W.push(e("handlers",O,Date.now()-V))}if(w.includes("tests")||b.checkTests){let V=Date.now(),O=await Qm($,B);y.push(...O),W.push(e("tests",O,Date.now()-V))}if(w.includes("test-refs")){let V=Date.now(),O=await Sm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-V))}if(w.includes("coverage")){let V=Date.now(),O=await C0($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-V))}if(w.includes("implementation")){let V=Date.now(),O=await i0($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-V))}if(w.includes("layers")){let V=Date.now(),O=await a0($,b);y.push(...O),W.push(e("layers",O,Date.now()-V))}if(w.includes("drift")){let V=Date.now(),O=await u0($,b);y.push(...O),W.push(e("drift",O,Date.now()-V))}let S=y.filter((V)=>V.severity==="error").length,Q=y.filter((V)=>V.severity==="warning").length,Z=y.filter((V)=>V.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await dw(A),G={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:G.durationMs}),G}var AK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],mK={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function BK($,b={}){let{fs:n,logger:A}=$,m=(b.outputDir??"./src").replace(/\\/g,"/"),y=["generated/**","dist/**",".turbo/**"],W=[`${m}/handlers/**/*.handler.ts`,`${m}/handlers/**/*.handler.test.ts`,`${m}/components/**/*.tsx`,`${m}/components/**/*.test.tsx`,`${m}/forms/**/*.form.tsx`,`${m}/forms/**/*.form.test.tsx`,`${m}/**/*.runner.ts`,`${m}/**/*.renderer.tsx`],w=b.generatedOnly?[...y,...W]:[...y,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...W],j=await n.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await n.stat(Q),X=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&X<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)A.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await n.remove(Q),A.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}$$();var Vj={};f(Vj,{writeReviewPacket:()=>Rm,writeDecisionEnvelope:()=>db,withBranch:()=>o$,verifyConnectMutation:()=>B6,resolveWorkspace:()=>i,resolveStoragePaths:()=>X$,replayConnectDecision:()=>f4,persistLatestArtifacts:()=>zm,persistDecisionArtifacts:()=>hb,normalizeEvalInput:()=>T4,matchConfiguredPath:()=>gb,loadStoredDecision:()=>ub,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>c4,isReviewCommand:()=>Zm,isDeniedCommand:()=>Xm,isAllowedCommand:()=>jA,initConnectWorkspace:()=>g4,inferSurfaces:()=>rb,evaluateConnectDecision:()=>E4,ensureStorage:()=>cb,defaultActor:()=>kb,decisionArtifactRefs:()=>Sb,createConnectControlPlaneRuntime:()=>e4,connectVerdictToPolicy:()=>I$,configuredThreshold:()=>u$,compileConnectPlanPacket:()=>ob,buildConnectContextPack:()=>fb,assessConnectPolicy:()=>Pb,assertConnectEnabled:()=>A$,artifactRef:()=>_$,appendAuditRecord:()=>Lm,analyzeConnectImpact:()=>i$,CONTROL_PLANE_TRACE_GET_REF:()=>BA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>SA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>qm,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Hm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>U$,AGENT_APPROVALS_REF:()=>QA,ACP_TERMINAL_EXEC_REF:()=>W4,ACP_FS_ACCESS_REF:()=>y4});import A4 from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function gb($,b,n){if(!n||n.length===0)return!1;let A=b.replaceAll("\\","/");return A4.isMatch(A,n,{contains:!0})}function u$($,b,n){return $.config.connect?.policy?.reviewThresholds?.[b]??n}function jA($,b){return Ym($.config.connect?.commands?.allow,b)}function Zm($,b){return Ym($.config.connect?.commands?.review,b)}function Xm($,b){return Ym($.config.connect?.commands?.deny,b)}function Ym($,b){if(!$||$.length===0)return!1;return $.some((n)=>b===n||b.startsWith(`${n} `))}function iw($,b){if(b.length===0)return{state:"none"};for(let A of b)if(Xm($,A))return{commandMatch:A,state:"deny"};for(let A of b)if(Zm($,A))return{commandMatch:A,state:"review"};if(b.every((A)=>jA($,A)))return{state:"allow"};let n=b.find(m4);if(n)return{commandMatch:n,state:"destructive"};return{commandMatch:b.find((A)=>!jA($,A)),state:"unknown"}}function m4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return ow(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return ow(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function ow($,b){return b.every((n)=>$.includes(n)||$.includes(n.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Hm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},BA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},SA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},U$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},y4={key:"acp.fs.access",version:"1.0.0",kind:"command"},W4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},QA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Pb($,b){let n=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.immutablePaths)),A=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=iw($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=w4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(n),protectedPath:Boolean(A),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=j4({breakingChange:b.impactAnalysis.breakingChange,commandMatch:y,commandState:W,contractDrift:j,protectedPath:A,unknownPaths:b.impactAnalysis.unknownPaths}),Q=I$(B);return{commandMatch:y,commandState:W,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:m,immutablePath:n,protectedPath:A,requiredApprovals:Q.requiresApproval?[{capability:U$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function I$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function w4($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(u$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(u$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(u$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(u$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(u$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(B4)[0]??"permit"}function j4($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function B4($,b){return tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as x4}from"crypto";var sw={};f(sw,{formatPrComment:()=>lw,formatMinimalComment:()=>Om,formatJson:()=>aw,formatCheckRun:()=>pw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>G4});function lw($,b={template:"detailed"}){let n=[];if(n.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),n.push(""),$.hasBreaking)n.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)n.push("⚠️ **Contract changed (non-breaking)**");else n.push("✅ **No contract impact**");if(n.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(n.push("### Summary"),n.push(""),n.push("| Type | Count |"),n.push("|------|-------|"),$.summary.breaking>0)n.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)n.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)n.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)n.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)n.push(`| ➖ Removed | ${$.summary.removed} |`);n.push("")}if(b.template==="detailed"&&$.deltas.length>0){n.push("### Changes"),n.push("");let A=$.deltas.filter((y)=>y.severity==="breaking"),m=$.deltas.filter((y)=>y.severity==="non_breaking");if(A.length>0){n.push("#### \uD83D\uDD34 Breaking Changes"),n.push("");for(let y of A)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}if(m.length>0){n.push("#### \uD83D\uDFE1 Non-breaking Changes"),n.push("");for(let y of m)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}}if($.addedSpecs.length>0){n.push("### Added Specs"),n.push("");for(let A of $.addedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if($.removedSpecs.length>0){n.push("### Removed Specs"),n.push("");for(let A of $.removedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if(b.drift)if(b.drift.hasDrift){n.push("### ⚠️ Drift Detected"),n.push(""),n.push("The following generated files are out of sync with their specs:"),n.push("");for(let A of b.drift.files)n.push(`- \`${A}\``);n.push(""),n.push("Run `contractspec generate` to regenerate artifacts."),n.push("")}else n.push("### ✅ No Drift Detected"),n.push("");return n.push("---"),n.push(`*Generated by ContractSpec at ${$.timestamp}*`),n.join(`
|
|
2025
|
+
`)}function Om($){if($.hasBreaking)return`❌ **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`⚠️ **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"✅ **No contract impact**"}function pw($,b,n={}){let A=n.key??"ContractSpec Impact",m=n.failOnBreaking??!0,y,W;if($.hasBreaking)y=m?"failure":"neutral",W=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)y="success",W=`Non-breaking changes (${$.summary.nonBreaking})`;else y="success",W="No contract impact";let w=Om($);return{name:A,headSha:b,conclusion:y,title:W,summary:w,annotations:$.deltas.filter((j)=>j.severity==="breaking").slice(0,50).map((j)=>({path:j.path,startLine:1,endLine:1,annotationLevel:"failure",message:j.description,title:`Breaking: ${j.rule}`}))}}function aw($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((n)=>({type:n.rule,path:n.specKey,summary:n.description,severity:n.severity==="breaking"?"breaking":n.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as S4,computeIoDiff as Q4,generateSnapshot as ew}from"@contractspec/module.workspace";async function K$($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting impact detection...",{baseline:b.baseline});let w=(await n.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${w.length} spec files`);let j=await Z4(n,w,y),B=ew(j),S;if(b.baseline){let X=await X4(n,A,w,b.baseline,y);S=ew(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=Y4(S.specs,B.specs),Z=S4(S.specs,B.specs,Q);return m.info("Impact detection complete",{status:Z.status,breaking:Z.summary.breaking,nonBreaking:Z.summary.nonBreaking}),{...Z,workspaceRoot:y,specsAnalyzed:w.length,baseRef:b.baseline}}async function Z4($,b,n){let A=[];for(let m of b){let y=await $.readFile(m);A.push({path:m,content:y})}return A}async function X4($,b,n,A,m){let y=[];for(let W of n)try{let w=await b.showFile(A,W);y.push({path:W,content:w})}catch{}return y}function Y4($,b){let n=[],A=new Map($.map((y)=>[`${y.key}@${y.version}`,y])),m=new Map(b.map((y)=>[`${y.key}@${y.version}`,y]));for(let[y,W]of m){let w=A.get(y);if(w&&W.type==="operation"&&w.type==="operation"){let j=Q4(w.io,W.io);n.push(...j)}}return n}var G4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1612
2026
|
# Contract Impact Detection
|
|
1613
2027
|
|
|
1614
2028
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -1654,49 +2068,49 @@ The system consists of three layers:
|
|
|
1654
2068
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1655
2069
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1656
2070
|
3. **Integrations**: CLI command + GitHub Action
|
|
1657
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
1658
|
-
`;await $.writeFile(
|
|
1659
|
-
`)}async function
|
|
1660
|
-
`);if(A.test(
|
|
1661
|
-
`)?
|
|
2071
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as bj,readFileSync as nj}from"node:fs";import{basename as H4,join as Vm,resolve as q4}from"node:path";import{ContractsrcSchema as O4,DEFAULT_CONTRACTSRC as V4}from"@contractspec/lib.contracts-spec/workspace-config";function i($={}){let b=q4($.cwd??process.cwd()),n=$.workspaceRoot??I(b),A=$.packageRoot??c(b),m=$.config??J4(n,A),y=U4(A,n);return{cwd:b,workspaceRoot:n,packageRoot:A,config:m,repoId:y,branch:"unknown"}}function o$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function kb($,b){return b??{id:`cli:${$}`,type:"human"}}function rb($){let b=new Set;for(let n of $){if(n.includes("/cli-")||n.includes("/apps/cli-"))b.add("cli");if(n.includes("/contracts-spec/")||n.includes("/specs/"))b.add("contract");if(n.includes("/components/")||n.includes("/ui/")||n.endsWith(".tsx")||n.endsWith(".jsx"))b.add("ui");if(n.includes("/integrations/")||n.includes("/provider"))b.add("integration");if(n.includes("/libs/")||n.includes("/shared/")||n.includes("/utils/"))b.add("library");if(n.includes("/modules/")||n.includes("/bundles/")||n.includes("/examples/"))b.add("solution");if(n.includes("/runtime/"))b.add("runtime");if(n.includes("/harness"))b.add("harness");if(n.includes("/ai-agent/"))b.add("agent");if(n.includes("/knowledge/"))b.add("knowledge");if(n.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function J4($,b){let n={...V4};if($!==b)n=$j(n,Vm($,".contractsrc.json"));return $j(n,Vm(b,".contractsrc.json"))}function $j($,b){if(!bj(b))return $;try{let n=nj(b,"utf-8"),A=JSON.parse(n),m=O4.safeParse(A);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function U4($,b){let n=Vm($,"package.json");if(bj(n))try{let A=JSON.parse(nj(n,"utf-8"));if(A.name)return A.name}catch{}return H4(b)}async function i$($,b){let n=await j$({fs:$.fs},{config:b.workspace.config}),A=new Map(n.filter((j)=>typeof j.key==="string").map((j)=>[j.key,j])),m=b.touchedPaths.map((j)=>K4($.fs,b.workspace,j,n,A)),y=b.baseline!=null?await K$({...$,logger:$.logger??mj},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,W=await _4($,b.workspace,b.touchedPaths),w=_m([...m.flatMap((j)=>j.contracts),...(y?.deltas??[]).map((j)=>({key:j.specKey,version:j.specVersion,kind:j.specType==="event"?"event":"command"}))]);return{breakingChange:y?.hasBreaking===!0,driftFiles:W,impactResult:y,impactedContracts:w,pathImpacts:m,unknownPaths:m.filter((j)=>j.contracts.length===0).map((j)=>j.path)}}function K4($,b,n,A,m){let y=$.resolve(b.workspaceRoot,n),W=Km(n),w=A.map((Y)=>{let G=m$($.relative(b.workspaceRoot,Y.filePath));return{score:R4(n,W,G,Y.key),spec:Y}}).filter((Y)=>Y.score>=45).sort((Y,G)=>G.score-Y.score).slice(0,3),j=A.find((Y)=>Y.filePath===y),B=j?[{score:100,spec:j}]:w,S=B.filter((Y)=>typeof Y.spec.key==="string").map((Y)=>Um(Y.spec.key,Y.spec.version,Y.spec.kind)),Q=B.flatMap((Y)=>[...Y.spec.emittedEvents??[],...Y.spec.policyRefs??[],...Y.spec.testRefs??[]].map((G)=>m.get(G.key)).filter(Boolean).map((G)=>Um(G.key,G.version,G.kind))),Z=_m([...S,...Q]),X=_m([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((Y)=>Y.spec.policyRefs??[]).map((Y)=>Um(Y.key,Y.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:n,policies:X,reasons:B.map((Y)=>`${Y.spec.key??Y.spec.filePath} matched with score ${Y.score}`),surfaces:rb([n])}}async function _4($,b,n){let A=z4($.fs,b,n),m=await Promise.all(A.map(async(y)=>{let W=$.fs.resolve(b.packageRoot,y.comparisonRoot),w=await bA({...$,logger:$.logger??mj},b.workspaceRoot,W,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),j=y.filterPrefix&&y.filterPrefix!==y.comparisonRoot?m$($.fs.relative(y.comparisonRoot,y.filterPrefix)):void 0;return w.files.filter((B)=>j?m$(B)===j||m$(B).startsWith(`${j}/`):!0).map((B)=>m$($.fs.join(y.comparisonRoot,B)))}));return[...new Set(m.flat())].sort()}function z4($,b,n){let A=(b.config.connect?.policy?.generatedPaths??[]).map(C4).filter(Boolean),m=b.config.outputDir&&b.config.outputDir!=="./src"?m$(b.config.outputDir):void 0,y=new Map;for(let W of n){let w=m$(W);if(m&&w.startsWith(m))y.set(m,{comparisonRoot:m});for(let j of A)if(w.startsWith(j)){let B=L4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function L4($,b,n){if(b&&n.startsWith(b))return b;return $.basename(n)==="docs"?m$($.dirname(n)):n}function R4($,b,n,A){if(m$($)===m$(n))return 100;let m=Km(n),y=Km(A??""),W=Aj($)===Aj(n)?40:0,w=Jm($.split("/"),n.split("/"),5),j=Jm(b,m,5),B=Jm(b,y,4);return W+w+j+B}function Jm($,b,n){let A=new Set(b);return $.filter((m)=>A.has(m)).length*n}function Km($){return m$($).split(/[\/._-]+/).filter(Boolean)}function Aj($){return m$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function C4($){return m$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function m$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Um($,b,n){return{key:$,version:String(b??"1.0.0"),kind:n==="query"||n==="event"||n==="policy"||n==="capability"?n:"command"}}function _m($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var mj={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function fb($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let A=kb(b.taskId,b.actor),m=await I4($,n.workspaceRoot,b),y=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),W=n.config.connect?.canonPacks??[];return{id:`connect.ctx_${x4()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:A,knowledge:W.map((w)=>({spaceKey:w.ref,category:"canonical",trustLevel:w.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:y.impactedContracts,affectedSurfaces:y.pathImpacts.length>0?[...new Set(y.pathImpacts.flatMap((w)=>w.surfaces))].sort():rb(m),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...W.map((w)=>({key:w.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...W.map((w)=>({kind:"canon-pack",ref:w.ref}))],acceptanceChecks:n.config.connect?.policy?.smokeChecks??[]}}async function I4($,b,n){let A=n.paths??[];if(A.length>0)return A.map((y)=>yj($.fs,b,y));if(!n.baseline)return[];return(await $.git.diffFiles(n.baseline)).map((y)=>yj($.fs,b,y))}function yj($,b,n){let A=$.resolve(b,n);return $.relative(b,A).replaceAll("\\","/")}import{resolve as t$}from"node:path";function X$($){let b=$.config.connect?.storage,n=t$($.packageRoot,b?.root??".contractspec/connect");return{root:n,contextPack:t$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:t$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:t$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:t$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:t$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:t$(n,"decisions")}}async function cb($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function zm($,b,n){if(n.contextPack)await Z$($,b.contextPack,n.contextPack);if(n.planPacket)await Z$($,b.planPacket,n.planPacket);if(n.patchVerdict)await Z$($,b.patchVerdict,n.patchVerdict)}async function hb($,b,n,A){let m=$.join(b.decisionsDir,n);if(await $.mkdir(m),A.contextPack)await Z$($,$.join(m,"context-pack.json"),A.contextPack);if(A.planPacket)await Z$($,$.join(m,"plan-packet.json"),A.planPacket);if(A.patchVerdict)await Z$($,$.join(m,"patch-verdict.json"),A.patchVerdict);if(A.reviewPacket)await Z$($,$.join(m,"review-packet.json"),A.reviewPacket);if(A.evaluationResult!==void 0)await Z$($,$.join(m,"evaluation-result.json"),A.evaluationResult);if(A.replayBundle!==void 0)await Z$($,$.join(m,"replay-bundle.json"),A.replayBundle);return m}async function db($,b,n,A){let m=$.join(b.decisionsDir,n,"decision-envelope.json");return await Z$($,m,A),m}async function Lm($,b,n){let A=await Wj($,b.auditFile)??"",m=`${JSON.stringify(n)}
|
|
2072
|
+
`;await $.writeFile(b.auditFile,`${A}${m}`)}async function Rm($,b,n){let A=$.join(b.reviewPacketsDir,`${n.id}.json`);return await Z$($,A,n),A}async function ub($,b,n){let A=$.join(b.decisionsDir,n);return{historyDir:A,contextPack:await Bb($,$.join(A,"context-pack.json")),planPacket:await Bb($,$.join(A,"plan-packet.json")),patchVerdict:await Bb($,$.join(A,"patch-verdict.json")),reviewPacket:await Bb($,$.join(A,"review-packet.json")),envelope:await Bb($,$.join(A,"decision-envelope.json"))}}async function Cm($,b){let n=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),A=[];for(let m of n){let y=await Bb($,m);if(y)A.push({filePath:m,packet:y})}return A.sort((m,y)=>m.packet.id.localeCompare(y.packet.id))}function _$($,b,n){return $.relative(b.packageRoot,$.resolve(n)).replaceAll("\\","/")}function Sb($,b,n,A,m){let y=$.join(n.decisionsDir,A);return{contextPack:_$($,b,$.join(y,"context-pack.json")),planPacket:_$($,b,$.join(y,"plan-packet.json")),patchVerdict:_$($,b,$.join(y,"patch-verdict.json")),reviewPacket:m.reviewPacket?_$($,b,$.join(y,"review-packet.json")):void 0,evaluationResult:m.evaluationResult?_$($,b,$.join(y,"evaluation-result.json")):void 0,replayBundle:m.replayBundle?_$($,b,$.join(y,"replay-bundle.json")):void 0}}async function Z$($,b,n){await $.writeFile(b,`${JSON.stringify(n,null,2)}
|
|
2073
|
+
`)}async function Bb($,b){let n=await Wj($,b);if(!n)return;try{return JSON.parse(n)}catch{return}}async function Wj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function E4($,b,n){let A=i(b);if(A$(A),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let m=X$(A),y=await ub($.fs,m,b.decisionId),W=M4(A,y),w=b.scenarioKey?await n.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:W}):await n.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:W}),j=await hb($.fs,m,b.decisionId,{evaluationResult:w}),B=await $.fs.exists($.fs.join(j,"replay-bundle.json")),S={artifacts:Sb($.fs,A,m,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(y.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:y.envelope?.createdAt??new Date().toISOString(),runtimeLink:y.envelope?.runtimeLink,taskId:y.contextPack?.taskId??b.decisionId,verdict:y.patchVerdict?.verdict??"permit"};return await db($.fs,m,b.decisionId,S),{historyDir:j,evaluation:w,context:W}}function M4($,b){return{traceId:b.envelope?.runtimeLink?.traceId??b.patchVerdict?.controlPlane.traceId??b.contextPack?.actor.traceId,actorId:b.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:b.envelope?.runtimeLink?.decisionId,controlPlanePlanId:b.envelope?.runtimeLink?.planId??b.planPacket?.id,metadata:{approvalStatus:b.envelope?.runtimeLink?.approvalStatus,decisionId:b.patchVerdict?.decisionId,taskId:b.contextPack?.taskId,branch:b.contextPack?.branch??$.branch}}}function T4($){return $}import{DEFAULT_CONTRACTSRC as v4}from"@contractspec/lib.contracts-spec/workspace-config";async function ZA($,b){let n=$.join(b.root,".gitignore"),A=b.behavior??"auto",m=Bj(b.patterns);if(m.length===0||A==="skip")return{target:"gitignore",filePath:n,action:"skipped",message:A==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(A==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${n}?`,!0))return{target:"gitignore",filePath:n,action:"skipped",message:"User skipped ContractSpec gitignore update"};let y=await $.exists(n),W=y?await $.readFile(n):"",w=D4(W,m);if(jj(W)===jj(w))return{target:"gitignore",filePath:n,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(n,w),{target:"gitignore",filePath:n,action:y?"merged":"created",message:y?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(y){return{target:"gitignore",filePath:n,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}function D4($,b){let n=N4(b),A=F4(),m=$.replace(/\r\n/g,`
|
|
2074
|
+
`);if(A.test(m))return m.replace(A,n);if(m.trim().length===0)return n;return`${m.endsWith(`
|
|
2075
|
+
`)?m:`${m}
|
|
1662
2076
|
`}
|
|
1663
|
-
${
|
|
2077
|
+
${n}`}function N4($){return`# contractspec:init:gitignore:start
|
|
1664
2078
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1665
|
-
${
|
|
2079
|
+
${Bj($).join(`
|
|
1666
2080
|
`)}
|
|
1667
2081
|
# contractspec:init:gitignore:end
|
|
1668
|
-
`}function
|
|
1669
|
-
`).trimEnd()}function L4($){return[...new Set($.map((W)=>W.trim()).filter(Boolean))]}async function lX($,W={}){let j=d(W),A=W.scope==="package"?j.packageRoot:j.workspaceRoot,Q=$.join(A,".contractsrc.json"),Z={connect:{...rX.connect,enabled:!0}},X="created";if(await $.exists(Q)){let q=r(await $.readFile(Q)),H=p(q??{},Z);if(q?.connect&&typeof q.connect==="object")H.connect.enabled=!0;await $.writeFile(Q,F(H)),X="merged"}else await $.writeFile(Q,F(Z));let Y=A$(d({...W,workspaceRoot:A,packageRoot:A}));await K0($,Y);let B=await EW($,{behavior:W.gitignoreBehavior,interactive:W.interactive??!1,patterns:[Y0.connect,Y0.verificationCache],prompts:W.prompts,root:j.workspaceRoot});return{configPath:Q,targetRoot:A,action:X,gitignore:B}}import{randomUUID as NW}from"crypto";async function Uj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let{commands:A,touchedPaths:Q}=oX(W.candidate),Z=await bj($,{...W,paths:Q}),X=b0(W.taskId,W.actor),Y=iX(W.candidate.steps,W.candidate),B=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),q=J0(j,{commands:A,impactAnalysis:B,touchedPaths:Q}),H={id:`connect.plan_${NW()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:Z.impactedContracts,affectedSurfaces:Z.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:q.requiredApprovals,riskScore:pX(Q.length,A.length),verificationStatus:q.verificationStatus,controlPlane:{intentSubmit:Zj,planCompile:Xj,planVerify:Yj,traceId:X.traceId},acpActions:[...Q.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:Z,planPacket:H}}function oX($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let Q of A.paths??[])W.add(Q);for(let Q of A.commands??[])j.add(Q)}return{commands:[...j],touchedPaths:[...W]}}function iX($,W){if(!$||$.length===0)return[{id:`step_${NW()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${NW()}`,summary:j}:{id:`step_${NW()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function pX($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function tX($,W,j){let A=d(W);a(A);let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X={decisionId:Z.envelope?.runtimeLink?.decisionId,traceId:Z.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,B=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:Z.historyDir,contextPack:Z.contextPack,planPacket:Z.planPacket,patchVerdict:Z.patchVerdict,reviewPacket:Z.reviewPacket,trace:Y??void 0,replay:B??void 0,source:Y?"local+control-plane":"local"}}async function aX($,W={}){let j=d(W);return a(j),zj($.fs,A$(j))}import{buildChannelPlanTrace as sX,compileChannelPlan as eX,finalizeChannelPlan as $2,replayExecutionTrace as W2,resolveChannelExecutionActor as j2}from"@contractspec/integration.runtime/channel";import{createHash as A2}from"crypto";var L0="connect.local",Q2="connect.runtime-link.v1",Z2="connect.adapter.v1",X2="connect-control-plane-bridge";function Y2($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:A,patchVerdict:Q,planPacket:Z,workspace:X})=>{let Y=new Date(j),B=JSON.stringify({connectDecisionId:W,objective:Z.objective,taskId:Z.taskId,tool:A.tool,verdict:Q.verdict}),q={workspaceId:X.repoId,providerKey:L0,externalEventId:W,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Q.controlPlane.traceId,thread:{externalThreadId:`connect:${Z.taskId}`,externalUserId:Z.actor.id},message:{text:V2(Z.objective,A)},metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`}),rawPayload:B},H=await $.store.claimEventReceipt({workspaceId:q.workspaceId,providerKey:q.providerKey,externalEventId:q.externalEventId,eventType:q.eventType,signatureValid:!0,payloadHash:G2(B),traceId:q.traceId});if(H.duplicate)return B2($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:q.workspaceId,providerKey:q.providerKey,externalThreadId:q.thread.externalThreadId,externalUserId:q.thread.externalUserId,occurredAt:Y}),G=j2(q,{actorId:Z.actor.id,actorType:Z.actor.type,capabilityGrants:H2(Q.verdict),capabilitySource:"connect",sessionId:Z.actor.sessionId}),J=eX({event:q,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),b=$2({plan:J,decision:q2(Q),approvalTimeoutMs:900000,now:Y}),w=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:b.policy?.verdict??"blocked",riskTier:b.policy?.riskTier??"blocked",confidence:b.policy?.confidence??0.5,modelName:X2,promptVersion:Q2,policyVersion:Z2,toolTrace:sX(b),actionPlan:b,requiresApproval:b.approval.required,approvalStatus:b.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:b.approval.required?"pending":"processed",decisionId:w.id,receiptId:H.receiptId,traceId:b.traceId,workspaceId:X.repoId,providerKey:L0,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`,metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,tool:A.tool})}),{approvalStatus:w.approvalStatus,decisionId:w.id,planId:b.id,providerKey:L0,receiptId:H.receiptId,threadId:V.id,traceId:b.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>O4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await O4($.traceService,W);return j?W2(j):null}}}async function B2($,W,j){let Q=(await $.listDecisions({externalEventId:j,limit:1,providerKey:L0,workspaceId:W}))[0];return Q?{approvalStatus:Q.approvalStatus,decisionId:Q.id,planId:Q.actionPlan.id,providerKey:L0,receiptId:Q.receiptId,threadId:Q.threadId,traceId:Q.actionPlan.traceId,workspaceId:W}:null}async function O4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function q2($){let W=n$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((j)=>`${j.status}:${j.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:W.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:W.controlPlaneVerdict}}function H2($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function V2($,W){return`${$} [${W.tool}]`}function G2($){return A2("sha256").update($).digest("hex")}function S4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as w2}from"crypto";function I4($){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 J2}from"crypto";function M4($,W,j){let A=$?`Immutable path: ${$}`:W?`Protected path: ${W}`:j?`Generated path: ${j}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":W||j?"warn":"pass",detail:A}}function E4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:A}}function N4($,W,j){return{id:"impact-analysis",status:$?"fail":W||j?"warn":"pass",detail:$?"Breaking change detected.":W?"Generated-path drift detected.":j?"Impact could not be resolved.":"Impact resolved."}}function R4($,W,j,A,Q,Z){let X=Z.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${Z.runtimeLink.decisionId}`:Z.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${Z.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${J2()}`,sourceDecisionId:W,objective:A.objective,reason:Z.reason,summary:{paths:Q,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:Z.artifactRefs.contextPack},{type:"plan-packet",ref:Z.artifactRefs.planPacket},{type:"patch-verdict",ref:Z.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:T$.key,reason:Z.reason}],controlPlane:{traceQuery:SW,policyExplain:IW,approvalStatus:Z.runtimeLink?.approvalStatus,decisionId:Z.runtimeLink?.decisionId,traceId:Z.runtimeLink?.traceId??j.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Lj($,W,j,A,Q,Z,X,Y,B){let q=n$(X);return{decisionId:$,summary:A.objective,action:W.tool==="acp.fs.access"?{actionType:W.operation==="write"?"write_file":"edit_file",tool:W.tool,target:W.path}:{actionType:"run_command",tool:W.tool,cwd:W.cwd},impacted:Q,checks:Z,verdict:X,controlPlane:{verdict:q.controlPlaneVerdict,requiresApproval:q.requiresApproval,approvalStatus:B?.approvalStatus,decisionId:B?.decisionId,traceId:B?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${T$.key}@${T$.version}`,`${MW.key}@${MW.version}`]:void 0,remediation:b2(X),reviewPacketRef:Y,replay:{traceQuery:SW,policyExplain:IW}}}function b2($){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 K2($,W,j={}){let A=d(W);a(A),A=x$(A,await $.git.currentBranch());let Q=`connect.dec_${w2()}`,Z=(j.now??(()=>new Date))().toISOString(),X=A$(A);await K0($.fs,X);let{contextPack:Y,planPacket:B}=await Uj($,{...W,candidate:_2(W)}),q=z2(W),H=await y$($,{baseline:W.baseline,touchedPaths:q,workspace:A}),V=await U2(j,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),G=V.some((M)=>M.id.startsWith("smoke:")&&M.status==="fail"),J=J0(A,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:q}),b=[M4(J.immutablePath,J.protectedPath,J.generatedPath),E4(J.commandState,J.commandMatch),N4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],w=r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0}),L=H.pathImpacts.length>0?H.pathImpacts.map((M)=>({file:M.path,contracts:M.contracts,policies:M.policies,surfaces:M.surfaces})):q.map((M)=>({file:M,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),z=Lj(Q,W,Y,B,L,b,J.verdict,void 0),S=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Q,createdAt:Z,input:W,patchVerdict:z,planPacket:B,workspace:A}):null,U=S?{...B,controlPlane:{...B.controlPlane,decisionId:S.decisionId,traceId:S.traceId??B.controlPlane.traceId}}:B,O=J.verdict==="require_review"?R4(A,Q,Y,U,q,{artifactRefs:w,reason:J.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:S}):void 0,K=Lj(Q,W,Y,U,L,b,J.verdict,O?V$($.fs,A,$.fs.join(X.reviewPacketsDir,`${O.id}.json`)):void 0,S);if(await wj($.fs,X,{contextPack:Y,planPacket:U,patchVerdict:K}),O)await _j($.fs,X,O);let _=await _0($.fs,X,Q,{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O}),I={artifacts:r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(O)}),connectDecisionId:Q,createdAt:Z,runtimeLink:S??void 0,taskId:W.taskId,verdict:J.verdict};return await z0($.fs,X,Q,I),await Kj($.fs,X,I4({contextPack:Y,createdAt:Z,envelope:I,reviewPacket:O,verifyInput:W,workspace:A})),{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O,historyDir:_}}function _2($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function z2($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function U2($,W,j){if(!$.runCommand)return[];let A=[];for(let Q of W){let Z=await $.runCommand(Q,{cwd:j});A.push({id:`smoke:${Q}`,status:Z.exitCode===0?"pass":"fail",detail:Z.exitCode===0?`Passed: ${Q}`:`Failed (${Z.exitCode}): ${Q}`})}return A}DW();var Ij={};h(Ij,{generateWorkflowSpec:()=>Y8,generateWorkflowRunnerTemplate:()=>jW,generateWorkflowDevkitWorkflowTemplate:()=>a0,generateWorkflowDevkitStreamRouteTemplate:()=>$W,generateWorkflowDevkitStartRouteTemplate:()=>s0,generateWorkflowDevkitGenericTemplate:()=>WW,generateWorkflowDevkitFollowUpRouteTemplate:()=>e0,generateTestTemplate:()=>s5,generateTelemetrySpec:()=>X8,generatePresentationSpec:()=>Z8,generateOperationSpec:()=>Q8,generateMigrationSpec:()=>A8,generateKnowledgeSpaceSpec:()=>W8,generateIntegrationSpec:()=>$8,generateHandlerTemplate:()=>t5,generateFormSpec:()=>p5,generateFeatureSpec:()=>i5,generateExperimentSpec:()=>o5,generateEventSpec:()=>l5,generateDataViewSpec:()=>r5,generateDataViewRendererTemplate:()=>p0,generateComponentTemplate:()=>a5,generateAppBlueprintSpec:()=>c5});DW();class T4{ai;templates=Ij;constructor($){this.ai=new CW($)}}function GU($){return new T4($)}import{scanSpecSource as D2}from"@contractspec/module.workspace";function F4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function zU($,W,j={}){let{fs:A,logger:Q}=W,Z=await A.exists($);if(!Z&&!j.force)return{specPath:$,specInfo:F4($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let X=F4($),Y;if(Z)try{let q=await A.readFile($);X=D2(q,$),Y=X.key}catch{}let B=[];if(j.clean&&Y)try{let q=await _W(Y,{fs:A});for(let H of q)try{await A.remove(H.filePath),B.push(H.filePath),Q.info(`Removed artifact: ${H.filePath}`)}catch{Q.warn(`Could not remove artifact: ${H.filePath}`)}}catch{Q.warn("Could not discover implementations for cleanup")}if(Z)await A.remove($),Q.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:X,deleted:!0,cleanedFiles:B,errors:[]}}import{computeSemanticDiff as T2}from"@contractspec/module.workspace";async function OU($,W,j,A={}){let{fs:Q,git:Z}=j;if(!await Q.exists($))throw Error(`Spec file not found: ${$}`);let Y=await Q.readFile($),B,q;if(A.baseline)B=await Z.showFile(A.baseline,$),q=`${A.baseline}:${$}`;else{if(!await Q.exists(W))throw Error(`Spec file not found: ${W}`);B=await Q.readFile(W),q=W}let H=T2(Y,$,B,q,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:q,differences:H}}i();import{openApiForRegistry as F2}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Mj}from"@contractspec/lib.contracts-spec/operations";async function x2($,W){let{fs:j,logger:A}=W,{registryPath:Q,outputPath:Z="./openapi.json"}=$;A.info("Loading registry...",{registryPath:Q});let X=await y2(Q,j);A.info("Generating OpenAPI document...");let Y=F2(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),B=JSON.stringify(Y,null,2)+`
|
|
1670
|
-
`,
|
|
2082
|
+
`}function F4(){return new RegExp(`${wj("# contractspec:init:gitignore:start")}[\\s\\S]*?${wj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function wj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jj($){return $.replace(/\r\n/g,`
|
|
2083
|
+
`).trimEnd()}function Bj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function g4($,b={}){let n=i(b),A=b.scope==="package"?n.packageRoot:n.workspaceRoot,m=$.join(A,".contractsrc.json"),y={connect:{...v4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=b$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,N(S)),W="merged"}else await $.writeFile(m,N(y));let w=X$(i({...b,workspaceRoot:A,packageRoot:A}));await cb($,w);let j=await ZA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ib.connect,Ib.verificationCache],prompts:b.prompts,root:n.workspaceRoot});return{configPath:m,targetRoot:A,action:W,gitignore:j}}import{randomUUID as XA}from"crypto";async function ob($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let{commands:A,touchedPaths:m}=P4(b.candidate),y=await fb($,{...b,paths:m}),W=kb(b.taskId,b.actor),w=k4(b.candidate.steps,b.candidate),j=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),B=Pb(n,{commands:A,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${XA()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:n.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:r4(m.length,A.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:Hm,planVerify:qm,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function P4($){let b=new Set($.touchedPaths??[]),n=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let m of A.paths??[])b.add(m);for(let m of A.commands??[])n.add(m)}return{commands:[...n],touchedPaths:[...b]}}function k4($,b){if(!$||$.length===0)return[{id:`step_${XA()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((n)=>typeof n==="string"?{id:`step_${XA()}`,summary:n}:{id:`step_${XA()}`,summary:n.summary,paths:n.paths,commands:n.commands,contractRefs:n.contractRefs})}function r4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function f4($,b,n){let A=i(b);A$(A);let m=X$(A),y=await ub($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=n&&(W.decisionId||W.traceId)?await n.getExecutionTrace(W):null,j=n&&w?await n.replayExecutionTrace(W):null;return{decisionId:b.decisionId,historyDir:y.historyDir,contextPack:y.contextPack,planPacket:y.planPacket,patchVerdict:y.patchVerdict,reviewPacket:y.reviewPacket,trace:w??void 0,replay:j??void 0,source:w?"local+control-plane":"local"}}async function c4($,b={}){let n=i(b);return A$(n),Cm($.fs,X$(n))}import{buildChannelPlanTrace as h4,compileChannelPlan as d4,finalizeChannelPlan as u4,replayExecutionTrace as o4,resolveChannelExecutionActor as i4}from"@contractspec/integration.runtime/channel";import{createHash as t4}from"crypto";var ib="connect.local",l4="connect.runtime-link.v1",p4="connect.adapter.v1",a4="connect-control-plane-bridge";function e4($){return{linkDecision:async({connectDecisionId:b,createdAt:n,input:A,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(n),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:A.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:ib,externalEventId:b,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:n6(y.objective,A)},metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`}),rawPayload:j},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:A6(j),traceId:B.traceId});if(S.duplicate)return s4($.store,W.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:w}),Z=i4(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:b6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=d4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=u4({plan:X,decision:$6(m),approvalTimeoutMs:900000,now:w}),G=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:Y.policy?.verdict??"blocked",riskTier:Y.policy?.riskTier??"blocked",confidence:Y.policy?.confidence??0.5,modelName:a4,promptVersion:l4,policyVersion:p4,toolTrace:h4(Y),actionPlan:Y,requiresApproval:Y.approval.required,approvalStatus:Y.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:Y.approval.required?"pending":"processed",decisionId:G.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:ib,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,tool:A.tool})}),{approvalStatus:G.approvalStatus,decisionId:G.id,planId:Y.id,providerKey:ib,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Sj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let n=await Sj($.traceService,b);return n?o4(n):null}}}async function s4($,b,n){let m=(await $.listDecisions({externalEventId:n,limit:1,providerKey:ib,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:ib,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Sj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function $6($){let b=I$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((n)=>`${n.status}:${n.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function b6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function n6($,b){return`${$} [${b.tool}]`}function A6($){return t4("sha256").update($).digest("hex")}function Qj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as j6}from"crypto";async function Zj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let n=m6(b);if(!n)return{};let A=await Jb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:n,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:n==="ui"?y6(b):void 0,query:xm(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:A.verdict==="permit"?"pass":A.verdict==="rewrite"?"warn":"fail",detail:A.reason},reason:A.reason,remediation:A.selected!=null?[`Prefer ${A.selected.candidate.source} candidate ${A.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:A,verdict:A.verdict}}function m6($){let b=xm($).toLowerCase();if(/\b(contract|operation|event|spec|presentation|form)\b/.test(b))return"contracts";if(/\b(integration|provider|sdk|adapter|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render)\b/.test(b))return"runtime";if(/\b(component|ui|screen|view|page|tsx|jsx)\b/.test(b))return"ui";if(/\b(module|bundle|example|template)\b/.test(b))return"solutions";if(/\b(logger|schema|testing|observability|identity|utility|shared|lib)\b/.test(b))return"sharedLibs";return null}function xm($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function y6($){let b=xm($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function Xj($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as W6}from"crypto";function Yj($,b,n){let A=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:n?`Generated path: ${n}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||n?"warn":"pass",detail:A}}function Gj($,b){let n=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:n,detail:A}}function Hj($,b,n){return{id:"impact-analysis",status:$?"fail":b||n?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":n?"Impact could not be resolved.":"Impact resolved."}}function qj($,b,n,A,m,y){let W=y.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${y.runtimeLink.decisionId}`:y.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${y.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${W6()}`,sourceDecisionId:b,objective:A.objective,reason:y.reason,summary:{paths:m,impactedContracts:n.impactedContracts,affectedSurfaces:n.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:y.artifactRefs.contextPack},{type:"plan-packet",ref:y.artifactRefs.planPacket},{type:"patch-verdict",ref:y.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:W}],requiredApprovals:[{capability:U$.key,reason:y.reason}],controlPlane:{traceQuery:BA,policyExplain:SA,approvalStatus:y.runtimeLink?.approvalStatus,decisionId:y.runtimeLink?.decisionId,traceId:y.runtimeLink?.traceId??n.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Im($,b,n,A,m,y,W,w,j){let B=I$(W);return{decisionId:$,summary:A.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:m,checks:y,verdict:W,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:j?.approvalStatus,decisionId:j?.decisionId,traceId:j?.traceId??n.actor.traceId},approvalOperationRefs:W==="require_review"?[`${U$.key}@${U$.version}`,`${QA.key}@${QA.version}`]:void 0,remediation:w6(W),reviewPacketRef:w,replay:{traceQuery:BA,policyExplain:SA}}}function w6($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function B6($,b,n={}){let A=i(b);A$(A),A=o$(A,await $.git.currentBranch());let m=`connect.dec_${j6()}`,y=(n.now??(()=>new Date))().toISOString(),W=X$(A);await cb($.fs,W);let{contextPack:w,planPacket:j}=await ob($,{...b,candidate:Z6(b)}),B=X6(b),S=await i$($,{baseline:b.baseline,touchedPaths:B,workspace:A}),Q=await Y6(n,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=Pb(A,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await Zj($,b),G=[Yj(X.immutablePath,X.protectedPath,X.generatedPath),Gj(X.commandState,X.commandMatch),Hj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],V=S6(X,Y.verdict),O=I$(V),K=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:U$.key,reason:K}]:[],U={...j,requiredApprovals:J,verificationStatus:O.verificationStatus},H=Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((r)=>({file:r.path,contracts:r.contracts,policies:r.policies,surfaces:r.surfaces})):B.map((r)=>({file:r,contracts:w.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:w.affectedSurfaces})),_=Im(m,b,w,U,q,G,V,void 0),z=n.controlPlane?await n.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:_,planPacket:U,workspace:A}):null,L=z?{...j,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:z.decisionId,traceId:z.traceId??j.controlPlane.traceId}}:U,C=V==="require_review"?qj(A,m,w,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,D=Im(m,b,w,L,q,G,V,C?_$($.fs,A,$.fs.join(W.reviewPacketsDir,`${C.id}.json`)):void 0,z);if(Y.remediation?.length)D.remediation=Y.remediation;if(await zm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:D}),C)await Rm($.fs,W,C);let F=await hb($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C}),E={artifacts:Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(C)}),connectDecisionId:m,createdAt:y,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await db($.fs,W,m,E),await Lm($.fs,W,Xj({contextPack:w,createdAt:y,envelope:E,reviewPacket:C,verifyInput:b,workspace:A})),{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C,historyDir:F}}function S6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return Q6($.verdict,b)}function Q6($,b){if(!b)return $;return Oj($)<=Oj(b)?$:b}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Z6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function X6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function Y6($,b,n){if(!$.runCommand)return[];let A=[];for(let m of b){let y=await $.runCommand(m,{cwd:n});A.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return A}HA();var Tm={};f(Tm,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});HA();class Uj{ai;templates=Tm;constructor($){this.ai=new GA($)}}function wz($){return new Uj($)}import{scanSpecSource as z6}from"@contractspec/module.workspace";function Kj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Xz($,b,n={}){let{fs:A,logger:m}=b,y=await A.exists($);if(!y&&!n.force)return{specPath:$,specInfo:Kj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let W=Kj($),w;if(y)try{let B=await A.readFile($);W=z6(B,$),w=W.key}catch{}let j=[];if(n.clean&&w)try{let B=await AA(w,{fs:A});for(let S of B)try{await A.remove(S.filePath),j.push(S.filePath),m.info(`Removed artifact: ${S.filePath}`)}catch{m.warn(`Could not remove artifact: ${S.filePath}`)}}catch{m.warn("Could not discover implementations for cleanup")}if(y)await A.remove($),m.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:W,deleted:!0,cleanedFiles:j,errors:[]}}import{computeSemanticDiff as L6}from"@contractspec/module.workspace";async function Hz($,b,n,A={}){let{fs:m,git:y}=n;if(!await m.exists($))throw Error(`Spec file not found: ${$}`);let w=await m.readFile($),j,B;if(A.baseline)j=await y.showFile(A.baseline,$),B=`${A.baseline}:${$}`;else{if(!await m.exists(b))throw Error(`Spec file not found: ${b}`);j=await m.readFile(b),B=b}let S=L6(w,$,j,B,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:B,differences:S}}$$();import{openApiForRegistry as R6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Dm}from"@contractspec/lib.contracts-spec/operations";async function C6($,b){let{fs:n,logger:A}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;A.info("Loading registry...",{registryPath:m});let W=await x6(m,n);A.info("Generating OpenAPI document...");let w=R6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2084
|
+
`,B=n.resolve(y);return await n.mkdir(n.dirname(B)),await n.writeFile(B,j),A.info(`OpenAPI document written to ${B}`),{document:w,outputPath:B,json:j}}async function x6($,b){let A=await import(b.resolve($));if(A instanceof Dm)return A;if(A.registry instanceof Dm)return A.registry;let m=typeof A.createRegistry==="function"?A.createRegistry:typeof A.default==="function"?A.default:void 0;if(m){let y=await m();if(y instanceof Dm)return y}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as I6,parseOpenApi as E6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Nm,dirname as _j,join as Qb}from"path";function M6($,b,n){if(b.outputDir)return b.outputDir;let{outputDir:A,conventions:m}=n;switch($){case"operation":return Qb(A,m.operations.split("|")[0]??"operations");case"event":return Qb(A,m.events);case"model":return Qb(A,"models");default:return A}}async function zj($,b,n){let{fs:A,logger:m}=n,{source:y,prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;m.info(`Importing from OpenAPI: ${y}`);let X=await E6(y,{fetch:globalThis.fetch,readFile:(J)=>A.readFile(J)});if(X.warnings.length>0)for(let J of X.warnings)m.warn(`Parse warning: ${J}`);m.info(`Parsed ${X.operations.length} operations from ${X.info.title} v${X.info.version}`);let Y=I6(X,$,{prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q});m.info(`Import result: ${Y.summary.imported} imported, ${Y.summary.skipped} skipped, ${Y.summary.errors} errors`);let G=[],V=[],O=[],K=new Map;for(let J of Y.operationSpecs){let U="operation",H=null;if(J.code.includes("defineEvent("))U="event",H=J.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((J.code.includes("defineSchemaModel(")||J.code.includes("new EnumType(")||J.code.includes("ScalarTypeEnum.")||J.code.includes("new ZodSchemaType(")||J.code.includes("z.enum(")||J.code.includes("new JsonSchemaType(")||J.code.includes("new GraphQLSchemaType("))&&!J.code.includes("defineCommand(")&&!J.code.includes("defineQuery("))U="model";else U="operation",H=J.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let q=M6(U,b,$),_=Qb(q,J.fileName);if(!H&&U==="model"){if(J.code.includes("new ZodSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(J.code.includes("new JsonSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(J.code.includes("new GraphQLSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!H)H=J.code.match(/export const (\w+)\s*=/)}if(Z)m.info(`[DRY RUN] Would create: ${_}`);else{let z=_j(_);if(!await A.exists(z))await A.mkdir(z);await A.writeFile(_,J.code),m.info(`Created: ${_}`)}if(G.push({path:_,operationId:J.source.sourceId,specName:J.fileName.replace(".ts","")}),H){let z=_j(_),L=K.get(z)||[];L.push({file:Nm(_),name:H[1],type:U}),K.set(z,L)}}if(!Z&&G.length>0)for(let[J,U]of K.entries()){if(U.length===0)continue;let H=U.map((E)=>E.type),q=H.every((E)=>E==="operation"),_=H.every((E)=>E==="event"),z=H.every((E)=>E==="model"),L=`/**
|
|
1671
2085
|
* Auto-generated registry file.
|
|
1672
2086
|
*/
|
|
1673
|
-
`;
|
|
1674
|
-
`}),
|
|
1675
|
-
`;let C=!1;if(
|
|
2087
|
+
`;U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;L+=`import { ${E.name} } from '${r}';
|
|
2088
|
+
`}),L+=`
|
|
2089
|
+
`;let C=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1676
2090
|
|
|
1677
|
-
`,
|
|
1678
|
-
`,
|
|
1679
|
-
`}),C=!0;else if(
|
|
2091
|
+
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
2092
|
+
`,U.forEach((E)=>{L+=`operationRegistry.register(${E.name});
|
|
2093
|
+
`}),C=!0;else if(_)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
1680
2094
|
|
|
1681
|
-
`,
|
|
1682
|
-
`,
|
|
1683
|
-
`}),C=!0;else if(
|
|
2095
|
+
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2096
|
+
`,U.forEach((E)=>{L+=`eventRegistry.register(${E.name});
|
|
2097
|
+
`}),C=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
1684
2098
|
|
|
1685
|
-
`,
|
|
1686
|
-
`,
|
|
1687
|
-
`}),C=!0;if(C){let
|
|
2099
|
+
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2100
|
+
`,U.forEach((E)=>{L+=`modelRegistry.register(${E.name});
|
|
2101
|
+
`}),C=!0;if(C){let E=Qb(J,"registry.ts");await A.writeFile(E,L),m.info(`Created/Updated registry: ${E}`)}let D=`/**
|
|
1688
2102
|
* Auto-generated barrel file.
|
|
1689
2103
|
*/
|
|
1690
2104
|
|
|
1691
|
-
`;if(
|
|
1692
|
-
`}),C)
|
|
1693
|
-
`;let
|
|
1694
|
-
{ key: '${
|
|
2105
|
+
`;if(U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;D+=`export * from '${r}';
|
|
2106
|
+
`}),C)D+=`export * from './registry';
|
|
2107
|
+
`;let F=Qb(J,"index.ts");await A.writeFile(F,D),m.info(`Created/Updated index: ${F}`)}for(let J of Y.skipped)V.push({operationId:J.sourceId,reason:J.reason}),m.debug(`Skipped: ${J.sourceId} - ${J.reason}`);for(let J of Y.errors)O.push({operationId:J.sourceId,error:J.error}),m.error(`Error: ${J.sourceId} - ${J.error}`);return{imported:Y.summary.imported,skipped:Y.summary.skipped,errors:Y.summary.errors,files:G,skippedOperations:V,errorMessages:O}}import{importFromOpenApi as T6,parseOpenApi as D6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as N6,join as F6}from"path";async function Iz($,b,n){let{fs:A,logger:m}=n,{sources:y,sourceName:W,interactive:w,force:j,dryRun:B}=$,{outputDir:S}=b,Q=y??b.openapi?.sources??[];if(W){if(Q=Q.filter((X)=>X.name===W),Q.length===0)throw Error(`Source not found: ${W}`)}if(Q.length===0)return m.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let Z={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let X of Q){m.info(`Syncing with source: ${X.name}`);let Y=X.url??X.file;if(!Y){m.warn(`Source ${X.name} has no url or file configured`);continue}let G=await D6(Y,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});m.info(`Parsed ${G.operations.length} operations from ${X.name}`);let V=T6(G,b,{prefix:X.prefix,tags:X.tags,exclude:X.exclude,defaultStability:X.defaultStability,defaultAuth:X.defaultAuth});for(let O of V.operationSpecs){let K=F6(S,O.fileName);if(!await A.exists(K)){if(!B){let U=N6(K);await A.mkdir(U),await A.writeFile(K,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:K}),m.info(`Added: ${O.source.sourceId}`)}else if(await A.readFile(K)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K});else if(j==="openapi"){if(!B)await A.writeFile(K,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:K}),m.info(`Updated: ${O.source.sourceId}`)}else if(j==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K}),m.info(`Kept: ${O.source.sourceId}`);else if(w)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId}`)}}return m.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as v6}from"@contractspec/lib.contracts-transformers/openapi";async function Tz($,b){let{fs:n,logger:A}=b,{specPath:m,openApiSource:y,ignoreDescriptions:W,ignoreTags:w,ignoreTransport:j}=$;A.info(`Validating specs against OpenAPI: ${y}`);let B=await v6(y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});A.info(`Parsed ${B.operations.length} operations from ${B.info.title}`);let S=new Map;for(let O of B.operations)S.set(O.operationId,O);let Q=[],Z=0,X=0,Y=await n.stat(m),G=[];if(Y.isDirectory){let O=await n.glob({pattern:"**/*.ts",cwd:m,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});G.push(...O)}else G.push(m);A.info(`Found ${G.length} spec files to validate`);for(let O of G)try{let K=await n.readFile(O),J=K.match(/operationId:\s*['"]([^'"]+)['"]/)||K.match(/name:\s*['"]([^'"]+)['"]/)||K.match(/export\s+const\s+(\w+)Spec\s*=/);if(!J||!J[1]){A.debug(`Could not extract operationId from ${O}`);continue}let U=J[1];Z++;let H;if(H=S.get(U),!H){let z=U.replace(/([A-Z])/g,"_$1").toLowerCase();H=S.get(z)}if(!H){for(let[z,L]of S)if(z.toLowerCase().includes(U.toLowerCase())||U.toLowerCase().includes(z.toLowerCase())){H=L;break}}if(!H){Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${U}`}]}),X++;continue}let q=[];if(H.deprecated&&!K.includes("deprecated"))q.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!j){let z=K.match(/path:\s*['"]([^'"]+)['"]/);if(z&&z[1]!==H.path)q.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${z[1]}", OpenAPI has "${H.path}"`})}if(!j){let z=K.match(/method:\s*['"]([^'"]+)['"]/);if(z?.[1]&&z[1].toLowerCase()!==H.method.toLowerCase())q.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${z[1]}", OpenAPI has "${H.method.toUpperCase()}"`})}let _=q.length===0;if(!_)X++;Q.push({specPath:O,operationId:H.operationId,valid:_,diffs:q})}catch(K){A.error(`Error validating ${O}: ${K}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${K instanceof Error?K.message:String(K)}`}]}),X++}let V=X===0;return A.info(`Validation ${V?"passed":"failed"}: ${Z} specs checked, ${X} with differences`),{valid:V,specsValidated:Z,specsWithDiffs:X,results:Q}}async function cz($,b,n){let{fs:A,logger:m}=$,{source:y,outputDir:W}=b,w=A.resolve(n??process.cwd(),y);if(!await A.exists(w))throw Error(`Source file not found: ${w}`);let B={...await P(A,n),outputDir:W};return m.info(`Extracting contracts from ${w} to ${W}`),zj(B,{source:w,outputDir:W,dryRun:!1},$)}var Rj={};f(Rj,{validateFeatureRefs:()=>k6,getArrayNameForSpecType:()=>Lj,detectFeatureContext:()=>g6,computeAddSpecEdit:()=>P6});function g6($,b){let n=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],A=null;for(let{type:Q,regex:Z,specType:X}of n){let Y;Z.lastIndex=0;while((Y=Z.exec($))!==null)if(!A||Y.index>A.index)A={type:Q,specType:X,index:Y.index}}if(!A)return null;let m=$.slice(A.index)+b,y=A.type;new RegExp(`${y}\\s*:\\s*\\[`).exec(m);let w=$.slice(A.index),j=0,B=!1,S="";for(let Q=0;Q<w.length;Q++){let Z=w[Q],X=Q>0?w[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&X!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")j++;else if(Z==="]"){if(j--,j===0)return null}}if(j>0)return{type:A.type,specType:A.specType};return null}function P6($,b){let n=Lj(b.type),m=new RegExp(`${n}\\s*:\\s*\\[`,"g").exec($);if(m){let y=m.index+m[0].length,W=typeof b.version==="string"?`'${b.version}'`:b.version,w=`
|
|
2108
|
+
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function Lj($){switch($){case"operation":case"command":case"query":return"operations";case"event":return"events";case"presentation":return"presentations";case"experiment":return"experiments";case"workflow":return"workflows";default:return"operations"}}function k6($,b){let n=[],A=(m,y,W)=>{for(let w of m){let j=`${w.key}.v${w.version}`;if(!y.has(j))n.push({key:w.key,version:w.version,type:W,message:`${W} ${w.key}.v${w.version} not found`})}};return A($.operations,b.operations,"Operation"),A($.events,b.events,"Event"),A($.presentations,b.presentations,"Presentation"),A($.experiments,b.experiments,"Experiment"),n}var Ej={};f(Ej,{removeReferenceStrategy:()=>JA,implementSkeletonStrategy:()=>VA,implementAiStrategy:()=>OA,generateFixLinks:()=>r6,FixService:()=>Ij,FIX_STRATEGY_STABILITY:()=>sb,FIX_STRATEGY_LABELS:()=>o6,CiOutputSchema:()=>A7});function r6($,b){let n=[];if(!$.ref||!$.file)return n;if(b.includeCli)n.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let A=$.file.startsWith("/")?$.file:`/${$.file}`,m=$.ref,y=m.line||1,W=m.column||1;n.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${A}:${y}:${W}`})}if(b.includeGithubIssue&&b.repository){let A=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),m=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
1695
2109
|
|
|
1696
2110
|
> ${$.message}
|
|
1697
2111
|
|
|
1698
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
1699
|
-
`)}function
|
|
2112
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${A}&body=${m}`})}return n}import i6 from"node:path";function E$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function M$($,b){let n=$.enrichment?.owners?.length?$.enrichment.owners.map((W)=>`'${W}'`).join(", "):"'@team'",A=$.enrichment?.tags?.length?$.enrichment.tags.map((W)=>`'${W}'`).join(", "):"",m=$.description||`TODO: Add description for ${$.key}`,y=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([W,w])=>{if(w!==void 0)y.push(`${W}: ${w}`)});return y.push(`owners: [${n}]`),y.push(`tags: [${A}]`),y.push(`description: '${m}'`),y.join(`,
|
|
2113
|
+
`)}function lb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=M$($,{kind:"'api'"});return`/**
|
|
1700
2114
|
* Capability: ${$.key}
|
|
1701
2115
|
*
|
|
1702
2116
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1707,7 +2121,7 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",labe
|
|
|
1707
2121
|
|
|
1708
2122
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
1709
2123
|
|
|
1710
|
-
export const ${
|
|
2124
|
+
export const ${n} = defineCapability({
|
|
1711
2125
|
meta: {
|
|
1712
2126
|
${A}
|
|
1713
2127
|
},
|
|
@@ -1733,7 +2147,7 @@ export const ${j} = defineCapability({
|
|
|
1733
2147
|
// }
|
|
1734
2148
|
],
|
|
1735
2149
|
});
|
|
1736
|
-
`}function
|
|
2150
|
+
`}function pb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"EventSpec",A=n.replace("Spec","Payload"),m=M$($);return`/**
|
|
1737
2151
|
* Event: ${$.key}
|
|
1738
2152
|
*
|
|
1739
2153
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1757,9 +2171,9 @@ export const ${A} = new SchemaModel({
|
|
|
1757
2171
|
},
|
|
1758
2172
|
});
|
|
1759
2173
|
|
|
1760
|
-
export const ${
|
|
2174
|
+
export const ${n} = defineEvent({
|
|
1761
2175
|
meta: {
|
|
1762
|
-
${
|
|
2176
|
+
${m}
|
|
1763
2177
|
},
|
|
1764
2178
|
|
|
1765
2179
|
payload: ${A},
|
|
@@ -1773,7 +2187,7 @@ export const ${j} = defineEvent({
|
|
|
1773
2187
|
// policy: 'archive',
|
|
1774
2188
|
// },
|
|
1775
2189
|
});
|
|
1776
|
-
`}function
|
|
2190
|
+
`}function f6($){let b=$.toLowerCase(),n=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let A of n)if(b.includes(A))return"query";return"command"}function ab($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=n.replace("Spec","Input"),m=n.replace("Spec","Output"),y=f6($.key),W=y==="query"?"defineQuery":"defineCommand",w=$.enrichment?.goal||"TODO: Define the business goal",j=$.enrichment?.context||"TODO: Provide context",B=M$($,{goal:`'${w}'`,context:`'${j}'`});return`/**
|
|
1777
2191
|
* Operation: ${$.key}
|
|
1778
2192
|
*
|
|
1779
2193
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1782,7 +2196,7 @@ export const ${j} = defineEvent({
|
|
|
1782
2196
|
* Referenced by feature: ${$.featureKey||"unknown"}
|
|
1783
2197
|
*/
|
|
1784
2198
|
|
|
1785
|
-
import { ${
|
|
2199
|
+
import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
1786
2200
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1787
2201
|
|
|
1788
2202
|
// TODO: Define input schema
|
|
@@ -1796,8 +2210,8 @@ export const ${A} = new SchemaModel({
|
|
|
1796
2210
|
});
|
|
1797
2211
|
|
|
1798
2212
|
// TODO: Define output schema
|
|
1799
|
-
export const ${
|
|
1800
|
-
name: '${
|
|
2213
|
+
export const ${m} = new SchemaModel({
|
|
2214
|
+
name: '${m}',
|
|
1801
2215
|
description: 'Output for ${$.key}',
|
|
1802
2216
|
fields: {
|
|
1803
2217
|
// Add your output fields here
|
|
@@ -1805,14 +2219,14 @@ export const ${Q} = new SchemaModel({
|
|
|
1805
2219
|
},
|
|
1806
2220
|
});
|
|
1807
2221
|
|
|
1808
|
-
export const ${
|
|
2222
|
+
export const ${n} = ${W}({
|
|
1809
2223
|
meta: {
|
|
1810
|
-
${
|
|
2224
|
+
${B}
|
|
1811
2225
|
},
|
|
1812
2226
|
|
|
1813
2227
|
io: {
|
|
1814
2228
|
input: ${A},
|
|
1815
|
-
output: ${
|
|
2229
|
+
output: ${m},
|
|
1816
2230
|
errors: {
|
|
1817
2231
|
// TODO: Define possible errors
|
|
1818
2232
|
// EXAMPLE_ERROR: {
|
|
@@ -1834,7 +2248,7 @@ export const ${j} = ${X}({
|
|
|
1834
2248
|
},
|
|
1835
2249
|
|
|
1836
2250
|
transport: {
|
|
1837
|
-
rest: { method: '${
|
|
2251
|
+
rest: { method: '${y==="command"?"POST":"GET"}' },
|
|
1838
2252
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
1839
2253
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
1840
2254
|
},
|
|
@@ -1851,7 +2265,7 @@ export const ${j} = ${X}({
|
|
|
1851
2265
|
examples: [],
|
|
1852
2266
|
},
|
|
1853
2267
|
});
|
|
1854
|
-
`}function
|
|
2268
|
+
`}function c6($){let b=$.toLowerCase();if(b.includes("doc")||b.includes("guide")||b.includes("readme"))return"markdown";if(b.includes("data")||b.includes("api")||b.includes("export"))return"data";return"web_component"}function eb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"PresentationSpec",A=c6($.key),m=M$($);return`/**
|
|
1855
2269
|
* Presentation: ${$.key}
|
|
1856
2270
|
*
|
|
1857
2271
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1862,9 +2276,9 @@ export const ${j} = ${X}({
|
|
|
1862
2276
|
|
|
1863
2277
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
1864
2278
|
|
|
1865
|
-
export const ${
|
|
2279
|
+
export const ${n} = definePresentation({
|
|
1866
2280
|
meta: {
|
|
1867
|
-
${
|
|
2281
|
+
${m}
|
|
1868
2282
|
},
|
|
1869
2283
|
|
|
1870
2284
|
kind: '${A}',
|
|
@@ -1891,7 +2305,7 @@ export const ${j} = definePresentation({
|
|
|
1891
2305
|
// focusable: true,
|
|
1892
2306
|
// },
|
|
1893
2307
|
});
|
|
1894
|
-
`}import X$ from"node:path";function TW($,W){if(W.outputDir)return Nj(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=i2($.featureFile);if(j)return Nj(j,$.ref.key,$.specType)}return Nj(X$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function i2($){let W=X$.dirname($),j=X$.parse($).root,A=0;while(W!==j&&A<50){if(X$.basename(W)==="src")return W;W=X$.dirname(W),A++}W=X$.dirname($),A=0;while(W!==j&&A<50)W=X$.dirname(W),A++;let Q=$.lastIndexOf(`${X$.sep}src${X$.sep}`);if(Q!==-1)return $.substring(0,Q+5);return null}function Nj($,W,j){let A=W.replace(/\./g,"-").toLowerCase(),Q=p2(j),Z=t2(j);return X$.join($,Z,`${A}${Q}`)}function p2($){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 t2($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var a2={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},N0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function FW($,W,j){let{fs:A,logger:Q}=j,{ref:Z,specType:X,featureKey:Y}=$;try{let B={key:Z.key,version:Z.version,specType:X,stability:N0["implement-ai"],featureKey:Y},q=B;if(W.aiConfig)try{q=await e2(B,W,Q)}catch(J){Q.warn("AI enrichment failed, falling back to skeleton",{error:J instanceof Error?J.message:String(J)})}else Q.info("No AI config provided, using skeleton with experimental stability");let H=jY(q);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=TW($,W),G=[];if(!W.dryRun){let J=s2.dirname(V);await A.mkdir(J),await A.writeFile(V,H),G.push({path:V,action:"created"})}else G.push({path:V,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:G}}catch(B){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:B instanceof Error?B.message:String(B)}}}async function e2($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Q}=await Promise.resolve().then(() => (DW(),D4)),Z=$Y(W),X=new Q(Z),Y=$.specType==="operation"?"command":$.specType,B=`${P4($.specType)} for ${$.key}`;if($.specType==="operation"){let q=await X.generateOperationSpec(B,Y);return{...$,description:q.description,enrichment:{goal:q.goal,context:q.context,owners:q.owners,tags:q.tags}}}if($.specType==="event"){let q=await X.generateEventSpec(B);return{...$,description:q.description,enrichment:{goal:`Emit ${$.key} event`,context:q.description,owners:["@team"],tags:q.tags}}}}catch(Q){j.warn("AIGenerator call failed, falling back to heuristics",{error:Q instanceof Error?Q.message:String(Q)})}let A=WY($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function $Y($){let W=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[W?.provider??"openai"]??"openai",aiModel:W?.model??"gpt-4-turbo",customApiKey:W?.apiKey??"",customEndpoint:W?.endpoint??""}}function WY($,W){let j=$.split("."),A=j[0]||"unknown",Q=j.slice(1).join(" ").replace(/_/g," "),Z=[A],X=Q.toLowerCase().split(" "),B=["auth","user","admin","api","data","search","create","update","delete"].filter((q)=>X.some((H)=>H.includes(q)));return{description:`${P4(W)} for ${A} ${Q}`,goal:`Enable ${Q} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...Z,...B]}}function jY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}function P4($){return $.charAt(0).toUpperCase()+$.slice(1)}import AY from"node:path";async function xW($,W,j){let{fs:A}=j,{ref:Q,specType:Z,featureKey:X}=$;try{let Y={key:Q.key,version:Q.version,specType:Z,stability:N0["implement-skeleton"],description:`Skeleton spec for ${Q.key}`,featureKey:X},B=QY(Y);if(!B)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${Z}`};let q=TW($,W),H=[];if(!W.dryRun){let V=AY.dirname(q);await A.mkdir(V),await A.writeFile(q,B),H.push({path:q,action:"created"})}else H.push({path:q,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function QY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}async function yW($,W,j){let{fs:A}=j,{ref:Q,featureFile:Z,specType:X}=$;try{let Y=await A.readFile(Z),B=Y,q=ZY(Y,Q,X);if(q===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Q.key}.v${Q.version} in ${Z}`};let H=[];if(!W.dryRun)await A.writeFile(Z,q),H.push({path:Z,action:"modified",previousContent:B});else H.push({path:Z,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function ZY($,W,j){if(!XY(j))return $;let Q=k4(W.key),Z=k4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Q}['"],\\s*version:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${Z}['"],\\s*key:\\s*['"]${Q}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let B of X)Y=Y.replace(B,"");return Y=YY(Y),Y}function XY($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function k4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YY($){return $.replace(/,(\s*)\]/g,"$1]")}class h4{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(W,j)=>yW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(W,j)=>xW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(W,j)=>FW(W,j,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let W=[];if($.type==="unresolved-ref")W.push("remove-reference"),W.push("implement-skeleton"),W.push("implement-ai");else if($.type==="broken-link")W.push("remove-reference"),W.push("implement-skeleton");return W}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,W){let j=this.strategies.get(W.strategy);if(!j)return{success:!1,strategy:W.strategy,issue:$,filesChanged:[],error:`Strategy ${W.strategy} not found`};return this.adapters.logger.info(`Applying fix ${W.strategy} for ${$.ref.key}`,{dryRun:W.dryRun}),j.fix($,W)}async batchFix($){let W=[],j=0,A=0;for(let Q of $.issues)try{let Z=await this.fixIssue(Q,$.options);if(W.push(Z),Z.success)j++;else A++}catch(Z){A++,W.push({success:!1,strategy:$.options.strategy,issue:Q,filesChanged:[],error:Z instanceof Error?Z.message:String(Z)})}return{total:$.issues.length,succeeded:j,failed:A,results:W}}async scanAndGetFixables($={}){return(await zW(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((j)=>this.getToFix(j)).filter((j)=>j!==null)}getToFix($){let W=this.getStrategiesForIssue($);if(W.length===0)return null;let j=this.parseFixableIssue($);if(!j)return null;return{...j,availableStrategies:W,strategies:[]}}resolveStrategy($,W){let{forceStrategy:j,preferAi:A,select:Q}=W;if(j)return Promise.resolve(j);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 Q==="function")return Q($,$.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((W)=>{return this.getToFix(W)}).filter((W)=>W!==null)}}import{z as o$}from"zod";var BY=o$.union([o$.array(o$.unknown()),o$.object({issues:o$.array(o$.unknown())}).transform(($)=>$.issues)]);import{exec as qY}from"node:child_process";import{promisify as HY}from"node:util";var VY=HY(qY),f4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function lL($,W,j={}){if($.length===0)return;let A=j.cwd??process.cwd(),Q=f4[j.type??"biome"]??f4.biome,Z=50;for(let X=0;X<$.length;X+=Z){let B=$.slice(X,X+Z).map((q)=>`"${q}"`).join(" ");try{await VY(`${Q} ${B}`,{cwd:A})}catch(q){}}}import _$ from"path";async function tL($,W){let j=_$.join(W,"contracts"),A=_$.join(W,"generated"),Q=_$.join(A,"docs"),Z=await $.fs.exists(j),X=await $.fs.exists(A);if(!Z)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await $$($,{pattern:"contracts/**/*.ts"}),B=[];if(X)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts"),w=_$.join(Q,`${b}.md`);if(!await $.fs.exists(w))B.push(b)}else if(Y.length>0)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts");B.push(b)}let q=_$.join(j,"index.ts"),H=_$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(q),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:B,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var c4={};h(c4,{runHook:()=>u4,getAvailableHooks:()=>d4});import{exec as GY}from"node:child_process";import{promisify as JY}from"node:util";var bY=JY(GY);async function u4($,W){let{fs:j,logger:A}=$,{hookName:Q,dryRun:Z=!1}=W,X=D(W.workspaceRoot);A.info(`Running hook: ${Q}`,{workspaceRoot:X,dryRun:Z});let Y=await n4(j,X);if(!Y)return{hookName:Q,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let B=Y[Q];if(!B||B.length===0)return{hookName:Q,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Q}`};A.info(`Found ${B.length} command(s) for ${Q}`);let q=[],H=!0;for(let G of B){if(Z){A.info(`[DRY RUN] Would execute: ${G}`),q.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${G}`);try{let{stdout:J,stderr:b}=await bY(G,{cwd:X,timeout:300000});q.push({command:G,success:!0,exitCode:0,stdout:J,stderr:b}),A.info(`✓ ${G}`)}catch(J){H=!1;let b=J;q.push({command:G,success:!1,exitCode:b.code??1,stdout:b.stdout??"",stderr:b.stderr??b.message??String(J)}),A.error(`✗ ${G}`,{exitCode:b.code,stderr:b.stderr});break}}let V=q.filter((G)=>G.success).length;return{hookName:Q,success:H,commandResults:q,totalCommands:B.length,successfulCommands:V,summary:H?`✓ All ${B.length} command(s) passed`:`✗ ${V}/${B.length} command(s) passed`}}async function d4($,W){let j=await n4($.fs,W);return j?Object.keys(j):[]}async function n4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let A=await $.readFile(j);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as wY,extractFromProject as KY}from"@contractspec/lib.source-extractors";import{generateOperations as _Y,generateRegistry as zY,generateSchemas as UY}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as LY}from"@contractspec/lib.source-extractors/extractors";import{dirname as OY,join as Rj}from"path";async function SY($,W,j,A){let{fs:Q,logger:Z}=j,X=A??process.cwd();LY(),Z.info(`Scanning source code in ${X}...`);let Y={readFile:(O)=>Q.readFile(O),glob:(O,K)=>Q.glob({pattern:O,cwd:K?.cwd}),exists:(O)=>Q.exists(O)},B=await wY(X,{readFile:(O)=>Q.readFile(O),glob:(O)=>Q.glob({pattern:O})});if(B.frameworks.length===0)return Z.warn("No supported frameworks detected"),{success:!1,report:IY(),errors:["No supported frameworks detected in project"]};Z.info(`Detected frameworks: ${B.frameworks.map((O)=>O.name).join(", ")}`);let{extractorRegistry:q}=await import("@contractspec/lib.source-extractors");for(let O of q.getAll())if("setFs"in O&&typeof O.setFs==="function")O.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await KY(B,H);if(!V.success||!V.ir)return{success:!1,report:MY(V.errors??[]),errors:V.errors?.map((O)=>O.message)};let G=V.ir;if(Z.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:EY(G)};let J=W.outputDir??Rj($.outputDir,"generated"),b={outputDir:J,defaultAuth:"user"},w=_Y(G,b),L=UY(G,b),z=zY(w),S=[...w,...L,z];if(!W.dryRun)for(let O of S){let K=Rj(J,O.path),_=OY(K);if(!await Q.exists(_))await Q.mkdir(_);await Q.writeFile(K,O.content),Z.info(`Created: ${K}`)}else for(let O of S)Z.info(`[DRY RUN] Would create: ${Rj(J,O.path)}`);let U={files:S,operationsGenerated:w.length,schemasGenerated:L.length,warnings:[]};return{success:!0,ir:G,generation:U,report:NY(G,U,W)}}function IY(){return`# Import Report
|
|
2308
|
+
`}import H$ from"node:path";function qA($,b){if(b.outputDir)return Fm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let n=h6($.featureFile);if(n)return Fm(n,$.ref.key,$.specType)}return Fm(H$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function h6($){let b=H$.dirname($),n=H$.parse($).root,A=0;while(b!==n&&A<50){if(H$.basename(b)==="src")return b;b=H$.dirname(b),A++}b=H$.dirname($),A=0;while(b!==n&&A<50)b=H$.dirname(b),A++;let m=$.lastIndexOf(`${H$.sep}src${H$.sep}`);if(m!==-1)return $.substring(0,m+5);return null}function Fm($,b,n){let A=b.replace(/\./g,"-").toLowerCase(),m=d6(n),y=u6(n);return H$.join($,y,`${A}${m}`)}function d6($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function u6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var o6={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},sb={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function OA($,b,n){let{fs:A,logger:m}=n,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:sb["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await t6(j,b,m)}catch(X){m.warn("AI enrichment failed, falling back to skeleton",{error:X instanceof Error?X.message:String(X)})}else m.info("No AI config provided, using skeleton with experimental stability");let S=a6(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=qA($,b),Z=[];if(!b.dryRun){let X=i6.dirname(Q);await A.mkdir(X),await A.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(j){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}async function t6($,b,n){if(n.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:m}=await Promise.resolve().then(() => (HA(),Jj)),y=l6(b),W=new m(y),w=$.specType==="operation"?"command":$.specType,j=`${Cj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await W.generateOperationSpec(j,w);return{...$,description:B.description,enrichment:{goal:B.goal,context:B.context,owners:B.owners,tags:B.tags}}}if($.specType==="event"){let B=await W.generateEventSpec(j);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(m){n.warn("AIGenerator call failed, falling back to heuristics",{error:m instanceof Error?m.message:String(m)})}let A=p6($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function l6($){let b=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[b?.provider??"openai"]??"openai",aiModel:b?.model??"gpt-4-turbo",customApiKey:b?.apiKey??"",customEndpoint:b?.endpoint??""}}function p6($,b){let n=$.split("."),A=n[0]||"unknown",m=n.slice(1).join(" ").replace(/_/g," "),y=[A],W=m.toLowerCase().split(" "),j=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>W.some((S)=>S.includes(B)));return{description:`${Cj(b)} for ${A} ${m}`,goal:`Enable ${m} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...y,...j]}}function a6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import e6 from"node:path";async function VA($,b,n){let{fs:A}=n,{ref:m,specType:y,featureKey:W}=$;try{let w={key:m.key,version:m.version,specType:y,stability:sb["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=s6(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=qA($,b),S=[];if(!b.dryRun){let Q=e6.dirname(B);await A.mkdir(Q),await A.writeFile(B,j),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function s6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}async function JA($,b,n){let{fs:A}=n,{ref:m,featureFile:y,specType:W}=$;try{let w=await A.readFile(y),j=w,B=$7(w,m,W);if(B===w)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${m.key}.v${m.version} in ${y}`};let S=[];if(!b.dryRun)await A.writeFile(y,B),S.push({path:y,action:"modified",previousContent:j});else S.push({path:y,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function $7($,b,n){if(!b7(n))return $;let m=xj(b.key),y=xj(b.version),W=[new RegExp(`\\{\\s*key:\\s*['"]${m}['"],\\s*version:\\s*['"]${y}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${y}['"],\\s*key:\\s*['"]${m}['"]\\s*\\},?\\s*`,"g")],w=$;for(let j of W)w=w.replace(j,"");return w=n7(w),w}function b7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n7($){return $.replace(/,(\s*)\]/g,"$1]")}class Ij{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,n)=>JA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,n)=>VA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,n)=>OA(b,n,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let n=this.strategies.get(b.strategy);if(!n)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),n.fix($,b)}async batchFix($){let b=[],n=0,A=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)n++;else A++}catch(y){A++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:n,failed:A,results:b}}async scanAndGetFixables($={}){return(await mA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((n)=>this.getToFix(n)).filter((n)=>n!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let n=this.parseFixableIssue($);if(!n)return null;return{...n,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:n,preferAi:A,select:m}=b;if(n)return Promise.resolve(n);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof m==="function")return m($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as Zb}from"zod";var A7=Zb.union([Zb.array(Zb.unknown()),Zb.object({issues:Zb.array(Zb.unknown())}).transform(($)=>$.issues)]);import{exec as m7}from"node:child_process";import{promisify as y7}from"node:util";var W7=y7(m7),Mj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function fL($,b,n={}){if($.length===0)return;let A=n.cwd??process.cwd(),m=Mj[n.type??"biome"]??Mj.biome,y=50;for(let W=0;W<$.length;W+=y){let j=$.slice(W,W+y).map((B)=>`"${B}"`).join(" ");try{await W7(`${m} ${j}`,{cwd:A})}catch(B){}}}import T$ from"path";async function uL($,b){let n=T$.join(b,"contracts"),A=T$.join(b,"generated"),m=T$.join(A,"docs"),y=await $.fs.exists(n),W=await $.fs.exists(A);if(!y)return{hasContracts:!1,hasGenerated:W,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let w=await j$($,{pattern:"contracts/**/*.ts"}),j=[];if(W)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts"),G=T$.join(m,`${Y}.md`);if(!await $.fs.exists(G))j.push(Y)}else if(w.length>0)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts");j.push(Y)}let B=T$.join(n,"index.ts"),S=T$.join(n,"registry.ts"),Q=w.length>0&&!await $.fs.exists(B),Z=w.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:W,missingDocs:j,missingIndex:Q,missingRegistry:Z,totalSpecs:w.length}}var Fj={};f(Fj,{runHook:()=>Tj,getAvailableHooks:()=>Dj});import{exec as w7}from"node:child_process";import{promisify as j7}from"node:util";var B7=j7(w7);async function Tj($,b){let{fs:n,logger:A}=$,{hookName:m,dryRun:y=!1}=b,W=I(b.workspaceRoot);A.info(`Running hook: ${m}`,{workspaceRoot:W,dryRun:y});let w=await Nj(n,W);if(!w)return{hookName:m,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let j=w[m];if(!j||j.length===0)return{hookName:m,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${m}`};A.info(`Found ${j.length} command(s) for ${m}`);let B=[],S=!0;for(let Z of j){if(y){A.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${Z}`);try{let{stdout:X,stderr:Y}=await B7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),A.info(`✓ ${Z}`)}catch(X){S=!1;let Y=X;B.push({command:Z,success:!1,exitCode:Y.code??1,stdout:Y.stdout??"",stderr:Y.stderr??Y.message??String(X)}),A.error(`✗ ${Z}`,{exitCode:Y.code,stderr:Y.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:m,success:S,commandResults:B,totalCommands:j.length,successfulCommands:Q,summary:S?`✓ All ${j.length} command(s) passed`:`✗ ${Q}/${j.length} command(s) passed`}}async function Dj($,b){let n=await Nj($.fs,b);return n?Object.keys(n):[]}async function Nj($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return null;try{let A=await $.readFile(n);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as S7,extractFromProject as Q7}from"@contractspec/lib.source-extractors";import{generateOperations as Z7,generateRegistry as X7,generateSchemas as Y7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as G7}from"@contractspec/lib.source-extractors/extractors";import{dirname as H7,join as vm}from"path";async function q7($,b,n,A){let{fs:m,logger:y}=n,W=A??process.cwd();G7(),y.info(`Scanning source code in ${W}...`);let w={readFile:(U)=>m.readFile(U),glob:(U,H)=>m.glob({pattern:U,cwd:H?.cwd}),exists:(U)=>m.exists(U)},j=await S7(W,{readFile:(U)=>m.readFile(U),glob:(U)=>m.glob({pattern:U})});if(j.frameworks.length===0)return y.warn("No supported frameworks detected"),{success:!1,report:O7(),errors:["No supported frameworks detected in project"]};y.info(`Detected frameworks: ${j.frameworks.map((U)=>U.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let U of B.getAll())if("setFs"in U&&typeof U.setFs==="function")U.setFs(w);let S={scope:b.scope,framework:b.framework},Q=await Q7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:V7(Q.errors??[]),errors:Q.errors?.map((U)=>U.message)};let Z=Q.ir;if(y.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:J7(Z)};let X=b.outputDir??vm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},G=Z7(Z,Y),V=Y7(Z,Y),O=X7(G),K=[...G,...V,O];if(!b.dryRun)for(let U of K){let H=vm(X,U.path),q=H7(H);if(!await m.exists(q))await m.mkdir(q);await m.writeFile(H,U.content),y.info(`Created: ${H}`)}else for(let U of K)y.info(`[DRY RUN] Would create: ${vm(X,U.path)}`);let J={files:K,operationsGenerated:G.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:U7(Z,J,b)}}function O7(){return`# Import Report
|
|
1895
2309
|
|
|
1896
2310
|
## ❌ No Supported Frameworks Detected
|
|
1897
2311
|
|
|
@@ -1908,13 +2322,13 @@ No supported frameworks were detected in the project.
|
|
|
1908
2322
|
- Next.js API Routes
|
|
1909
2323
|
|
|
1910
2324
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
1911
|
-
`}function
|
|
2325
|
+
`}function V7($){return`# Import Report
|
|
1912
2326
|
|
|
1913
2327
|
## ❌ Extraction Failed
|
|
1914
2328
|
|
|
1915
|
-
${$.map((
|
|
2329
|
+
${$.map((b)=>`- ${b.message}`).join(`
|
|
1916
2330
|
`)}
|
|
1917
|
-
`}function
|
|
2331
|
+
`}function J7($){return`# Import Analysis Report
|
|
1918
2332
|
|
|
1919
2333
|
## Summary
|
|
1920
2334
|
|
|
@@ -1934,19 +2348,19 @@ ${$.map((W)=>`- ${W.message}`).join(`
|
|
|
1934
2348
|
|
|
1935
2349
|
## Detected Frameworks
|
|
1936
2350
|
|
|
1937
|
-
${$.project.frameworks.map((
|
|
2351
|
+
${$.project.frameworks.map((b)=>`- ${b.name} (${b.confidence})`).join(`
|
|
1938
2352
|
`)}
|
|
1939
2353
|
|
|
1940
2354
|
## Endpoints
|
|
1941
2355
|
|
|
1942
|
-
${$.endpoints.map((
|
|
2356
|
+
${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).join(`
|
|
1943
2357
|
`)}
|
|
1944
2358
|
|
|
1945
2359
|
## Ambiguities (Require Review)
|
|
1946
2360
|
|
|
1947
|
-
${$.ambiguities.length>0?$.ambiguities.map((
|
|
2361
|
+
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
1948
2362
|
`):"None"}
|
|
1949
|
-
`}function
|
|
2363
|
+
`}function U7($,b,n){return`# Import Report${n.dryRun?" (Dry Run)":""}
|
|
1950
2364
|
|
|
1951
2365
|
## ✅ Import Successful
|
|
1952
2366
|
|
|
@@ -1958,9 +2372,9 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1958
2372
|
|
|
1959
2373
|
### Generation Summary
|
|
1960
2374
|
|
|
1961
|
-
- **Operations Generated**: ${
|
|
1962
|
-
- **Schemas Generated**: ${
|
|
1963
|
-
- **Total Files**: ${
|
|
2375
|
+
- **Operations Generated**: ${b.operationsGenerated}
|
|
2376
|
+
- **Schemas Generated**: ${b.schemasGenerated}
|
|
2377
|
+
- **Total Files**: ${b.files.length}
|
|
1964
2378
|
|
|
1965
2379
|
### Confidence Breakdown
|
|
1966
2380
|
|
|
@@ -1972,41 +2386,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1972
2386
|
|
|
1973
2387
|
### Next Steps
|
|
1974
2388
|
|
|
1975
|
-
1. Review generated contracts in \`${
|
|
2389
|
+
1. Review generated contracts in \`${n.outputDir??"generated/"}\`
|
|
1976
2390
|
2. Fill in TODO placeholders with business context
|
|
1977
2391
|
3. Run \`contractspec validate\` to verify contracts
|
|
1978
2392
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
1979
|
-
`}function
|
|
1980
|
-
`)}function
|
|
1981
|
-
`)}async function
|
|
1982
|
-
`)}function
|
|
1983
|
-
`)}function
|
|
1984
|
-
`)}function
|
|
1985
|
-
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let
|
|
1986
|
-
`)}function
|
|
1987
|
-
`)}async function
|
|
2393
|
+
`}function K7($,b,n={}){let A=[];if(A.push("# Import Report"),A.push(""),A.push(`**Generated**: ${new Date().toISOString()}`),A.push(""),A.push("## Summary"),A.push(""),A.push("| Metric | Count |"),A.push("|--------|-------|"),A.push(`| Files Scanned | ${$.stats.filesScanned} |`),A.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),A.push(`| Schemas Found | ${$.stats.schemasFound} |`),A.push(`| Errors Found | ${$.stats.errorsFound} |`),A.push(`| Events Found | ${$.stats.eventsFound} |`),A.push(""),n.includeStats!==!1)A.push("### Confidence"),A.push(""),A.push("| Level | Count |"),A.push("|-------|-------|"),A.push(`| High | ${$.stats.highConfidence} |`),A.push(`| Medium | ${$.stats.mediumConfidence} |`),A.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),A.push("");A.push("### Frameworks Detected"),A.push("");for(let m of $.project.frameworks)A.push(`- **${m.name}** (${m.confidence})`);if(A.push(""),n.includeEndpoints!==!1&&$.endpoints.length>0){A.push("## Endpoints"),A.push(""),A.push("| Method | Path | Kind | Confidence |"),A.push("|--------|------|------|------------|");for(let m of $.endpoints)A.push(`| ${m.method} | \`${m.path}\` | ${m.kind} | ${m.confidence.level} |`);A.push("")}if(n.includeSchemas!==!1&&$.schemas.length>0){A.push("## Schemas"),A.push(""),A.push("| Name | Type | Confidence |"),A.push("|------|------|------------|");for(let m of $.schemas)A.push(`| ${m.name} | ${m.schemaType} | ${m.confidence.level} |`);A.push("")}if(b&&n.includeIssues!==!1){A.push("## Verification"),A.push(""),A.push("| Status | Count |"),A.push("|--------|-------|"),A.push(`| Valid | ${b.summary.validEndpoints} |`),A.push(`| Warnings | ${b.summary.warningEndpoints} |`),A.push(`| Errors | ${b.summary.errorEndpoints} |`),A.push("");let m=b.endpointResults.filter((y)=>y.issues.length>0);if(m.length>0){A.push("### Issues"),A.push("");for(let y of m){A.push(`#### ${y.endpoint.method} ${y.endpoint.path}`);for(let W of y.issues){let w=W.severity==="error"?"❌":W.severity==="warning"?"⚠️":"ℹ️";if(A.push(`- ${w} **${W.code}**: ${W.message}`),W.suggestion)A.push(` - *Suggestion*: ${W.suggestion}`)}A.push("")}}}if(n.includeAmbiguities!==!1&&$.ambiguities.length>0){A.push("## Ambiguities (Require Review)"),A.push("");for(let m of $.ambiguities)if(A.push(`- **${m.type}** (${m.itemId}): ${m.description}`),m.suggestion)A.push(` - *Suggestion*: ${m.suggestion}`);A.push("")}return A.push("## Next Steps"),A.push(""),A.push("1. Review generated contracts in the output directory"),A.push("2. Fill in TODO placeholders with business context"),A.push("3. Run `contractspec validate` to verify contracts"),A.push("4. Move stable contracts from `generated/` to `curated/`"),A.push(""),A.join(`
|
|
2394
|
+
`)}function _7($,b){let n=[];n.push(""),n.push("\uD83D\uDCCA Summary"),n.push(` Files scanned: ${$.stats.filesScanned}`),n.push(` Endpoints: ${$.stats.endpointsFound}`),n.push(` Schemas: ${$.stats.schemasFound}`),n.push(""),n.push("\uD83D\uDCC8 Confidence"),n.push(` High: ${$.stats.highConfidence}`),n.push(` Medium: ${$.stats.mediumConfidence}`),n.push(` Low: ${$.stats.lowConfidence}`),n.push(""),n.push("\uD83D\uDD27 Frameworks");for(let A of $.project.frameworks)n.push(` • ${A.name}`);if(n.push(""),b)n.push("✅ Verification"),n.push(` Valid: ${b.summary.validEndpoints}`),n.push(` Warnings: ${b.summary.warningEndpoints}`),n.push(` Errors: ${b.summary.errorEndpoints}`),n.push("");return n.join(`
|
|
2395
|
+
`)}async function z7($,b,n){let{logger:A}=n,m=[],y=[...$.ambiguities];A.info(`Verifying ${$.endpoints.length} endpoints...`);for(let w of $.endpoints){let j=[];if(w.confidence.level==="low"||w.confidence.level==="ambiguous")j.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${w.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!w.input&&(w.method==="POST"||w.method==="PUT"||w.method==="PATCH"))j.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!w.output)j.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(b.checkDuplicates){if($.endpoints.filter((Q)=>Q.id!==w.id&&Q.path===w.path&&Q.method===w.method).length>0)j.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${w.method} ${w.path} found`,severity:"error"})}if(b.checkConflicts){let S=L7(w,$.endpoints);for(let Q of S)j.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=j.some((S)=>S.severity==="error")?"error":j.some((S)=>S.severity==="warning")?"warning":"valid";m.push({endpoint:w,status:B,issues:j})}if(b.validateSchemas){for(let w of $.schemas)if(!w.fields||w.fields.length===0)y.push({type:"schema",itemId:w.id,description:`Schema ${w.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:w.source})}let W={totalEndpoints:m.length,validEndpoints:m.filter((w)=>w.status==="valid").length,warningEndpoints:m.filter((w)=>w.status==="warning").length,errorEndpoints:m.filter((w)=>w.status==="error").length,totalIssues:m.reduce((w,j)=>w+j.issues.length,0)};return A.info(`Verification complete: ${W.validEndpoints} valid, ${W.warningEndpoints} warnings, ${W.errorEndpoints} errors`),{valid:W.errorEndpoints===0,endpointResults:m,ambiguities:y,summary:W}}function L7($,b){let n=[],A=$.path.split("/").filter(Boolean);for(let m of b){if(m.id===$.id)continue;if(m.method!==$.method)continue;let y=m.path.split("/").filter(Boolean);if(y.length!==A.length)continue;let W=!0;for(let w=0;w<A.length;w++){let j=A[w]??"",B=y[w]??"",S=j.startsWith(":")||j.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&j!==B){W=!1;break}}if(W&&$.path!==m.path)n.push(m)}return n}function YR($,b="feature-map",n={}){switch(b){case"feature-map":return km($,n);case"orphans":return R7($,n);case"dependencies":return C7($,n);case"full":return x7($,n);default:return km($,n)}}function km($,b){let{direction:n="LR",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=$.features;if(b.featureKeys&&b.featureKeys.length>0)W=W.filter((Z)=>b.featureKeys?.includes(Z.key));let w=0,j=!1;if(W.length>0){y.push(" subgraph features [Features]");for(let Z of W){if(w>=m)break;let X=v(`F_${Z.key}`),Y=Z.title??Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let B=gm(W,"operations",$.inventory);if(B.length>0&&w<m){y.push(" subgraph ops [Operations]");for(let Z of B){if(w>=m)break;let X=v(`O_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let S=gm(W,"events",$.inventory);if(S.length>0&&w<m){y.push(" subgraph events [Events]");for(let Z of S){if(w>=m)break;let X=v(`E_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let Q=gm(W,"presentations",$.inventory);if(Q.length>0&&w<m){y.push(" subgraph presentations [Presentations]");for(let Z of Q){if(w>=m)break;let X=v(`P_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}for(let Z of W){let X=v(`F_${Z.key}`);for(let Y of Z.operations){let G=v(`O_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}for(let Y of Z.events){let G=v(`E_${Y.key}_v${Y.version}`);y.push(` ${X} -.-> ${G}`)}for(let Y of Z.presentations){let G=v(`P_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}}if(j)y.push(` note["... and more (truncated at ${m} nodes)"]`);return y.join(`
|
|
2396
|
+
`)}function R7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=new Set,w=new Set,j=new Set;for(let Q of $.features){for(let Z of Q.operations)W.add(`${Z.key}.v${Z.version}`);for(let Z of Q.events)w.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)j.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){y.push(" subgraph features [Features]");for(let Q of $.features){if(B>=m)break;let Z=v(`F_${Q.key}`);y.push(` ${Z}["${B$(Q.title??Q.key)}"]`),B++}y.push(" end")}if($.orphanedSpecs.length>0){y.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=m)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}let S=[];for(let Q of W){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"operation",key:Z,version:X})}for(let Q of w){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"event",key:Z,version:X})}for(let Q of j){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"presentation",key:Z,version:X})}if(S.length>0&&B<m){y.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=m)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let X of Q.operations){let Y=v(`operation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}for(let X of Q.events){let Y=v(`event_${X.key}_v${X.version}`);y.push(` ${Z} -.-> ${Y}`)}for(let X of Q.presentations){let Y=v(`presentation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}}return y.join(`
|
|
2397
|
+
`)}function C7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=0;for(let w of $.features){if(W>=m)break;let j=v(`F_${w.key}`);y.push(` ${j}["${B$(w.title??w.key)}"]`),W++;for(let B of w.operations){if(W>=m)break;let S=v(`O_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.events){if(W>=m)break;let S=v(`E_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} -.-> ${S}`),W++}for(let B of w.presentations){if(W>=m)break;let S=v(`P_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);y.push(` ${S} --> ${Q}`)}}return y.join(`
|
|
2398
|
+
`)}function x7($,b){let n=km($,b);if($.orphanedSpecs.length===0)return n;let A=n.split(`
|
|
2399
|
+
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let m of $.orphanedSpecs.slice(0,20)){let y=v(`orphan_${m.type}_${m.key}_v${m.version}`),W=`${m.key}.v${m.version}`;A.push(` ${y}["${B$(W)}"]:::orphan`)}return A.push(" end"),A.push(" classDef orphan stroke-dasharray: 5 5"),A.join(`
|
|
2400
|
+
`)}function gm($,b,n){let A=new Set,m=[];for(let y of $)for(let W of y[b]){let w=`${W.key}.v${W.version}`;if(!A.has(w))A.add(w),m.push(W)}return m}function Pm($){let b=$.match(/^(.+)\.v(\d+)$/);if(!b)return[void 0,void 0];return[b[1],b[2]]}function v($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function B$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as I7,specToMarkdown as D$}from"@contractspec/module.workspace";function HR($,b,n){let A=[];if(n.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))A.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))A.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(n.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))A.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))A.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(b))A.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return A}function qR($,b){let n=[];n.push(`# Verification Report: ${$.meta.key}`),n.push("");let A=b.filter((W)=>W.severity==="error"),m=b.filter((W)=>W.severity==="warning"),y=b.filter((W)=>W.severity==="info");if(n.push("## Summary"),n.push(""),n.push(`- Errors: ${A.length}`),n.push(`- Warnings: ${m.length}`),n.push(`- Info: ${y.length}`),n.push(""),A.length>0){n.push("## Errors"),n.push("");for(let W of A)n.push(`- ❌ **${W.category}**: ${W.message}`);n.push("")}if(m.length>0){n.push("## Warnings"),n.push("");for(let W of m)n.push(`- ⚠️ **${W.category}**: ${W.message}`);n.push("")}if(y.length>0){n.push("## Info"),n.push("");for(let W of y)n.push(`- ℹ️ **${W.category}**: ${W.message}`);n.push("")}return n.join(`
|
|
2401
|
+
`)}async function UR($,b){let n=[];n.push(D$($,"context"));let A=await j$(b),m=async(y)=>{let W=A.find((j)=>j.key===y.name&&j.version===y.version);if(!W)return null;return(await I7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){n.push(`
|
|
1988
2402
|
## Operations (${$.operations.length})
|
|
1989
|
-
`);for(let
|
|
2403
|
+
`);for(let y of $.operations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
1990
2404
|
|
|
1991
|
-
*Spec not found*`);
|
|
2405
|
+
*Spec not found*`);n.push("---")}}if($.events?.length){n.push(`
|
|
1992
2406
|
## Events (${$.events.length})
|
|
1993
|
-
`);for(let
|
|
2407
|
+
`);for(let y of $.events){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
1994
2408
|
|
|
1995
|
-
*Spec not found*`);
|
|
2409
|
+
*Spec not found*`);n.push("---")}}if($.presentations?.length){n.push(`
|
|
1996
2410
|
## Presentations (${$.presentations.length})
|
|
1997
|
-
`);for(let
|
|
1998
|
-
|
|
1999
|
-
*Spec not found*`);
|
|
2000
|
-
`)}function
|
|
2001
|
-
`)}function
|
|
2002
|
-
`)}function
|
|
2003
|
-
`)}
|
|
2004
|
-
`).
|
|
2005
|
-
${
|
|
2006
|
-
${
|
|
2007
|
-
${
|
|
2008
|
-
|
|
2009
|
-
`).trimEnd()}function $3(){return new RegExp(`${e4($9)}[\\s\\S]*?${e4(W9)}(?:\\r?\\n)?`)}function e4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{generateArtifactsForAudience as W3,generateBiomePreset as j3}from"@contractspec/biome-config";async function kj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"biome.jsonc"),Z=$.join(A,".contractspec","biome"),X=$.join(Z,"plugins"),Y=$.join(Z,"ai"),B=W3("consumer");try{let q=await $.exists(Q);if(q&&W.interactive){if(!await j.confirm(`${Q} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Q,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Q,j3("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(B.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),B.aiRules),{target:"biome-config",filePath:Q,action:q?"merged":"created",message:q?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(q){return{target:"biome-config",filePath:Q,action:"error",message:q instanceof Error?q.message:"Unknown error"}}}async function hj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".contractsrc.json");try{let Z=await $.exists(Q),X=u$(W);if(Z){let Y=await $.readFile(Q),B=r(Y);if(!B)return{target:"cli-config",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Q,action:"skipped",message:"User skipped merge"}}let q=p(B,X);if((W.preset==="connect"||W.preset?.startsWith("builder-"))&&typeof X==="object"&&X!==null){let H={};if("connect"in X)H.connect=X.connect;if("builder"in X)H.builder=X.builder;await $.writeFile(Q,F(y1(q,H)))}else await $.writeFile(Q,F(q));return{target:"cli-config",filePath:Q,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Q,F(X)),{target:"cli-config",filePath:Q,action:"created",message:"Created CLI configuration"}}catch(Z){return{target:"cli-config",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function gj($,W,j){let A=$.join(W.workspaceRoot,".cursor","rules"),Q=$.join(A,"contractspec.mdc");try{let Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=C8(W);if(X)if(W.interactive){if(!await j.confirm(`${Q} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Q,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Q,action:"skipped",message:"File already exists"};return await $.writeFile(Q,Y),{target:"cursor-rules",filePath:Q,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(Z){return{target:"cursor-rules",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function fj($,W,j){let A=qW();try{let Q=await $.exists(A),Z=R8();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Q){let B=await $.readFile(A),q=r(B);if(!q)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let H=p(q,Z);return await $.writeFile(A,F(H)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(A,F(Z)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(Q){return{target:"mcp-claude",filePath:A,action:"error",message:Q instanceof Error?Q.message:"Unknown error"}}}async function uj($,W,j){let A=$.join(W.workspaceRoot,".cursor"),Q=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=q0();if(X){let B=await $.readFile(Q),q=r(B);if(!q)return{target:"mcp-cursor",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Q,action:"skipped",message:"User skipped merge"}}let H=p(q,Y);return await $.writeFile(Q,F(H)),{target:"mcp-cursor",filePath:Q,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Q,F(Y)),{target:"mcp-cursor",filePath:Q,action:"created",message:"Created Cursor MCP configuration"}}catch(Z){return{target:"mcp-cursor",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function dj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".vscode"),Z=$.join(Q,"settings.json");try{if(!await $.exists(Q))await $.mkdir(Q);let Y=await $.exists(Z),B=BW(W);if(Y){let q=await $.readFile(Z),H=r(q);if(!H)return{target:"vscode-settings",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:Z,action:"skipped",message:"User skipped merge"}}let V=p(H,B);if((W.preset==="builder-managed"||W.preset==="builder-hybrid")&&"contractspec.api.baseUrl"in B)V["contractspec.api.baseUrl"]=B["contractspec.api.baseUrl"];return await $.writeFile(Z,F(V)),{target:"vscode-settings",filePath:Z,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(Z,F(B)),{target:"vscode-settings",filePath:Z,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:Z,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var A3={confirm:async($,W)=>W??!0,select:async($,W)=>{return W.find((j)=>j.selected)?.value??W[0]?.value??""},multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function hS($,W,j=A3){let A=[],Q=W.targets.length>0?W.targets:X0,Z=W.workspaceRoot,X=D(Z),Y=W.packageRoot??f(Z),B=W.isMonorepo??e$(X),q=W.packageName??(B?I$(Y):void 0),H=await A9($,[Y,X]),V=W.preset??B0(H);if(W.interactive&&!W.preset)V=await j.select("Select initialization preset:",U8.map((R)=>({value:R,label:L8[R],description:O8[R],selected:R===V})));let G=W.scope??"workspace",J=Y!==X;if(B&&W.interactive&&J)G=await j.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${q??Y})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${X})`,description:"Create config files at the workspace root"}]);let b=B&&G==="package"?Y:X,w=await A9($,[b]),L={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:B,scope:G,packageName:q,preset:V,builderApiBaseUrl:W.builderApiBaseUrl??w?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:W.builderControlPlaneTokenEnvVar??w?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:W.builderLocalRuntimeId??w?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:W.builderLocalGrantedTo??w?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:W.builderLocalProviderIds??w?.builder?.localRuntime?.providerIds,connectStudioEndpoint:W.connectStudioEndpoint??w?.connect?.studio?.endpoint,connectStudioQueue:W.connectStudioQueue??w?.connect?.studio?.queue},z=S8(V,Q);if(W.interactive)z=await j.multiSelect("Select components to configure:",X0.map((R)=>({value:R,label:z8[R],selected:z.includes(R)})));let S=L.projectName;if(W.interactive&&!S){let R=G==="package"&&q?q:b.split("/").pop()??"my-project";S=await j.input("Project name:",R)}let U=L.builderApiBaseUrl;if(W.interactive&&(V==="builder-managed"||V==="builder-hybrid"))U=await j.input("Builder API base URL:",U??"https://api.contractspec.io");let{builderLocalRuntimeId:O,builderLocalGrantedTo:K}=L;if(W.interactive&&(V==="builder-local"||V==="builder-hybrid"))O=await j.input("Default local runtime target id:",O??"rt_local_daemon"),K=await j.input("Default local runtime grant target:",K??"local:operator");let _={...L,projectName:S,targets:z,builderApiBaseUrl:U,builderLocalRuntimeId:O,builderLocalGrantedTo:K};for(let R of z){let v=await Q3($,R,_,j);A.push(v)}let I=await EW($,{behavior:_.gitignoreBehavior,interactive:_.interactive,patterns:N8({preset:V}),prompts:j,root:X});if(_.gitignoreBehavior!=="skip"||I.action!=="skipped")A.push(I);let M=A.filter((R)=>R.action!=="error").length,E=A.filter((R)=>R.action==="error").length,C=B?` (${G} level)`:"";return{success:E===0,preset:V,files:A,summary:`Setup complete${C}: ${M} configured, ${E} failed.`,nextSteps:E8(_)}}async function Q3($,W,j,A){switch(W){case"agents-md":return Pj($,j,A);case"cli-config":return hj($,j,A);case"biome-config":return kj($,j,A);case"vscode-settings":return dj($,j,A);case"mcp-cursor":return uj($,j,A);case"mcp-claude":return fj($,j,A);case"cursor-rules":return gj($,j,A);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}async function A9($,W){for(let j of W){let A=$.join(j,".contractsrc.json");if(!await $.exists(A))continue;let Q=r(await $.readFile(A));if(Q)return Q}return null}import{validateBlueprint as Z3}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as X3}from"path";async function tS($,W){let{fs:j}=W,A=X3(process.cwd(),$);if(!await j.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let Q=await Q$(A),Z=Y3(Q.exports),X=Z3(Z);return{spec:Z,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Q){return{valid:!1,errors:[Q instanceof Error?Q.message:String(Q)]}}}function Y3($){let W=Object.values($).filter(B3);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function B3($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as q3,dirname as nj,join as R0}from"path";async function $I($,W,j,A,Q){let{fs:Z}=Q,X=A.implementationPath;if(!X){let H=nj($),V=q3($,".ts"),G=[R0(H,V.replace(".contracts",".handler")+".ts"),R0(H,V.replace(".presentation","")+".tsx"),R0(H,V.replace(".form",".form")+".tsx"),R0(nj(H),"handlers",V.replace(".contracts",".handler")+".ts"),R0(nj(H),"components",V.replace(".presentation","")+".tsx")];for(let J of G)if(await Z.exists(J)){X=J;break}}if(!X||!await Z.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await Z.readFile(X),q=await new g0(j).validate(W,Y);return{success:q.success,errors:q.errors||[],warnings:q.warnings||[],suggestions:q.suggestions||[],report:q.code}}import{validateBuilderBlueprint as H3,validateBuilderReadinessReport as V3,validateBuilderWorkspace as G3,validateBuilderWorkspaceSnapshot as J3}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as b3,validateExternalPatchProposal as w3,validateProviderRoutingPolicy as K3,validateRuntimeTarget as _3}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as z3,validateLayoutSlots as U3}from"@contractspec/lib.surface-runtime/spec";async function XI($,W){if(!M3($.specType))return{valid:!0,errors:[],warnings:[]};let j=v3($.filePath),A=[`${j}/package.json`,`${j}/README.md`,`${j}/src/index.ts`,$.filePath],Q=[];for(let Y of A)if(!await W.exists(Y))Q.push(`Missing package scaffold file: ${Y}`);if(Q.length>0)return{valid:!1,errors:Q,warnings:[]};let Z;try{Z=(await Q$($.filePath)).exports}catch(Y){return{valid:!1,errors:[Y instanceof Error?Y.message:String(Y)],warnings:[]}}let X=$.specType==="module-bundle"?L3(Z):$.specType==="builder-spec"?O3(Z):S3(Z);return{valid:Q.length===0&&X.errors.length===0,errors:[...Q,...X.errors],warnings:X.warnings.map((Y)=>`[${$.filePath}] ${Y}`)}}function L3($){let W=[],j=[],A=I3($,E3);if(A.length===0)return j.push(cj("module-bundle","bundle")),{errors:W,warnings:j};for(let Q of A){let Z=Object.values(Q.value.surfaces);for(let X of Z){try{U3(X)}catch(Y){W.push(`[${Q.exportName}] ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of z3(X).warnings)j.push(`[${Q.exportName}] ${Y}`)}}return{errors:W,warnings:j}}function O3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(N3(Z)){A+=1,W.push(...PW(Q,G3(Z)));continue}if(R3(Z)){A+=1,W.push(...PW(Q,H3(Z)));continue}if(C3(Z)){A+=1,W.push(...PW(Q,V3(Z)));continue}if(D3(Z))A+=1,W.push(...PW(Q,J3(Z)))}if(A===0)j.push(cj("builder-spec","builder"));return{errors:W,warnings:j}}function S3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(T3(Z)){A+=1,W.push(...kW(Q,_3(Z)));continue}if(F3(Z)){A+=1,W.push(...kW(Q,K3(Z)));continue}if(x3(Z)){A+=1,W.push(...kW(Q,b3(Z)));continue}if(y3(Z))A+=1,W.push(...kW(Q,w3(Z)))}if(A===0)j.push(cj("provider-spec","provider"));return{errors:W,warnings:j}}function I3($,W){return Object.entries($).filter(([j,A])=>j!=="__esModule"&&W(A)).map(([j,A])=>({exportName:j,value:A}))}function PW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function kW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function M3($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function E3($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function N3($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function R3($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function C3($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function D3($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function T3($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function F3($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function x3($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function y3($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function v3($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function cj($,W){return`No recognized ${W} exports were found for ${$} deep validation.`}import{validateSpecStructure as m3}from"@contractspec/module.workspace";function Q9($,W={}){let j=[],A=[],Q;if(!W.skipStructure)Q=m3($),j.push(...Q.errors),A.push(...Q.warnings);return{valid:j.length===0,structureResult:Q,errors:j,warnings:A,code:$.sourceBlock}}async function HI($,W={}){return $.map((j)=>({spec:j,...Q9(j,W)}))}async function m$($,W,j={}){let{fs:A}=W;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let Z=await A.readFile($),X=[],Y=[],B=void 0;if(!j.skipStructure){let q=await $$(W,{pattern:$});for(let H of q){let V=Q9(H,j);B=V.structureResult,X.push(...V.errors),Y.push(...V.warnings)}}return{valid:X.length===0,structureResult:B,errors:X,warnings:Y,code:Z}}async function VI($,W,j={}){let A=new Map;for(let Q of $){let Z=await m$(Q,W,j);A.set(Q,Z)}return A}import{validateConfig as P3}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as lj}from"fs/promises";import{resolve as hW}from"path";async function _I($,W,j,A){let{fs:Q}=A,Z=hW(process.cwd(),W);if(!await Q.exists(Z))return{valid:!1,errors:[`Tenant config file not found: ${Z}`]};try{let X=await k3(Z),Y=await h3(j.connections,Q),B=await g3(j.translationCatalog,Q),q=await f3(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(B)H.translationCatalogs={blueprint:[B],platform:[]};if(q)H.integrationSpecs=q;let V=P3($,X,H);return{config:X,report:V,valid:V.valid,errors:V.errors.map((G)=>`[${G.code}] ${G.path}: ${G.message}`)}}catch(X){return{valid:!1,errors:[X instanceof Error?X.message:String(X)]}}}async function k3($){if($.endsWith(".json")){let A=await lj($,"utf-8"),Q=JSON.parse(A);if(!Z9(Q))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Q}let W=await Q$($),j=Object.values(W.exports).filter(Z9);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function Z9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function q9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function h3($,W){let j=q9($);if(!j.length)return[];let A=[];for(let Q of j){let Z=hW(process.cwd(),Q);if(!await W.exists(Z)){console.warn(`Warning: Connection file not found: ${Z}`);continue}if(Z.endsWith(".json")){let Y=await lj(Z,"utf-8"),B=JSON.parse(Y);A.push(...rj(B));continue}let X=await Q$(Z);A.push(...rj(X.exports))}return A}function rj($){if(Array.isArray($)){let W=$.filter(X9);if(W.length)return W}if(X9($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((A)=>rj(A));if(j.length)return j}return[]}function X9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function g3($,W){if(!$)return;let j=hW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let Z=await lj(j,"utf-8"),X=JSON.parse(Z);if(Y9(X))return B9(X);return}let A=await Q$(j),Q=Object.values(A.exports).filter(Y9);if(Q.length===0)return;return B9(Q[0])}function Y9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function B9($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function f3($){let W=q9($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),A=new j;for(let Q of W){let{modulePath:Z,exportName:X}=u3(Q);if(!Z)continue;let Y=hW(process.cwd(),Z);try{let B=await Q$(Y),q=d3(B.exports,X);if(q)await q(A)}catch(B){console.warn(`Failed to load registrar from ${Y}: ${B}`)}}return A}function u3($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),A=W?.trim()??null,Q=j?.trim();return{modulePath:A,exportName:Q}}function d3($,W){if(W){let j=$[W];if(typeof j==="function")return j;return}if(typeof $.default==="function")return $.default;for(let j of Object.values($))if(typeof j==="function")return j;return}async function CI($,W,j={},A){let{fs:Q,logger:Z}=$,X=await Q.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],B=[],q=A?.validate??((V)=>m$(V,{fs:Q,logger:Z})),H=A?.build??((V,G)=>f$(V,{fs:Q,logger:Z},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let J={specPath:V,outputDir:G};if(j.validate)try{J.validation=await q(V)}catch(b){J.error={phase:"validate",message:b instanceof Error?b.message:String(b)},B.push(J);continue}if(!j.dryRun)try{J.build=await H(V,G)}catch(b){J.error={phase:"build",message:b instanceof Error?b.message:String(b)},B.push(J);continue}else Z.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});B.push(J)}return{specs:X,runs:B}}import{generateText as n3}from"ai";var c3=`
|
|
2411
|
+
`);for(let y of $.presentations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2412
|
+
|
|
2413
|
+
*Spec not found*`);n.push("---")}}return n.join(`
|
|
2414
|
+
`)}function E7($,b){let n=[];if(n.push(`# Implementation Guide: ${$.meta.key}`),n.push(""),n.push(`**Target Agent**: ${b}`),n.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),n.push(""),$.meta.description)n.push("## Overview"),n.push(""),n.push($.meta.description),n.push("");if($.meta.goal)n.push("## Goal"),n.push(""),n.push($.meta.goal),n.push("");if($.meta.context)n.push("## Context"),n.push(""),n.push($.meta.context),n.push("");if(n.push("## Implementation Steps"),n.push(""),$.specType==="operation"){if(n.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)n.push("2. Implement input validation according to the schema"),n.push("3. Implement the core business logic"),n.push("4. Return output matching the expected schema");if($.hasPolicy)n.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){n.push("6. Emit events on success:");for(let A of $.emittedEvents)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("7. Add error handling for expected failure cases"),n.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(n.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){n.push("2. Implement operations:");for(let A of $.operations)n.push(` - \`${A.name}\` (v${A.version})`)}if($.presentations&&$.presentations.length>0){n.push("3. Implement presentations:");for(let A of $.presentations)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("4. Wire up feature exports"),n.push("5. Add integration tests")}else n.push("1. Review the spec requirements"),n.push("2. Implement the core logic"),n.push("3. Add tests"),n.push("4. Document the implementation");if(n.push(""),n.push("## Constraints"),n.push(""),n.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)n.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)n.push(`- Tags: ${$.meta.tags.join(", ")}`);if(n.push(""),b==="cursor-cli")n.push("## Cursor Notes"),n.push(""),n.push("- Use Composer mode for multi-file changes"),n.push("- Reference this guide in your cursor rules"),n.push("- Break implementation into small, focused commits");else if(b==="claude-code")n.push("## Claude Code Notes"),n.push(""),n.push("- Use extended thinking for complex logic"),n.push("- Ask for clarification on ambiguous requirements"),n.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")n.push("## General Notes"),n.push(""),n.push("- Use inline comments to guide generation"),n.push("- Review generated code carefully");return n.push(""),n.push("## Spec Definition"),n.push(""),n.push(D$($,"full")),n.join(`
|
|
2415
|
+
`)}function M7($){let b=[];if(b.push(`# ${$.meta.key}`),b.push(""),b.push(`Description: ${$.meta.description??"No description"}`),b.push(""),b.push("## Rules"),b.push(""),$.specType==="operation"){if(b.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)b.push("- Validate input and output against schemas");if($.hasPolicy)b.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)b.push("- Emit documented events")}else if($.specType==="feature")b.push("- Implement all operations and presentations"),b.push("- Follow modular architecture");else b.push(`- Follow ${$.specType} patterns`);return b.push("- Follow project code quality standards"),b.push("- Write tests for new functionality"),b.join(`
|
|
2416
|
+
`)}function KR($,b,n="generic-mcp"){switch(b){case"guide":return E7($,n);case"rules":return M7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as T7}from"node:fs/promises";import{createRequire as D7}from"node:module";import{dirname as N7,resolve as gj}from"node:path";import{pathToFileURL as F7}from"node:url";import vj from"node:vm";import rm from"typescript";async function y$($,b={}){let n=gj(process.cwd(),$),A=b.runtime??P7();try{let m=A==="bun"?await v7(n):await g7(n);return{modulePath:n,exports:m}}catch(m){throw Error(kj(n,m))}}async function MR($,b){let n=gj(process.cwd(),$);if(!await b.exists(n))return null;return y$(n)}async function UA($,b={}){return(await y$($,b)).exports}async function Pj($,b){let n=await UA($);return rj(n,$,b)}function kj($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function rj($,b,n){if(n.isValue($))return $;for(let A of n.instanceKeys??[])if(n.isValue($[A]))return $[A];for(let A of n.factoryKeys??[]){let m=$[A];if(typeof m!=="function")continue;let y=await m();if(n.isValue(y))return y}throw Error(`${n.description} module ${b} must export a supported instance or factory.`)}async function v7($){return await import(F7($).href)}async function g7($){return await k7($)??{}}function P7(){return typeof globalThis.Bun<"u"?"bun":"node"}var TR={formatModuleLoadError:kj,resolveAuthoredModuleValue:rj};async function k7($){let b=await T7($,"utf-8"),n=rm.transpileModule(b,{compilerOptions:{module:rm.ModuleKind.CommonJS,target:rm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),A={},m={exports:A},y=D7($),W=vj.createContext({module:m,exports:A,require:y,__dirname:N7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new vj.Script(n.outputText,{filename:$}).runInContext(W),m.exports}var oj={};f(oj,{renderOnboardingGuides:()=>hm,listOnboardingTracks:()=>KA,getOnboardingTrack:()=>cm,createOnboardingConnectArtifacts:()=>p7,buildOnboardingPlan:()=>l7,ONBOARDING_TRACKS:()=>fm});var fm=[{id:"contracts",title:"Contracts",summary:"Author and validate spec-first contracts before implementation.",description:"Use ContractSpec contracts as the durable source of truth for operations, events, presentations, and validation.",reuseFamily:"contracts",adoptionQuery:"contract operation event policy presentation spec-first contracts",primaryDocsRoute:"/docs/getting-started/start-here",secondaryDocsRoutes:["/docs/guides/spec-validation-and-typing","/docs/guides/generate-docs-clients-schemas"],packages:["@contractspec/lib.contracts-spec","@contractspec/lib.schema"],recommendedCommands:["contractspec create --type operation","contractspec generate","contractspec validate","contractspec ci"],starterExample:{key:"minimal",packageRef:"@contractspec/example.minimal",title:"Minimal",summary:"Smallest reference implementation for baseline ContractSpec usage."},connectSurfaces:["cli","contract","runtime"]},{id:"ui-design",title:"UI Design",summary:"Adopt the design system and contract-backed theming flow.",description:"Use ThemeSpec, the design system, and composed UI surfaces instead of ad-hoc theme files or raw primitives.",reuseFamily:"ui",adoptionQuery:"ui design system theme tokens composed controls themes",adoptionPlatform:"web",primaryDocsRoute:"/docs/tech/contracts/themes",secondaryDocsRoutes:["/docs/guides/first-module-bundle","/docs/getting-started/installation"],packages:["@contractspec/lib.design-system","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec create --type theme","contractspec generate","contractspec validate"],starterExample:{key:"data-grid-showcase",packageRef:"@contractspec/example.data-grid-showcase",title:"Data Grid Showcase",summary:"Reference app for composed design-system tables and contract-backed UI rendering."},connectSurfaces:["cli","runtime","ui"]},{id:"knowledge",title:"Knowledge",summary:"Model trusted knowledge spaces, sources, and retrieval flows.",description:"Use knowledge spaces, bindings, and governed retrieval instead of prompt-only context injection.",reuseFamily:"sharedLibs",adoptionQuery:"knowledge spaces sources bindings retrieval canon ingestion assistant",primaryDocsRoute:"/docs/knowledge",secondaryDocsRoutes:["/docs/knowledge/spaces","/docs/knowledge/examples"],packages:["@contractspec/lib.knowledge","@contractspec/lib.ai-agent"],recommendedCommands:["contractspec create --type knowledge","contractspec validate","contractspec connect adoption resolve --family sharedLibs --stdin"],starterExample:{key:"knowledge-canon",packageRef:"@contractspec/example.knowledge-canon",title:"Knowledge Canon",summary:"Minimal contract-first knowledge space example with bindings and source samples."},advancedExample:{key:"policy-safe-knowledge-assistant",packageRef:"@contractspec/example.policy-safe-knowledge-assistant",title:"Policy-Safe Knowledge Assistant",summary:"End-to-end governed knowledge assistant with policy, locale, and learning flows."},connectSurfaces:["cli","knowledge","mcp","runtime"]},{id:"ai-agents",title:"AI Agents",summary:"Define agents, tools, approvals, and MCP-aware execution.",description:"Use the ContractSpec agent runtime and agent specs instead of ad-hoc prompt wrappers.",reuseFamily:"sharedLibs",adoptionQuery:"ai agent tools approvals mcp orchestration unified agent runtime",primaryDocsRoute:"/docs/libraries/ai-agent",secondaryDocsRoutes:["/docs/advanced/mcp","/docs/getting-started/cli"],packages:["@contractspec/lib.ai-agent","@contractspec/lib.contracts-spec"],recommendedCommands:["contractspec create --type agent","contractspec agent export --spec <path> --format opencode","contractspec validate"],starterExample:{key:"agent-console",packageRef:"@contractspec/example.agent-console",title:"Agent Console",summary:"Reference autonomous-agent workspace with runs, tools, metrics, and replay."},connectSurfaces:["agent","cli","mcp","runtime"]},{id:"learning-journey",title:"Learning Journey",summary:"Guide users through milestones, progression, and adaptive journeys.",description:"Use the learning-journey module and example family for structured onboarding and progression flows.",reuseFamily:"solutions",adoptionQuery:"learning journey onboarding progression coaching drills guided wizard",primaryDocsRoute:"/docs/guides/first-module-bundle",secondaryDocsRoutes:["/docs/getting-started/start-here"],packages:["@contractspec/module.learning-journey","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec examples list --query learning-journey","contractspec validate","contractspec doctor"],starterExample:{key:"learning-journey-ui-onboarding",packageRef:"@contractspec/example.learning-journey-ui-onboarding",title:"Learning Journey UI Onboarding",summary:"Checklist- and journey-map-based onboarding mini app."},advancedExample:{key:"learning-journey-registry",packageRef:"@contractspec/example.learning-journey-registry",title:"Learning Journey Registry",summary:"Registry and template aggregation surface for broader learning-journey compositions."},connectSurfaces:["cli","runtime","solution"]}];function KA(){return fm}function cm($){return fm.find((b)=>b.id===$)}function hm($){return{agentGuide:r7($),humanGuide:c7($)}}function r7($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let n of $.recommendations)b.push(...f7(n.track,n.reason));return b.join(`
|
|
2417
|
+
`)}function f7($,b){let n=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return[...n,""]}function c7($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((n,A)=>`${A+1}. \`${n}\``),"","## Track Guide",""];for(let n of $.recommendations)b.push(...h7(n.track,n.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let n of $.builderNextSteps)b.push(`- \`${n}\``);b.push("")}return b.join(`
|
|
2418
|
+
`)}function h7($,b){let n=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)n.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(n.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)n.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);n.push("","Commands:");for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return n.push("",`Packages: ${$.packages.map((A)=>`\`${A}\``).join(", ")}`,""),n}import{buildContext as d7}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as u7}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as o7}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function fj($,b,n,A){let m=d7({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:n,workspaceId:A}),y=await u7(o7(i7(b)),m);return{journeyContext:m,journeyPlan:y}}function cj($){if(!$||$.length===0)return[...KA()];return $.map((b)=>{let n=cm(b);if(!n)throw Error(`Unknown onboarding track: ${b}`);return n})}function hj($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function dj($){switch($){case"managed":return["contractspec builder status"];case"local":case"hybrid":return["contractspec builder status","contractspec builder local status"];case"none":default:return["contractspec init --preset builder-managed","contractspec init --preset builder-local","contractspec init --preset builder-hybrid"]}}function uj($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let n of KA()){if(n.starterExample.key===b)return n.starterExample;if(n.advancedExample?.key===b)return n.advancedExample}return}function dm($,b){return t7($,b.flatMap((n)=>n.track.connectSurfaces))}function i7($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((n)=>({defaultSurface:n.id,path:`/onboard/${n.id}`,routeId:`onboard-${n.id}`})),surfaces:Object.fromEntries($.map((n)=>[n.id,{commands:n.recommendedCommands.map((A,m)=>({commandId:`${n.id}-${m}`,intent:`Run ${A}`,title:A})),data:[{hydrateInto:"track",recipeId:`track-${n.id}`,source:{entityType:`onboarding.${n.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${n.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:n.id,title:n.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function t7($,b){return[...new Set([...$,...b])].sort()}async function l7($,b={}){let n=await s$($.fs,b),A=cj(b.selectedTracks),m=hj(n.config),W=[...await Promise.all(A.map(async(Y)=>{let G=await Jb($,{config:n.config,cwd:n.cwd,family:Y.reuseFamily,packageRoot:n.packageRoot,platform:Y.adoptionPlatform,query:Y.adoptionQuery,workspaceRoot:n.workspaceRoot});return{reason:G.reason,resolution:G,score:G.selected?.score??0,selected:!1,track:Y}}))].sort((Y,G)=>G.score-Y.score).map((Y,G)=>({...Y,selected:G===0})),w=W[0]?.track;if(!w)throw Error("No onboarding tracks are available.");let{journeyContext:j,journeyPlan:B}=await fj(w,A,n.workspaceRoot,n.packageRoot),S=uj(w,b.forcedExampleKey)??w.starterExample,Q=a7(["contractspec onboard",...w.recommendedCommands,"contractspec doctor"]),Z=dj(m),X={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:m,builderNextSteps:Z,config:n.config,cwd:n.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:j,journeyPlan:B,nextCommands:Q,packageRoot:n.packageRoot,primaryTrack:w,recommendations:W,selectedExample:S,workspaceRoot:n.workspaceRoot};return{...X,guides:hm(X)}}async function p7($,b){if(!b.config.connect?.enabled)return;let n=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,A=[b.agentGuidePath,b.humanGuidePath],m=await fb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot}),y=await ob($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((W)=>W.track.id).join(", ")}`,steps:b.recommendations.map((W)=>({commands:W.track.recommendedCommands,paths:A,summary:`Adopt ${W.track.title}`})),touchedPaths:A},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot});return{contextPack:{...m,affectedSurfaces:dm(m.affectedSurfaces,b.recommendations)},planPacket:{...y.planPacket,affectedSurfaces:dm(y.planPacket.affectedSurfaces,b.recommendations)}}}function a7($){return[...new Set($)]}var ij=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],e7=[...ij,{name:"@contractspec/lib.schema",description:"Extended schema utilities and common types"},{name:"@contractspec/app.cli-contractspec",dev:!0,description:"ContractSpec CLI for validation, scaffolding, and code generation"},{name:"typescript",dev:!0,description:"TypeScript compiler for type checking"}];function um($){return $==="minimal"?ij:e7}function om($){return $.filter((b)=>!b.dev)}function im($){return $.filter((b)=>b.dev)}import{exec as s7}from"node:child_process";import{promisify as $Z}from"node:util";var bZ=$Z(s7),nZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function bC($,b,n=nZ){let A=um(b.mode),m=om(A),y=im(A),W=[],w=[],j=[],B=$.join(b.workspaceRoot,"package.json");if(!await $.exists(B))return{success:!1,installed:[],skipped:[],errors:[{name:"package.json",action:"error",message:"No package.json found. Run `npm init` first."}],summary:"No package.json found in workspace root."};let Q=await $.readFile(B),Z=JSON.parse(Q),X=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),Y=a$(b.workspaceRoot),G=m.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),V=y.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let J=[...G,...V];return{success:!0,installed:J.map((U)=>({name:U.name,action:"installed",message:`Would install: ${U.description}`,dev:U.dev})),skipped:w,errors:[],summary:`Dry run: would install ${J.length} package(s), skip ${w.length}.`}}if(!b.skipPrompts&&(G.length>0||V.length>0)){let J=G.length+V.length;if(!await n.confirm(`Install ${J} package(s) using ${Y}?`))return{success:!0,installed:[],skipped:[...w,...G.map((H)=>({name:H.name,action:"skipped",message:"User cancelled"})),...V.map((H)=>({name:H.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(G.length>0){let J=await tj(G,Y,b.workspaceRoot,!1);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}if(V.length>0){let J=await tj(V,Y,b.workspaceRoot,!0);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}let O=j.length===0,K=O?`Successfully installed ${W.length} package(s), skipped ${w.length}.`:`Installed ${W.length}, skipped ${w.length}, failed ${j.length}.`;return{success:O,installed:W,skipped:w,errors:j,summary:K}}async function tj($,b,n,A){let m=[],y=$.map((W)=>W.version?`${W.name}@${W.version}`:W.name);try{let w=`${hy(b,A)} ${y.join(" ")}`;await bZ(w,{cwd:n,timeout:120000});for(let j of $)m.push({name:j.name,action:"installed",message:j.description,dev:A})}catch(W){let w=W instanceof Error?W.message:String(W);for(let j of $)m.push({name:j.name,action:"error",message:`Failed to install: ${w}`,dev:A})}return m}async function nC($,b){let n=$.join(b,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A);return"@contractspec/lib.contracts-spec"in{...m.dependencies,...m.devDependencies}}catch{return!1}}function AC($){let b=um($),n=[];n.push(`ContractSpec ${$} installation:`),n.push("");let A=om(b);if(A.length>0){n.push("Dependencies:");for(let y of A)n.push(` • ${y.name} - ${y.description}`)}let m=im(b);if(m.length>0){n.push(""),n.push("Dev Dependencies:");for(let y of m)n.push(` • ${y.name} - ${y.description}`)}return n.join(`
|
|
2419
|
+
`)}import{RegeneratorService as AZ}from"@contractspec/lib.contracts-spec/regenerator";function SC($){return new AZ({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class _A{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,n;try{n=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(A){throw Error(`Registry request failed: ${b} (${A instanceof Error?A.message:String(A)})`)}if(!n.ok){let A=await n.text().catch(()=>"");throw Error(`Registry request failed: ${n.status} ${n.statusText} ${A}`)}return await n.json()}}function tm($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function ZC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Adding spec to registry: ${$}`,{registryUrl:m}),await new _A({registryUrl:m}).getJson(`/specs/add?path=${encodeURIComponent($)}`),A.info("Spec added to registry successfully")}async function XC($,b){let{logger:n}=b,A=tm($.registryUrl);n.info("Listing specs from registry",{registryUrl:A});let m=new _A({registryUrl:A}),y=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",W=await m.getJson(`/specs${y}`);return n.info(`Found ${W.length} specs`),W}async function YC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Searching registry: ${$}`,{registryUrl:m});let W=await new _A({registryUrl:m}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return A.info(`Found ${W.length} results`),W}class mZ{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:n}=$,A=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${A.join(", ")}...`);try{let m=this.fs.join(n,b.rulesDir??".rules");if(!await this.fs.exists(m))return{success:!1,files:[],errors:[`Rules directory not found: ${m}`]};let W=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${W}`);let w=[];for(let j of A){let B=this.getTargetFileName(j);if(B){let S=this.fs.join(n,B);w.push(S)}}return{success:!0,files:w,logs:[`Successfully synchronized rules to ${w.length} targets.`]}}catch(m){let y=m instanceof Error?m.message:String(m);return this.logger.error(`Rule synchronization failed: ${y}`),{success:!1,files:[],errors:[y]}}}async generateConfig($){let{config:b}=$,n={rules:(b.rules??[]).map((A)=>this.fs.join(b.rulesDir??".rules",A)),targets:$.targets||b.targets};return JSON.stringify(n,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}function zA($,b,n,A){let m=$n(b,n),y=yZ(n);if(y.test($))return $.replace(y,m);if(A&&lm($)===lm(A))return m;return`${m}${$}`}function $n($,b){let n=lm($);return`${b.startMarker}
|
|
2420
|
+
${b.note}
|
|
2421
|
+
${n}
|
|
2422
|
+
${b.endMarker}
|
|
2423
|
+
`}function lm($){return $.replace(/\r\n/g,`
|
|
2424
|
+
`).trimEnd()}function yZ($){return new RegExp(`${lj($.startMarker)}[\\s\\S]*?${lj($.endMarker)}(?:\\r?\\n)?`)}function lj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var WZ="<!-- contractspec:init:agents:start -->",wZ="<!-- contractspec:init:agents:end -->",jZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",pj={endMarker:wZ,note:jZ,startMarker:WZ};async function pm($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"AGENTS.md");try{let y=await $.exists(m),W=Bw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:m,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(m,zA(w,W,pj,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,$n(W,pj)),{target:"agents-md",filePath:m,action:"created",message:"Created AI agent guide"}}catch(y){return{target:"agents-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}import{generateArtifactsForAudience as BZ,generateBiomePreset as SZ}from"@contractspec/biome-config";async function am($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"biome.jsonc"),y=$.join(A,".contractspec","biome"),W=$.join(y,"plugins"),w=$.join(y,"ai"),j=BZ("consumer");try{let B=await $.exists(m);if(B&&b.interactive){if(!await n.confirm(`${m} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:m,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(W),await $.mkdir(w),await $.writeFile(m,SZ("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(j.plugins))await $.writeFile($.join(W,S),Q);return await $.writeFile($.join(w,"consumer.md"),j.aiRules),{target:"biome-config",filePath:m,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:m,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function em($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".contractsrc.json");try{let y=await $.exists(m),W=Wb(b);if(y){let w=await $.readFile(m),j=a(w);if(!j)return{target:"cli-config",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=b$(j,W);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof W==="object"&&W!==null){let S={};if("connect"in W)S.connect=W.connect;if("builder"in W)S.builder=W.builder;await $.writeFile(m,N(D0(B,S)))}else await $.writeFile(m,N(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,N(W)),{target:"cli-config",filePath:m,action:"created",message:"Created CLI configuration"}}catch(y){return{target:"cli-config",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function sm($,b,n){let A=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(A,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=jw(b);if(W)if(b.interactive){if(!await n.confirm(`${m} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:m,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:m,action:"skipped",message:"File already exists"};return await $.writeFile(m,w),{target:"cursor-rules",filePath:m,action:W?"merged":"created",message:W?"Updated Cursor rules":"Created Cursor rules"}}catch(y){return{target:"cursor-rules",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function $y($,b,n){let A=ln();try{let m=await $.exists(A),y=ww();if(b.interactive){if(!await n.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(A),B=a(j);if(!B)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let S=b$(B,y);return await $.writeFile(A,N(S)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(A,N(y)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:A,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function by($,b,n){let A=$.join(b.workspaceRoot,".cursor"),m=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=Mb();if(W){let j=await $.readFile(m),B=a(j);if(!B)return{target:"mcp-cursor",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=b$(B,w);return await $.writeFile(m,N(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,N(w)),{target:"mcp-cursor",filePath:m,action:"created",message:"Created Cursor MCP configuration"}}catch(y){return{target:"mcp-cursor",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}var QZ="<!-- contractspec:init:usage:start -->",ZZ="<!-- contractspec:init:usage:end -->",XZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:ZZ,note:XZ,startMarker:QZ};async function ny($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"USAGE.md");try{let y=await $.exists(m),W=Sw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:m,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(m,zA(w,W,aj,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,$n(W,aj)),{target:"usage-md",filePath:m,action:"created",message:"Created usage guide"}}catch(y){return{target:"usage-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function Ay($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=tn(b);if(w){let B=await $.readFile(y),S=a(B);if(!S)return{target:"vscode-settings",filePath:y,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=b$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,N(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,N(j)),{target:"vscode-settings",filePath:y,action:"created",message:"Created VS Code settings"}}catch(W){return{target:"vscode-settings",filePath:y,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var YZ={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((n)=>n.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((n)=>n.selected!==!1).map((n)=>n.value),input:async($,b)=>b??""},GZ={"agents-md":pm,"biome-config":am,"cli-config":em,"cursor-rules":sm,"mcp-claude":$y,"mcp-cursor":by,"usage-md":ny,"vscode-settings":Ay},HZ={findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$};async function bx($,b,n=YZ,A={}){let m=[],y=b.targets.length>0?b.targets:xb,W={...HZ,...A.workspace},w={...GZ,...A.targets},j=A.setupGitignore??ZA,B=b.workspaceRoot,S=W.findWorkspaceRoot(B),Q=b.packageRoot??W.findPackageRoot(B),Z=b.isMonorepo??W.isMonorepo(S),X=b.packageName??(Z?W.getPackageName(Q):void 0),Y=await ej($,[Q,S]),G=b.preset??Eb(Y);if(b.interactive&&!b.preset)G=await n.select("Select initialization preset:",$w.map((g)=>({value:g,label:bw[g],description:nw[g],selected:g===G})));let V=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)V=await n.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${X??Q})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${S})`,description:"Create config files at the workspace root"}]);let K=Z&&V==="package"?Q:S,J=await ej($,[K]),U={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:V,packageName:X,preset:G,builderApiBaseUrl:b.builderApiBaseUrl??J?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??J?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??J?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??J?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??J?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??J?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??J?.connect?.studio?.queue},H=Aw(G,y);if(b.interactive)H=await n.multiSelect("Select components to configure:",xb.map((g)=>({value:g,label:sW[g],selected:H.includes(g)})));let q=U.projectName;if(b.interactive&&!q){let g=V==="package"&&X?X:K.split("/").pop()??"my-project";q=await n.input("Project name:",g)}let _=U.builderApiBaseUrl;if(b.interactive&&G.startsWith("builder-"))_=await n.input("Builder API base URL:",_??"https://api.contractspec.io");let{builderLocalRuntimeId:z,builderLocalGrantedTo:L}=U;if(b.interactive&&(G==="builder-local"||G==="builder-hybrid"))z=await n.input("Default local runtime target id:",z??"rt_local_daemon"),L=await n.input("Default local runtime grant target:",L??"local:operator");let C={...U,projectName:q,targets:H,builderApiBaseUrl:_,builderLocalRuntimeId:z,builderLocalGrantedTo:L};for(let g of H){let iA=await qZ($,g,C,n,w);m.push(iA)}let D=await j($,{behavior:C.gitignoreBehavior,interactive:C.interactive,patterns:Ww({preset:G}),prompts:n,root:S});if(C.gitignoreBehavior!=="skip"||D.action!=="skipped")m.push(D);let F=m.filter((g)=>g.action!=="error").length,E=m.filter((g)=>g.action==="error").length,r=Z?` (${V} level)`:"";return{success:E===0,preset:G,files:m,summary:`Setup complete${r}: ${F} configured, ${E} failed.`,nextSteps:yw(C)}}async function qZ($,b,n,A,m){let y=m[b];if(y)return y($,n,A);return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}async function ej($,b){for(let n of b){let A=$.join(n,".contractsrc.json");if(!await $.exists(A))continue;let m=a(await $.readFile(A));if(m)return m}return null}import{validateBlueprint as OZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as VZ}from"path";async function Hx($,b){let{fs:n}=b,A=VZ(process.cwd(),$);if(!await n.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let m=await y$(A),y=JZ(m.exports),W=OZ(y);return{spec:y,report:W,valid:W.valid,errors:W.errors.map((w)=>`[${w.code}] ${w.path}: ${w.message}`)}}catch(m){return{valid:!1,errors:[m instanceof Error?m.message:String(m)]}}}function JZ($){let b=Object.values($).filter(UZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function UZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as KZ,dirname as my,join as bn}from"path";async function Jx($,b,n,A,m){let{fs:y}=m,W=A.implementationPath;if(!W){let S=my($),Q=KZ($,".ts"),Z=[bn(S,Q.replace(".contracts",".handler")+".ts"),bn(S,Q.replace(".presentation","")+".tsx"),bn(S,Q.replace(".form",".form")+".tsx"),bn(my(S),"handlers",Q.replace(".contracts",".handler")+".ts"),bn(my(S),"components",Q.replace(".presentation","")+".tsx")];for(let X of Z)if(await y.exists(X)){W=X;break}}if(!W||!await y.exists(W))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let w=await y.readFile(W),B=await new On(n).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as _Z,validateBuilderReadinessReport as zZ,validateBuilderWorkspace as LZ,validateBuilderWorkspaceSnapshot as RZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as CZ,validateExternalPatchProposal as xZ,validateProviderRoutingPolicy as IZ,validateRuntimeTarget as EZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as MZ,validateLayoutSlots as TZ}from"@contractspec/lib.surface-runtime/spec";async function Rx($,b){if(!gZ($.specType))return{valid:!0,errors:[],warnings:[]};let n=iZ($.filePath),A=[`${n}/package.json`,`${n}/README.md`,`${n}/src/index.ts`,$.filePath],m=[];for(let w of A)if(!await b.exists(w))m.push(`Missing package scaffold file: ${w}`);if(m.length>0)return{valid:!1,errors:m,warnings:[]};let y;try{y=(await y$($.filePath)).exports}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)],warnings:[]}}let W=$.specType==="module-bundle"?DZ(y):$.specType==="builder-spec"?NZ(y):FZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function DZ($){let b=[],n=[],A=vZ($,PZ);if(A.length===0)return n.push(yy("module-bundle","bundle")),{errors:b,warnings:n};for(let m of A){let y=Object.values(m.value.surfaces);for(let W of y){try{TZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of MZ(W).warnings)n.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:n}}function NZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(kZ(y)){A+=1,b.push(...LA(m,LZ(y)));continue}if(rZ(y)){A+=1,b.push(...LA(m,_Z(y)));continue}if(fZ(y)){A+=1,b.push(...LA(m,zZ(y)));continue}if(cZ(y))A+=1,b.push(...LA(m,RZ(y)))}if(A===0)n.push(yy("builder-spec","builder"));return{errors:b,warnings:n}}function FZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(hZ(y)){A+=1,b.push(...RA(m,EZ(y)));continue}if(dZ(y)){A+=1,b.push(...RA(m,IZ(y)));continue}if(uZ(y)){A+=1,b.push(...RA(m,CZ(y)));continue}if(oZ(y))A+=1,b.push(...RA(m,xZ(y)))}if(A===0)n.push(yy("provider-spec","provider"));return{errors:b,warnings:n}}function vZ($,b){return Object.entries($).filter(([n,A])=>n!=="__esModule"&&b(A)).map(([n,A])=>({exportName:n,value:A}))}function LA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function RA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function gZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function PZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function kZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function rZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function fZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function cZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function hZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function dZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function uZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function oZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function iZ($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function yy($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as tZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as lZ}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as pZ}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as aZ}from"@contractspec/module.workspace";async function $1($,b={}){let n=[],A=[],m;if(!b.skipStructure){m=aZ($),n.push(...m.errors),A.push(...m.warnings);let y=await eZ($);n.push(...y.errors),A.push(...y.warnings)}return{valid:n.length===0,structureResult:m,errors:n,warnings:A,code:$.sourceBlock}}async function Nx($,b={}){return Promise.all($.map(async(n)=>({spec:n,...await $1(n,b)})))}async function l$($,b,n={}){let{fs:A}=b;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let y=await A.readFile($),W=[],w=[],j=void 0;if(!n.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await $1(S,n);j=Q.structureResult,W.push(...Q.errors),w.push(...Q.warnings)}}return{valid:W.length===0,structureResult:j,errors:W,warnings:w,code:y}}async function Fx($,b,n={}){let A=new Map;for(let m of $){let y=await l$(m,b,n);A.set(m,y)}return A}async function eZ($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await y$($.filePath);if($.specType==="app-config"){let m=sZ(b.exports,$),y=tZ(m);return{errors:y.errors.map((W)=>sj(W)),warnings:[...y.warnings,...y.info].map((W)=>sj(W))}}if($.specType==="feature"){let m=$2(b.exports,$),y=lZ(m);return{errors:y.issues.filter((W)=>W.level==="error").map((W)=>CA(W)),warnings:y.issues.filter((W)=>W.level!=="error").map((W)=>CA(W))}}let n=b2(b.exports,$),A=pZ(n);return{errors:A.issues.filter((m)=>m.level==="error").map((m)=>CA(m)),warnings:A.issues.filter((m)=>m.level!=="error").map((m)=>CA(m))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function sZ($,b){return Wy($,b.exportName,n2)}function $2($,b){return Wy($,b.exportName,A2)}function b2($,b){return Wy($,b.exportName,m2)}function Wy($,b,n){if(b&&n($[b]))return $[b];let A=Object.values($).find(n);if(!A)throw Error("Expected authored module to export a compatible spec value.");return A}function n2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function A2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function m2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function sj($){let b=$.code?`[${$.code}] `:"",n=$.path?`${$.path}: `:"";return`${b}${n}${$.message}`}function CA($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as y2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as jy}from"fs/promises";import{resolve as xA}from"path";async function fx($,b,n,A){let{fs:m}=A,y=xA(process.cwd(),b);if(!await m.exists(y))return{valid:!1,errors:[`Tenant config file not found: ${y}`]};try{let W=await W2(y),w=await w2(n.connections,m),j=await j2(n.translationCatalog,m),B=await B2(n.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=y2($,W,S);return{config:W,report:Q,valid:Q.valid,errors:Q.errors.map((Z)=>`[${Z.code}] ${Z.path}: ${Z.message}`)}}catch(W){return{valid:!1,errors:[W instanceof Error?W.message:String(W)]}}}async function W2($){if($.endsWith(".json")){let A=await jy($,"utf-8"),m=JSON.parse(A);if(!b1(m))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return m}let b=await y$($),n=Object.values(b.exports).filter(b1);if(n.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return n[0]}function b1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function y1($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((n)=>n.trim()).filter(Boolean)}async function w2($,b){let n=y1($);if(!n.length)return[];let A=[];for(let m of n){let y=xA(process.cwd(),m);if(!await b.exists(y)){console.warn(`Warning: Connection file not found: ${y}`);continue}if(y.endsWith(".json")){let w=await jy(y,"utf-8"),j=JSON.parse(w);A.push(...wy(j));continue}let W=await y$(y);A.push(...wy(W.exports))}return A}function wy($){if(Array.isArray($)){let b=$.filter(n1);if(b.length)return b}if(n1($))return[$];if($&&typeof $==="object"){let n=Object.values($).flatMap((A)=>wy(A));if(n.length)return n}return[]}function n1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function j2($,b){if(!$)return;let n=xA(process.cwd(),$);if(!await b.exists(n))return;if(n.endsWith(".json")){let y=await jy(n,"utf-8"),W=JSON.parse(y);if(A1(W))return m1(W);return}let A=await y$(n),m=Object.values(A.exports).filter(A1);if(m.length===0)return;return m1(m[0])}function A1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function m1($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function B2($){let b=y1($);if(!b.length)return;let{IntegrationSpecRegistry:n}=await import("@contractspec/lib.contracts-integrations"),A=new n;for(let m of b){let{modulePath:y,exportName:W}=S2(m);if(!y)continue;let w=xA(process.cwd(),y);try{let j=await y$(w),B=Q2(j.exports,W);if(B)await B(A)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return A}function S2($){if(!$)return{modulePath:null};let[b,n]=$.split("#"),A=b?.trim()??null,m=n?.trim();return{modulePath:A,exportName:m}}function Q2($,b){if(b){let n=$[b];if(typeof n==="function")return n;return}if(typeof $.default==="function")return $.default;for(let n of Object.values($))if(typeof n==="function")return n;return}async function ex($,b,n={},A){let{fs:m,logger:y}=$,W=await m.glob({pattern:n.pattern}),w=n.outputDirs?.length?n.outputDirs:[void 0],j=[],B=A?.validate??((Q)=>l$(Q,{fs:m,logger:y})),S=A?.build??((Q,Z)=>yb(Q,{fs:m,logger:y},Z?{...b,outputDir:Z}:b,{...n.buildOptions??{},outputDir:Z}));for(let Q of W)for(let Z of w){let X={specPath:Q,outputDir:Z};if(n.validate)try{X.validation=await B(Q)}catch(Y){X.error={phase:"validate",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}if(!n.dryRun)try{X.build=await S(Q,Z)}catch(Y){X.error={phase:"build",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}else y.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});j.push(X)}return{specs:W,runs:j}}import{generateText as Z2}from"ai";var X2=`
|
|
2010
2425
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2011
2426
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2012
2427
|
|
|
@@ -2024,7 +2439,7 @@ Generate scenarios covering:
|
|
|
2024
2439
|
- Happy path (valid input, successful execution)
|
|
2025
2440
|
- Edge cases (boundary values, optional fields)
|
|
2026
2441
|
- Error cases (invalid input, business rule violations)
|
|
2027
|
-
`.trim();class
|
|
2442
|
+
`.trim();class Y2{logger;defaultModel;generateTextImpl;constructor($,b,n=Z2){this.logger=$;this.defaultModel=b;this.generateTextImpl=n}async generateTests($,b={}){let n=b.model??this.defaultModel;if(!n)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let A=`
|
|
2028
2443
|
Generate a TestSpec for the following Operation:
|
|
2029
2444
|
|
|
2030
2445
|
\`\`\`json
|
|
@@ -2033,23 +2448,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2033
2448
|
|
|
2034
2449
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2035
2450
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2036
|
-
`.trim();try{let{text:
|
|
2037
|
-
`)}function
|
|
2038
|
-
`)}function
|
|
2039
|
-
`);for(let
|
|
2040
|
-
`)}function
|
|
2451
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:n,system:X2,prompt:A});this.logUsage(y);let W=this.parseResponse(m);return this.enrichSpec(W,$)}catch(m){throw this.logger.error("Failed to generate tests",{error:m}),m}}parseResponse($){try{let b=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(b)}catch(b){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,b){let n={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},A={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:n,target:A,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let b=$;this.logger.debug(`AI Usage: ${b.promptTokens} prompt + ${b.completionTokens} completion = ${b.totalTokens} total tokens`)}}import{OperationSpecRegistry as W1}from"@contractspec/lib.contracts-spec";import{TestRunner as w1}from"@contractspec/lib.contracts-spec/tests";import{resolve as By}from"path";async function WI($,b){let n=new w1({registry:b}),A=[],m=0,y=0;for(let W of $){let w=await n.run(W);A.push(w),m+=w.passed,y+=w.failed}return{results:A,passed:m,failed:y}}async function wI($,b,n){let{logger:A}=n,m;if(b.registry)m=await H2(By(b.registry));else m=new W1,A.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let y=new w1({registry:m}),W=[],w=!0;for(let j of $)try{let B=By(j),S=await UA(B),Q=j1(S);if(Q.length===0){A.warn(`No TestSpec exports found in ${j}`);continue}for(let Z of Q){A.info(`Running ${Z.meta.key}...`);let X=await y.run(Z);if(W.push(X),X.failed>0)w=!1,A.error(`${Z.meta.key} failed (${X.failed}/${X.scenarios.length})`);else A.info(`${Z.meta.key} passed (${X.passed}/${X.scenarios.length})`)}}catch(B){A.error(`Failed to load/run spec ${j}: ${B instanceof Error?B.message:String(B)}`),w=!1}return{results:W,passed:w}}async function jI($,b){let n=[];for(let A of $)try{let m=By(A),y=await UA(m),W=j1(y);n.push(...W)}catch(m){b.logger.warn(`Failed to load tests from ${A}: ${m instanceof Error?m.message:String(m)}`)}return n}function j1($){let b=[];for(let n of Object.values($))if(G2(n))b.push(n);return b}function G2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function H2($){return Pj($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof W1,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as nn}from"@contractspec/module.workspace";import{IndentationText as q2,Node as Xb,Project as O2,QuoteKind as V2,SyntaxKind as J2}from"ts-morph";function U2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function HI($,b,n={}){let{fs:A,logger:m}=b;if(!await A.exists($))return{specPath:$,specInfo:U2($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let W=await A.readFile($),w;if(n.content!==void 0)w=n.content;else if(n.fields?.length)w=K2(W,n.fields);else return{specPath:$,specInfo:nn(W,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!n.skipValidation){await A.writeFile($,w);let j=await l$($,b);if(j.errors.length>0)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:j.errors,warnings:j.warnings};if(j.warnings.length>0&&!n.allowWarnings)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:j.warnings};return m.info(`Updated spec: ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:j.warnings}}return await A.writeFile($,w),m.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:[]}}function K2($,b){let A=new O2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:q2.TwoSpaces,quoteKind:V2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=z2(A);if(!m)return $;for(let y of b)_2(m,y);return A.getFullText()}function _2($,b){let n=b.key.split(".").map((w)=>w.trim()).filter(Boolean);if(n.length===0)return;let A=$;for(let w of n.slice(0,-1)){if(!A.getProperty(w))A.addPropertyAssignment({name:w,initializer:"{}"});let B=A.getPropertyOrThrow(w);if(!Xb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!Xb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(J2.ObjectLiteralExpression);if(!Q)return;A=Q}let m=n[n.length-1];if(!m)return;let y=L2(b.value),W=A.getProperty(m);if(W&&Xb.isPropertyAssignment(W)){W.setInitializer(y);return}A.addPropertyAssignment({name:m,initializer:y})}function z2($){for(let b of $.getVariableDeclarations()){let n=b.getInitializer();if(!n)continue;if(Xb.isObjectLiteralExpression(n))return n;if(Xb.isCallExpression(n)){let A=n.getArguments()[0];if(A&&Xb.isObjectLiteralExpression(A))return A}}return}function L2($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var z1={};f(z1,{getPackageUpgradeCommand:()=>O1,getDefaultVersioningConfig:()=>EA,getDefaultHooksConfig:()=>MA,applyGuidedUpgrade:()=>_1,applyConfigUpgrades:()=>q1,analyzeUpgrades:()=>IA,analyzeGuidedUpgrade:()=>Xy});import{GeneratedReleaseManifestSchema as U1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as N2,DEFAULT_CONTRACTSRC as F2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function B1($){return $.packages.map((b)=>{let n=b.version?`@${b.version}`:"";return`- ${b.name}${n} (${b.releaseType})`})}function S1($){return $.map((b)=>` - ${b}`)}function Sy($,b){return $.audiences.filter((n)=>b.includes(n.kind)).map((n)=>`- ${R2(n.kind)}: ${n.summary}`)}function Q1($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...B1($),...Sy($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));return b.join(`
|
|
2452
|
+
`)}function Z1($){let b=[`### ${$.summary}`,...B1($),...Sy($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`);return b.join(`
|
|
2453
|
+
`)}function X1($){let b=[`### ${$.summary}`,...Sy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2454
|
+
`);for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`),b.push(...S1(n.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let n of $.upgradeSteps)b.push(` - [${n.level}] ${n.title}: ${n.summary}`),b.push(...n.instructions.map((A)=>` - ${A}`))}return b.join(`
|
|
2455
|
+
`)}function Qy($){return["# Patch Notes","",...$.releases.map(Q1)].join(`
|
|
2041
2456
|
|
|
2042
|
-
`)}function
|
|
2457
|
+
`)}function Zy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[Z1(b),"",X1(b)])].join(`
|
|
2043
2458
|
|
|
2044
|
-
`)}function
|
|
2459
|
+
`)}function Y1($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...S1(b.instructions)].join(`
|
|
2045
2460
|
`)).join(`
|
|
2046
|
-
`)}function
|
|
2047
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2048
|
-
`)}import{compareVersions as
|
|
2049
|
-
`),A.info("Configuration upgraded",{sectionsUpgraded:
|
|
2050
|
-
`),!0}async function
|
|
2051
|
-
`),!0}async function
|
|
2052
|
-
`),
|
|
2461
|
+
`)}function Yb($,b){let n=b.targetPackages.map((A)=>`${A.name}: ${A.currentVersion??"unknown"} -> ${A.targetVersion??"latest"}`).join(`
|
|
2462
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",n||"- No package version targets were inferred.","","Required steps:",Y1(b)].join(`
|
|
2463
|
+
`)}function R2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as H1,countUpgradePlanStepLevels as C2,createAgentPromptBundles as x2,dedupeUpgradePlanSteps as I2,sortReleaseManifest as G1}from"@contractspec/lib.contracts-spec";function E2($,b){if(b.length===0)return G1($);let n=new Map(b.map((A)=>[A.name,A.currentVersion??"0.0.0"]));return G1({...$,releases:$.releases.filter((A)=>A.packages.some((m)=>{let y=n.get(m.name);if(!y||!m.version)return!1;return H1(m.version,y)===1}))})}function An($,b,n,A){let m=E2($,b),y=M2(m,b),W=I2(m.flatMap((S)=>S.upgradeSteps)),w=C2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=x2(j,n,A);return{...j,agentPrompts:B}}function M2($,b){let n=new Map(b.map((m)=>[m.name,m.currentVersion])),A=new Map;for(let m of $)for(let y of m.packages){let W=n.get(y.name),w=A.get(y.name);if(!w){A.set(y.name,{name:y.name,currentVersion:W,targetVersion:y.version});continue}if(y.version&&w.targetVersion&&H1(y.version,w.targetVersion)===1)w.targetVersion=y.version}return Array.from(A.values()).sort((m,y)=>m.name.localeCompare(y.name))}async function IA($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=a$(y);A.info("Analyzing available upgrades...",{workspaceRoot:y,packageRoot:m,packageManager:W});let w=await T2(n,m),j=await D2(n,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function T2($,b){let n=$.join(b,"package.json");if(!await $.exists(n))return[];try{let A=await $.readFile(n),m=JSON.parse(A),y=m.dependencies??{},W=m.devDependencies??{},w=[],j={...y,...W};for(let[B,S]of Object.entries(j))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))w.push({name:B,currentVersion:S,isDevDependency:!!W[B]});return w}catch{return[]}}async function D2($,b,n){let A=$.join(b,".contractsrc.json"),m=Cb({configRoot:b,workspaceRoot:n});if(!await $.exists(A))return[];try{let y=await $.readFile(A),W=JSON.parse(y),w=[],j=W.$schema;if(!j||j!==m)w.push({key:"$schema",currentValue:j,suggestedValue:m,isNew:!j});if(!W.versioning)w.push({key:"versioning",currentValue:void 0,suggestedValue:EA(),isNew:!0});else if(W.versioning.integrateWithChangesets===void 0)w.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!W.hooks)w.push({key:"hooks",currentValue:void 0,suggestedValue:MA(),isNew:!0});if(!W.release)w.push({key:"release",currentValue:void 0,suggestedValue:V1(),isNew:!0});if(!W.upgrade)w.push({key:"upgrade",currentValue:void 0,suggestedValue:J1(),isNew:!0});return w}catch{return[]}}async function q1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=Cb({configRoot:m,workspaceRoot:y});if(b.dryRun)A.info("Dry run - no changes will be made");let w=n.join(m,".contractsrc.json");if(!await n.exists(w))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let j=await n.readFile(w),B=JSON.parse(j),S=0,Q=B.$schema;if(!Q||Q!==W)B.$schema=W,S++;if(!B.versioning)B.versioning=EA(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=MA(),S++;if(!B.release)B.release=V1(),S++;if(!B.upgrade)B.upgrade=J1(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await n.writeFile(w,JSON.stringify(B,null,2)+`
|
|
2464
|
+
`),A.info("Configuration upgraded",{sectionsUpgraded:S});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:S,summary:b.dryRun?`Would upgrade ${S} config section(s)`:`Upgraded ${S} config section(s)`}}catch(j){let B=j instanceof Error?j.message:String(j);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function O1($,b,n){let A=n?b.map((m)=>`${m.name}@latest`).join(" "):b.map((m)=>m.name).join(" ");switch($){case"bun":return`bun add ${A}`;case"pnpm":return`pnpm add ${A}`;case"yarn":return`yarn add ${A}`;default:return`npm install ${A}`}}function EA(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function MA(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function V1(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function J1(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var v2="**/*.{ts,tsx,js,jsx,mjs,cjs}",K1=F2.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Xy($,b){let{fs:n}=$,A=c(b.workspaceRoot),m=I(b.workspaceRoot),y=await P2(n,A,m),W=await g2(n,A,m,b.manifestPaths??y.manifestPaths),w=await IA($,{workspaceRoot:A,dryRun:b.dryRun}),j=[b.agentTarget??y.defaultAgentTarget??"codex"],B=An(W.manifest,w.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),j,Yb),S=k2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:r2(S)}}async function _1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=await Xy($,b),W=[];if(!b.dryRun){for(let j of y.plan.steps){if(j.level!=="auto")continue;for(let B of j.autofixes??[])if(await f2(n,m,B))W.push(B.id)}A.info("Applied guided upgrade autofixes",{count:W.length,workspaceRoot:m})}let w=y.plan.steps.filter((j)=>j.level!=="auto");return{success:!0,packagesUpgraded:W.filter((j)=>j.startsWith("pkg:")).length,configSectionsUpgraded:W.filter((j)=>j.startsWith("config:")).length,summary:b.dryRun?`Would apply ${y.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${W.length} deterministic upgrade autofix(es)`,appliedAutofixes:W,remainingSteps:w,humanChecklist:y.humanChecklist,promptBundle:y.plan.agentPrompts[0],plan:y.plan,manifestPath:y.manifestPath}}async function g2($,b,n,A){let m=A??["generated/releases/upgrade-manifest.json"],y=Array.from(new Set([b,n]));for(let W of m){let w=W.startsWith("/")?[W]:y.map((j)=>$.join(j,W));for(let j of w){if(!await $.exists(j))continue;let B=U1.parse(JSON.parse(await $.readFile(j)));return{path:j,manifest:B}}}return{manifest:U1.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function P2($,b,n){for(let A of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(n,".contractsrc.json")]))){if(!await $.exists(A))continue;try{let m=JSON.parse(await $.readFile(A)),y=N2.safeParse(m);if(y.success)return{...K1,...y.data.upgrade}}catch{continue}}return K1}function k2($,b,n){let A=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;A.push({id:`pkg:${S.name}`,kind:"package-json",title:`Update ${S.name}`,summary:`Update ${S.name} to ${Q.targetVersion}`,packageName:S.name,dependencyType:S.isDevDependency?"devDependencies":"dependencies",from:S.currentVersion,to:Q.targetVersion})}let m=n.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),y=[];if(A.length>0)y.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:A.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:A.map((S)=>S.packageName??""),autofixes:A});if(m.length>0)y.push({id:"upgrade-contractsrc-config",title:"Refresh .contractsrc.json defaults",summary:"Bring workspace release and upgrade config in line with current defaults.",level:"auto",instructions:m.map((S)=>`${S.configPath} -> updated`),autofixes:m});let W=[...y,...$.steps],w=W.filter((S)=>S.level==="auto").length,j=W.filter((S)=>S.level==="assisted").length,B=W.filter((S)=>S.level==="manual").length;return{...$,steps:W,autofixCount:w,assistedCount:j,manualCount:B,agentPrompts:An({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),Yb).agentPrompts}}function r2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function f2($,b,n){switch(n.kind){case"package-json":return c2($,b,n);case"contractsrc":return h2($,b,n);case"import-rewrite":return d2($,b,n);case"codemod":return!1}}async function c2($,b,n){let A=$.join(b,"package.json");if(!await $.exists(A))return!1;let m=JSON.parse(await $.readFile(A)),y=n.dependencyType??"dependencies",W=m[y]??{};if(!n.packageName||!n.to||!W[n.packageName])return!1;return W[n.packageName]=n.to,m[y]=W,await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2465
|
+
`),!0}async function h2($,b,n){let A=$.join(b,".contractsrc.json"),m=await $.exists(A)?JSON.parse(await $.readFile(A)):{};if(!n.configPath)return!1;return u2(m,n.configPath,n.value),await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2466
|
+
`),!0}async function d2($,b,n){if(!n.from||!n.to)return!1;let A=await $.glob({pattern:n.path??v2,cwd:b,absolute:!0}),m=!1;for(let y of A){let W=await $.readFile(y);if(!W.includes(n.from))continue;await $.writeFile(y,W.split(n.from).join(n.to)),m=!0}return m}function u2($,b,n){let A=b.split("."),m=$;for(let W of A.slice(0,-1)){let w=m[W];if(!w||typeof w!=="object"||Array.isArray(w))m[W]={};m=m[W]}let y=A.at(-1);if(y)m[y]=n}import{existsSync as Yy,mkdirSync as o2,readFileSync as i2,renameSync as t2,statSync as l2,writeFileSync as p2}from"fs";import{dirname as a2,join as e2}from"path";var s2=".contractspec/verification-cache.json",L1=1;class R1{filePath;cache;isDirty=!1;constructor($,b){let n=b??process.cwd();this.filePath=$??e2(n,s2),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Yy(this.filePath))return;let $=i2(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==L1)return;for(let[n,A]of Object.entries(b.entries))this.cache.set(n,A)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=a2(this.filePath);if(!Yy($))o2($,{recursive:!0});let b={version:L1,entries:Object.fromEntries(this.cache.entries())},n=`${this.filePath}.tmp`;p2(n,JSON.stringify(b,null,2),"utf-8"),t2(n,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(Yy(this.filePath))$=l2(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function vI($,b){return new R1($,b)}class C1{cache=new Map;async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[b,n]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(n).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function PI(){return new C1}class x1{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let b=this.getStorageKey($);return this.store.get(b)??null}async set($,b){let n=this.getStorageKey($);if(await this.store.update(n,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),n=this.keyIndex.has($);if(n)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return n}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function rI($){return new x1($)}import{createHash as $X}from"crypto";var I1={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function E1($){return $X("sha256").update($).digest("hex")}function M1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function bX($){try{let b=$.split("|"),n=new Map;for(let W of b){let[w,j]=W.split(":");if(w&&j)n.set(w,j)}let A=n.get("spec"),m=n.get("impl"),y=n.get("tier");if(!A||!m||!y)return null;return{specHash:A,implHash:m,tier:y,aiModelVersion:n.get("model")}}catch{return null}}function nX($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class T1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...I1,...b},this.stats={hits:0,misses:0}}createKey($,b,n,A){return{specHash:E1($),implHash:E1(b),tier:n,aiModelVersion:n==="ai_review"?A:void 0}}async lookup($){let b=M1($),n=await this.storage.get(b);if(!n)return this.stats.misses++,{hit:!1,reason:"not_found"};if(n.meta.expiresAt){let A=new Date(n.meta.expiresAt).getTime();if(Date.now()>A)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(n.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(n.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&n.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:n}}async store($,b,n={}){let A=M1($),m=nX($.tier,this.config),y={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+m).toISOString(),dependencies:n.dependencies??[],specName:n.specName,implPath:n.implPath}};await this.storage.set(A,y),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),n=0;for(let A of b){let m=await this.storage.get(A);if(!m)continue;if(m.meta.dependencies.includes($))await this.storage.delete(A),n++;if(m.meta.specName===$||m.meta.implPath===$)await this.storage.delete(A),n++}return n}async invalidateForSpec($){let b=await this.storage.keys(),n=0;for(let A of b){let m=bX(A);if(m&&m.specHash.startsWith($.substring(0,16)))await this.storage.delete(A),n++}return n}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let b=[];for(let A of $){let m=await this.storage.get(A);if(m)b.push({key:A,createdAt:new Date(m.meta.createdAt).getTime()})}b.sort((A,m)=>A.createdAt-m.createdAt);let n=b.length-this.config.maxEntries;for(let A=0;A<n;A++){let m=b[A];if(m)await this.storage.delete(m.key)}}}function lI($,b){return new T1($,b)}import{generateVerificationPrompt as AX}from"@contractspec/lib.contracts-spec/llm";function mX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let j=JSON.parse(b[1]);return{compliant:j.passed??!1,confidence:(j.score??0)/100,findings:(j.issues??[]).map((B)=>({category:String(B.category??"semantic"),severity:String(B.severity??"warning"),message:String(B.message??""),location:B.location?String(B.location):void 0,suggestion:B.suggestion?String(B.suggestion):void 0})),rawResponse:$}}catch{}let n=[],A=$.split(`
|
|
2467
|
+
`),m="info";for(let j of A){let B=j.toLowerCase();if(B.includes("error")||B.includes("critical"))m="error";else if(B.includes("warning")||B.includes("should"))m="warning";else if(B.includes("info")||B.includes("note"))m="info";let S=j.match(/^[-*•]\s*(.+)$/),Q=j.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)n.push({category:"semantic",severity:m,message:Z})}}let y=n.some((j)=>j.severity==="error"),W=!y,w=y?0.3:n.length===0?0.9:0.7;return{compliant:W,confidence:w,findings:n,rawResponse:$}}async function D1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2053
2468
|
{
|
|
2054
2469
|
"passed": true,
|
|
2055
2470
|
"score": 50,
|
|
@@ -2066,23 +2481,23 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2066
2481
|
],
|
|
2067
2482
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2068
2483
|
}
|
|
2069
|
-
\`\`\``;try{let
|
|
2484
|
+
\`\`\``;try{let n=b.aiProvider??"anthropic";if(n==="anthropic"){let{anthropic:A}=await import("@ai-sdk/anthropic"),{generateText:m}=await import("ai");return(await m({model:A("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(n==="openai"){let{openai:A}=await import("@ai-sdk/openai"),{generateText:m}=await import("ai");return(await m({model:A("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${n}`)}catch(n){return`\`\`\`json
|
|
2070
2485
|
{
|
|
2071
2486
|
"passed": false,
|
|
2072
2487
|
"score": 0,
|
|
2073
2488
|
"issues": [
|
|
2074
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2489
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${n instanceof Error?n.message:"Unknown error"}" }
|
|
2075
2490
|
],
|
|
2076
2491
|
"summary": "AI verification encountered an error"
|
|
2077
2492
|
}
|
|
2078
|
-
\`\`\``}}async function
|
|
2493
|
+
\`\`\``}}async function mn($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=AX(n,A),w=await D1(W.taskPrompt,b),j=mX(w),B=j.findings.map((X)=>({severity:X.severity,category:"semantic",message:X.message,location:X.location?{file:X.location}:m?{file:m}:void 0,suggestion:X.suggestion})),S=Math.round(j.confidence*100),Q=j.compliant,Z=j.findings.filter((X)=>X.suggestion).map((X)=>X.suggestion);return{tier:"ai_review",passed:Q,score:S,issues:B,suggestions:Z,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Q?1:0}},meta:{specName:n.meta.key,specVersion:n.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-y}}}function TA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];if(n.includes("console.log"))y.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(n.includes("// TODO")||n.includes("// FIXME"))y.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(b.policy.auth!=="anonymous"&&!n.includes("auth"))y.push({severity:"warning",category:"semantic",message:`Spec requires ${b.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let W=y.filter((j)=>j.severity==="error").length===0?80:40,w=y.filter((j)=>j.severity==="error").length===0;return{tier:"ai_review",passed:w,score:W,issues:y,suggestions:y.filter((j)=>j.suggestion).map((j)=>j.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:w?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}function yX($,b){return`You are analyzing a code implementation against its specification.
|
|
2079
2494
|
|
|
2080
2495
|
## Spec Schema Fields
|
|
2081
2496
|
${$}
|
|
2082
2497
|
|
|
2083
2498
|
## Implementation Code
|
|
2084
2499
|
\`\`\`typescript
|
|
2085
|
-
${
|
|
2500
|
+
${b}
|
|
2086
2501
|
\`\`\`
|
|
2087
2502
|
|
|
2088
2503
|
## Task
|
|
@@ -2122,42 +2537,43 @@ Match types:
|
|
|
2122
2537
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2123
2538
|
- "mismatch": Different meaning despite similar naming
|
|
2124
2539
|
- "missing": Spec field not found in implementation
|
|
2125
|
-
`}function
|
|
2126
|
-
`)}function
|
|
2127
|
-
`),A=[];for(let
|
|
2128
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,
|
|
2129
|
-
`)}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
|
|
2130
|
-
`)}function
|
|
2131
|
-
`)}function
|
|
2132
|
-
`),
|
|
2133
|
-
`).trim()||void 0,
|
|
2134
|
-
${
|
|
2540
|
+
`}function WX($){let b=[],n=(A,m)=>{try{let W=A?._def?.shape;if(W&&typeof W==="function"){let w=W();for(let[j,B]of Object.entries(w)){let Q=B?._def?.typeName??"unknown";b.push(`- ${j}: ${String(Q).replace("Zod","").toLowerCase()} (${m})`)}}}catch{b.push(`- [unable to extract ${m} fields]`)}};if($.io.input)n($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))n($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2541
|
+
`)}function wX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let n=JSON.parse(b[1]);return{fieldMappings:(n.fieldMappings??[]).map((A)=>({specField:String(A.specField??""),specType:String(A.specType??"unknown"),implementationField:A.implementationField?String(A.implementationField):void 0,implementationType:A.implementationType?String(A.implementationType):void 0,match:A.match??"missing",aiConfidence:typeof A.aiConfidence==="number"?A.aiConfidence:0.5,suggestion:A.suggestion?String(A.suggestion):void 0})),intentAlignment:{score:typeof n.intentAlignment?.score==="number"?n.intentAlignment.score:50,issues:Array.isArray(n.intentAlignment?.issues)?n.intentAlignment.issues:[],suggestions:Array.isArray(n.intentAlignment?.suggestions)?n.intentAlignment.suggestions:[]},semanticIssues:(n.semanticIssues??[]).map((A)=>({category:String(A.category??"semantic"),severity:A.severity??"warning",message:String(A.message??""),suggestion:A.suggestion?String(A.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function N1($,b={}){let{spec:n,implementationCode:A}=$,m=WX(n),y=yX(m,A),W=await D1(y,b);return wX(W)}async function jX($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=await mn($,b),w;if(b.aiApiKey)try{w=await N1($,b)}catch{}if(w){let j=[];for(let Z of w.fieldMappings)if(Z.match==="missing")j.push({severity:"error",category:"semantic",message:`Missing field: '${Z.specField}' (${Z.specType}) not found in implementation`,suggestion:Z.suggestion??`Add field '${Z.specField}' to implementation`});else if(Z.match==="mismatch")j.push({severity:"warning",category:"semantic",message:`Field mismatch: '${Z.specField}' has incorrect implementation as '${Z.implementationField}'`,suggestion:Z.suggestion});else if(Z.match==="compatible"&&Z.aiConfidence<0.8)j.push({severity:"info",category:"semantic",message:`Field naming: '${Z.specField}' implemented as '${Z.implementationField}' (compatible but not exact)`,suggestion:Z.suggestion});for(let Z of w.intentAlignment.issues)j.push({severity:"warning",category:"semantic",message:Z});for(let Z of w.semanticIssues)j.push({severity:Z.severity,category:"semantic",message:Z.message,suggestion:Z.suggestion});W.issues=[...W.issues,...j];let B=w.fieldMappings.length,S=w.fieldMappings.filter((Z)=>Z.match==="exact"||Z.match==="compatible").length;if(B>0){let Z=Math.round(S/B*100);W.score=Math.round((W.score+Z)/2),W.coverage.fields={total:B,implemented:S}}if(j.some((Z)=>Z.severity==="error"))W.passed=!1;W.suggestions=[...W.suggestions,...w.intentAlignment.suggestions]}return W.meta={...W.meta,duration:Date.now()-y},W}import{isEmitDeclRef as BX}from"@contractspec/lib.contracts-spec/operations";function SX($,b){let n=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),A=$.toLowerCase(),m=n.filter((B)=>A.includes(B)),y=n.length>0?m.length/n.length:0,W=b.key.toLowerCase().replace(/\s+/g,""),w=A.includes(W)||A.includes(`test('${b.key.toLowerCase()}'`)||A.includes(`it('${b.key.toLowerCase()}'`)||A.includes(`describe('${b.key.toLowerCase()}'`),j=y>=0.3||w;return{name:b.key,type:"scenario",passed:j,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:j?void 0:`Scenario keywords not found in implementation (${Math.round(y*100)}% coverage)`}}function QX($,b){let n=JSON.stringify(b.input),A=JSON.stringify(b.output),m=F1(b.input),y=F1(b.output),W=$.toLowerCase(),w=m.filter((X)=>W.includes(X.toLowerCase())),j=y.filter((X)=>W.includes(X.toLowerCase())),B=m.length>0?w.length/m.length:1,S=y.length>0?j.length/y.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${n.slice(0,100)}...; Output: ${A.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function F1($){let b=[];function n(A){if(typeof A==="string"&&A.length>2)b.push(A);else if(Array.isArray(A))A.forEach(n);else if(A&&typeof A==="object")Object.values(A).forEach(n)}return n($),b}function ZX($,b,n){let A=$.includes(b),m=n.http?$.includes(String(n.http)):!0,y=n.when??n.description,W=y.toLowerCase().split(/\s+/).filter((Q)=>Q.length>3),w=$.toLowerCase(),j=W.filter((Q)=>w.includes(Q)),B=W.length>0?j.length/W.length:1,S=A&&(m||B>=0.3);return{name:`Error: ${b}`,type:"error",passed:S,expected:`When: ${y}; Return: ${b} (HTTP ${n.http??400})`,details:S?void 0:!A?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function XX($,b){let n=b.sideEffects?.emits??[],A=[];for(let m of n){let y=BX(m)?m.ref.key:m.key,W=m.when,w=W.toLowerCase().split(/\s+/).filter((Z)=>Z.length>3),j=$.toLowerCase(),B=j.includes(y.toLowerCase()),S=w.filter((Z)=>j.includes(Z)),Q=w.length>0?S.length/w.length:1;A.push({name:`Event: ${y}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${y} when: ${W}`,details:!B?`Event '${y}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return A}function YX($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let n=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],A=$.toLowerCase(),m=n.some((y)=>A.includes(y));return{name:"Idempotency",type:"scenario",passed:m,expected:"Operation should be idempotent (safe to retry)",details:m?void 0:"No idempotency pattern found for idempotent operation"}}function DA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];for(let Y of b.acceptance?.scenarios??[])y.push(SX(n,Y));for(let Y of b.acceptance?.examples??[])y.push(QX(n,Y));for(let[Y,G]of Object.entries(b.io.errors??{}))y.push(ZX(n,Y,G));y.push(...XX(n,b));let W=YX(n,b);if(W)y.push(W);let w=y.filter((Y)=>!Y.passed).map((Y)=>({severity:Y.type==="error"?"error":"warning",category:Y.type==="scenario"?"scenario":Y.type==="example"?"scenario":"error_handling",message:Y.details??`${Y.type} not covered: ${Y.name}`,location:A?{file:A}:void 0,suggestion:Y.expected?`Expected: ${Y.expected}`:void 0})),j=y.filter((Y)=>Y.type==="scenario"),B=y.filter((Y)=>Y.type==="error"),S=y.filter((Y)=>Y.passed).length,Q=y.length>0?Math.round(S/y.length*100):100,Z=w.filter((Y)=>Y.severity==="error").length===0,X=y.filter((Y)=>!Y.passed&&Y.expected).map((Y)=>`${Y.name}: ${Y.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:w,suggestions:X,coverage:{scenarios:{total:j.length,covered:j.filter((Y)=>Y.passed).length},errors:{total:B.length,handled:B.filter((Y)=>Y.passed).length},fields:{total:y.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}import{isEmitDeclRef as GX}from"@contractspec/lib.contracts-spec/operations";function HX($){let b=/export\s+(async\s+)?function\s+\w+/.test($)||/export\s+const\s+\w+\s*=\s*(async\s*)?\(/.test($)||/export\s+default\s+(async\s+)?function/.test($)||/export\s+\{\s*\w+/.test($);return{name:"handler_export",passed:b,details:b?void 0:"No exported handler function found",suggestion:"Export a function that handles the operation: export async function handle(...) { }"}}function qX($){if(!$)return!1;let b=$.replace(/\\/g,"/");return b.includes("/packages/libs/contracts-spec/src/")||b.includes("/packages/libs/contracts-integrations/src/")||b.includes("/packages/libs/contracts-runtime-")}function OX($,b){if(qX(b))return{name:"contracts_import",passed:!0};let n=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:n,details:n?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function VX($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let A=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function JX($){let b=/:\s*any\b|as\s+any\b|<any>/,n=$.split(`
|
|
2542
|
+
`),A=[];for(let m=0;m<n.length;m++){let y=n[m]??"";if(y.trim().startsWith("//")||y.trim().startsWith("*"))continue;if(b.test(y))A.push(m+1)}return{name:"no_any_type",passed:A.length===0,details:A.length>0?`Found 'any' type on lines: ${A.slice(0,5).join(", ")}${A.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function UX($,b){let n=b.io.errors;if(!n||Object.keys(n).length===0)return{name:"error_handling",passed:!0};let A=Object.keys(n),m=[];for(let y of A)if(!$.includes(y))m.push(y);return{name:"error_handling",passed:m.length===0,details:m.length>0?`Missing error handling for: ${m.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function KX($,b){let n=b.sideEffects?.emits;if(!n||n.length===0)return{name:"event_emission",passed:!0};let A=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),m=n.map((W)=>{if(GX(W))return W.ref.key;return W.key}),y=m.filter((W)=>$.includes(W));return{name:"event_emission",passed:A&&y.length>0,details:!A?"No event emission pattern found":y.length===0?`Events not referenced: ${m.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function _X($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let n=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:n,details:n?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function zX($,b){let n=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:n,details:n?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function yn($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[HX(n),OX(n,A),VX(n,b),JX(n),UX(n,b),KX(n,b),_X(n,b),zX(n,b)],W=y.filter((X)=>!X.passed).map((X)=>({severity:X.name==="no_any_type"?"warning":"error",category:X.name.includes("import")?"import":X.name.includes("export")?"export":"type",message:X.details??`Check failed: ${X.name}`,location:A?{file:A}:void 0,suggestion:X.suggestion})),w=y.filter((X)=>X.passed).length,j=Math.round(w/y.length*100),B=W.filter((X)=>X.severity==="error").length===0,S=y.filter((X)=>!X.passed&&X.suggestion).map((X)=>X.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=y.find((X)=>X.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:j,issues:W,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:y.length,implemented:w}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}var LX={verbose:!1},RX=["structure","behavior","ai_review"];class NA{config;constructor($={}){this.config={...LX,...$}}async verify($,b,n={}){let A=Date.now(),m=new Map,y=[],W={spec:$,implementationCode:b},w=n.tiers??["structure","behavior"];for(let Z of RX){if(!w.includes(Z))continue;let X;switch(Z){case"structure":X=yn(W);break;case"behavior":X=DA(W);break;case"ai_review":if(this.config.aiApiKey)X=await mn(W,this.config);else X=TA(W);break;default:continue}if(m.set(Z,X),y.push(...X.issues),n.failFast&&!X.passed)break}let j=Array.from(m.values()),B=j.every((Z)=>Z.passed),S=j.length>0?Math.round(j.reduce((Z,X)=>Z+X.score,0)/j.length):100,Q=this.generateSummary(j,y);return{passed:B,score:S,reports:m,allIssues:y,summary:Q,duration:Date.now()-A}}verifyStructure($,b,n){return yn({spec:$,implementationCode:b,implementationPath:n})}verifyBehavior($,b,n){return DA({spec:$,implementationCode:b,implementationPath:n})}async verifyAI($,b,n){let A={spec:$,implementationCode:b,implementationPath:n};if(this.config.aiApiKey)return mn(A,this.config);return TA(A)}quickVerify($,b){return yn({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[A,m]of $.reports){if(b.push(`## ${this.formatTierName(A)}`),b.push(""),b.push(`**Status:** ${m.passed?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${m.score}/100`),b.push(""),m.issues.length>0){b.push("### Issues"),b.push("");for(let y of m.issues){let W=y.severity==="error"?"❌":y.severity==="warning"?"⚠️":"ℹ️";if(b.push(`${W} **${y.category}**: ${y.message}`),y.suggestion)b.push(` - Suggestion: ${y.suggestion}`)}b.push("")}if(m.coverage.scenarios.total>0)b.push(`**Scenarios:** ${m.coverage.scenarios.covered}/${m.coverage.scenarios.total}`);if(m.coverage.errors.total>0)b.push(`**Errors handled:** ${m.coverage.errors.handled}/${m.coverage.errors.total}`);b.push("")}let n=Array.from($.reports.values()).flatMap((A)=>A.suggestions);if(n.length>0){b.push("## Suggestions"),b.push("");for(let A of n.slice(0,10))b.push(`- ${A}`);if(n.length>10)b.push(`- ... and ${n.length-10} more`);b.push("")}return b.join(`
|
|
2543
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let n=[],A=$.every((j)=>j.passed),m=$.length>0?Math.round($.reduce((j,B)=>j+B.score,0)/$.length):100;n.push(A?"✓ Verification passed":"✗ Verification failed"),n.push(`Score: ${m}/100`),n.push("");for(let j of $){let B=j.passed?"✓":"✗";n.push(`${B} ${j.tier}: ${j.score}/100`)}n.push("");let y=b.filter((j)=>j.severity==="error"),W=b.filter((j)=>j.severity==="warning"),w=b.filter((j)=>j.severity==="info");if(y.length>0)n.push(`Errors: ${y.length}`);if(W.length>0)n.push(`Warnings: ${W.length}`);if(w.length>0)n.push(`Info: ${w.length}`);return n.join(`
|
|
2544
|
+
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function CX($){return new NA($)}var xX=new NA;var nB={};f(nB,{saveReleaseDraft:()=>t1,renderUpgradePrompt:()=>Yb,renderUpgradeChecklist:()=>Y1,renderPatchNotes:()=>Qy,renderMigrationGuide:()=>X1,renderMaintainerSummary:()=>Q1,renderCustomerPatchNote:()=>Z1,renderCustomerGuide:()=>Zy,prepareReleaseAuthoring:()=>i1,parseConventionalCommit:()=>gA,isConventionalCommit:()=>FX,initReleaseArtifacts:()=>e1,getHighestBumpType:()=>Hy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>o1,formatKeepAChangelog:()=>Wn,formatConventionalChangelog:()=>g1,formatChangelogJson:()=>FA,filterCommitsByScope:()=>vX,filterBumpableCommits:()=>gX,commitsToChangeEntries:()=>qy,commitToChangeEntry:()=>k1,checkReleaseArtifacts:()=>$B,buildReleaseArtifacts:()=>s1,applyVersionBump:()=>u1,analyzeVersionsFromCommits:()=>Gb,analyzeVersions:()=>Qn,DEFAULT_COMMIT_TYPE_MAP:()=>vA});import{basename as IX,dirname as EX}from"node:path";function Wn($){let b=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){b.push(`## [${A.version}] - ${A.date}`),b.push("");let m=A.changes.filter((Q)=>Q.type==="added"),y=A.changes.filter((Q)=>Q.type==="changed"),W=A.changes.filter((Q)=>Q.type==="deprecated"),w=A.changes.filter((Q)=>Q.type==="removed"),j=A.changes.filter((Q)=>Q.type==="fixed"),B=A.changes.filter((Q)=>Q.type==="security"),S=A.breakingChanges??A.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### ⚠️ Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(m.length>0)b.push("### Added"),m.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(y.length>0)b.push("### Changed"),y.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(W.length>0)b.push("### Deprecated"),W.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(w.length>0)b.push("### Removed"),w.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(j.length>0)b.push("### Fixed"),j.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(B.length>0)b.push("### Security"),B.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("")}return b.join(`
|
|
2545
|
+
`)}function g1($){let b=["# Changelog",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){let m=A.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":A.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${A.version} (${A.date}) - ${m}`),b.push("");let y={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let W of A.changes){let w=y[W.type]??"chore",j=W.path?`(${W.path})`:"",B=W.type==="breaking"?"!":"";b.push(`- **${w}${j}${B}**: ${W.description}`)}b.push("")}return b.join(`
|
|
2546
|
+
`)}function FA($,b){let n=$.analyses.filter((y)=>y.needsBump),A=new Date().toISOString(),m=A.split("T")[0]??"";return{generatedAt:A,baseline:b,specs:n.map((y)=>({key:y.specKey,version:y.suggestedVersion,path:y.specPath,entries:[{version:y.suggestedVersion,date:m,bumpType:y.bumpType,changes:y.changes,breakingChanges:y.changes.filter((W)=>W.type==="breaking")}]})),libraries:TX(n,m)}}function MX($){let b=$.split("/"),n=b.lastIndexOf("packages");if(n>=0&&n+2<b.length)return b.slice(0,n+3).join("/");return EX($)}var v1={major:3,minor:2,patch:1};function TX($,b){let n=new Map;for(let A of $){let m=MX(A.specPath),y=n.get(m);if(y)y.push(A);else n.set(m,[A])}return Array.from(n.entries()).flatMap(([A,m])=>{let y=m[0];if(!y)return[];let W=m.reduce((w,j)=>{return(v1[j.bumpType]??0)>(v1[w.bumpType]??0)?j:w},y);return[{name:IX(A),path:A,version:W.suggestedVersion,entries:[{version:W.suggestedVersion,date:b,bumpType:W.bumpType,changes:m.flatMap((w)=>w.changes),breakingChanges:m.flatMap((w)=>w.changes).filter((w)=>w.type==="breaking")}]}]})}function P1($,b){let n=(y)=>{return y.split(".").map((w)=>parseInt(w,10)||0)},A=n($),m=n(b);for(let y=0;y<3;y++){let W=A[y]??0,w=m[y]??0;if(W!==w)return w-W}return 0}var vA={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},DX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,NX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function gA($){let b=$.split(`
|
|
2547
|
+
`),n=b[0]?.trim();if(!n)return null;let A=n.match(DX);if(!A)return null;let[,m,y,W,w]=A;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2548
|
+
`).trim()||void 0,B=j?.match(NX),S=B?.[1];return{type:m.toLowerCase(),scope:y?.toLowerCase(),breaking:!!W||!!B,description:w.trim(),body:j,breakingDescription:S,raw:$}}function FX($){return gA($)!==null}function Gy($,b=vA){if($.breaking)return"major";return b[$.type]??null}function Hy($,b=vA){let n=["major","minor","patch"],A=null;for(let m of $){let y=Gy(m,b);if(!y)continue;if(!A){A=y;continue}let W=n.indexOf(A);if(n.indexOf(y)<W)A=y}return A}function k1($){if($.breaking)return{type:"breaking",description:$.breakingDescription??$.description,path:$.scope};switch($.type){case"feat":return{type:"added",description:$.description,path:$.scope};case"fix":return{type:"fixed",description:$.description,path:$.scope};case"deprecate":return{type:"deprecated",description:$.description,path:$.scope};case"remove":return{type:"removed",description:$.description,path:$.scope};case"security":return{type:"security",description:$.description,path:$.scope};default:return{type:"changed",description:$.description,path:$.scope}}}function qy($){return $.map(k1)}function vX($,b){return $.filter((n)=>n.scope?.toLowerCase()===b.toLowerCase())}function gX($,b=vA){return $.filter((n)=>Gy(n,b)!==null)}import{z as M}from"zod";import{ReleaseCapsuleSchema as r1}from"@contractspec/lib.contracts-spec";import{dump as PX,load as kX}from"js-yaml";var rX=".changeset/*.md",fX=".changeset/*.release.yaml",cX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,hX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function dX($,b){return(await $.glob({pattern:rX,cwd:b,absolute:!0})).filter((A)=>$.basename(A)!=="README.md")}async function wn($,b){let n=await dX($,b),A=[];for(let m of n){let y=await $.readFile(m);A.push(uX($.basename(m),y))}return A}async function jn($,b,n){let A=await $.glob({pattern:fX,cwd:b,absolute:!0}),m=new Map(n.map((w)=>[w.slug,w.packages])),y=new Map,W=[];for(let w of A){let j=$.basename(w).replace(/\.release\.yaml$/,"");try{let B=kX(await $.readFile(w)),S=oX(B,j,m.get(j)??[]);y.set(j,S)}catch(B){W.push(iX(w,j,B))}}return{capsules:y,issues:W}}async function Bn($,b){let n=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),A=[];for(let m of n){let y=JSON.parse(await $.readFile(m));if(!y.name||!y.version||y.private===!0)continue;let W=$.relative(b,$.dirname(m))||".";A.push({name:y.name,dir:W,version:y.version})}return A.sort((m,y)=>m.dir.localeCompare(y.dir))}function PA($,b){let n=new Set;for(let A of $){let m=b.find((y)=>y.dir==="."?!A.startsWith("packages/"):A===y.dir||A.startsWith(`${y.dir}/`));if(m)n.add(m.name)}return Array.from(n).sort((A,m)=>A.localeCompare(m))}function kA($,b){return`---
|
|
2549
|
+
${b.map((A)=>`"${A.name}": ${A.releaseType}`).join(`
|
|
2135
2550
|
`)}
|
|
2136
2551
|
---
|
|
2137
2552
|
|
|
2138
2553
|
${$}
|
|
2139
|
-
`}function
|
|
2140
|
-
`)
|
|
2141
|
-
`)}function
|
|
2142
|
-
|
|
2554
|
+
`}function rA($){return PX(r1.parse($),{noRefs:!0,lineWidth:100})}function Sn($){return $.map((b)=>{let n=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",A=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${n} ${b.message}.${A}`.trim()}).join(`
|
|
2555
|
+
`)}function uX($,b){let n=$.replace(/\.md$/,""),A=b.match(cX);if(!A)return{slug:n,summary:b.trim(),packages:[]};let m=A[1]??"",y=(A[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2556
|
+
`)){let j=w.trim().match(hX);if(!j)continue;let B=j[1],S=j[2];if(!B||S==="none")continue;W.push({name:B,releaseType:S})}return{slug:n,summary:y,packages:W}}function oX($,b,n){let A=typeof $==="object"&&$!==null?$:{},m=Array.isArray(A.packageNames)?A.packageNames.filter((y)=>typeof y==="string").map((y)=>({name:y,releaseType:A.releaseType??"patch"})):[];return r1.parse({...A,slug:b,packages:Array.isArray(A.packages)&&A.packages.length>0?A.packages:m.length>0?m:n})}function iX($,b,n){let A=typeof n==="object"&&n!==null?n:null,m=Array.isArray(A?.issues)?A.issues.map((W)=>W.message).filter((W)=>typeof W==="string"):[],y=m.length>0?`Release capsule validation failed: ${m.join("; ")}`:typeof A?.reason==="string"?`Release capsule YAML parse failed: ${A.reason}`:`Release capsule parse failed: ${n instanceof Error?n.message:String(n)}`;return{slug:b,filePath:$,message:y,line:typeof A?.mark?.line==="number"?A.mark.line+1:void 0,column:typeof A?.mark?.column==="number"?A.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as d1,determineBumpType as tX}from"@contractspec/lib.contracts-spec";async function Qn($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting version analysis...",{baseline:b.baseline});let W=b.pattern??"**/*.{operation,event,presentation}.ts",j=(await n.glob({pattern:W,cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${j.length} spec files`);let B=[],S=0,Q=0;for(let X of j)try{let Y=await n.readFile(X),G=fA(Y);if(!G)continue;let V=null;if(b.baseline)try{V=await A.showFile(b.baseline,X)}catch{V=null}let O=lX(Y,V),K=O.some((_)=>_.type==="breaking"),J=O.length>0&&!K,U=O.length>0;if(K)S++;if(J)Q++;let H=tX(K,J),q=U?d1(G.version,H):G.version;B.push({specPath:X,specKey:G.key,currentVersion:G.version,suggestedVersion:q,bumpType:H,changes:O,hasBreaking:K,needsBump:U})}catch(Y){m.warn(`Failed to analyze ${X}:`,{error:Y instanceof Error?Y.message:String(Y)})}let Z=B.filter((X)=>X.needsBump).length;return m.info("Version analysis complete",{totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q}),{analyses:B,totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q,baseline:b.baseline}}async function Gb($,b={}){let{git:n,logger:A}=$,m=b.baseline??"HEAD~10";A.info("Analyzing commits for version bump...",{baseline:m});try{let y=await n.log(m),W=[],w=[];for(let Q of y){let Z=gA(Q.message);if(Z)W.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),w.push(Z)}let j=Hy(w),B=qy(w),S=W.filter((Q)=>Q.breaking).length;return A.info("Commit analysis complete",{totalCommits:W.length,breakingCommits:S,suggestedBumpType:j}),{suggestedBumpType:j,commits:W,changes:B,totalCommits:W.length,breakingCommits:S}}catch(y){return A.warn("Failed to analyze commits",{error:y instanceof Error?y.message:String(y)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function u1($,b){let{fs:n,logger:A}=$,{specPath:m,dryRun:y=!1,config:W}=b;A.info("Applying version bump...",{specPath:m,bumpType:b.bumpType});try{let w=await n.readFile(m),j=fA(w);if(!j)return{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:c1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=d1(j.version,B),Q=b.changes??[];if(b.changeDescription)Q.push({type:B==="major"?"breaking":"changed",description:b.changeDescription});let Z={version:S,date:new Date().toISOString().split("T")[0]??"",bumpType:B,changes:Q,breakingChanges:Q.filter((X)=>X.type==="breaking")};if(!y){let X=aX(w,j.version,S);await n.writeFile(m,X)}if(A.info("Version bump applied",{specPath:m,previousVersion:j.version,newVersion:S}),W?.integrateWithChangesets)await $Y($,{specPath:m,bumpType:B,summary:b.changeDescription??`Bump ${j.key} to ${S}`,dryRun:y});return{success:!0,specPath:m,specKey:j.key,previousVersion:j.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(w){let j=w instanceof Error?w.message:String(w);return A.error("Version bump failed",{specPath:m,error:j}),{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:c1(),error:j}}}async function o1($,b={}){let{logger:n}=$,A=b.tiers??["spec","library","monorepo"],m=b.format??"keep-a-changelog";n.info("Generating changelogs...",{tiers:A,format:m});let y=await Qn($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),W=[],w=new Map,j="",B=0;if(A.includes("spec"))for(let Q of y.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:eX(Q),kind:"changelog",specKey:Q.specKey,specVersion:Q.suggestedVersion,entries:[{version:Q.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:Q.bumpType,changes:Q.changes,breakingChanges:Q.changes.filter((X)=>X.type==="breaking")}]};W.push(Z),B++}if(A.includes("library")){let Q=sX(y.analyses);for(let[Z,X]of Q){let Y=X.filter((G)=>G.needsBump);if(Y.length>0)w.set(Z,Wn(Y.map(h1))),B+=Y.length}}if(A.includes("monorepo")){let Q=y.analyses.filter((Z)=>Z.needsBump).map(h1);j=Wn(Q)}let S=FA(y,b.baseline);return n.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:W,libraryMarkdown:w,monorepoMarkdown:j,json:S,totalEntries:B}}function fA($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),n=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!n)return null;let A=b[1],m=n[1];if(!A||!m)return null;return{key:A,version:m}}function lX($,b){let n=[];if(!b)return n.push({type:"added",description:"New spec added"}),n;let A=fA($),m=fA(b);if(!A||!m)return n;if(A.version!==m.version)n.push({type:"changed",description:`Version updated from ${m.version} to ${A.version}`,path:"meta.version"});let y=pX($,b);if(y.breaking)n.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(y.nonBreaking)n.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return n}function pX($,b){let n=/io:\s*\{[\s\S]*?\}/,A=$.match(n)?.[0]??"",m=b.match(n)?.[0]??"";if(A===m)return{breaking:!1,nonBreaking:!1};let y=f1(A),W=f1(m),w=W.filter((B)=>!y.includes(B)),j=y.filter((B)=>!W.includes(B));return{breaking:w.length>0,nonBreaking:j.length>0&&w.length===0}}function f1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((A)=>A[1]).filter((A)=>!!A)}function aX($,b,n){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${n}'`)}function c1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function eX($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],n=$.changes.filter((y)=>y.type==="breaking"),A=$.changes.filter((y)=>y.type==="changed"),m=$.changes.filter((y)=>y.type==="added");if(n.length>0)b.push("### Breaking Changes"),n.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(m.length>0)b.push("### Added"),m.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(A.length>0)b.push("### Changed"),A.forEach((y)=>b.push(`- ${y.description}`)),b.push("");return b.join(`
|
|
2557
|
+
`)}function sX($){let b=new Map;for(let n of $){let y=n.specPath.match(/(.+?\/src\/)/)?.[1]??n.specPath,W=b.get(y)??[];W.push(n),b.set(y,W)}return b}function h1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function $Y($,b){let{fs:n,logger:A}=$,{specPath:m,bumpType:y,summary:W,dryRun:w}=b;try{let j=c(m),B=g$(j);if(!B){A.warn("Could not determine package name for changeset",{specPath:m});return}let S=j,Q=null;while(!0){let G=n.join(S,".changeset");if(await n.exists(G)){Q=G;break}let V=n.dirname(S);if(V===S)break;S=V}if(!Q){A.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${bY()}.md`,X=n.join(Q,Z),Y=`---
|
|
2558
|
+
"${B}": ${y}
|
|
2143
2559
|
---
|
|
2144
2560
|
|
|
2145
|
-
${
|
|
2146
|
-
`;if(!Y)await j.writeFile(J,b),A.info("Generated changeset",{filePath:J});else A.info("Would generate changeset",{filePath:J,content:b})}catch(B){A.error("Failed to generate changeset",{error:B instanceof Error?B.message:String(B)})}}function Fq(){let $=["neat","calm","wild","soft","bold","fair","cool"],W=["fox","cat","dog","bat","ant","elk","owl"],j=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],Q=W[Math.floor(Math.random()*W.length)],Z=j[Math.floor(Math.random()*j.length)],X=Math.floor(Math.random()*1000);return`${A}-${Q}-${Z}-${X}`}var e9="generated/releases",tW=vq.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function $A($,W={}){let{fs:j,git:A,logger:Q}=$,Z=D(W.workspaceRoot),X=await A5(j,Z),Y=W.baseline?await A.diffFiles(W.baseline):[],B=W.packages&&W.packages.length>0?W.packages:c9(Y,X),q=W.baseline?await pW($,{baseline:W.baseline,workspaceRoot:Z}):null,H=W.baseline?await F$($,{baseline:W.baseline,workspaceRoot:Z}):null,V=(H?.summary.breaking??0)>0?"major":q?.suggestedBumpType??mq(B),G=W.releaseType??V,J=W.summary??`Describe the ${G} release for ${B[0]??"the workspace"}`,b=W.slug??kq(J),w=B.map((K)=>({name:K,releaseType:G,version:X.find((_)=>_.name===K)?.version})),L={schemaVersion:"1",slug:b,summary:J,isBreaking:G==="major"||(H?.summary.breaking??0)>0,packages:w,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:J},{kind:"customer",summary:J}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},z=j.join(Z,".changeset",`${b}.md`),S=j.join(Z,".changeset",`${b}.release.yaml`);if(!W.force){if(await j.exists(z))throw Error(`Changeset already exists: ${z}`);if(await j.exists(S))throw Error(`Release capsule already exists: ${S}`)}let U=r9(J,w),O=l9(L);if(!W.dryRun)await j.writeFile(z,U),await j.writeFile(S,O);return Q.info("Initialized release artifacts",{slug:b,workspaceRoot:Z}),{slug:b,changesetPath:z,capsulePath:S,changesetContent:U,capsuleContent:O,packages:w,releaseType:G,isBreaking:L.isBreaking}}async function WA($,W={}){let{fs:j,logger:A}=$,Q=D(W.workspaceRoot),Z=await AA(j,Q),X=j.join(Q,W.outputDir??e9),Y=await W5(j,Q),B=await j5(j,Q,Y),q=await A5(j,Q),H=await Promise.all(Array.from(B.entries()).map(async([U,O])=>{let K=j.join(Q,".changeset",`${U}.release.yaml`),_=await j.stat(K);return{slug:U,version:Pq(O,q),summary:O.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:O.isBreaking,packages:O.packages.map((I)=>({...I,version:q.find((M)=>M.name===I.name)?.version??I.version})),affectedRuntimes:[...O.affectedRuntimes],affectedFrameworks:[...O.affectedFrameworks],audiences:[...O.audiences],deprecations:[...O.deprecations],migrationInstructions:[...O.migrationInstructions],upgradeSteps:[...O.upgradeSteps],validation:O.validation}})),V=xq.parse({generatedAt:new Date().toISOString(),releases:H}),G=W.agentTargets??Z.agentTargets??["codex"],J=D0(V,[],G,p$),b=j.join(X,"manifest.json"),w=j.join(X,"upgrade-manifest.json"),L=j.join(X,"patch-notes.md"),z=j.join(X,"customer-guide.md"),S=Object.fromEntries(J.agentPrompts.map((U)=>[U.agent,j.join(X,"prompts",`${U.agent}.md`)]));if(!W.dryRun){await j.writeFile(b,JSON.stringify(V,null,2)),await j.writeFile(w,JSON.stringify(V,null,2)),await j.writeFile(L,ij(V)),await j.writeFile(z,pj(V));for(let U of J.agentPrompts)await j.writeFile(S[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:X,releasesBuilt:V.releases.length}),{outputDir:X,manifestPath:b,upgradeManifestPath:w,patchNotesPath:L,customerGuidePath:z,promptPaths:S,manifest:V,upgradePlan:J,releasesBuilt:V.releases.length}}async function jA($,W={}){let{fs:j}=$,A=D(W.workspaceRoot),Q=await AA(j,A),Z=j.join(A,W.outputDir??e9),X=[],Y=[],B=[],q=await W5(j,A),H=await j5(j,A,q),V=q.length>0,G=!V&&H.size>0;t$(X,V||G,"changesets",V?`Found ${q.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let J of q)if(!H.has(J.slug)&&Q.requireReleaseCapsule)B.push(`Missing release capsule for changeset ${J.slug}.`);for(let[J,b]of H){if(b.isBreaking&&b.migrationInstructions.length===0)B.push(`Breaking release ${J} is missing migration instructions.`);if(b.validation.commands.length===0)B.push(`Release capsule ${J} is missing validation commands.`);if(b.validation.evidence.length===0)B.push(`Release capsule ${J} is missing validation evidence.`)}if(W.baseline){try{let J=await F$($,{baseline:W.baseline,workspaceRoot:A});if(t$(X,!0,"impact",`Impact status: ${J.status}`),J.summary.breaking>0&&!Array.from(H.values()).some((b)=>b.isBreaking))B.push("Breaking impact detected without a breaking release capsule.")}catch(J){t$(X,!1,"impact",aW(J)),B.push(`Impact detection failed: ${aW(J)}`)}try{let J=await y0($,{baseline:W.baseline,workspaceRoot:A});t$(X,!0,"versioning",`${J.specsNeedingBump} spec(s) need version review.`)}catch(J){t$(X,!1,"versioning",aW(J)),B.push(`Version analysis failed: ${aW(J)}`)}}if(W.strict)for(let J of Q.publishArtifacts??[]){let b=j.join(Z,J);if(!await j.exists(b))B.push(`Missing generated release artifact: ${b}`)}if(t$(X,B.length===0,"capsules",B.length===0?"All release capsules are complete.":B[0]??""),!V&&!G)Y.push("No pending release changesets were found.");return{success:B.length===0,errors:B,warnings:Y,checks:X}}async function AA($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return tW;try{let A=JSON.parse(await $.readFile(j)),Q=yq.safeParse(A);return Q.success?{...tW,...Q.data.release}:tW}catch{return tW}}function mq($){return $.length>0?"minor":"patch"}function Pq($,W){return $.packages.map((A)=>W.find((Q)=>Q.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function kq($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function t$($,W,j,A){$.push({name:j,ok:W,message:A})}function aW($){return $ instanceof Error?$.message:String($)}var wA={};h(wA,{silentLogger:()=>YA,runWorkflow:()=>BA,loadWorkflows:()=>X5,loadVibeConfig:()=>eW,installPack:()=>bA,getWorkflow:()=>HA,exportContext:()=>XA,consoleLogger:()=>Z5,builtinWorkflows:()=>$1,DEFAULT_VIBE_CONFIG:()=>sW});import{existsSync as hq}from"node:fs";import{readFile as gq}from"node:fs/promises";import{join as Q5}from"node:path";import fq from"js-yaml";var sW={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function eW($){let W=$??process.cwd(),j=D(W)??W,A=[Q5(j,".contractspec","vibe","config.json"),Q5(j,".contractspec","vibe","config.yaml"),Q5(j,".contractspec","vibe","config.yml")],Q={};for(let Z of A)if(hq(Z))try{let X=await gq(Z,"utf-8");if(Z.endsWith(".json"))Q=JSON.parse(X);else Q=fq.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${Z}`,X)}return{...sW,...Q}}import{existsSync as uq}from"node:fs";import{copyFile as dq,mkdir as ZA,readFile as nq,writeFile as cq}from"node:fs/promises";import{dirname as rq,join as a$}from"node:path";import{glob as lq}from"glob";var oq=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function XA($){let W=$??process.cwd(),j=D(W)??W,A=await eW(W),Q=a$(j,".contractspec","context"),Z=a$(Q,"files"),X=[...oq],Y=a$(j,".gitignore");if(uq(Y)){let w=(await nq(Y,"utf-8")).split(`
|
|
2147
|
-
`).map((
|
|
2561
|
+
${W}
|
|
2562
|
+
`;if(!w)await n.writeFile(X,Y),A.info("Generated changeset",{filePath:X});else A.info("Would generate changeset",{filePath:X,content:Y})}catch(j){A.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function bY(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],n=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],m=b[Math.floor(Math.random()*b.length)],y=n[Math.floor(Math.random()*n.length)],W=Math.floor(Math.random()*1000);return`${A}-${m}-${y}-${W}`}var nY=M.object({summary:M.string(),maintainerSummary:M.string(),customerSummary:M.string(),integratorSummary:M.string(),deprecations:M.array(M.string()).default([]),migrationInstructions:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),required:M.boolean().default(!1),when:M.string().optional(),steps:M.array(M.string()).default([])})).default([]),upgradeSteps:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),level:M.enum(["auto","assisted","manual"]).default("manual"),instructions:M.array(M.string()).default([])})).default([]),validationCommands:M.array(M.string()).default([]),validationEvidence:M.array(M.string()).default([])});async function i1($,b={}){let{fs:n,git:A,logger:m,ai:y}=$,W=I(b.workspaceRoot),w=await Bn(n,W),j=b.baseline?await A.diffFiles(b.baseline):[],B=await wn(n,W),S=await jn(n,W,B),Q=b.packages&&b.packages.length>0?b.packages:PA(j,w),Z=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??wY(B,S.capsules,Q),G=Y?n.join(W,".changeset",`${Y}.md`):void 0,V=Y?n.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((q)=>q.slug===Y):void 0,K=Y?S.capsules.get(Y):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??jY(Q)),U=(G?await n.exists(G):!1)||(V?await n.exists(V):!1),H=await mY(y,AY({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:w,isBreaking:J==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await A.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},m);return{workspaceRoot:W,source:U?"existing":"created",changesetPath:G??n.join(W,".changeset",`${H.slug}.md`),capsulePath:V??n.join(W,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${Sn(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:n}=$,A=I(b.workspaceRoot),m=Zn(b.draft),y=n.join(A,".changeset",`${m.slug}.md`),W=n.join(A,".changeset",`${m.slug}.release.yaml`),w=await n.exists(y)||await n.exists(W)?"updated":"created",j=kA(m.summary,m.packages),B=rA(WY(m));return await n.writeFile(y,j),await n.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function AY($){if($.existingCapsule)return Zn({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((A)=>({...A,version:$.workspacePackages.find((m)=>m.name===A.name)?.version??A.version})):$.packageNames.map((A)=>({name:A,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===A)?.version})),n=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return Zn({slug:$.selectedSlug??BY(n),summary:n,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:l1(n),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function mY($,b,n,A){if(!$)return b;try{let m=await $.generateStructured({schema:nY,systemPrompt:"You write structured release metadata for a TypeScript monorepo. Be concise, concrete, and safe for public release notes.",prompt:JSON.stringify({draft:b,changedFiles:n.changedFiles.slice(0,40),commitMessages:n.commitMessages.slice(0,20),parseIssues:n.parseIssues})});return yY(b,m.object)}catch(m){return A.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:m instanceof Error?m.message:String(m)}),b}}function yY($,b){let n=[...$.audiences];return Oy(n,"maintainer",b.maintainerSummary),Oy(n,"customer",b.customerSummary),Oy(n,"integrator",b.integratorSummary),Zn({...$,summary:p1($.summary)?b.summary:$.summary,audiences:n,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function Zn($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:l1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function WY($){let{releaseType:b,...n}=Zn($);return{schemaVersion:"1",...n}}function l1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Oy($,b,n){let A=$.find((m)=>m.kind===b);if(A&&!p1(A.summary))return;if(A){A.summary=n;return}$.push({kind:b,summary:n})}function wY($,b,n){let A=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(A.size===1)return Array.from(A)[0];if(n.length===0)return;let m=Array.from(A).filter((y)=>{let W=b.get(y),w=$.find((B)=>B.slug===y);return(W?.packages.map((B)=>B.name)??w?.packages.map((B)=>B.name)??[]).some((B)=>n.includes(B))});return m.length===1?m[0]:void 0}function jY($){return $.length>0?"minor":"patch"}function p1($){return $.trim().startsWith("Describe the ")}function BY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as SY}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as QY,DEFAULT_CONTRACTSRC as ZY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var a1="generated/releases",cA=ZY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function e1($,b={}){let{fs:n,git:A,logger:m}=$,y=I(b.workspaceRoot),W=await Bn(n,y),w=b.baseline?await A.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:PA(w,W),B=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:y}):null,S=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:y}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??XY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??GY(X),G=j.map((H)=>({name:H,releaseType:Z,version:W.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:G,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:X},{kind:"customer",summary:X}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=n.join(y,".changeset",`${Y}.md`),K=n.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await n.exists(O))throw Error(`Changeset already exists: ${O}`);if(await n.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=kA(X,G),U=rA(V);if(!b.dryRun)await n.writeFile(O,J),await n.writeFile(K,U);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:U,packages:G,releaseType:Z,isBreaking:V.isBreaking}}async function s1($,b={}){let{fs:n,logger:A}=$,m=I(b.workspaceRoot),y=await bB(n,m),W=n.join(m,b.outputDir??a1),w=await wn(n,m),j=await jn(n,m,w);if(j.issues.length>0)throw Error(Sn(j.issues));let B=j.capsules,S=await Bn(n,m),Q=await Promise.all(Array.from(B.entries()).map(async([U,H])=>{let q=n.join(m,".changeset",`${U}.release.yaml`),_=await n.stat(q);return{slug:U,version:YY(H,S),summary:H.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:H.isBreaking,packages:H.packages.map((z)=>({...z,version:S.find((L)=>L.name===z.name)?.version??z.version})),affectedRuntimes:[...H.affectedRuntimes],affectedFrameworks:[...H.affectedFrameworks],audiences:[...H.audiences],deprecations:[...H.deprecations],migrationInstructions:[...H.migrationInstructions],upgradeSteps:[...H.upgradeSteps],validation:H.validation}})),Z=SY.parse({generatedAt:new Date().toISOString(),releases:Q}),X=b.agentTargets??y.agentTargets??["codex"],Y=An(Z,[],X,Yb),G=n.join(W,"manifest.json"),V=n.join(W,"upgrade-manifest.json"),O=n.join(W,"patch-notes.md"),K=n.join(W,"customer-guide.md"),J=Object.fromEntries(Y.agentPrompts.map((U)=>[U.agent,n.join(W,"prompts",`${U.agent}.md`)]));if(!b.dryRun){await n.writeFile(G,JSON.stringify(Z,null,2)),await n.writeFile(V,JSON.stringify(Z,null,2)),await n.writeFile(O,Qy(Z)),await n.writeFile(K,Zy(Z));for(let U of Y.agentPrompts)await n.writeFile(J[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:W,releasesBuilt:Z.releases.length}),{outputDir:W,manifestPath:G,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:Y,releasesBuilt:Z.releases.length}}async function $B($,b={}){let{fs:n}=$,A=I(b.workspaceRoot),m=await bB(n,A),y=n.join(A,b.outputDir??a1),W=[],w=[],j=[],B=await wn(n,A),S=await jn(n,A,B),Q=S.capsules,Z=B.length>0,X=!Z&&Q.size>0;j.push(...S.issues.map((Y)=>Sn([Y]))),Hb(W,Z||X,"changesets",Z?`Found ${B.length} release changeset(s).`:X?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let Y of B)if(!Q.has(Y.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${Y.slug}.`);for(let[Y,G]of Q){if(G.isBreaking&&G.migrationInstructions.length===0)j.push(`Breaking release ${Y} is missing migration instructions.`);if(G.validation.commands.length===0)j.push(`Release capsule ${Y} is missing validation commands.`);if(G.validation.evidence.length===0)j.push(`Release capsule ${Y} is missing validation evidence.`)}if(b.baseline){try{let Y=await K$($,{baseline:b.baseline,workspaceRoot:A});if(Hb(W,!0,"impact",`Impact status: ${Y.status}`),Y.summary.breaking>0&&!Array.from(Q.values()).some((G)=>G.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(Y){Hb(W,!1,"impact",hA(Y)),j.push(`Impact detection failed: ${hA(Y)}`)}try{let Y=await Qn($,{baseline:b.baseline,workspaceRoot:A});Hb(W,!0,"versioning",`${Y.specsNeedingBump} spec(s) need version review.`)}catch(Y){Hb(W,!1,"versioning",hA(Y)),j.push(`Version analysis failed: ${hA(Y)}`)}}if(b.strict)for(let Y of m.publishArtifacts??[]){let G=n.join(y,Y);if(!await n.exists(G))j.push(`Missing generated release artifact: ${G}`)}if(Hb(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!Z&&!X)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function bB($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return cA;try{let A=JSON.parse(await $.readFile(n)),m=QY.safeParse(A);return m.success?{...cA,...m.data.release}:cA}catch{return cA}}function XY($){return $.length>0?"minor":"patch"}function YY($,b){return $.packages.map((A)=>b.find((m)=>m.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function GY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Hb($,b,n,A){$.push({name:n,ok:b,message:A})}function hA($){return $ instanceof Error?$.message:String($)}var XB={};f(XB,{silentLogger:()=>yB,runWorkflow:()=>WB,loadWorkflows:()=>Uy,loadVibeConfig:()=>uA,installPack:()=>ZB,getWorkflow:()=>jB,exportContext:()=>mB,consoleLogger:()=>Jy,builtinWorkflows:()=>oA,DEFAULT_VIBE_CONFIG:()=>dA});import{existsSync as HY}from"node:fs";import{readFile as qY}from"node:fs/promises";import{join as Vy}from"node:path";import OY from"js-yaml";var dA={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function uA($){let b=$??process.cwd(),n=I(b)??b,A=[Vy(n,".contractspec","vibe","config.json"),Vy(n,".contractspec","vibe","config.yaml"),Vy(n,".contractspec","vibe","config.yml")],m={};for(let y of A)if(HY(y))try{let W=await qY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=OY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...dA,...m}}import{existsSync as VY}from"node:fs";import{copyFile as JY,mkdir as AB,readFile as UY,writeFile as KY}from"node:fs/promises";import{dirname as _Y,join as qb}from"node:path";import{glob as zY}from"glob";var LY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function mB($){let b=$??process.cwd(),n=I(b)??b,A=await uA(b),m=qb(n,".contractspec","context"),y=qb(m,"files"),W=[...LY],w=qb(n,".gitignore");if(VY(w)){let G=(await UY(w,"utf-8")).split(`
|
|
2563
|
+
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));W=[...W,...G]}let j=A.contextExportAllowlist.length>0?A.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let Y of j){let G=await zY(Y,{cwd:n,ignore:W,nodir:!0,dot:!0});B.push(...G)}let S=Array.from(new Set(B)).sort();if(S.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await AB(y,{recursive:!0});let Q=[];for(let Y of S){let G=qb(n,Y),V=qb(y,Y);await AB(_Y(V),{recursive:!0}),await JY(G,V),Q.push({path:Y,size:0})}let Z=qb(m,"index.json"),X={generatedAt:new Date().toISOString(),files:Q.map((Y)=>Y.path),config:{allowlist:A.contextExportAllowlist,ignores:W.length}};return await KY(Z,JSON.stringify(X,null,2)),{success:!0,files:S,indexPath:Z}}var oA=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and generate artifacts.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
|
|
2148
2564
|
Please review them and move selected files to contracts/ directory.
|
|
2149
|
-
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:"
|
|
2150
|
-
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${
|
|
2151
|
-
`);let
|
|
2152
|
-
\uD83D\uDC49 Step: ${
|
|
2565
|
+
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"release",label:"Prepare Release",command:"contractspec release prepare"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as RY}from"node:child_process";var yB={log:()=>{},warn:()=>{},error:()=>{}},Jy={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function WB($,b,n){let A=n?.logger??Jy,m=n?.prompter;if(A.log(`
|
|
2566
|
+
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${b.track}`),b.dryRun)A.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2567
|
+
`);let y={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let W of $.steps){let w={id:W.id,name:W.label,status:"skip",command:W.command};if(W.tracks&&!W.tracks.includes(b.track)){y.steps.push(w);continue}if(W.condition){if(!await W.condition(b)){y.steps.push(w);continue}}if(A.log(`
|
|
2568
|
+
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)A.log(` Command: ${W.command}`);if(W.manualCheckpoint){if(b.dryRun)A.warn(" [Manual Checkpoint] Would pause here for user input.");else if(m){if(W.manualMessage)A.log(W.manualMessage);let j=await m.select({message:"Checkpoint action:",choices:[{name:"Proceed",value:"proceed",description:"Run this step"},{name:"Skip Step",value:"skip",description:"Skip this step and continue"},{name:"Abort Workflow",value:"abort",description:"Exit workflow"}]});if(j==="abort")return A.warn("Workflow aborted by user."),y.success=!1,y.steps.push({...w,status:"skip",error:"Aborted by user"}),y;if(j==="skip"){A.warn(" → Skipped by user."),y.steps.push(w);continue}}}if(!b.dryRun)try{if(W.execute)await W.execute(b);else if(W.command)await CY(W.command,b.root);w.status="pass",y.stepsExecuted.push(W.id),y.steps.push(w),A.log(" ✓ Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return A.error(` ❌ Failed: ${B}`),y.success=!1,y.error=j instanceof Error?j:Error(String(j)),w.status="fail",w.error=B,y.stepsExecuted.push(W.id),y.steps.push(w),y}else y.steps.push(w)}return y}async function CY($,b){let n=$.split(" "),A=n[0],m=n.slice(1);if(!A)throw Error("Invalid command");return new Promise((y,W)=>{let w=RY(A,m,{cwd:b,stdio:"inherit",shell:!0});w.on("error",W),w.on("exit",(j)=>{if(j===0)y();else W(Error(`Command exited with code ${j}`))})})}import{existsSync as xY}from"node:fs";import{readdir as IY,readFile as EY}from"node:fs/promises";import{join as wB}from"node:path";import MY from"js-yaml";async function Uy($){let b=[...oA],n=$??process.cwd(),A=I(n)??n,m=wB(A,".contractspec","vibe","workflows");if(xY(m))try{let y=await IY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await EY(wB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=MY.load(w);if(j.id&&j.steps)b.push(j)}catch(j){console.warn(`Failed to parse workflow ${W}:`,j)}}}catch(y){console.warn("Error loading user workflows:",y)}return b}async function jB($,b){return(await Uy(b)).find((A)=>A.id===$)}import{existsSync as Ky}from"node:fs";import{copyFile as BB,mkdir as SB,readdir as QB,stat as TY}from"node:fs/promises";import{join as N$,resolve as DY}from"node:path";async function ZB($,b){let n=b??process.cwd(),A=I(n)??n;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let m=DY(n,$);if(!Ky(m))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${m}`};let y=0,W=0,w=N$(m,"workflows");if(Ky(w)){let B=N$(A,".contractspec","vibe","workflows");await SB(B,{recursive:!0});let S=await QB(w);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await BB(N$(w,Q),N$(B,Q)),y++}let j=N$(m,"templates");if(Ky(j)){let B=N$(A,".contractspec","vibe","templates");await SB(B,{recursive:!0});let S=await QB(j);for(let Q of S){let Z=N$(j,Q),X=N$(B,Q);if((await TY(Z)).isFile())await BB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as NY}from"@contractspec/module.workspace";var YB=["product","eng","qa"];function FY($){return YB.includes($)}async function FM($,b){if(!FY(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${YB.join(", ")}`);let n,A,m;if(b.specFiles&&b.specFiles.length>0)n=b.specFiles;else{let W=await vY($,{baseline:b.baseline});if(A=W.totalSpecs,m=W.changedFilesCount,b.baseline){if(W.changedFilesCount===0)return{views:[],totalSpecs:A,changedFilesCount:0,status:"no_changes"};if(W.specFiles.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_changed_specs"}}n=W.specFiles}if(n.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_specs"};let y=[];for(let W of n){let w=await gY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:A,changedFilesCount:m,status:"success"}}async function vY($,b={}){let A=(await j$({fs:$.fs})).map((w)=>w.filePath),m=A.length;if(!b.baseline)return{specFiles:A,totalSpecs:m};let y=await $.git.diffFiles(b.baseline);if(y.length===0)return{specFiles:[],totalSpecs:m,changedFilesCount:0,hasChanges:!1};let W=A.filter((w)=>y.some((j)=>w.endsWith(j)||j.endsWith(w)||w.includes(j)||j.includes(w)));return{specFiles:W,totalSpecs:m,changedFilesCount:y.length,hasChanges:W.length>0}}async function gY($,b,n){if(!await n.fs.exists($))throw Error(`File not found: ${$}`);let A=await NY($);if(A.length===0)return`No specs found in ${$} (Parse result empty)`;return A.map((m)=>PY(m,b)).join(`
|
|
2153
2569
|
|
|
2154
2570
|
---
|
|
2155
2571
|
|
|
2156
|
-
`)}function
|
|
2157
|
-
`)}function
|
|
2572
|
+
`)}function PY($,b){let n=[];switch(b){case"product":kY($,n);break;case"eng":rY($,n);break;case"qa":fY($,n);break}return n.join(`
|
|
2573
|
+
`)}function kY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2158
2574
|
${$.meta.goal}
|
|
2159
|
-
`);if($.meta.context)
|
|
2575
|
+
`);if($.meta.context)b.push(`### Context
|
|
2160
2576
|
${$.meta.context}
|
|
2161
|
-
`);if($.specType==="feature"){if($.operations?.length)
|
|
2162
|
-
`);if($.testRefs?.length)
|
|
2163
|
-
`)}export{
|
|
2577
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- ✅ Enforces Business Policies");if($.hasIo)b.push("- ✅ Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((n)=>b.push(`- **${n.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function rY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"✅ Defined":"❌ Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"✅ Defined":"❌ None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function fY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2578
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((n)=>b.push(`- \uD83E\uDDEA \`${n.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((n)=>b.push(`- [ ] Verify event \`${n.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((n)=>b.push(`- [ ] Test Operation flow: \`${n.name}\``));if($.presentations?.length)$.presentations.forEach((n)=>b.push(`- [ ] Test UI Component: \`${n.name}\``))}}function kM($,b,n,A){let{watcher:m,fs:y,logger:W}=$,w=m.watch(n),j=A?.validate??(async(S)=>{await l$(S,{fs:y,logger:W})}),B=A?.build??(async(S)=>{await yb(S,{fs:y,logger:W},b)});return w.on(async(S)=>{if(S.type!=="change")return;if(W.info("watchSpecs.changed",{path:S.path}),n.runValidate)await j(S.path);if(n.runBuild)if(n.dryRun)W.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),w}async function cM($,b,n={}){let A=(n.getWorkspaceInfo??cy)(b),m=$.join(A.workspaceRoot,".contractsrc.json"),y=$.join(A.packageRoot,".contractsrc.json"),W=await $.exists(m),w=A.workspaceRoot!==A.packageRoot?await $.exists(y):!1,j;if(W)try{let B=await $.readFile(m),S=JSON.parse(B);if(S.packages||S.excludePackages||S.recursive)j={packages:S.packages,excludePackages:S.excludePackages,recursive:S.recursive}}catch{}return{...A,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?y:void 0}}async function hM($,b){let n=[],A=$.join(b,".contractsrc.json");if(await $.exists(A))n.push(A);let m=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let y of m)if(y!==A)n.push(y);return n}async function dM($,b,n){let A={};if(b&&await $.exists(b))try{let m=await $.readFile(b);A=JSON.parse(m)}catch{}if(n&&await $.exists(n))try{let m=await $.readFile(n),y=JSON.parse(m);A=GB(A,y)}catch{}return A}function GB($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(typeof m==="object"&&m!==null&&!Array.isArray(m)&&typeof y==="object"&&y!==null&&!Array.isArray(y))n[A]=GB(m,y);else n[A]=y}return n}function uM($){let b=[];if(b.push(`Package Manager: ${$.packageManager}`),b.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(b.push("Monorepo: Yes"),b.push(`Package Root: ${$.packageRoot}`),$.packageName)b.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)b.push(`Package Patterns: ${$.packages.join(", ")}`)}else b.push("Monorepo: No");if($.workspaceConfigPath)b.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)b.push(`Package Config: ${$.packageConfigPath}`);return b.join(`
|
|
2579
|
+
`)}export{kM as watchSpecs,XB as vibe,nB as versioning,jX as verifyWithAIEnhanced,mn as verifyWithAI,yn as verifyStructure,xX as verifyService,N1 as verifySemanticFields,z7 as verifyImportedContracts,HR as verifyImplementationAgainstParsedSpec,DA as verifyBehavior,fx as validateTenantConfig,Fx as validateSpecs,l$ as validateSpec,$1 as validateScannedSpec,Rx as validatePackageScaffold,Jx as validateImplementationWithAgent,nA as validateImplementationFiles,Nx as validateDiscoveredSpecs,Hx as validateBlueprint,FY as validateAudience,Tz as validateAgainstOpenApiService,aW as utils,z1 as upgrade,HI as updateSpec,ZQ as toKebabCase,dW as templates,Iz as syncWithOpenApiService,ex as syncSpecs,bX as stringToCacheKey,ny as setupUsageMd,ZA as setupGitignore,pm as setupAgentsMd,YC as searchRegistry,a as safeParseJson,WI as runTests,wI as runTestSpecs,bx as runSetup,bC as runQuickstart,Jw as runDoctor,bK as runCIChecks,Aw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,OQ as resolveImplementations,J0 as resolveDefaultBuildTargets,rj as resolveAuthoredModuleValue,Tw as resolveAllImplementations,$n as renderManagedMarkdownBlock,ey as prompts,ry as parseGitModules,Iw as parseExplicitImplementations,cw as packageDeclarations,f3 as operationRegistry,oj as onboarding,lm as normalizeMarkdownContent,gT as module,dM as mergeMonorepoConfigs,zA as mergeManagedMarkdown,D4 as mergeGitignoreContent,P as loadWorkspaceConfig,oV as loadPackageAuthoredDocBlocks,Pj as loadAuthoredModuleValue,MR as loadAuthoredModuleIfExists,UA as loadAuthoredModuleExports,y$ as loadAuthoredModule,uV as loadAuthoredDocBlocksFromSourceFiles,jI as listTests,vY as listSpecsForView,j$ as listSpecs,XC as listFromRegistry,G0 as listAgentTypes,Vb as isMonorepo,nC as isContractSpecInstalled,fO as isConnectPreset,rO as isBuilderPreset,Eb as inferSetupPresetFromConfig,QQ as inferImplementationType,q7 as importFromSourceService,zj as importFromOpenApiService,sw as impact,Fj as hooks,bU as groupSpecsByType,nS as getWorkspacePackages,cy as getWorkspaceInfo,CG as getRunCommand,om as getProductionDependencies,g$ as getPackageName,mS as getMetaRepoInfo,hy as getInstallCommand,KJ as getImplementationSummary,_O as getGraphStats,cM as getExtendedWorkspaceInfo,xG as getExecCommand,im as getDevDependencies,um as getDependencies,xw as getConventionPaths,UO as getContractNode,ln as getClaudeDesktopConfigPath,T0 as getBuilderRuntimeModeForPreset,mw as getBuilderBootstrapPresetForSetupPreset,tW as getApiKey,hJ as getAllSpecs,yV as getAllLayerLocations,Ub as getAgentAdapter,m0 as getAIProvider,Cn as genericMCPAdapter,hW as generateWorkflowSpec,kn as generateWorkflowRunnerTemplate,Nn as generateWorkflowDevkitWorkflowTemplate,gn as generateWorkflowDevkitStreamRouteTemplate,Fn as generateWorkflowDevkitStartRouteTemplate,Pn as generateWorkflowDevkitGenericTemplate,vn as generateWorkflowDevkitFollowUpRouteTemplate,tn as generateVscodeSettings,HW as generateVisualizationSpec,FM as generateViews,gY as generateView,Sw as generateUsageGuide,YW as generateTranslationSpec,cW as generateThemeSpec,DW as generateTestTemplate,XW as generateTestSpec,fW as generateTelemetrySpec,OW as generateProductIntentSpec,rW as generatePresentationSpec,ZW as generatePolicySpec,kW as generateOperationSpec,PW as generateMigrationSpec,YR as generateMermaidDiagram,K7 as generateMarkdownReport,vW as generateKnowledgeSpaceSpec,GW as generateJobSpec,FW as generateIntegrationSpec,JW as generateHarnessSuiteSpec,VW as generateHarnessScenarioSpec,MW as generateHandlerTemplate,E7 as generateGuideFromParsedSpec,EW as generateFormSpec,IW as generateFeatureSpec,UR as generateFeatureContextMarkdown,xW as generateExperimentSpec,In as generateExampleSpec,CW as generateEventSpec,_w as generateDocsFromSpecs,RW as generateDataViewSpec,Tn as generateDataViewRendererTemplate,M7 as generateCursorRulesFromParsedSpec,jw as generateCursorRules,Mb as generateCursorMcpConfig,Wb as generateContractsrcConfig,TW as generateComponentTemplate,_7 as generateCliReport,ww as generateClaudeMcpConfig,QW as generateCapabilitySpec,Lw as generateArtifacts,LW as generateAppBlueprintSpec,Bw as generateAgentsGuide,qW as generateAgentSpec,bW as formatters,uM as formatWorkspaceInfo,qR as formatVerificationReport,AC as formatQuickstartPreview,kj as formatModuleLoadError,N as formatJson,fL as formatFiles,NV as formatDoctorSummary,FV as formatCheckResult,Ej as fix,I as findWorkspaceRoot,c as findPackageRoot,fy as findMetaRepoRoot,hM as findAllConfigFiles,dJ as filterIssuesByType,uJ as filterIssuesBySeverity,Rj as features,Rw as extractSpecReferences,cz as extractContracts,KR as exportSpecForLLM,C6 as exportOpenApi,KO as exportGraphAsDot,oW as ensurePackageScaffold,cn as discoverSpecs,c$ as discoverSpecFiles,an as discoverLayers,AA as discoverImplementationsForSpec,qJ as discoverAllImplementations,Ew as determineStatus,yS as detectRepositoryType,a$ as detectPackageManager,Xz as deleteSpec,b$ as deepMergePreserve,D0 as deepMergeOverwrite,Ln as cursorCLIAdapter,rI as createWorkspaceStateCacheStorage,IS as createWorkspaceRegistry,CX as createVerifyService,lI as createVerificationCacheService,wz as createSpecCreator,yw as createSetupNextSteps,Ww as createSetupGitignorePatterns,SC as createRegeneratorService,TA as createQuickAIReview,rn as createPackageTargetSpecSource,Fy as createNoopLoggerAdapter,vy as createNodeWatcherAdapter,Dy as createNodeGitAdapter,Ey as createNodeFsAdapter,Ry as createNodeAiAdapter,HG as createNodeAdapters,PI as createInMemoryCacheStorage,vI as createFileSystemCacheStorage,V9 as createEmptyLayerInventory,Ny as createConsoleLoggerAdapter,KG as createBunFsAdapter,a8 as createBuilderWorkspaceId,w5 as createAgentGuideService,Vj as connect,E1 as computeContentHash,Hz as compareSpecs,BK as cleanArtifacts,_n as claudeCodeAdapter,M1 as cacheKeyToString,yb as buildSpec,dn as analyzeWorkspaceDocBlocks,mA as analyzeIntegrity,uL as analyzeGap,eW as analyzeDeps,j5 as agentGuideService,Y0 as agentAdapters,X0 as adoption,ZC as addToRegistry,TR as __moduleLoaderInternals,x1 as WorkspaceStateCacheStorage,L3 as WorkspaceBundle,NA as VerifyService,T1 as VerificationCacheService,YB as VALID_AUDIENCES,Y2 as TestGeneratorService,Uj as SpecCreatorService,qn as SimpleAgent,sW as SETUP_TARGET_LABELS,bw as SETUP_PRESET_LABELS,nw as SETUP_PRESET_DESCRIPTIONS,Ib as SETUP_GITIGNORE_PATTERNS,mZ as RuleSyncService,_A as RegistryClient,TS as PrActionService,Hn as OpenAICodexAgent,ij as MINIMAL_DEPENDENCIES,C1 as InMemoryCacheStorage,Rn as GenericMCPAdapter,R1 as FileSystemCacheStorage,e7 as FULL_DEPENDENCIES,ES as DriftActionService,q$ as DEFAULT_SPEC_PATTERNS,v$ as DEFAULT_FS_IGNORES,I1 as DEFAULT_CACHE_CONFIG,zn as CursorCLIAdapter,Gn as CursorAgent,Yn as ClaudeCodeAgent,Kn as ClaudeCodeAdapter,QZ as CONTRACTSPEC_USAGE_BLOCK_START,ZZ as CONTRACTSPEC_USAGE_BLOCK_END,WZ as CONTRACTSPEC_AGENTS_BLOCK_START,wZ as CONTRACTSPEC_AGENTS_BLOCK_END,mK as CI_CHECK_CATEGORY_LABELS,Vw as CHECK_CATEGORY_LABELS,On as AgentOrchestrator,xn as AgentGuideService,xb as ALL_SETUP_TARGETS,$w as ALL_SETUP_PRESETS,AK as ALL_CI_CHECK_CATEGORIES,Ow as ALL_CHECK_CATEGORIES,GA as AIGenerator};
|