@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/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)){if(!
|
|
4
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
5
|
-
`).map((
|
|
2
|
+
var HB=Object.defineProperty;var qB=($)=>$;function OB($,b){this[$]=qB.bind(null,b)}var f=($,b)=>{for(var n in b)HB($,n,{get:b[n],enumerable:!0,configurable:!0,set:OB.bind(b,n)})};var _y=($,b)=>()=>($&&(b=$($=0)),b);var F$=import.meta.require;import{ContractsrcSchema as H8,DEFAULT_CONTRACTSRC as fn}from"@contractspec/lib.contracts-spec/workspace-config";async function P($,b){let n=$.join(b??".",".contractsrc.json");if(!await $.exists(n))return fn;try{let m=await $.readFile(n),y=JSON.parse(m),W=H8.safeParse(y);return{...fn,...W.data,conventions:{...fn.conventions,...W.data?.conventions||{}}}}catch{return fn}}function tW($){switch($){case"claude":return process.env.ANTHROPIC_API_KEY;case"openai":return process.env.OPENAI_API_KEY;case"custom":return process.env.CONTRACTSPEC_LLM_API_KEY;case"ollama":return;default:return}}var $$=()=>{};var Jj={};f(Jj,{AIGenerator:()=>GA});import{createProvider as Y6}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as G6,buildEventSpecPrompt as H6,buildFormPrompt as q6,buildHandlerPrompt as O6,buildOperationSpecPrompt as V6,buildPresentationSpecPrompt as J6,buildTestPrompt as U6,getCodeGenSystemPrompt as tb,getSystemPrompt as Em}from"@contractspec/module.workspace";import{generateObject as Mm,generateText as YA,streamText as K6}from"ai";import*as R from"zod";class GA{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||tW(this.config.aiProvider),n={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return Y6(n).getModel()}async generateOperationSpec($,b){let n=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.operation"'),version:R.number().int().positive().default(1),description:R.string().describe("Clear, concise summary"),goal:R.string().describe("Business purpose"),context:R.string().describe("Background and constraints"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).describe("Team/person owners with @ prefix"),tags:R.array(R.string()).describe("Categorization tags"),auth:R.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:R.string().describe("Description of input structure"),outputShape:R.string().describe("Description of output structure"),flags:R.array(R.string()).describe("Feature flags").default([]),possibleEvents:R.array(R.string()).describe("Events this may emit").default([]),analytics:R.array(R.string()).describe("Analytics events to track").default([])}),m=V6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateEventSpec($){let b=this.getModel(),n=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),A=H6($);return(await Mm({model:b,schema:n,prompt:A,system:Em()})).object}async generatePresentationSpec($,b){let n=this.getModel(),A=R.object({name:R.string(),version:R.number().int().positive().default(1),description:R.string(),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),componentKey:R.string().optional(),propsShape:R.string().optional(),content:R.string().optional(),mimeType:R.string().optional(),dataShape:R.string().optional()}),m=J6($,b);return(await Mm({model:n,schema:A,prompt:m,system:Em()})).object}async generateHandler($){let b=this.getModel();return(await YA({model:b,prompt:O6($),system:tb()})).text}async generateComponent($){let b=this.getModel();return(await YA({model:b,prompt:G6($),system:tb()})).text}async generateForm($){let b=this.getModel();return(await YA({model:b,prompt:q6($),system:tb()})).text}async generateTests($,b,n){let A=this.getModel();return(await YA({model:A,prompt:U6($,b,n),system:tb()})).text}async streamCodeGeneration($,b){let n=this.getModel(),A=await K6({model:n,prompt:$,system:tb()}),m="";for await(let y of A.textStream)m+=y,b(y);return m}}var HA=_y(()=>{$$()});import*as FT from"@contractspec/module.workspace";import{anthropic as VB}from"@ai-sdk/anthropic";import{openai as zy}from"@ai-sdk/openai";import{DEFAULT_MODELS as Ly}from"@contractspec/lib.ai-providers/models";import{generateObject as JB,generateText as UB,streamText as KB}from"ai";import{ollama as _B}from"ollama-ai-provider";function Ry($){return{async validateProvider(b){try{let{aiProvider:n}=b;if(n==="ollama")return{success:!0};if(n==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(n==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}},async generateText(b){let n=tA($);return{text:(await UB({model:n,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let A={model:tA($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await JB(A)).object}},async streamText(b,n){let A=tA($),m=await KB({model:A,prompt:b.prompt,system:b.systemPrompt}),y="";for await(let W of m.textStream)y+=W,n(W);return y}}}function tA($){let{aiProvider:b,aiModel:n,customEndpoint:A}=$;switch(b){case"claude":{let m=n??Ly.anthropic;return VB(m)}case"openai":{let m=n??Ly.openai;return zy(m)}case"ollama":return _B(n??"codellama");case"custom":{if(!A)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return zy(n??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as cB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as zB,stat as LB,mkdir as Cy,readFile as RB,rm as CB,writeFile as xB}from"fs/promises";import{basename as IB,dirname as xy,isAbsolute as EB,join as MB,relative as TB,resolve as Iy}from"path";import{glob as DB}from"glob";var q$=["**/*.command.ts","**/*.query.ts","**/*.operation.ts","**/*.operations.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts","**/*.capability.ts","**/*.workflow.ts","**/*.data-view.ts","**/*.form.ts","**/*.migration.ts","**/*.telemetry.ts","**/*.experiment.ts","**/*.app-config.ts","**/*.integration.ts","**/*.knowledge.ts","**/*.policy.ts","**/*.test-spec.ts","**/blueprint.ts","**/integration.ts","**/example.ts","**/bundles/*Bundle.ts","**/contracts/*.ts","**/contracts/index.ts","**/commands/*.ts","**/commands/index.ts","**/queries/*.ts","**/queries/index.ts","**/operations/*.ts","**/operations/index.ts","**/operations.ts","**/events.ts","**/presentations.ts","**/events/index.ts","**/presentations/index.ts","**/tests/*.ts","**/tests/*.test-spec.ts"],v$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function Ey($){let b=$??process.cwd();return{async exists(A){try{return await zB(n(A)),!0}catch{return!1}},async readFile(A){return RB(n(A),"utf-8")},async writeFile(A,m){let y=n(A),W=xy(y);await Cy(W,{recursive:!0}),await xB(y,m,"utf-8")},async remove(A){await CB(n(A),{recursive:!0,force:!0})},async stat(A){let m=await LB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await Cy(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return(await DB(m,{cwd:W,ignore:y,absolute:w})).sort((B,S)=>B.localeCompare(S))},resolve(...A){let[m,...y]=A;if(!m)return b;return Iy(b,m,...y)},dirname(A){return xy(A)},basename(A){return IB(A)},join(...A){return MB(...A)},relative(A,m){return TB(A,m)}};function n(A){return EB(A)?A:Iy(b,A)}}import{spawnSync as NB}from"child_process";import{existsSync as My,readFileSync as Ty}from"fs";import{access as FB}from"fs/promises";import{resolve as Xn}from"path";function Dy($){let b=$??process.cwd();return{async currentBranch(){try{let n=Ob(["rev-parse","--abbrev-ref","HEAD"],b).trim()||vB(b);return n.length>0?n:void 0}catch{return}},async showFile(n,A){try{let m=Ob(["show",`${n}:${A}`],b);if(m.length>0||n!=="HEAD")return m;return gB(b,A)??m}catch(m){throw Error(`Could not load ${A} at ref ${n}: ${m instanceof Error?m.message:String(m)}`)}},async clean(n){let A=[];if(n?.force)A.push("-f");if(n?.directories)A.push("-d");if(n?.ignored)A.push("-x");if(n?.dryRun)A.push("--dry-run");Ob(["clean",...A],b,{inherit:!0})},async isGitRepo(n){let A=n?Xn(b,n):b;try{return await FB(Xn(A,".git")),!0}catch{return!1}},async log(n){let A=n??"HEAD~10",m="--format=%H|||%s|||%an|||%aI";try{let y=Ob(["log",`${A}..HEAD`,"--format=%H|||%s|||%an|||%aI"],b),W=[];for(let w of y.trim().split(`
|
|
3
|
+
`)){if(!w)continue;let[j,B,S,Q]=w.split("|||");if(j&&B)W.push({hash:j,message:B,author:S,date:Q})}return W}catch{return[]}},async diffFiles(n,A){try{let m=A&&A.length>0?["--",...A]:[];return Ob(["diff","--name-only",`${n}...HEAD`,...m],b).trim().split(`
|
|
4
|
+
`).filter(Boolean)}catch{return[]}}}}function vB($){let b=Xn($,".git","HEAD");if(!My(b))return"";let n=Ty(b,"utf8").trim(),A="ref: refs/heads/";return n.startsWith(A)?n.slice(A.length):n}function gB($,b){let n=Xn($,b);if(!My(n))return;return Ty(n,"utf8")}function Ob($,b,n={}){let A=NB("git",$,{cwd:b,encoding:"utf-8",stdio:n.inherit?"inherit":["ignore","pipe","pipe"]});if(A.error)throw A.error;if(A.status!==0)throw Error(typeof A.stderr==="string"&&A.stderr.length>0?A.stderr:`git ${$.join(" ")} failed with status ${A.status??"unknown"}`);return typeof A.stdout==="string"?A.stdout:""}function Ny(){return{debug($,b){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,b??"")},info($,b){console.info(`[INFO] ${$}`,b??"")},warn($,b){console.warn(`[WARN] ${$}`,b??"")},error($,b){console.error(`[ERROR] ${$}`,b??"")},createProgress(){return PB()}}}function Fy(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:kB}}function PB(){return{start($){console.warn(`\u23F3 ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`\u2705 ${$??"Done"}`)},fail($){console.error(`\u274C ${$??"Failed"}`)},warn($){console.warn(`\u26A0\uFE0F ${$??"Warning"}`)},stop(){}}}function kB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import rB from"chokidar";var fB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function vy($){let b=$??process.cwd();return{watch(n){let A=[],m,y=rB.watch(n.pattern,{cwd:b,ignored:n.ignore??fB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),W=(w)=>{if(n.debounceMs&&n.debounceMs>0)clearTimeout(m),m=setTimeout(()=>{A.forEach((j)=>j(w))},n.debounceMs);else A.forEach((j)=>j(w))};return y.on("add",(w)=>{W({type:"add",path:w})}),y.on("change",(w)=>{W({type:"change",path:w})}),y.on("unlink",(w)=>{W({type:"unlink",path:w})}),{on(w){A.push(w)},async close(){clearTimeout(m),await y.close()}}}}}function YG($={}){let{cwd:b,config:n,silent:A}=$,m=n??cB;return{fs:Ey(b),git:Dy(b),watcher:vy(b),ai:Ry(m),logger:A?Fy():Ny()}}import{stat as hB,mkdir as dB}from"fs/promises";import{basename as uB,dirname as oB,isAbsolute as iB,join as tB,relative as lB,resolve as gy}from"path";import{glob as pB}from"glob";function JG($){let b=$??process.cwd();return{async exists(A){let m=Bun.file(n(A));try{return await m.exists(),!0}catch{return!1}},async readFile(A){return Bun.file(n(A)).text()},async writeFile(A,m){let y=n(A);await Bun.write(y,m)},async remove(A){await Bun.file(n(A)).delete()},async stat(A){let m=await hB(n(A));return{size:m.size,isFile:m.isFile(),isDirectory:m.isDirectory(),mtime:m.mtime}},async mkdir(A){await dB(n(A),{recursive:!0})},async glob(A){let m=A.patterns??(A.pattern?[A.pattern]:q$),y=A.ignore??v$,W=A.cwd??b,w=A.absolute??!0;return await pB(m,{cwd:W,ignore:y,absolute:w})},resolve(...A){let[m,...y]=A;if(!m)return b;return gy(b,m,...y)},dirname(A){return oB(A)},basename(A){return uB(A)},join(...A){return tB(...A)},relative(A,m){return lB(A,m)}};function n(A){return iB(A)?A:gy(b,A)}}import{existsSync as u,readFileSync as z$}from"fs";import{tmpdir as aB}from"os";import{dirname as lA,isAbsolute as eB,join as d,relative as sB,resolve as p$}from"path";var Py={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},ky=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function $S($,b){let n=sB(b,$);return n===""||!n.startsWith("..")&&!eB(n)}function pA($){let b=p$($),n=p$(aB());return $S(b,n)?n:void 0}function c($=process.cwd()){let b=p$($),n=pA($);while(!0){if(u(d(b,"package.json")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return $}function I($=process.cwd()){let b=p$($),n=null,A=pA($);while(!0){for(let W of ky)if(u(d(b,W)))return b;let m=d(b,"package.json");if(u(m)){n=b;try{if(JSON.parse(z$(m,"utf-8")).workspaces)return b}catch{}}for(let W of Object.keys(Py))if(u(d(b,W)))return b;let y=lA(b);if(y===b||b===A)break;b=y}return n??$}function a$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let A of b){let m=Object.entries(Py).filter(([,y])=>y===A);for(let[y]of m)if(u(d($,y)))return A}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(A.packageManager){let m=A.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(m)return m[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Vb($=process.cwd()){for(let n of ky)if(u(d($,n)))return!0;let b=d($,"package.json");if(u(b))try{if(JSON.parse(z$(b,"utf-8")).workspaces)return!0}catch{}return!1}function bS($){let b=d($,"pnpm-workspace.yaml");if(u(b))try{let m=z$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(m?.[1])return m[1].split(`
|
|
5
|
+
`).map((W)=>W.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let n=d($,"package.json");if(u(n))try{let A=JSON.parse(z$(n,"utf-8"));if(Array.isArray(A.workspaces))return A.workspaces;if(A.workspaces?.packages&&Array.isArray(A.workspaces.packages))return A.workspaces.packages}catch{}return}function g$($){let b=d($,"package.json");if(u(b))try{return JSON.parse(z$(b,"utf-8")).name}catch{}return}function ry($){let b=d($,".gitmodules");if(!u(b))return[];try{let n=z$(b,"utf-8"),A=[],m=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,y;while((y=m.exec(n))!==null){let[,W,w,j]=y;if(W&&w&&j){let B=d($,w),S=u(d(B,"package.json"))&&nS(B);A.push({name:W,path:w,url:j,absolutePath:B,hasWorkspaces:S})}}return A}catch{return[]}}function nS($){let b=d($,"package.json");if(u(b))try{let n=JSON.parse(z$(b,"utf-8"));return Boolean(n.workspaces)}catch{}return u(d($,"pnpm-workspace.yaml"))}function fy($){let b=p$($),n=pA($);while(!0){if(u(d(b,".gitmodules")))return b;let A=lA(b);if(A===b||b===n)break;b=A}return}function AS($){let b=fy($);if(!b)return;let n=ry(b);if(n.length===0)return;let A=p$($),m=n.find((y)=>A.startsWith(y.absolutePath));return{root:b,submodules:n,activeSubmodule:m}}function mS($,b){let n=fy($);if(n){if(ry(n).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function cy($=process.cwd()){let b=c($),n=I($),A=a$(n),m=Vb(n),y=m?bS(n):void 0,W=g$(b),w=mS($,m),j=w==="meta-repo"?AS($):void 0;return{packageManager:A,workspaceRoot:n,packageRoot:b,isMonorepo:m,packages:y,packageName:W,repositoryType:w,metaRepo:j}}function LG($,b){switch($){case"bun":return`bun run ${b}`;case"pnpm":return`pnpm run ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npm run ${b}`}}function RG($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function hy($,b=!1){let n=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${n}`.trim();case"pnpm":return`pnpm add ${n}`.trim();case"yarn":return`yarn add ${n}`.trim();case"npm":return`npm install ${n}`.trim()}}import{anthropic as dy}from"@ai-sdk/anthropic";import{generateText as uy}from"ai";class Yn{name="claude-code";apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set. Claude Code agent requires API access."]};try{let b=dy("claude-3-7-sonnet-20250219"),n=this.buildSystemPrompt($),A=this.buildUserPrompt($),m=await uy({model:b,prompt:A,system:n,temperature:0.2});return{success:!0,code:this.extractCode(m.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:m.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let b=dy("claude-3-7-sonnet-20250219"),n=`
|
|
6
6
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
7
7
|
|
|
8
8
|
SPECIFICATION:
|
|
@@ -31,7 +31,7 @@ Provide a structured validation report:
|
|
|
31
31
|
- Are there any missing edge cases?
|
|
32
32
|
|
|
33
33
|
Be thorough and precise. Use a critical but constructive tone.
|
|
34
|
-
`,A=await
|
|
34
|
+
`,A=await uy({model:b,prompt:n,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),suggestions:this.extractSuggestions(A.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
35
35
|
|
|
36
36
|
Your code is:
|
|
37
37
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -51,7 +51,7 @@ Your code is:
|
|
|
51
51
|
- Following SOLID principles and best practices
|
|
52
52
|
- Modular and testable
|
|
53
53
|
|
|
54
|
-
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let
|
|
54
|
+
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let b={generate:`Generate a complete, production-ready implementation for this specification:
|
|
55
55
|
|
|
56
56
|
${$.specCode}
|
|
57
57
|
|
|
@@ -74,10 +74,10 @@ Spec:
|
|
|
74
74
|
${$.specCode}
|
|
75
75
|
|
|
76
76
|
Code:
|
|
77
|
-
${$.existingCode}`};return
|
|
78
|
-
`);for(let A of
|
|
79
|
-
`);for(let A of
|
|
80
|
-
`);for(let A of
|
|
77
|
+
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
78
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("error")||m.includes("bug")||m.includes("incorrect")||m.includes("missing"))b.push(A.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],n=$.split(`
|
|
79
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("warning")||m.includes("should")||m.includes("consider"))b.push(A.trim())}return b}extractSuggestions($){let b=[],n=$.split(`
|
|
80
|
+
`);for(let A of n){let m=A.toLowerCase();if(m.includes("suggest")||m.includes("recommend")||m.includes("could")||m.includes("improvement"))b.push(A.trim())}return b}}import{spawn as yS}from"child_process";import{existsSync as oy}from"fs";import{mkdir as iy,readFile as WS,rm as wS,writeFile as Y$}from"fs/promises";import{homedir as aA,tmpdir as ty}from"os";import{join as o}from"path";class Gn{name="cursor";cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||"3000",this.detectEnvironment()}canHandle($){return this.isCursorAvailable()}async generate($){try{let b=o(ty(),`cursor-agent-${Date.now()}`);await iy(b,{recursive:!0});let n=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=o(ty(),`cursor-validate-${Date.now()}`);await iy(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let n=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),n}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",o(aA(),".cursor","cursor"),o(aA(),"AppData","Local","Programs","cursor","Cursor.exe"),o(aA(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let b of $)if(b.includes("cursor")||b.includes("Cursor")||b.includes("windsurf")||b.includes("Windsurf"))try{if(oy(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let n=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let A of n)try{let m=await A.fn();if(m.success)return m}catch(m){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,b){if(!this.cursorPath)throw Error("Cursor executable not found");let n=o(b,"spec.ts"),A=o(b,"output.ts"),m=o(b,"INSTRUCTIONS.md");if(await Y$(n,$.specCode),await Y$(m,this.buildDetailedPrompt($)),$.existingCode)await Y$(o(b,"existing.ts"),$.existingCode);return new Promise((y,W)=>{let w=["--wait","--new-window",b],j=yS(this.cursorPath,w,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";j.stdout?.on("data",(Q)=>{B+=Q.toString()}),j.stderr?.on("data",(Q)=>{S+=Q.toString()}),j.on("error",(Q)=>{W(Q)}),j.on("close",async(Q)=>{if(oy(A))try{let Z=await WS(A,"utf-8");y({success:!0,code:Z,metadata:{agentMode:"cursor",method:"cli",exitCode:Q}})}catch(Z){W(Error("Failed to read generated output"))}else W(Error(`Cursor CLI exited with code ${Q}. No output generated.`))}),setTimeout(()=>{j.kill(),W(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let n=o(b,"SPECIFICATION.ts"),A=o(b,"INSTRUCTIONS.md"),m=o(b,"template.ts");return await Y$(n,$.specCode),await Y$(A,this.buildDetailedPrompt($)),await Y$(m,this.generateTemplate($)),await Y$(o(b,"README.md"),`# Cursor Agent Workspace
|
|
81
81
|
|
|
82
82
|
This workspace was prepared for Cursor AI code generation.
|
|
83
83
|
|
|
@@ -92,13 +92,13 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
92
92
|
3. Use Cursor AI to generate code based on the spec
|
|
93
93
|
4. Save the result as output.ts
|
|
94
94
|
|
|
95
|
-
Workspace path: ${
|
|
96
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${
|
|
95
|
+
Workspace path: ${b}
|
|
96
|
+
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Y$(o(b,"specification.ts"),$.specCode),await Y$(o(b,"implementation.ts"),$.existingCode||"// No implementation"),await Y$(o(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let n=[{path:"spec.ts",content:$.specCode}];if($.existingCode)n.push({path:"existing.ts",content:$.existingCode});return n}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
97
97
|
|
|
98
98
|
**Task Type:** ${$.type}
|
|
99
99
|
**Generated:** ${new Date().toISOString()}
|
|
100
100
|
|
|
101
|
-
`,
|
|
101
|
+
`,n=`## Specification
|
|
102
102
|
|
|
103
103
|
\`\`\`typescript
|
|
104
104
|
${$.specCode}
|
|
@@ -197,7 +197,7 @@ ${$.existingCode||""}
|
|
|
197
197
|
- Enhance error messages
|
|
198
198
|
|
|
199
199
|
### Output Format:
|
|
200
|
-
Refactored code that maintains functionality while improving quality.`};return
|
|
200
|
+
Refactored code that maintains functionality while improving quality.`};return b+n+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
201
201
|
|
|
202
202
|
## Specification
|
|
203
203
|
\`\`\`typescript
|
|
@@ -245,7 +245,7 @@ Provide detailed feedback for each failed item.
|
|
|
245
245
|
Suggest specific improvements with code examples where applicable.`}generateTemplate($){return`// Auto-generated template for ${$.type} task
|
|
246
246
|
// Specification:
|
|
247
247
|
${$.specCode.split(`
|
|
248
|
-
`).map((
|
|
248
|
+
`).map((b)=>`// ${b}`).join(`
|
|
249
249
|
`)}
|
|
250
250
|
|
|
251
251
|
// TODO: Implement according to specification
|
|
@@ -255,7 +255,7 @@ export function implementation() {
|
|
|
255
255
|
// Implementation goes here
|
|
256
256
|
throw new Error('Not implemented');
|
|
257
257
|
}
|
|
258
|
-
`}async cleanupWorkDir($){try{await
|
|
258
|
+
`}async cleanupWorkDir($){try{await wS($,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}}import{openai as ly}from"@ai-sdk/openai";import{generateText as py}from"ai";class Hn{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let n=this.isComplexTask($)?"o1":"gpt-5.4",A=ly(n),m=this.buildSystemPrompt($),y=this.buildUserPrompt($),W=await py({model:A,prompt:y,system:m,temperature:0.2});return{success:!0,code:this.extractCode(W.text),metadata:{model:n,agentMode:"openai-codex",usage:W.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=ly("gpt-5.4"),n=`
|
|
259
259
|
Review this code implementation against its specification.
|
|
260
260
|
|
|
261
261
|
SPECIFICATION:
|
|
@@ -275,7 +275,7 @@ Provide a detailed validation report including:
|
|
|
275
275
|
4. Recommendations for improvement
|
|
276
276
|
|
|
277
277
|
Format as a structured report.
|
|
278
|
-
`,A=await
|
|
278
|
+
`,A=await py({model:b,prompt:n,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),m=this.detectIssues(A.text);return{success:!m,code:A.text,errors:m?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],n=($.specCode+($.existingCode||"")).toLowerCase();return b.some((A)=>n.includes(A))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
279
279
|
|
|
280
280
|
Generate production-quality code that is:
|
|
281
281
|
- Type-safe and well-typed
|
|
@@ -312,9 +312,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
312
312
|
${$.existingCode}
|
|
313
313
|
|
|
314
314
|
Spec:
|
|
315
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let
|
|
316
|
-
`);for(let A of
|
|
317
|
-
`);for(let A of
|
|
315
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],n=$.toLowerCase();return b.some((A)=>n.includes(A))}extractErrors($){let b=[],n=$.split(`
|
|
316
|
+
`);for(let A of n)if(A.toLowerCase().includes("error")||A.toLowerCase().includes("bug")||A.toLowerCase().includes("fails"))b.push(A.trim());return b}extractWarnings($){let b=[],n=$.split(`
|
|
317
|
+
`);for(let A of n)if(A.toLowerCase().includes("warning")||A.toLowerCase().includes("should")||A.toLowerCase().includes("consider"))b.push(A.trim());return b}}import P$ from"chalk";import SS from"ora";import{generateText as ay}from"ai";var A0={};f(A0,{getCodeGenSystemPrompt:()=>n0,buildTestPrompt:()=>b0,buildHandlerPrompt:()=>eA,buildFormPrompt:()=>$0,buildComponentPrompt:()=>sA});function eA($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
318
318
|
|
|
319
319
|
Here is the contract spec:
|
|
320
320
|
|
|
@@ -333,7 +333,7 @@ Generate a complete handler implementation that:
|
|
|
333
333
|
|
|
334
334
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
335
335
|
|
|
336
|
-
Return only the TypeScript code for the handler function.`}function
|
|
336
|
+
Return only the TypeScript code for the handler function.`}function sA($){return`You are a senior React developer creating a component for a presentation specification.
|
|
337
337
|
|
|
338
338
|
Here is the presentation spec:
|
|
339
339
|
|
|
@@ -352,7 +352,7 @@ Generate a complete React component that:
|
|
|
352
352
|
|
|
353
353
|
The component should follow Atomic Design principles and be reusable.
|
|
354
354
|
|
|
355
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
355
|
+
Return only the TypeScript/TSX code for the component.`}function $0($){return`You are a senior React developer creating a form component from a form specification.
|
|
356
356
|
|
|
357
357
|
Here is the form spec:
|
|
358
358
|
|
|
@@ -372,7 +372,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
372
372
|
|
|
373
373
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
374
374
|
|
|
375
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
375
|
+
Return only the TypeScript/TSX code for the form component.`}function b0($,b,n){return`You are a senior developer writing comprehensive tests.
|
|
376
376
|
|
|
377
377
|
Spec:
|
|
378
378
|
\`\`\`typescript
|
|
@@ -381,11 +381,11 @@ ${$}
|
|
|
381
381
|
|
|
382
382
|
Implementation:
|
|
383
383
|
\`\`\`typescript
|
|
384
|
-
${
|
|
384
|
+
${b}
|
|
385
385
|
\`\`\`
|
|
386
386
|
|
|
387
387
|
Generate complete test suite using Vitest that:
|
|
388
|
-
${
|
|
388
|
+
${n==="handler"?`
|
|
389
389
|
- Test all acceptance scenarios from the spec
|
|
390
390
|
- Test error cases defined in spec.io.errors
|
|
391
391
|
- Verify events are emitted correctly
|
|
@@ -399,7 +399,7 @@ ${j==="handler"?`
|
|
|
399
399
|
|
|
400
400
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
401
401
|
|
|
402
|
-
Return only the TypeScript test code.`}function
|
|
402
|
+
Return only the TypeScript test code.`}function n0(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
403
403
|
- Type-safe API design
|
|
404
404
|
- React and modern hooks
|
|
405
405
|
- Test-driven development
|
|
@@ -413,7 +413,7 @@ Generate production-ready code that is:
|
|
|
413
413
|
- Defensive and error-safe
|
|
414
414
|
- Easy to maintain and extend
|
|
415
415
|
|
|
416
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
416
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as jS}from"@contractspec/lib.ai-providers";function m0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return jS(b)}class qn{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=m0(this.config),n=this.buildPrompt($),A=await ay({model:b,prompt:n,system:n0()});return{success:!0,code:A.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=m0(this.config),n=`
|
|
417
417
|
Review the following implementation against its specification.
|
|
418
418
|
|
|
419
419
|
Specification:
|
|
@@ -427,17 +427,17 @@ Provide a detailed validation report:
|
|
|
427
427
|
2. Are there any missing features?
|
|
428
428
|
3. Are there any bugs or issues?
|
|
429
429
|
4. Suggestions for improvement
|
|
430
|
-
`,A=await
|
|
431
|
-
${$.specCode}`;case"test":return
|
|
432
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
430
|
+
`,A=await ay({model:b,prompt:n,system:"You are a code review expert. Provide thorough, constructive feedback."}),m=A.text.toLowerCase().includes("error")||A.text.toLowerCase().includes("missing")||A.text.toLowerCase().includes("incorrect");return{success:!m,code:A.text,warnings:m?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return eA($.specCode);else if($.specCode.includes(".presentation."))return sA($.specCode);else if($.specCode.includes(".form."))return $0($.specCode);return`Generate implementation for:
|
|
431
|
+
${$.specCode}`;case"test":return b0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
432
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as BS}from"@contractspec/lib.ai-agent/agent/unified-agent";class y0{name;agent;constructor($,b,n={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=BS(n,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),n=await this.agent.run(b);return{success:!0,code:n.text,metadata:{finishReason:n.finishReason,usage:n.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
433
433
|
${$.specCode}
|
|
434
434
|
|
|
435
|
-
`;if($.existingCode)
|
|
435
|
+
`;if($.existingCode)b+=`Existing Code:
|
|
436
436
|
${$.existingCode}
|
|
437
437
|
|
|
438
|
-
`;switch($.type){case"generate":
|
|
438
|
+
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class On{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new qn($),n=new Gn,A=new Yn,m=new Hn;this.agents.set("simple",b),this.agents.set("cursor",n),this.agents.set("claude-code",A),this.agents.set("openai-codex",m),this.defaultAgent=b,this.agents.set("opencode-sdk",new y0("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),n=this.agents.get(b);if(!n)return console.log(P$.yellow(`\u26A0\uFE0F Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!n.canHandle($))return console.log(P$.yellow(`\u26A0\uFE0F Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let A=SS(`Executing with ${b} agent...`).start();try{let m=$.type==="validate"?await n.validate($):await n.generate($);if(m.success)return A.succeed(P$.green(`${b} agent completed successfully`)),m;A.warn(P$.yellow(`${b} agent failed, trying fallback...`));let y=this.getFallbackMode(b);if(y&&y!==b){let W=this.agents.get(y);if(W&&W.canHandle($))return $.type==="validate"?await W.validate($):await W.generate($)}return A.info(P$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(m){return A.fail(P$.red("Agent execution failed")),console.log(P$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,n]of this.agents){let A={type:"generate",specCode:"test"},m=n.canHandle(A);$.push({mode:b,available:m,reason:m?void 0:"Not configured or dependencies missing"})}return $}getAgentMode(){return this.config.agentMode||"simple"}getFallbackMode($){return{cursor:"claude-code","claude-agent-sdk":"claude-code","claude-code":"openai-codex","openai-codex":"simple",opencode:"opencode-sdk","opencode-sdk":"claude-code",simple:"simple"}[$]}}var ey={};f(ey,{specCreation:()=>W0,codeGeneration:()=>A0});var W0={};f(W0,{getSystemPrompt:()=>YS,buildPresentationSpecPrompt:()=>XS,buildOperationSpecPrompt:()=>QS,buildEventSpecPrompt:()=>ZS,addExampleContext:()=>GS});function QS($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
439
439
|
|
|
440
|
-
The operation is a ${
|
|
440
|
+
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
441
441
|
|
|
442
442
|
User description: ${$}
|
|
443
443
|
|
|
@@ -453,7 +453,7 @@ Create a complete contract specification following these guidelines:
|
|
|
453
453
|
8. **Feature Flags**: Any flags that gate this operation
|
|
454
454
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
455
455
|
|
|
456
|
-
Respond with a structured spec.`}function
|
|
456
|
+
Respond with a structured spec.`}function ZS($){return`You are a senior software architect creating an event specification.
|
|
457
457
|
|
|
458
458
|
User description: ${$}
|
|
459
459
|
|
|
@@ -467,9 +467,9 @@ Create a complete event specification following these guidelines:
|
|
|
467
467
|
|
|
468
468
|
Events represent things that have already happened and should use past tense.
|
|
469
469
|
|
|
470
|
-
Respond with a structured spec.`}function
|
|
470
|
+
Respond with a structured spec.`}function XS($,b){return`You are a senior software architect creating a presentation specification.
|
|
471
471
|
|
|
472
|
-
This is a ${
|
|
472
|
+
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
473
473
|
|
|
474
474
|
User description: ${$}
|
|
475
475
|
|
|
@@ -479,13 +479,13 @@ Create a complete presentation specification following these guidelines:
|
|
|
479
479
|
2. **Version**: Start at 1
|
|
480
480
|
3. **Description**: What this presentation shows/provides
|
|
481
481
|
4. **Kind-specific details**:
|
|
482
|
-
${
|
|
482
|
+
${b==="web_component"?`- Component key (symbolic, resolved by host app)
|
|
483
483
|
- Props structure
|
|
484
|
-
- Analytics events to track`:
|
|
484
|
+
- Analytics events to track`:b==="markdown"?`- Content or resource URI
|
|
485
485
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
486
486
|
- Data structure description`}
|
|
487
487
|
|
|
488
|
-
Respond with a structured spec.`}function
|
|
488
|
+
Respond with a structured spec.`}function YS(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
489
489
|
|
|
490
490
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
491
491
|
|
|
@@ -495,111 +495,362 @@ Your specs are:
|
|
|
495
495
|
- Business-oriented (capturing the "why" not just "what")
|
|
496
496
|
- Designed for both humans and AI agents to understand
|
|
497
497
|
|
|
498
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
498
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function GS($,b){if(b.length===0)return $;return`${$}
|
|
499
499
|
|
|
500
500
|
Here are some good examples for reference:
|
|
501
501
|
|
|
502
|
-
${
|
|
502
|
+
${b.join(`
|
|
503
503
|
|
|
504
504
|
`)}
|
|
505
505
|
|
|
506
|
-
Follow this structure and quality level.`}var
|
|
507
|
-
`)}function
|
|
506
|
+
Follow this structure and quality level.`}import{defineModuleBundle as HS}from"@contractspec/lib.surface-runtime/spec";var _3=HS({meta:{key:"bundles.workspace",version:"1.0.0",title:"Workspace",description:"Workspace utilities for monorepo development"},routes:[{routeId:"default",path:"/",defaultSurface:"main"}],surfaces:{main:{surfaceId:"main",kind:"workbench",title:"Workspace",slots:[],layouts:[],data:[],verification:{dimensions:{guidance:"Scaffolded guidance profile for Workspace.",density:"Scaffolded density profile for Workspace.",dataDepth:"Scaffolded data-depth profile for Workspace.",control:"Scaffolded control profile for Workspace.",media:"Scaffolded media profile for Workspace.",pace:"Scaffolded pace profile for Workspace.",narrative:"Scaffolded narrative profile for Workspace."}}}}});var bW={};f(bW,{sarifToJson:()=>KS,formatAsTextLines:()=>$W,formatAsText:()=>_S,formatAsSarif:()=>VS,formatAsJson:()=>qS});function qS($,b={}){let{pretty:n=!0,driftResult:A}=b,m=$.issues.map((S)=>({name:S.ruleId,status:S.severity==="error"?"fail":S.severity==="warning"?"warn":"pass",category:S.category,message:S.message,file:S.file,line:S.line,details:S.context})),y=$.categories.filter((S)=>S.passed).length,W=$.totalErrors,w=$.totalWarnings,j=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:m,categories:$.categories.map((S)=>({category:S.category,label:S.label,passed:S.passed,errors:S.errors,warnings:S.warnings,notes:S.notes,durationMs:S.durationMs})),drift:{status:A?.hasDrift?"detected":"none",files:A?.files??[]},summary:{pass:y,fail:W,warn:w,note:j,total:y+W+w+j,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return n?JSON.stringify(B,null,2):JSON.stringify(B)}var OS={"spec-structure-error":{name:"Spec Structure Error",description:"Contract specification is missing required structure elements"},"spec-structure-warning":{name:"Spec Structure Warning",description:"Contract specification has recommended but missing elements"},"integrity-orphaned":{name:"Orphaned Spec",description:"Contract specification is not linked to any feature"},"integrity-unresolved-ref":{name:"Unresolved Reference",description:"Contract specification references a non-existent spec"},"integrity-missing-feature":{name:"Missing Feature",description:"Feature referenced by spec does not exist"},"integrity-broken-link":{name:"Broken Link",description:"Link between specs is broken"},"deps-circular":{name:"Circular Dependency",description:"Circular dependency detected between contracts"},"deps-missing":{name:"Missing Dependency",description:"Contract depends on a non-existent contract"},"handler-missing":{name:"Missing Handler",description:"Handler implementation file does not exist for this contract"},"handler-warning":{name:"Handler Warning",description:"Handler implementation has potential issues"},"test-missing":{name:"Missing Test",description:"Test file does not exist for this contract"},"test-warning":{name:"Test Warning",description:"Test implementation has potential issues"}};function VS($,b={}){let{toolName:n="ContractSpec",toolVersion:A="1.0.0",toolUri:m="https://contractspec.io",repositoryUri:y,workingDirectory:W}=b,w=new Map,j=new Map,B=$.issues.filter((X)=>X.file);for(let X of B)if(!w.has(X.ruleId)){let Y=OS[X.ruleId]??{name:X.ruleId,description:`Rule: ${X.ruleId}`},G={id:X.ruleId,name:Y.name,shortDescription:{text:Y.description},defaultConfiguration:{level:sy(X.severity)}};if(Y.helpUri)G.helpUri=Y.helpUri;j.set(X.ruleId,w.size),w.set(X.ruleId,G)}let S=B.map((X)=>{let Y={ruleId:X.ruleId,ruleIndex:j.get(X.ruleId)??0,level:sy(X.severity),message:{text:X.message}},G={physicalLocation:{artifactLocation:{uri:JS(X.file),uriBaseId:"%SRCROOT%"}}};if(X.line!==void 0)G.physicalLocation.region={startLine:X.line,startColumn:X.column??1,endLine:X.endLine??X.line,endColumn:X.endColumn};return Y.locations=[G],Y.partialFingerprints={primaryLocationLineHash:US(X)},Y}),Q=[];if(y)Q.push({repositoryUri:y,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:n,version:A,informationUri:m,rules:Array.from(w.values())}},results:S,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...W&&{workingDirectory:{uri:W}}}]};if(Q.length>0)Z.versionControlProvenance=Q;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[Z]}}function sy($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function JS($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function US($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function KS($){return JSON.stringify($,null,2)}function $W($,b={}){let n=[],{verbose:A=!1,showTiming:m=!0,groupByFile:y=!1}=b;if(n.push({text:"",style:"normal"}),n.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),n.push({text:"",style:"normal"}),$.commitSha||$.branch){let w=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");n.push({text:`Git: ${w}`,style:"muted"})}n.push({text:"",style:"normal"}),n.push({text:"Check Results:",style:"bold"});for(let w of $.categories){let j=w.passed?"\u2713":"\u2717",B=w.passed?"success":"error",S=zS(w),Q=m?` (${w.durationMs}ms)`:"";n.push({text:` ${j} ${w.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(n.push({text:"",style:"normal"}),n.push({text:"Issues:",style:"bold"}),y){let w=LS($.issues);for(let[j,B]of w){n.push({text:"",style:"normal"}),n.push({text:` ${j||"(no file)"}`,style:"bold",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}else{let w=$.issues.filter((S)=>S.severity==="error"),j=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(w.length>0){n.push({text:"",style:"normal"}),n.push({text:" Errors:",style:"error",indent:1});for(let S of w)n.push(...Vn(S,A,2))}if(j.length>0){n.push({text:"",style:"normal"}),n.push({text:" Warnings:",style:"warning",indent:1});for(let S of j)n.push(...Vn(S,A,2))}if(B.length>0&&A){n.push({text:"",style:"normal"}),n.push({text:" Notes:",style:"muted",indent:1});for(let S of B)n.push(...Vn(S,A,2))}}n.push({text:"",style:"normal"}),n.push({text:"\u2500".repeat(50),style:"muted"});let W=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&A?`${$.totalNotes} note(s)`:null].filter(Boolean);if(W.length>0)n.push({text:`Found: ${W.join(", ")}`,style:$.success?"warning":"error"});if(m)n.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(n.push({text:"",style:"normal"}),$.success)n.push({text:"\u2705 All CI checks passed!",style:"success"});else n.push({text:"\u274C CI checks failed",style:"error"});return n.push({text:"",style:"normal"}),n}function _S($,b={}){return $W($,b).map((A)=>" ".repeat(A.indent??0)+A.text).join(`
|
|
507
|
+
`)}function zS($){let b=[];if($.errors>0)b.push(`${$.errors} error(s)`);if($.warnings>0)b.push(`${$.warnings} warning(s)`);if(b.length===0)return"passed";return b.join(", ")}function Vn($,b,n){let A=[],m=$.severity==="error"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",y=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",W=`${m} ${$.message}`;if($.file){let w=$.line?`:${$.line}`:"";W+=` (${$.file}${w})`}if(A.push({text:W,style:y,indent:n}),b&&$.context){let w=JSON.stringify($.context);if(w!=="{}")A.push({text:`Context: ${w}`,style:"muted",indent:n+1})}return A}function LS($){let b=new Map;for(let n of $){let A=n.file??"";if(!b.has(A))b.set(A,[]);let m=b.get(A);if(m)m.push(n)}return new Map([...b.entries()].sort(([n],[A])=>n.localeCompare(A)))}import{OperationSpecRegistry as RS}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as CS}from"@contractspec/lib.contracts-spec/operations/report";function xS(){let $=new RS;return CS($),$}var k3=xS();class IS{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let n=$.drift?.status==="fail",A=!1;if(n&&b==="fail")A=!0;return{driftDetected:n,shouldFail:A}}}function ES($){if(!$)return"\u2014";let b=new Date($),A=new Date().getTime()-b.getTime(),m=Math.floor(A/86400000);if(m<1)return"today";if(m===1)return"yesterday";return`${m} days ago`}class MS{collectChanges($,b,n){if($){let A=$.endsWith("/")?$:`${$}/`;return n.filter((m)=>m.startsWith(A))}if(b){let A=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return n.filter((m)=>A.test(m))}return n}detectDrift($){let b=$.map((n)=>n.slice(3)).filter((n)=>n&&n.trim().length>0).filter((n)=>n!==".contractspec-ci"&&!n.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},n=b.breaking||0,A=b.nonBreaking||0,m=b.total;if(m===void 0)m=n+A;let y=$?.breaking||!1,W="unknown";if($){if(y||n>0)W="breaking",y=!0;else if(A>0)W="non-breaking";else if(m===0)W="no-impact"}return{status:W,breaking:y,breakingCount:n,nonBreakingCount:A,total:m||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,n=this.deriveImpactStatus($.impactJson),A={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:n.status,breaking:n.breakingCount,nonBreaking:n.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(A.validation?.status==="fail")A.nextSteps?.push("Fix validation errors and rerun the workflow.");if(A.risk?.status==="breaking")A.nextSteps?.push("Review breaking changes and plan a migration.");if(A.risk?.status==="unknown")A.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(A.drift?.status==="fail")A.nextSteps?.push("Run the generate command locally and commit drift fixes.");let m=this.finalizeResults(A,$.failOn);if(m.shouldFail)A.nextSteps?.unshift(`CI failed: ${m.failReasons.join(", ")} (fail_on=${$.failOn}).`);return A}finalizeResults($,b){let n=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,A=$.drift?.status==="fail",m=$.validation?.status==="fail",y=$.risk?.status==="unknown",W=[],w=!1;if(b!=="never"){if(b==="breaking"){if(n)W.push("breaking changes detected");if(y)W.push("impact status unknown")}else if(b==="drift"){if(A)W.push("drift detected");if(y)W.push("impact status unknown")}else if(b==="any"){if(n)W.push("breaking changes detected");if(A)W.push("drift detected");if(m)W.push("validation failed");if(y)W.push("impact status unknown")}else W.push(`invalid fail_on value (${b})`);if(W.length>0)w=!0}return{driftDetected:A,breakingChangeDetected:n,validationFailed:m,shouldFail:w,failReasons:W}}generateReportMarkdown($,b){let n=(j,B=60000)=>{if(j.length<=B)return j;return`${j.slice(0,B)}
|
|
508
508
|
|
|
509
|
-
*(output truncated)*`},A=(
|
|
510
|
-
`)},
|
|
509
|
+
*(output truncated)*`},A=(j)=>{if(!j||j.length===0)return"- None";return j.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
510
|
+
`)},m=n($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),y=n($.validation?.outputPath?b($.validation.outputPath):""),W=$.drift?.files??[],w=[];if(w.push("## ContractSpec Report"),w.push(""),$.contracts&&$.contracts.length>0){w.push("### Overall verification status"),w.push(""),w.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),w.push("| --- | --- | --- | --- | --- |");for(let j of $.contracts){let B=j.lastVerifiedSha??"\u2014",S=ES(j.lastVerifiedDate),Q=j.surfaces.join(", ");w.push(`| ${j.name} | ${S} | ${j.driftMismatches} | ${Q} | ${B} |`)}w.push("")}if(w.push("### 1) What changed"),$.whatChanged?.summary)w.push($.whatChanged.summary);else w.push("No contract changes detected.");if(m.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Contract view (product)</summary>"),w.push(""),w.push(m),w.push(""),w.push("</details>");if(w.push(""),w.push("### 2) Risk classification"),$.risk?.status){let j=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);w.push(j.join(" | "))}else w.push("Impact analysis unavailable.");if(w.push(""),w.push("### 3) Validation results"),$.validation?.status){if(w.push(`Status: ${$.validation.status}`),y.trim().length>0)w.push(""),w.push("<details>"),w.push("<summary>Validation output</summary>"),w.push(""),w.push(y),w.push(""),w.push("</details>")}else w.push("Validation step not run.");if(w.push(""),w.push("### 4) Drift results"),$.drift?.status){if(w.push(`Status: ${$.drift.status}`),W.length>0)w.push(""),w.push("<details>"),w.push("<summary>Drifted files</summary>"),w.push(""),w.push(A(W)),w.push(""),w.push("</details>")}else w.push("Drift check not run.");if(w.push(""),w.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)w.push(A($.nextSteps));else w.push("- No action required.");return`${w.join(`
|
|
511
511
|
`)}
|
|
512
|
-
`}}import{AGENT_SYSTEM_PROMPTS as FQ}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":"\u270F\uFE0F";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(`- \u26A0\uFE0F ${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:FQ["claude-code"],taskPrompt:W.join(`
|
|
513
|
-
`)}}
|
|
514
|
-
`)}
|
|
515
|
-
`)}
|
|
516
|
-
`)}
|
|
517
|
-
`)}}
|
|
518
|
-
`)}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
export const ${
|
|
512
|
+
`}}var X0={};f(X0,{uniqueTokens:()=>k$,tokenize:()=>e$,syncAdoptionCatalog:()=>sS,scanWorkspaceAdoptionCandidates:()=>S0,resolveAdoptionWorkspace:()=>s$,resolveAdoption:()=>Jb,overlap:()=>Un,normalizeText:()=>wW,inferFamilyFromPath:()=>Z0,hasLocalShadcnRegistry:()=>Q0,getContractSpecAdoptionCatalog:()=>Jn,createAdoptionCatalogDocument:()=>w0,candidateTokens:()=>j0});function x($,b,n,A,m,y,W,w,j={}){return{id:$,source:"contractspec",packageRef:b,family:n,packageKind:A,title:j.title??b,description:w,capabilityTags:y,preferredUseCases:W,avoidWhen:j.avoidWhen,platforms:j.platforms,replacementImportHints:j.replacementImportHints,resolutionPriority:m,runtimes:j.runtimes}}var nW=[x("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),x("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),x("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),x("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),x("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var AW=[x("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),x("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),x("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),x("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),x("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),x("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),x("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),x("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var mW=[x("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),x("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),x("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),x("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),x("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),x("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),x("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),x("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),x("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var yW=[x("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),x("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),x("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),x("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),x("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),x("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var WW=[x("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),x("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),x("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var TS=[...WW,...nW,...AW,...mW,...yW];function Jn(){return[...TS].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function w0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:Jn()}}import{DEFAULT_CONTRACTSRC as fS}from"@contractspec/lib.contracts-spec/workspace-config";function wW($){return $.toLowerCase().trim()}function e$($){return wW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function k$($){return[...new Set($.flatMap((b)=>e$(b)))]}function j0($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return k$(b)}function Un($,b){let n=new Set(b);return $.filter((A)=>n.has(A)).length}import{resolve as DS}from"path";import{ContractsrcSchema as NS,DEFAULT_CONTRACTSRC as B0}from"@contractspec/lib.contracts-spec/workspace-config";async function s$($,b={}){let n=DS(b.cwd??process.cwd()),A=b.workspaceRoot??I(n),m=b.packageRoot??c(n),y=b.config?BW(B0,b.config):await FS($,A,m);return{adoption:y.connect?.adoption??B0.connect.adoption,config:y,cwd:n,packageRoot:m,workspaceRoot:A}}async function FS($,b,n){let A=B0;if(b!==n)A=await jW($,A,$.join(b,".contractsrc.json"));return jW($,A,$.join(n,".contractsrc.json"))}async function jW($,b,n){if(!await $.exists(n))return b;try{let A=JSON.parse(await $.readFile(n)),m=NS.safeParse(A);if(!m.success)return b;return BW(b,m.data)}catch{return b}}function BW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var vS=["package.json","packages/*/package.json"];async function S0($,b){let[n,A]=await Promise.all([gS($,b),PS($,b)]);return{fileCandidates:A,packageCandidates:n}}async function Q0($,b){let n=$.join(b.workspaceRoot,"components.json");if(await $.exists(n))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function gS($,b){let n=await $.glob({patterns:vS,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),A=[];for(let m of n)try{let y=JSON.parse(await $.readFile($.join(b.workspaceRoot,m))),W=Z0(m);if(!W)continue;let w=y.name??$.dirname(m);A.push({id:`workspace.package.${w}`,source:"workspace",family:W,title:w,description:y.description??`Local reusable package at ${m}.`,packageKind:rS(m),packageRef:w,capabilityTags:k$([w,m]),preferredUseCases:[m],resolutionPriority:120})}catch{continue}return A}async function PS($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((A)=>{let m=Z0(A);if(!m)return[];let y=A.split("/").pop()?.replace(/\.[^.]+$/,"")??A;return[{id:`workspace.file.${A}`,source:"workspace",family:m,title:y,description:`Local reusable source at ${A}.`,filePath:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:kS(m,A)}]})}function Z0($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function kS($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function rS($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Jb($,b){let n=await s$($.fs,b),A=pS(b),m=k$([A,b.symbol??"",...b.paths??[]]),y=await S0($.fs,n),W=await aS($,n),w=await Q0($.fs,n),j=cS(n,m,b,[...y.packageCandidates,...y.fileCandidates,...W,...eS(b.family,b.platform,w)]),B=j[0]??null,S=j.length>1&&B!=null&&B.candidate.source===j[1].candidate.source&&Math.abs(B.score-j[1].score)<=40,Q=iS(n,B,S,b.currentTarget);return{ambiguous:S,candidates:j,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:A,reason:lS(B,S),selected:B,verdict:Q}}function cS($,b,n,A){return A.filter((m)=>m.family===n.family&&uS($,m.family)).filter((m)=>oS(m,n.platform)).map((m)=>hS(m,b,n.paths)).filter((m)=>m.score>40).sort((m,y)=>y.score-m.score).slice(0,8)}function hS($,b,n){let A=j0($),m=k$(n??[]),y=[],W=Un(b,A)*25,w=Un(m,A)*10;if(W>0)y.push("query overlap");if(w>0)y.push("path overlap");return{candidate:$,matchReasons:y,score:dS($.source)+($.resolutionPriority??0)+W+w}}function dS($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function uS($,b){return $.adoption.families?.[b]??!0}function oS($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function iS($,b,n,A){let m=$.adoption.thresholds??fS.connect.adoption.thresholds;if(n)return m.ambiguous??"require_review";if(!b)return m.newImplementation??"require_review";if(b.candidate.source==="workspace")return tS(b.candidate,A)?"permit":m.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return m.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return m.newImplementation??"require_review";return m.newExternalDependency??"require_review"}function tS($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function lS($,b){if(b)return"Multiple similarly strong adoption candidates were found.";if(!$)return"No reusable workspace or ContractSpec candidate matched the request.";return`Selected ${$.candidate.source} candidate ${$.candidate.title}.`}function pS($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function aS($,b){let n=Jn(),A=b.adoption.catalog?.overrideManifestPath;if(!A||!await $.fs.exists($.fs.join(b.workspaceRoot,A)))return n;try{let m=await $.fs.readFile($.fs.join(b.workspaceRoot,A)),y=JSON.parse(m);return[...n,...Array.isArray(y)?y:y.entries??[]]}catch{return n}}function eS($,b,n){if($==="ui"&&b==="web"&&n)return[$b("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[$b("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[$b("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[$b("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[$b("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[$b("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function $b($,b,n,A,m){return{id:$,source:"ecosystem",packageRef:n,family:b,packageKind:"primitive",title:A,description:A,capabilityTags:e$(A),preferredUseCases:[A],resolutionPriority:m}}async function sS($,b={}){let n=await s$($.fs,b),A=w0(),m=$.fs.join(n.workspaceRoot,n.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(m,`${JSON.stringify(A,null,2)}
|
|
513
|
+
`),{catalog:A,catalogPath:m}}import{AGENT_SYSTEM_PROMPTS as $5}from"@contractspec/lib.contracts-spec/llm";class Kn{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let n of $.fileStructure){let A=n.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";b.push(`${A} \`${n.path}\``),b.push(` ${n.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let n of $.steps){b.push(`### ${n.order}. ${n.title}`),b.push(""),b.push(n.description),b.push(""),b.push("**Acceptance Criteria:**");for(let A of n.acceptanceCriteria)b.push(`- [ ] ${A}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let n of $.constraints.security)b.push(`- \u26A0\uFE0F ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:$5["claude-code"],taskPrompt:b.join(`
|
|
514
|
+
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
515
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let n=[],A=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let m of A){let y=$.matchAll(m);for(let W of y)if(W[1])n.push(W[1])}if(n.length>0)return{errors:n};return{code:$}}}var _n=new Kn;import{AGENT_SYSTEM_PROMPTS as b5}from"@contractspec/lib.contracts-spec/llm";class zn{agentType="cursor-cli";formatPlan($){let b=[];if(b.push(`# ${$.target.key}.v${$.target.version}`),b.push(""),b.push(`> ${$.context.goal}`),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push("");for(let A of $.fileStructure)b.push(`- ${A.type}: \`${A.path}\` - ${A.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let A of $.steps)b.push(`${A.order}. **${A.title}**: ${A.description}`);b.push("");let n=[...$.constraints.policy,...$.constraints.security.map((A)=>`\u26A0\uFE0F ${A}`)];if(n.length>0){b.push("## Constraints"),b.push("");for(let A of n)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((A)=>`\`${A}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:b5["cursor-cli"],taskPrompt:b.join(`
|
|
516
|
+
`)}}generateConfig($){let b=$.meta,n=[];if(n.push("---"),n.push(`description: Implementation rules for ${b.key}.v${b.version}`),n.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),n.push("alwaysApply: false"),n.push("---"),n.push(""),n.push(`# ${b.key} Implementation Rules`),n.push(""),n.push(`This ${b.kind} operation must follow the ContractSpec specification.`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Requirements"),n.push(""),n.push("1. Input/output types MUST match the spec schema exactly"),n.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)n.push("3. Events MUST be emitted as specified");if(n.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)n.push(`5. Idempotency: ${$.policy.idempotent}`);if(n.push(""),$.io.errors&&Object.keys($.io.errors).length>0){n.push("## Error Cases"),n.push("");for(let[A,m]of Object.entries($.io.errors))n.push(`- \`${A}\` (HTTP ${m.http??400}): ${m.when}`);n.push("")}if($.sideEffects?.emits?.length){n.push("## Events to Emit"),n.push("");for(let A of $.sideEffects.emits)if("ref"in A)n.push(`- \`${A.ref.key}.v${A.ref.version}\`: ${A.when}`);else n.push(`- \`${A.key}.v${A.version}\`: ${A.when}`);n.push("")}if($.policy.pii?.length){n.push("## PII Handling"),n.push(""),n.push("These fields contain PII and must be handled with care:");for(let A of $.policy.pii)n.push(`- \`${A}\``);n.push("")}if($.acceptance?.scenarios?.length){n.push("## Acceptance Scenarios"),n.push("");for(let A of $.acceptance.scenarios)n.push(`### ${A.key}`),n.push(`- Given: ${A.given.join("; ")}`),n.push(`- When: ${A.when.join("; ")}`),n.push(`- Then: ${A.then.join("; ")}`),n.push("")}return n.join(`
|
|
517
|
+
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var Ln=new zn;import{AGENT_SYSTEM_PROMPTS as n5}from"@contractspec/lib.contracts-spec/llm";class Rn{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let n of $.fileStructure)b.push(`| \`${n.path}\` | ${n.type} | ${n.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let n of $.steps)if(b.push(`### Step ${n.order}: ${n.title}`),b.push(""),b.push(n.description),b.push(""),n.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let A of n.acceptanceCriteria)b.push(`- ${A}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let n of $.constraints.policy)b.push(`- ${n}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let n of $.constraints.security)b.push(`- ${n}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let n of $.constraints.pii)b.push(`- \`${n}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let n of $.verificationChecklist)b.push(`- [ ] ${n}`);return b.push(""),{agent:"generic-mcp",systemPrompt:n5["generic-mcp"],taskPrompt:b.join(`
|
|
518
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,n=[];return n.push(`# ${b.key} v${b.version}`),n.push(""),n.push(`**Type:** ${b.kind}`),n.push(`**Stability:** ${b.stability}`),n.push(""),n.push("## Goal"),n.push(""),n.push(b.goal),n.push(""),n.push("## Description"),n.push(""),n.push(b.description),n.push(""),n.join(`
|
|
519
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let n=JSON.parse($);if(typeof n.code==="string")return{code:n.code};if(typeof n.errors==="object")return{errors:Array.isArray(n.errors)?n.errors:[String(n.errors)]}}catch{}return{code:$}}}var Cn=new Rn;var Y0={"claude-code":_n,"cursor-cli":Ln,"generic-mcp":Cn};function Ub($){let b=Y0[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function G0(){return Object.keys(Y0)}import{featureToMarkdown as H0,generateImplementationPlan as SW,operationSpecToAgentPrompt as A5,operationSpecToFullMarkdown as m5}from"@contractspec/lib.contracts-spec/llm";var y5={defaultAgent:"generic-mcp",verbose:!1};class xn{config;constructor($={}){this.config={...y5,...$}}generateGuide($,b={}){let n=b.agent??this.config.defaultAgent,A=Ub(n),m=SW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),y=A.formatPlan(m),W=m5($);return{plan:m,prompt:y,markdown:W}}generateFeatureGuide($,b,n={}){let A=n.agent??this.config.defaultAgent,m=Ub(A),y=$.operations?.[0],W=y?b.specs?.get(y.key,y.version):void 0,w;if(W)w=SW(W,{projectRoot:this.config.projectRoot}),w.target={type:"feature",key:$.meta.key,version:"1.0.0"},w.context.goal=$.meta.description??w.context.goal;else w={target:{type:"feature",key:$.meta.key,version:"1.0.0"},context:{goal:$.meta.description??`Implement feature ${$.meta.key}`,description:$.meta.title??$.meta.key,background:""},specMarkdown:H0($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(w.specMarkdown=H0($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)w.steps=$.operations.map((S,Q)=>({order:Q+1,title:`Implement ${S.key}`,description:`Implement operation ${S.key}.v${S.version}`,acceptanceCriteria:[`Operation ${S.key} works as specified`]}));let j=m.formatPlan(w),B=H0($,b);return{plan:w,prompt:j,markdown:B}}generateAgentConfig($,b){return Ub(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,n="implement",A){return A5($,{taskType:n,existingCode:A})}listAgentTypes(){return G0()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function W5($){return new xn($)}var w5=new xn;import{detectAuthoringTarget as s5,generateComponentTemplate as $8,generateHandlerTemplate as b8,generateTestTemplate as n8,getAuthoringTargetDefinition as A8,inferSpecTypeFromFilePath as m8,scanSpecSource as y8}from"@contractspec/module.workspace";var dW={};f(dW,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});function QW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
520
|
+
|
|
521
|
+
export const ${nb($.key)}Capability = defineCapability({
|
|
522
522
|
meta: {
|
|
523
|
-
key: '${
|
|
524
|
-
version: ${$.version},
|
|
523
|
+
key: '${$.key}',
|
|
524
|
+
version: '${$.version}',
|
|
525
|
+
kind: '${$.kind??"api"}',
|
|
526
|
+
title: '${k(bb($))}',
|
|
527
|
+
description: '${k($.description)}',
|
|
528
|
+
domain: '${k(r$($))}',
|
|
529
|
+
owners: [${W$($.owners)}],
|
|
530
|
+
tags: [${W$($.tags)}],
|
|
531
|
+
stability: '${$.stability}',
|
|
532
|
+
},
|
|
533
|
+
provides: [],
|
|
534
|
+
requires: [],
|
|
535
|
+
});
|
|
536
|
+
`}function ZW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
537
|
+
|
|
538
|
+
export const ${nb($.key)}Policy = definePolicy({
|
|
539
|
+
meta: {
|
|
540
|
+
key: '${$.key}',
|
|
541
|
+
version: '${$.version}',
|
|
542
|
+
title: '${k(bb($))}',
|
|
543
|
+
description: '${k($.description)}',
|
|
544
|
+
domain: '${k(r$($))}',
|
|
545
|
+
owners: [${W$($.owners)}],
|
|
546
|
+
tags: [${W$($.tags)}],
|
|
547
|
+
stability: '${$.stability}',
|
|
548
|
+
scope: '${$.scope??"feature"}',
|
|
549
|
+
},
|
|
550
|
+
rules: [
|
|
551
|
+
{
|
|
552
|
+
effect: 'allow',
|
|
553
|
+
actions: ['read'],
|
|
554
|
+
resource: { type: '${k(r$($))}' },
|
|
555
|
+
reason: 'TODO: replace with real access rules',
|
|
556
|
+
},
|
|
557
|
+
],
|
|
558
|
+
});
|
|
559
|
+
`}function XW($){let b=$.targetVersion??"1.0.0",n=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
560
|
+
|
|
561
|
+
export const ${nb($.key)}TestSpec = defineTestSpec({
|
|
562
|
+
meta: {
|
|
563
|
+
key: '${$.key}',
|
|
564
|
+
version: '${$.version}',
|
|
565
|
+
title: '${k(bb($))}',
|
|
566
|
+
description: '${k($.description)}',
|
|
567
|
+
domain: '${k(r$($))}',
|
|
568
|
+
owners: [${W$($.owners)}],
|
|
569
|
+
tags: [${W$($.tags)}],
|
|
570
|
+
stability: '${$.stability}',
|
|
571
|
+
},
|
|
572
|
+
target: {
|
|
573
|
+
type: '${$.targetType}',
|
|
574
|
+
${$.targetType}: ${n},
|
|
575
|
+
},
|
|
576
|
+
scenarios: [
|
|
577
|
+
{
|
|
578
|
+
key: 'success',
|
|
579
|
+
when: { ${$.targetType}: { key: '${$.targetKey}' } },
|
|
580
|
+
then: [{ type: 'expectOutput', match: {} }],
|
|
581
|
+
},
|
|
582
|
+
],
|
|
583
|
+
});
|
|
584
|
+
`}function YW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
585
|
+
|
|
586
|
+
export const ${nb(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
587
|
+
meta: {
|
|
588
|
+
key: '${$.key}',
|
|
589
|
+
version: '${$.version}',
|
|
590
|
+
domain: '${k(r$($))}',
|
|
591
|
+
description: '${k($.description)}',
|
|
592
|
+
owners: [${W$($.owners)}],
|
|
593
|
+
tags: [${W$($.tags)}],
|
|
594
|
+
stability: '${$.stability}',
|
|
595
|
+
},
|
|
596
|
+
locale: '${$.locale}',
|
|
597
|
+
fallback: '${$.fallback??$.locale}',
|
|
598
|
+
messages: {
|
|
599
|
+
'${$.key}.title': {
|
|
600
|
+
value: '${k(bb($))}',
|
|
601
|
+
description: 'TODO: replace with a real localized message',
|
|
602
|
+
},
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
`}function GW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
|
|
606
|
+
|
|
607
|
+
export const ${nb($.key)}Job = defineJob({
|
|
608
|
+
meta: {
|
|
609
|
+
key: '${$.key}',
|
|
610
|
+
version: '${$.version}',
|
|
611
|
+
title: '${k(bb($))}',
|
|
612
|
+
description: '${k($.description)}',
|
|
613
|
+
domain: '${k(r$($))}',
|
|
614
|
+
owners: [${W$($.owners)}],
|
|
615
|
+
tags: [${W$($.tags)}],
|
|
616
|
+
stability: '${$.stability}',
|
|
617
|
+
},
|
|
618
|
+
payload: { schema: {} },
|
|
619
|
+
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
620
|
+
});
|
|
621
|
+
`}function HW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
622
|
+
|
|
623
|
+
export const ${nb($.key)}Visualization = defineVisualization({
|
|
624
|
+
meta: {
|
|
625
|
+
key: '${$.key}',
|
|
626
|
+
version: '${$.version}',
|
|
627
|
+
title: '${k(bb($))}',
|
|
628
|
+
description: '${k($.description)}',
|
|
629
|
+
goal: 'TODO: describe the decision this visualization supports',
|
|
630
|
+
context: 'TODO: describe where this visualization appears',
|
|
631
|
+
domain: '${k(r$($))}',
|
|
632
|
+
owners: [${W$($.owners)}],
|
|
633
|
+
tags: [${W$($.tags)}],
|
|
634
|
+
stability: '${$.stability}',
|
|
635
|
+
},
|
|
636
|
+
source: {
|
|
637
|
+
primary: {
|
|
638
|
+
key: '${$.sourceOperationKey}',
|
|
639
|
+
version: '${$.sourceOperationVersion??"1.0.0"}',
|
|
640
|
+
},
|
|
641
|
+
resultPath: 'data',
|
|
642
|
+
},
|
|
643
|
+
visualization: {
|
|
644
|
+
kind: 'metric',
|
|
645
|
+
measures: [{ key: 'value', label: 'Value', dataPath: 'value', format: 'number' }],
|
|
646
|
+
measure: 'value',
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
`}function bb($){return $.title??j5($.key.split(".").at(-1)??$.key)}function r$($){return $.domain??$.key.split(".")[0]??"contractspec"}function W$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function nb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function j5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function In($){let b=$.packageName??`@contractspec/example.${S5($.key.split(".").at(-1)??$.key)}`,n=`${Kb($.key)}Example`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
650
|
+
|
|
651
|
+
const ${n} = defineExample({
|
|
652
|
+
meta: {
|
|
653
|
+
key: '${$.key}',
|
|
654
|
+
version: '${$.version}',
|
|
655
|
+
title: '${t(En($))}',
|
|
656
|
+
description: '${t($.description)}',
|
|
657
|
+
kind: 'template',
|
|
658
|
+
visibility: 'experimental',
|
|
659
|
+
stability: '${$.stability}',
|
|
660
|
+
owners: [${S$($.owners)}],
|
|
661
|
+
tags: [${S$($.tags)}],
|
|
662
|
+
},
|
|
663
|
+
surfaces: {
|
|
664
|
+
templates: true,
|
|
665
|
+
sandbox: { enabled: true, modes: ['playground', 'specs'] },
|
|
666
|
+
studio: { enabled: false, installable: false },
|
|
667
|
+
mcp: { enabled: false },
|
|
668
|
+
},
|
|
669
|
+
entrypoints: {
|
|
670
|
+
packageName: '${b}',
|
|
671
|
+
},
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
export default ${n};
|
|
675
|
+
export { ${n} };
|
|
676
|
+
`}function qW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
677
|
+
|
|
678
|
+
export const ${Kb($.key)}Agent = defineAgent({
|
|
679
|
+
meta: {
|
|
680
|
+
key: '${$.key}',
|
|
681
|
+
version: '${$.version}',
|
|
682
|
+
description: '${t($.description)}',
|
|
683
|
+
owners: [${S$($.owners)}],
|
|
684
|
+
tags: [${S$($.tags)}],
|
|
685
|
+
stability: '${$.stability}',
|
|
686
|
+
},
|
|
687
|
+
instructions: '${t($.instructions)}',
|
|
688
|
+
tools: [{ name: 'todo' }],
|
|
689
|
+
});
|
|
690
|
+
`}function OW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
691
|
+
|
|
692
|
+
export const ${Kb($.key)}ProductIntent = defineProductIntentSpec({
|
|
693
|
+
id: '${$.id??`${$.key}-run`}',
|
|
694
|
+
meta: {
|
|
695
|
+
key: '${$.key}',
|
|
696
|
+
version: '${$.version}',
|
|
697
|
+
title: '${t(En($))}',
|
|
698
|
+
description: '${t($.description)}',
|
|
699
|
+
goal: 'TODO: capture the desired product outcome',
|
|
700
|
+
context: 'TODO: capture the decision context',
|
|
701
|
+
stability: '${$.stability}',
|
|
702
|
+
owners: [${S$($.owners)}],
|
|
703
|
+
tags: [${S$($.tags)}],
|
|
704
|
+
},
|
|
705
|
+
question: '${t($.question)}',
|
|
706
|
+
insights: { insights: [] },
|
|
707
|
+
});
|
|
708
|
+
`}function VW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
709
|
+
|
|
710
|
+
export const ${Kb($.key)}HarnessScenario = defineHarnessScenario({
|
|
711
|
+
meta: {
|
|
712
|
+
key: '${$.key}',
|
|
713
|
+
version: '${$.version}',
|
|
714
|
+
title: '${t(En($))}',
|
|
715
|
+
description: '${t($.description)}',
|
|
716
|
+
domain: '${t(UW($))}',
|
|
717
|
+
owners: [${S$($.owners)}],
|
|
718
|
+
tags: [${S$($.tags)}],
|
|
719
|
+
stability: '${$.stability}',
|
|
720
|
+
},
|
|
721
|
+
target: {
|
|
722
|
+
isolation: 'preview',
|
|
723
|
+
preferredTargets: ['preview'],
|
|
724
|
+
},
|
|
725
|
+
allowedModes: ['deterministic-browser'],
|
|
726
|
+
steps: [
|
|
727
|
+
{
|
|
728
|
+
key: 'open-home',
|
|
729
|
+
description: 'Open the target application',
|
|
730
|
+
actionClass: 'navigate',
|
|
731
|
+
intent: 'Navigate to the primary page under test.',
|
|
732
|
+
},
|
|
733
|
+
],
|
|
734
|
+
assertions: [
|
|
735
|
+
{
|
|
736
|
+
key: 'step-completes',
|
|
737
|
+
type: 'step-status',
|
|
738
|
+
description: 'TODO: replace with a real scenario assertion',
|
|
739
|
+
match: 'completed',
|
|
740
|
+
},
|
|
741
|
+
],
|
|
742
|
+
});
|
|
743
|
+
`}function JW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
744
|
+
|
|
745
|
+
export const ${Kb($.key)}HarnessSuite = defineHarnessSuite({
|
|
746
|
+
meta: {
|
|
747
|
+
key: '${$.key}',
|
|
748
|
+
version: '${$.version}',
|
|
749
|
+
title: '${t(En($))}',
|
|
750
|
+
description: '${t($.description)}',
|
|
751
|
+
domain: '${t(UW($))}',
|
|
752
|
+
owners: [${S$($.owners)}],
|
|
753
|
+
tags: [${S$($.tags)}],
|
|
754
|
+
stability: '${$.stability}',
|
|
755
|
+
},
|
|
756
|
+
scenarios: [
|
|
757
|
+
{
|
|
758
|
+
scenario: {
|
|
759
|
+
key: '${$.scenarioKey}',
|
|
760
|
+
version: '${$.scenarioVersion??"1.0.0"}',
|
|
761
|
+
},
|
|
762
|
+
required: true,
|
|
763
|
+
weight: 1,
|
|
764
|
+
},
|
|
765
|
+
],
|
|
766
|
+
summary: '${t($.description)}',
|
|
767
|
+
tags: [${S$($.tags)}],
|
|
768
|
+
});
|
|
769
|
+
`}function En($){return $.title??B5($.key.split(".").at(-1)??$.key)}function UW($){return $.domain??$.key.split(".")[0]??"contractspec"}function S$($){return $.map((b)=>`'${t(b)}'`).join(", ")}function Kb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function B5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function S5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function t($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function LW($){let b=V5($.key.split(".").pop()??"App")+"AppConfig",n=Q5($),A=Z5($),m=KW("dataViews",$.dataViews),y=KW("workflows",$.workflows),W=X5($),w=Y5($),j=G5($),B=H5($),S=q5($),Q=O5($),Z=$.notes?` notes: '${T($.notes)}',
|
|
770
|
+
`:"";return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
771
|
+
|
|
772
|
+
export const ${b} = defineAppConfig({
|
|
773
|
+
meta: {
|
|
774
|
+
key: '${T($.key)}',
|
|
775
|
+
version: '${$.version}',
|
|
525
776
|
title: '${T($.title)}',
|
|
526
777
|
description: '${T($.description)}',
|
|
527
778
|
domain: '${T($.domain)}',
|
|
528
|
-
owners: [${$.owners.map((
|
|
529
|
-
tags: [${$.tags.map((
|
|
779
|
+
owners: [${$.owners.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
780
|
+
tags: [${$.tags.map((X)=>`'${T(X)}'`).join(", ")}],
|
|
530
781
|
stability: '${$.stability}',
|
|
531
782
|
appId: '${T($.appId)}',
|
|
532
783
|
},
|
|
533
|
-
${
|
|
534
|
-
`}function
|
|
535
|
-
`:"",
|
|
784
|
+
${n}${A}${m}${y}${W}${w}${j}${B}${S}${Q}${Z}});
|
|
785
|
+
`}function Q5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((A)=>_W(A)).join(", ")}],
|
|
786
|
+
`:"",n=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((A)=>_W(A)).join(", ")}],
|
|
536
787
|
`:"";return` capabilities: {
|
|
537
|
-
${
|
|
538
|
-
`}function
|
|
539
|
-
`:"",
|
|
788
|
+
${b}${n} },
|
|
789
|
+
`}function Z5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
790
|
+
`:"",n=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
540
791
|
`:"";return` features: {
|
|
541
|
-
${
|
|
542
|
-
`}function
|
|
543
|
-
|
|
544
|
-
|
|
792
|
+
${b}${n} },
|
|
793
|
+
`}function KW($,b){if(b.length===0)return"";let n=b.map((A)=>` ${A.slot}: {
|
|
794
|
+
key: '${T(A.key)}'${A.version?`,
|
|
795
|
+
version: '${A.version}'`:""}
|
|
545
796
|
}`).join(`,
|
|
546
797
|
`);return` ${$}: {
|
|
547
|
-
${
|
|
798
|
+
${n}
|
|
548
799
|
},
|
|
549
|
-
`}function
|
|
550
|
-
${$.policyRefs.map((
|
|
551
|
-
|
|
552
|
-
version: '${
|
|
800
|
+
`}function X5($){if($.policyRefs.length===0)return"";return` policies: [
|
|
801
|
+
${$.policyRefs.map((n)=>` {
|
|
802
|
+
key: '${T(n.key)}'${n.version?`,
|
|
803
|
+
version: '${n.version}'`:""}
|
|
553
804
|
}`).join(`,
|
|
554
805
|
`)}
|
|
555
806
|
],
|
|
556
|
-
`}function
|
|
557
|
-
`,
|
|
807
|
+
`}function Y5($){if(!$.theme)return"";let b=` primary: { key: '${T($.theme.key)}', version: '${$.theme.version}' },
|
|
808
|
+
`,n=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((A)=>`{ key: '${T(A.key)}', version: '${A.version}' }`).join(", ")}],
|
|
558
809
|
`:"";return` theme: {
|
|
559
|
-
${
|
|
560
|
-
`}function
|
|
810
|
+
${b}${n} },
|
|
811
|
+
`}function G5($){if(!$.telemetry)return"";return` telemetry: {
|
|
561
812
|
spec: {
|
|
562
|
-
|
|
813
|
+
key: '${T($.telemetry.key)}'${$.telemetry.version?`,
|
|
563
814
|
version: '${$.telemetry.version}'`:""}
|
|
564
815
|
},
|
|
565
816
|
},
|
|
566
|
-
`}function
|
|
567
|
-
`:"",
|
|
817
|
+
`}function H5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((A)=>zW(A)).join(", ")}],
|
|
818
|
+
`:"",n=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((A)=>zW(A)).join(", ")}],
|
|
568
819
|
`:"";return` experiments: {
|
|
569
|
-
${
|
|
570
|
-
`}function
|
|
571
|
-
${$.featureFlags.map((
|
|
572
|
-
key: '${T(
|
|
573
|
-
enabled: ${
|
|
574
|
-
${
|
|
575
|
-
${
|
|
820
|
+
${b}${n} },
|
|
821
|
+
`}function q5($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
822
|
+
${$.featureFlags.map((n)=>` {
|
|
823
|
+
key: '${T(n.key)}',
|
|
824
|
+
enabled: ${n.enabled},
|
|
825
|
+
${n.variant?`variant: '${T(n.variant)}',`:""}
|
|
826
|
+
${n.description?`description: '${T(n.description)}',`:""}
|
|
576
827
|
}`).join(`,
|
|
577
828
|
`)}
|
|
578
829
|
],
|
|
579
|
-
`}function
|
|
580
|
-
${$.routes.map((
|
|
830
|
+
`}function O5($){if($.routes.length===0)return"";return` routes: [
|
|
831
|
+
${$.routes.map((n)=>{return` { ${[`path: '${T(n.path)}'`,n.label?`label: '${T(n.label)}'`:null,n.dataView?`dataView: '${T(n.dataView)}'`:null,n.workflow?`workflow: '${T(n.workflow)}'`:null,n.guardKey?`guard: { key: '${T(n.guardKey)}'${n.guardVersion?`, version: '${n.guardVersion}'`:""} }`:null,n.featureFlag?`featureFlag: '${T(n.featureFlag)}'`:null,n.experimentKey?`experiment: { key: '${T(n.experimentKey)}'${n.experimentVersion?`, version: '${n.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
581
832
|
`)}
|
|
582
833
|
],
|
|
583
|
-
`}function
|
|
584
|
-
key: '${
|
|
585
|
-
label: '${
|
|
586
|
-
dataPath: '${
|
|
587
|
-
${
|
|
588
|
-
${
|
|
589
|
-
${
|
|
834
|
+
`}function _W($){return`{ key: '${T($)}' }`}function zW($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${T($.key)}'${b} }`}function V5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RW($){let b=J5($.name.split(".").pop()??"DataView")+"DataView",n=$.fields.map((y)=>` {
|
|
835
|
+
key: '${y.key}',
|
|
836
|
+
label: '${Mn(y.label)}',
|
|
837
|
+
dataPath: '${y.dataPath}',
|
|
838
|
+
${y.format?`format: '${y.format}',`:""}
|
|
839
|
+
${y.sortable?"sortable: true,":""}
|
|
840
|
+
${y.filterable?"filterable: true,":""}
|
|
590
841
|
}`).join(`,
|
|
591
|
-
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((
|
|
842
|
+
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((y)=>`'${y}'`).join(", ")}],`:"",m=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
592
843
|
|
|
593
|
-
export const ${
|
|
844
|
+
export const ${b}: DataViewSpec = {
|
|
594
845
|
meta: {
|
|
595
846
|
key: '${$.name}',
|
|
596
847
|
version: ${$.version},
|
|
597
848
|
entity: '${$.entity}',
|
|
598
|
-
title: '${
|
|
599
|
-
description: '${
|
|
600
|
-
domain: '${
|
|
601
|
-
owners: [${$.owners.map((
|
|
602
|
-
tags: [${$.tags.map((
|
|
849
|
+
title: '${Mn($.title)}',
|
|
850
|
+
description: '${Mn($.description||"Describe the purpose of this data view.")}',
|
|
851
|
+
domain: '${Mn($.domain||$.entity)}',
|
|
852
|
+
owners: [${$.owners.map((y)=>`'${y}'`).join(", ")}],
|
|
853
|
+
tags: [${$.tags.map((y)=>`'${y}'`).join(", ")}],
|
|
603
854
|
stability: '${$.stability}',
|
|
604
855
|
},
|
|
605
856
|
source: {
|
|
@@ -607,7 +858,7 @@ export const ${W}: DataViewSpec = {
|
|
|
607
858
|
name: '${$.primaryOperation.name}',
|
|
608
859
|
version: ${$.primaryOperation.version},
|
|
609
860
|
},
|
|
610
|
-
${
|
|
861
|
+
${m}
|
|
611
862
|
refreshEvents: [
|
|
612
863
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
613
864
|
],
|
|
@@ -615,7 +866,7 @@ export const ${W}: DataViewSpec = {
|
|
|
615
866
|
view: {
|
|
616
867
|
kind: '${$.kind}',
|
|
617
868
|
fields: [
|
|
618
|
-
${
|
|
869
|
+
${n}
|
|
619
870
|
],
|
|
620
871
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
621
872
|
${A}
|
|
@@ -633,13 +884,13 @@ ${j}
|
|
|
633
884
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
634
885
|
},
|
|
635
886
|
};
|
|
636
|
-
`}function
|
|
887
|
+
`}function J5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Mn($){return $.replace(/'/g,"\\'")}function Tn({exportName:$,specImportPath:b,rendererName:n,viewKind:A}){return`'use client';
|
|
637
888
|
|
|
638
889
|
import * as React from 'react';
|
|
639
890
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
640
|
-
import { ${$} } from '${
|
|
891
|
+
import { ${$} } from '${b}';
|
|
641
892
|
|
|
642
|
-
export interface ${
|
|
893
|
+
export interface ${n}Props {
|
|
643
894
|
items?: Record<string, unknown>[];
|
|
644
895
|
item?: Record<string, unknown> | null;
|
|
645
896
|
className?: string;
|
|
@@ -652,14 +903,14 @@ export interface ${j}Props {
|
|
|
652
903
|
* Auto-generated renderer for the "${A}" data view.
|
|
653
904
|
* Customize as needed for app-specific behaviour.
|
|
654
905
|
*/
|
|
655
|
-
export function ${
|
|
906
|
+
export function ${n}({
|
|
656
907
|
items = [],
|
|
657
908
|
item = null,
|
|
658
909
|
className,
|
|
659
910
|
renderActions,
|
|
660
911
|
onSelect,
|
|
661
912
|
onRowClick,
|
|
662
|
-
}: ${
|
|
913
|
+
}: ${n}Props) {
|
|
663
914
|
return (
|
|
664
915
|
<DataViewRenderer
|
|
665
916
|
spec={${$}}
|
|
@@ -672,93 +923,93 @@ export function ${j}({
|
|
|
672
923
|
/>
|
|
673
924
|
);
|
|
674
925
|
}
|
|
675
|
-
`}function
|
|
926
|
+
`}function CW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,piiFields:w}=$,j=U5(b.replace(/\./g,"_"))+"V"+n,B=j+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
676
927
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
677
928
|
|
|
678
929
|
// TODO: Define event payload schema
|
|
679
|
-
export const ${
|
|
680
|
-
name: '${
|
|
681
|
-
description: 'Payload for ${
|
|
930
|
+
export const ${B} = new SchemaModel({
|
|
931
|
+
name: '${B}',
|
|
932
|
+
description: 'Payload for ${b}',
|
|
682
933
|
fields: {
|
|
683
934
|
// Add your payload fields here
|
|
684
935
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
685
936
|
},
|
|
686
937
|
});
|
|
687
938
|
|
|
688
|
-
export const ${
|
|
689
|
-
name: '${
|
|
690
|
-
name: '${
|
|
691
|
-
version: '${
|
|
939
|
+
export const ${j} = defineEvent({
|
|
940
|
+
name: '${b}',
|
|
941
|
+
name: '${b}',
|
|
942
|
+
version: '${n}',
|
|
692
943
|
description: '${A}',
|
|
693
944
|
description: '${A}',
|
|
694
|
-
stability: '${
|
|
695
|
-
owners: [${
|
|
696
|
-
tags: [${
|
|
697
|
-
${
|
|
698
|
-
payload: ${
|
|
945
|
+
stability: '${m}',
|
|
946
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
947
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
948
|
+
${w.length>0?`pii: [${w.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
949
|
+
payload: ${B},
|
|
699
950
|
});
|
|
700
|
-
`}function
|
|
701
|
-
${
|
|
702
|
-
type: '${
|
|
703
|
-
target: '${
|
|
704
|
-
${typeof
|
|
951
|
+
`}function U5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function xW($){let b=_5($.name.split(".").pop()??"Experiment")+"Experiment",n=$.variants.map((y)=>{let W=y.overrides?.length?` overrides: [
|
|
952
|
+
${y.overrides.map((w)=>` {
|
|
953
|
+
type: '${w.type}',
|
|
954
|
+
target: '${h(w.target)}',
|
|
955
|
+
${typeof w.version==="string"?`version: ${w.version},`:""}
|
|
705
956
|
}`).join(`,
|
|
706
957
|
`)}
|
|
707
958
|
],`:"";return` {
|
|
708
|
-
id: '${
|
|
709
|
-
name: '${
|
|
710
|
-
${
|
|
711
|
-
${typeof
|
|
712
|
-
${
|
|
959
|
+
id: '${h(y.id)}',
|
|
960
|
+
name: '${h(y.name)}',
|
|
961
|
+
${y.description?`description: '${h(y.description)}',`:""}
|
|
962
|
+
${typeof y.weight==="number"?`weight: ${y.weight},`:""}
|
|
963
|
+
${W}
|
|
713
964
|
}`}).join(`,
|
|
714
|
-
`),A=
|
|
715
|
-
${$.successMetrics.map((
|
|
716
|
-
name: '${
|
|
717
|
-
telemetryEvent: { name: '${
|
|
718
|
-
aggregation: '${
|
|
719
|
-
${typeof
|
|
965
|
+
`),A=K5($.allocation),m=$.successMetrics?.length?` successMetrics: [
|
|
966
|
+
${$.successMetrics.map((y)=>` {
|
|
967
|
+
name: '${h(y.name)}',
|
|
968
|
+
telemetryEvent: { name: '${h(y.eventName)}', version: ${typeof y.eventVersion==="string"?`'${y.eventVersion}'`:y.eventVersion} },
|
|
969
|
+
aggregation: '${y.aggregation}',
|
|
970
|
+
${typeof y.target==="number"?`target: ${y.target},`:""}
|
|
720
971
|
}`).join(`,
|
|
721
972
|
`)}
|
|
722
973
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
723
974
|
|
|
724
|
-
export const ${
|
|
975
|
+
export const ${b}: ExperimentSpec = {
|
|
725
976
|
meta: {
|
|
726
|
-
key: '${
|
|
977
|
+
key: '${h($.name)}',
|
|
727
978
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
728
|
-
title: '${
|
|
729
|
-
description: '${
|
|
730
|
-
domain: '${
|
|
731
|
-
owners: [${$.owners.map((
|
|
732
|
-
tags: [${$.tags.map((
|
|
979
|
+
title: '${h($.name)} experiment',
|
|
980
|
+
description: '${h($.description||"Describe the experiment goal.")}',
|
|
981
|
+
domain: '${h($.domain)}',
|
|
982
|
+
owners: [${$.owners.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
983
|
+
tags: [${$.tags.map((y)=>`'${h(y)}'`).join(", ")}],
|
|
733
984
|
stability: '${$.stability}',
|
|
734
985
|
},
|
|
735
|
-
controlVariant: '${
|
|
986
|
+
controlVariant: '${h($.controlVariant)}',
|
|
736
987
|
variants: [
|
|
737
|
-
${
|
|
988
|
+
${n}
|
|
738
989
|
],
|
|
739
990
|
allocation: ${A},
|
|
740
|
-
${
|
|
991
|
+
${m}
|
|
741
992
|
};
|
|
742
|
-
`}function
|
|
993
|
+
`}function K5($){switch($.type){case"random":return`{
|
|
743
994
|
type: 'random',
|
|
744
|
-
${$.salt?`salt: '${
|
|
995
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
745
996
|
}`;case"sticky":return`{
|
|
746
997
|
type: 'sticky',
|
|
747
998
|
attribute: '${$.attribute}',
|
|
748
|
-
${$.salt?`salt: '${
|
|
999
|
+
${$.salt?`salt: '${h($.salt)}',`:""}
|
|
749
1000
|
}`;case"targeted":return`{
|
|
750
1001
|
type: 'targeted',
|
|
751
1002
|
rules: [
|
|
752
|
-
${$.rules.map((
|
|
753
|
-
variantId: '${
|
|
754
|
-
${typeof
|
|
755
|
-
${
|
|
756
|
-
${
|
|
1003
|
+
${$.rules.map((b)=>` {
|
|
1004
|
+
variantId: '${h(b.variantId)}',
|
|
1005
|
+
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1006
|
+
${b.policy?`policy: { name: '${h(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1007
|
+
${b.expression?`expression: '${h(b.expression)}',`:""}
|
|
757
1008
|
}`).join(`,
|
|
758
1009
|
`)}
|
|
759
1010
|
],
|
|
760
1011
|
fallback: '${$.fallback??"control"}',
|
|
761
|
-
}`;default:return
|
|
1012
|
+
}`;default:return z5($)}}function _5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function h($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function z5($){throw Error(`Unsupported allocation type ${$}`)}function L5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function IW($){let b=(n)=>n.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
762
1013
|
`);return`/**
|
|
763
1014
|
* ${$.title} Feature
|
|
764
1015
|
*
|
|
@@ -767,35 +1018,35 @@ ${$.rules.map((W)=>` {
|
|
|
767
1018
|
|
|
768
1019
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
769
1020
|
|
|
770
|
-
export const ${
|
|
1021
|
+
export const ${L5($.key)}Feature = defineFeature({
|
|
771
1022
|
meta: {
|
|
772
1023
|
key: '${$.key}',
|
|
773
1024
|
version: '${$.version}',
|
|
774
1025
|
title: '${$.title}',
|
|
775
1026
|
description: '${$.description||"TODO: Add description"}',
|
|
776
1027
|
domain: '${$.domain}',
|
|
777
|
-
owners: [${$.owners.map((
|
|
778
|
-
tags: [${$.tags.map((
|
|
1028
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1029
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
779
1030
|
stability: '${$.stability||"beta"}',
|
|
780
1031
|
},
|
|
781
1032
|
|
|
782
1033
|
operations: [
|
|
783
|
-
${
|
|
1034
|
+
${b($.operations)||" // Add operations here"}
|
|
784
1035
|
],
|
|
785
1036
|
|
|
786
1037
|
events: [
|
|
787
|
-
${
|
|
1038
|
+
${b($.events)||" // Add events here"}
|
|
788
1039
|
],
|
|
789
1040
|
|
|
790
1041
|
presentations: [
|
|
791
|
-
${
|
|
1042
|
+
${b($.presentations)||" // Add presentations here"}
|
|
792
1043
|
],
|
|
793
1044
|
|
|
794
1045
|
experiments: [
|
|
795
|
-
${
|
|
1046
|
+
${b($.experiments)||" // Add experiments here"}
|
|
796
1047
|
],
|
|
797
1048
|
});
|
|
798
|
-
`}function
|
|
1049
|
+
`}function R5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function EW($){let b=R5($.key),n=`${b}FormModel`,A=`${b}Form`;return`/**
|
|
799
1050
|
* ${$.title} Form
|
|
800
1051
|
*
|
|
801
1052
|
* Auto-generated form spec.
|
|
@@ -804,8 +1055,8 @@ ${W($.experiments)||" // Add experiments here"}
|
|
|
804
1055
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
805
1056
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
806
1057
|
|
|
807
|
-
const ${
|
|
808
|
-
name: '${
|
|
1058
|
+
const ${n} = defineSchemaModel({
|
|
1059
|
+
name: '${n}',
|
|
809
1060
|
description: '${$.description||"TODO: Add form model description"}',
|
|
810
1061
|
fields: {
|
|
811
1062
|
${$.primaryFieldKey}: {
|
|
@@ -822,11 +1073,11 @@ export const ${A} = defineFormSpec({
|
|
|
822
1073
|
title: '${$.title}',
|
|
823
1074
|
description: '${$.description||"TODO: Add description"}',
|
|
824
1075
|
domain: '${$.domain}',
|
|
825
|
-
owners: [${$.owners.map((
|
|
826
|
-
tags: [${$.tags.map((
|
|
1076
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1077
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
827
1078
|
stability: '${$.stability||"beta"}',
|
|
828
1079
|
},
|
|
829
|
-
model: ${
|
|
1080
|
+
model: ${n},
|
|
830
1081
|
fields: [
|
|
831
1082
|
{
|
|
832
1083
|
kind: 'text',
|
|
@@ -851,17 +1102,17 @@ export const ${A} = defineFormSpec({
|
|
|
851
1102
|
form: 'react-hook-form',
|
|
852
1103
|
},
|
|
853
1104
|
});
|
|
854
|
-
`}function
|
|
855
|
-
import { ${A} } from '../contracts/${
|
|
1105
|
+
`}function MW($,b){let n=C5($.split(".").pop()||"unknown")+"Handler",A=Dn($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1106
|
+
import { ${A} } from '../contracts/${NW($)}.contracts';
|
|
856
1107
|
|
|
857
1108
|
/**
|
|
858
1109
|
* Handler for ${$}
|
|
859
1110
|
*/
|
|
860
|
-
export const ${
|
|
1111
|
+
export const ${n}: ContractHandler<typeof ${A}> = async (
|
|
861
1112
|
input,
|
|
862
1113
|
context
|
|
863
1114
|
) => {
|
|
864
|
-
// TODO: Implement ${
|
|
1115
|
+
// TODO: Implement ${b} logic
|
|
865
1116
|
|
|
866
1117
|
try {
|
|
867
1118
|
// 1. Validate prerequisites
|
|
@@ -877,28 +1128,28 @@ export const ${j}: ContractHandler<typeof ${A}> = async (
|
|
|
877
1128
|
throw error;
|
|
878
1129
|
}
|
|
879
1130
|
};
|
|
880
|
-
`}function
|
|
1131
|
+
`}function TW($,b){let n=Dn($);return`import React from 'react';
|
|
881
1132
|
|
|
882
|
-
interface ${
|
|
1133
|
+
interface ${n}Props {
|
|
883
1134
|
// TODO: Define props based on presentation spec
|
|
884
1135
|
}
|
|
885
1136
|
|
|
886
1137
|
/**
|
|
887
|
-
* ${
|
|
1138
|
+
* ${b}
|
|
888
1139
|
*/
|
|
889
|
-
export const ${
|
|
1140
|
+
export const ${n}: React.FC<${n}Props> = (props) => {
|
|
890
1141
|
return (
|
|
891
1142
|
<div>
|
|
892
1143
|
{/* TODO: Implement component UI */}
|
|
893
|
-
<p>Component: ${
|
|
1144
|
+
<p>Component: ${n}</p>
|
|
894
1145
|
</div>
|
|
895
1146
|
);
|
|
896
1147
|
};
|
|
897
|
-
`}function
|
|
898
|
-
import { ${A} } from '${
|
|
1148
|
+
`}function DW($,b){let n=b==="handler"?"../handlers":"../components",A=Dn($);return`import { describe, it, expect } from 'bun:test';
|
|
1149
|
+
import { ${A} } from '${n}/${NW($)}';
|
|
899
1150
|
|
|
900
1151
|
describe('${A}', () => {
|
|
901
|
-
it('should ${
|
|
1152
|
+
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
902
1153
|
// TODO: Implement test
|
|
903
1154
|
expect(true).toBe(true);
|
|
904
1155
|
});
|
|
@@ -907,50 +1158,50 @@ describe('${A}', () => {
|
|
|
907
1158
|
// TODO: Test edge cases
|
|
908
1159
|
});
|
|
909
1160
|
|
|
910
|
-
${
|
|
1161
|
+
${b==="handler"?`it('should handle errors appropriately', async () => {
|
|
911
1162
|
// TODO: Test error scenarios
|
|
912
1163
|
});`:`it('should be accessible', async () => {
|
|
913
1164
|
// TODO: Test accessibility
|
|
914
1165
|
});`}
|
|
915
1166
|
});
|
|
916
|
-
`}function
|
|
917
|
-
`),
|
|
918
|
-
${$.capabilitiesRequired.map((
|
|
1167
|
+
`}function C5($){let b=Dn($);return b.charAt(0).toLowerCase()+b.slice(1)}function Dn($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function NW($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function FW($){let b=v5($.name.split(".").pop()??"Integration"),n=`${b}IntegrationSpec`,A=`register${b}Integration`,m=$.supportedModes.length?$.supportedModes:["managed"],y=m.map((G)=>`'${G}'`).join(", "),W=$.capabilitiesProvided.map((G)=>` { key: '${G.key}', version: '${G.version}' }`).join(`,
|
|
1168
|
+
`),w=$.capabilitiesRequired.length>0?` requires: [
|
|
1169
|
+
${$.capabilitiesRequired.map((G)=>{let V=G.version!==void 0?`, version: '${G.version}'`:"",O=G.optional?", optional: true":"",K=G.reason?`, reason: '${w$(G.reason)}'`:"";return` { key: '${G.key}'${V}${O}${K} }`}).join(`,
|
|
919
1170
|
`)}
|
|
920
|
-
],`:"",
|
|
921
|
-
`:"",
|
|
1171
|
+
],`:"",j=x5($.configFields),B=E5($.configFields),S=I5($.secretFields),Q=M5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
|
|
1172
|
+
`:"",X=T5($.rateLimitRpm,$.rateLimitRph),Y=D5(m,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
922
1173
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
923
1174
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
924
1175
|
|
|
925
|
-
export const ${
|
|
1176
|
+
export const ${n}: IntegrationSpec = {
|
|
926
1177
|
meta: {
|
|
927
1178
|
key: '${$.name}',
|
|
928
1179
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
929
1180
|
category: '${$.category}',
|
|
930
|
-
displayName: '${
|
|
931
|
-
title: '${
|
|
932
|
-
description: '${
|
|
933
|
-
domain: '${
|
|
934
|
-
owners: [${$.owners.map((
|
|
935
|
-
tags: [${$.tags.map((
|
|
936
|
-
stability: StabilityEnum.${
|
|
937
|
-
},
|
|
938
|
-
supportedModes: [${
|
|
1181
|
+
displayName: '${w$($.displayName)}',
|
|
1182
|
+
title: '${w$($.title)}',
|
|
1183
|
+
description: '${w$($.description)}',
|
|
1184
|
+
domain: '${w$($.domain)}',
|
|
1185
|
+
owners: [${$.owners.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1186
|
+
tags: [${$.tags.map((G)=>`'${w$(G)}'`).join(", ")}],
|
|
1187
|
+
stability: StabilityEnum.${F5($.stability)},
|
|
1188
|
+
},
|
|
1189
|
+
supportedModes: [${y}],
|
|
939
1190
|
capabilities: {
|
|
940
1191
|
provides: [
|
|
941
|
-
${
|
|
1192
|
+
${W}
|
|
942
1193
|
],
|
|
943
|
-
${
|
|
1194
|
+
${w.length>0?`${w}
|
|
944
1195
|
`:""} },
|
|
945
1196
|
configSchema: {
|
|
946
|
-
${
|
|
947
|
-
example: ${
|
|
1197
|
+
${j}
|
|
1198
|
+
example: ${B},
|
|
948
1199
|
},
|
|
949
1200
|
secretSchema: {
|
|
950
|
-
${
|
|
951
|
-
example: ${
|
|
1201
|
+
${S}
|
|
1202
|
+
example: ${Q},
|
|
952
1203
|
},
|
|
953
|
-
${
|
|
1204
|
+
${Z}${X}${Y} healthCheck: {
|
|
954
1205
|
method: '${$.healthCheckMethod}',
|
|
955
1206
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
956
1207
|
},
|
|
@@ -959,118 +1210,118 @@ ${G}${J}${b} healthCheck: {
|
|
|
959
1210
|
export function ${A}(
|
|
960
1211
|
registry: IntegrationSpecRegistry
|
|
961
1212
|
): IntegrationSpecRegistry {
|
|
962
|
-
return registry.register(${
|
|
1213
|
+
return registry.register(${n});
|
|
963
1214
|
}
|
|
964
|
-
`}function
|
|
965
|
-
`:"",A=$.length?$.map((
|
|
1215
|
+
`}function x5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1216
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: '${N5(m.type)}'${y} }`}).join(`,
|
|
966
1217
|
`):"";return` schema: {
|
|
967
1218
|
type: 'object',
|
|
968
|
-
${
|
|
1219
|
+
${n} properties: {
|
|
969
1220
|
${A||" "}
|
|
970
1221
|
},
|
|
971
1222
|
},
|
|
972
|
-
`}function
|
|
973
|
-
`:"",A=$.length?$.map((
|
|
1223
|
+
`}function I5($){let b=$.filter((m)=>m.required),n=b.length>0?` required: [${b.map((m)=>`'${m.key}'`).join(", ")}],
|
|
1224
|
+
`:"",A=$.length?$.map((m)=>{let y=m.description?`, description: '${w$(m.description)}'`:"";return` ${m.key}: { type: 'string'${y} }`}).join(`,
|
|
974
1225
|
`):"";return` schema: {
|
|
975
1226
|
type: 'object',
|
|
976
|
-
${
|
|
1227
|
+
${n} properties: {
|
|
977
1228
|
${A||" "}
|
|
978
1229
|
},
|
|
979
1230
|
},
|
|
980
|
-
`}function
|
|
981
|
-
${$.map((
|
|
1231
|
+
`}function E5($){if($.length===0)return"{}";return`{
|
|
1232
|
+
${$.map((n)=>{switch(n.type){case"number":return` ${n.key}: 0`;case"boolean":return` ${n.key}: true`;case"string":default:return` ${n.key}: '${n.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
982
1233
|
`)}
|
|
983
|
-
}`}function
|
|
984
|
-
${$.map((
|
|
1234
|
+
}`}function M5($){if($.length===0)return"{}";return`{
|
|
1235
|
+
${$.map((n)=>` ${n.key}: '${n.key.toUpperCase()}_SECRET'`).join(`,
|
|
985
1236
|
`)}
|
|
986
|
-
}`}function
|
|
1237
|
+
}`}function T5($,b){if($==null&&b==null)return"";let n=[];if($!=null)n.push(` rpm: ${$}`);if(b!=null)n.push(` rph: ${b}`);return` constraints: {
|
|
987
1238
|
rateLimit: {
|
|
988
|
-
${
|
|
1239
|
+
${n.join(`,
|
|
989
1240
|
`)}
|
|
990
1241
|
},
|
|
991
1242
|
},
|
|
992
|
-
`}function
|
|
993
|
-
`:"",
|
|
994
|
-
`:"";if(!A&&!
|
|
995
|
-
${A}${
|
|
996
|
-
`}function
|
|
1243
|
+
`}function D5($,b,n){if(!$.includes("byok"))return"";let A=b?` setupInstructions: '${w$(b)}',
|
|
1244
|
+
`:"",m=n&&n.length?` requiredScopes: [${n.map((y)=>`'${w$(y)}'`).join(", ")}],
|
|
1245
|
+
`:"";if(!A&&!m)return"";return` byokSetup: {
|
|
1246
|
+
${A}${m} },
|
|
1247
|
+
`}function N5($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function F5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function v5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function w$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function vW($){let b=f5($.name.split(".").pop()??"KnowledgeSpace"),n=`${b}KnowledgeSpace`,A=`register${b}KnowledgeSpace`,m=g5($),y=P5($),W=k5($),w=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
997
1248
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
998
1249
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
999
1250
|
|
|
1000
|
-
export const ${
|
|
1251
|
+
export const ${n}: KnowledgeSpaceSpec = {
|
|
1001
1252
|
meta: {
|
|
1002
1253
|
key: '${$.name}',
|
|
1003
1254
|
version: ${$.version},
|
|
1004
1255
|
category: '${$.category}',
|
|
1005
|
-
displayName: '${
|
|
1006
|
-
title: '${
|
|
1007
|
-
description: '${
|
|
1008
|
-
domain: '${
|
|
1009
|
-
owners: [${$.owners.map((
|
|
1010
|
-
tags: [${$.tags.map((
|
|
1011
|
-
stability: StabilityEnum.${
|
|
1012
|
-
},
|
|
1013
|
-
retention: ${
|
|
1256
|
+
displayName: '${O$($.displayName)}',
|
|
1257
|
+
title: '${O$($.title)}',
|
|
1258
|
+
description: '${O$($.description)}',
|
|
1259
|
+
domain: '${O$($.domain)}',
|
|
1260
|
+
owners: [${$.owners.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1261
|
+
tags: [${$.tags.map((j)=>`'${O$(j)}'`).join(", ")}],
|
|
1262
|
+
stability: StabilityEnum.${r5($.stability)},
|
|
1263
|
+
},
|
|
1264
|
+
retention: ${m},
|
|
1014
1265
|
access: {
|
|
1015
|
-
${
|
|
1266
|
+
${y}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${w}
|
|
1016
1267
|
`:""} },
|
|
1017
|
-
${
|
|
1268
|
+
${W} description: '${O$($.description||$.displayName)}',
|
|
1018
1269
|
};
|
|
1019
1270
|
|
|
1020
1271
|
export function ${A}(
|
|
1021
1272
|
registry: KnowledgeSpaceRegistry
|
|
1022
1273
|
): KnowledgeSpaceRegistry {
|
|
1023
|
-
return registry.register(${
|
|
1274
|
+
return registry.register(${n});
|
|
1024
1275
|
}
|
|
1025
|
-
`}function
|
|
1026
|
-
`,
|
|
1027
|
-
`;return`${
|
|
1028
|
-
${
|
|
1276
|
+
`}function g5($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",n=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${n} }`}function P5($){let b=` trustLevel: '${$.trustLevel}',
|
|
1277
|
+
`,n=` automationWritable: ${$.automationWritable},
|
|
1278
|
+
`;return`${b}${n}`}function k5($){let b=[];if($.embeddingModel)b.push(` embeddingModel: '${O$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")b.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)b.push(` vectorDbIntegration: '${O$($.vectorDbIntegration)}'`);if(b.length===0)return"";return` indexing: {
|
|
1279
|
+
${b.join(`,
|
|
1029
1280
|
`)}
|
|
1030
1281
|
},
|
|
1031
|
-
`}function
|
|
1282
|
+
`}function r5($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function f5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function O$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function PW($){let n=`${c5($.name.split(".").pop()??"Migration")}Migration`,A=$.dependencies.length>0?`dependencies: [${$.dependencies.map((m)=>`'${m}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1032
1283
|
|
|
1033
|
-
export const ${
|
|
1284
|
+
export const ${n}: MigrationSpec = {
|
|
1034
1285
|
meta: {
|
|
1035
1286
|
key: '${$.name}',
|
|
1036
1287
|
version: ${$.version},
|
|
1037
|
-
title: '${
|
|
1038
|
-
description: '${
|
|
1039
|
-
domain: '${
|
|
1040
|
-
owners: [${$.owners.map((
|
|
1041
|
-
tags: [${$.tags.map((
|
|
1288
|
+
title: '${f$($.title)}',
|
|
1289
|
+
description: '${f$($.description??"")}',
|
|
1290
|
+
domain: '${f$($.domain)}',
|
|
1291
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1292
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1042
1293
|
stability: '${$.stability}',
|
|
1043
1294
|
},
|
|
1044
1295
|
plan: {
|
|
1045
1296
|
up: [
|
|
1046
|
-
${
|
|
1297
|
+
${gW($.up)}
|
|
1047
1298
|
],${$.down&&$.down.length?`
|
|
1048
1299
|
down: [
|
|
1049
|
-
${
|
|
1300
|
+
${gW($.down)}
|
|
1050
1301
|
],`:""}
|
|
1051
1302
|
},
|
|
1052
1303
|
${A}
|
|
1053
1304
|
};
|
|
1054
|
-
`}function
|
|
1305
|
+
`}function gW($){return $.map((b)=>{let n=b.description?`description: '${f$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1055
1306
|
kind: 'schema',
|
|
1056
|
-
${
|
|
1057
|
-
sql: \`${
|
|
1307
|
+
${n}
|
|
1308
|
+
sql: \`${f$(b.sql??"")}\`,
|
|
1058
1309
|
}`;case"data":return` {
|
|
1059
1310
|
kind: 'data',
|
|
1060
|
-
${
|
|
1061
|
-
script: \`${
|
|
1311
|
+
${n}
|
|
1312
|
+
script: \`${f$(b.script??"")}\`,
|
|
1062
1313
|
}`;case"validation":default:return` {
|
|
1063
1314
|
kind: 'validation',
|
|
1064
|
-
${
|
|
1065
|
-
assertion: \`${
|
|
1315
|
+
${n}
|
|
1316
|
+
assertion: \`${f$(b.assertion??"")}\`,
|
|
1066
1317
|
}`}}).join(`,
|
|
1067
|
-
`)}function
|
|
1318
|
+
`)}function c5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function kW($){let{name:b,version:n,kind:A,description:m,goal:y,context:W,stability:w,owners:j,tags:B,auth:S,flags:Q}=$,Z=h5(b.split(".").pop()||"Unknown")+"Spec",X=Z.replace("Spec","Input"),Y=Z.replace("Spec","Output");return`import { define${q0(A)} } from '@contractspec/lib.contracts-spec';
|
|
1068
1319
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1069
1320
|
|
|
1070
1321
|
// TODO: Define input schema
|
|
1071
|
-
export const ${
|
|
1072
|
-
name: '${
|
|
1073
|
-
description: 'Input for ${
|
|
1322
|
+
export const ${X} = new SchemaModel({
|
|
1323
|
+
name: '${X}',
|
|
1324
|
+
description: 'Input for ${b}',
|
|
1074
1325
|
fields: {
|
|
1075
1326
|
// Add your fields here
|
|
1076
1327
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
@@ -1078,32 +1329,32 @@ export const ${J} = new SchemaModel({
|
|
|
1078
1329
|
});
|
|
1079
1330
|
|
|
1080
1331
|
// TODO: Define output schema
|
|
1081
|
-
export const ${
|
|
1082
|
-
name: '${
|
|
1083
|
-
description: 'Output for ${
|
|
1332
|
+
export const ${Y} = new SchemaModel({
|
|
1333
|
+
name: '${Y}',
|
|
1334
|
+
description: 'Output for ${b}',
|
|
1084
1335
|
fields: {
|
|
1085
1336
|
// Add your fields here
|
|
1086
1337
|
ok: { type: ScalarTypeEnum.Boolean(), isOptional: false },
|
|
1087
1338
|
},
|
|
1088
1339
|
});
|
|
1089
1340
|
|
|
1090
|
-
export const ${
|
|
1341
|
+
export const ${Z} = define${q0(A)}({
|
|
1091
1342
|
meta: {
|
|
1092
|
-
key: '${
|
|
1093
|
-
key: '${
|
|
1094
|
-
version: '${
|
|
1095
|
-
stability: '${
|
|
1096
|
-
stability: '${
|
|
1097
|
-
owners: [${
|
|
1098
|
-
tags: [${
|
|
1099
|
-
description: '${
|
|
1100
|
-
goal: '${
|
|
1101
|
-
context: '${
|
|
1343
|
+
key: '${b}',
|
|
1344
|
+
key: '${b}',
|
|
1345
|
+
version: '${n}',
|
|
1346
|
+
stability: '${w}',
|
|
1347
|
+
stability: '${w}',
|
|
1348
|
+
owners: [${j.map((G)=>`'${G}'`).join(", ")}],
|
|
1349
|
+
tags: [${B.map((G)=>`'${G}'`).join(", ")}],
|
|
1350
|
+
description: '${m}',
|
|
1351
|
+
goal: '${y}',
|
|
1352
|
+
context: '${W}',
|
|
1102
1353
|
},
|
|
1103
1354
|
|
|
1104
1355
|
io: {
|
|
1105
|
-
input: ${
|
|
1106
|
-
output: ${
|
|
1356
|
+
input: ${X},
|
|
1357
|
+
output: ${Y},
|
|
1107
1358
|
errors: {
|
|
1108
1359
|
// Define possible errors
|
|
1109
1360
|
// EXAMPLE_ERROR: {
|
|
@@ -1115,8 +1366,8 @@ export const ${G} = define${_1(A)}({
|
|
|
1115
1366
|
},
|
|
1116
1367
|
|
|
1117
1368
|
policy: {
|
|
1118
|
-
auth: '${
|
|
1119
|
-
${
|
|
1369
|
+
auth: '${S}',
|
|
1370
|
+
${Q.length>0?`flags: [${Q.map((G)=>`'${G}'`).join(", ")}],`:"// flags: [],"}
|
|
1120
1371
|
},
|
|
1121
1372
|
|
|
1122
1373
|
sideEffects: {
|
|
@@ -1131,8 +1382,8 @@ export const ${G} = define${_1(A)}({
|
|
|
1131
1382
|
|
|
1132
1383
|
transport: {
|
|
1133
1384
|
rest: { method: '${A==="command"?"POST":"GET"}' },
|
|
1134
|
-
gql: { field: '${
|
|
1135
|
-
mcp: { toolName: '${
|
|
1385
|
+
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1386
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(n).replace(/\./g,"_")}' },
|
|
1136
1387
|
},
|
|
1137
1388
|
|
|
1138
1389
|
acceptance: {
|
|
@@ -1153,13 +1404,13 @@ export const ${G} = define${_1(A)}({
|
|
|
1153
1404
|
],
|
|
1154
1405
|
},
|
|
1155
1406
|
});
|
|
1156
|
-
`}function
|
|
1407
|
+
`}function q0($){return $.charAt(0).toUpperCase()+$.slice(1)}function h5($){return $.split(/[-_.]/).map(q0).join("")}function rW($){let{name:b,version:n,description:A,stability:m,owners:y,tags:W,presentationKind:w}=$,j=d5(b.replace(/\./g,"_"))+"Presentation",B="";switch(w){case"web_component":B=` content: {
|
|
1157
1408
|
kind: 'web_component',
|
|
1158
1409
|
framework: 'react',
|
|
1159
|
-
componentKey: '${
|
|
1410
|
+
componentKey: '${b.replace(/\./g,"_")}',
|
|
1160
1411
|
props: new SchemaModel({
|
|
1161
|
-
name: '${
|
|
1162
|
-
description: 'Props for ${
|
|
1412
|
+
name: '${j}Props',
|
|
1413
|
+
description: 'Props for ${b}',
|
|
1163
1414
|
fields: {
|
|
1164
1415
|
// TODO: Define component props
|
|
1165
1416
|
},
|
|
@@ -1167,20 +1418,20 @@ export const ${G} = define${_1(A)}({
|
|
|
1167
1418
|
analytics: [
|
|
1168
1419
|
// TODO: Define analytics events
|
|
1169
1420
|
],
|
|
1170
|
-
},`;break;case"markdown":
|
|
1421
|
+
},`;break;case"markdown":B=` content: {
|
|
1171
1422
|
kind: 'markdown',
|
|
1172
1423
|
content: \`
|
|
1173
1424
|
# ${A}
|
|
1174
1425
|
|
|
1175
1426
|
TODO: Add markdown content here
|
|
1176
1427
|
\`,
|
|
1177
|
-
// Or use resourceUri: 'feature://${
|
|
1178
|
-
},`;break;case"data":
|
|
1428
|
+
// Or use resourceUri: 'feature://${b}/guide.md'
|
|
1429
|
+
},`;break;case"data":B=` content: {
|
|
1179
1430
|
kind: 'data',
|
|
1180
1431
|
mimeType: 'application/json',
|
|
1181
1432
|
model: new SchemaModel({
|
|
1182
|
-
name: '${
|
|
1183
|
-
description: 'Data structure for ${
|
|
1433
|
+
name: '${j}Data',
|
|
1434
|
+
description: 'Data structure for ${b}',
|
|
1184
1435
|
fields: {
|
|
1185
1436
|
// TODO: Define data structure
|
|
1186
1437
|
},
|
|
@@ -1188,13 +1439,13 @@ TODO: Add markdown content here
|
|
|
1188
1439
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1189
1440
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1190
1441
|
|
|
1191
|
-
export const ${
|
|
1442
|
+
export const ${j}: PresentationSpec = {
|
|
1192
1443
|
meta: {
|
|
1193
|
-
key: '${
|
|
1194
|
-
version: ${
|
|
1195
|
-
stability: '${
|
|
1196
|
-
owners: [${
|
|
1197
|
-
tags: [${
|
|
1444
|
+
key: '${b}',
|
|
1445
|
+
version: ${n},
|
|
1446
|
+
stability: '${m}',
|
|
1447
|
+
owners: [${y.map((S)=>`'${S}'`).join(", ")}],
|
|
1448
|
+
tags: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1198
1449
|
description: '${A}',
|
|
1199
1450
|
},
|
|
1200
1451
|
|
|
@@ -1203,81 +1454,109 @@ export const ${B}: PresentationSpec = {
|
|
|
1203
1454
|
// pii: [],
|
|
1204
1455
|
},
|
|
1205
1456
|
|
|
1206
|
-
${
|
|
1457
|
+
${B}
|
|
1207
1458
|
};
|
|
1208
|
-
`}function
|
|
1209
|
-
${$.providers.map((
|
|
1210
|
-
type: '${
|
|
1211
|
-
config: ${
|
|
1459
|
+
`}function d5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function fW($){let b=u5($.name.split(".").pop()??"Telemetry")+"Telemetry",n=$.providers?.length?`providers: [
|
|
1460
|
+
${$.providers.map((m)=>` {
|
|
1461
|
+
type: '${m.type}',
|
|
1462
|
+
config: ${o5(m.config)},
|
|
1212
1463
|
}`).join(`,
|
|
1213
1464
|
`)}
|
|
1214
|
-
],`:"",A=$.events.map((
|
|
1215
|
-
type: '${
|
|
1216
|
-
${
|
|
1217
|
-
${
|
|
1218
|
-
${
|
|
1219
|
-
${
|
|
1465
|
+
],`:"",A=$.events.map((m)=>{let y=m.properties.map((w)=>` '${w.name}': {
|
|
1466
|
+
type: '${w.type}',
|
|
1467
|
+
${w.required?"required: true,":""}
|
|
1468
|
+
${w.pii?"pii: true,":""}
|
|
1469
|
+
${w.redact?"redact: true,":""}
|
|
1470
|
+
${w.description?`description: '${l(w.description)}',`:""}
|
|
1220
1471
|
}`).join(`,
|
|
1221
|
-
`),
|
|
1472
|
+
`),W=m.anomalyRules?.length?` anomalyDetection: {
|
|
1222
1473
|
enabled: true,
|
|
1223
|
-
${typeof
|
|
1474
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1224
1475
|
thresholds: [
|
|
1225
|
-
${
|
|
1226
|
-
metric: '${
|
|
1227
|
-
${typeof
|
|
1228
|
-
${typeof
|
|
1476
|
+
${m.anomalyRules.map((w)=>` {
|
|
1477
|
+
metric: '${l(w.metric)}',
|
|
1478
|
+
${typeof w.min==="number"?`min: ${w.min},`:""}
|
|
1479
|
+
${typeof w.max==="number"?`max: ${w.max},`:""}
|
|
1229
1480
|
}`).join(`,
|
|
1230
1481
|
`)}
|
|
1231
1482
|
],
|
|
1232
|
-
actions: [${(
|
|
1233
|
-
},`:
|
|
1483
|
+
actions: [${(m.anomalyActions??[]).map((w)=>`'${w}'`).join(", ")}],
|
|
1484
|
+
},`:m.anomalyEnabled?` anomalyDetection: {
|
|
1234
1485
|
enabled: true,
|
|
1235
|
-
${typeof
|
|
1486
|
+
${typeof m.anomalyMinimumSample==="number"?`minimumSample: ${m.anomalyMinimumSample},`:""}
|
|
1236
1487
|
},`:"";return` {
|
|
1237
|
-
name: '${
|
|
1238
|
-
version: ${
|
|
1488
|
+
name: '${l(m.name)}',
|
|
1489
|
+
version: ${m.version},
|
|
1239
1490
|
semantics: {
|
|
1240
|
-
what: '${
|
|
1241
|
-
${
|
|
1242
|
-
${
|
|
1491
|
+
what: '${l(m.what)}',
|
|
1492
|
+
${m.who?`who: '${l(m.who)}',`:""}
|
|
1493
|
+
${m.why?`why: '${l(m.why)}',`:""}
|
|
1243
1494
|
},
|
|
1244
|
-
privacy: '${
|
|
1495
|
+
privacy: '${m.privacy}',
|
|
1245
1496
|
properties: {
|
|
1246
|
-
${
|
|
1497
|
+
${y}
|
|
1247
1498
|
},
|
|
1248
|
-
${typeof
|
|
1249
|
-
${typeof
|
|
1250
|
-
${
|
|
1251
|
-
${
|
|
1499
|
+
${typeof m.retentionDays==="number"?`retention: { days: ${m.retentionDays}, ${m.retentionPolicy?`policy: '${m.retentionPolicy}'`:""} },`:""}
|
|
1500
|
+
${typeof m.samplingRate==="number"?`sampling: { rate: ${m.samplingRate}${m.samplingConditions?`, conditions: ['${l(m.samplingConditions)}']`:""} },`:""}
|
|
1501
|
+
${W}
|
|
1502
|
+
${m.tags?.length?`tags: [${m.tags.map((w)=>`'${l(w)}'`).join(", ")}],`:""}
|
|
1252
1503
|
}`}).join(`,
|
|
1253
1504
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1254
1505
|
|
|
1255
|
-
export const ${
|
|
1506
|
+
export const ${b}: TelemetrySpec = {
|
|
1256
1507
|
meta: {
|
|
1257
|
-
key: '${
|
|
1508
|
+
key: '${l($.name)}',
|
|
1258
1509
|
version: ${$.version},
|
|
1259
|
-
title: '${
|
|
1260
|
-
description: '${
|
|
1261
|
-
domain: '${
|
|
1262
|
-
owners: [${$.owners.map((
|
|
1263
|
-
tags: [${$.tags.map((
|
|
1510
|
+
title: '${l($.name)} telemetry',
|
|
1511
|
+
description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1512
|
+
domain: '${l($.domain)}',
|
|
1513
|
+
owners: [${$.owners.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1514
|
+
tags: [${$.tags.map((m)=>`'${l(m)}'`).join(", ")}],
|
|
1264
1515
|
stability: '${$.stability}',
|
|
1265
1516
|
},
|
|
1266
1517
|
config: {
|
|
1267
1518
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1268
1519
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1269
1520
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1270
|
-
${
|
|
1521
|
+
${n}
|
|
1271
1522
|
},
|
|
1272
1523
|
events: [
|
|
1273
1524
|
${A}
|
|
1274
1525
|
],
|
|
1275
1526
|
};
|
|
1276
|
-
`}function
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1527
|
+
`}function u5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function o5($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function i5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function cW($){return`/**
|
|
1528
|
+
* ${$.title} Theme
|
|
1529
|
+
*
|
|
1530
|
+
* Auto-generated theme spec.
|
|
1531
|
+
*/
|
|
1532
|
+
|
|
1533
|
+
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1534
|
+
|
|
1535
|
+
export const ${i5($.key)}Theme = defineTheme({
|
|
1536
|
+
meta: {
|
|
1537
|
+
key: '${$.key}',
|
|
1538
|
+
version: '${$.version}',
|
|
1539
|
+
title: '${$.title}',
|
|
1540
|
+
description: '${$.description}',
|
|
1541
|
+
domain: '${$.domain}',
|
|
1542
|
+
owners: [${$.owners.map((b)=>`'${b}'`).join(", ")}],
|
|
1543
|
+
tags: [${$.tags.map((b)=>`'${b}'`).join(", ")}],
|
|
1544
|
+
stability: '${$.stability}',
|
|
1545
|
+
scopes: [${$.scopes.map((b)=>`'${b}'`).join(", ")}],
|
|
1546
|
+
},
|
|
1547
|
+
tokens: {
|
|
1548
|
+
colors: {
|
|
1549
|
+
primary: { value: '#2563eb' },
|
|
1550
|
+
background: { value: '#ffffff' },
|
|
1551
|
+
foreground: { value: '#111827' },
|
|
1552
|
+
},
|
|
1553
|
+
},
|
|
1554
|
+
});
|
|
1555
|
+
`}function hW($){let b=l5($.name.split(".").pop()??"Workflow")+"Workflow",n=$.steps.map((m)=>t5(m)).join(`,
|
|
1556
|
+
`),A=$.transitions.map((m)=>` {
|
|
1557
|
+
from: '${m.from}',
|
|
1558
|
+
to: '${m.to}',
|
|
1559
|
+
${m.condition?` condition: '${Ab(m.condition)}',`:""}
|
|
1281
1560
|
}`).join(`,
|
|
1282
1561
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1283
1562
|
|
|
@@ -1289,36 +1568,36 @@ ${Q.condition?` condition: '${h$(Q.condition)}',`:""}
|
|
|
1289
1568
|
* - Provide form renderers for human steps.
|
|
1290
1569
|
* - Add guards/conditions as needed.
|
|
1291
1570
|
*/
|
|
1292
|
-
export const ${
|
|
1571
|
+
export const ${b}: WorkflowSpec = {
|
|
1293
1572
|
meta: {
|
|
1294
1573
|
key: '${$.name}',
|
|
1295
1574
|
version: ${$.version},
|
|
1296
|
-
title: '${
|
|
1297
|
-
description: '${
|
|
1298
|
-
domain: '${
|
|
1575
|
+
title: '${Ab($.title)}',
|
|
1576
|
+
description: '${Ab($.description)}',
|
|
1577
|
+
domain: '${Ab($.domain)}',
|
|
1299
1578
|
stability: '${$.stability}',
|
|
1300
|
-
owners: [${$.owners.map((
|
|
1301
|
-
tags: [${$.tags.map((
|
|
1579
|
+
owners: [${$.owners.map((m)=>`'${m}'`).join(", ")}],
|
|
1580
|
+
tags: [${$.tags.map((m)=>`'${m}'`).join(", ")}],
|
|
1302
1581
|
},
|
|
1303
1582
|
definition: {
|
|
1304
1583
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1305
1584
|
`:""} steps: [
|
|
1306
|
-
${
|
|
1585
|
+
${n}
|
|
1307
1586
|
],
|
|
1308
1587
|
transitions: [
|
|
1309
1588
|
${A}
|
|
1310
1589
|
],
|
|
1311
1590
|
},
|
|
1312
1591
|
${$.policyFlags.length>0?`policy: {
|
|
1313
|
-
flags: [${$.policyFlags.map((
|
|
1592
|
+
flags: [${$.policyFlags.map((m)=>`'${m}'`).join(", ")}],
|
|
1314
1593
|
},`:"// policy: { flags: [] },"}
|
|
1315
1594
|
};
|
|
1316
|
-
`}function
|
|
1317
|
-
`)}function
|
|
1595
|
+
`}function t5($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${Ab($.label)}',`];if($.description)b.push(` description: '${Ab($.description)}',`);let n=[];if($.operation)n.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)n.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(n.length)b.push(` action: { ${n.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1596
|
+
`)}function l5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ab($){return $.replace(/'/g,"\\'")}function Nn({exportName:$,specImportPath:b,workflowFunctionName:n}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1318
1597
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1319
|
-
import { ${$} } from '${
|
|
1598
|
+
import { ${$} } from '${b}';
|
|
1320
1599
|
|
|
1321
|
-
export async function ${
|
|
1600
|
+
export async function ${n}(input = {}, bridge = {}) {
|
|
1322
1601
|
"use workflow";
|
|
1323
1602
|
|
|
1324
1603
|
// Keep the workflow function deterministic.
|
|
@@ -1335,29 +1614,29 @@ export async function ${j}(input = {}, bridge = {}) {
|
|
|
1335
1614
|
},
|
|
1336
1615
|
});
|
|
1337
1616
|
}
|
|
1338
|
-
`}function
|
|
1339
|
-
import { ${
|
|
1617
|
+
`}function Fn($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1618
|
+
import { ${b} } from '${$}';
|
|
1340
1619
|
|
|
1341
1620
|
export const POST = createWorkflowDevkitStartRoute({
|
|
1342
|
-
workflow: ${
|
|
1621
|
+
workflow: ${b},
|
|
1343
1622
|
async buildArgs(body) {
|
|
1344
1623
|
return [body];
|
|
1345
1624
|
},
|
|
1346
1625
|
});
|
|
1347
|
-
`}function
|
|
1626
|
+
`}function vn(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1348
1627
|
|
|
1349
1628
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1350
1629
|
resolveToken({ runId }) {
|
|
1351
1630
|
return \`workflow-session:\${runId}\`;
|
|
1352
1631
|
},
|
|
1353
1632
|
});
|
|
1354
|
-
`}function
|
|
1633
|
+
`}function gn(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1355
1634
|
|
|
1356
1635
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1357
|
-
`}function
|
|
1636
|
+
`}function Pn($,b){return`import { ${b} } from '${$}';
|
|
1358
1637
|
|
|
1359
1638
|
export const workflowDevkitBootstrap = {
|
|
1360
|
-
workflow: ${
|
|
1639
|
+
workflow: ${b},
|
|
1361
1640
|
createBridge() {
|
|
1362
1641
|
return {
|
|
1363
1642
|
executeAutomationStep: async () => {
|
|
@@ -1366,10 +1645,10 @@ export const workflowDevkitBootstrap = {
|
|
|
1366
1645
|
};
|
|
1367
1646
|
},
|
|
1368
1647
|
};
|
|
1369
|
-
`}function
|
|
1648
|
+
`}function kn({exportName:$,specImportPath:b,runnerName:n,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1370
1649
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1371
1650
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1372
|
-
import { ${$} } from '${
|
|
1651
|
+
import { ${$} } from '${b}';
|
|
1373
1652
|
|
|
1374
1653
|
/**
|
|
1375
1654
|
* Runner wiring for ${A}.
|
|
@@ -1384,7 +1663,7 @@ registry.register(${$});
|
|
|
1384
1663
|
|
|
1385
1664
|
const stateStore = new InMemoryStateStore();
|
|
1386
1665
|
|
|
1387
|
-
export const ${
|
|
1666
|
+
export const ${n} = new WorkflowRunner({
|
|
1388
1667
|
registry,
|
|
1389
1668
|
stateStore,
|
|
1390
1669
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1406,12 +1685,12 @@ export const ${j} = new WorkflowRunner({
|
|
|
1406
1685
|
// console.log(event, payload);
|
|
1407
1686
|
},
|
|
1408
1687
|
});
|
|
1409
|
-
`}import{getAuthoringTargetDefinition as
|
|
1410
|
-
`],[
|
|
1688
|
+
`}import{getAuthoringTargetDefinition as p5}from"@contractspec/module.workspace";var uW={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function oW($,b){let n=a5($,b.specPath),A=e5($,b.target,n),m=$.join(n,"package.json"),y=$.join(n,"README.md"),W=$.join(n,"src"),w=$.join(W,"index.ts"),j=O0($.relative(W,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(W);let B=[[m,JSON.stringify({name:A,version:"0.1.0",description:uW[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1689
|
+
`],[y,`# ${A}
|
|
1411
1690
|
|
|
1412
|
-
${
|
|
1413
|
-
`],[
|
|
1414
|
-
`],[
|
|
1691
|
+
${uW[b.target]}.
|
|
1692
|
+
`],[w,`export * from "./${j.startsWith(".")?j:`./${j}`}";
|
|
1693
|
+
`],[b.specPath,b.specCode]],S={packageRoot:n,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function rn($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1415
1694
|
|
|
1416
1695
|
export const ${$.exportName} = defineModuleBundle({
|
|
1417
1696
|
meta: {
|
|
@@ -1436,7 +1715,15 @@ export const ${$.exportName} = defineModuleBundle({
|
|
|
1436
1715
|
layouts: [],
|
|
1437
1716
|
data: [],
|
|
1438
1717
|
verification: {
|
|
1439
|
-
|
|
1718
|
+
dimensions: {
|
|
1719
|
+
guidance: "Scaffolded guidance profile for ${$.title}.",
|
|
1720
|
+
density: "Scaffolded density profile for ${$.title}.",
|
|
1721
|
+
dataDepth: "Scaffolded data-depth profile for ${$.title}.",
|
|
1722
|
+
control: "Scaffolded control profile for ${$.title}.",
|
|
1723
|
+
media: "Scaffolded media profile for ${$.title}.",
|
|
1724
|
+
pace: "Scaffolded pace profile for ${$.title}.",
|
|
1725
|
+
narrative: "Scaffolded narrative profile for ${$.title}.",
|
|
1726
|
+
},
|
|
1440
1727
|
},
|
|
1441
1728
|
},
|
|
1442
1729
|
},
|
|
@@ -1472,22 +1759,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1472
1759
|
supportedArtifactTypes: ["patch"],
|
|
1473
1760
|
knownConstraints: [],
|
|
1474
1761
|
};
|
|
1475
|
-
`}}function
|
|
1762
|
+
`}}function a5($,b){let n=O0(b),A="/src/",m=n.lastIndexOf("/src/");if(m===-1)return $.dirname(b);return n.slice(0,m)}function e5($,b,n){let A=p5(b),m=O0($.basename(n));return`${A.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${m}`}function O0($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function yb($,b,n,A={}){let{fs:m,logger:y,workspace:W}=b,w=W?.scanSpecSource??y8,j=W?.inferSpecTypeFromFilePath??m8,B=W?.generateHandlerTemplate??b8,S=W?.generateComponentTemplate??$8,Q=W?.generateTestTemplate??n8,{targets:Z=void 0,outputDir:X=n.outputDir,overwrite:Y=!1,dryRun:G=!1,includeTests:V=!1,runtimeGeneration:O}=A,K=await m.readFile($),J=w(K,$),U=s5(K,$),H=U==="unknown"?j($):U,q=Z??J0(H,{includeTests:V});y.info(`Building from spec: ${$}`,{targetId:H});let _=[],z={};for(let L of q)try{let C=await W8(L,$,K,J,H,{fs:m,logger:y},X,Y,G,O,z,{genHandler:B,genComponent:S,genTest:Q});if(_.push(C),C.success&&C.generatedCode)z[L]=C.generatedCode}catch(C){_.push({target:L,outputPath:"",success:!1,error:C instanceof Error?C.message:String(C),skipped:!1})}return{specPath:$,specInfo:J,targetId:H,results:_}}async function W8($,b,n,A,m,y,W,w,j,B,S,Q){let{fs:Z,logger:X}=y,{genHandler:Y,genComponent:G,genTest:V}=Q,O,K,J=[];switch($){case"handler":{if(m!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${m})`};let q=A.kind==="command"||A.kind==="query"?A.kind:"command",_=Y(s(n,A,b),q);K=mb(b,W,"handlers",s(n,A,b),".handler.ts",y.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:n,outputPath:K,fallbackCode:_})??_;break}case"component":{if(m!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${m})`};let q=G(s(n,A,b),A.description??"");K=mb(b,W,"components",s(n,A,b),".tsx",y.fs),O=await B?.generateArtifact?.({kind:"component",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"test":{let q=m==="operation"?"handler":"component",_=m==="operation"?S.handler??"":m==="presentation"?S.component??"":m==="form"?S.form??"":"",z=V(s(n,A,b),q);K=mb(b,W,"__tests__",s(n,A,b),".test.ts",y.fs),O=await B?.generateTest?.({kind:q,specCode:n,outputPath:K,existingCode:_,fallbackCode:z})??z;break}case"form":{if(m!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${m})`};let q=`import * as React from "react";
|
|
1476
1763
|
|
|
1477
|
-
export interface ${
|
|
1764
|
+
export interface ${V$(s(n,A,b))}Props {
|
|
1478
1765
|
className?: string;
|
|
1479
1766
|
}
|
|
1480
1767
|
|
|
1481
|
-
export function ${
|
|
1768
|
+
export function ${V$(s(n,A,b))}Form({
|
|
1482
1769
|
className,
|
|
1483
|
-
}: ${
|
|
1484
|
-
return <form className={className}>TODO: implement ${
|
|
1770
|
+
}: ${V$(s(n,A,b))}Props) {
|
|
1771
|
+
return <form className={className}>TODO: implement ${s(n,A,b)}</form>;
|
|
1485
1772
|
}
|
|
1486
|
-
`;
|
|
1773
|
+
`;K=mb(b,W,"forms",s(n,A,b),".form.tsx",y.fs),O=await B?.generateArtifact?.({kind:"form",specCode:n,outputPath:K,fallbackCode:q})??q;break}case"workflow-runner":{if(m!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${m})`};let q=s(n,A,b),_=S8(n)??`${V$(q)}Workflow`,z=`${V$(q)}Runner`,L=U0(q);if(K=mb(b,W,"workflows",q,".runner.ts",y.fs),O=kn({exportName:_,specImportPath:V0(y.fs,K,b),runnerName:z,workflowName:q}),X8(n)){let C=`${V$(q)}WorkflowDevkit`,D=_b(y.fs,K,`${L}.workflow-devkit.ts`),F=_b(y.fs,K,`${L}.workflow-devkit.start.route.ts`),E=_b(y.fs,K,`${L}.workflow-devkit.follow-up.route.ts`),r=_b(y.fs,K,`${L}.workflow-devkit.stream.route.ts`),g=_b(y.fs,K,`${L}.workflow-devkit.generic.ts`);J=[{path:D,code:Nn({exportName:_,specImportPath:V0(y.fs,D,b),workflowFunctionName:C})},{path:F,code:Fn(iW(y.fs,F,D),C)},{path:E,code:vn()},{path:r,code:gn()},{path:g,code:Pn(iW(y.fs,g,D),C)}]}break}case"data-view-renderer":{if(m!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${m})`};let q=s(n,A,b),_=Q8(n)??`${V$(q)}DataView`,z=`${V$(q)}Renderer`;K=mb(b,W,"data-views",q,".renderer.tsx",y.fs),O=Tn({exportName:_,specImportPath:V0(y.fs,K,b),rendererName:z,viewKind:Z8(n)??"table"});break}case"package-scaffold":{if(m!=="module-bundle"&&m!=="builder-spec"&&m!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${m})`};if(j){let z=j8(b);return X.info(`[dry-run] Would scaffold package: ${z}`),{target:$,outputPath:z,success:!0}}let q=n.trim().length>0?n:rn({target:m,key:A.key??y.fs.basename(b),title:A.key??y.fs.basename(b),description:A.description??A8(m).title,exportName:V$(A.key??y.fs.basename(b))});return K=(await oW(y.fs,{target:m,specPath:b,specCode:q,overwrite:w})).packageRoot,X.info(`Generated package scaffold: ${K}`),{target:$,outputPath:K,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let U=[{path:K,code:O},...J],H=w?void 0:await w8(U,Z);if(H)return{target:$,outputPath:H,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(j){for(let q of U)X.info(`[dry-run] Would write: ${q.path}`);return{target:$,outputPath:K,success:!0,generatedCode:U[0]?.code}}for(let q of U)await Z.mkdir(Z.dirname(q.path)),await Z.writeFile(q.path,Y8(q.code)),X.info(`Generated: ${q.path}`);return{target:$,outputPath:K,success:!0}}function J0($,b){switch($){case"operation":return b.includeTests?["handler","test"]:["handler"];case"presentation":return b.includeTests?["component","test"]:["component"];case"form":return b.includeTests?["form","test"]:["form"];case"workflow":return["workflow-runner"];case"data-view":return["data-view-renderer"];case"module-bundle":case"builder-spec":case"provider-spec":return["package-scaffold"];default:return[]}}function mb($,b,n,A,m,y){let W=U0(A.split(".").pop()??"unknown"),w;if(b.startsWith("."))w=y.resolve(y.dirname($),"..",b,n);else w=y.resolve(b,n);return y.join(w,`${W}${m}`)}async function w8($,b){for(let n of $)if(await b.exists(n.path))return n.path;return}function U0($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function V$($){return U0($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function K0($){return $.replace(/\.[^.]+$/,"")}function j8($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function V0($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function iW($,b,n){let A=K0($.relative($.dirname(b),n));return A.startsWith(".")?A:`./${A}`}function _b($,b,n){return $.join($.dirname(b),n)}function s($,b,n){return B8($,"name")??b.key??K0(G8(n))}function B8($,b){let n=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(n)?.[1]??null}function S8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function Q8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function Z8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function X8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function Y8($){return $.endsWith(`
|
|
1487
1774
|
`)?$:`${$}
|
|
1488
|
-
`}function dZ($){return $.replaceAll("\\","/").split("/").pop()??$}i();import{scanAllSpecsFromSource as iZ,scanSpecSource as pZ}from"@contractspec/module.workspace";import tZ from"micromatch";var K8={};h(K8,{validators:()=>oZ,urlSchema:()=>lZ,isValidVersion:()=>cZ,isValidIdentifier:()=>b8,isValidDotName:()=>w8,isTestFile:()=>j0,isLibraryDefinitionFile:()=>A0,emailSchema:()=>rZ});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 cZ($){return Number.isInteger($)&&$>0}var rZ=H$.string().email(),lZ=H$.string().url(),oZ={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 aZ($){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 sZ($,W,j){if($.specType==="unknown")return!1;if(W.type&&!j.includes($.specType))return!1;return!0}function eZ($,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:aZ(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&&tZ.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=iZ(X,Z),B=Y.length>0?Y:[pZ(X,Z)];for(let q of B)if(sZ(q,W,A))Q.push(q)}catch{}}return Q.sort(eZ)}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=$6(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 $6($,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 W6,buildReverseEdges as j6,createContractGraph as A6,detectCycles as Q6,findMissingDependencies as Z6,parseImportedSpecNames as X6,toDot as Y6}from"@contractspec/module.workspace";async function _8($,W={}){let{fs:j}=$,A=await N$(j,{config:W.config,pattern:W.pattern}),Q=A6();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=X6(B,Y);W6(Q,H,q,V)}j6(Q);let Z=Q6(Q),X=Z6(Q);return{graph:Q,total:Q.size,cycles:Z,missing:X}}function pJ($,W){return $.get(W)}function tJ($){return Y6($)}function aJ($){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(" \u2192 ")}`,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 B6}from"@contractspec/module.workspace";var q6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function H6($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:q6}),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 H6($,W);for(let Q of A){let Z=B6({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 V6($,W);if(A.push(Q),Q.status==="pass")A.push(await G6($,W,j));return A}async function V6($,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 G6($,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+=`
|
|
1489
|
-
`}return
|
|
1490
|
-
`,await $.writeFile(
|
|
1775
|
+
`}function G8($){return $.replaceAll("\\","/").split("/").pop()??$}$$();import{scanAllSpecsFromSource as U8,scanSpecSource as K8}from"@contractspec/module.workspace";import _8 from"micromatch";var aW={};f(aW,{validators:()=>J8,urlSchema:()=>V8,isValidVersion:()=>q8,isValidIdentifier:()=>lW,isValidDotName:()=>pW,isTestFile:()=>zb,isLibraryDefinitionFile:()=>Lb,emailSchema:()=>O8});import _0 from"micromatch";function zb($,b){let n=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return _0.isMatch($,n)}function Lb($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(_0.isMatch($,b))return!1;let n=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return _0.isMatch($,n)}import*as J$ from"zod";function lW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function pW($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function q8($){return Number.isInteger($)&&$>0}var O8=J$.string().email(),V8=J$.string().url(),J8={specName:J$.string().refine(pW,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:J$.number().int().positive(),identifier:J$.string().refine(lW,{message:"Must be a valid TypeScript identifier"}),owner:J$.string().startsWith("@"),tag:J$.string().min(1)};function Rb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function z8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],n=[...Rb($?.conventions.models),...Rb($?.conventions.operations),...Rb($?.conventions.events),...Rb($?.conventions.presentations),...Rb($?.conventions.forms)];return[...new Set(b.flatMap((A)=>{let m=A==="**"?"":`${A}/`,y=q$.map((w)=>`${m}${w}`),W=n.map((w)=>`${m}${w}/**/*.ts`);return[...y,...W]}))]}function L8($,b,n){if($.specType==="unknown")return!1;if(b.type&&!n.includes($.specType))return!1;return!0}function R8($,b){let n=$.filePath.localeCompare(b.filePath);if(n!==0)return n;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function c$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((n,A)=>n.localeCompare(A));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:z8(b.config)})}async function cn($,b={}){let n=await c$($.fs,b),A=b.type?Array.isArray(b.type)?b.type:[b.type]:[],m=[];for(let y of n){if(b.config?.excludePackages&&_8.isMatch(y,b.config.excludePackages,{contains:!0}))continue;if(y.includes("node_modules")||y.includes("/dist/")||zb(y,b.config)||Lb(y))continue;try{let W=await $.fs.readFile(y),w=U8(W,y),j=w.length>0?w:[K8(W,y)];for(let B of j)if(L8(B,b,A))m.push(B)}catch{}}return m.sort(R8)}function L$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function hn($){let b=JSON.parse($),n=new Map,A=0,m=0,y=0,W=0,w=0,j=0,B=0,S=0;for(let[Z,X]of Object.entries(b)){let Y=C8(Z,X);n.set(Z,Y),A+=Y.statements.total,m+=Y.statements.covered,y+=Y.branches.total,W+=Y.branches.covered,w+=Y.functions.total,j+=Y.functions.covered,B+=Y.lines.total,S+=Y.lines.covered}let Q={statements:{covered:m,total:A,pct:L$(m,A)},branches:{covered:W,total:y,pct:L$(W,y)},functions:{covered:j,total:w,pct:L$(j,w)},lines:{covered:S,total:B,pct:L$(S,B)}};return{files:n,total:Q}}function C8($,b){let n=Object.keys(b.statementMap).length,A=Object.values(b.s).filter((S)=>S>0).length,m=Object.keys(b.fnMap).length,y=Object.values(b.f).filter((S)=>S>0).length,W=0,w=0;for(let S of Object.values(b.b))W+=S.length,w+=S.filter((Q)=>Q>0).length;let j=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(j.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:A,total:n,pct:L$(A,n)},branches:{covered:w,total:W,pct:L$(w,W)},functions:{covered:y,total:m,pct:L$(y,m)},lines:{covered:B.size,total:j.size,pct:L$(B.size,j.size)}}}function z0($){switch($){case"istanbul":return{parse:hn};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function L0($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function R0($,b,n,A){let m=[];if(n.statements!==void 0&&A.statements.pct<n.statements)m.push({metric:"statements",required:n.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${n.statements}%`});if(n.branches!==void 0&&A.branches.pct<n.branches)m.push({metric:"branches",required:n.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${n.branches}%`});if(n.functions!==void 0&&A.functions.pct<n.functions)m.push({metric:"functions",required:n.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${n.functions}%`});if(n.lines!==void 0&&A.lines.pct<n.lines)m.push({metric:"lines",required:n.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${n.lines}%`});if(n.mutations!==void 0)m.push({metric:"mutations",required:n.mutations,actual:0,message:`Mutation coverage required (${n.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:n,actual:A,passed:m.length===0,failures:m}}async function C0($,b,n){let{fs:A,logger:m}=$,y=[],W=n.workspaceRoot?`${n.workspaceRoot}/coverage`:"./coverage",w=[`${W}/coverage-final.json`,`${W}/coverage.json`,`${W}/coverage-summary.json`],j,B;for(let X of w)if(await A.exists(X)){j=await A.readFile(X),B=X;break}if(!j)return m.info("No coverage report found, skipping coverage checks"),y;let S=L0(B??"coverage.json"),Z=z0(S).parse(j);for(let X of b){if(X.specType!=="test-spec"||!X.key||!X.version||!X.sourceBlock)continue;let Y=X.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!Y||!Y[1])continue;let G=Y[1],V={},O=G.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=G.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=G.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let U=G.match(/lines\s*:\s*(\d+)/);if(U&&U[1])V.lines=parseInt(U[1],10);if(Object.keys(V).length===0)continue;let H=R0(X.key,X.version,V,Z.total);for(let q of H.failures)y.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:X.filePath,context:{specKey:X.key,specVersion:X.version,metric:q.metric,required:q.required,actual:q.actual}})}return y}$$();import{addContractNode as x8,buildReverseEdges as I8,createContractGraph as E8,detectCycles as M8,findMissingDependencies as T8,parseImportedSpecNames as D8,toDot as N8}from"@contractspec/module.workspace";async function eW($,b={}){let{fs:n}=$,A=await c$(n,{config:b.config,pattern:b.pattern}),m=E8();for(let w of A){let j=await n.readFile(w),B=n.relative(".",w),S=n.basename(w).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=D8(j,w);x8(m,S,B,Q)}I8(m);let y=M8(m),W=T8(m);return{graph:m,total:m.size,cycles:y,missing:W}}function VO($,b){return $.get(b)}function JO($){return N8($)}function UO($){let b=Array.from($.values()),n=b.filter((W)=>W.dependencies.length>0),A=b.filter((W)=>W.dependencies.length===0),m=b.filter((W)=>W.dependents.length>0),y=b.filter((W)=>W.dependents.length===0);return{total:$.size,withDeps:n.length,withoutDeps:A.length,used:m.length,unused:y.length}}async function x0($,b){let n=[],A=await P($.fs),m=await eW($,{config:A,pattern:b.pattern});for(let y of m.cycles)n.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${y.join(" \u2192 ")}`,category:"deps",context:{cycle:y}});for(let y of m.missing)for(let W of y.missing)n.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${y.contract} requires ${W}`,category:"deps",context:{contract:y.contract,missing:W}});return n}import{analyzePackageDocBlocks as F8}from"@contractspec/module.workspace";var v8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function g8($,b){let n=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:v8}),A=new Map;for(let W of n){let w=$.dirname(W),j=$.join(w,"src");if(!await $.exists(j))continue;try{let B=JSON.parse(await $.readFile(W));A.set(w,{packageName:B.name??$.relative(b,w),packageRoot:w,srcRoot:j})}catch{continue}}let m=$.join(b,"package.json"),y=$.join(b,"src");if(await $.exists(m)&&await $.exists(y))try{let W=JSON.parse(await $.readFile(m));A.set(b,{packageName:W.name??b,packageRoot:b,srcRoot:y})}catch{}return[...A.values()].sort((W,w)=>W.packageRoot.localeCompare(w.packageRoot))}async function dn($,b){let n=[],A=await g8($,b);for(let m of A){let y=F8({packageName:m.packageName,srcRoot:m.srcRoot});for(let W of y.diagnostics)n.push({...W,packageName:m.packageName,packageRoot:m.packageRoot,srcRoot:m.srcRoot})}return n}async function I0($,b){let n=b.workspaceRoot??process.cwd();return(await dn($.fs,n)).map((m)=>({ruleId:m.ruleId,severity:m.severity==="warning"?"warning":"error",message:m.message,category:"docs",file:m.file,line:m.line,column:m.column,context:{packageName:m.packageName,packageRoot:m.packageRoot,...m.context}}))}async function E0($,b,n){let A=[],m=await P8($,b);if(A.push(m),m.status==="pass")A.push(await k8($,b,n));return A}async function P8($,b){let n=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(n))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let m=await $.readFile(n),y=JSON.parse(m),W=y.aiProvider??"claude",w=y.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${W}, Model: ${w}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function k8($,b,n){let A=$.join(b.workspaceRoot,".contractsrc.json");try{let m=await $.readFile(A),W=JSON.parse(m).aiProvider??"claude",j={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[W];if(!j)return{category:"ai",name:"API Key",status:"pass",message:`${W} does not require an API key`};if(!!process.env[j])return{category:"ai",name:"API Key",status:"pass",message:`${j} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${j} not set`,details:`Set ${j} in your environment to use AI features`,fix:n?{description:`Set ${j} environment variable`,apply:async()=>{let S=await n.input(`Enter your ${W} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${j}=`))return{success:!1,message:`${j} already in .env, update manually`};Z+=`
|
|
1776
|
+
`}return Z+=`${j}=${S}
|
|
1777
|
+
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${j} to .env (restart required)`}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as r8}from"child_process";import{promisify as f8}from"util";var un=f8(r8);async function M0($,b){let n=[];return n.push(await c8(b)),n.push(await h8(b)),n.push(await d8($,b)),n}async function c8($){try{return await un("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4}),{category:"cli",name:"CLI Accessible",status:"pass",message:"ContractSpec CLI is accessible"}}catch{return{category:"cli",name:"CLI Accessible",status:"fail",message:"ContractSpec CLI is not accessible",details:'Could not run "bunx contractspec --version"',fix:{description:"Install ContractSpec CLI globally",apply:async()=>{try{return await un("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(b){return{success:!1,message:`Failed to install: ${b instanceof Error?b.message:String(b)}`}}}}}}}async function h8($){try{let{stdout:b}=await un("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${b.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function d8($,b){let n=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(n))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let w=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(w))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let m=await $.readFile(n),y=JSON.parse(m);if(y.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||y.devDependencies?.["@contractspec/app.cli-contractspec"]!==void 0)return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is installed as a project dependency"};return{category:"cli",name:"Local Installation",status:"warn",message:"CLI is not installed as a project dependency",details:"Consider adding @contractspec/app.cli-contractspec to devDependencies",fix:{description:"Add CLI as a dev dependency",apply:async()=>{try{return await un("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(w){return{success:!1,message:`Failed to install: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}$$();import{DEFAULT_CONTRACTSRC as on}from"@contractspec/lib.contracts-spec/workspace-config";import{join as u8,relative as o8}from"path";var i8="contractspec",t8="contractsrc.schema.json";function l8($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Cb($){return l8(o8($.configRoot,u8($.workspaceRoot,"node_modules",i8,t8)))}var xb=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],sW={"cli-config":"CLI Configuration (.contractsrc.json)","biome-config":"Biome Configuration (biome.jsonc + plugins)","vscode-settings":"VS Code Settings (.vscode/settings.json)","mcp-cursor":"MCP for Cursor (.cursor/mcp.json)","mcp-claude":"MCP for Claude Desktop","cursor-rules":"Cursor AI Rules (.cursor/rules/)","agents-md":"AI Agent Guide (AGENTS.md)","usage-md":"Usage Guide (USAGE.md)"},$w=["core","connect","builder-managed","builder-local","builder-hybrid"],bw={core:"Core workspace setup",connect:"Connect-enabled setup","builder-managed":"Builder setup (managed runtime)","builder-local":"Builder setup (local runtime)","builder-hybrid":"Builder setup (hybrid runtime)"},nw={core:"Generic ContractSpec workspace files and editor wiring.",connect:"Core workspace setup plus Connect config, artifact storage, and adapter defaults.","builder-managed":"Core workspace setup plus Builder config for managed runtime and API-based next steps.","builder-local":"Core workspace setup plus Builder config for local runtime registration and control-plane-backed next steps.","builder-hybrid":"Core workspace setup plus Builder config for hybrid runtime with API and local defaults."};var Ib={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function Eb($){if($?.builder?.enabled)switch($.builder.runtimeMode){case"local":return"builder-local";case"hybrid":return"builder-hybrid";default:return"builder-managed"}if($?.connect?.enabled)return"connect";return"core"}function R$($){return $.preset??"core"}function Aw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return xb}}function T0($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function mw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function PO($){return $.startsWith("builder-")}function kO($){return $==="connect"}function yw($){let b=R$($),n=p8($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset managed-mvp`,`contractspec builder status --workspace-id ${n}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${n} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${n} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function p8($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function Ww($){let b=R$($),n=[Ib.verificationCache];if(b==="connect")n.unshift(Ib.connect);return n}function Wb($){let b=$.isMonorepo&&$.scope==="package",n=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,A=a8($),m=e8($);return{$schema:Cb({configRoot:n,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...A?{connect:A}:{},...m?{builder:m}:{},...b&&$.packageName?{package:$.packageName}:{}}}function tn($){let b=R$($),n={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(T0(b))n["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return n}function Mb(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function ww(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function jw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1491
1778
|
|
|
1492
1779
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1493
1780
|
|
|
@@ -1520,6 +1807,14 @@ Contracts are located in:
|
|
|
1520
1807
|
3. **If no contract**: Create a new contract using \`contractspec create\`.
|
|
1521
1808
|
4. **After changes**: Validate with \`contractspec validate\`.
|
|
1522
1809
|
|
|
1810
|
+
## Adoption Engine
|
|
1811
|
+
|
|
1812
|
+
- Reuse existing workspace code before inventing a new local surface.
|
|
1813
|
+
- Prefer ContractSpec OSS packages before reaching for raw framework or vendor primitives.
|
|
1814
|
+
- Use \`contractspec connect adoption sync\` to mirror the local catalog.
|
|
1815
|
+
- Use \`contractspec connect adoption resolve --family <family> --stdin\` to resolve the recommended reuse target.
|
|
1816
|
+
- If Connect says \`rewrite\`, reuse the existing workspace or ContractSpec candidate instead of creating a duplicate.
|
|
1817
|
+
|
|
1523
1818
|
## Key Commands
|
|
1524
1819
|
|
|
1525
1820
|
- \`contractspec create\` - Scaffold new specs
|
|
@@ -1539,13 +1834,13 @@ defineCommand({
|
|
|
1539
1834
|
});
|
|
1540
1835
|
\`\`\`
|
|
1541
1836
|
|
|
1542
|
-
## Rules for ${
|
|
1837
|
+
## Rules for ${b}
|
|
1543
1838
|
|
|
1544
1839
|
- All API endpoints must have a corresponding operation contract.
|
|
1545
1840
|
- Events must be declared in contracts before being emitted.
|
|
1546
1841
|
- UI components should reference presentation contracts.
|
|
1547
1842
|
- Feature flags should be defined in feature modules.
|
|
1548
|
-
`}function
|
|
1843
|
+
`}function Bw($){let b=$.projectName??"this project",n=$.isMonorepo&&$.scope==="package",A=R$($),m=n&&$.packageName?`${$.packageName} package`:b,y="src/contracts",W=$.isMonorepo?n?`
|
|
1549
1844
|
## Monorepo Scope
|
|
1550
1845
|
|
|
1551
1846
|
This guide is scoped to the current package.
|
|
@@ -1559,7 +1854,7 @@ This guide is scoped to the workspace root.
|
|
|
1559
1854
|
- Prefer the nearest package guide when working inside a specific package.
|
|
1560
1855
|
`:"";return`# ContractSpec AI Guide
|
|
1561
1856
|
|
|
1562
|
-
Scope: \`${
|
|
1857
|
+
Scope: \`${m}\`
|
|
1563
1858
|
|
|
1564
1859
|
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1565
1860
|
|
|
@@ -1569,7 +1864,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
|
|
|
1569
1864
|
- Validate contracts after changes with \`contractspec validate\`.
|
|
1570
1865
|
- Regenerate derived artifacts before considering the work complete.
|
|
1571
1866
|
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1572
|
-
${
|
|
1867
|
+
${W}
|
|
1573
1868
|
## Contract Locations
|
|
1574
1869
|
|
|
1575
1870
|
- \`src/contracts/operations/\` - command and query specs
|
|
@@ -1596,20 +1891,139 @@ ${X}
|
|
|
1596
1891
|
- Keep changes spec-first, deterministic, and reviewable.
|
|
1597
1892
|
- Do not change generated outputs without updating their source contract.
|
|
1598
1893
|
- When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
|
|
1894
|
+
- Reuse existing workspace code before creating new files, packages, or dependencies.
|
|
1895
|
+
- Prefer ContractSpec OSS packages by family:
|
|
1896
|
+
- UI: local reusable UI -> \`@contractspec/lib.design-system\` -> platform ui-kit -> shadcn/web fallback
|
|
1897
|
+
- Contracts: existing local spec -> \`@contractspec/lib.contracts-spec\` / \`@contractspec/lib.schema\`
|
|
1898
|
+
- Integrations/runtime/shared libs: existing workspace surface -> ContractSpec OSS catalog -> reviewed fallback
|
|
1899
|
+
- Use \`contractspec connect adoption sync\` and \`contractspec connect adoption resolve --family <family>\` when the right reusable surface is unclear.
|
|
1599
1900
|
|
|
1600
1901
|
## Initialization Preset
|
|
1601
1902
|
|
|
1602
1903
|
- This workspace was initialized with the \`${A}\` setup preset.
|
|
1603
|
-
`}function
|
|
1604
|
-
`}async function v1($,W){let j=[];return j.push(await N6($,W)),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}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 N6($,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 R6($,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 C6($,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 D6($,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 T6($,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 F6($,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 x6($,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 y6}from"child_process";import{promisify as v6}from"util";var C$=v6(y6);async function m1($,W){let j=[];return j.push(await m6(W)),j.push(await P6(W)),j.push(await k6($,W)),j.push(await h6($,W)),j.push(await g6($,W)),j}async function m6($){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 P6($){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 k6($,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 h6($,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 g6($,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 f6,isFeatureFile as u6,scanAllSpecsFromSource as d6,scanExampleSource as n6,scanFeatureSource as c6}from"@contractspec/module.workspace";function r6(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function VW($,W={}){let{fs:j,logger:A}=$,Q=r6(),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(u6(B)){let H=c6(q,B);Q.features.set(H.key,H);continue}if(f6(B)){let H=n6(q,B);Q.examples.set(H.key,H);continue}if(B.includes(".app-config.")||B.includes(".blueprint.")){let H=d6(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 yb($){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(l6(Q.stats.features)),j.push(o6(Q.stats.examples)),j.push(i6(Q.inventory.features,A,W)),j.push(p6(Q.inventory.examples)),j.push(t6(Q.inventory.workspaceConfigs)),j}function l6($){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 o6($){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 i6($,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 p6($){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 t6($){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 a6($,W)),j.push(await s6($,W)),j.push(await e6($,W)),j}async function a6($,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 s6($,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 e6($,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 $7=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],x8=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function W7($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,A])=>{if(typeof A==="string")W[j]=A;return W},{})}function j7($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function A7($,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=W7(B.scripts),H=await $.glob({patterns:$7,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:j7(q),testFileCount:H.length,tier:T8(Y,j)})}catch{continue}}return Q}function Q7($){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 Z7($){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 A7($,W,j),Q=[];for(let X of A){if(X.tier==="critical")Q.push(...Q7(X));Q.push(...Z7(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 X7=["src/contracts","contracts","src/specs","specs"];async function f1($,W){let j=[];return j.push(Y7(W)),j.push(await B7($,W)),j.push(await q7($,W)),j.push(await H7($,W)),j.push(await G7($,W)),j.push(...await P8($,W)),j}function Y7($){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 B7($,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 q7($,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 X7){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 H7($,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 V7($,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 G7($,W){try{let j=await V7($,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 J7={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$}},b7={confirm:async()=>!1,input:async()=>""};async function g8($,W,j=b7,A=J7){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 w7(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(`\u2713 ${I.message}`),K.status="pass",K.message=`Fixed: ${I.message}`,K.fix=void 0;else Z.warn(`\u2717 ${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 w7($,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 Bw($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("\u2713 All checks passed!");else W.push("\u2717 Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
`).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 rw($,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 h7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o8($,W,j){let A=h7(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 g7,SyntaxKind as f7}from"ts-morph";function i8($){let W=[],A=new g7({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(f7.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 tw($){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 n7={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function t8($){return u7("sha256").update($).digest("hex")}async function c7($,W,j,A={},Q){let Z={...n7,...A},X=Z.computeHashes?t8($.sourceBlock||""):void 0,Y=$.key??d7.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 c7(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 o7,scanAllSpecsFromSource as i7,scanFeatureSource as p7}from"@contractspec/module.workspace";function r7($,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=r7(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=l7(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 l7($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function t($,W){return`${$}.v${W}`}function t7(){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=t7(),X=[],Y=[];for(let K of Q){if((await j.stat(K)).isDirectory)continue;let I=await j.readFile(K);if(o7(K)){let M=p7(I,K);X.push(M)}else{let M=i7(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 _K($){let W=[];for(let j of Object.values($))for(let A of j.values())W.push(A);return W}function zK($,W){return $.filter((j)=>j.type===W)}function UK($,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 s7,DEFAULT_CONTRACTSRC as UW}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as a7}from"@contractspec/module.workspace";async function $$($,W={}){let{fs:j,scan:A=a7}=$,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 DK($){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 e7=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,$X=/@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?)?['"]/,WX=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,jX=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,AX=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,QX=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,ZX=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function LW($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function XX($,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 YX($,W,j){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||AX.test(A)||jX.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(W.has(A))return!1;if(XX(A,j))return!1;return e7.test(A)}function $4($){return $.replaceAll("\\","/").match(QX)?.[1]??null}function BX($){let W=$.split(`
|
|
1611
|
-
`).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 qX($){if(!$)return UW;let W=s7.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?qX(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(!YX(H,Y,Z))continue;try{let V=await j.readFile(H);if(BX(V))continue;let G=$4(H);if(!(G!==null&&ZX.test(G)&&B.has(G))&&!WX.test(V))continue;if($X.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 HX}from"@contractspec/module.workspace";async function e1($){let W=[];for(let j of $){let A=HX(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 Y_($,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 q_=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],H_={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_($,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:()=>w2,resolveWorkspace:()=>d,resolveStoragePaths:()=>A$,replayConnectDecision:()=>pX,persistLatestArtifacts:()=>wj,persistDecisionArtifacts:()=>_0,normalizeEvalInput:()=>fX,matchConfiguredPath:()=>G0,loadStoredDecision:()=>U0,listStoredReviewPackets:()=>zj,listConnectReviewPackets:()=>tX,isReviewCommand:()=>jj,isDeniedCommand:()=>Aj,isAllowedCommand:()=>OW,initConnectWorkspace:()=>rX,inferSurfaces:()=>w0,evaluateConnectDecision:()=>hX,ensureStorage:()=>K0,defaultActor:()=>b0,decisionArtifactRefs:()=>r$,createConnectControlPlaneRuntime:()=>X2,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:()=>bX,ACP_FS_ACCESS_REF:()=>JX});import VX 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 VX.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(GX);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((A)=>!OW($,A)),state:"unknown"}}function GX($){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"},JX={key:"acp.fs.access",version:"1.0.0",kind:"command"},bX={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=wX({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=KX({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 wX($){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(_X)[0]??"permit"}function KX($){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 _X($,W){return Z4($)-Z4(W)}function Z4($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as PX}from"crypto";var H4={};h(H4,{formatPrComment:()=>X4,formatMinimalComment:()=>Bj,formatJson:()=>B4,formatCheckRun:()=>Y4,detectImpact:()=>F$,ImpactDetectionOverviewDocBlock:()=>IX});function X4($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)j.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else j.push("\u2705 **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(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| \u2796 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("### \u26A0\uFE0F 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("### \u2705 No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
|
|
1612
|
-
|
|
1904
|
+
`}function Sw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1905
|
+
|
|
1906
|
+
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1907
|
+
|
|
1908
|
+
This workspace uses ContractSpec to keep contracts, generated artifacts, and AI guidance aligned.
|
|
1909
|
+
|
|
1910
|
+
## Start Here
|
|
1911
|
+
|
|
1912
|
+
1. Run \`contractspec onboard\` to generate a track-aware onboarding guide for this repo.
|
|
1913
|
+
2. Run \`contractspec validate\` after changing contracts or generated outputs.
|
|
1914
|
+
3. Run \`contractspec doctor\` if local setup or tooling looks unhealthy.
|
|
1915
|
+
|
|
1916
|
+
## Recommended Commands
|
|
1917
|
+
|
|
1918
|
+
- \`contractspec onboard\` - generate repo-local onboarding guidance and next steps
|
|
1919
|
+
- \`contractspec create\` - scaffold a new contract or package target
|
|
1920
|
+
- \`contractspec generate\` - refresh derived docs and artifacts
|
|
1921
|
+
- \`contractspec validate\` - validate contracts, package scaffolds, and integrity
|
|
1922
|
+
- \`contractspec connect adoption resolve --family <family> --stdin\` - reuse existing ContractSpec or workspace surfaces before building new ones
|
|
1923
|
+
|
|
1924
|
+
## Builder / Connect
|
|
1925
|
+
|
|
1926
|
+
- Use \`contractspec init --preset connect\` when you want local Connect artifacts and reuse guidance in the repo.
|
|
1927
|
+
- Use \`contractspec init --preset builder-managed\`, \`builder-local\`, or \`builder-hybrid\` when you want Builder control-plane defaults.
|
|
1928
|
+
|
|
1929
|
+
## Notes
|
|
1930
|
+
|
|
1931
|
+
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1932
|
+
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1933
|
+
`}function a8($){if(R$($)!=="connect")return;return{...on.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin",packageRef:"contractspec-adoption"},codex:{enabled:!0,mode:"wrapper",packageRef:"contractspec-adoption"},"claude-code":{enabled:!0,mode:"rule",packageRef:"contractspec-adoption"}},adoption:{...on.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:on.connect?.studio}}function e8($){let b=T0(R$($)),n=mw(R$($));if(!b||!n)return;let A=!0,m=b==="local"||b==="hybrid";return{...on.builder,enabled:!0,runtimeMode:b,bootstrapPreset:n,api:A?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:m?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function ln(){let $=process.platform,b=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${b}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??b}/Claude/claude_desktop_config.json`;default:return`${b}/.config/claude/claude_desktop_config.json`}}function b$($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(m===void 0)n[A]=y;else if(pn(m)&&pn(y))n[A]=b$(m,y)}return n}function D0($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(y===void 0)continue;if(pn(m)&&pn(y))n[A]=D0(m,y);else n[A]=y}return n}function pn($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function a($){try{return JSON.parse($)}catch{return null}}function N($){return JSON.stringify($,null,2)+`
|
|
1934
|
+
`}async function N0($,b){let n=[];return n.push(await s8($,b)),n.push(await $9($,b)),n.push(await b9($,b)),n.push(await n9($,b)),n.push(await A9($,b)),n.push(await m9($,b)),n.push(await y9($,b)),n}async function h$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function s8($,b){let n=$.join(await h$($,b),".contractsrc.json");if(await $.exists(n))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let m=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(m)),{success:!0,message:"Created .contractsrc.json"}}catch(m){return{success:!1,message:`Failed to create: ${m instanceof Error?m.message:String(m)}`}}}}}}async function $9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n);return JSON.parse(m),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(m){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:m instanceof Error?m.message:String(m),fix:{description:"Replace with valid default config",apply:async()=>{try{let W=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(n,N(W)),{success:!0,message:"Replaced with valid config"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function b9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m),W=[];if(!y.outputDir)W.push("outputDir");if(!y.conventions)W.push("conventions");if(W.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${W.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let w=Wb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let j of W)if(w[j]!==void 0)y[j]=w[j];return await $.writeFile(n,N(y)),{success:!0,message:"Added missing fields"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function n9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:y.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return y.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(n,N(y)),{success:!0,message:"Added versioning configuration"}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function A9($,b){let n=$.join(await h$($,b),".contractsrc.json");if(!await $.exists(n))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.hooks){let j=y.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(j).length} git hook(s) configured`}}let W=$.join(b.workspaceRoot,".husky");if(await $.exists(W))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return y.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(n,N(y)),{success:!0,message:"Added hooks configuration"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function m9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(m==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(m==="connect"){let w=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),j=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(w.length===0&&!j)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...w,...j?["connect.studio.endpoint"]:[]].join(", ")}`}}let y=[],W=A.builder?.api?.controlPlaneTokenEnvVar;if(m.startsWith("builder-")&&!A.builder?.api?.baseUrl)y.push("builder.api.baseUrl");if(m.startsWith("builder-")&&!W)y.push("builder.api.controlPlaneTokenEnvVar");if(m.startsWith("builder-")&&W&&!process.env[W])y.push(`env:${W}`);if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)y.push("builder.localRuntime.runtimeId");if((m==="builder-local"||m==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)y.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:y.length===0?"pass":"warn",message:y.length===0?`Builder preset inferred (${m}) and required config is present`:`Builder preset inferred (${m}) but setup is missing ${y.join(", ")}`}}async function y9($,b){let n=await h$($,b),A=await P($,n),m=Eb(A);if(!m.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let y=$.join(n,".vscode","settings.json"),W=A.builder?.api?.baseUrl;if(!W)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let w=await $.readFile(y).catch(()=>""),j=w?a(w):void 0;if(j?.["contractspec.api.baseUrl"]===W)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(n,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...j??{},...tn({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:m,targets:[],builderApiBaseUrl:W})};return await $.writeFile(y,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as W9}from"child_process";import{promisify as w9}from"util";var d$=w9(W9);async function F0($,b){let n=[];return n.push(await j9(b)),n.push(await B9(b)),n.push(await S9($,b)),n.push(await Q9($,b)),n.push(await Z9($,b)),n}async function j9($){try{let{stdout:b}=await d$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function B9($){try{let{stdout:b}=await d$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function S9($,b){let n=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:m,name:y}of n){let W=$.join(b.workspaceRoot,m);if(await $.exists(W)){A=y;break}}if(!A){let m=$.join(b.workspaceRoot,".."),y=$.join(b.workspaceRoot,"../.."),W=[m,y];for(let w of W){for(let{file:j,name:B}of n){let S=$.join(w,j);if(await $.exists(S)){A=B;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await d$(`${A} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function Q9($,b){let n=$.join(b.workspaceRoot,"node_modules");if(await $.exists(n))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await d$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function Z9($,b){let n=$.join(b.workspaceRoot,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A),y={...m.dependencies,...m.devDependencies};if("@contractspec/lib.contracts-spec"in y)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${y["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await d$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await d$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function v0($,b){let n=await dn($,b.workspaceRoot);if(n.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return n.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(b.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as X9,isFeatureFile as Y9,scanAllSpecsFromSource as G9,scanExampleSource as H9,scanFeatureSource as q9}from"@contractspec/module.workspace";function O9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function an($,b={}){let{fs:n,logger:A}=$,m=O9(),y=b.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let W=await n.glob({pattern:y});for(let j of W){if(j.includes("node_modules")||j.includes("/dist/"))continue;try{let B=await n.readFile(j);if(Y9(j)){let S=q9(B,j);m.features.set(S.key,S);continue}if(X9(j)){let S=H9(B,j);m.examples.set(S.key,S);continue}if(j.includes(".app-config.")||j.includes(".blueprint.")||j.endsWith("/blueprint.ts")){let S=G9(B,j);for(let Q of S)if(Q.specType==="app-config"&&Q.key)m.appConfigs.set(Q.key,Q)}}catch{}}try{let j=await n.glob({pattern:"**/.contractsrc.json"});for(let B of j){if(B.includes("node_modules"))continue;try{let S=await n.readFile(B),Q=JSON.parse(S);m.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){m.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let w={features:m.features.size,examples:m.examples.size,appConfigs:m.appConfigs.size,workspaceConfigs:m.workspaceConfigs.size,total:m.features.size+m.examples.size+m.appConfigs.size+m.workspaceConfigs.size};return A.info(`Discovered ${w.features} features, ${w.examples} examples, ${w.appConfigs} app configs, ${w.workspaceConfigs} workspace configs`),{inventory:m,stats:w}}function AV($){let b=[];for(let[n,A]of $.features)b.push({key:n,file:A.filePath,type:"feature"});for(let[n,A]of $.examples)b.push({key:n,version:A.version,file:A.filePath,type:"example"});for(let[n,A]of $.appConfigs)b.push({key:n,version:A.version,file:A.filePath,type:"app-config"});for(let[,n]of $.workspaceConfigs)b.push({key:n.file,file:n.file,type:"workspace-config"});return b}function en($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function g0($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function sn($,b){let n=$.join(b,"config/stability-policy.json");if(!await $.exists(n))return;try{let A=await $.readFile(n),m=JSON.parse(A);return{version:typeof m.version==="number"&&Number.isFinite(m.version)?m.version:1,criticalPackages:g0(m.criticalPackages).map(en),criticalFeatureKeys:g0(m.criticalFeatureKeys),smokePackages:g0(m.smokePackages)}}catch{return}}function Qw($,b){let n=en($);if(b?.criticalPackages.includes(n))return"critical";return"non-critical"}function Zw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function wb($){return en(`${en($)}/config/stability-policy.json`)}async function P0($,b){let n=[],A=await sn($,b.workspaceRoot),m=await an({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return n.push(V9(m.stats.features)),n.push(J9(m.stats.examples)),n.push(U9(m.inventory.features,A,b)),n.push(K9(m.inventory.examples)),n.push(_9(m.inventory.workspaceConfigs)),n}function V9($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function J9($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function U9($,b,n){let A=[],m=[];for(let[y,W]of $)if(!(Boolean(W.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(W.sourceBlock??"")))if(Zw(y,b))m.push(y);else A.push(y);if(m.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:m.length>0?"fail":"warn",message:m.length>0?`${m.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:m.length>0?`Critical features: ${m.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:b?wb(n.workspaceRoot):void 0,criticalMissingFeatures:m,missingFeatures:A}}}function K9($){let b=[];for(let[n,A]of $)if(!A.entrypoints.packageName)b.push(n);if(b.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function _9($){let b=[];for(let[,n]of $)if(!n.valid)b.push(n.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function k0($,b){let n=[];return n.push(await z9($,b)),n.push(await L9($,b)),n.push(await R9($,b)),n}async function z9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(n))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let m=$.join(b.workspaceRoot,".cursor");if(!await $.exists(m))await $.mkdir(m);let y=Mb();return await $.writeFile(n,N(y)),{success:!0,message:"Created .cursor/mcp.json"}}catch(m){return{success:!1,message:`Failed: ${m instanceof Error?m.message:String(m)}`}}}}}}async function L9($,b){let n=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(n))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let m=await $.readFile(n),y=JSON.parse(m);if(y.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let w=Mb(),j=b$(y,w);return await $.writeFile(n,N(j)),{success:!0,message:"Registered MCP server"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function R9($,b){let n=ln();try{if(!await $.exists(n))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let m=await $.readFile(n);if(JSON.parse(m).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var C9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],Xw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function x9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[n,A])=>{if(typeof A==="string")b[n]=A;return b},{})}function I9($){return Object.entries($).some(([b,n])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(n)})}async function E9($,b,n){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:Xw}),m=[];for(let y of A){let W=$.dirname(y),w=$.relative(b,W);try{let j=JSON.parse(await $.readFile(y)),B=x9(j.scripts),S=await $.glob({patterns:C9,cwd:W,ignore:Xw});m.push({packageName:j.name??w,packagePath:w.replace(/\\/g,"/"),hasBuildScript:typeof B.build==="string",hasTypecheckScript:typeof B.typecheck==="string",hasLintScript:typeof B.lint==="string"||typeof B["lint:check"]==="string",hasTestScript:typeof B.test==="string",usesPassWithNoTests:I9(B),testFileCount:S.length,tier:Qw(w,n)})}catch{continue}}return m}function M9($){let b=[];if(!$.hasBuildScript)b.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)b.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)b.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)b.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)b.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)b.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return b}function T9($){let b=[];if($.testFileCount>0&&!$.hasTestScript)b.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)b.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return b}async function Yw($,b,n){let A=await E9($,b,n),m=[];for(let W of A){if(W.tier==="critical")m.push(...M9(W));m.push(...T9(W))}let y=A.filter((W)=>W.tier==="critical").map((W)=>({packageName:W.packageName,packagePath:W.packagePath,hasBuildScript:W.hasBuildScript,hasTypecheckScript:W.hasTypecheckScript,hasLintScript:W.hasLintScript,hasTestScript:W.hasTestScript,usesPassWithNoTests:W.usesPassWithNoTests,testFileCount:W.testFileCount}));return{findings:m,criticalPackages:y}}function Hw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function Gw($,b,n,A){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let m=b.filter((y)=>{return y.tier==="critical"||n.has(y.code)});return{category:"workspace",name:$,status:m.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:Hw(b),context:{findings:b}}}async function qw($,b){let n=await sn($,b.workspaceRoot);if(!n)return[];let A=await Yw($,b.workspaceRoot,n),m=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),y=A.findings.filter((j)=>m.has(j.code)),W=A.findings.filter((j)=>j.code==="tests-without-test-script"),w=A.findings.filter((j)=>j.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:y.length>0?"fail":"pass",message:y.length>0?`${y.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:y.length>0?Hw(y):b.verbose?`Policy: ${wb(b.workspaceRoot)}`:void 0,context:{policyPath:wb(b.workspaceRoot),criticalPackages:A.criticalPackages,findings:y}},Gw("Package Test Scripts",W,new Set,"All tested packages expose a test script"),Gw("Buildable Packages Without Tests",w,new Set,"All buildable packages have tests or explicit test scripts")]}var D9=["src/contracts","contracts","src/specs","specs"];async function r0($,b){let n=[];return n.push(N9(b)),n.push(await F9($,b)),n.push(await v9($,b)),n.push(await g9($,b)),n.push(await k9($,b)),n.push(...await qw($,b)),n}function N9($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",n=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${n}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function F9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let A of n){let m=$.join(A,"package.json");if(await $.exists(m))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function v9($,b){let n=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],A=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let W of n)for(let w of D9){let j=$.join(W,w);if(await $.exists(j)){let B=W===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${w}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let m=b.isMonorepo?"src/contracts":"src/contracts",y=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${m}/${y} to organize your specs`,fix:{description:`Create ${m}/ directory${y}`,apply:async()=>{try{let W=$.join(A,"src","contracts");return await $.mkdir(W),{success:!0,message:`Created ${m}/`}}catch(W){return{success:!1,message:`Failed: ${W instanceof Error?W.message:String(W)}`}}}}}}async function g9($,b){try{let n=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=b.isMonorepo?b.packageRoot:b.workspaceRoot,m=await $.glob({patterns:n,ignore:["node_modules/**","dist/**"],cwd:A});if(m.length>0){let W=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${m.length} contract file(s)${W}`,details:b.verbose?m.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:b.isMonorepo?`No contract files found in package "${b.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function P9($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let A=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.packageRoot,level:"package"}}let n=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(n))return{path:n,root:b.workspaceRoot,level:"workspace"};return null}async function k9($,b){try{let n=await P9($,b);if(!n)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(n.path),m=JSON.parse(A),y=m.outputDir??"./src",W=$.join(n.root,y),w=b.isMonorepo?` (${n.level} level)`:"";if(await $.exists(W))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${y}${w}`,details:b.verbose?`Resolved to: ${W}`:void 0};let B=y==="./src"||y==="src",S=Array.isArray(m.packages)&&m.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||n.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${n.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${y}${w}`,details:b.verbose?`Expected at: ${W}`:void 0,fix:{description:`Create ${y} directory`,apply:async()=>{try{return await $.mkdir(W),{success:!0,message:`Created ${y}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var Ow=["cli","config","mcp","deps","docs","workspace","ai","layers"],Vw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var r9={checks:{runCliChecks:M0,runConfigChecks:N0,runMcpChecks:k0,runDepsChecks:F0,runDocChecks:v0,runWorkspaceChecks:r0,runAiChecks:E0,runLayerChecks:P0},workspace:{findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$}},f9={confirm:async()=>!1,input:async()=>""};async function Jw($,b,n=f9,A=r9){let{fs:m,logger:y}=$,W=b.categories??Ow,{checks:w,workspace:j}=A,B=j.findWorkspaceRoot(b.workspaceRoot),S=j.findPackageRoot(b.workspaceRoot),Q=j.isMonorepo(B),Z=Q?j.getPackageName(S):void 0,X={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";y.info(`Detected monorepo${J}`)}let Y=[];for(let J of W){if(b.skipAi&&J==="ai")continue;y.info(`Checking ${Vw[J]}...`);let U=await c9(J,m,X,n,w);for(let H of U){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await n.confirm(`Fix "${H.name}"? ${H.fix.description}`)){y.info(`Applying fix: ${H.fix.description}`);let _=await H.fix.apply();if(_.success)y.info(`\u2713 ${_.message}`),H.status="pass",H.message=`Fixed: ${_.message}`,H.fix=void 0;else y.warn(`\u2717 ${_.message}`)}}Y.push(H)}}let G=Y.filter((J)=>J.status==="pass").length,V=Y.filter((J)=>J.status==="warn").length,O=Y.filter((J)=>J.status==="fail").length,K=Y.filter((J)=>J.status==="skip").length;return{checks:Y,passed:G,warnings:V,failures:O,skipped:K,healthy:O===0}}async function c9($,b,n,A,m){switch($){case"cli":return m.runCliChecks(b,n);case"config":return m.runConfigChecks(b,n);case"mcp":return m.runMcpChecks(b,n);case"deps":return m.runDepsChecks(b,n);case"docs":return m.runDocChecks(b,n);case"workspace":return m.runWorkspaceChecks(b,n);case"ai":return m.runAiChecks(b,n,A);case"layers":return m.runLayerChecks(b,n);default:return[]}}function TV($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1935
|
+
`)}function DV($){let n=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)n+=`
|
|
1936
|
+
${$.details}`;if($.fix)n+=`
|
|
1937
|
+
Fix available: ${$.fix.description}`;return n}async function f0($,b){let n=[],A=b.workspaceRoot??process.cwd(),m=await Jw($,{workspaceRoot:A,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let y of m.checks)if(y.status==="fail")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});else if(y.status==="warn")n.push({ruleId:`doctor-${y.category}-${y.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${y.name}: ${y.message}`,category:"doctor",context:{details:y.details,...y.context??{}}});return n}$$();import{mkdtemp as mQ,rm as yQ}from"fs/promises";import{tmpdir as WQ}from"os";import Tb from"path";import{DEFAULT_CONTRACTSRC as p9}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as a9}from"@contractspec/module.workspace";import e9 from"path";import{packageDocBlocks as h9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as d9,convertSpecToDocBlock as u9,extractModuleDocData as o9,loadSpecFromSource as i9,scanAllSpecsFromSource as t9,scanSpecSource as l9}from"@contractspec/module.workspace";import h0 from"path";import{dirname as Uw,sep as $A}from"path";class c0{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let n;if(b.specType==="app-config")n="app-config";else if(b.specType==="example")n="example";else if(b.specType==="feature")n="feature";if(n&&b.key){let A=Uw(b.filePath);this.modules.push({type:n,key:b.key,dirPath:A})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=Uw($),n=this.modules.filter((A)=>{let m=A.dirPath.endsWith($A)?A.dirPath:A.dirPath+$A;return(b.endsWith($A)?b:b+$A).startsWith(m)||b===A.dirPath});if(n.length===0)return;return n.sort((A,m)=>{let y={"app-config":3,example:2,feature:1},W=y[A.type],w=y[m.type];if(W!==w)return w-W;return m.dirPath.length-A.dirPath.length}),n[0]}}async function _w($,b,n){let{fs:A,logger:m}=n,y=[];if(m.info(`Generating docs for ${$.length} files...`),b.outputDir)await A.mkdir(b.outputDir);let W=new c0(n),w=[];for(let B of $)try{let S=await A.readFile(B),Q=t9(S,B);if(Q.length>0)w.push(...Q);else{let Z=l9(S,B);if(Z.specType!=="unknown")w.push(Z)}}catch(S){}W.initialize(w);let j=await zw($,n);for(let B of j)if(y.push(B.entry.block),m.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await Kw(B.entry.block,B.filePath,b.outputDir,W,A);for(let B of $)try{let S=await i9(B);if(!S?.length){m.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=u9(Q,{rootPath:b.rootPath});if(y.push(Z),m.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await Kw(Z,B,b.outputDir,W,A)}}catch(S){m.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)m.info(`Wrote ${y.length} doc files to ${b.outputDir}`);return{blocks:y,count:y.length}}async function hV($,b){return(await zw($,b)).map(({entry:A})=>A.block)}function dV($,b){return h9(d9({packageName:$,srcRoot:b}))}async function zw($,b){let n=[...new Set($)].sort((m,y)=>m.localeCompare(y)),A=[];for(let m of n){let y=await b.fs.readFile(m),W=m.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),w=o9(y,m,W);for(let j of w.entries)A.push({entry:j,filePath:m})}return A}async function Kw($,b,n,A,m){let y=A.resolve(b),W=y?h0.join(n,y.key):h0.join(n,"_common");await m.mkdir(W);let w=h0.join(W,`${$.id}.md`),j=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1938
|
+
|
|
1939
|
+
${$.body}`;await m.writeFile(w,j)}async function Lw($,b,n,A,m={}){let y=m.config,W=await cn($,{cwd:m.specSearchRoot,config:y,pattern:m.specPattern??$Q(b,m)});if(W.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let w=e9.join(bQ(n,y),"docs"),j=await _w(W.map((S)=>S.filePath),{outputDir:w,format:"markdown",rootPath:A},$),B=0;for(let S of W){let Q=s9(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await yb(S.filePath,$,y??p9,{targets:J0(S.specType,{includeTests:Boolean(m.includeRuntimeTests)}),outputDir:y?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((X)=>X.success).length}return{specsCount:W.length,docsCount:j.count,materializedCount:B}}function s9($){return a9($.specType)}function $Q($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${d0($)}/**/*.ts`:void 0}function bQ($,b){let n=(b?.connect?.policy?.generatedPaths??[]).map(AQ).filter(Boolean);if(n.length>0)return n[0];if(b?.outputDir&&b.outputDir!=="./src")return d0(b.outputDir);return $}function nQ($){return d0($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function AQ($){let b=nQ($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function d0($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function bA($,b,n,A={}){let m=await mQ(Tb.join(WQ(),"contractspec-drift-"));try{await Lw($,b,m,A.rootPath,A.generation);let y=[],W=await import("fs/promises");async function w(Z){let X=await W.readdir(Z,{withFileTypes:!0}),Y=[];for(let G of X){let V=Tb.resolve(Z,G.name);if(G.isDirectory())Y.push(...await w(V));else Y.push(V)}return Y}let j=async(Z)=>{if(!await W.stat(Z).catch(()=>!1))return[];return(await w(Z)).map((Y)=>Tb.relative(Z,Y)).sort()},B=await j(m),S=await j(n),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){y.push(Z);continue}if(!B.includes(Z)){y.push(Z);continue}let X=await W.readFile(Tb.join(m,Z)),Y=await W.readFile(Tb.join(n,Z));if(!X.equals(Y))y.push(Z)}return{hasDrift:y.length>0,files:y}}finally{await yQ(m,{recursive:!0,force:!0})}}async function u0($,b){let{fs:n,logger:A}=$,m=[],y=await P(n);if(!y.outputDir)return A.info("No outputDir configured, skipping drift checks"),m;let W="./contracts",w=y.outputDir;if(!await n.exists(w))return A.info("Generated directory does not exist, skipping drift checks"),m;try{let j=await bA($,W,w);if(j.hasDrift)for(let B of j.files)m.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${w}/${B}`,context:{file:B}})}catch(j){A.warn("Drift detection failed",{error:j instanceof Error?j.message:String(j)})}return m}$$();function wQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function jQ($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function nA($,b,n,A={}){let{fs:m}=b,y=[],W=[],w=$.key??m.basename($.filePath).replace(/\.[jt]s$/,""),j=A.outputDir??n.outputDir??"./src",B=wQ(w),S={};if($.specType==="operation")S.handlerPath=m.join(j,"handlers",`${B}.handler.ts`),S.handlerTestPath=m.join(j,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=m.join(j,"components",`${B}.tsx`),S.componentTestPath=m.join(j,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=m.join(j,"forms",`${B}.form.tsx`),S.formTestPath=m.join(j,"forms",`${B}.form.test.tsx`);if(A.checkHandlers&&S.handlerPath)if(!await m.exists(S.handlerPath))y.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await m.readFile(S.handlerPath),X=`${jQ(w.split(".").pop()??w)}Spec`,Y=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),G=new RegExp(`typeof\\s+${X}\\b`).test(Z);if(!Y)W.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!G)W.push(`Handler ContractHandler typing does not reference expected spec var (${X}): ${S.handlerPath}`)}if(A.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await m.exists(Z))y.push(`Missing test file: ${Z}`)}return{valid:y.length===0,errors:y,warnings:W,expected:S}}async function o0($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkHandlers:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"handler-missing",severity:"warning",message:w,category:"handlers",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"handler-warning",severity:"warning",message:w,category:"handlers",file:y.filePath})}return A}$$();import{createHash as YQ}from"crypto";import GQ from"path";var Db={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},BQ={".handler.ts":"handler",".handler.tsx":"handler",".service.ts":"service",".service.tsx":"service",".test.ts":"test",".test.tsx":"test",".spec.ts":"test",".spec.tsx":"test",".component.tsx":"component",".tsx":"component",".form.tsx":"form",".hook.ts":"hook",".hook.tsx":"hook"};function SQ($){let b=$.toLowerCase();for(let[n,A]of Object.entries(BQ))if(b.endsWith(n))return A;if(b.includes("/handlers/"))return"handler";if(b.includes("/services/"))return"service";if(b.includes("/components/"))return"component";if(b.includes("/forms/"))return"form";if(b.includes("/hooks/"))return"hook";if(b.includes("/__tests__/"))return"test";return"other"}function Rw($,b){let n=[],A=new Set,m=(Z,X,Y)=>{let G=`${Z}:${X}`;if(A.has(G))return;A.add(G),n.push({filePath:b,specKey:Z,referenceType:X,lineNumber:Y,inferredType:SQ(b)})},y=(Z)=>{return $.substring(0,Z).split(`
|
|
1940
|
+
`).length},W,w=new RegExp(Db.contractHandler);while((W=w.exec($))!==null)if(W[1])m(W[1],"handler",y(W.index));let j=new RegExp(Db.typeofSpec);while((W=j.exec($))!==null)if(W[1])m(W[1],"typeof",y(W.index));let B=new RegExp(Db.namedImport);while((W=B.exec($))!==null){let X=W[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(X)for(let Y of X)m(Y,"import",y(W.index))}let S=new RegExp(Db.defaultImport);while((W=S.exec($))!==null)if(W[1])m(W[1],"import",y(W.index));let Q=new RegExp(Db.specAssignment);while((W=Q.exec($))!==null)if(W[1])m(W[1],"unknown",y(W.index));return n}var Cw=["**/*.ts(x)"];async function AA($,b,n={}){let{fs:A}=b,m=n.includePatterns??Cw,y=n.excludePatterns??[...new Set([...v$,...q$])],W=[];for(let w of m){let j=await A.glob({pattern:w,ignore:y});for(let B of j)try{let S=await A.readFile(B),Z=Rw(S,B).filter((X)=>X.specKey===$);W.push(...Z)}catch{}}return W}async function GJ($,b={}){let{fs:n}=$,A=b.includePatterns??Cw,m=b.excludePatterns??[...new Set([...v$,...q$])],y=new Map;for(let W of A){let w=await n.glob({pattern:W,ignore:m});for(let j of w)try{let B=await n.readFile(j),S=Rw(B,j);for(let Q of S){let Z=y.get(Q.specKey)??[];Z.push(Q),y.set(Q.specKey,Z)}}catch{}}return y}function QQ($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xw($,b,n){let A=QQ(b),m=[];if($==="operation")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")m.push({path:`${n}/components/${A}.tsx`,type:"component"}),m.push({path:`${n}/components/${A}.test.tsx`,type:"test"});if($==="form")m.push({path:`${n}/forms/${A}.form.tsx`,type:"form"}),m.push({path:`${n}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")m.push({path:`${n}/handlers/${A}.handler.ts`,type:"handler"}),m.push({path:`${n}/handlers/${A}.handler.test.ts`,type:"test"});return m}import{Node as p,Project as ZQ,SyntaxKind as XQ}from"ts-morph";function Iw($){let b=[],A=new ZQ({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),m=(j)=>{if(!p.isObjectLiteralExpression(j))return;let B=j.getProperty("implementations");if(B&&p.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&p.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(p.isObjectLiteralExpression(Q)){let Z,X,Y,G=Q.getProperty("path");if(G&&p.isPropertyAssignment(G)){let K=G.getInitializer();if(p.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&p.isPropertyAssignment(V)){let K=V.getInitializer();if(p.isStringLiteral(K))X=K.getLiteralText()}let O=Q.getProperty("description");if(O&&p.isPropertyAssignment(O)){let K=O.getInitializer();if(p.isStringLiteral(K))Y=K.getLiteralText()}if(Z&&X)b.push({path:Z,type:X,description:Y})}}}},y=A.getDescendantsOfKind(XQ.CallExpression);for(let j of y){let B=j.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=j.getArguments();if(S.length>0&&p.isObjectLiteralExpression(S[0]))return m(S[0]),b}}let W=A.getVariableStatements();for(let j of W)if(j.isExported())for(let B of j.getDeclarations()){let S=B.getInitializer();if(S&&p.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return m(S),b}}let w=A.getExportAssignment((j)=>!j.isExportEquals());if(w){let j=w.getExpression();if(p.isObjectLiteralExpression(j))m(j);else if(p.isAsExpression(j)&&p.isObjectLiteralExpression(j.getExpression()))m(j.getExpression())}return b}function Ew($){if($.length===0)return"missing";let b=$.filter((m)=>m.exists),n=$.filter((m)=>m.type!=="test");if(b.filter((m)=>m.type!=="test").length===0)return"missing";if($.every((m)=>m.exists))return"implemented";return"partial"}function JJ($){let b=$.filter((m)=>m.status==="implemented").length,n=$.filter((m)=>m.status==="partial").length,A=$.filter((m)=>m.status==="missing").length;return{total:$.length,implemented:b,partial:n,missing:A,coverage:$.length>0?Math.round(b/$.length*100):100}}var HQ={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Mw($){return YQ("sha256").update($).digest("hex")}async function qQ($,b,n,A={},m){let y={...HQ,...A},W=y.computeHashes?Mw($.sourceBlock||""):void 0,w=$.key??GQ.basename($.filePath).replace(/\.[jt]s$/,""),j=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(Y,G,V,O)=>{if(Q.has(Y))return;Q.add(Y);let K=await B.exists(Y),J=void 0,U=void 0;if(K&&y.computeHashes)try{J=await B.readFile(Y),U=Mw(J)}catch{}S.push({path:Y,type:G,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:U,description:O})};if(y.includeExplicit&&$.sourceBlock){if(m)m.suffixText="Discover explicit implementations";let Y=Iw($.sourceBlock);for(let G of Y)await Z(G.path,G.type,"explicit",G.description)}if(y.includeDiscovered){if(m)m.suffixText="Discover implementations";let Y=await AA(w,b,y);for(let G of Y){if(G.filePath===$.filePath)continue;await Z(G.filePath,G.inferredType,"discovered")}}if(y.includeConvention){if(m)m.suffixText="Discover implementations based on conventions";let Y=y.outputDir??n.outputDir??"./src",G=xw($.specType,w,Y);for(let{path:V,type:O}of G)await Z(V,O,"convention")}if(m)m.suffixText="Determine implementation status";let X=Ew(S);return{specKey:w,specVersion:j,specPath:$.filePath,specType:$.specType,implementations:S,status:X,specHash:W}}async function Tw($,b,n,A={},m){let y=[];for(let W of $){if(m)m.text=`Resolving implementation... (${y.length}/${$.length})`;try{let w=await qQ(W,b,n,A,m);y.push(w)}catch(w){console.error(`Failed to resolve implementations for ${W}:`,w)}}return y}async function i0($,b,n){let{fs:A}=$,m=[],y=await P(A),W=n.implementation??{},w=b.filter((B)=>B.specType==="operation"),j=await Tw(w,{fs:A},y,{computeHashes:W.useCache??!0});for(let B of j){if(W.requireImplemented&&B.status==="missing")m.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")m.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!W.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);m.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)m.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return m}$$();import{isFeatureFile as JQ,scanAllSpecsFromSource as UQ,scanFeatureSource as KQ}from"@contractspec/module.workspace";function OQ($,b){return`${$}.v${b}`}function t0($,b,n,A,m,y={}){let{treatMissingAsError:W=!0}=y;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let w=[],j=[],B=[];for(let S of A){let Q=OQ(S.key,S.version);if(m.has(Q))w.push(S);else if(j.push(S),W)B.push(`Spec ${b}.v${n} references test ${S.key}.v${S.version} which does not exist`)}return{valid:j.length===0,foundTests:w,missingTests:j,errors:B,specFile:$}}function Dw($,b){return`${$}.v${b}`}function Nw($,b){let n=new Map,A=new Map,m=[],y=[];for(let W of $){if(!W.key||!W.version)continue;let w=Dw(W.key,W.version);if(!W.testTarget){y.push(w);continue}let{type:j,key:B,version:S}=W.testTarget,Q=S??W.version,Z=Dw(B,Q),X=VQ(b,j);if(!X||!X.has(Z)){m.push(w);continue}if(A.set(w,Z),!n.has(Z))n.set(Z,new Set);n.get(Z)?.add(w)}return{targetToTests:n,testToTarget:A,orphanedTests:m,testsWithoutTarget:y}}function VQ($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function n$($,b){return`${$}.v${b}`}function _Q(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function l0($,b){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[b]}async function mA($,b={}){let{fs:n,logger:A}=$;A.info("Starting integrity analysis...",{options:b});let m=await c$(n,{config:b.config,cwd:b.cwd,pattern:b.pattern}),y=_Q(),W=[],w=[];for(let H of m){if((await n.stat(H)).isDirectory)continue;let _=await n.readFile(H);if(JQ(H)){let z=KQ(_,H);W.push(z)}else{let z=UQ(_,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let C=l0(y,L.specType);if(C&&L.key&&L.version!==void 0){let D=n$(L.key,L.version);C.set(D,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let j=b.featureKey?W.filter((H)=>H.key===b.featureKey):W,B=new Set;for(let H of j){for(let q of H.operations){let _=n$(q.key,q.version);if(B.add(`operation:${_}`),!y.operations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let _=n$(q.key,q.version);if(B.add(`event:${_}`),!y.events.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let _=n$(q.key,q.version);if(B.add(`presentation:${_}`),!y.presentations.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let _=n$(q.key,q.version);if(B.add(`experiment:${_}`),!y.experiments.has(_))w.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let _=n$(q.key,q.version);if(B.add(`capability:${_}`),!y.capabilities.has(_))w.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let _=n$(q.key,q.version);B.add(`capability:${_}`)}for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=n$(q.pres.key,q.pres.version);if(!y.operations.has(_))w.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!y.presentations.has(z))w.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let _=n$(q.key,q.version);if(!y.presentations.has(_))w.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=l0(y,H);if(!q)continue;for(let[_,z]of q)if(!B.has(`${H}:${_}`))S.push(z),w.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of y.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let X=Nw(Z,y);for(let H of j)for(let q of H.opToPresentationLinks){let _=n$(q.op.key,q.op.version),z=X.targetToTests.get(_),L=!1,C=!1;if(z)for(let D of z){let F=y.testSpecs.get(D);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)C=!0}}if(!z||!L||!C){let D=[];if(!L)D.push("success scenario");if(!C)D.push("error scenario");w.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${D.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let Y={},G=0;for(let H of Q){let q=l0(y,H);if(!q)continue;let _=q.size,z=0,L=0,C=b.requireTestsFor?.includes(H);for(let[D,F]of q){if(B.has(`${H}:${D}`))z++;if(C){let E=n$(F.key,F.version),r=X.targetToTests.has(E),g=`${F.key}.test`,iA=y.testSpecs.has(n$(g,F.version));if(!r&&!iA)L++,G++,w.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}Y[H]={total:_,covered:z,orphaned:_-z,missingTest:C?L:0}}let V=Object.values(Y).reduce((H,q)=>H+q.total,0),O=Object.values(Y).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:G,byType:Y},U=!w.some((H)=>H.severity==="error");return A.info("Integrity analysis complete",{features:W.length,totalSpecs:V,orphaned:S.length,issues:w.length,healthy:U}),{inventory:y,features:j,coverage:K,issues:w,orphanedSpecs:S,healthy:U}}function fJ($){let b=[];for(let n of Object.values($))for(let A of n.values())b.push(A);return b}function cJ($,b){return $.filter((n)=>n.type===b)}function hJ($,b){return $.filter((n)=>n.severity===b)}async function p0($,b){let n=[],A=await P($.fs),m=await mA($,{config:A,pattern:b.pattern,all:!0});for(let y of m.issues)n.push({ruleId:`integrity-${y.type}`,severity:y.severity==="error"?"error":"warning",message:y.message,category:"integrity",file:y.file,context:{specKey:y.specKey,specType:y.specType,featureKey:y.featureKey,ref:y.ref}});return n}async function a0($,b){let n=[],A=await an($,{});for(let[m,y]of A.inventory.features){if(!y.key)n.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:y.filePath,context:{key:m}});if(!y.owners?.length)n.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${m}' missing 'owners' field`,category:"layers",file:y.filePath,context:{key:m}});if(y.operations.length===0&&y.events.length===0&&y.presentations.length===0)n.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${m}' has no operations, events, or presentations`,category:"layers",file:y.filePath,context:{key:m}})}for(let[m,y]of A.inventory.examples){if(!y.entrypoints.packageName)n.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${m}' missing 'packageName' in entrypoints`,category:"layers",file:y.filePath,context:{key:m}});if(!y.surfaces.templates&&!y.surfaces.sandbox.enabled&&!y.surfaces.studio.enabled&&!y.surfaces.mcp.enabled)n.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${m}' has no enabled surfaces`,category:"layers",file:y.filePath,context:{key:m}})}for(let m of A.inventory.workspaceConfigs.values())if(!m.valid)for(let y of m.errors)n.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${y}`,category:"layers",file:m.file});return n}$$();import{ContractsrcSchema as hQ,DEFAULT_CONTRACTSRC as WA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as zQ}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:n,scan:A=zQ}=$,m=await c$(n,b),y=[],W=Array.isArray(b.type)?b.type:[b.type];for(let w of m){if(zb(w,b.config))continue;if(Lb(w))continue;try{let j=await n.readFile(w),B=A(j,w);if(B.specType==="unknown")continue;if(b.type&&!W.includes(B.specType))continue;y.push(B)}catch{}}return y}function sJ($){let b=new Map;for(let n of $){let A=b.get(n.specType)??[];A.push(n),b.set(n.specType,A)}return b}var cw={};f(cw,{toPascalCase:()=>yA,syncPackageDeclarations:()=>kQ,resolvePackageDeclarationConfig:()=>Nb,renderPackageDeclaration:()=>Wm,normalizePath:()=>C$,matchesAllowMissing:()=>ym,inferWorkspacePackageKind:()=>s0,getIndexExportPath:()=>bm,getCanonicalDeclarationRelativePath:()=>$m,discoverWorkspacePackages:()=>gw,createPackageDeclarationIssue:()=>wm,buildPackageTitle:()=>Fb,buildPackageDeclarationKey:()=>nm,buildExportName:()=>G$,buildDomain:()=>Am,buildDeclarationTags:()=>mm,auditPackageDeclarations:()=>vb,WORKSPACE_PACKAGE_KIND_BY_PREFIX:()=>e0,DEFAULT_PACKAGE_DECLARATION_REQUIRED_BY_KIND:()=>Fw});var Fw={libs:"feature",modules:"feature",integrations:"integration",bundles:"module-bundle",apps:"app-config",appsRegistry:"app-config",examples:"example"},e0={"packages/libs/":"libs","packages/modules/":"modules","packages/integrations/":"integrations","packages/bundles/":"bundles","packages/apps/":"apps","packages/apps-registry/":"appsRegistry","packages/examples/":"examples"};function Nb($){return{severity:$?.ci?.packageDeclarations?.severity??"error",requiredByKind:{...Fw,...$?.ci?.packageDeclarations?.requiredByKind??{}},allowMissing:$?.ci?.packageDeclarations?.allowMissing??[]}}function s0($){let b=C$($);for(let[n,A]of Object.entries(e0))if(b.startsWith(n))return A;return null}function $m($,b){switch($){case"libs":case"modules":return`src/${b}.feature.ts`;case"integrations":return"src/integration.ts";case"apps":case"appsRegistry":return"src/blueprint.ts";case"bundles":return`src/bundles/${yA(b)}Bundle.ts`;case"examples":return"src/example.ts"}}function bm($,b){switch($){case"libs":case"modules":return`./${b}.feature`;case"integrations":return"./integration";case"apps":case"appsRegistry":return"./blueprint";case"bundles":return`./bundles/${yA(b)}Bundle`;case"examples":return"./example"}}function nm($){return C$($).replace(/^packages\//,"").replace(/\//g,".")}function Fb($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function Am($){return $.replace(/[^a-zA-Z0-9-]/g,"-")}function mm($,b,n){return[...new Set([...n,"package",b,$])]}function ym($,b,n){return $.some((A)=>{let m=C$(A);return m===C$(b)||m===n})}function C$($){return $.replaceAll("\\","/").replace(/\/+$/,"")}function yA($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function G$($,b){let n=yA(b);switch($){case"feature":return`${n}Feature`;case"integration":return`${n}IntegrationSpec`;case"app-config":return`${n}Blueprint`;case"module-bundle":return`${n}Bundle`;case"example":return`${n}Example`}}import{scanAllSpecsFromSource as LQ,scanSpecSource as RQ}from"@contractspec/module.workspace";var CQ=["packages/libs/*/package.json","packages/modules/*/package.json","packages/integrations/*/package.json","packages/bundles/*/package.json","packages/apps/*/package.json","packages/apps-registry/*/package.json","packages/examples/*/package.json"];async function gw($,b={}){let n=C$(b.workspaceRoot??process.cwd()),A=await xQ($,n,b.config),m=await $.glob({cwd:n,patterns:A,absolute:!1,ignore:["**/node_modules/**","**/dist/**","**/.turbo/**"]}),y=Nb(b.config),W=[];for(let w of m){let j=C$($.dirname(w)),B=s0(j);if(!B)continue;let S=await Pw($,$.join(n,w)),Q=$.basename(j),Z=$.join(n,j),X=y.requiredByKind?.[EQ(B)];if(!X)continue;let Y=$m(B,Q);W.push({workspaceRoot:n,relativePackageRoot:j,packageRoot:Z,packageName:typeof S.name==="string"?S.name:j,packageDirName:Q,description:typeof S.description==="string"?S.description:void 0,kind:B,target:X,canonicalDeclarationRelativePath:Y,canonicalDeclarationPath:$.join(Z,Y),indexPath:$.join(Z,"src/index.ts"),indexExportPath:bm(B,Q)})}return W.sort((w,j)=>w.relativePackageRoot.localeCompare(j.relativePackageRoot))}async function vb($,b={}){let n=await gw($,b),A=[];for(let m of n){let y=await $.exists(m.canonicalDeclarationPath),W,w=!1;if(y){let j=await $.readFile(m.canonicalDeclarationPath),B=LQ(j,m.canonicalDeclarationPath);W=(B.length>0?B:[RQ(j,m.canonicalDeclarationPath)]).find((Q)=>Q.specType!=="unknown")?.specType,w=W===m.target}A.push({...m,exists:y,matchesExpectedTarget:w,detectedSpecType:W})}return A}async function xQ($,b,n){let A=$.join(b,"package.json");if(await $.exists(A)){let m=await Pw($,A),y=IQ(m);if(y.length>0)return y.map((W)=>`${vw(W)}/package.json`)}if(n?.packages?.length)return n.packages.map((m)=>`${vw(m)}/package.json`);return CQ}function IQ($){if(Array.isArray($.workspaces))return $.workspaces.filter((n)=>typeof n==="string");let b=$.workspaces;if(Array.isArray(b?.packages))return b.packages.filter((n)=>typeof n==="string");return[]}function EQ($){return $==="appsRegistry"?"appsRegistry":$}function vw($){return $.replace(/\/+$/,"")}async function Pw($,b){try{return JSON.parse(await $.readFile(b))}catch{return{}}}function Wm($){let{pkg:b,refs:n,owners:A,defaultTags:m}=$,y={key:nm(b.relativePackageRoot),version:"1.0.0",title:Fb(b.packageDirName),description:b.description??`ContractSpec package declaration for ${b.packageName}.`,domain:Am(b.packageDirName),owners:A,tags:mm(b.packageDirName,b.kind,m),stability:"experimental"};switch(b.target){case"feature":return MQ(b,n,y);case"integration":return TQ(b,n,y);case"app-config":return DQ(b,n,y);case"module-bundle":return rn({target:"module-bundle",key:y.key,title:y.title,description:y.description,exportName:G$("module-bundle",b.packageDirName)});case"example":return In({key:y.key,version:y.version,description:y.description,title:y.title,domain:y.domain,owners:y.owners,tags:y.tags,stability:y.stability,packageName:b.packageName})}}function MQ($,b,n){let A=[jb("operations",b.operations),jb("events",b.events),jb("presentations",b.presentations),jb("experiments",b.experiments),jb("workflows",b.workflows),jb("dataViews",b.dataViews)].filter(Boolean);return`${$.packageName==="@contractspec/lib.contracts-spec"?"import { defineFeature } from './features';":"import { defineFeature } from '@contractspec/lib.contracts-spec/features';"}
|
|
1941
|
+
|
|
1942
|
+
export const ${G$("feature",$.packageDirName)} = defineFeature({
|
|
1943
|
+
meta: ${NQ(n)},
|
|
1944
|
+
${A.length>0?`${A.join(`
|
|
1945
|
+
`)}
|
|
1946
|
+
`:""}});
|
|
1947
|
+
`}function TQ($,b,n){let A=b.capabilities.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
1948
|
+
`);return`import { defineIntegration } from '@contractspec/lib.contracts-integrations';
|
|
1949
|
+
import { defineSchemaModel } from '@contractspec/lib.schema';
|
|
1950
|
+
|
|
1951
|
+
const ${G$("integration",$.packageDirName)}Config = defineSchemaModel({
|
|
1952
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationConfig',
|
|
1953
|
+
description: 'Managed configuration for ${$.packageName}.',
|
|
1954
|
+
fields: {},
|
|
1955
|
+
});
|
|
1956
|
+
|
|
1957
|
+
const ${G$("integration",$.packageDirName)}Secrets = defineSchemaModel({
|
|
1958
|
+
name: '${Fb($.packageDirName).replace(/\s+/g,"")}IntegrationSecret',
|
|
1959
|
+
description: 'Secret material for ${$.packageName}.',
|
|
1960
|
+
fields: {},
|
|
1961
|
+
});
|
|
1962
|
+
|
|
1963
|
+
export const ${G$("integration",$.packageDirName)} = defineIntegration({
|
|
1964
|
+
meta: {
|
|
1965
|
+
...${rw(n)},
|
|
1966
|
+
category: 'custom',
|
|
1967
|
+
},
|
|
1968
|
+
supportedModes: ['managed'],
|
|
1969
|
+
capabilities: {
|
|
1970
|
+
provides: [
|
|
1971
|
+
${A||" // Add capability refs here"}
|
|
1972
|
+
],
|
|
1973
|
+
},
|
|
1974
|
+
configSchema: { schema: ${G$("integration",$.packageDirName)}Config, example: {} },
|
|
1975
|
+
secretSchema: { schema: ${G$("integration",$.packageDirName)}Secrets, example: {} },
|
|
1976
|
+
healthCheck: { method: 'ping', timeoutMs: 5000 },
|
|
1977
|
+
});
|
|
1978
|
+
`}function DQ($,b,n){let A=b.features.map((w)=>` { key: '${w.key}' },`).join(`
|
|
1979
|
+
`),m=kw(b.workflows),y=kw(b.dataViews),W=b.capabilities.map((w)=>` { key: '${w.key}', version: '${w.version}' },`).join(`
|
|
1980
|
+
`);return`import { defineAppConfig } from '@contractspec/lib.contracts-spec/app-config/spec';
|
|
1981
|
+
|
|
1982
|
+
export const ${G$("app-config",$.packageDirName)} = defineAppConfig({
|
|
1983
|
+
meta: {
|
|
1984
|
+
...${rw(n)},
|
|
1985
|
+
appId: '${Q$($.packageDirName)}',
|
|
1986
|
+
},
|
|
1987
|
+
capabilities: {
|
|
1988
|
+
enabled: [
|
|
1989
|
+
${W||" // Add capability refs here"}
|
|
1990
|
+
],
|
|
1991
|
+
},${A?`
|
|
1992
|
+
features: {
|
|
1993
|
+
include: [
|
|
1994
|
+
${A}
|
|
1995
|
+
],
|
|
1996
|
+
},`:""}${y?`
|
|
1997
|
+
dataViews: {
|
|
1998
|
+
${y}
|
|
1999
|
+
},`:""}${m?`
|
|
2000
|
+
workflows: {
|
|
2001
|
+
${m}
|
|
2002
|
+
},`:""}
|
|
2003
|
+
});
|
|
2004
|
+
`}function jb($,b){if(b.length===0)return"";return` ${$}: [
|
|
2005
|
+
${b.map((n)=>` { key: '${n.key}', version: '${n.version}' },`).join(`
|
|
2006
|
+
`)}
|
|
2007
|
+
],`}function kw($){return $.map((b,n)=>` ${n===0?"primary":`item${n+1}`}: {
|
|
2008
|
+
key: '${b.key}',
|
|
2009
|
+
version: '${b.version}',
|
|
2010
|
+
},`).join(`
|
|
2011
|
+
`)}function NQ($){return`{
|
|
2012
|
+
key: '${$.key}',
|
|
2013
|
+
version: '${$.version}',
|
|
2014
|
+
title: '${Q$($.title)}',
|
|
2015
|
+
description: '${Q$($.description)}',
|
|
2016
|
+
domain: '${Q$($.domain)}',
|
|
2017
|
+
owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2018
|
+
tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}],
|
|
2019
|
+
stability: '${$.stability}',
|
|
2020
|
+
}`}function rw($){return`{ key: '${$.key}', version: '${$.version}', title: '${Q$($.title)}', description: '${Q$($.description)}', domain: '${Q$($.domain)}', owners: [${$.owners.map((b)=>`'${Q$(b)}'`).join(", ")}], tags: [${$.tags.map((b)=>`'${Q$(b)}'`).join(", ")}], stability: '${$.stability}' }`}function Q$($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{scanAllSpecsFromSource as FQ}from"@contractspec/module.workspace";var vQ={feature:["@contractspec/lib.contracts-spec"],integration:["@contractspec/lib.contracts-integrations","@contractspec/lib.schema"],"app-config":["@contractspec/lib.contracts-spec"],"module-bundle":["@contractspec/lib.surface-runtime"],example:["@contractspec/lib.contracts-spec"]};function gQ($){return $.packageName!=="@contractspec/lib.schema"}function PQ($,b){if(b===$.packageName)return!1;if($.packageName==="@contractspec/lib.schema"&&b==="@contractspec/lib.contracts-spec")return!1;return!0}async function kQ($,b={}){let n=await vb($,b),A=[],m=[],y=[];for(let W of n){if(!b.force&&W.exists&&W.matchesExpectedTarget){y.push({...W,action:"skipped",declarationCreated:!1,indexUpdated:!1,packageJsonUpdated:!1,dependenciesUpdated:[]});continue}let w=await rQ($,W),j=Wm({pkg:W,refs:w,owners:b.config?.defaultOwners?.length?b.config.defaultOwners:["@contractspec-core"],defaultTags:b.config?.defaultTags??[]});if(!b.dryRun)await $.writeFile(W.canonicalDeclarationPath,`${j.trimEnd()}
|
|
2021
|
+
`);let B=await fQ($,W,b.dryRun,gQ(W)),{dependenciesUpdated:S,packageJsonUpdated:Q}=await cQ($,W,b.dryRun);if(W.exists)m.push(W.canonicalDeclarationPath);else A.push(W.canonicalDeclarationPath);if(B)m.push(W.indexPath);if(Q)m.push($.join(W.packageRoot,"package.json"));y.push({...W,action:W.exists?"updated":"created",declarationCreated:!W.exists,indexUpdated:B,packageJsonUpdated:Q,dependenciesUpdated:S})}return{packages:y,createdFiles:A,updatedFiles:m}}function wm($,b){return{allowlisted:ym(b,$.relativePackageRoot,$.packageName),message:$.exists?`Package declaration at ${$.canonicalDeclarationRelativePath} must be a ${$.target} spec.`:`Package ${$.relativePackageRoot} is missing its canonical ${$.target} declaration at ${$.canonicalDeclarationRelativePath}.`}}async function rQ($,b){let n=await $.glob({cwd:b.packageRoot,patterns:["src/**/*.{ts,tsx}"],absolute:!1,ignore:["**/dist/**","**/*.test.*","**/*.spec.*","**/*.stories.*"]}),A={operations:[],events:[],presentations:[],experiments:[],workflows:[],dataViews:[],capabilities:[],features:[]};for(let m of n){if(m===b.canonicalDeclarationRelativePath)continue;let y=await $.readFile($.join(b.packageRoot,m)),W=FQ(y,m);for(let w of W){if(!w.key||!w.version)continue;let j={key:w.key,version:w.version};switch(w.specType){case"operation":x$(A.operations,j);break;case"event":x$(A.events,j);break;case"presentation":x$(A.presentations,j);break;case"experiment":x$(A.experiments,j);break;case"workflow":x$(A.workflows,j);break;case"data-view":x$(A.dataViews,j);break;case"capability":x$(A.capabilities,j);break;case"feature":x$(A.features,j);break}}}return A}function x$($,b){if(!$.some((n)=>n.key===b.key&&n.version===b.version))$.push(b)}async function fQ($,b,n=!1,A=!0){if(!A)return!1;let m=`export * from "${b.indexExportPath}";`,y=new RegExp(`export \\* from ['"]${b.indexExportPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"];`),W=await $.exists(b.indexPath)?await $.readFile(b.indexPath):"";if(y.test(W))return!1;if(W=`${W.trimEnd()}
|
|
2022
|
+
${m}
|
|
2023
|
+
`.trimStart(),!n)await $.writeFile(b.indexPath,W);return!0}async function cQ($,b,n=!1){let A=$.join(b.packageRoot,"package.json"),m=JSON.parse(await $.readFile(A)),y=fw(m,"dependencies"),W=[],w=!1;for(let B of vQ[b.target]){if(!PQ(b,B)){if(B in y)delete y[B],w=!0;continue}if(typeof y[B]!=="string")y[B]="workspace:*",W.push(B)}let j=fw(m,"exports");if(w=w||W.length>0,typeof j["."]!=="string")j["."]="./src/index.ts",w=!0;if(w&&!n)await $.writeFile(A,`${JSON.stringify(m,null,"\t")}
|
|
2024
|
+
`);return{dependenciesUpdated:W,packageJsonUpdated:w}}function fw($,b){let n=$[b];if(typeof n==="object"&&n!==null&&!Array.isArray(n))return n;let A={};return $[b]=A,A}var dQ=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,uQ=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,oQ=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,iQ=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,tQ=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,lQ=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,pQ=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function wA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function aQ($,b){let n=$.replaceAll("\\","/"),A=new Set(["contracts","features",...wA(b?.conventions?.operations),...wA(b?.conventions?.events),...wA(b?.conventions?.presentations),...wA(b?.conventions?.forms)]);return n.split("/").some((m)=>A.has(m))}function eQ($,b,n){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||tQ.test(A)||iQ.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(b.has(A))return!1;if(aQ(A,n))return!1;return dQ.test(A)}function hw($){return $.replaceAll("\\","/").match(lQ)?.[1]??null}function sQ($){let b=$.split(`
|
|
2025
|
+
`).map((n)=>n.trim()).filter((n)=>n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")&&!n.startsWith("*/"));return b.length>0&&b.every((n)=>n.startsWith("import ")||n.startsWith("export *")||n.startsWith("export {")||n.startsWith("export type {")||n==="'use client';"||n==='"use client";'||n==="'use server';"||n==='"use server";')}function $4($){if(!$)return WA;let b=hQ.safeParse($),n=b.success?b.data:{};return{...WA,...n,conventions:{...WA.conventions,...n.conventions??{}},ci:{...WA.ci,...n.ci??{}}}}async function jm($,b){let{fs:n,logger:A}=$,m=[],y=b.config?$4(b.config):await P(n),W=Nb(y),w=await j$({fs:n},{config:y}),j=new Set(w.map((Q)=>Q.filePath.replaceAll("\\","/"))),B=new Set(w.map((Q)=>hw(Q.filePath)).filter((Q)=>Boolean(Q))),S=await n.glob({pattern:"**/*.{ts,tsx}"});for(let Q of S){if(!eQ(Q,j,y))continue;try{let Z=await n.readFile(Q);if(sQ(Z))continue;let X=hw(Q);if(!(X!==null&&pQ.test(X)&&B.has(X))&&!oQ.test(Z))continue;if(uQ.test(Z))continue;m.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:Q})}catch(Z){A.warn("Policy scan failed for file",{file:Q,error:Z instanceof Error?Z.message:String(Z)})}}if(W.severity!=="off"){let Q=await vb(n,{config:y,workspaceRoot:b.workspaceRoot});for(let Z of Q){if(Z.exists&&Z.matchesExpectedTarget)continue;let X=wm(Z,W.allowMissing??[]);m.push({ruleId:"policy-package-declaration",severity:X.allowlisted||W.severity==="warning"?"warning":"error",message:X.message,category:"policy",file:Z.canonicalDeclarationPath,context:{allowlisted:X.allowlisted,expectedTarget:Z.target,packageName:Z.packageName,packageRoot:Z.relativePackageRoot}})}}return m}import{validateSpecStructure as b4}from"@contractspec/module.workspace";async function Bm($){let b=[];for(let n of $){let A=b4(n);for(let m of A.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:m,category:"structure",file:n.filePath});for(let m of A.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:m,category:"structure",file:n.filePath})}return b}async function Sm($){let b=[],n=new Map,A=new Map;for(let m of $){if(!m.key||!m.version)continue;if(m.specType==="test-spec"){let y=`${m.key}.v${m.version}`;n.set(y,{key:m.key,version:m.version,file:m.filePath,type:"test-spec"})}if(m.testRefs&&m.testRefs.length>0){if(!A.has(m.filePath))A.set(m.filePath,[]);A.get(m.filePath)?.push({key:m.key,version:m.version,testRefs:m.testRefs})}}for(let[m,y]of A)for(let W of y){if(!W.testRefs)continue;let w=t0(m,W.key,W.version,W.testRefs,n,{treatMissingAsError:!0});for(let j of w.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:j,category:"test-refs",file:m,context:{specKey:W.key,specVersion:W.version,missingTests:w.missingTests}})}return b}$$();async function Qm($,b){let{fs:n}=$,A=[],m=await P(n);for(let y of b){if(y.specType!=="operation")continue;let W=await nA(y,{fs:n},m,{checkTests:!0,outputDir:m.outputDir});for(let w of W.errors)A.push({ruleId:"test-missing",severity:"warning",message:w,category:"tests",file:y.filePath});for(let w of W.warnings)A.push({ruleId:"test-warning",severity:"warning",message:w,category:"tests",file:y.filePath})}return A}function e($,b,n){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},m=b.filter((w)=>w.severity==="error").length,y=b.filter((w)=>w.severity==="warning").length,W=b.filter((w)=>w.severity==="note").length;return{category:$,label:A[$],errors:m,warnings:y,notes:W,passed:m===0,durationMs:n}}async function dw($){try{if(!await $.exists(".git/HEAD"))return{};let n=await $.readFile(".git/HEAD"),A=n.match(/^ref: (.+)$/m);if(A){let y=A[1]?.replace("refs/heads/",""),W=`.git/${A[1]}`;if(await $.exists(W))return{commitSha:(await $.readFile(W)).trim(),branch:y};return{branch:y}}return{commitSha:n.trim()}}catch{return{}}}function uw($){let b=$.config?.ci?.checks,n=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)n.push("handlers");if($.checkTests)n.push("tests");if($.implementation)n.push("implementation");if($.checkDrift)n.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return n.filter((A)=>!$.skip?.includes(A));return n}async function sU($,b={}){let n=Date.now(),{fs:A,logger:m}=$,y=[],W=[],w=uw(b);m.info("Starting CI checks...",{checks:w});let j=await P(A),B=await cn($,{config:j,pattern:b.pattern});if(w.includes("structure")){let V=Date.now(),O=await Bm(B);y.push(...O),W.push(e("structure",O,Date.now()-V))}if(w.includes("integrity")){let V=Date.now(),O=await p0($,b);y.push(...O),W.push(e("integrity",O,Date.now()-V))}if(w.includes("deps")){let V=Date.now(),O=await x0($,b);y.push(...O),W.push(e("deps",O,Date.now()-V))}if(w.includes("doctor")){let V=Date.now(),O=await f0($,b);y.push(...O),W.push(e("doctor",O,Date.now()-V))}if(w.includes("docs")){let V=Date.now(),O=await I0($,b);y.push(...O),W.push(e("docs",O,Date.now()-V))}if(w.includes("policy")){let V=Date.now(),O=await jm($,b);y.push(...O),W.push(e("policy",O,Date.now()-V))}if(w.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await o0($,B);y.push(...O),W.push(e("handlers",O,Date.now()-V))}if(w.includes("tests")||b.checkTests){let V=Date.now(),O=await Qm($,B);y.push(...O),W.push(e("tests",O,Date.now()-V))}if(w.includes("test-refs")){let V=Date.now(),O=await Sm(B);y.push(...O),W.push(e("test-refs",O,Date.now()-V))}if(w.includes("coverage")){let V=Date.now(),O=await C0($,B,b);y.push(...O),W.push(e("coverage",O,Date.now()-V))}if(w.includes("implementation")){let V=Date.now(),O=await i0($,B,b);y.push(...O),W.push(e("implementation",O,Date.now()-V))}if(w.includes("layers")){let V=Date.now(),O=await a0($,b);y.push(...O),W.push(e("layers",O,Date.now()-V))}if(w.includes("drift")){let V=Date.now(),O=await u0($,b);y.push(...O),W.push(e("drift",O,Date.now()-V))}let S=y.filter((V)=>V.severity==="error").length,Q=y.filter((V)=>V.severity==="warning").length,Z=y.filter((V)=>V.severity==="note").length,X=b.failOnWarnings?S===0&&Q===0:S===0,Y=await dw(A),G={success:X,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:y,categories:W,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...Y};return m.info("CI checks complete",{success:X,errors:S,warnings:Q,durationMs:G.durationMs}),G}var bK=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],nK={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function wK($,b={}){let{fs:n,logger:A}=$,m=(b.outputDir??"./src").replace(/\\/g,"/"),y=["generated/**","dist/**",".turbo/**"],W=[`${m}/handlers/**/*.handler.ts`,`${m}/handlers/**/*.handler.test.ts`,`${m}/components/**/*.tsx`,`${m}/components/**/*.test.tsx`,`${m}/forms/**/*.form.tsx`,`${m}/forms/**/*.form.test.tsx`,`${m}/**/*.runner.ts`,`${m}/**/*.renderer.tsx`],w=b.generatedOnly?[...y,...W]:[...y,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...W],j=await n.glob({patterns:w,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of j)try{let Z=await n.stat(Q),X=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&X<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)A.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await n.remove(Q),A.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}$$();var Vj={};f(Vj,{writeReviewPacket:()=>Rm,writeDecisionEnvelope:()=>db,withBranch:()=>o$,verifyConnectMutation:()=>j6,resolveWorkspace:()=>i,resolveStoragePaths:()=>X$,replayConnectDecision:()=>r4,persistLatestArtifacts:()=>zm,persistDecisionArtifacts:()=>hb,normalizeEvalInput:()=>M4,matchConfiguredPath:()=>gb,loadStoredDecision:()=>ub,listStoredReviewPackets:()=>Cm,listConnectReviewPackets:()=>f4,isReviewCommand:()=>Zm,isDeniedCommand:()=>Xm,isAllowedCommand:()=>jA,initConnectWorkspace:()=>v4,inferSurfaces:()=>rb,evaluateConnectDecision:()=>I4,ensureStorage:()=>cb,defaultActor:()=>kb,decisionArtifactRefs:()=>Sb,createConnectControlPlaneRuntime:()=>a4,connectVerdictToPolicy:()=>I$,configuredThreshold:()=>u$,compileConnectPlanPacket:()=>ob,buildConnectContextPack:()=>fb,assessConnectPolicy:()=>Pb,assertConnectEnabled:()=>A$,artifactRef:()=>_$,appendAuditRecord:()=>Lm,analyzeConnectImpact:()=>i$,CONTROL_PLANE_TRACE_GET_REF:()=>BA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>SA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>qm,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Hm,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Gm,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>U$,AGENT_APPROVALS_REF:()=>QA,ACP_TERMINAL_EXEC_REF:()=>y4,ACP_FS_ACCESS_REF:()=>m4});import n4 from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function gb($,b,n){if(!n||n.length===0)return!1;let A=b.replaceAll("\\","/");return n4.isMatch(A,n,{contains:!0})}function u$($,b,n){return $.config.connect?.policy?.reviewThresholds?.[b]??n}function jA($,b){return Ym($.config.connect?.commands?.allow,b)}function Zm($,b){return Ym($.config.connect?.commands?.review,b)}function Xm($,b){return Ym($.config.connect?.commands?.deny,b)}function Ym($,b){if(!$||$.length===0)return!1;return $.some((n)=>b===n||b.startsWith(`${n} `))}function iw($,b){if(b.length===0)return{state:"none"};for(let A of b)if(Xm($,A))return{commandMatch:A,state:"deny"};for(let A of b)if(Zm($,A))return{commandMatch:A,state:"review"};if(b.every((A)=>jA($,A)))return{state:"allow"};let n=b.find(A4);if(n)return{commandMatch:n,state:"destructive"};return{commandMatch:b.find((A)=>!jA($,A)),state:"unknown"}}function A4($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return ow(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return ow(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function ow($,b){return b.every((n)=>$.includes(n)||$.includes(n.replace("-","")))}var Gm={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Hm={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},qm={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},BA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},SA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},U$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},m4={key:"acp.fs.access",version:"1.0.0",kind:"command"},y4={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},QA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Pb($,b){let n=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.immutablePaths)),A=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.protectedPaths)),m=b.touchedPaths.find((Z)=>gb($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:y,state:W}=iw($,b.commands??[]),w=b.impactAnalysis.unknownPaths.length>0,j=b.impactAnalysis.driftFiles.length>0,B=W4({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:W==="destructive",commandState:W,contractDrift:j,generatedPath:Boolean(m),immutable:Boolean(n),protectedPath:Boolean(A),smokeFailed:b.smokeFailed===!0,unknownImpact:w,workspace:$}),S=w4({breakingChange:b.impactAnalysis.breakingChange,commandMatch:y,commandState:W,contractDrift:j,protectedPath:A,unknownPaths:b.impactAnalysis.unknownPaths}),Q=I$(B);return{commandMatch:y,commandState:W,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:m,immutablePath:n,protectedPath:A,requiredApprovals:Q.requiresApproval?[{capability:U$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function I$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function W4($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(u$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(u$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(u$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(u$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(u$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(j4)[0]??"permit"}function w4($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function j4($,b){return tw($)-tw(b)}function tw($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as C4}from"crypto";var sw={};f(sw,{formatPrComment:()=>lw,formatMinimalComment:()=>Om,formatJson:()=>aw,formatCheckRun:()=>pw,detectImpact:()=>K$,ImpactDetectionOverviewDocBlock:()=>Y4});function lw($,b={template:"detailed"}){let n=[];if(n.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),n.push(""),$.hasBreaking)n.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)n.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else n.push("\u2705 **No contract impact**");if(n.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(n.push("### Summary"),n.push(""),n.push("| Type | Count |"),n.push("|------|-------|"),$.summary.breaking>0)n.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)n.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)n.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)n.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)n.push(`| \u2796 Removed | ${$.summary.removed} |`);n.push("")}if(b.template==="detailed"&&$.deltas.length>0){n.push("### Changes"),n.push("");let A=$.deltas.filter((y)=>y.severity==="breaking"),m=$.deltas.filter((y)=>y.severity==="non_breaking");if(A.length>0){n.push("#### \uD83D\uDD34 Breaking Changes"),n.push("");for(let y of A)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}if(m.length>0){n.push("#### \uD83D\uDFE1 Non-breaking Changes"),n.push("");for(let y of m)n.push(`- **${y.specKey}**: ${y.description}`);n.push("")}}if($.addedSpecs.length>0){n.push("### Added Specs"),n.push("");for(let A of $.addedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if($.removedSpecs.length>0){n.push("### Removed Specs"),n.push("");for(let A of $.removedSpecs)n.push(`- \`${A.key}\` v${A.version} (${A.type})`);n.push("")}if(b.drift)if(b.drift.hasDrift){n.push("### \u26A0\uFE0F Drift Detected"),n.push(""),n.push("The following generated files are out of sync with their specs:"),n.push("");for(let A of b.drift.files)n.push(`- \`${A}\``);n.push(""),n.push("Run `contractspec generate` to regenerate artifacts."),n.push("")}else n.push("### \u2705 No Drift Detected"),n.push("");return n.push("---"),n.push(`*Generated by ContractSpec at ${$.timestamp}*`),n.join(`
|
|
2026
|
+
`)}function Om($){if($.hasBreaking)return`\u274C **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`\u26A0\uFE0F **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"\u2705 **No contract impact**"}function pw($,b,n={}){let A=n.key??"ContractSpec Impact",m=n.failOnBreaking??!0,y,W;if($.hasBreaking)y=m?"failure":"neutral",W=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)y="success",W=`Non-breaking changes (${$.summary.nonBreaking})`;else y="success",W="No contract impact";let w=Om($);return{name:A,headSha:b,conclusion:y,title:W,summary:w,annotations:$.deltas.filter((j)=>j.severity==="breaking").slice(0,50).map((j)=>({path:j.path,startLine:1,endLine:1,annotationLevel:"failure",message:j.description,title:`Breaking: ${j.rule}`}))}}function aw($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((n)=>({type:n.rule,path:n.specKey,summary:n.description,severity:n.severity==="breaking"?"breaking":n.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as B4,computeIoDiff as S4,generateSnapshot as ew}from"@contractspec/module.workspace";async function K$($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting impact detection...",{baseline:b.baseline});let w=(await n.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${w.length} spec files`);let j=await Q4(n,w,y),B=ew(j),S;if(b.baseline){let X=await Z4(n,A,w,b.baseline,y);S=ew(X)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=X4(S.specs,B.specs),Z=B4(S.specs,B.specs,Q);return m.info("Impact detection complete",{status:Z.status,breaking:Z.summary.breaking,nonBreaking:Z.summary.nonBreaking}),{...Z,workspaceRoot:y,specsAnalyzed:w.length,baseRef:b.baseline}}async function Q4($,b,n){let A=[];for(let m of b){let y=await $.readFile(m);A.push({path:m,content:y})}return A}async function Z4($,b,n,A,m){let y=[];for(let W of n)try{let w=await b.showFile(A,W);y.push({path:W,content:w})}catch{}return y}function X4($,b){let n=[],A=new Map($.map((y)=>[`${y.key}@${y.version}`,y])),m=new Map(b.map((y)=>[`${y.key}@${y.version}`,y]));for(let[y,W]of m){let w=A.get(y);if(w&&W.type==="operation"&&w.type==="operation"){let j=S4(w.io,W.io);n.push(...j)}}return n}var Y4={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1613
2027
|
# Contract Impact Detection
|
|
1614
2028
|
|
|
1615
2029
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -1655,49 +2069,49 @@ The system consists of three layers:
|
|
|
1655
2069
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1656
2070
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1657
2071
|
3. **Integrations**: CLI command + GitHub Action
|
|
1658
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
1659
|
-
`;await $.writeFile(
|
|
1660
|
-
`)}async function
|
|
1661
|
-
`);if(A.test(
|
|
1662
|
-
`)?
|
|
2072
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as bj,readFileSync as nj}from"fs";import{basename as G4,join as Vm,resolve as H4}from"path";import{ContractsrcSchema as q4,DEFAULT_CONTRACTSRC as O4}from"@contractspec/lib.contracts-spec/workspace-config";function i($={}){let b=H4($.cwd??process.cwd()),n=$.workspaceRoot??I(b),A=$.packageRoot??c(b),m=$.config??V4(n,A),y=J4(A,n);return{cwd:b,workspaceRoot:n,packageRoot:A,config:m,repoId:y,branch:"unknown"}}function o$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function kb($,b){return b??{id:`cli:${$}`,type:"human"}}function rb($){let b=new Set;for(let n of $){if(n.includes("/cli-")||n.includes("/apps/cli-"))b.add("cli");if(n.includes("/contracts-spec/")||n.includes("/specs/"))b.add("contract");if(n.includes("/components/")||n.includes("/ui/")||n.endsWith(".tsx")||n.endsWith(".jsx"))b.add("ui");if(n.includes("/integrations/")||n.includes("/provider"))b.add("integration");if(n.includes("/libs/")||n.includes("/shared/")||n.includes("/utils/"))b.add("library");if(n.includes("/modules/")||n.includes("/bundles/")||n.includes("/examples/"))b.add("solution");if(n.includes("/runtime/"))b.add("runtime");if(n.includes("/harness"))b.add("harness");if(n.includes("/ai-agent/"))b.add("agent");if(n.includes("/knowledge/"))b.add("knowledge");if(n.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function V4($,b){let n={...O4};if($!==b)n=$j(n,Vm($,".contractsrc.json"));return $j(n,Vm(b,".contractsrc.json"))}function $j($,b){if(!bj(b))return $;try{let n=nj(b,"utf-8"),A=JSON.parse(n),m=q4.safeParse(A);if(!m.success)return $;return{...$,...m.data}}catch{return $}}function J4($,b){let n=Vm($,"package.json");if(bj(n))try{let A=JSON.parse(nj(n,"utf-8"));if(A.name)return A.name}catch{}return G4(b)}async function i$($,b){let n=await j$({fs:$.fs},{config:b.workspace.config}),A=new Map(n.filter((j)=>typeof j.key==="string").map((j)=>[j.key,j])),m=b.touchedPaths.map((j)=>U4($.fs,b.workspace,j,n,A)),y=b.baseline!=null?await K$({...$,logger:$.logger??mj},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,W=await K4($,b.workspace,b.touchedPaths),w=_m([...m.flatMap((j)=>j.contracts),...(y?.deltas??[]).map((j)=>({key:j.specKey,version:j.specVersion,kind:j.specType==="event"?"event":"command"}))]);return{breakingChange:y?.hasBreaking===!0,driftFiles:W,impactResult:y,impactedContracts:w,pathImpacts:m,unknownPaths:m.filter((j)=>j.contracts.length===0).map((j)=>j.path)}}function U4($,b,n,A,m){let y=$.resolve(b.workspaceRoot,n),W=Km(n),w=A.map((Y)=>{let G=m$($.relative(b.workspaceRoot,Y.filePath));return{score:L4(n,W,G,Y.key),spec:Y}}).filter((Y)=>Y.score>=45).sort((Y,G)=>G.score-Y.score).slice(0,3),j=A.find((Y)=>Y.filePath===y),B=j?[{score:100,spec:j}]:w,S=B.filter((Y)=>typeof Y.spec.key==="string").map((Y)=>Um(Y.spec.key,Y.spec.version,Y.spec.kind)),Q=B.flatMap((Y)=>[...Y.spec.emittedEvents??[],...Y.spec.policyRefs??[],...Y.spec.testRefs??[]].map((G)=>m.get(G.key)).filter(Boolean).map((G)=>Um(G.key,G.version,G.kind))),Z=_m([...S,...Q]),X=_m([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((Y)=>Y.spec.policyRefs??[]).map((Y)=>Um(Y.key,Y.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:n,policies:X,reasons:B.map((Y)=>`${Y.spec.key??Y.spec.filePath} matched with score ${Y.score}`),surfaces:rb([n])}}async function K4($,b,n){let A=_4($.fs,b,n),m=await Promise.all(A.map(async(y)=>{let W=$.fs.resolve(b.packageRoot,y.comparisonRoot),w=await bA({...$,logger:$.logger??mj},b.workspaceRoot,W,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),j=y.filterPrefix&&y.filterPrefix!==y.comparisonRoot?m$($.fs.relative(y.comparisonRoot,y.filterPrefix)):void 0;return w.files.filter((B)=>j?m$(B)===j||m$(B).startsWith(`${j}/`):!0).map((B)=>m$($.fs.join(y.comparisonRoot,B)))}));return[...new Set(m.flat())].sort()}function _4($,b,n){let A=(b.config.connect?.policy?.generatedPaths??[]).map(R4).filter(Boolean),m=b.config.outputDir&&b.config.outputDir!=="./src"?m$(b.config.outputDir):void 0,y=new Map;for(let W of n){let w=m$(W);if(m&&w.startsWith(m))y.set(m,{comparisonRoot:m});for(let j of A)if(w.startsWith(j)){let B=z4($,m,j);y.set(`${B}::${j}`,{comparisonRoot:B,filterPrefix:j})}}return[...y.values()]}function z4($,b,n){if(b&&n.startsWith(b))return b;return $.basename(n)==="docs"?m$($.dirname(n)):n}function L4($,b,n,A){if(m$($)===m$(n))return 100;let m=Km(n),y=Km(A??""),W=Aj($)===Aj(n)?40:0,w=Jm($.split("/"),n.split("/"),5),j=Jm(b,m,5),B=Jm(b,y,4);return W+w+j+B}function Jm($,b,n){let A=new Set(b);return $.filter((m)=>A.has(m)).length*n}function Km($){return m$($).split(/[\/._-]+/).filter(Boolean)}function Aj($){return m$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function R4($){return m$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function m$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Um($,b,n){return{key:$,version:String(b??"1.0.0"),kind:n==="query"||n==="event"||n==="policy"||n==="capability"?n:"command"}}function _m($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var mj={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function fb($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let A=kb(b.taskId,b.actor),m=await x4($,n.workspaceRoot,b),y=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),W=n.config.connect?.canonPacks??[];return{id:`connect.ctx_${C4()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:A,knowledge:W.map((w)=>({spaceKey:w.ref,category:"canonical",trustLevel:w.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:y.impactedContracts,affectedSurfaces:y.pathImpacts.length>0?[...new Set(y.pathImpacts.flatMap((w)=>w.surfaces))].sort():rb(m),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...W.map((w)=>({key:w.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...W.map((w)=>({kind:"canon-pack",ref:w.ref}))],acceptanceChecks:n.config.connect?.policy?.smokeChecks??[]}}async function x4($,b,n){let A=n.paths??[];if(A.length>0)return A.map((y)=>yj($.fs,b,y));if(!n.baseline)return[];return(await $.git.diffFiles(n.baseline)).map((y)=>yj($.fs,b,y))}function yj($,b,n){let A=$.resolve(b,n);return $.relative(b,A).replaceAll("\\","/")}import{resolve as t$}from"path";function X$($){let b=$.config.connect?.storage,n=t$($.packageRoot,b?.root??".contractspec/connect");return{root:n,contextPack:t$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:t$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:t$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:t$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:t$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:t$(n,"decisions")}}async function cb($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function zm($,b,n){if(n.contextPack)await Z$($,b.contextPack,n.contextPack);if(n.planPacket)await Z$($,b.planPacket,n.planPacket);if(n.patchVerdict)await Z$($,b.patchVerdict,n.patchVerdict)}async function hb($,b,n,A){let m=$.join(b.decisionsDir,n);if(await $.mkdir(m),A.contextPack)await Z$($,$.join(m,"context-pack.json"),A.contextPack);if(A.planPacket)await Z$($,$.join(m,"plan-packet.json"),A.planPacket);if(A.patchVerdict)await Z$($,$.join(m,"patch-verdict.json"),A.patchVerdict);if(A.reviewPacket)await Z$($,$.join(m,"review-packet.json"),A.reviewPacket);if(A.evaluationResult!==void 0)await Z$($,$.join(m,"evaluation-result.json"),A.evaluationResult);if(A.replayBundle!==void 0)await Z$($,$.join(m,"replay-bundle.json"),A.replayBundle);return m}async function db($,b,n,A){let m=$.join(b.decisionsDir,n,"decision-envelope.json");return await Z$($,m,A),m}async function Lm($,b,n){let A=await Wj($,b.auditFile)??"",m=`${JSON.stringify(n)}
|
|
2073
|
+
`;await $.writeFile(b.auditFile,`${A}${m}`)}async function Rm($,b,n){let A=$.join(b.reviewPacketsDir,`${n.id}.json`);return await Z$($,A,n),A}async function ub($,b,n){let A=$.join(b.decisionsDir,n);return{historyDir:A,contextPack:await Bb($,$.join(A,"context-pack.json")),planPacket:await Bb($,$.join(A,"plan-packet.json")),patchVerdict:await Bb($,$.join(A,"patch-verdict.json")),reviewPacket:await Bb($,$.join(A,"review-packet.json")),envelope:await Bb($,$.join(A,"decision-envelope.json"))}}async function Cm($,b){let n=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),A=[];for(let m of n){let y=await Bb($,m);if(y)A.push({filePath:m,packet:y})}return A.sort((m,y)=>m.packet.id.localeCompare(y.packet.id))}function _$($,b,n){return $.relative(b.packageRoot,$.resolve(n)).replaceAll("\\","/")}function Sb($,b,n,A,m){let y=$.join(n.decisionsDir,A);return{contextPack:_$($,b,$.join(y,"context-pack.json")),planPacket:_$($,b,$.join(y,"plan-packet.json")),patchVerdict:_$($,b,$.join(y,"patch-verdict.json")),reviewPacket:m.reviewPacket?_$($,b,$.join(y,"review-packet.json")):void 0,evaluationResult:m.evaluationResult?_$($,b,$.join(y,"evaluation-result.json")):void 0,replayBundle:m.replayBundle?_$($,b,$.join(y,"replay-bundle.json")):void 0}}async function Z$($,b,n){await $.writeFile(b,`${JSON.stringify(n,null,2)}
|
|
2074
|
+
`)}async function Bb($,b){let n=await Wj($,b);if(!n)return;try{return JSON.parse(n)}catch{return}}async function Wj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function I4($,b,n){let A=i(b);if(A$(A),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let m=X$(A),y=await ub($.fs,m,b.decisionId),W=E4(A,y),w=b.scenarioKey?await n.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:W}):await n.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:W}),j=await hb($.fs,m,b.decisionId,{evaluationResult:w}),B=await $.fs.exists($.fs.join(j,"replay-bundle.json")),S={artifacts:Sb($.fs,A,m,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(y.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:y.envelope?.createdAt??new Date().toISOString(),runtimeLink:y.envelope?.runtimeLink,taskId:y.contextPack?.taskId??b.decisionId,verdict:y.patchVerdict?.verdict??"permit"};return await db($.fs,m,b.decisionId,S),{historyDir:j,evaluation:w,context:W}}function E4($,b){return{traceId:b.envelope?.runtimeLink?.traceId??b.patchVerdict?.controlPlane.traceId??b.contextPack?.actor.traceId,actorId:b.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:b.envelope?.runtimeLink?.decisionId,controlPlanePlanId:b.envelope?.runtimeLink?.planId??b.planPacket?.id,metadata:{approvalStatus:b.envelope?.runtimeLink?.approvalStatus,decisionId:b.patchVerdict?.decisionId,taskId:b.contextPack?.taskId,branch:b.contextPack?.branch??$.branch}}}function M4($){return $}import{DEFAULT_CONTRACTSRC as F4}from"@contractspec/lib.contracts-spec/workspace-config";async function ZA($,b){let n=$.join(b.root,".gitignore"),A=b.behavior??"auto",m=Bj(b.patterns);if(m.length===0||A==="skip")return{target:"gitignore",filePath:n,action:"skipped",message:A==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(A==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${n}?`,!0))return{target:"gitignore",filePath:n,action:"skipped",message:"User skipped ContractSpec gitignore update"};let y=await $.exists(n),W=y?await $.readFile(n):"",w=T4(W,m);if(jj(W)===jj(w))return{target:"gitignore",filePath:n,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(n,w),{target:"gitignore",filePath:n,action:y?"merged":"created",message:y?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(y){return{target:"gitignore",filePath:n,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}function T4($,b){let n=D4(b),A=N4(),m=$.replace(/\r\n/g,`
|
|
2075
|
+
`);if(A.test(m))return m.replace(A,n);if(m.trim().length===0)return n;return`${m.endsWith(`
|
|
2076
|
+
`)?m:`${m}
|
|
1663
2077
|
`}
|
|
1664
|
-
${
|
|
2078
|
+
${n}`}function D4($){return`# contractspec:init:gitignore:start
|
|
1665
2079
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1666
|
-
${
|
|
2080
|
+
${Bj($).join(`
|
|
1667
2081
|
`)}
|
|
1668
2082
|
# contractspec:init:gitignore:end
|
|
1669
|
-
`}function
|
|
1670
|
-
`).trimEnd()}function L4($){return[...new Set($.map((W)=>W.trim()).filter(Boolean))]}async function rX($,W={}){let j=d(W),A=W.scope==="package"?j.packageRoot:j.workspaceRoot,Q=$.join(A,".contractsrc.json"),Z={connect:{...cX.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}=lX(W.candidate),Z=await bj($,{...W,paths:Q}),X=b0(W.taskId,W.actor),Y=oX(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:iX(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 lX($){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 oX($,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 iX($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function pX($,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 tX($,W={}){let j=d(W);return a(j),zj($.fs,A$(j))}import{buildChannelPlanTrace as aX,compileChannelPlan as sX,finalizeChannelPlan as eX,replayExecutionTrace as $2,resolveChannelExecutionActor as W2}from"@contractspec/integration.runtime/channel";import{createHash as j2}from"crypto";var L0="connect.local",A2="connect.runtime-link.v1",Q2="connect.adapter.v1",Z2="connect-control-plane-bridge";function X2($){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:H2(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:V2(B),traceId:q.traceId});if(H.duplicate)return Y2($.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=W2(q,{actorId:Z.actor.id,actorType:Z.actor.type,capabilityGrants:q2(Q.verdict),capabilitySource:"connect",sessionId:Z.actor.sessionId}),J=sX({event:q,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),b=eX({plan:J,decision:B2(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:Z2,promptVersion:A2,policyVersion:Q2,toolTrace:aX(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?$2(j):null}}}async function Y2($,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 B2($){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 q2($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function H2($,W){return`${$} [${W.tool}]`}function V2($){return j2("sha256").update($).digest("hex")}function S4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as b2}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 G2}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_${G2()}`,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:J2(X),reviewPacketRef:Y,replay:{traceQuery:SW,policyExplain:IW}}}function J2($){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 w2($,W,j={}){let A=d(W);a(A),A=x$(A,await $.git.currentBranch());let Q=`connect.dec_${b2()}`,Z=(j.now??(()=>new Date))().toISOString(),X=A$(A);await K0($.fs,X);let{contextPack:Y,planPacket:B}=await Uj($,{...W,candidate:K2(W)}),q=_2(W),H=await y$($,{baseline:W.baseline,touchedPaths:q,workspace:A}),V=await z2(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 K2($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function _2($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function z2($,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 HU($){return new T4($)}import{scanSpecSource as C2}from"@contractspec/module.workspace";function F4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function KU($,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=C2(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 D2}from"@contractspec/module.workspace";async function UU($,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=D2(Y,$,B,q,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:q,differences:H}}i();import{openApiForRegistry as T2}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Mj}from"@contractspec/lib.contracts-spec/operations";async function F2($,W){let{fs:j,logger:A}=W,{registryPath:Q,outputPath:Z="./openapi.json"}=$;A.info("Loading registry...",{registryPath:Q});let X=await x2(Q,j);A.info("Generating OpenAPI document...");let Y=T2(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),B=JSON.stringify(Y,null,2)+`
|
|
1671
|
-
`,
|
|
2083
|
+
`}function N4(){return new RegExp(`${wj("# contractspec:init:gitignore:start")}[\\s\\S]*?${wj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function wj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jj($){return $.replace(/\r\n/g,`
|
|
2084
|
+
`).trimEnd()}function Bj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function v4($,b={}){let n=i(b),A=b.scope==="package"?n.packageRoot:n.workspaceRoot,m=$.join(A,".contractsrc.json"),y={connect:{...F4.connect,enabled:!0}},W="created";if(await $.exists(m)){let B=a(await $.readFile(m)),S=b$(B??{},y);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(m,N(S)),W="merged"}else await $.writeFile(m,N(y));let w=X$(i({...b,workspaceRoot:A,packageRoot:A}));await cb($,w);let j=await ZA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ib.connect,Ib.verificationCache],prompts:b.prompts,root:n.workspaceRoot});return{configPath:m,targetRoot:A,action:W,gitignore:j}}import{randomUUID as XA}from"crypto";async function ob($,b){let n=i(b);A$(n),n=o$(n,await $.git.currentBranch());let{commands:A,touchedPaths:m}=g4(b.candidate),y=await fb($,{...b,paths:m}),W=kb(b.taskId,b.actor),w=P4(b.candidate.steps,b.candidate),j=await i$($,{baseline:b.baseline,touchedPaths:m,workspace:n}),B=Pb(n,{commands:A,impactAnalysis:j,touchedPaths:m}),S={id:`connect.plan_${XA()}`,taskId:b.taskId,repoId:n.repoId,branch:n.branch,actor:W,objective:b.candidate.objective,steps:w,impactedContracts:y.impactedContracts,affectedSurfaces:y.affectedSurfaces,requiredChecks:n.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:k4(m.length,A.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:Gm,planCompile:Hm,planVerify:qm,traceId:W.traceId},acpActions:[...m.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:y,planPacket:S}}function g4($){let b=new Set($.touchedPaths??[]),n=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let m of A.paths??[])b.add(m);for(let m of A.commands??[])n.add(m)}return{commands:[...n],touchedPaths:[...b]}}function P4($,b){if(!$||$.length===0)return[{id:`step_${XA()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((n)=>typeof n==="string"?{id:`step_${XA()}`,summary:n}:{id:`step_${XA()}`,summary:n.summary,paths:n.paths,commands:n.commands,contractRefs:n.contractRefs})}function k4($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function r4($,b,n){let A=i(b);A$(A);let m=X$(A),y=await ub($.fs,m,b.decisionId),W={decisionId:y.envelope?.runtimeLink?.decisionId,traceId:y.envelope?.runtimeLink?.traceId},w=n&&(W.decisionId||W.traceId)?await n.getExecutionTrace(W):null,j=n&&w?await n.replayExecutionTrace(W):null;return{decisionId:b.decisionId,historyDir:y.historyDir,contextPack:y.contextPack,planPacket:y.planPacket,patchVerdict:y.patchVerdict,reviewPacket:y.reviewPacket,trace:w??void 0,replay:j??void 0,source:w?"local+control-plane":"local"}}async function f4($,b={}){let n=i(b);return A$(n),Cm($.fs,X$(n))}import{buildChannelPlanTrace as c4,compileChannelPlan as h4,finalizeChannelPlan as d4,replayExecutionTrace as u4,resolveChannelExecutionActor as o4}from"@contractspec/integration.runtime/channel";import{createHash as i4}from"crypto";var ib="connect.local",t4="connect.runtime-link.v1",l4="connect.adapter.v1",p4="connect-control-plane-bridge";function a4($){return{linkDecision:async({connectDecisionId:b,createdAt:n,input:A,patchVerdict:m,planPacket:y,workspace:W})=>{let w=new Date(n),j=JSON.stringify({connectDecisionId:b,objective:y.objective,taskId:y.taskId,tool:A.tool,verdict:m.verdict}),B={workspaceId:W.repoId,providerKey:ib,externalEventId:b,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:w,signatureValid:!0,traceId:m.controlPlane.traceId,thread:{externalThreadId:`connect:${y.taskId}`,externalUserId:y.actor.id},message:{text:b6(y.objective,A)},metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`}),rawPayload:j},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:n6(j),traceId:B.traceId});if(S.duplicate)return e4($.store,W.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:w}),Z=o4(B,{actorId:y.actor.id,actorType:y.actor.type,capabilityGrants:$6(m.verdict),capabilitySource:"connect",sessionId:y.actor.sessionId}),X=h4({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:w}),Y=d4({plan:X,decision:s4(m),approvalTimeoutMs:900000,now:w}),G=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:Y.policy?.verdict??"blocked",riskTier:Y.policy?.riskTier??"blocked",confidence:Y.policy?.confidence??0.5,modelName:p4,promptVersion:t4,policyVersion:l4,toolTrace:c4(Y),actionPlan:Y,requiresApproval:Y.approval.required,approvalStatus:Y.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:Y.approval.required?"pending":"processed",decisionId:G.id,receiptId:S.receiptId,traceId:Y.traceId,workspaceId:W.repoId,providerKey:ib,sessionId:y.actor.sessionId,workflowId:`connect:${y.taskId}`,metadata:Qj({connectDecisionId:b,connectVerdict:m.verdict,tool:A.tool})}),{approvalStatus:G.approvalStatus,decisionId:G.id,planId:Y.id,providerKey:ib,receiptId:S.receiptId,threadId:Q.id,traceId:Y.traceId,workspaceId:W.repoId}},getExecutionTrace:(b)=>Sj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let n=await Sj($.traceService,b);return n?u4(n):null}}}async function e4($,b,n){let m=(await $.listDecisions({externalEventId:n,limit:1,providerKey:ib,workspaceId:b}))[0];return m?{approvalStatus:m.approvalStatus,decisionId:m.id,planId:m.actionPlan.id,providerKey:ib,receiptId:m.receiptId,threadId:m.threadId,traceId:m.actionPlan.traceId,workspaceId:b}:null}async function Sj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function s4($){let b=I$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((n)=>`${n.status}:${n.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function $6($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function b6($,b){return`${$} [${b.tool}]`}function n6($){return i4("sha256").update($).digest("hex")}function Qj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as w6}from"crypto";async function Zj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let n=A6(b);if(!n)return{};let A=await Jb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:n,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:n==="ui"?m6(b):void 0,query:xm(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:A.verdict==="permit"?"pass":A.verdict==="rewrite"?"warn":"fail",detail:A.reason},reason:A.reason,remediation:A.selected!=null?[`Prefer ${A.selected.candidate.source} candidate ${A.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:A,verdict:A.verdict}}function A6($){let b=xm($).toLowerCase();if(/\b(contract|operation|event|spec|presentation|form)\b/.test(b))return"contracts";if(/\b(integration|provider|sdk|adapter|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render)\b/.test(b))return"runtime";if(/\b(component|ui|screen|view|page|tsx|jsx)\b/.test(b))return"ui";if(/\b(module|bundle|example|template)\b/.test(b))return"solutions";if(/\b(logger|schema|testing|observability|identity|utility|shared|lib)\b/.test(b))return"sharedLibs";return null}function xm($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function m6($){let b=xm($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function Xj($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as y6}from"crypto";function Yj($,b,n){let A=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:n?`Generated path: ${n}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||n?"warn":"pass",detail:A}}function Gj($,b){let n=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:n,detail:A}}function Hj($,b,n){return{id:"impact-analysis",status:$?"fail":b||n?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":n?"Impact could not be resolved.":"Impact resolved."}}function qj($,b,n,A,m,y){let W=y.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${y.runtimeLink.decisionId}`:y.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${y.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${y6()}`,sourceDecisionId:b,objective:A.objective,reason:y.reason,summary:{paths:m,impactedContracts:n.impactedContracts,affectedSurfaces:n.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:y.artifactRefs.contextPack},{type:"plan-packet",ref:y.artifactRefs.planPacket},{type:"patch-verdict",ref:y.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:W}],requiredApprovals:[{capability:U$.key,reason:y.reason}],controlPlane:{traceQuery:BA,policyExplain:SA,approvalStatus:y.runtimeLink?.approvalStatus,decisionId:y.runtimeLink?.decisionId,traceId:y.runtimeLink?.traceId??n.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Im($,b,n,A,m,y,W,w,j){let B=I$(W);return{decisionId:$,summary:A.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:m,checks:y,verdict:W,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:j?.approvalStatus,decisionId:j?.decisionId,traceId:j?.traceId??n.actor.traceId},approvalOperationRefs:W==="require_review"?[`${U$.key}@${U$.version}`,`${QA.key}@${QA.version}`]:void 0,remediation:W6(W),reviewPacketRef:w,replay:{traceQuery:BA,policyExplain:SA}}}function W6($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function j6($,b,n={}){let A=i(b);A$(A),A=o$(A,await $.git.currentBranch());let m=`connect.dec_${w6()}`,y=(n.now??(()=>new Date))().toISOString(),W=X$(A);await cb($.fs,W);let{contextPack:w,planPacket:j}=await ob($,{...b,candidate:Q6(b)}),B=Z6(b),S=await i$($,{baseline:b.baseline,touchedPaths:B,workspace:A}),Q=await X6(n,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),Z=Q.some((r)=>r.id.startsWith("smoke:")&&r.status==="fail"),X=Pb(A,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),Y=await Zj($,b),G=[Yj(X.immutablePath,X.protectedPath,X.generatedPath),Gj(X.commandState,X.commandMatch),Hj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...Y.check?[Y.check]:[],...Q],V=B6(X,Y.verdict),O=I$(V),K=Y.reason??X.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?X.requiredApprovals.length>0?X.requiredApprovals:[{capability:U$.key,reason:K}]:[],U={...j,requiredApprovals:J,verificationStatus:O.verificationStatus},H=Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((r)=>({file:r.path,contracts:r.contracts,policies:r.policies,surfaces:r.surfaces})):B.map((r)=>({file:r,contracts:w.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:w.affectedSurfaces})),_=Im(m,b,w,U,q,G,V,void 0),z=n.controlPlane?await n.controlPlane.linkDecision({connectDecisionId:m,createdAt:y,input:b,patchVerdict:_,planPacket:U,workspace:A}):null,L=z?{...j,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...j.controlPlane,decisionId:z.decisionId,traceId:z.traceId??j.controlPlane.traceId}}:U,C=V==="require_review"?qj(A,m,w,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,D=Im(m,b,w,L,q,G,V,C?_$($.fs,A,$.fs.join(W.reviewPacketsDir,`${C.id}.json`)):void 0,z);if(Y.remediation?.length)D.remediation=Y.remediation;if(await zm($.fs,W,{contextPack:w,planPacket:L,patchVerdict:D}),C)await Rm($.fs,W,C);let F=await hb($.fs,W,m,{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C}),E={artifacts:Sb($.fs,A,W,m,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(C)}),connectDecisionId:m,createdAt:y,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await db($.fs,W,m,E),await Lm($.fs,W,Xj({contextPack:w,createdAt:y,envelope:E,reviewPacket:C,verifyInput:b,workspace:A})),{contextPack:w,planPacket:L,patchVerdict:D,reviewPacket:C,historyDir:F}}function B6($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return S6($.verdict,b)}function S6($,b){if(!b)return $;return Oj($)<=Oj(b)?$:b}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Q6($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function Z6($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function X6($,b,n){if(!$.runCommand)return[];let A=[];for(let m of b){let y=await $.runCommand(m,{cwd:n});A.push({id:`smoke:${m}`,status:y.exitCode===0?"pass":"fail",detail:y.exitCode===0?`Passed: ${m}`:`Failed (${y.exitCode}): ${m}`})}return A}HA();var Tm={};f(Tm,{generateWorkflowSpec:()=>hW,generateWorkflowRunnerTemplate:()=>kn,generateWorkflowDevkitWorkflowTemplate:()=>Nn,generateWorkflowDevkitStreamRouteTemplate:()=>gn,generateWorkflowDevkitStartRouteTemplate:()=>Fn,generateWorkflowDevkitGenericTemplate:()=>Pn,generateWorkflowDevkitFollowUpRouteTemplate:()=>vn,generateVisualizationSpec:()=>HW,generateTranslationSpec:()=>YW,generateThemeSpec:()=>cW,generateTestTemplate:()=>DW,generateTestSpec:()=>XW,generateTelemetrySpec:()=>fW,generateProductIntentSpec:()=>OW,generatePresentationSpec:()=>rW,generatePolicySpec:()=>ZW,generateOperationSpec:()=>kW,generateMigrationSpec:()=>PW,generateKnowledgeSpaceSpec:()=>vW,generateJobSpec:()=>GW,generateIntegrationSpec:()=>FW,generateHarnessSuiteSpec:()=>JW,generateHarnessScenarioSpec:()=>VW,generateHandlerTemplate:()=>MW,generateFormSpec:()=>EW,generateFeatureSpec:()=>IW,generateExperimentSpec:()=>xW,generateExampleSpec:()=>In,generateEventSpec:()=>CW,generateDataViewSpec:()=>RW,generateDataViewRendererTemplate:()=>Tn,generateComponentTemplate:()=>TW,generateCapabilitySpec:()=>QW,generateAppBlueprintSpec:()=>LW,generateAgentSpec:()=>qW});HA();class Uj{ai;templates=Tm;constructor($){this.ai=new GA($)}}function yz($){return new Uj($)}import{scanSpecSource as _6}from"@contractspec/module.workspace";function Kj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function Qz($,b,n={}){let{fs:A,logger:m}=b,y=await A.exists($);if(!y&&!n.force)return{specPath:$,specInfo:Kj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let W=Kj($),w;if(y)try{let B=await A.readFile($);W=_6(B,$),w=W.key}catch{}let j=[];if(n.clean&&w)try{let B=await AA(w,{fs:A});for(let S of B)try{await A.remove(S.filePath),j.push(S.filePath),m.info(`Removed artifact: ${S.filePath}`)}catch{m.warn(`Could not remove artifact: ${S.filePath}`)}}catch{m.warn("Could not discover implementations for cleanup")}if(y)await A.remove($),m.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:W,deleted:!0,cleanedFiles:j,errors:[]}}import{computeSemanticDiff as z6}from"@contractspec/module.workspace";async function Yz($,b,n,A={}){let{fs:m,git:y}=n;if(!await m.exists($))throw Error(`Spec file not found: ${$}`);let w=await m.readFile($),j,B;if(A.baseline)j=await y.showFile(A.baseline,$),B=`${A.baseline}:${$}`;else{if(!await m.exists(b))throw Error(`Spec file not found: ${b}`);j=await m.readFile(b),B=b}let S=z6(w,$,j,B,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:B,differences:S}}$$();import{openApiForRegistry as L6}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Dm}from"@contractspec/lib.contracts-spec/operations";async function R6($,b){let{fs:n,logger:A}=b,{registryPath:m,outputPath:y="./openapi.json"}=$;A.info("Loading registry...",{registryPath:m});let W=await C6(m,n);A.info("Generating OpenAPI document...");let w=L6(W,{title:$.title,version:$.version,description:$.description,servers:$.servers}),j=JSON.stringify(w,null,2)+`
|
|
2085
|
+
`,B=n.resolve(y);return await n.mkdir(n.dirname(B)),await n.writeFile(B,j),A.info(`OpenAPI document written to ${B}`),{document:w,outputPath:B,json:j}}async function C6($,b){let A=await import(b.resolve($));if(A instanceof Dm)return A;if(A.registry instanceof Dm)return A.registry;let m=typeof A.createRegistry==="function"?A.createRegistry:typeof A.default==="function"?A.default:void 0;if(m){let y=await m();if(y instanceof Dm)return y}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as x6,parseOpenApi as I6}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Nm,dirname as _j,join as Qb}from"path";function E6($,b,n){if(b.outputDir)return b.outputDir;let{outputDir:A,conventions:m}=n;switch($){case"operation":return Qb(A,m.operations.split("|")[0]??"operations");case"event":return Qb(A,m.events);case"model":return Qb(A,"models");default:return A}}async function zj($,b,n){let{fs:A,logger:m}=n,{source:y,prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;m.info(`Importing from OpenAPI: ${y}`);let X=await I6(y,{fetch:globalThis.fetch,readFile:(J)=>A.readFile(J)});if(X.warnings.length>0)for(let J of X.warnings)m.warn(`Parse warning: ${J}`);m.info(`Parsed ${X.operations.length} operations from ${X.info.title} v${X.info.version}`);let Y=x6(X,$,{prefix:W,tags:w,exclude:j,defaultStability:B,defaultOwners:S,defaultAuth:Q});m.info(`Import result: ${Y.summary.imported} imported, ${Y.summary.skipped} skipped, ${Y.summary.errors} errors`);let G=[],V=[],O=[],K=new Map;for(let J of Y.operationSpecs){let U="operation",H=null;if(J.code.includes("defineEvent("))U="event",H=J.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((J.code.includes("defineSchemaModel(")||J.code.includes("new EnumType(")||J.code.includes("ScalarTypeEnum.")||J.code.includes("new ZodSchemaType(")||J.code.includes("z.enum(")||J.code.includes("new JsonSchemaType(")||J.code.includes("new GraphQLSchemaType("))&&!J.code.includes("defineCommand(")&&!J.code.includes("defineQuery("))U="model";else U="operation",H=J.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let q=E6(U,b,$),_=Qb(q,J.fileName);if(!H&&U==="model"){if(J.code.includes("new ZodSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(J.code.includes("new JsonSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(J.code.includes("new GraphQLSchemaType("))H=J.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!H)H=J.code.match(/export const (\w+)\s*=/)}if(Z)m.info(`[DRY RUN] Would create: ${_}`);else{let z=_j(_);if(!await A.exists(z))await A.mkdir(z);await A.writeFile(_,J.code),m.info(`Created: ${_}`)}if(G.push({path:_,operationId:J.source.sourceId,specName:J.fileName.replace(".ts","")}),H){let z=_j(_),L=K.get(z)||[];L.push({file:Nm(_),name:H[1],type:U}),K.set(z,L)}}if(!Z&&G.length>0)for(let[J,U]of K.entries()){if(U.length===0)continue;let H=U.map((E)=>E.type),q=H.every((E)=>E==="operation"),_=H.every((E)=>E==="event"),z=H.every((E)=>E==="model"),L=`/**
|
|
1672
2086
|
* Auto-generated registry file.
|
|
1673
2087
|
*/
|
|
1674
|
-
`;
|
|
1675
|
-
`}),
|
|
1676
|
-
`;let C=!1;if(
|
|
2088
|
+
`;U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;L+=`import { ${E.name} } from '${r}';
|
|
2089
|
+
`}),L+=`
|
|
2090
|
+
`;let C=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1677
2091
|
|
|
1678
|
-
`,
|
|
1679
|
-
`,
|
|
1680
|
-
`}),C=!0;else if(
|
|
2092
|
+
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
2093
|
+
`,U.forEach((E)=>{L+=`operationRegistry.register(${E.name});
|
|
2094
|
+
`}),C=!0;else if(_)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
1681
2095
|
|
|
1682
|
-
`,
|
|
1683
|
-
`,
|
|
1684
|
-
`}),C=!0;else if(
|
|
2096
|
+
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2097
|
+
`,U.forEach((E)=>{L+=`eventRegistry.register(${E.name});
|
|
2098
|
+
`}),C=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
1685
2099
|
|
|
1686
|
-
`,
|
|
1687
|
-
`,
|
|
1688
|
-
`}),C=!0;if(C){let
|
|
2100
|
+
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2101
|
+
`,U.forEach((E)=>{L+=`modelRegistry.register(${E.name});
|
|
2102
|
+
`}),C=!0;if(C){let E=Qb(J,"registry.ts");await A.writeFile(E,L),m.info(`Created/Updated registry: ${E}`)}let D=`/**
|
|
1689
2103
|
* Auto-generated barrel file.
|
|
1690
2104
|
*/
|
|
1691
2105
|
|
|
1692
|
-
`;if(
|
|
1693
|
-
`}),C)
|
|
1694
|
-
`;let
|
|
1695
|
-
{ key: '${
|
|
2106
|
+
`;if(U.forEach((E)=>{let r=`./${Nm(E.file,".ts")}`;D+=`export * from '${r}';
|
|
2107
|
+
`}),C)D+=`export * from './registry';
|
|
2108
|
+
`;let F=Qb(J,"index.ts");await A.writeFile(F,D),m.info(`Created/Updated index: ${F}`)}for(let J of Y.skipped)V.push({operationId:J.sourceId,reason:J.reason}),m.debug(`Skipped: ${J.sourceId} - ${J.reason}`);for(let J of Y.errors)O.push({operationId:J.sourceId,error:J.error}),m.error(`Error: ${J.sourceId} - ${J.error}`);return{imported:Y.summary.imported,skipped:Y.summary.skipped,errors:Y.summary.errors,files:G,skippedOperations:V,errorMessages:O}}import{importFromOpenApi as M6,parseOpenApi as T6}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as D6,join as N6}from"path";async function Cz($,b,n){let{fs:A,logger:m}=n,{sources:y,sourceName:W,interactive:w,force:j,dryRun:B}=$,{outputDir:S}=b,Q=y??b.openapi?.sources??[];if(W){if(Q=Q.filter((X)=>X.name===W),Q.length===0)throw Error(`Source not found: ${W}`)}if(Q.length===0)return m.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let Z={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let X of Q){m.info(`Syncing with source: ${X.name}`);let Y=X.url??X.file;if(!Y){m.warn(`Source ${X.name} has no url or file configured`);continue}let G=await T6(Y,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});m.info(`Parsed ${G.operations.length} operations from ${X.name}`);let V=M6(G,b,{prefix:X.prefix,tags:X.tags,exclude:X.exclude,defaultStability:X.defaultStability,defaultAuth:X.defaultAuth});for(let O of V.operationSpecs){let K=N6(S,O.fileName);if(!await A.exists(K)){if(!B){let U=D6(K);await A.mkdir(U),await A.writeFile(K,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:K}),m.info(`Added: ${O.source.sourceId}`)}else if(await A.readFile(K)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K});else if(j==="openapi"){if(!B)await A.writeFile(K,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:K}),m.info(`Updated: ${O.source.sourceId}`)}else if(j==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K}),m.info(`Kept: ${O.source.sourceId}`);else if(w)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),m.warn(`Conflict: ${O.source.sourceId}`)}}return m.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as F6}from"@contractspec/lib.contracts-transformers/openapi";async function Ez($,b){let{fs:n,logger:A}=b,{specPath:m,openApiSource:y,ignoreDescriptions:W,ignoreTags:w,ignoreTransport:j}=$;A.info(`Validating specs against OpenAPI: ${y}`);let B=await F6(y,{fetch:globalThis.fetch,readFile:(O)=>n.readFile(O)});A.info(`Parsed ${B.operations.length} operations from ${B.info.title}`);let S=new Map;for(let O of B.operations)S.set(O.operationId,O);let Q=[],Z=0,X=0,Y=await n.stat(m),G=[];if(Y.isDirectory){let O=await n.glob({pattern:"**/*.ts",cwd:m,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});G.push(...O)}else G.push(m);A.info(`Found ${G.length} spec files to validate`);for(let O of G)try{let K=await n.readFile(O),J=K.match(/operationId:\s*['"]([^'"]+)['"]/)||K.match(/name:\s*['"]([^'"]+)['"]/)||K.match(/export\s+const\s+(\w+)Spec\s*=/);if(!J||!J[1]){A.debug(`Could not extract operationId from ${O}`);continue}let U=J[1];Z++;let H;if(H=S.get(U),!H){let z=U.replace(/([A-Z])/g,"_$1").toLowerCase();H=S.get(z)}if(!H){for(let[z,L]of S)if(z.toLowerCase().includes(U.toLowerCase())||U.toLowerCase().includes(z.toLowerCase())){H=L;break}}if(!H){Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${U}`}]}),X++;continue}let q=[];if(H.deprecated&&!K.includes("deprecated"))q.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!j){let z=K.match(/path:\s*['"]([^'"]+)['"]/);if(z&&z[1]!==H.path)q.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${z[1]}", OpenAPI has "${H.path}"`})}if(!j){let z=K.match(/method:\s*['"]([^'"]+)['"]/);if(z?.[1]&&z[1].toLowerCase()!==H.method.toLowerCase())q.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${z[1]}", OpenAPI has "${H.method.toUpperCase()}"`})}let _=q.length===0;if(!_)X++;Q.push({specPath:O,operationId:H.operationId,valid:_,diffs:q})}catch(K){A.error(`Error validating ${O}: ${K}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${K instanceof Error?K.message:String(K)}`}]}),X++}let V=X===0;return A.info(`Validation ${V?"passed":"failed"}: ${Z} specs checked, ${X} with differences`),{valid:V,specsValidated:Z,specsWithDiffs:X,results:Q}}async function rz($,b,n){let{fs:A,logger:m}=$,{source:y,outputDir:W}=b,w=A.resolve(n??process.cwd(),y);if(!await A.exists(w))throw Error(`Source file not found: ${w}`);let B={...await P(A,n),outputDir:W};return m.info(`Extracting contracts from ${w} to ${W}`),zj(B,{source:w,outputDir:W,dryRun:!1},$)}var Rj={};f(Rj,{validateFeatureRefs:()=>P6,getArrayNameForSpecType:()=>Lj,detectFeatureContext:()=>v6,computeAddSpecEdit:()=>g6});function v6($,b){let n=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],A=null;for(let{type:Q,regex:Z,specType:X}of n){let Y;Z.lastIndex=0;while((Y=Z.exec($))!==null)if(!A||Y.index>A.index)A={type:Q,specType:X,index:Y.index}}if(!A)return null;let m=$.slice(A.index)+b,y=A.type;new RegExp(`${y}\\s*:\\s*\\[`).exec(m);let w=$.slice(A.index),j=0,B=!1,S="";for(let Q=0;Q<w.length;Q++){let Z=w[Q],X=Q>0?w[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&X!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")j++;else if(Z==="]"){if(j--,j===0)return null}}if(j>0)return{type:A.type,specType:A.specType};return null}function g6($,b){let n=Lj(b.type),m=new RegExp(`${n}\\s*:\\s*\\[`,"g").exec($);if(m){let y=m.index+m[0].length,W=typeof b.version==="string"?`'${b.version}'`:b.version,w=`
|
|
2109
|
+
{ key: '${b.key}', version: ${W} },`;return{index:y,text:w}}return null}function Lj($){switch($){case"operation":case"command":case"query":return"operations";case"event":return"events";case"presentation":return"presentations";case"experiment":return"experiments";case"workflow":return"workflows";default:return"operations"}}function P6($,b){let n=[],A=(m,y,W)=>{for(let w of m){let j=`${w.key}.v${w.version}`;if(!y.has(j))n.push({key:w.key,version:w.version,type:W,message:`${W} ${w.key}.v${w.version} not found`})}};return A($.operations,b.operations,"Operation"),A($.events,b.events,"Event"),A($.presentations,b.presentations,"Presentation"),A($.experiments,b.experiments,"Experiment"),n}var Ej={};f(Ej,{removeReferenceStrategy:()=>JA,implementSkeletonStrategy:()=>VA,implementAiStrategy:()=>OA,generateFixLinks:()=>k6,FixService:()=>Ij,FIX_STRATEGY_STABILITY:()=>sb,FIX_STRATEGY_LABELS:()=>u6,CiOutputSchema:()=>n7});function k6($,b){let n=[];if(!$.ref||!$.file)return n;if(b.includeCli)n.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let A=$.file.startsWith("/")?$.file:`/${$.file}`,m=$.ref,y=m.line||1,W=m.column||1;n.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${A}:${y}:${W}`})}if(b.includeGithubIssue&&b.repository){let A=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),m=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
1696
2110
|
|
|
1697
2111
|
> ${$.message}
|
|
1698
2112
|
|
|
1699
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
1700
|
-
`)}function
|
|
2113
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);n.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${A}&body=${m}`})}return n}import o6 from"path";function E$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function M$($,b){let n=$.enrichment?.owners?.length?$.enrichment.owners.map((W)=>`'${W}'`).join(", "):"'@team'",A=$.enrichment?.tags?.length?$.enrichment.tags.map((W)=>`'${W}'`).join(", "):"",m=$.description||`TODO: Add description for ${$.key}`,y=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([W,w])=>{if(w!==void 0)y.push(`${W}: ${w}`)});return y.push(`owners: [${n}]`),y.push(`tags: [${A}]`),y.push(`description: '${m}'`),y.join(`,
|
|
2114
|
+
`)}function lb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=M$($,{kind:"'api'"});return`/**
|
|
1701
2115
|
* Capability: ${$.key}
|
|
1702
2116
|
*
|
|
1703
2117
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1708,7 +2122,7 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",labe
|
|
|
1708
2122
|
|
|
1709
2123
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
1710
2124
|
|
|
1711
|
-
export const ${
|
|
2125
|
+
export const ${n} = defineCapability({
|
|
1712
2126
|
meta: {
|
|
1713
2127
|
${A}
|
|
1714
2128
|
},
|
|
@@ -1734,7 +2148,7 @@ export const ${j} = defineCapability({
|
|
|
1734
2148
|
// }
|
|
1735
2149
|
],
|
|
1736
2150
|
});
|
|
1737
|
-
`}function
|
|
2151
|
+
`}function pb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"EventSpec",A=n.replace("Spec","Payload"),m=M$($);return`/**
|
|
1738
2152
|
* Event: ${$.key}
|
|
1739
2153
|
*
|
|
1740
2154
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1758,9 +2172,9 @@ export const ${A} = new SchemaModel({
|
|
|
1758
2172
|
},
|
|
1759
2173
|
});
|
|
1760
2174
|
|
|
1761
|
-
export const ${
|
|
2175
|
+
export const ${n} = defineEvent({
|
|
1762
2176
|
meta: {
|
|
1763
|
-
${
|
|
2177
|
+
${m}
|
|
1764
2178
|
},
|
|
1765
2179
|
|
|
1766
2180
|
payload: ${A},
|
|
@@ -1774,7 +2188,7 @@ export const ${j} = defineEvent({
|
|
|
1774
2188
|
// policy: 'archive',
|
|
1775
2189
|
// },
|
|
1776
2190
|
});
|
|
1777
|
-
`}function
|
|
2191
|
+
`}function r6($){let b=$.toLowerCase(),n=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let A of n)if(b.includes(A))return"query";return"command"}function ab($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"Spec",A=n.replace("Spec","Input"),m=n.replace("Spec","Output"),y=r6($.key),W=y==="query"?"defineQuery":"defineCommand",w=$.enrichment?.goal||"TODO: Define the business goal",j=$.enrichment?.context||"TODO: Provide context",B=M$($,{goal:`'${w}'`,context:`'${j}'`});return`/**
|
|
1778
2192
|
* Operation: ${$.key}
|
|
1779
2193
|
*
|
|
1780
2194
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1783,7 +2197,7 @@ export const ${j} = defineEvent({
|
|
|
1783
2197
|
* Referenced by feature: ${$.featureKey||"unknown"}
|
|
1784
2198
|
*/
|
|
1785
2199
|
|
|
1786
|
-
import { ${
|
|
2200
|
+
import { ${W} } from '@contractspec/lib.contracts-spec';
|
|
1787
2201
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1788
2202
|
|
|
1789
2203
|
// TODO: Define input schema
|
|
@@ -1797,8 +2211,8 @@ export const ${A} = new SchemaModel({
|
|
|
1797
2211
|
});
|
|
1798
2212
|
|
|
1799
2213
|
// TODO: Define output schema
|
|
1800
|
-
export const ${
|
|
1801
|
-
name: '${
|
|
2214
|
+
export const ${m} = new SchemaModel({
|
|
2215
|
+
name: '${m}',
|
|
1802
2216
|
description: 'Output for ${$.key}',
|
|
1803
2217
|
fields: {
|
|
1804
2218
|
// Add your output fields here
|
|
@@ -1806,14 +2220,14 @@ export const ${Q} = new SchemaModel({
|
|
|
1806
2220
|
},
|
|
1807
2221
|
});
|
|
1808
2222
|
|
|
1809
|
-
export const ${
|
|
2223
|
+
export const ${n} = ${W}({
|
|
1810
2224
|
meta: {
|
|
1811
|
-
${
|
|
2225
|
+
${B}
|
|
1812
2226
|
},
|
|
1813
2227
|
|
|
1814
2228
|
io: {
|
|
1815
2229
|
input: ${A},
|
|
1816
|
-
output: ${
|
|
2230
|
+
output: ${m},
|
|
1817
2231
|
errors: {
|
|
1818
2232
|
// TODO: Define possible errors
|
|
1819
2233
|
// EXAMPLE_ERROR: {
|
|
@@ -1835,7 +2249,7 @@ export const ${j} = ${X}({
|
|
|
1835
2249
|
},
|
|
1836
2250
|
|
|
1837
2251
|
transport: {
|
|
1838
|
-
rest: { method: '${
|
|
2252
|
+
rest: { method: '${y==="command"?"POST":"GET"}' },
|
|
1839
2253
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
1840
2254
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
1841
2255
|
},
|
|
@@ -1852,7 +2266,7 @@ export const ${j} = ${X}({
|
|
|
1852
2266
|
examples: [],
|
|
1853
2267
|
},
|
|
1854
2268
|
});
|
|
1855
|
-
`}function
|
|
2269
|
+
`}function f6($){let b=$.toLowerCase();if(b.includes("doc")||b.includes("guide")||b.includes("readme"))return"markdown";if(b.includes("data")||b.includes("api")||b.includes("export"))return"data";return"web_component"}function eb($){let b=$.key.split(".").pop()||"Unknown",n=E$(b)+"PresentationSpec",A=f6($.key),m=M$($);return`/**
|
|
1856
2270
|
* Presentation: ${$.key}
|
|
1857
2271
|
*
|
|
1858
2272
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1863,9 +2277,9 @@ export const ${j} = ${X}({
|
|
|
1863
2277
|
|
|
1864
2278
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
1865
2279
|
|
|
1866
|
-
export const ${
|
|
2280
|
+
export const ${n} = definePresentation({
|
|
1867
2281
|
meta: {
|
|
1868
|
-
${
|
|
2282
|
+
${m}
|
|
1869
2283
|
},
|
|
1870
2284
|
|
|
1871
2285
|
kind: '${A}',
|
|
@@ -1892,7 +2306,7 @@ export const ${j} = definePresentation({
|
|
|
1892
2306
|
// focusable: true,
|
|
1893
2307
|
// },
|
|
1894
2308
|
});
|
|
1895
|
-
`}import X$ from"path";function TW($,W){if(W.outputDir)return Nj(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=o2($.featureFile);if(j)return Nj(j,$.ref.key,$.specType)}return Nj(X$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function o2($){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=i2(j),Z=p2(j);return X$.join($,Z,`${A}${Q}`)}function i2($){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 p2($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var t2={"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 s2(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=WY(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=a2.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 s2($,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=e2(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=$Y($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function e2($){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 $Y($,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 WY($){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 jY from"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=AY(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=jY.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 AY($){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=QY(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 QY($,W,j){if(!ZY(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=XY(Y),Y}function ZY($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function k4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XY($){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 YY=o$.union([o$.array(o$.unknown()),o$.object({issues:o$.array(o$.unknown())}).transform(($)=>$.issues)]);import{exec as BY}from"child_process";import{promisify as qY}from"util";var HY=qY(BY),f4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function cL($,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 HY(`${Q} ${B}`,{cwd:A})}catch(q){}}}import _$ from"path";async function iL($,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 VY}from"child_process";import{promisify as GY}from"util";var JY=GY(VY);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 JY(G,{cwd:X,timeout:300000});q.push({command:G,success:!0,exitCode:0,stdout:J,stderr:b}),A.info(`\u2713 ${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(`\u2717 ${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?`\u2713 All ${B.length} command(s) passed`:`\u2717 ${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 bY,extractFromProject as wY}from"@contractspec/lib.source-extractors";import{generateOperations as KY,generateRegistry as _Y,generateSchemas as zY}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as UY}from"@contractspec/lib.source-extractors/extractors";import{dirname as LY,join as Rj}from"path";async function OY($,W,j,A){let{fs:Q,logger:Z}=j,X=A??process.cwd();UY(),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 bY(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:SY(),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 wY(B,H);if(!V.success||!V.ir)return{success:!1,report:IY(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:MY(G)};let J=W.outputDir??Rj($.outputDir,"generated"),b={outputDir:J,defaultAuth:"user"},w=KY(G,b),L=zY(G,b),z=_Y(w),S=[...w,...L,z];if(!W.dryRun)for(let O of S){let K=Rj(J,O.path),_=LY(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:EY(G,U,W)}}function SY(){return`# Import Report
|
|
2309
|
+
`}import H$ from"path";function qA($,b){if(b.outputDir)return Fm(b.outputDir,$.ref.key,$.specType);if($.featureFile){let n=c6($.featureFile);if(n)return Fm(n,$.ref.key,$.specType)}return Fm(H$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function c6($){let b=H$.dirname($),n=H$.parse($).root,A=0;while(b!==n&&A<50){if(H$.basename(b)==="src")return b;b=H$.dirname(b),A++}b=H$.dirname($),A=0;while(b!==n&&A<50)b=H$.dirname(b),A++;let m=$.lastIndexOf(`${H$.sep}src${H$.sep}`);if(m!==-1)return $.substring(0,m+5);return null}function Fm($,b,n){let A=b.replace(/\./g,"-").toLowerCase(),m=h6(n),y=d6(n);return H$.join($,y,`${A}${m}`)}function h6($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function d6($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var u6={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},sb={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function OA($,b,n){let{fs:A,logger:m}=n,{ref:y,specType:W,featureKey:w}=$;try{let j={key:y.key,version:y.version,specType:W,stability:sb["implement-ai"],featureKey:w},B=j;if(b.aiConfig)try{B=await i6(j,b,m)}catch(X){m.warn("AI enrichment failed, falling back to skeleton",{error:X instanceof Error?X.message:String(X)})}else m.info("No AI config provided, using skeleton with experimental stability");let S=p6(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let Q=qA($,b),Z=[];if(!b.dryRun){let X=o6.dirname(Q);await A.mkdir(X),await A.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(j){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}async function i6($,b,n){if(n.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:m}=await Promise.resolve().then(() => (HA(),Jj)),y=t6(b),W=new m(y),w=$.specType==="operation"?"command":$.specType,j=`${Cj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await W.generateOperationSpec(j,w);return{...$,description:B.description,enrichment:{goal:B.goal,context:B.context,owners:B.owners,tags:B.tags}}}if($.specType==="event"){let B=await W.generateEventSpec(j);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(m){n.warn("AIGenerator call failed, falling back to heuristics",{error:m instanceof Error?m.message:String(m)})}let A=l6($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function t6($){let b=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[b?.provider??"openai"]??"openai",aiModel:b?.model??"gpt-4-turbo",customApiKey:b?.apiKey??"",customEndpoint:b?.endpoint??""}}function l6($,b){let n=$.split("."),A=n[0]||"unknown",m=n.slice(1).join(" ").replace(/_/g," "),y=[A],W=m.toLowerCase().split(" "),j=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>W.some((S)=>S.includes(B)));return{description:`${Cj(b)} for ${A} ${m}`,goal:`Enable ${m} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...y,...j]}}function p6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}function Cj($){return $.charAt(0).toUpperCase()+$.slice(1)}import a6 from"path";async function VA($,b,n){let{fs:A}=n,{ref:m,specType:y,featureKey:W}=$;try{let w={key:m.key,version:m.version,specType:y,stability:sb["implement-skeleton"],description:`Skeleton spec for ${m.key}`,featureKey:W},j=e6(w);if(!j)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${y}`};let B=qA($,b),S=[];if(!b.dryRun){let Q=a6.dirname(B);await A.mkdir(Q),await A.writeFile(B,j),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function e6($){switch($.specType){case"operation":return ab($);case"event":return pb($);case"presentation":return eb($);case"capability":return lb($);default:return}}async function JA($,b,n){let{fs:A}=n,{ref:m,featureFile:y,specType:W}=$;try{let w=await A.readFile(y),j=w,B=s6(w,m,W);if(B===w)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${m.key}.v${m.version} in ${y}`};let S=[];if(!b.dryRun)await A.writeFile(y,B),S.push({path:y,action:"modified",previousContent:j});else S.push({path:y,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(w){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:w instanceof Error?w.message:String(w)}}}function s6($,b,n){if(!$7(n))return $;let m=xj(b.key),y=xj(b.version),W=[new RegExp(`\\{\\s*key:\\s*['"]${m}['"],\\s*version:\\s*['"]${y}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${y}['"],\\s*key:\\s*['"]${m}['"]\\s*\\},?\\s*`,"g")],w=$;for(let j of W)w=w.replace(j,"");return w=b7(w),w}function $7($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b7($){return $.replace(/,(\s*)\]/g,"$1]")}class Ij{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,n)=>JA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,n)=>VA(b,n,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,n)=>OA(b,n,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let n=this.strategies.get(b.strategy);if(!n)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),n.fix($,b)}async batchFix($){let b=[],n=0,A=0;for(let m of $.issues)try{let y=await this.fixIssue(m,$.options);if(b.push(y),y.success)n++;else A++}catch(y){A++,b.push({success:!1,strategy:$.options.strategy,issue:m,filesChanged:[],error:y instanceof Error?y.message:String(y)})}return{total:$.issues.length,succeeded:n,failed:A,results:b}}async scanAndGetFixables($={}){return(await mA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((n)=>this.getToFix(n)).filter((n)=>n!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let n=this.parseFixableIssue($);if(!n)return null;return{...n,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:n,preferAi:A,select:m}=b;if(n)return Promise.resolve(n);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof m==="function")return m($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as Zb}from"zod";var n7=Zb.union([Zb.array(Zb.unknown()),Zb.object({issues:Zb.array(Zb.unknown())}).transform(($)=>$.issues)]);import{exec as A7}from"child_process";import{promisify as m7}from"util";var y7=m7(A7),Mj={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function kL($,b,n={}){if($.length===0)return;let A=n.cwd??process.cwd(),m=Mj[n.type??"biome"]??Mj.biome,y=50;for(let W=0;W<$.length;W+=y){let j=$.slice(W,W+y).map((B)=>`"${B}"`).join(" ");try{await y7(`${m} ${j}`,{cwd:A})}catch(B){}}}import T$ from"path";async function hL($,b){let n=T$.join(b,"contracts"),A=T$.join(b,"generated"),m=T$.join(A,"docs"),y=await $.fs.exists(n),W=await $.fs.exists(A);if(!y)return{hasContracts:!1,hasGenerated:W,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let w=await j$($,{pattern:"contracts/**/*.ts"}),j=[];if(W)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts"),G=T$.join(m,`${Y}.md`);if(!await $.fs.exists(G))j.push(Y)}else if(w.length>0)for(let X of w){let Y=X.key||T$.basename(X.filePath,".ts");j.push(Y)}let B=T$.join(n,"index.ts"),S=T$.join(n,"registry.ts"),Q=w.length>0&&!await $.fs.exists(B),Z=w.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:W,missingDocs:j,missingIndex:Q,missingRegistry:Z,totalSpecs:w.length}}var Fj={};f(Fj,{runHook:()=>Tj,getAvailableHooks:()=>Dj});import{exec as W7}from"child_process";import{promisify as w7}from"util";var j7=w7(W7);async function Tj($,b){let{fs:n,logger:A}=$,{hookName:m,dryRun:y=!1}=b,W=I(b.workspaceRoot);A.info(`Running hook: ${m}`,{workspaceRoot:W,dryRun:y});let w=await Nj(n,W);if(!w)return{hookName:m,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let j=w[m];if(!j||j.length===0)return{hookName:m,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${m}`};A.info(`Found ${j.length} command(s) for ${m}`);let B=[],S=!0;for(let Z of j){if(y){A.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${Z}`);try{let{stdout:X,stderr:Y}=await j7(Z,{cwd:W,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:X,stderr:Y}),A.info(`\u2713 ${Z}`)}catch(X){S=!1;let Y=X;B.push({command:Z,success:!1,exitCode:Y.code??1,stdout:Y.stdout??"",stderr:Y.stderr??Y.message??String(X)}),A.error(`\u2717 ${Z}`,{exitCode:Y.code,stderr:Y.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:m,success:S,commandResults:B,totalCommands:j.length,successfulCommands:Q,summary:S?`\u2713 All ${j.length} command(s) passed`:`\u2717 ${Q}/${j.length} command(s) passed`}}async function Dj($,b){let n=await Nj($.fs,b);return n?Object.keys(n):[]}async function Nj($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return null;try{let A=await $.readFile(n);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as B7,extractFromProject as S7}from"@contractspec/lib.source-extractors";import{generateOperations as Q7,generateRegistry as Z7,generateSchemas as X7}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as Y7}from"@contractspec/lib.source-extractors/extractors";import{dirname as G7,join as vm}from"path";async function H7($,b,n,A){let{fs:m,logger:y}=n,W=A??process.cwd();Y7(),y.info(`Scanning source code in ${W}...`);let w={readFile:(U)=>m.readFile(U),glob:(U,H)=>m.glob({pattern:U,cwd:H?.cwd}),exists:(U)=>m.exists(U)},j=await B7(W,{readFile:(U)=>m.readFile(U),glob:(U)=>m.glob({pattern:U})});if(j.frameworks.length===0)return y.warn("No supported frameworks detected"),{success:!1,report:q7(),errors:["No supported frameworks detected in project"]};y.info(`Detected frameworks: ${j.frameworks.map((U)=>U.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let U of B.getAll())if("setFs"in U&&typeof U.setFs==="function")U.setFs(w);let S={scope:b.scope,framework:b.framework},Q=await S7(j,S);if(!Q.success||!Q.ir)return{success:!1,report:O7(Q.errors??[]),errors:Q.errors?.map((U)=>U.message)};let Z=Q.ir;if(y.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:V7(Z)};let X=b.outputDir??vm($.outputDir,"generated"),Y={outputDir:X,defaultAuth:"user"},G=Q7(Z,Y),V=X7(Z,Y),O=Z7(G),K=[...G,...V,O];if(!b.dryRun)for(let U of K){let H=vm(X,U.path),q=G7(H);if(!await m.exists(q))await m.mkdir(q);await m.writeFile(H,U.content),y.info(`Created: ${H}`)}else for(let U of K)y.info(`[DRY RUN] Would create: ${vm(X,U.path)}`);let J={files:K,operationsGenerated:G.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:J7(Z,J,b)}}function q7(){return`# Import Report
|
|
1896
2310
|
|
|
1897
2311
|
## \u274C No Supported Frameworks Detected
|
|
1898
2312
|
|
|
@@ -1909,13 +2323,13 @@ No supported frameworks were detected in the project.
|
|
|
1909
2323
|
- Next.js API Routes
|
|
1910
2324
|
|
|
1911
2325
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
1912
|
-
`}function
|
|
2326
|
+
`}function O7($){return`# Import Report
|
|
1913
2327
|
|
|
1914
2328
|
## \u274C Extraction Failed
|
|
1915
2329
|
|
|
1916
|
-
${$.map((
|
|
2330
|
+
${$.map((b)=>`- ${b.message}`).join(`
|
|
1917
2331
|
`)}
|
|
1918
|
-
`}function
|
|
2332
|
+
`}function V7($){return`# Import Analysis Report
|
|
1919
2333
|
|
|
1920
2334
|
## Summary
|
|
1921
2335
|
|
|
@@ -1935,19 +2349,19 @@ ${$.map((W)=>`- ${W.message}`).join(`
|
|
|
1935
2349
|
|
|
1936
2350
|
## Detected Frameworks
|
|
1937
2351
|
|
|
1938
|
-
${$.project.frameworks.map((
|
|
2352
|
+
${$.project.frameworks.map((b)=>`- ${b.name} (${b.confidence})`).join(`
|
|
1939
2353
|
`)}
|
|
1940
2354
|
|
|
1941
2355
|
## Endpoints
|
|
1942
2356
|
|
|
1943
|
-
${$.endpoints.map((
|
|
2357
|
+
${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).join(`
|
|
1944
2358
|
`)}
|
|
1945
2359
|
|
|
1946
2360
|
## Ambiguities (Require Review)
|
|
1947
2361
|
|
|
1948
|
-
${$.ambiguities.length>0?$.ambiguities.map((
|
|
2362
|
+
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
1949
2363
|
`):"None"}
|
|
1950
|
-
`}function
|
|
2364
|
+
`}function J7($,b,n){return`# Import Report${n.dryRun?" (Dry Run)":""}
|
|
1951
2365
|
|
|
1952
2366
|
## \u2705 Import Successful
|
|
1953
2367
|
|
|
@@ -1959,9 +2373,9 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1959
2373
|
|
|
1960
2374
|
### Generation Summary
|
|
1961
2375
|
|
|
1962
|
-
- **Operations Generated**: ${
|
|
1963
|
-
- **Schemas Generated**: ${
|
|
1964
|
-
- **Total Files**: ${
|
|
2376
|
+
- **Operations Generated**: ${b.operationsGenerated}
|
|
2377
|
+
- **Schemas Generated**: ${b.schemasGenerated}
|
|
2378
|
+
- **Total Files**: ${b.files.length}
|
|
1965
2379
|
|
|
1966
2380
|
### Confidence Breakdown
|
|
1967
2381
|
|
|
@@ -1973,41 +2387,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1973
2387
|
|
|
1974
2388
|
### Next Steps
|
|
1975
2389
|
|
|
1976
|
-
1. Review generated contracts in \`${
|
|
2390
|
+
1. Review generated contracts in \`${n.outputDir??"generated/"}\`
|
|
1977
2391
|
2. Fill in TODO placeholders with business context
|
|
1978
2392
|
3. Run \`contractspec validate\` to verify contracts
|
|
1979
2393
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
1980
|
-
`}function
|
|
1981
|
-
`)}function
|
|
1982
|
-
`)}async function
|
|
1983
|
-
`)}function
|
|
1984
|
-
`)}function
|
|
1985
|
-
`)}function
|
|
1986
|
-
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let
|
|
1987
|
-
`)}function
|
|
1988
|
-
`)}async function
|
|
2394
|
+
`}function U7($,b,n={}){let A=[];if(A.push("# Import Report"),A.push(""),A.push(`**Generated**: ${new Date().toISOString()}`),A.push(""),A.push("## Summary"),A.push(""),A.push("| Metric | Count |"),A.push("|--------|-------|"),A.push(`| Files Scanned | ${$.stats.filesScanned} |`),A.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),A.push(`| Schemas Found | ${$.stats.schemasFound} |`),A.push(`| Errors Found | ${$.stats.errorsFound} |`),A.push(`| Events Found | ${$.stats.eventsFound} |`),A.push(""),n.includeStats!==!1)A.push("### Confidence"),A.push(""),A.push("| Level | Count |"),A.push("|-------|-------|"),A.push(`| High | ${$.stats.highConfidence} |`),A.push(`| Medium | ${$.stats.mediumConfidence} |`),A.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),A.push("");A.push("### Frameworks Detected"),A.push("");for(let m of $.project.frameworks)A.push(`- **${m.name}** (${m.confidence})`);if(A.push(""),n.includeEndpoints!==!1&&$.endpoints.length>0){A.push("## Endpoints"),A.push(""),A.push("| Method | Path | Kind | Confidence |"),A.push("|--------|------|------|------------|");for(let m of $.endpoints)A.push(`| ${m.method} | \`${m.path}\` | ${m.kind} | ${m.confidence.level} |`);A.push("")}if(n.includeSchemas!==!1&&$.schemas.length>0){A.push("## Schemas"),A.push(""),A.push("| Name | Type | Confidence |"),A.push("|------|------|------------|");for(let m of $.schemas)A.push(`| ${m.name} | ${m.schemaType} | ${m.confidence.level} |`);A.push("")}if(b&&n.includeIssues!==!1){A.push("## Verification"),A.push(""),A.push("| Status | Count |"),A.push("|--------|-------|"),A.push(`| Valid | ${b.summary.validEndpoints} |`),A.push(`| Warnings | ${b.summary.warningEndpoints} |`),A.push(`| Errors | ${b.summary.errorEndpoints} |`),A.push("");let m=b.endpointResults.filter((y)=>y.issues.length>0);if(m.length>0){A.push("### Issues"),A.push("");for(let y of m){A.push(`#### ${y.endpoint.method} ${y.endpoint.path}`);for(let W of y.issues){let w=W.severity==="error"?"\u274C":W.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(A.push(`- ${w} **${W.code}**: ${W.message}`),W.suggestion)A.push(` - *Suggestion*: ${W.suggestion}`)}A.push("")}}}if(n.includeAmbiguities!==!1&&$.ambiguities.length>0){A.push("## Ambiguities (Require Review)"),A.push("");for(let m of $.ambiguities)if(A.push(`- **${m.type}** (${m.itemId}): ${m.description}`),m.suggestion)A.push(` - *Suggestion*: ${m.suggestion}`);A.push("")}return A.push("## Next Steps"),A.push(""),A.push("1. Review generated contracts in the output directory"),A.push("2. Fill in TODO placeholders with business context"),A.push("3. Run `contractspec validate` to verify contracts"),A.push("4. Move stable contracts from `generated/` to `curated/`"),A.push(""),A.join(`
|
|
2395
|
+
`)}function K7($,b){let n=[];n.push(""),n.push("\uD83D\uDCCA Summary"),n.push(` Files scanned: ${$.stats.filesScanned}`),n.push(` Endpoints: ${$.stats.endpointsFound}`),n.push(` Schemas: ${$.stats.schemasFound}`),n.push(""),n.push("\uD83D\uDCC8 Confidence"),n.push(` High: ${$.stats.highConfidence}`),n.push(` Medium: ${$.stats.mediumConfidence}`),n.push(` Low: ${$.stats.lowConfidence}`),n.push(""),n.push("\uD83D\uDD27 Frameworks");for(let A of $.project.frameworks)n.push(` \u2022 ${A.name}`);if(n.push(""),b)n.push("\u2705 Verification"),n.push(` Valid: ${b.summary.validEndpoints}`),n.push(` Warnings: ${b.summary.warningEndpoints}`),n.push(` Errors: ${b.summary.errorEndpoints}`),n.push("");return n.join(`
|
|
2396
|
+
`)}async function _7($,b,n){let{logger:A}=n,m=[],y=[...$.ambiguities];A.info(`Verifying ${$.endpoints.length} endpoints...`);for(let w of $.endpoints){let j=[];if(w.confidence.level==="low"||w.confidence.level==="ambiguous")j.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${w.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!w.input&&(w.method==="POST"||w.method==="PUT"||w.method==="PATCH"))j.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!w.output)j.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(b.checkDuplicates){if($.endpoints.filter((Q)=>Q.id!==w.id&&Q.path===w.path&&Q.method===w.method).length>0)j.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${w.method} ${w.path} found`,severity:"error"})}if(b.checkConflicts){let S=z7(w,$.endpoints);for(let Q of S)j.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=j.some((S)=>S.severity==="error")?"error":j.some((S)=>S.severity==="warning")?"warning":"valid";m.push({endpoint:w,status:B,issues:j})}if(b.validateSchemas){for(let w of $.schemas)if(!w.fields||w.fields.length===0)y.push({type:"schema",itemId:w.id,description:`Schema ${w.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:w.source})}let W={totalEndpoints:m.length,validEndpoints:m.filter((w)=>w.status==="valid").length,warningEndpoints:m.filter((w)=>w.status==="warning").length,errorEndpoints:m.filter((w)=>w.status==="error").length,totalIssues:m.reduce((w,j)=>w+j.issues.length,0)};return A.info(`Verification complete: ${W.validEndpoints} valid, ${W.warningEndpoints} warnings, ${W.errorEndpoints} errors`),{valid:W.errorEndpoints===0,endpointResults:m,ambiguities:y,summary:W}}function z7($,b){let n=[],A=$.path.split("/").filter(Boolean);for(let m of b){if(m.id===$.id)continue;if(m.method!==$.method)continue;let y=m.path.split("/").filter(Boolean);if(y.length!==A.length)continue;let W=!0;for(let w=0;w<A.length;w++){let j=A[w]??"",B=y[w]??"",S=j.startsWith(":")||j.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&j!==B){W=!1;break}}if(W&&$.path!==m.path)n.push(m)}return n}function ZR($,b="feature-map",n={}){switch(b){case"feature-map":return km($,n);case"orphans":return L7($,n);case"dependencies":return R7($,n);case"full":return C7($,n);default:return km($,n)}}function km($,b){let{direction:n="LR",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=$.features;if(b.featureKeys&&b.featureKeys.length>0)W=W.filter((Z)=>b.featureKeys?.includes(Z.key));let w=0,j=!1;if(W.length>0){y.push(" subgraph features [Features]");for(let Z of W){if(w>=m)break;let X=v(`F_${Z.key}`),Y=Z.title??Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let B=gm(W,"operations",$.inventory);if(B.length>0&&w<m){y.push(" subgraph ops [Operations]");for(let Z of B){if(w>=m)break;let X=v(`O_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let S=gm(W,"events",$.inventory);if(S.length>0&&w<m){y.push(" subgraph events [Events]");for(let Z of S){if(w>=m)break;let X=v(`E_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}let Q=gm(W,"presentations",$.inventory);if(Q.length>0&&w<m){y.push(" subgraph presentations [Presentations]");for(let Z of Q){if(w>=m)break;let X=v(`P_${Z.key}_v${Z.version}`),Y=A?`${Z.key}.v${Z.version}`:Z.key;y.push(` ${X}["${B$(Y)}"]`),w++}y.push(" end")}for(let Z of W){let X=v(`F_${Z.key}`);for(let Y of Z.operations){let G=v(`O_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}for(let Y of Z.events){let G=v(`E_${Y.key}_v${Y.version}`);y.push(` ${X} -.-> ${G}`)}for(let Y of Z.presentations){let G=v(`P_${Y.key}_v${Y.version}`);y.push(` ${X} --> ${G}`)}}if(j)y.push(` note["... and more (truncated at ${m} nodes)"]`);return y.join(`
|
|
2397
|
+
`)}function L7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=new Set,w=new Set,j=new Set;for(let Q of $.features){for(let Z of Q.operations)W.add(`${Z.key}.v${Z.version}`);for(let Z of Q.events)w.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)j.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){y.push(" subgraph features [Features]");for(let Q of $.features){if(B>=m)break;let Z=v(`F_${Q.key}`);y.push(` ${Z}["${B$(Q.title??Q.key)}"]`),B++}y.push(" end")}if($.orphanedSpecs.length>0){y.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=m)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}let S=[];for(let Q of W){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"operation",key:Z,version:X})}for(let Q of w){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"event",key:Z,version:X})}for(let Q of j){let[Z,X]=Pm(Q);if(Z&&X)S.push({type:"presentation",key:Z,version:X})}if(S.length>0&&B<m){y.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=m)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),X=A?`${Q.key}.v${Q.version}`:Q.key;y.push(` ${Z}["${B$(X)}"]`),B++}y.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let X of Q.operations){let Y=v(`operation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}for(let X of Q.events){let Y=v(`event_${X.key}_v${X.version}`);y.push(` ${Z} -.-> ${Y}`)}for(let X of Q.presentations){let Y=v(`presentation_${X.key}_v${X.version}`);y.push(` ${Z} --> ${Y}`)}}return y.join(`
|
|
2398
|
+
`)}function R7($,b){let{direction:n="TB",showVersions:A=!0,maxNodes:m=50}=b,y=[`flowchart ${n}`],W=0;for(let w of $.features){if(W>=m)break;let j=v(`F_${w.key}`);y.push(` ${j}["${B$(w.title??w.key)}"]`),W++;for(let B of w.operations){if(W>=m)break;let S=v(`O_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.events){if(W>=m)break;let S=v(`E_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} -.-> ${S}`),W++}for(let B of w.presentations){if(W>=m)break;let S=v(`P_${B.key}_v${B.version}`),Q=A?`${B.key}.v${B.version}`:B.key;y.push(` ${S}["${B$(Q)}"]`),y.push(` ${j} --> ${S}`),W++}for(let B of w.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);y.push(` ${S} --> ${Q}`)}}return y.join(`
|
|
2399
|
+
`)}function C7($,b){let n=km($,b);if($.orphanedSpecs.length===0)return n;let A=n.split(`
|
|
2400
|
+
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let m of $.orphanedSpecs.slice(0,20)){let y=v(`orphan_${m.type}_${m.key}_v${m.version}`),W=`${m.key}.v${m.version}`;A.push(` ${y}["${B$(W)}"]:::orphan`)}return A.push(" end"),A.push(" classDef orphan stroke-dasharray: 5 5"),A.join(`
|
|
2401
|
+
`)}function gm($,b,n){let A=new Set,m=[];for(let y of $)for(let W of y[b]){let w=`${W.key}.v${W.version}`;if(!A.has(w))A.add(w),m.push(W)}return m}function Pm($){let b=$.match(/^(.+)\.v(\d+)$/);if(!b)return[void 0,void 0];return[b[1],b[2]]}function v($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function B$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as x7,specToMarkdown as D$}from"@contractspec/module.workspace";function YR($,b,n){let A=[];if(n.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))A.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))A.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(n.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))A.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))A.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(b))A.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return A}function GR($,b){let n=[];n.push(`# Verification Report: ${$.meta.key}`),n.push("");let A=b.filter((W)=>W.severity==="error"),m=b.filter((W)=>W.severity==="warning"),y=b.filter((W)=>W.severity==="info");if(n.push("## Summary"),n.push(""),n.push(`- Errors: ${A.length}`),n.push(`- Warnings: ${m.length}`),n.push(`- Info: ${y.length}`),n.push(""),A.length>0){n.push("## Errors"),n.push("");for(let W of A)n.push(`- \u274C **${W.category}**: ${W.message}`);n.push("")}if(m.length>0){n.push("## Warnings"),n.push("");for(let W of m)n.push(`- \u26A0\uFE0F **${W.category}**: ${W.message}`);n.push("")}if(y.length>0){n.push("## Info"),n.push("");for(let W of y)n.push(`- \u2139\uFE0F **${W.category}**: ${W.message}`);n.push("")}return n.join(`
|
|
2402
|
+
`)}async function VR($,b){let n=[];n.push(D$($,"context"));let A=await j$(b),m=async(y)=>{let W=A.find((j)=>j.key===y.name&&j.version===y.version);if(!W)return null;return(await x7(W.filePath)).find((j)=>j.meta.key===y.name)??null};if($.operations?.length){n.push(`
|
|
1989
2403
|
## Operations (${$.operations.length})
|
|
1990
|
-
`);for(let
|
|
2404
|
+
`);for(let y of $.operations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
1991
2405
|
|
|
1992
|
-
*Spec not found*`);
|
|
2406
|
+
*Spec not found*`);n.push("---")}}if($.events?.length){n.push(`
|
|
1993
2407
|
## Events (${$.events.length})
|
|
1994
|
-
`);for(let
|
|
2408
|
+
`);for(let y of $.events){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
1995
2409
|
|
|
1996
|
-
*Spec not found*`);
|
|
2410
|
+
*Spec not found*`);n.push("---")}}if($.presentations?.length){n.push(`
|
|
1997
2411
|
## Presentations (${$.presentations.length})
|
|
1998
|
-
`);for(let
|
|
1999
|
-
|
|
2000
|
-
*Spec not found*`);
|
|
2001
|
-
`)}function
|
|
2002
|
-
`)}function
|
|
2003
|
-
`)}function
|
|
2004
|
-
`)}
|
|
2005
|
-
`).
|
|
2006
|
-
${
|
|
2007
|
-
${
|
|
2008
|
-
${
|
|
2009
|
-
|
|
2010
|
-
`).trimEnd()}function eY(){return new RegExp(`${e4($9)}[\\s\\S]*?${e4(W9)}(?:\\r?\\n)?`)}function e4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{generateArtifactsForAudience as $3,generateBiomePreset as W3}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=$3("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,W3("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 j3={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 PS($,W,j=j3){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 A3($,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 A3($,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 Q3}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as Z3}from"path";async function iS($,W){let{fs:j}=W,A=Z3(process.cwd(),$);if(!await j.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let Q=await Q$(A),Z=X3(Q.exports),X=Q3(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 X3($){let W=Object.values($).filter(Y3);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function Y3($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as B3,dirname as nj,join as R0}from"path";async function sS($,W,j,A,Q){let{fs:Z}=Q,X=A.implementationPath;if(!X){let H=nj($),V=B3($,".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 q3,validateBuilderReadinessReport as H3,validateBuilderWorkspace as V3,validateBuilderWorkspaceSnapshot as G3}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as J3,validateExternalPatchProposal as b3,validateProviderRoutingPolicy as w3,validateRuntimeTarget as K3}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as _3,validateLayoutSlots as z3}from"@contractspec/lib.surface-runtime/spec";async function QI($,W){if(!I3($.specType))return{valid:!0,errors:[],warnings:[]};let j=y3($.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"?U3(Z):$.specType==="builder-spec"?L3(Z):O3(Z);return{valid:Q.length===0&&X.errors.length===0,errors:[...Q,...X.errors],warnings:X.warnings.map((Y)=>`[${$.filePath}] ${Y}`)}}function U3($){let W=[],j=[],A=S3($,M3);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{z3(X)}catch(Y){W.push(`[${Q.exportName}] ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of _3(X).warnings)j.push(`[${Q.exportName}] ${Y}`)}}return{errors:W,warnings:j}}function L3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(E3(Z)){A+=1,W.push(...PW(Q,V3(Z)));continue}if(N3(Z)){A+=1,W.push(...PW(Q,q3(Z)));continue}if(R3(Z)){A+=1,W.push(...PW(Q,H3(Z)));continue}if(C3(Z))A+=1,W.push(...PW(Q,G3(Z)))}if(A===0)j.push(cj("builder-spec","builder"));return{errors:W,warnings:j}}function O3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(D3(Z)){A+=1,W.push(...kW(Q,K3(Z)));continue}if(T3(Z)){A+=1,W.push(...kW(Q,w3(Z)));continue}if(F3(Z)){A+=1,W.push(...kW(Q,J3(Z)));continue}if(x3(Z))A+=1,W.push(...kW(Q,b3(Z)))}if(A===0)j.push(cj("provider-spec","provider"));return{errors:W,warnings:j}}function S3($,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 I3($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function M3($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function E3($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function N3($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function R3($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function C3($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function D3($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function T3($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function F3($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function x3($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function y3($){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 v3}from"@contractspec/module.workspace";function Q9($,W={}){let j=[],A=[],Q;if(!W.skipStructure)Q=v3($),j.push(...Q.errors),A.push(...Q.warnings);return{valid:j.length===0,structureResult:Q,errors:j,warnings:A,code:$.sourceBlock}}async function BI($,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 qI($,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 m3}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as lj}from"fs/promises";import{resolve as hW}from"path";async function wI($,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 P3(Z),Y=await k3(j.connections,Q),B=await h3(j.translationCatalog,Q),q=await g3(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(B)H.translationCatalogs={blueprint:[B],platform:[]};if(q)H.integrationSpecs=q;let V=m3($,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 P3($){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 k3($,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 h3($,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 g3($){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}=f3(Q);if(!Z)continue;let Y=hW(process.cwd(),Z);try{let B=await Q$(Y),q=u3(B.exports,X);if(q)await q(A)}catch(B){console.warn(`Failed to load registrar from ${Y}: ${B}`)}}return A}function f3($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),A=W?.trim()??null,Q=j?.trim();return{modulePath:A,exportName:Q}}function u3($,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 NI($,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 d3}from"ai";var n3=`
|
|
2412
|
+
`);for(let y of $.presentations){let W=await m(y);if(W)n.push(D$(W,"full"));else n.push(`### ${y.name} (v${y.version})
|
|
2413
|
+
|
|
2414
|
+
*Spec not found*`);n.push("---")}}return n.join(`
|
|
2415
|
+
`)}function I7($,b){let n=[];if(n.push(`# Implementation Guide: ${$.meta.key}`),n.push(""),n.push(`**Target Agent**: ${b}`),n.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),n.push(""),$.meta.description)n.push("## Overview"),n.push(""),n.push($.meta.description),n.push("");if($.meta.goal)n.push("## Goal"),n.push(""),n.push($.meta.goal),n.push("");if($.meta.context)n.push("## Context"),n.push(""),n.push($.meta.context),n.push("");if(n.push("## Implementation Steps"),n.push(""),$.specType==="operation"){if(n.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)n.push("2. Implement input validation according to the schema"),n.push("3. Implement the core business logic"),n.push("4. Return output matching the expected schema");if($.hasPolicy)n.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){n.push("6. Emit events on success:");for(let A of $.emittedEvents)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("7. Add error handling for expected failure cases"),n.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(n.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){n.push("2. Implement operations:");for(let A of $.operations)n.push(` - \`${A.name}\` (v${A.version})`)}if($.presentations&&$.presentations.length>0){n.push("3. Implement presentations:");for(let A of $.presentations)n.push(` - \`${A.name}\` (v${A.version})`)}n.push("4. Wire up feature exports"),n.push("5. Add integration tests")}else n.push("1. Review the spec requirements"),n.push("2. Implement the core logic"),n.push("3. Add tests"),n.push("4. Document the implementation");if(n.push(""),n.push("## Constraints"),n.push(""),n.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)n.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)n.push(`- Tags: ${$.meta.tags.join(", ")}`);if(n.push(""),b==="cursor-cli")n.push("## Cursor Notes"),n.push(""),n.push("- Use Composer mode for multi-file changes"),n.push("- Reference this guide in your cursor rules"),n.push("- Break implementation into small, focused commits");else if(b==="claude-code")n.push("## Claude Code Notes"),n.push(""),n.push("- Use extended thinking for complex logic"),n.push("- Ask for clarification on ambiguous requirements"),n.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")n.push("## General Notes"),n.push(""),n.push("- Use inline comments to guide generation"),n.push("- Review generated code carefully");return n.push(""),n.push("## Spec Definition"),n.push(""),n.push(D$($,"full")),n.join(`
|
|
2416
|
+
`)}function E7($){let b=[];if(b.push(`# ${$.meta.key}`),b.push(""),b.push(`Description: ${$.meta.description??"No description"}`),b.push(""),b.push("## Rules"),b.push(""),$.specType==="operation"){if(b.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)b.push("- Validate input and output against schemas");if($.hasPolicy)b.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)b.push("- Emit documented events")}else if($.specType==="feature")b.push("- Implement all operations and presentations"),b.push("- Follow modular architecture");else b.push(`- Follow ${$.specType} patterns`);return b.push("- Follow project code quality standards"),b.push("- Write tests for new functionality"),b.join(`
|
|
2417
|
+
`)}function JR($,b,n="generic-mcp"){switch(b){case"guide":return I7($,n);case"rules":return E7($);case"prompt":return D$($,"prompt");case"context":return D$($,"context");case"full":default:return D$($,"full")}}import{readFile as M7}from"fs/promises";import{createRequire as T7}from"module";import{dirname as D7,resolve as gj}from"path";import{pathToFileURL as N7}from"url";import vj from"vm";import rm from"typescript";async function y$($,b={}){let n=gj(process.cwd(),$),A=b.runtime??g7();try{let m=A==="bun"?await F7(n):await v7(n);return{modulePath:n,exports:m}}catch(m){throw Error(kj(n,m))}}async function IR($,b){let n=gj(process.cwd(),$);if(!await b.exists(n))return null;return y$(n)}async function UA($,b={}){return(await y$($,b)).exports}async function Pj($,b){let n=await UA($);return rj(n,$,b)}function kj($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function rj($,b,n){if(n.isValue($))return $;for(let A of n.instanceKeys??[])if(n.isValue($[A]))return $[A];for(let A of n.factoryKeys??[]){let m=$[A];if(typeof m!=="function")continue;let y=await m();if(n.isValue(y))return y}throw Error(`${n.description} module ${b} must export a supported instance or factory.`)}async function F7($){return await import(N7($).href)}async function v7($){return await P7($)??{}}function g7(){return typeof globalThis.Bun<"u"?"bun":"node"}var ER={formatModuleLoadError:kj,resolveAuthoredModuleValue:rj};async function P7($){let b=await M7($,"utf-8"),n=rm.transpileModule(b,{compilerOptions:{module:rm.ModuleKind.CommonJS,target:rm.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),A={},m={exports:A},y=T7($),W=vj.createContext({module:m,exports:A,require:y,__dirname:D7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new vj.Script(n.outputText,{filename:$}).runInContext(W),m.exports}var oj={};f(oj,{renderOnboardingGuides:()=>hm,listOnboardingTracks:()=>KA,getOnboardingTrack:()=>cm,createOnboardingConnectArtifacts:()=>l7,buildOnboardingPlan:()=>t7,ONBOARDING_TRACKS:()=>fm});var fm=[{id:"contracts",title:"Contracts",summary:"Author and validate spec-first contracts before implementation.",description:"Use ContractSpec contracts as the durable source of truth for operations, events, presentations, and validation.",reuseFamily:"contracts",adoptionQuery:"contract operation event policy presentation spec-first contracts",primaryDocsRoute:"/docs/getting-started/start-here",secondaryDocsRoutes:["/docs/guides/spec-validation-and-typing","/docs/guides/generate-docs-clients-schemas"],packages:["@contractspec/lib.contracts-spec","@contractspec/lib.schema"],recommendedCommands:["contractspec create --type operation","contractspec generate","contractspec validate","contractspec ci"],starterExample:{key:"minimal",packageRef:"@contractspec/example.minimal",title:"Minimal",summary:"Smallest reference implementation for baseline ContractSpec usage."},connectSurfaces:["cli","contract","runtime"]},{id:"ui-design",title:"UI Design",summary:"Adopt the design system and contract-backed theming flow.",description:"Use ThemeSpec, the design system, and composed UI surfaces instead of ad-hoc theme files or raw primitives.",reuseFamily:"ui",adoptionQuery:"ui design system theme tokens composed controls themes",adoptionPlatform:"web",primaryDocsRoute:"/docs/tech/contracts/themes",secondaryDocsRoutes:["/docs/guides/first-module-bundle","/docs/getting-started/installation"],packages:["@contractspec/lib.design-system","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec create --type theme","contractspec generate","contractspec validate"],starterExample:{key:"data-grid-showcase",packageRef:"@contractspec/example.data-grid-showcase",title:"Data Grid Showcase",summary:"Reference app for composed design-system tables and contract-backed UI rendering."},connectSurfaces:["cli","runtime","ui"]},{id:"knowledge",title:"Knowledge",summary:"Model trusted knowledge spaces, sources, and retrieval flows.",description:"Use knowledge spaces, bindings, and governed retrieval instead of prompt-only context injection.",reuseFamily:"sharedLibs",adoptionQuery:"knowledge spaces sources bindings retrieval canon ingestion assistant",primaryDocsRoute:"/docs/knowledge",secondaryDocsRoutes:["/docs/knowledge/spaces","/docs/knowledge/examples"],packages:["@contractspec/lib.knowledge","@contractspec/lib.ai-agent"],recommendedCommands:["contractspec create --type knowledge","contractspec validate","contractspec connect adoption resolve --family sharedLibs --stdin"],starterExample:{key:"knowledge-canon",packageRef:"@contractspec/example.knowledge-canon",title:"Knowledge Canon",summary:"Minimal contract-first knowledge space example with bindings and source samples."},advancedExample:{key:"policy-safe-knowledge-assistant",packageRef:"@contractspec/example.policy-safe-knowledge-assistant",title:"Policy-Safe Knowledge Assistant",summary:"End-to-end governed knowledge assistant with policy, locale, and learning flows."},connectSurfaces:["cli","knowledge","mcp","runtime"]},{id:"ai-agents",title:"AI Agents",summary:"Define agents, tools, approvals, and MCP-aware execution.",description:"Use the ContractSpec agent runtime and agent specs instead of ad-hoc prompt wrappers.",reuseFamily:"sharedLibs",adoptionQuery:"ai agent tools approvals mcp orchestration unified agent runtime",primaryDocsRoute:"/docs/libraries/ai-agent",secondaryDocsRoutes:["/docs/advanced/mcp","/docs/getting-started/cli"],packages:["@contractspec/lib.ai-agent","@contractspec/lib.contracts-spec"],recommendedCommands:["contractspec create --type agent","contractspec agent export --spec <path> --format opencode","contractspec validate"],starterExample:{key:"agent-console",packageRef:"@contractspec/example.agent-console",title:"Agent Console",summary:"Reference autonomous-agent workspace with runs, tools, metrics, and replay."},connectSurfaces:["agent","cli","mcp","runtime"]},{id:"learning-journey",title:"Learning Journey",summary:"Guide users through milestones, progression, and adaptive journeys.",description:"Use the learning-journey module and example family for structured onboarding and progression flows.",reuseFamily:"solutions",adoptionQuery:"learning journey onboarding progression coaching drills guided wizard",primaryDocsRoute:"/docs/guides/first-module-bundle",secondaryDocsRoutes:["/docs/getting-started/start-here"],packages:["@contractspec/module.learning-journey","@contractspec/lib.surface-runtime"],recommendedCommands:["contractspec examples list --query learning-journey","contractspec validate","contractspec doctor"],starterExample:{key:"learning-journey-ui-onboarding",packageRef:"@contractspec/example.learning-journey-ui-onboarding",title:"Learning Journey UI Onboarding",summary:"Checklist- and journey-map-based onboarding mini app."},advancedExample:{key:"learning-journey-registry",packageRef:"@contractspec/example.learning-journey-registry",title:"Learning Journey Registry",summary:"Registry and template aggregation surface for broader learning-journey compositions."},connectSurfaces:["cli","runtime","solution"]}];function KA(){return fm}function cm($){return fm.find((b)=>b.id===$)}function hm($){return{agentGuide:k7($),humanGuide:f7($)}}function k7($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let n of $.recommendations)b.push(...r7(n.track,n.reason));return b.join(`
|
|
2418
|
+
`)}function r7($,b){let n=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return[...n,""]}function f7($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((n,A)=>`${A+1}. \`${n}\``),"","## Track Guide",""];for(let n of $.recommendations)b.push(...c7(n.track,n.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let n of $.builderNextSteps)b.push(`- \`${n}\``);b.push("")}return b.join(`
|
|
2419
|
+
`)}function c7($,b){let n=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)n.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(n.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)n.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);n.push("","Commands:");for(let A of $.recommendedCommands)n.push(`- \`${A}\``);return n.push("",`Packages: ${$.packages.map((A)=>`\`${A}\``).join(", ")}`,""),n}import{buildContext as h7}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as d7}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as u7}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function fj($,b,n,A){let m=h7({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:n,workspaceId:A}),y=await d7(u7(o7(b)),m);return{journeyContext:m,journeyPlan:y}}function cj($){if(!$||$.length===0)return[...KA()];return $.map((b)=>{let n=cm(b);if(!n)throw Error(`Unknown onboarding track: ${b}`);return n})}function hj($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function dj($){switch($){case"managed":return["contractspec builder status"];case"local":case"hybrid":return["contractspec builder status","contractspec builder local status"];case"none":default:return["contractspec init --preset builder-managed","contractspec init --preset builder-local","contractspec init --preset builder-hybrid"]}}function uj($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let n of KA()){if(n.starterExample.key===b)return n.starterExample;if(n.advancedExample?.key===b)return n.advancedExample}return}function dm($,b){return i7($,b.flatMap((n)=>n.track.connectSurfaces))}function o7($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((n)=>({defaultSurface:n.id,path:`/onboard/${n.id}`,routeId:`onboard-${n.id}`})),surfaces:Object.fromEntries($.map((n)=>[n.id,{commands:n.recommendedCommands.map((A,m)=>({commandId:`${n.id}-${m}`,intent:`Run ${A}`,title:A})),data:[{hydrateInto:"track",recipeId:`track-${n.id}`,source:{entityType:`onboarding.${n.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${n.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:n.id,title:n.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function i7($,b){return[...new Set([...$,...b])].sort()}async function t7($,b={}){let n=await s$($.fs,b),A=cj(b.selectedTracks),m=hj(n.config),W=[...await Promise.all(A.map(async(Y)=>{let G=await Jb($,{config:n.config,cwd:n.cwd,family:Y.reuseFamily,packageRoot:n.packageRoot,platform:Y.adoptionPlatform,query:Y.adoptionQuery,workspaceRoot:n.workspaceRoot});return{reason:G.reason,resolution:G,score:G.selected?.score??0,selected:!1,track:Y}}))].sort((Y,G)=>G.score-Y.score).map((Y,G)=>({...Y,selected:G===0})),w=W[0]?.track;if(!w)throw Error("No onboarding tracks are available.");let{journeyContext:j,journeyPlan:B}=await fj(w,A,n.workspaceRoot,n.packageRoot),S=uj(w,b.forcedExampleKey)??w.starterExample,Q=p7(["contractspec onboard",...w.recommendedCommands,"contractspec doctor"]),Z=dj(m),X={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:m,builderNextSteps:Z,config:n.config,cwd:n.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:j,journeyPlan:B,nextCommands:Q,packageRoot:n.packageRoot,primaryTrack:w,recommendations:W,selectedExample:S,workspaceRoot:n.workspaceRoot};return{...X,guides:hm(X)}}async function l7($,b){if(!b.config.connect?.enabled)return;let n=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,A=[b.agentGuidePath,b.humanGuidePath],m=await fb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot}),y=await ob($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((W)=>W.track.id).join(", ")}`,steps:b.recommendations.map((W)=>({commands:W.track.recommendedCommands,paths:A,summary:`Adopt ${W.track.title}`})),touchedPaths:A},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:A,taskId:n,workspaceRoot:b.workspaceRoot});return{contextPack:{...m,affectedSurfaces:dm(m.affectedSurfaces,b.recommendations)},planPacket:{...y.planPacket,affectedSurfaces:dm(y.planPacket.affectedSurfaces,b.recommendations)}}}function p7($){return[...new Set($)]}var ij=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],a7=[...ij,{name:"@contractspec/lib.schema",description:"Extended schema utilities and common types"},{name:"@contractspec/app.cli-contractspec",dev:!0,description:"ContractSpec CLI for validation, scaffolding, and code generation"},{name:"typescript",dev:!0,description:"TypeScript compiler for type checking"}];function um($){return $==="minimal"?ij:a7}function om($){return $.filter((b)=>!b.dev)}function im($){return $.filter((b)=>b.dev)}import{exec as e7}from"child_process";import{promisify as s7}from"util";var $Z=s7(e7),bZ={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function sR($,b,n=bZ){let A=um(b.mode),m=om(A),y=im(A),W=[],w=[],j=[],B=$.join(b.workspaceRoot,"package.json");if(!await $.exists(B))return{success:!1,installed:[],skipped:[],errors:[{name:"package.json",action:"error",message:"No package.json found. Run `npm init` first."}],summary:"No package.json found in workspace root."};let Q=await $.readFile(B),Z=JSON.parse(Q),X=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),Y=a$(b.workspaceRoot),G=m.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),V=y.filter((J)=>{if(X.has(J.name)&&!b.force)return w.push({name:J.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let J=[...G,...V];return{success:!0,installed:J.map((U)=>({name:U.name,action:"installed",message:`Would install: ${U.description}`,dev:U.dev})),skipped:w,errors:[],summary:`Dry run: would install ${J.length} package(s), skip ${w.length}.`}}if(!b.skipPrompts&&(G.length>0||V.length>0)){let J=G.length+V.length;if(!await n.confirm(`Install ${J} package(s) using ${Y}?`))return{success:!0,installed:[],skipped:[...w,...G.map((H)=>({name:H.name,action:"skipped",message:"User cancelled"})),...V.map((H)=>({name:H.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(G.length>0){let J=await tj(G,Y,b.workspaceRoot,!1);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}if(V.length>0){let J=await tj(V,Y,b.workspaceRoot,!0);for(let U of J)if(U.action==="installed")W.push(U);else j.push(U)}let O=j.length===0,K=O?`Successfully installed ${W.length} package(s), skipped ${w.length}.`:`Installed ${W.length}, skipped ${w.length}, failed ${j.length}.`;return{success:O,installed:W,skipped:w,errors:j,summary:K}}async function tj($,b,n,A){let m=[],y=$.map((W)=>W.version?`${W.name}@${W.version}`:W.name);try{let w=`${hy(b,A)} ${y.join(" ")}`;await $Z(w,{cwd:n,timeout:120000});for(let j of $)m.push({name:j.name,action:"installed",message:j.description,dev:A})}catch(W){let w=W instanceof Error?W.message:String(W);for(let j of $)m.push({name:j.name,action:"error",message:`Failed to install: ${w}`,dev:A})}return m}async function $C($,b){let n=$.join(b,"package.json");try{let A=await $.readFile(n),m=JSON.parse(A);return"@contractspec/lib.contracts-spec"in{...m.dependencies,...m.devDependencies}}catch{return!1}}function bC($){let b=um($),n=[];n.push(`ContractSpec ${$} installation:`),n.push("");let A=om(b);if(A.length>0){n.push("Dependencies:");for(let y of A)n.push(` \u2022 ${y.name} - ${y.description}`)}let m=im(b);if(m.length>0){n.push(""),n.push("Dev Dependencies:");for(let y of m)n.push(` \u2022 ${y.name} - ${y.description}`)}return n.join(`
|
|
2420
|
+
`)}import{RegeneratorService as nZ}from"@contractspec/lib.contracts-spec/regenerator";function jC($){return new nZ({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class _A{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,n;try{n=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(A){throw Error(`Registry request failed: ${b} (${A instanceof Error?A.message:String(A)})`)}if(!n.ok){let A=await n.text().catch(()=>"");throw Error(`Registry request failed: ${n.status} ${n.statusText} ${A}`)}return await n.json()}}function tm($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function SC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Adding spec to registry: ${$}`,{registryUrl:m}),await new _A({registryUrl:m}).getJson(`/specs/add?path=${encodeURIComponent($)}`),A.info("Spec added to registry successfully")}async function QC($,b){let{logger:n}=b,A=tm($.registryUrl);n.info("Listing specs from registry",{registryUrl:A});let m=new _A({registryUrl:A}),y=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",W=await m.getJson(`/specs${y}`);return n.info(`Found ${W.length} specs`),W}async function ZC($,b,n){let{logger:A}=n,m=tm(b.registryUrl);A.info(`Searching registry: ${$}`,{registryUrl:m});let W=await new _A({registryUrl:m}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return A.info(`Found ${W.length} results`),W}class AZ{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:n}=$,A=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${A.join(", ")}...`);try{let m=this.fs.join(n,b.rulesDir??".rules");if(!await this.fs.exists(m))return{success:!1,files:[],errors:[`Rules directory not found: ${m}`]};let W=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${W}`);let w=[];for(let j of A){let B=this.getTargetFileName(j);if(B){let S=this.fs.join(n,B);w.push(S)}}return{success:!0,files:w,logs:[`Successfully synchronized rules to ${w.length} targets.`]}}catch(m){let y=m instanceof Error?m.message:String(m);return this.logger.error(`Rule synchronization failed: ${y}`),{success:!1,files:[],errors:[y]}}}async generateConfig($){let{config:b}=$,n={rules:(b.rules??[]).map((A)=>this.fs.join(b.rulesDir??".rules",A)),targets:$.targets||b.targets};return JSON.stringify(n,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}function zA($,b,n,A){let m=$n(b,n),y=mZ(n);if(y.test($))return $.replace(y,m);if(A&&lm($)===lm(A))return m;return`${m}${$}`}function $n($,b){let n=lm($);return`${b.startMarker}
|
|
2421
|
+
${b.note}
|
|
2422
|
+
${n}
|
|
2423
|
+
${b.endMarker}
|
|
2424
|
+
`}function lm($){return $.replace(/\r\n/g,`
|
|
2425
|
+
`).trimEnd()}function mZ($){return new RegExp(`${lj($.startMarker)}[\\s\\S]*?${lj($.endMarker)}(?:\\r?\\n)?`)}function lj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yZ="<!-- contractspec:init:agents:start -->",WZ="<!-- contractspec:init:agents:end -->",wZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",pj={endMarker:WZ,note:wZ,startMarker:yZ};async function pm($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"AGENTS.md");try{let y=await $.exists(m),W=Bw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:m,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(m,zA(w,W,pj,W)),{target:"agents-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(m,$n(W,pj)),{target:"agents-md",filePath:m,action:"created",message:"Created AI agent guide"}}catch(y){return{target:"agents-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}import{generateArtifactsForAudience as jZ,generateBiomePreset as BZ}from"@contractspec/biome-config";async function am($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"biome.jsonc"),y=$.join(A,".contractspec","biome"),W=$.join(y,"plugins"),w=$.join(y,"ai"),j=jZ("consumer");try{let B=await $.exists(m);if(B&&b.interactive){if(!await n.confirm(`${m} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:m,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(W),await $.mkdir(w),await $.writeFile(m,BZ("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(j.plugins))await $.writeFile($.join(W,S),Q);return await $.writeFile($.join(w,"consumer.md"),j.aiRules),{target:"biome-config",filePath:m,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:m,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function em($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".contractsrc.json");try{let y=await $.exists(m),W=Wb(b);if(y){let w=await $.readFile(m),j=a(w);if(!j)return{target:"cli-config",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:m,action:"skipped",message:"User skipped merge"}}let B=b$(j,W);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof W==="object"&&W!==null){let S={};if("connect"in W)S.connect=W.connect;if("builder"in W)S.builder=W.builder;await $.writeFile(m,N(D0(B,S)))}else await $.writeFile(m,N(B));return{target:"cli-config",filePath:m,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(m,N(W)),{target:"cli-config",filePath:m,action:"created",message:"Created CLI configuration"}}catch(y){return{target:"cli-config",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function sm($,b,n){let A=$.join(b.workspaceRoot,".cursor","rules"),m=$.join(A,"contractspec.mdc");try{let y=$.join(b.workspaceRoot,".cursor");if(!await $.exists(y))await $.mkdir(y);if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=jw(b);if(W)if(b.interactive){if(!await n.confirm(`${m} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:m,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:m,action:"skipped",message:"File already exists"};return await $.writeFile(m,w),{target:"cursor-rules",filePath:m,action:W?"merged":"created",message:W?"Updated Cursor rules":"Created Cursor rules"}}catch(y){return{target:"cursor-rules",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function $y($,b,n){let A=ln();try{let m=await $.exists(A),y=ww();if(b.interactive){if(!await n.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(m){let j=await $.readFile(A),B=a(j);if(!B)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let S=b$(B,y);return await $.writeFile(A,N(S)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let W=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(W))await $.mkdir(W);return await $.writeFile(A,N(y)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(m){return{target:"mcp-claude",filePath:A,action:"error",message:m instanceof Error?m.message:"Unknown error"}}}async function by($,b,n){let A=$.join(b.workspaceRoot,".cursor"),m=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let W=await $.exists(m),w=Mb();if(W){let j=await $.readFile(m),B=a(j);if(!B)return{target:"mcp-cursor",filePath:m,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${m} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:m,action:"skipped",message:"User skipped merge"}}let S=b$(B,w);return await $.writeFile(m,N(S)),{target:"mcp-cursor",filePath:m,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(m,N(w)),{target:"mcp-cursor",filePath:m,action:"created",message:"Created Cursor MCP configuration"}}catch(y){return{target:"mcp-cursor",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}var SZ="<!-- contractspec:init:usage:start -->",QZ="<!-- contractspec:init:usage:end -->",ZZ="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",aj={endMarker:QZ,note:ZZ,startMarker:SZ};async function ny($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,"USAGE.md");try{let y=await $.exists(m),W=Sw(b);if(y){let w=await $.readFile(m);if(b.interactive){if(!await n.confirm(`${m} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:m,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(m,zA(w,W,aj,W)),{target:"usage-md",filePath:m,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(m,$n(W,aj)),{target:"usage-md",filePath:m,action:"created",message:"Created usage guide"}}catch(y){return{target:"usage-md",filePath:m,action:"error",message:y instanceof Error?y.message:"Unknown error"}}}async function Ay($,b,n){let A=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,m=$.join(A,".vscode"),y=$.join(m,"settings.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(y),j=tn(b);if(w){let B=await $.readFile(y),S=a(B);if(!S)return{target:"vscode-settings",filePath:y,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await n.confirm(`${y} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:y,action:"skipped",message:"User skipped merge"}}let Q=b$(S,j);if("contractspec.api.baseUrl"in j)Q["contractspec.api.baseUrl"]=j["contractspec.api.baseUrl"];return await $.writeFile(y,N(Q)),{target:"vscode-settings",filePath:y,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(y,N(j)),{target:"vscode-settings",filePath:y,action:"created",message:"Created VS Code settings"}}catch(W){return{target:"vscode-settings",filePath:y,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var XZ={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((n)=>n.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((n)=>n.selected!==!1).map((n)=>n.value),input:async($,b)=>b??""},YZ={"agents-md":pm,"biome-config":am,"cli-config":em,"cursor-rules":sm,"mcp-claude":$y,"mcp-cursor":by,"usage-md":ny,"vscode-settings":Ay},GZ={findWorkspaceRoot:I,findPackageRoot:c,isMonorepo:Vb,getPackageName:g$};async function sC($,b,n=XZ,A={}){let m=[],y=b.targets.length>0?b.targets:xb,W={...GZ,...A.workspace},w={...YZ,...A.targets},j=A.setupGitignore??ZA,B=b.workspaceRoot,S=W.findWorkspaceRoot(B),Q=b.packageRoot??W.findPackageRoot(B),Z=b.isMonorepo??W.isMonorepo(S),X=b.packageName??(Z?W.getPackageName(Q):void 0),Y=await ej($,[Q,S]),G=b.preset??Eb(Y);if(b.interactive&&!b.preset)G=await n.select("Select initialization preset:",$w.map((g)=>({value:g,label:bw[g],description:nw[g],selected:g===G})));let V=b.scope??"workspace",O=Q!==S;if(Z&&b.interactive&&O)V=await n.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${X??Q})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${S})`,description:"Create config files at the workspace root"}]);let K=Z&&V==="package"?Q:S,J=await ej($,[K]),U={...b,workspaceRoot:S,packageRoot:Q,isMonorepo:Z,scope:V,packageName:X,preset:G,builderApiBaseUrl:b.builderApiBaseUrl??J?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??J?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??J?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??J?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??J?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??J?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??J?.connect?.studio?.queue},H=Aw(G,y);if(b.interactive)H=await n.multiSelect("Select components to configure:",xb.map((g)=>({value:g,label:sW[g],selected:H.includes(g)})));let q=U.projectName;if(b.interactive&&!q){let g=V==="package"&&X?X:K.split("/").pop()??"my-project";q=await n.input("Project name:",g)}let _=U.builderApiBaseUrl;if(b.interactive&&G.startsWith("builder-"))_=await n.input("Builder API base URL:",_??"https://api.contractspec.io");let{builderLocalRuntimeId:z,builderLocalGrantedTo:L}=U;if(b.interactive&&(G==="builder-local"||G==="builder-hybrid"))z=await n.input("Default local runtime target id:",z??"rt_local_daemon"),L=await n.input("Default local runtime grant target:",L??"local:operator");let C={...U,projectName:q,targets:H,builderApiBaseUrl:_,builderLocalRuntimeId:z,builderLocalGrantedTo:L};for(let g of H){let iA=await HZ($,g,C,n,w);m.push(iA)}let D=await j($,{behavior:C.gitignoreBehavior,interactive:C.interactive,patterns:Ww({preset:G}),prompts:n,root:S});if(C.gitignoreBehavior!=="skip"||D.action!=="skipped")m.push(D);let F=m.filter((g)=>g.action!=="error").length,E=m.filter((g)=>g.action==="error").length,r=Z?` (${V} level)`:"";return{success:E===0,preset:G,files:m,summary:`Setup complete${r}: ${F} configured, ${E} failed.`,nextSteps:yw(C)}}async function HZ($,b,n,A,m){let y=m[b];if(y)return y($,n,A);return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}async function ej($,b){for(let n of b){let A=$.join(n,".contractsrc.json");if(!await $.exists(A))continue;let m=a(await $.readFile(A));if(m)return m}return null}import{validateBlueprint as qZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as OZ}from"path";async function Yx($,b){let{fs:n}=b,A=OZ(process.cwd(),$);if(!await n.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let m=await y$(A),y=VZ(m.exports),W=qZ(y);return{spec:y,report:W,valid:W.valid,errors:W.errors.map((w)=>`[${w.code}] ${w.path}: ${w.message}`)}}catch(m){return{valid:!1,errors:[m instanceof Error?m.message:String(m)]}}}function VZ($){let b=Object.values($).filter(JZ);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function JZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as UZ,dirname as my,join as bn}from"path";async function Ox($,b,n,A,m){let{fs:y}=m,W=A.implementationPath;if(!W){let S=my($),Q=UZ($,".ts"),Z=[bn(S,Q.replace(".contracts",".handler")+".ts"),bn(S,Q.replace(".presentation","")+".tsx"),bn(S,Q.replace(".form",".form")+".tsx"),bn(my(S),"handlers",Q.replace(".contracts",".handler")+".ts"),bn(my(S),"components",Q.replace(".presentation","")+".tsx")];for(let X of Z)if(await y.exists(X)){W=X;break}}if(!W||!await y.exists(W))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let w=await y.readFile(W),B=await new On(n).validate(b,w);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as KZ,validateBuilderReadinessReport as _Z,validateBuilderWorkspace as zZ,validateBuilderWorkspaceSnapshot as LZ}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as RZ,validateExternalPatchProposal as CZ,validateProviderRoutingPolicy as xZ,validateRuntimeTarget as IZ}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as EZ,validateLayoutSlots as MZ}from"@contractspec/lib.surface-runtime/spec";async function zx($,b){if(!vZ($.specType))return{valid:!0,errors:[],warnings:[]};let n=oZ($.filePath),A=[`${n}/package.json`,`${n}/README.md`,`${n}/src/index.ts`,$.filePath],m=[];for(let w of A)if(!await b.exists(w))m.push(`Missing package scaffold file: ${w}`);if(m.length>0)return{valid:!1,errors:m,warnings:[]};let y;try{y=(await y$($.filePath)).exports}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)],warnings:[]}}let W=$.specType==="module-bundle"?TZ(y):$.specType==="builder-spec"?DZ(y):NZ(y);return{valid:m.length===0&&W.errors.length===0,errors:[...m,...W.errors],warnings:W.warnings.map((w)=>`[${$.filePath}] ${w}`)}}function TZ($){let b=[],n=[],A=FZ($,gZ);if(A.length===0)return n.push(yy("module-bundle","bundle")),{errors:b,warnings:n};for(let m of A){let y=Object.values(m.value.surfaces);for(let W of y){try{MZ(W)}catch(w){b.push(`[${m.exportName}] ${w instanceof Error?w.message:String(w)}`)}for(let w of EZ(W).warnings)n.push(`[${m.exportName}] ${w}`)}}return{errors:b,warnings:n}}function DZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(PZ(y)){A+=1,b.push(...LA(m,zZ(y)));continue}if(kZ(y)){A+=1,b.push(...LA(m,KZ(y)));continue}if(rZ(y)){A+=1,b.push(...LA(m,_Z(y)));continue}if(fZ(y))A+=1,b.push(...LA(m,LZ(y)))}if(A===0)n.push(yy("builder-spec","builder"));return{errors:b,warnings:n}}function NZ($){let b=[],n=[],A=0;for(let[m,y]of Object.entries($)){if(m==="__esModule")continue;if(cZ(y)){A+=1,b.push(...RA(m,IZ(y)));continue}if(hZ(y)){A+=1,b.push(...RA(m,xZ(y)));continue}if(dZ(y)){A+=1,b.push(...RA(m,RZ(y)));continue}if(uZ(y))A+=1,b.push(...RA(m,CZ(y)))}if(A===0)n.push(yy("provider-spec","provider"));return{errors:b,warnings:n}}function FZ($,b){return Object.entries($).filter(([n,A])=>n!=="__esModule"&&b(A)).map(([n,A])=>({exportName:n,value:A}))}function LA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function RA($,b){return b.map((n)=>`[${$}] ${n.path}: ${n.message}`)}function vZ($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function gZ($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function PZ($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function kZ($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function rZ($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function fZ($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function cZ($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function hZ($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function dZ($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function uZ($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function oZ($){let b=$.replaceAll("\\","/"),n=b.lastIndexOf("/src/");return n===-1?b.replace(/\/[^/]+$/,""):b.slice(0,n)}function yy($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as iZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as tZ}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as lZ}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as pZ}from"@contractspec/module.workspace";async function $1($,b={}){let n=[],A=[],m;if(!b.skipStructure){m=pZ($),n.push(...m.errors),A.push(...m.warnings);let y=await aZ($);n.push(...y.errors),A.push(...y.warnings)}return{valid:n.length===0,structureResult:m,errors:n,warnings:A,code:$.sourceBlock}}async function Tx($,b={}){return Promise.all($.map(async(n)=>({spec:n,...await $1(n,b)})))}async function l$($,b,n={}){let{fs:A}=b;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let y=await A.readFile($),W=[],w=[],j=void 0;if(!n.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await $1(S,n);j=Q.structureResult,W.push(...Q.errors),w.push(...Q.warnings)}}return{valid:W.length===0,structureResult:j,errors:W,warnings:w,code:y}}async function Dx($,b,n={}){let A=new Map;for(let m of $){let y=await l$(m,b,n);A.set(m,y)}return A}async function aZ($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await y$($.filePath);if($.specType==="app-config"){let m=eZ(b.exports,$),y=iZ(m);return{errors:y.errors.map((W)=>sj(W)),warnings:[...y.warnings,...y.info].map((W)=>sj(W))}}if($.specType==="feature"){let m=sZ(b.exports,$),y=tZ(m);return{errors:y.issues.filter((W)=>W.level==="error").map((W)=>CA(W)),warnings:y.issues.filter((W)=>W.level!=="error").map((W)=>CA(W))}}let n=$2(b.exports,$),A=lZ(n);return{errors:A.issues.filter((m)=>m.level==="error").map((m)=>CA(m)),warnings:A.issues.filter((m)=>m.level!=="error").map((m)=>CA(m))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function eZ($,b){return Wy($,b.exportName,b2)}function sZ($,b){return Wy($,b.exportName,n2)}function $2($,b){return Wy($,b.exportName,A2)}function Wy($,b,n){if(b&&n($[b]))return $[b];let A=Object.values($).find(n);if(!A)throw Error("Expected authored module to export a compatible spec value.");return A}function b2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function n2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function A2($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function sj($){let b=$.code?`[${$.code}] `:"",n=$.path?`${$.path}: `:"";return`${b}${n}${$.message}`}function CA($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as m2}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as jy}from"fs/promises";import{resolve as xA}from"path";async function kx($,b,n,A){let{fs:m}=A,y=xA(process.cwd(),b);if(!await m.exists(y))return{valid:!1,errors:[`Tenant config file not found: ${y}`]};try{let W=await y2(y),w=await W2(n.connections,m),j=await w2(n.translationCatalog,m),B=await j2(n.integrationRegistrars),S={};if(w.length>0)S.tenantConnections=w;if(j)S.translationCatalogs={blueprint:[j],platform:[]};if(B)S.integrationSpecs=B;let Q=m2($,W,S);return{config:W,report:Q,valid:Q.valid,errors:Q.errors.map((Z)=>`[${Z.code}] ${Z.path}: ${Z.message}`)}}catch(W){return{valid:!1,errors:[W instanceof Error?W.message:String(W)]}}}async function y2($){if($.endsWith(".json")){let A=await jy($,"utf-8"),m=JSON.parse(A);if(!b1(m))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return m}let b=await y$($),n=Object.values(b.exports).filter(b1);if(n.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return n[0]}function b1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function y1($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((n)=>n.trim()).filter(Boolean)}async function W2($,b){let n=y1($);if(!n.length)return[];let A=[];for(let m of n){let y=xA(process.cwd(),m);if(!await b.exists(y)){console.warn(`Warning: Connection file not found: ${y}`);continue}if(y.endsWith(".json")){let w=await jy(y,"utf-8"),j=JSON.parse(w);A.push(...wy(j));continue}let W=await y$(y);A.push(...wy(W.exports))}return A}function wy($){if(Array.isArray($)){let b=$.filter(n1);if(b.length)return b}if(n1($))return[$];if($&&typeof $==="object"){let n=Object.values($).flatMap((A)=>wy(A));if(n.length)return n}return[]}function n1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function w2($,b){if(!$)return;let n=xA(process.cwd(),$);if(!await b.exists(n))return;if(n.endsWith(".json")){let y=await jy(n,"utf-8"),W=JSON.parse(y);if(A1(W))return m1(W);return}let A=await y$(n),m=Object.values(A.exports).filter(A1);if(m.length===0)return;return m1(m[0])}function A1($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function m1($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function j2($){let b=y1($);if(!b.length)return;let{IntegrationSpecRegistry:n}=await import("@contractspec/lib.contracts-integrations"),A=new n;for(let m of b){let{modulePath:y,exportName:W}=B2(m);if(!y)continue;let w=xA(process.cwd(),y);try{let j=await y$(w),B=S2(j.exports,W);if(B)await B(A)}catch(j){console.warn(`Failed to load registrar from ${w}: ${j}`)}}return A}function B2($){if(!$)return{modulePath:null};let[b,n]=$.split("#"),A=b?.trim()??null,m=n?.trim();return{modulePath:A,exportName:m}}function S2($,b){if(b){let n=$[b];if(typeof n==="function")return n;return}if(typeof $.default==="function")return $.default;for(let n of Object.values($))if(typeof n==="function")return n;return}async function px($,b,n={},A){let{fs:m,logger:y}=$,W=await m.glob({pattern:n.pattern}),w=n.outputDirs?.length?n.outputDirs:[void 0],j=[],B=A?.validate??((Q)=>l$(Q,{fs:m,logger:y})),S=A?.build??((Q,Z)=>yb(Q,{fs:m,logger:y},Z?{...b,outputDir:Z}:b,{...n.buildOptions??{},outputDir:Z}));for(let Q of W)for(let Z of w){let X={specPath:Q,outputDir:Z};if(n.validate)try{X.validation=await B(Q)}catch(Y){X.error={phase:"validate",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}if(!n.dryRun)try{X.build=await S(Q,Z)}catch(Y){X.error={phase:"build",message:Y instanceof Error?Y.message:String(Y)},j.push(X);continue}else y.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});j.push(X)}return{specs:W,runs:j}}import{generateText as Q2}from"ai";var Z2=`
|
|
2011
2426
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2012
2427
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2013
2428
|
|
|
@@ -2025,7 +2440,7 @@ Generate scenarios covering:
|
|
|
2025
2440
|
- Happy path (valid input, successful execution)
|
|
2026
2441
|
- Edge cases (boundary values, optional fields)
|
|
2027
2442
|
- Error cases (invalid input, business rule violations)
|
|
2028
|
-
`.trim();class
|
|
2443
|
+
`.trim();class X2{logger;defaultModel;generateTextImpl;constructor($,b,n=Q2){this.logger=$;this.defaultModel=b;this.generateTextImpl=n}async generateTests($,b={}){let n=b.model??this.defaultModel;if(!n)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let A=`
|
|
2029
2444
|
Generate a TestSpec for the following Operation:
|
|
2030
2445
|
|
|
2031
2446
|
\`\`\`json
|
|
@@ -2034,23 +2449,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2034
2449
|
|
|
2035
2450
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2036
2451
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2037
|
-
`.trim();try{let{text:
|
|
2038
|
-
`)}function
|
|
2039
|
-
`)}function
|
|
2040
|
-
`);for(let
|
|
2041
|
-
`)}function
|
|
2452
|
+
`.trim();try{let{text:m,usage:y}=await this.generateTextImpl({model:n,system:Z2,prompt:A});this.logUsage(y);let W=this.parseResponse(m);return this.enrichSpec(W,$)}catch(m){throw this.logger.error("Failed to generate tests",{error:m}),m}}parseResponse($){try{let b=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(b)}catch(b){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,b){let n={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},A={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:n,target:A,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let b=$;this.logger.debug(`AI Usage: ${b.promptTokens} prompt + ${b.completionTokens} completion = ${b.totalTokens} total tokens`)}}import{OperationSpecRegistry as W1}from"@contractspec/lib.contracts-spec";import{TestRunner as w1}from"@contractspec/lib.contracts-spec/tests";import{resolve as By}from"path";async function mI($,b){let n=new w1({registry:b}),A=[],m=0,y=0;for(let W of $){let w=await n.run(W);A.push(w),m+=w.passed,y+=w.failed}return{results:A,passed:m,failed:y}}async function yI($,b,n){let{logger:A}=n,m;if(b.registry)m=await G2(By(b.registry));else m=new W1,A.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let y=new w1({registry:m}),W=[],w=!0;for(let j of $)try{let B=By(j),S=await UA(B),Q=j1(S);if(Q.length===0){A.warn(`No TestSpec exports found in ${j}`);continue}for(let Z of Q){A.info(`Running ${Z.meta.key}...`);let X=await y.run(Z);if(W.push(X),X.failed>0)w=!1,A.error(`${Z.meta.key} failed (${X.failed}/${X.scenarios.length})`);else A.info(`${Z.meta.key} passed (${X.passed}/${X.scenarios.length})`)}}catch(B){A.error(`Failed to load/run spec ${j}: ${B instanceof Error?B.message:String(B)}`),w=!1}return{results:W,passed:w}}async function WI($,b){let n=[];for(let A of $)try{let m=By(A),y=await UA(m),W=j1(y);n.push(...W)}catch(m){b.logger.warn(`Failed to load tests from ${A}: ${m instanceof Error?m.message:String(m)}`)}return n}function j1($){let b=[];for(let n of Object.values($))if(Y2(n))b.push(n);return b}function Y2($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function G2($){return Pj($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof W1,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as nn}from"@contractspec/module.workspace";import{IndentationText as H2,Node as Xb,Project as q2,QuoteKind as O2,SyntaxKind as V2}from"ts-morph";function J2($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function YI($,b,n={}){let{fs:A,logger:m}=b;if(!await A.exists($))return{specPath:$,specInfo:J2($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let W=await A.readFile($),w;if(n.content!==void 0)w=n.content;else if(n.fields?.length)w=U2(W,n.fields);else return{specPath:$,specInfo:nn(W,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!n.skipValidation){await A.writeFile($,w);let j=await l$($,b);if(j.errors.length>0)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:j.errors,warnings:j.warnings};if(j.warnings.length>0&&!n.allowWarnings)return await A.writeFile($,W),{specPath:$,specInfo:nn(w,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:j.warnings};return m.info(`Updated spec: ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:j.warnings}}return await A.writeFile($,w),m.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:nn(w,$),updated:!0,errors:[],warnings:[]}}function U2($,b){let A=new q2({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:H2.TwoSpaces,quoteKind:O2.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),m=_2(A);if(!m)return $;for(let y of b)K2(m,y);return A.getFullText()}function K2($,b){let n=b.key.split(".").map((w)=>w.trim()).filter(Boolean);if(n.length===0)return;let A=$;for(let w of n.slice(0,-1)){if(!A.getProperty(w))A.addPropertyAssignment({name:w,initializer:"{}"});let B=A.getPropertyOrThrow(w);if(!Xb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!Xb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(V2.ObjectLiteralExpression);if(!Q)return;A=Q}let m=n[n.length-1];if(!m)return;let y=z2(b.value),W=A.getProperty(m);if(W&&Xb.isPropertyAssignment(W)){W.setInitializer(y);return}A.addPropertyAssignment({name:m,initializer:y})}function _2($){for(let b of $.getVariableDeclarations()){let n=b.getInitializer();if(!n)continue;if(Xb.isObjectLiteralExpression(n))return n;if(Xb.isCallExpression(n)){let A=n.getArguments()[0];if(A&&Xb.isObjectLiteralExpression(A))return A}}return}function z2($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var z1={};f(z1,{getPackageUpgradeCommand:()=>O1,getDefaultVersioningConfig:()=>EA,getDefaultHooksConfig:()=>MA,applyGuidedUpgrade:()=>_1,applyConfigUpgrades:()=>q1,analyzeUpgrades:()=>IA,analyzeGuidedUpgrade:()=>Xy});import{GeneratedReleaseManifestSchema as U1}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as D2,DEFAULT_CONTRACTSRC as N2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function B1($){return $.packages.map((b)=>{let n=b.version?`@${b.version}`:"";return`- ${b.name}${n} (${b.releaseType})`})}function S1($){return $.map((b)=>` - ${b}`)}function Sy($,b){return $.audiences.filter((n)=>b.includes(n.kind)).map((n)=>`- ${L2(n.kind)}: ${n.summary}`)}function Q1($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...B1($),...Sy($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));return b.join(`
|
|
2453
|
+
`)}function Z1($){let b=[`### ${$.summary}`,...B1($),...Sy($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((n)=>` - ${n}`));for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`);return b.join(`
|
|
2454
|
+
`)}function X1($){let b=[`### ${$.summary}`,...Sy($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2455
|
+
`);for(let n of $.migrationInstructions)b.push(`- ${n.title}: ${n.summary}`),b.push(...S1(n.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let n of $.upgradeSteps)b.push(` - [${n.level}] ${n.title}: ${n.summary}`),b.push(...n.instructions.map((A)=>` - ${A}`))}return b.join(`
|
|
2456
|
+
`)}function Qy($){return["# Patch Notes","",...$.releases.map(Q1)].join(`
|
|
2042
2457
|
|
|
2043
|
-
`)}function
|
|
2458
|
+
`)}function Zy($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[Z1(b),"",X1(b)])].join(`
|
|
2044
2459
|
|
|
2045
|
-
`)}function
|
|
2460
|
+
`)}function Y1($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...S1(b.instructions)].join(`
|
|
2046
2461
|
`)).join(`
|
|
2047
|
-
`)}function
|
|
2048
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2049
|
-
`)}import{compareVersions as
|
|
2050
|
-
`),A.info("Configuration upgraded",{sectionsUpgraded:
|
|
2051
|
-
`),!0}async function
|
|
2052
|
-
`),!0}async function
|
|
2053
|
-
`),
|
|
2462
|
+
`)}function Yb($,b){let n=b.targetPackages.map((A)=>`${A.name}: ${A.currentVersion??"unknown"} -> ${A.targetVersion??"latest"}`).join(`
|
|
2463
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",n||"- No package version targets were inferred.","","Required steps:",Y1(b)].join(`
|
|
2464
|
+
`)}function L2($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as H1,countUpgradePlanStepLevels as R2,createAgentPromptBundles as C2,dedupeUpgradePlanSteps as x2,sortReleaseManifest as G1}from"@contractspec/lib.contracts-spec";function I2($,b){if(b.length===0)return G1($);let n=new Map(b.map((A)=>[A.name,A.currentVersion??"0.0.0"]));return G1({...$,releases:$.releases.filter((A)=>A.packages.some((m)=>{let y=n.get(m.name);if(!y||!m.version)return!1;return H1(m.version,y)===1}))})}function An($,b,n,A){let m=I2($,b),y=E2(m,b),W=x2(m.flatMap((S)=>S.upgradeSteps)),w=R2(W),j={generatedAt:new Date().toISOString(),targetPackages:y,releases:m,steps:W,autofixCount:w.auto,manualCount:w.manual,assistedCount:w.assisted,agentPrompts:[]},B=C2(j,n,A);return{...j,agentPrompts:B}}function E2($,b){let n=new Map(b.map((m)=>[m.name,m.currentVersion])),A=new Map;for(let m of $)for(let y of m.packages){let W=n.get(y.name),w=A.get(y.name);if(!w){A.set(y.name,{name:y.name,currentVersion:W,targetVersion:y.version});continue}if(y.version&&w.targetVersion&&H1(y.version,w.targetVersion)===1)w.targetVersion=y.version}return Array.from(A.values()).sort((m,y)=>m.name.localeCompare(y.name))}async function IA($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=a$(y);A.info("Analyzing available upgrades...",{workspaceRoot:y,packageRoot:m,packageManager:W});let w=await M2(n,m),j=await T2(n,m,y),B=w.length>0||j.length>0;return{packageManager:W,packages:w,configUpgrades:j,hasUpgrades:B}}async function M2($,b){let n=$.join(b,"package.json");if(!await $.exists(n))return[];try{let A=await $.readFile(n),m=JSON.parse(A),y=m.dependencies??{},W=m.devDependencies??{},w=[],j={...y,...W};for(let[B,S]of Object.entries(j))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))w.push({name:B,currentVersion:S,isDevDependency:!!W[B]});return w}catch{return[]}}async function T2($,b,n){let A=$.join(b,".contractsrc.json"),m=Cb({configRoot:b,workspaceRoot:n});if(!await $.exists(A))return[];try{let y=await $.readFile(A),W=JSON.parse(y),w=[],j=W.$schema;if(!j||j!==m)w.push({key:"$schema",currentValue:j,suggestedValue:m,isNew:!j});if(!W.versioning)w.push({key:"versioning",currentValue:void 0,suggestedValue:EA(),isNew:!0});else if(W.versioning.integrateWithChangesets===void 0)w.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!W.hooks)w.push({key:"hooks",currentValue:void 0,suggestedValue:MA(),isNew:!0});if(!W.release)w.push({key:"release",currentValue:void 0,suggestedValue:V1(),isNew:!0});if(!W.upgrade)w.push({key:"upgrade",currentValue:void 0,suggestedValue:J1(),isNew:!0});return w}catch{return[]}}async function q1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=I(b.workspaceRoot),W=Cb({configRoot:m,workspaceRoot:y});if(b.dryRun)A.info("Dry run - no changes will be made");let w=n.join(m,".contractsrc.json");if(!await n.exists(w))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let j=await n.readFile(w),B=JSON.parse(j),S=0,Q=B.$schema;if(!Q||Q!==W)B.$schema=W,S++;if(!B.versioning)B.versioning=EA(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=MA(),S++;if(!B.release)B.release=V1(),S++;if(!B.upgrade)B.upgrade=J1(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await n.writeFile(w,JSON.stringify(B,null,2)+`
|
|
2465
|
+
`),A.info("Configuration upgraded",{sectionsUpgraded:S});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:S,summary:b.dryRun?`Would upgrade ${S} config section(s)`:`Upgraded ${S} config section(s)`}}catch(j){let B=j instanceof Error?j.message:String(j);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function O1($,b,n){let A=n?b.map((m)=>`${m.name}@latest`).join(" "):b.map((m)=>m.name).join(" ");switch($){case"bun":return`bun add ${A}`;case"pnpm":return`pnpm add ${A}`;case"yarn":return`yarn add ${A}`;default:return`npm install ${A}`}}function EA(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function MA(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function V1(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function J1(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var F2="**/*.{ts,tsx,js,jsx,mjs,cjs}",K1=N2.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function Xy($,b){let{fs:n}=$,A=c(b.workspaceRoot),m=I(b.workspaceRoot),y=await g2(n,A,m),W=await v2(n,A,m,b.manifestPaths??y.manifestPaths),w=await IA($,{workspaceRoot:A,dryRun:b.dryRun}),j=[b.agentTarget??y.defaultAgentTarget??"codex"],B=An(W.manifest,w.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),j,Yb),S=P2(B,w.packages,w.configUpgrades);return{packageManager:w.packageManager,manifestPath:W.path,plan:S,humanChecklist:k2(S)}}async function _1($,b){let{fs:n,logger:A}=$,m=c(b.workspaceRoot),y=await Xy($,b),W=[];if(!b.dryRun){for(let j of y.plan.steps){if(j.level!=="auto")continue;for(let B of j.autofixes??[])if(await r2(n,m,B))W.push(B.id)}A.info("Applied guided upgrade autofixes",{count:W.length,workspaceRoot:m})}let w=y.plan.steps.filter((j)=>j.level!=="auto");return{success:!0,packagesUpgraded:W.filter((j)=>j.startsWith("pkg:")).length,configSectionsUpgraded:W.filter((j)=>j.startsWith("config:")).length,summary:b.dryRun?`Would apply ${y.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${W.length} deterministic upgrade autofix(es)`,appliedAutofixes:W,remainingSteps:w,humanChecklist:y.humanChecklist,promptBundle:y.plan.agentPrompts[0],plan:y.plan,manifestPath:y.manifestPath}}async function v2($,b,n,A){let m=A??["generated/releases/upgrade-manifest.json"],y=Array.from(new Set([b,n]));for(let W of m){let w=W.startsWith("/")?[W]:y.map((j)=>$.join(j,W));for(let j of w){if(!await $.exists(j))continue;let B=U1.parse(JSON.parse(await $.readFile(j)));return{path:j,manifest:B}}}return{manifest:U1.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function g2($,b,n){for(let A of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(n,".contractsrc.json")]))){if(!await $.exists(A))continue;try{let m=JSON.parse(await $.readFile(A)),y=D2.safeParse(m);if(y.success)return{...K1,...y.data.upgrade}}catch{continue}}return K1}function P2($,b,n){let A=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;A.push({id:`pkg:${S.name}`,kind:"package-json",title:`Update ${S.name}`,summary:`Update ${S.name} to ${Q.targetVersion}`,packageName:S.name,dependencyType:S.isDevDependency?"devDependencies":"dependencies",from:S.currentVersion,to:Q.targetVersion})}let m=n.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),y=[];if(A.length>0)y.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:A.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:A.map((S)=>S.packageName??""),autofixes:A});if(m.length>0)y.push({id:"upgrade-contractsrc-config",title:"Refresh .contractsrc.json defaults",summary:"Bring workspace release and upgrade config in line with current defaults.",level:"auto",instructions:m.map((S)=>`${S.configPath} -> updated`),autofixes:m});let W=[...y,...$.steps],w=W.filter((S)=>S.level==="auto").length,j=W.filter((S)=>S.level==="assisted").length,B=W.filter((S)=>S.level==="manual").length;return{...$,steps:W,autofixCount:w,assistedCount:j,manualCount:B,agentPrompts:An({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),Yb).agentPrompts}}function k2($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function r2($,b,n){switch(n.kind){case"package-json":return f2($,b,n);case"contractsrc":return c2($,b,n);case"import-rewrite":return h2($,b,n);case"codemod":return!1}}async function f2($,b,n){let A=$.join(b,"package.json");if(!await $.exists(A))return!1;let m=JSON.parse(await $.readFile(A)),y=n.dependencyType??"dependencies",W=m[y]??{};if(!n.packageName||!n.to||!W[n.packageName])return!1;return W[n.packageName]=n.to,m[y]=W,await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2466
|
+
`),!0}async function c2($,b,n){let A=$.join(b,".contractsrc.json"),m=await $.exists(A)?JSON.parse(await $.readFile(A)):{};if(!n.configPath)return!1;return d2(m,n.configPath,n.value),await $.writeFile(A,JSON.stringify(m,null,2)+`
|
|
2467
|
+
`),!0}async function h2($,b,n){if(!n.from||!n.to)return!1;let A=await $.glob({pattern:n.path??F2,cwd:b,absolute:!0}),m=!1;for(let y of A){let W=await $.readFile(y);if(!W.includes(n.from))continue;await $.writeFile(y,W.split(n.from).join(n.to)),m=!0}return m}function d2($,b,n){let A=b.split("."),m=$;for(let W of A.slice(0,-1)){let w=m[W];if(!w||typeof w!=="object"||Array.isArray(w))m[W]={};m=m[W]}let y=A.at(-1);if(y)m[y]=n}import{existsSync as Yy,mkdirSync as u2,readFileSync as o2,renameSync as i2,statSync as t2,writeFileSync as l2}from"fs";import{dirname as p2,join as a2}from"path";var e2=".contractspec/verification-cache.json",L1=1;class R1{filePath;cache;isDirty=!1;constructor($,b){let n=b??process.cwd();this.filePath=$??a2(n,e2),this.cache=new Map,this.loadSync()}loadSync(){try{if(!Yy(this.filePath))return;let $=o2(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==L1)return;for(let[n,A]of Object.entries(b.entries))this.cache.set(n,A)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=p2(this.filePath);if(!Yy($))u2($,{recursive:!0});let b={version:L1,entries:Object.fromEntries(this.cache.entries())},n=`${this.filePath}.tmp`;l2(n,JSON.stringify(b,null,2),"utf-8"),i2(n,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(Yy(this.filePath))$=t2(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function NI($,b){return new R1($,b)}class C1{cache=new Map;async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[b,n]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(n).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function vI(){return new C1}class x1{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let b=this.getStorageKey($);return this.store.get(b)??null}async set($,b){let n=this.getStorageKey($);if(await this.store.update(n,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),n=this.keyIndex.has($);if(n)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return n}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function PI($){return new x1($)}import{createHash as s2}from"crypto";var I1={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function E1($){return s2("sha256").update($).digest("hex")}function M1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function $X($){try{let b=$.split("|"),n=new Map;for(let W of b){let[w,j]=W.split(":");if(w&&j)n.set(w,j)}let A=n.get("spec"),m=n.get("impl"),y=n.get("tier");if(!A||!m||!y)return null;return{specHash:A,implHash:m,tier:y,aiModelVersion:n.get("model")}}catch{return null}}function bX($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class T1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...I1,...b},this.stats={hits:0,misses:0}}createKey($,b,n,A){return{specHash:E1($),implHash:E1(b),tier:n,aiModelVersion:n==="ai_review"?A:void 0}}async lookup($){let b=M1($),n=await this.storage.get(b);if(!n)return this.stats.misses++,{hit:!1,reason:"not_found"};if(n.meta.expiresAt){let A=new Date(n.meta.expiresAt).getTime();if(Date.now()>A)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(n.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(n.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&n.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:n}}async store($,b,n={}){let A=M1($),m=bX($.tier,this.config),y={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+m).toISOString(),dependencies:n.dependencies??[],specName:n.specName,implPath:n.implPath}};await this.storage.set(A,y),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),n=0;for(let A of b){let m=await this.storage.get(A);if(!m)continue;if(m.meta.dependencies.includes($))await this.storage.delete(A),n++;if(m.meta.specName===$||m.meta.implPath===$)await this.storage.delete(A),n++}return n}async invalidateForSpec($){let b=await this.storage.keys(),n=0;for(let A of b){let m=$X(A);if(m&&m.specHash.startsWith($.substring(0,16)))await this.storage.delete(A),n++}return n}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let b=[];for(let A of $){let m=await this.storage.get(A);if(m)b.push({key:A,createdAt:new Date(m.meta.createdAt).getTime()})}b.sort((A,m)=>A.createdAt-m.createdAt);let n=b.length-this.config.maxEntries;for(let A=0;A<n;A++){let m=b[A];if(m)await this.storage.delete(m.key)}}}function iI($,b){return new T1($,b)}import{generateVerificationPrompt as nX}from"@contractspec/lib.contracts-spec/llm";function AX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let j=JSON.parse(b[1]);return{compliant:j.passed??!1,confidence:(j.score??0)/100,findings:(j.issues??[]).map((B)=>({category:String(B.category??"semantic"),severity:String(B.severity??"warning"),message:String(B.message??""),location:B.location?String(B.location):void 0,suggestion:B.suggestion?String(B.suggestion):void 0})),rawResponse:$}}catch{}let n=[],A=$.split(`
|
|
2468
|
+
`),m="info";for(let j of A){let B=j.toLowerCase();if(B.includes("error")||B.includes("critical"))m="error";else if(B.includes("warning")||B.includes("should"))m="warning";else if(B.includes("info")||B.includes("note"))m="info";let S=j.match(/^[-*\u2022]\s*(.+)$/),Q=j.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)n.push({category:"semantic",severity:m,message:Z})}}let y=n.some((j)=>j.severity==="error"),W=!y,w=y?0.3:n.length===0?0.9:0.7;return{compliant:W,confidence:w,findings:n,rawResponse:$}}async function D1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2054
2469
|
{
|
|
2055
2470
|
"passed": true,
|
|
2056
2471
|
"score": 50,
|
|
@@ -2067,23 +2482,23 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2067
2482
|
],
|
|
2068
2483
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2069
2484
|
}
|
|
2070
|
-
\`\`\``;try{let
|
|
2485
|
+
\`\`\``;try{let n=b.aiProvider??"anthropic";if(n==="anthropic"){let{anthropic:A}=await import("@ai-sdk/anthropic"),{generateText:m}=await import("ai");return(await m({model:A("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(n==="openai"){let{openai:A}=await import("@ai-sdk/openai"),{generateText:m}=await import("ai");return(await m({model:A("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${n}`)}catch(n){return`\`\`\`json
|
|
2071
2486
|
{
|
|
2072
2487
|
"passed": false,
|
|
2073
2488
|
"score": 0,
|
|
2074
2489
|
"issues": [
|
|
2075
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2490
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${n instanceof Error?n.message:"Unknown error"}" }
|
|
2076
2491
|
],
|
|
2077
2492
|
"summary": "AI verification encountered an error"
|
|
2078
2493
|
}
|
|
2079
|
-
\`\`\``}}async function
|
|
2494
|
+
\`\`\``}}async function mn($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=nX(n,A),w=await D1(W.taskPrompt,b),j=AX(w),B=j.findings.map((X)=>({severity:X.severity,category:"semantic",message:X.message,location:X.location?{file:X.location}:m?{file:m}:void 0,suggestion:X.suggestion})),S=Math.round(j.confidence*100),Q=j.compliant,Z=j.findings.filter((X)=>X.suggestion).map((X)=>X.suggestion);return{tier:"ai_review",passed:Q,score:S,issues:B,suggestions:Z,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Q?1:0}},meta:{specName:n.meta.key,specVersion:n.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-y}}}function TA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];if(n.includes("console.log"))y.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(n.includes("// TODO")||n.includes("// FIXME"))y.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(b.policy.auth!=="anonymous"&&!n.includes("auth"))y.push({severity:"warning",category:"semantic",message:`Spec requires ${b.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let W=y.filter((j)=>j.severity==="error").length===0?80:40,w=y.filter((j)=>j.severity==="error").length===0;return{tier:"ai_review",passed:w,score:W,issues:y,suggestions:y.filter((j)=>j.suggestion).map((j)=>j.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:w?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}function mX($,b){return`You are analyzing a code implementation against its specification.
|
|
2080
2495
|
|
|
2081
2496
|
## Spec Schema Fields
|
|
2082
2497
|
${$}
|
|
2083
2498
|
|
|
2084
2499
|
## Implementation Code
|
|
2085
2500
|
\`\`\`typescript
|
|
2086
|
-
${
|
|
2501
|
+
${b}
|
|
2087
2502
|
\`\`\`
|
|
2088
2503
|
|
|
2089
2504
|
## Task
|
|
@@ -2123,42 +2538,43 @@ Match types:
|
|
|
2123
2538
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2124
2539
|
- "mismatch": Different meaning despite similar naming
|
|
2125
2540
|
- "missing": Spec field not found in implementation
|
|
2126
|
-
`}function
|
|
2127
|
-
`)}function
|
|
2128
|
-
`),A=[];for(let
|
|
2129
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,
|
|
2130
|
-
`)}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
|
|
2131
|
-
`)}function
|
|
2132
|
-
`)}function
|
|
2133
|
-
`),
|
|
2134
|
-
`).trim()||void 0,
|
|
2135
|
-
${
|
|
2541
|
+
`}function yX($){let b=[],n=(A,m)=>{try{let W=A?._def?.shape;if(W&&typeof W==="function"){let w=W();for(let[j,B]of Object.entries(w)){let Q=B?._def?.typeName??"unknown";b.push(`- ${j}: ${String(Q).replace("Zod","").toLowerCase()} (${m})`)}}}catch{b.push(`- [unable to extract ${m} fields]`)}};if($.io.input)n($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))n($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2542
|
+
`)}function WX($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let n=JSON.parse(b[1]);return{fieldMappings:(n.fieldMappings??[]).map((A)=>({specField:String(A.specField??""),specType:String(A.specType??"unknown"),implementationField:A.implementationField?String(A.implementationField):void 0,implementationType:A.implementationType?String(A.implementationType):void 0,match:A.match??"missing",aiConfidence:typeof A.aiConfidence==="number"?A.aiConfidence:0.5,suggestion:A.suggestion?String(A.suggestion):void 0})),intentAlignment:{score:typeof n.intentAlignment?.score==="number"?n.intentAlignment.score:50,issues:Array.isArray(n.intentAlignment?.issues)?n.intentAlignment.issues:[],suggestions:Array.isArray(n.intentAlignment?.suggestions)?n.intentAlignment.suggestions:[]},semanticIssues:(n.semanticIssues??[]).map((A)=>({category:String(A.category??"semantic"),severity:A.severity??"warning",message:String(A.message??""),suggestion:A.suggestion?String(A.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function N1($,b={}){let{spec:n,implementationCode:A}=$,m=yX(n),y=mX(m,A),W=await D1(y,b);return WX(W)}async function wX($,b={}){let{spec:n,implementationCode:A,implementationPath:m}=$,y=Date.now(),W=await mn($,b),w;if(b.aiApiKey)try{w=await N1($,b)}catch{}if(w){let j=[];for(let Z of w.fieldMappings)if(Z.match==="missing")j.push({severity:"error",category:"semantic",message:`Missing field: '${Z.specField}' (${Z.specType}) not found in implementation`,suggestion:Z.suggestion??`Add field '${Z.specField}' to implementation`});else if(Z.match==="mismatch")j.push({severity:"warning",category:"semantic",message:`Field mismatch: '${Z.specField}' has incorrect implementation as '${Z.implementationField}'`,suggestion:Z.suggestion});else if(Z.match==="compatible"&&Z.aiConfidence<0.8)j.push({severity:"info",category:"semantic",message:`Field naming: '${Z.specField}' implemented as '${Z.implementationField}' (compatible but not exact)`,suggestion:Z.suggestion});for(let Z of w.intentAlignment.issues)j.push({severity:"warning",category:"semantic",message:Z});for(let Z of w.semanticIssues)j.push({severity:Z.severity,category:"semantic",message:Z.message,suggestion:Z.suggestion});W.issues=[...W.issues,...j];let B=w.fieldMappings.length,S=w.fieldMappings.filter((Z)=>Z.match==="exact"||Z.match==="compatible").length;if(B>0){let Z=Math.round(S/B*100);W.score=Math.round((W.score+Z)/2),W.coverage.fields={total:B,implemented:S}}if(j.some((Z)=>Z.severity==="error"))W.passed=!1;W.suggestions=[...W.suggestions,...w.intentAlignment.suggestions]}return W.meta={...W.meta,duration:Date.now()-y},W}import{isEmitDeclRef as jX}from"@contractspec/lib.contracts-spec/operations";function BX($,b){let n=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),A=$.toLowerCase(),m=n.filter((B)=>A.includes(B)),y=n.length>0?m.length/n.length:0,W=b.key.toLowerCase().replace(/\s+/g,""),w=A.includes(W)||A.includes(`test('${b.key.toLowerCase()}'`)||A.includes(`it('${b.key.toLowerCase()}'`)||A.includes(`describe('${b.key.toLowerCase()}'`),j=y>=0.3||w;return{name:b.key,type:"scenario",passed:j,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:j?void 0:`Scenario keywords not found in implementation (${Math.round(y*100)}% coverage)`}}function SX($,b){let n=JSON.stringify(b.input),A=JSON.stringify(b.output),m=F1(b.input),y=F1(b.output),W=$.toLowerCase(),w=m.filter((X)=>W.includes(X.toLowerCase())),j=y.filter((X)=>W.includes(X.toLowerCase())),B=m.length>0?w.length/m.length:1,S=y.length>0?j.length/y.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${n.slice(0,100)}...; Output: ${A.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function F1($){let b=[];function n(A){if(typeof A==="string"&&A.length>2)b.push(A);else if(Array.isArray(A))A.forEach(n);else if(A&&typeof A==="object")Object.values(A).forEach(n)}return n($),b}function QX($,b,n){let A=$.includes(b),m=n.http?$.includes(String(n.http)):!0,y=n.when??n.description,W=y.toLowerCase().split(/\s+/).filter((Q)=>Q.length>3),w=$.toLowerCase(),j=W.filter((Q)=>w.includes(Q)),B=W.length>0?j.length/W.length:1,S=A&&(m||B>=0.3);return{name:`Error: ${b}`,type:"error",passed:S,expected:`When: ${y}; Return: ${b} (HTTP ${n.http??400})`,details:S?void 0:!A?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function ZX($,b){let n=b.sideEffects?.emits??[],A=[];for(let m of n){let y=jX(m)?m.ref.key:m.key,W=m.when,w=W.toLowerCase().split(/\s+/).filter((Z)=>Z.length>3),j=$.toLowerCase(),B=j.includes(y.toLowerCase()),S=w.filter((Z)=>j.includes(Z)),Q=w.length>0?S.length/w.length:1;A.push({name:`Event: ${y}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${y} when: ${W}`,details:!B?`Event '${y}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return A}function XX($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let n=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],A=$.toLowerCase(),m=n.some((y)=>A.includes(y));return{name:"Idempotency",type:"scenario",passed:m,expected:"Operation should be idempotent (safe to retry)",details:m?void 0:"No idempotency pattern found for idempotent operation"}}function DA($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[];for(let Y of b.acceptance?.scenarios??[])y.push(BX(n,Y));for(let Y of b.acceptance?.examples??[])y.push(SX(n,Y));for(let[Y,G]of Object.entries(b.io.errors??{}))y.push(QX(n,Y,G));y.push(...ZX(n,b));let W=XX(n,b);if(W)y.push(W);let w=y.filter((Y)=>!Y.passed).map((Y)=>({severity:Y.type==="error"?"error":"warning",category:Y.type==="scenario"?"scenario":Y.type==="example"?"scenario":"error_handling",message:Y.details??`${Y.type} not covered: ${Y.name}`,location:A?{file:A}:void 0,suggestion:Y.expected?`Expected: ${Y.expected}`:void 0})),j=y.filter((Y)=>Y.type==="scenario"),B=y.filter((Y)=>Y.type==="error"),S=y.filter((Y)=>Y.passed).length,Q=y.length>0?Math.round(S/y.length*100):100,Z=w.filter((Y)=>Y.severity==="error").length===0,X=y.filter((Y)=>!Y.passed&&Y.expected).map((Y)=>`${Y.name}: ${Y.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:w,suggestions:X,coverage:{scenarios:{total:j.length,covered:j.filter((Y)=>Y.passed).length},errors:{total:B.length,handled:B.filter((Y)=>Y.passed).length},fields:{total:y.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}import{isEmitDeclRef as YX}from"@contractspec/lib.contracts-spec/operations";function GX($){let b=/export\s+(async\s+)?function\s+\w+/.test($)||/export\s+const\s+\w+\s*=\s*(async\s*)?\(/.test($)||/export\s+default\s+(async\s+)?function/.test($)||/export\s+\{\s*\w+/.test($);return{name:"handler_export",passed:b,details:b?void 0:"No exported handler function found",suggestion:"Export a function that handles the operation: export async function handle(...) { }"}}function HX($){if(!$)return!1;let b=$.replace(/\\/g,"/");return b.includes("/packages/libs/contracts-spec/src/")||b.includes("/packages/libs/contracts-integrations/src/")||b.includes("/packages/libs/contracts-runtime-")}function qX($,b){if(HX(b))return{name:"contracts_import",passed:!0};let n=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:n,details:n?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function OX($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let A=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function VX($){let b=/:\s*any\b|as\s+any\b|<any>/,n=$.split(`
|
|
2543
|
+
`),A=[];for(let m=0;m<n.length;m++){let y=n[m]??"";if(y.trim().startsWith("//")||y.trim().startsWith("*"))continue;if(b.test(y))A.push(m+1)}return{name:"no_any_type",passed:A.length===0,details:A.length>0?`Found 'any' type on lines: ${A.slice(0,5).join(", ")}${A.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function JX($,b){let n=b.io.errors;if(!n||Object.keys(n).length===0)return{name:"error_handling",passed:!0};let A=Object.keys(n),m=[];for(let y of A)if(!$.includes(y))m.push(y);return{name:"error_handling",passed:m.length===0,details:m.length>0?`Missing error handling for: ${m.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function UX($,b){let n=b.sideEffects?.emits;if(!n||n.length===0)return{name:"event_emission",passed:!0};let A=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),m=n.map((W)=>{if(YX(W))return W.ref.key;return W.key}),y=m.filter((W)=>$.includes(W));return{name:"event_emission",passed:A&&y.length>0,details:!A?"No event emission pattern found":y.length===0?`Events not referenced: ${m.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function KX($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let n=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:n,details:n?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function _X($,b){let n=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:n,details:n?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function yn($){let{spec:b,implementationCode:n,implementationPath:A}=$,m=Date.now(),y=[GX(n),qX(n,A),OX(n,b),VX(n),JX(n,b),UX(n,b),KX(n,b),_X(n,b)],W=y.filter((X)=>!X.passed).map((X)=>({severity:X.name==="no_any_type"?"warning":"error",category:X.name.includes("import")?"import":X.name.includes("export")?"export":"type",message:X.details??`Check failed: ${X.name}`,location:A?{file:A}:void 0,suggestion:X.suggestion})),w=y.filter((X)=>X.passed).length,j=Math.round(w/y.length*100),B=W.filter((X)=>X.severity==="error").length===0,S=y.filter((X)=>!X.passed&&X.suggestion).map((X)=>X.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=y.find((X)=>X.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:j,issues:W,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:y.length,implemented:w}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-m}}}var zX={verbose:!1},LX=["structure","behavior","ai_review"];class NA{config;constructor($={}){this.config={...zX,...$}}async verify($,b,n={}){let A=Date.now(),m=new Map,y=[],W={spec:$,implementationCode:b},w=n.tiers??["structure","behavior"];for(let Z of LX){if(!w.includes(Z))continue;let X;switch(Z){case"structure":X=yn(W);break;case"behavior":X=DA(W);break;case"ai_review":if(this.config.aiApiKey)X=await mn(W,this.config);else X=TA(W);break;default:continue}if(m.set(Z,X),y.push(...X.issues),n.failFast&&!X.passed)break}let j=Array.from(m.values()),B=j.every((Z)=>Z.passed),S=j.length>0?Math.round(j.reduce((Z,X)=>Z+X.score,0)/j.length):100,Q=this.generateSummary(j,y);return{passed:B,score:S,reports:m,allIssues:y,summary:Q,duration:Date.now()-A}}verifyStructure($,b,n){return yn({spec:$,implementationCode:b,implementationPath:n})}verifyBehavior($,b,n){return DA({spec:$,implementationCode:b,implementationPath:n})}async verifyAI($,b,n){let A={spec:$,implementationCode:b,implementationPath:n};if(this.config.aiApiKey)return mn(A,this.config);return TA(A)}quickVerify($,b){return yn({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[A,m]of $.reports){if(b.push(`## ${this.formatTierName(A)}`),b.push(""),b.push(`**Status:** ${m.passed?"\u2713 Passed":"\u2717 Failed"}`),b.push(`**Score:** ${m.score}/100`),b.push(""),m.issues.length>0){b.push("### Issues"),b.push("");for(let y of m.issues){let W=y.severity==="error"?"\u274C":y.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(b.push(`${W} **${y.category}**: ${y.message}`),y.suggestion)b.push(` - Suggestion: ${y.suggestion}`)}b.push("")}if(m.coverage.scenarios.total>0)b.push(`**Scenarios:** ${m.coverage.scenarios.covered}/${m.coverage.scenarios.total}`);if(m.coverage.errors.total>0)b.push(`**Errors handled:** ${m.coverage.errors.handled}/${m.coverage.errors.total}`);b.push("")}let n=Array.from($.reports.values()).flatMap((A)=>A.suggestions);if(n.length>0){b.push("## Suggestions"),b.push("");for(let A of n.slice(0,10))b.push(`- ${A}`);if(n.length>10)b.push(`- ... and ${n.length-10} more`);b.push("")}return b.join(`
|
|
2544
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let n=[],A=$.every((j)=>j.passed),m=$.length>0?Math.round($.reduce((j,B)=>j+B.score,0)/$.length):100;n.push(A?"\u2713 Verification passed":"\u2717 Verification failed"),n.push(`Score: ${m}/100`),n.push("");for(let j of $){let B=j.passed?"\u2713":"\u2717";n.push(`${B} ${j.tier}: ${j.score}/100`)}n.push("");let y=b.filter((j)=>j.severity==="error"),W=b.filter((j)=>j.severity==="warning"),w=b.filter((j)=>j.severity==="info");if(y.length>0)n.push(`Errors: ${y.length}`);if(W.length>0)n.push(`Warnings: ${W.length}`);if(w.length>0)n.push(`Info: ${w.length}`);return n.join(`
|
|
2545
|
+
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function RX($){return new NA($)}var CX=new NA;var nB={};f(nB,{saveReleaseDraft:()=>t1,renderUpgradePrompt:()=>Yb,renderUpgradeChecklist:()=>Y1,renderPatchNotes:()=>Qy,renderMigrationGuide:()=>X1,renderMaintainerSummary:()=>Q1,renderCustomerPatchNote:()=>Z1,renderCustomerGuide:()=>Zy,prepareReleaseAuthoring:()=>i1,parseConventionalCommit:()=>gA,isConventionalCommit:()=>NX,initReleaseArtifacts:()=>e1,getHighestBumpType:()=>Hy,getBumpTypeFromCommit:()=>Gy,generateChangelogs:()=>o1,formatKeepAChangelog:()=>Wn,formatConventionalChangelog:()=>g1,formatChangelogJson:()=>FA,filterCommitsByScope:()=>FX,filterBumpableCommits:()=>vX,commitsToChangeEntries:()=>qy,commitToChangeEntry:()=>k1,checkReleaseArtifacts:()=>$B,buildReleaseArtifacts:()=>s1,applyVersionBump:()=>u1,analyzeVersionsFromCommits:()=>Gb,analyzeVersions:()=>Qn,DEFAULT_COMMIT_TYPE_MAP:()=>vA});import{basename as xX,dirname as IX}from"path";function Wn($){let b=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){b.push(`## [${A.version}] - ${A.date}`),b.push("");let m=A.changes.filter((Q)=>Q.type==="added"),y=A.changes.filter((Q)=>Q.type==="changed"),W=A.changes.filter((Q)=>Q.type==="deprecated"),w=A.changes.filter((Q)=>Q.type==="removed"),j=A.changes.filter((Q)=>Q.type==="fixed"),B=A.changes.filter((Q)=>Q.type==="security"),S=A.breakingChanges??A.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### \u26A0\uFE0F Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(m.length>0)b.push("### Added"),m.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(y.length>0)b.push("### Changed"),y.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(W.length>0)b.push("### Deprecated"),W.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(w.length>0)b.push("### Removed"),w.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(j.length>0)b.push("### Fixed"),j.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(B.length>0)b.push("### Security"),B.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("")}return b.join(`
|
|
2546
|
+
`)}function g1($){let b=["# Changelog",""],n=[...$].sort((A,m)=>P1(A.version,m.version));for(let A of n){let m=A.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":A.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${A.version} (${A.date}) - ${m}`),b.push("");let y={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let W of A.changes){let w=y[W.type]??"chore",j=W.path?`(${W.path})`:"",B=W.type==="breaking"?"!":"";b.push(`- **${w}${j}${B}**: ${W.description}`)}b.push("")}return b.join(`
|
|
2547
|
+
`)}function FA($,b){let n=$.analyses.filter((y)=>y.needsBump),A=new Date().toISOString(),m=A.split("T")[0]??"";return{generatedAt:A,baseline:b,specs:n.map((y)=>({key:y.specKey,version:y.suggestedVersion,path:y.specPath,entries:[{version:y.suggestedVersion,date:m,bumpType:y.bumpType,changes:y.changes,breakingChanges:y.changes.filter((W)=>W.type==="breaking")}]})),libraries:MX(n,m)}}function EX($){let b=$.split("/"),n=b.lastIndexOf("packages");if(n>=0&&n+2<b.length)return b.slice(0,n+3).join("/");return IX($)}var v1={major:3,minor:2,patch:1};function MX($,b){let n=new Map;for(let A of $){let m=EX(A.specPath),y=n.get(m);if(y)y.push(A);else n.set(m,[A])}return Array.from(n.entries()).flatMap(([A,m])=>{let y=m[0];if(!y)return[];let W=m.reduce((w,j)=>{return(v1[j.bumpType]??0)>(v1[w.bumpType]??0)?j:w},y);return[{name:xX(A),path:A,version:W.suggestedVersion,entries:[{version:W.suggestedVersion,date:b,bumpType:W.bumpType,changes:m.flatMap((w)=>w.changes),breakingChanges:m.flatMap((w)=>w.changes).filter((w)=>w.type==="breaking")}]}]})}function P1($,b){let n=(y)=>{return y.split(".").map((w)=>parseInt(w,10)||0)},A=n($),m=n(b);for(let y=0;y<3;y++){let W=A[y]??0,w=m[y]??0;if(W!==w)return w-W}return 0}var vA={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},TX=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,DX=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function gA($){let b=$.split(`
|
|
2548
|
+
`),n=b[0]?.trim();if(!n)return null;let A=n.match(TX);if(!A)return null;let[,m,y,W,w]=A;if(!m||!w)return null;let j=b.slice(1).join(`
|
|
2549
|
+
`).trim()||void 0,B=j?.match(DX),S=B?.[1];return{type:m.toLowerCase(),scope:y?.toLowerCase(),breaking:!!W||!!B,description:w.trim(),body:j,breakingDescription:S,raw:$}}function NX($){return gA($)!==null}function Gy($,b=vA){if($.breaking)return"major";return b[$.type]??null}function Hy($,b=vA){let n=["major","minor","patch"],A=null;for(let m of $){let y=Gy(m,b);if(!y)continue;if(!A){A=y;continue}let W=n.indexOf(A);if(n.indexOf(y)<W)A=y}return A}function k1($){if($.breaking)return{type:"breaking",description:$.breakingDescription??$.description,path:$.scope};switch($.type){case"feat":return{type:"added",description:$.description,path:$.scope};case"fix":return{type:"fixed",description:$.description,path:$.scope};case"deprecate":return{type:"deprecated",description:$.description,path:$.scope};case"remove":return{type:"removed",description:$.description,path:$.scope};case"security":return{type:"security",description:$.description,path:$.scope};default:return{type:"changed",description:$.description,path:$.scope}}}function qy($){return $.map(k1)}function FX($,b){return $.filter((n)=>n.scope?.toLowerCase()===b.toLowerCase())}function vX($,b=vA){return $.filter((n)=>Gy(n,b)!==null)}import{z as M}from"zod";import{ReleaseCapsuleSchema as r1}from"@contractspec/lib.contracts-spec";import{dump as gX,load as PX}from"js-yaml";var kX=".changeset/*.md",rX=".changeset/*.release.yaml",fX=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,cX=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function hX($,b){return(await $.glob({pattern:kX,cwd:b,absolute:!0})).filter((A)=>$.basename(A)!=="README.md")}async function wn($,b){let n=await hX($,b),A=[];for(let m of n){let y=await $.readFile(m);A.push(dX($.basename(m),y))}return A}async function jn($,b,n){let A=await $.glob({pattern:rX,cwd:b,absolute:!0}),m=new Map(n.map((w)=>[w.slug,w.packages])),y=new Map,W=[];for(let w of A){let j=$.basename(w).replace(/\.release\.yaml$/,"");try{let B=PX(await $.readFile(w)),S=uX(B,j,m.get(j)??[]);y.set(j,S)}catch(B){W.push(oX(w,j,B))}}return{capsules:y,issues:W}}async function Bn($,b){let n=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),A=[];for(let m of n){let y=JSON.parse(await $.readFile(m));if(!y.name||!y.version||y.private===!0)continue;let W=$.relative(b,$.dirname(m))||".";A.push({name:y.name,dir:W,version:y.version})}return A.sort((m,y)=>m.dir.localeCompare(y.dir))}function PA($,b){let n=new Set;for(let A of $){let m=b.find((y)=>y.dir==="."?!A.startsWith("packages/"):A===y.dir||A.startsWith(`${y.dir}/`));if(m)n.add(m.name)}return Array.from(n).sort((A,m)=>A.localeCompare(m))}function kA($,b){return`---
|
|
2550
|
+
${b.map((A)=>`"${A.name}": ${A.releaseType}`).join(`
|
|
2136
2551
|
`)}
|
|
2137
2552
|
---
|
|
2138
2553
|
|
|
2139
2554
|
${$}
|
|
2140
|
-
`}function
|
|
2141
|
-
`)
|
|
2142
|
-
`)}function
|
|
2143
|
-
|
|
2555
|
+
`}function rA($){return gX(r1.parse($),{noRefs:!0,lineWidth:100})}function Sn($){return $.map((b)=>{let n=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",A=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${n} ${b.message}.${A}`.trim()}).join(`
|
|
2556
|
+
`)}function dX($,b){let n=$.replace(/\.md$/,""),A=b.match(fX);if(!A)return{slug:n,summary:b.trim(),packages:[]};let m=A[1]??"",y=(A[2]??"").trim(),W=[];for(let w of m.split(`
|
|
2557
|
+
`)){let j=w.trim().match(cX);if(!j)continue;let B=j[1],S=j[2];if(!B||S==="none")continue;W.push({name:B,releaseType:S})}return{slug:n,summary:y,packages:W}}function uX($,b,n){let A=typeof $==="object"&&$!==null?$:{},m=Array.isArray(A.packageNames)?A.packageNames.filter((y)=>typeof y==="string").map((y)=>({name:y,releaseType:A.releaseType??"patch"})):[];return r1.parse({...A,slug:b,packages:Array.isArray(A.packages)&&A.packages.length>0?A.packages:m.length>0?m:n})}function oX($,b,n){let A=typeof n==="object"&&n!==null?n:null,m=Array.isArray(A?.issues)?A.issues.map((W)=>W.message).filter((W)=>typeof W==="string"):[],y=m.length>0?`Release capsule validation failed: ${m.join("; ")}`:typeof A?.reason==="string"?`Release capsule YAML parse failed: ${A.reason}`:`Release capsule parse failed: ${n instanceof Error?n.message:String(n)}`;return{slug:b,filePath:$,message:y,line:typeof A?.mark?.line==="number"?A.mark.line+1:void 0,column:typeof A?.mark?.column==="number"?A.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as d1,determineBumpType as iX}from"@contractspec/lib.contracts-spec";async function Qn($,b={}){let{fs:n,git:A,logger:m}=$,y=b.workspaceRoot??process.cwd();m.info("Starting version analysis...",{baseline:b.baseline});let W=b.pattern??"**/*.{operation,event,presentation}.ts",j=(await n.glob({pattern:W,cwd:y})).filter((X)=>!X.includes(".test.")&&!X.includes(".spec.")&&!X.includes("node_modules"));m.debug(`Found ${j.length} spec files`);let B=[],S=0,Q=0;for(let X of j)try{let Y=await n.readFile(X),G=fA(Y);if(!G)continue;let V=null;if(b.baseline)try{V=await A.showFile(b.baseline,X)}catch{V=null}let O=tX(Y,V),K=O.some((_)=>_.type==="breaking"),J=O.length>0&&!K,U=O.length>0;if(K)S++;if(J)Q++;let H=iX(K,J),q=U?d1(G.version,H):G.version;B.push({specPath:X,specKey:G.key,currentVersion:G.version,suggestedVersion:q,bumpType:H,changes:O,hasBreaking:K,needsBump:U})}catch(Y){m.warn(`Failed to analyze ${X}:`,{error:Y instanceof Error?Y.message:String(Y)})}let Z=B.filter((X)=>X.needsBump).length;return m.info("Version analysis complete",{totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q}),{analyses:B,totalSpecs:B.length,specsNeedingBump:Z,totalBreaking:S,totalNonBreaking:Q,baseline:b.baseline}}async function Gb($,b={}){let{git:n,logger:A}=$,m=b.baseline??"HEAD~10";A.info("Analyzing commits for version bump...",{baseline:m});try{let y=await n.log(m),W=[],w=[];for(let Q of y){let Z=gA(Q.message);if(Z)W.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),w.push(Z)}let j=Hy(w),B=qy(w),S=W.filter((Q)=>Q.breaking).length;return A.info("Commit analysis complete",{totalCommits:W.length,breakingCommits:S,suggestedBumpType:j}),{suggestedBumpType:j,commits:W,changes:B,totalCommits:W.length,breakingCommits:S}}catch(y){return A.warn("Failed to analyze commits",{error:y instanceof Error?y.message:String(y)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function u1($,b){let{fs:n,logger:A}=$,{specPath:m,dryRun:y=!1,config:W}=b;A.info("Applying version bump...",{specPath:m,bumpType:b.bumpType});try{let w=await n.readFile(m),j=fA(w);if(!j)return{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:c1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=d1(j.version,B),Q=b.changes??[];if(b.changeDescription)Q.push({type:B==="major"?"breaking":"changed",description:b.changeDescription});let Z={version:S,date:new Date().toISOString().split("T")[0]??"",bumpType:B,changes:Q,breakingChanges:Q.filter((X)=>X.type==="breaking")};if(!y){let X=pX(w,j.version,S);await n.writeFile(m,X)}if(A.info("Version bump applied",{specPath:m,previousVersion:j.version,newVersion:S}),W?.integrateWithChangesets)await sX($,{specPath:m,bumpType:B,summary:b.changeDescription??`Bump ${j.key} to ${S}`,dryRun:y});return{success:!0,specPath:m,specKey:j.key,previousVersion:j.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(w){let j=w instanceof Error?w.message:String(w);return A.error("Version bump failed",{specPath:m,error:j}),{success:!1,specPath:m,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:c1(),error:j}}}async function o1($,b={}){let{logger:n}=$,A=b.tiers??["spec","library","monorepo"],m=b.format??"keep-a-changelog";n.info("Generating changelogs...",{tiers:A,format:m});let y=await Qn($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),W=[],w=new Map,j="",B=0;if(A.includes("spec"))for(let Q of y.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:aX(Q),kind:"changelog",specKey:Q.specKey,specVersion:Q.suggestedVersion,entries:[{version:Q.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:Q.bumpType,changes:Q.changes,breakingChanges:Q.changes.filter((X)=>X.type==="breaking")}]};W.push(Z),B++}if(A.includes("library")){let Q=eX(y.analyses);for(let[Z,X]of Q){let Y=X.filter((G)=>G.needsBump);if(Y.length>0)w.set(Z,Wn(Y.map(h1))),B+=Y.length}}if(A.includes("monorepo")){let Q=y.analyses.filter((Z)=>Z.needsBump).map(h1);j=Wn(Q)}let S=FA(y,b.baseline);return n.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:W,libraryMarkdown:w,monorepoMarkdown:j,json:S,totalEntries:B}}function fA($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),n=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!n)return null;let A=b[1],m=n[1];if(!A||!m)return null;return{key:A,version:m}}function tX($,b){let n=[];if(!b)return n.push({type:"added",description:"New spec added"}),n;let A=fA($),m=fA(b);if(!A||!m)return n;if(A.version!==m.version)n.push({type:"changed",description:`Version updated from ${m.version} to ${A.version}`,path:"meta.version"});let y=lX($,b);if(y.breaking)n.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(y.nonBreaking)n.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return n}function lX($,b){let n=/io:\s*\{[\s\S]*?\}/,A=$.match(n)?.[0]??"",m=b.match(n)?.[0]??"";if(A===m)return{breaking:!1,nonBreaking:!1};let y=f1(A),W=f1(m),w=W.filter((B)=>!y.includes(B)),j=y.filter((B)=>!W.includes(B));return{breaking:w.length>0,nonBreaking:j.length>0&&w.length===0}}function f1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((A)=>A[1]).filter((A)=>!!A)}function pX($,b,n){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${n}'`)}function c1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function aX($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],n=$.changes.filter((y)=>y.type==="breaking"),A=$.changes.filter((y)=>y.type==="changed"),m=$.changes.filter((y)=>y.type==="added");if(n.length>0)b.push("### Breaking Changes"),n.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(m.length>0)b.push("### Added"),m.forEach((y)=>b.push(`- ${y.description}`)),b.push("");if(A.length>0)b.push("### Changed"),A.forEach((y)=>b.push(`- ${y.description}`)),b.push("");return b.join(`
|
|
2558
|
+
`)}function eX($){let b=new Map;for(let n of $){let y=n.specPath.match(/(.+?\/src\/)/)?.[1]??n.specPath,W=b.get(y)??[];W.push(n),b.set(y,W)}return b}function h1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function sX($,b){let{fs:n,logger:A}=$,{specPath:m,bumpType:y,summary:W,dryRun:w}=b;try{let j=c(m),B=g$(j);if(!B){A.warn("Could not determine package name for changeset",{specPath:m});return}let S=j,Q=null;while(!0){let G=n.join(S,".changeset");if(await n.exists(G)){Q=G;break}let V=n.dirname(S);if(V===S)break;S=V}if(!Q){A.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${$Y()}.md`,X=n.join(Q,Z),Y=`---
|
|
2559
|
+
"${B}": ${y}
|
|
2144
2560
|
---
|
|
2145
2561
|
|
|
2146
|
-
${
|
|
2147
|
-
`;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 Tq(){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=yq.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??vq(B),G=W.releaseType??V,J=W.summary??`Describe the ${G} release for ${B[0]??"the workspace"}`,b=W.slug??Pq(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:mq(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=Fq.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=xq.safeParse(A);return Q.success?{...tW,...Q.data.release}:tW}catch{return tW}}function vq($){return $.length>0?"minor":"patch"}function mq($,W){return $.packages.map((A)=>W.find((Q)=>Q.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function Pq($){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 kq}from"fs";import{readFile as hq}from"fs/promises";import{join as Q5}from"path";import gq 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(kq(Z))try{let X=await hq(Z,"utf-8");if(Z.endsWith(".json"))Q=JSON.parse(X);else Q=gq.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${Z}`,X)}return{...sW,...Q}}import{existsSync as fq}from"fs";import{copyFile as uq,mkdir as ZA,readFile as dq,writeFile as nq}from"fs/promises";import{dirname as cq,join as a$}from"path";import{glob as rq}from"glob";var lq=["**/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=[...lq],Y=a$(j,".gitignore");if(fq(Y)){let w=(await dq(Y,"utf-8")).split(`
|
|
2148
|
-
`).map((
|
|
2562
|
+
${W}
|
|
2563
|
+
`;if(!w)await n.writeFile(X,Y),A.info("Generated changeset",{filePath:X});else A.info("Would generate changeset",{filePath:X,content:Y})}catch(j){A.error("Failed to generate changeset",{error:j instanceof Error?j.message:String(j)})}}function $Y(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],n=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],m=b[Math.floor(Math.random()*b.length)],y=n[Math.floor(Math.random()*n.length)],W=Math.floor(Math.random()*1000);return`${A}-${m}-${y}-${W}`}var bY=M.object({summary:M.string(),maintainerSummary:M.string(),customerSummary:M.string(),integratorSummary:M.string(),deprecations:M.array(M.string()).default([]),migrationInstructions:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),required:M.boolean().default(!1),when:M.string().optional(),steps:M.array(M.string()).default([])})).default([]),upgradeSteps:M.array(M.object({id:M.string(),title:M.string(),summary:M.string(),level:M.enum(["auto","assisted","manual"]).default("manual"),instructions:M.array(M.string()).default([])})).default([]),validationCommands:M.array(M.string()).default([]),validationEvidence:M.array(M.string()).default([])});async function i1($,b={}){let{fs:n,git:A,logger:m,ai:y}=$,W=I(b.workspaceRoot),w=await Bn(n,W),j=b.baseline?await A.diffFiles(b.baseline):[],B=await wn(n,W),S=await jn(n,W,B),Q=b.packages&&b.packages.length>0?b.packages:PA(j,w),Z=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:W}):null,X=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:W}):null,Y=b.slug??WY(B,S.capsules,Q),G=Y?n.join(W,".changeset",`${Y}.md`):void 0,V=Y?n.join(W,".changeset",`${Y}.release.yaml`):void 0,O=Y?B.find((q)=>q.slug===Y):void 0,K=Y?S.capsules.get(Y):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((X?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??wY(Q)),U=(G?await n.exists(G):!1)||(V?await n.exists(V):!1),H=await AY(y,nY({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:w,isBreaking:J==="major"||(X?.summary.breaking??0)>0,selectedSlug:Y}),{changedFiles:j,commitMessages:b.baseline?(await A.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},m);return{workspaceRoot:W,source:U?"existing":"created",changesetPath:G??n.join(W,".changeset",`${H.slug}.md`),capsulePath:V??n.join(W,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${Sn(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:y!==void 0}}async function t1($,b){let{fs:n}=$,A=I(b.workspaceRoot),m=Zn(b.draft),y=n.join(A,".changeset",`${m.slug}.md`),W=n.join(A,".changeset",`${m.slug}.release.yaml`),w=await n.exists(y)||await n.exists(W)?"updated":"created",j=kA(m.summary,m.packages),B=rA(yY(m));return await n.writeFile(y,j),await n.writeFile(W,B),{source:w,changesetPath:y,capsulePath:W,changesetContent:j,capsuleContent:B}}function nY($){if($.existingCapsule)return Zn({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((A)=>({...A,version:$.workspacePackages.find((m)=>m.name===A.name)?.version??A.version})):$.packageNames.map((A)=>({name:A,releaseType:$.releaseType,version:$.workspacePackages.find((m)=>m.name===A)?.version})),n=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return Zn({slug:$.selectedSlug??jY(n),summary:n,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:l1(n),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function AY($,b,n,A){if(!$)return b;try{let m=await $.generateStructured({schema:bY,systemPrompt:"You write structured release metadata for a TypeScript monorepo. Be concise, concrete, and safe for public release notes.",prompt:JSON.stringify({draft:b,changedFiles:n.changedFiles.slice(0,40),commitMessages:n.commitMessages.slice(0,20),parseIssues:n.parseIssues})});return mY(b,m.object)}catch(m){return A.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:m instanceof Error?m.message:String(m)}),b}}function mY($,b){let n=[...$.audiences];return Oy(n,"maintainer",b.maintainerSummary),Oy(n,"customer",b.customerSummary),Oy(n,"integrator",b.integratorSummary),Zn({...$,summary:p1($.summary)?b.summary:$.summary,audiences:n,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function Zn($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:l1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function yY($){let{releaseType:b,...n}=Zn($);return{schemaVersion:"1",...n}}function l1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function Oy($,b,n){let A=$.find((m)=>m.kind===b);if(A&&!p1(A.summary))return;if(A){A.summary=n;return}$.push({kind:b,summary:n})}function WY($,b,n){let A=new Set([...$.map((y)=>y.slug),...b.keys()].filter((y)=>y!=="auto-dependent-bumps"));if(A.size===1)return Array.from(A)[0];if(n.length===0)return;let m=Array.from(A).filter((y)=>{let W=b.get(y),w=$.find((B)=>B.slug===y);return(W?.packages.map((B)=>B.name)??w?.packages.map((B)=>B.name)??[]).some((B)=>n.includes(B))});return m.length===1?m[0]:void 0}function wY($){return $.length>0?"minor":"patch"}function p1($){return $.trim().startsWith("Describe the ")}function jY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as BY}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as SY,DEFAULT_CONTRACTSRC as QY}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var a1="generated/releases",cA=QY.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function e1($,b={}){let{fs:n,git:A,logger:m}=$,y=I(b.workspaceRoot),W=await Bn(n,y),w=b.baseline?await A.diffFiles(b.baseline):[],j=b.packages&&b.packages.length>0?b.packages:PA(w,W),B=b.baseline?await Gb($,{baseline:b.baseline,workspaceRoot:y}):null,S=b.baseline?await K$($,{baseline:b.baseline,workspaceRoot:y}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??ZY(j),Z=b.releaseType??Q,X=b.summary??`Describe the ${Z} release for ${j[0]??"the workspace"}`,Y=b.slug??YY(X),G=j.map((H)=>({name:H,releaseType:Z,version:W.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:Y,summary:X,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:G,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:X},{kind:"customer",summary:X}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=n.join(y,".changeset",`${Y}.md`),K=n.join(y,".changeset",`${Y}.release.yaml`);if(!b.force){if(await n.exists(O))throw Error(`Changeset already exists: ${O}`);if(await n.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=kA(X,G),U=rA(V);if(!b.dryRun)await n.writeFile(O,J),await n.writeFile(K,U);return m.info("Initialized release artifacts",{slug:Y,workspaceRoot:y}),{slug:Y,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:U,packages:G,releaseType:Z,isBreaking:V.isBreaking}}async function s1($,b={}){let{fs:n,logger:A}=$,m=I(b.workspaceRoot),y=await bB(n,m),W=n.join(m,b.outputDir??a1),w=await wn(n,m),j=await jn(n,m,w);if(j.issues.length>0)throw Error(Sn(j.issues));let B=j.capsules,S=await Bn(n,m),Q=await Promise.all(Array.from(B.entries()).map(async([U,H])=>{let q=n.join(m,".changeset",`${U}.release.yaml`),_=await n.stat(q);return{slug:U,version:XY(H,S),summary:H.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:H.isBreaking,packages:H.packages.map((z)=>({...z,version:S.find((L)=>L.name===z.name)?.version??z.version})),affectedRuntimes:[...H.affectedRuntimes],affectedFrameworks:[...H.affectedFrameworks],audiences:[...H.audiences],deprecations:[...H.deprecations],migrationInstructions:[...H.migrationInstructions],upgradeSteps:[...H.upgradeSteps],validation:H.validation}})),Z=BY.parse({generatedAt:new Date().toISOString(),releases:Q}),X=b.agentTargets??y.agentTargets??["codex"],Y=An(Z,[],X,Yb),G=n.join(W,"manifest.json"),V=n.join(W,"upgrade-manifest.json"),O=n.join(W,"patch-notes.md"),K=n.join(W,"customer-guide.md"),J=Object.fromEntries(Y.agentPrompts.map((U)=>[U.agent,n.join(W,"prompts",`${U.agent}.md`)]));if(!b.dryRun){await n.writeFile(G,JSON.stringify(Z,null,2)),await n.writeFile(V,JSON.stringify(Z,null,2)),await n.writeFile(O,Qy(Z)),await n.writeFile(K,Zy(Z));for(let U of Y.agentPrompts)await n.writeFile(J[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:W,releasesBuilt:Z.releases.length}),{outputDir:W,manifestPath:G,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:Y,releasesBuilt:Z.releases.length}}async function $B($,b={}){let{fs:n}=$,A=I(b.workspaceRoot),m=await bB(n,A),y=n.join(A,b.outputDir??a1),W=[],w=[],j=[],B=await wn(n,A),S=await jn(n,A,B),Q=S.capsules,Z=B.length>0,X=!Z&&Q.size>0;j.push(...S.issues.map((Y)=>Sn([Y]))),Hb(W,Z||X,"changesets",Z?`Found ${B.length} release changeset(s).`:X?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let Y of B)if(!Q.has(Y.slug)&&m.requireReleaseCapsule)j.push(`Missing release capsule for changeset ${Y.slug}.`);for(let[Y,G]of Q){if(G.isBreaking&&G.migrationInstructions.length===0)j.push(`Breaking release ${Y} is missing migration instructions.`);if(G.validation.commands.length===0)j.push(`Release capsule ${Y} is missing validation commands.`);if(G.validation.evidence.length===0)j.push(`Release capsule ${Y} is missing validation evidence.`)}if(b.baseline){try{let Y=await K$($,{baseline:b.baseline,workspaceRoot:A});if(Hb(W,!0,"impact",`Impact status: ${Y.status}`),Y.summary.breaking>0&&!Array.from(Q.values()).some((G)=>G.isBreaking))j.push("Breaking impact detected without a breaking release capsule.")}catch(Y){Hb(W,!1,"impact",hA(Y)),j.push(`Impact detection failed: ${hA(Y)}`)}try{let Y=await Qn($,{baseline:b.baseline,workspaceRoot:A});Hb(W,!0,"versioning",`${Y.specsNeedingBump} spec(s) need version review.`)}catch(Y){Hb(W,!1,"versioning",hA(Y)),j.push(`Version analysis failed: ${hA(Y)}`)}}if(b.strict)for(let Y of m.publishArtifacts??[]){let G=n.join(y,Y);if(!await n.exists(G))j.push(`Missing generated release artifact: ${G}`)}if(Hb(W,j.length===0,"capsules",j.length===0?"All release capsules are complete.":j[0]??""),!Z&&!X)w.push("No pending release changesets were found.");return{success:j.length===0,errors:j,warnings:w,checks:W}}async function bB($,b){let n=$.join(b,".contractsrc.json");if(!await $.exists(n))return cA;try{let A=JSON.parse(await $.readFile(n)),m=SY.safeParse(A);return m.success?{...cA,...m.data.release}:cA}catch{return cA}}function ZY($){return $.length>0?"minor":"patch"}function XY($,b){return $.packages.map((A)=>b.find((m)=>m.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function YY($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Hb($,b,n,A){$.push({name:n,ok:b,message:A})}function hA($){return $ instanceof Error?$.message:String($)}var XB={};f(XB,{silentLogger:()=>yB,runWorkflow:()=>WB,loadWorkflows:()=>Uy,loadVibeConfig:()=>uA,installPack:()=>ZB,getWorkflow:()=>jB,exportContext:()=>mB,consoleLogger:()=>Jy,builtinWorkflows:()=>oA,DEFAULT_VIBE_CONFIG:()=>dA});import{existsSync as GY}from"fs";import{readFile as HY}from"fs/promises";import{join as Vy}from"path";import qY from"js-yaml";var dA={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function uA($){let b=$??process.cwd(),n=I(b)??b,A=[Vy(n,".contractspec","vibe","config.json"),Vy(n,".contractspec","vibe","config.yaml"),Vy(n,".contractspec","vibe","config.yml")],m={};for(let y of A)if(GY(y))try{let W=await HY(y,"utf-8");if(y.endsWith(".json"))m=JSON.parse(W);else m=qY.load(W);break}catch(W){console.warn(`Warning: Failed to parse ${y}`,W)}return{...dA,...m}}import{existsSync as OY}from"fs";import{copyFile as VY,mkdir as AB,readFile as JY,writeFile as UY}from"fs/promises";import{dirname as KY,join as qb}from"path";import{glob as _Y}from"glob";var zY=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function mB($){let b=$??process.cwd(),n=I(b)??b,A=await uA(b),m=qb(n,".contractspec","context"),y=qb(m,"files"),W=[...zY],w=qb(n,".gitignore");if(OY(w)){let G=(await JY(w,"utf-8")).split(`
|
|
2564
|
+
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));W=[...W,...G]}let j=A.contextExportAllowlist.length>0?A.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let Y of j){let G=await _Y(Y,{cwd:n,ignore:W,nodir:!0,dot:!0});B.push(...G)}let S=Array.from(new Set(B)).sort();if(S.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await AB(y,{recursive:!0});let Q=[];for(let Y of S){let G=qb(n,Y),V=qb(y,Y);await AB(KY(V),{recursive:!0}),await VY(G,V),Q.push({path:Y,size:0})}let Z=qb(m,"index.json"),X={generatedAt:new Date().toISOString(),files:Q.map((Y)=>Y.path),config:{allowlist:A.contextExportAllowlist,ignores:W.length}};return await UY(Z,JSON.stringify(X,null,2)),{success:!0,files:S,indexPath:Z}}var oA=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and generate artifacts.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
|
|
2149
2565
|
Please review them and move selected files to contracts/ directory.
|
|
2150
|
-
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:"
|
|
2151
|
-
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${
|
|
2152
|
-
`);let
|
|
2153
|
-
\uD83D\uDC49 Step: ${
|
|
2566
|
+
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"release",label:"Prepare Release",command:"contractspec release prepare"},{id:"publish",label:"Publish to Registry",command:'echo "Publishing..." && contractspec registry publish',tracks:["product","regulated"]}]},{id:"migration",name:"Migration: Upgrades",description:"Run migration scripts and verify integrity.",steps:[{id:"upgrade",label:"Upgrade Dependencies",command:"contractspec upgrade"},{id:"generate",label:"Regenerate Artifacts",command:"contractspec generate"},{id:"verify",label:"Verify Integrity",command:"contractspec ci"}]}];import{spawn as LY}from"child_process";var yB={log:()=>{},warn:()=>{},error:()=>{}},Jy={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function WB($,b,n){let A=n?.logger??Jy,m=n?.prompter;if(A.log(`
|
|
2567
|
+
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${b.track}`),b.dryRun)A.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2568
|
+
`);let y={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let W of $.steps){let w={id:W.id,name:W.label,status:"skip",command:W.command};if(W.tracks&&!W.tracks.includes(b.track)){y.steps.push(w);continue}if(W.condition){if(!await W.condition(b)){y.steps.push(w);continue}}if(A.log(`
|
|
2569
|
+
\uD83D\uDC49 Step: ${W.label}`),b.dryRun&&W.command)A.log(` Command: ${W.command}`);if(W.manualCheckpoint){if(b.dryRun)A.warn(" [Manual Checkpoint] Would pause here for user input.");else if(m){if(W.manualMessage)A.log(W.manualMessage);let j=await m.select({message:"Checkpoint action:",choices:[{name:"Proceed",value:"proceed",description:"Run this step"},{name:"Skip Step",value:"skip",description:"Skip this step and continue"},{name:"Abort Workflow",value:"abort",description:"Exit workflow"}]});if(j==="abort")return A.warn("Workflow aborted by user."),y.success=!1,y.steps.push({...w,status:"skip",error:"Aborted by user"}),y;if(j==="skip"){A.warn(" \u2192 Skipped by user."),y.steps.push(w);continue}}}if(!b.dryRun)try{if(W.execute)await W.execute(b);else if(W.command)await RY(W.command,b.root);w.status="pass",y.stepsExecuted.push(W.id),y.steps.push(w),A.log(" \u2713 Completed")}catch(j){let B=j instanceof Error?j.message:String(j);return A.error(` \u274C Failed: ${B}`),y.success=!1,y.error=j instanceof Error?j:Error(String(j)),w.status="fail",w.error=B,y.stepsExecuted.push(W.id),y.steps.push(w),y}else y.steps.push(w)}return y}async function RY($,b){let n=$.split(" "),A=n[0],m=n.slice(1);if(!A)throw Error("Invalid command");return new Promise((y,W)=>{let w=LY(A,m,{cwd:b,stdio:"inherit",shell:!0});w.on("error",W),w.on("exit",(j)=>{if(j===0)y();else W(Error(`Command exited with code ${j}`))})})}import{existsSync as CY}from"fs";import{readdir as xY,readFile as IY}from"fs/promises";import{join as wB}from"path";import EY from"js-yaml";async function Uy($){let b=[...oA],n=$??process.cwd(),A=I(n)??n,m=wB(A,".contractspec","vibe","workflows");if(CY(m))try{let y=await xY(m);for(let W of y)if(W.endsWith(".json")||W.endsWith(".yaml")||W.endsWith(".yml")){let w=await IY(wB(m,W),"utf-8");try{let j;if(W.endsWith(".json"))j=JSON.parse(w);else j=EY.load(w);if(j.id&&j.steps)b.push(j)}catch(j){console.warn(`Failed to parse workflow ${W}:`,j)}}}catch(y){console.warn("Error loading user workflows:",y)}return b}async function jB($,b){return(await Uy(b)).find((A)=>A.id===$)}import{existsSync as Ky}from"fs";import{copyFile as BB,mkdir as SB,readdir as QB,stat as MY}from"fs/promises";import{join as N$,resolve as TY}from"path";async function ZB($,b){let n=b??process.cwd(),A=I(n)??n;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let m=TY(n,$);if(!Ky(m))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${m}`};let y=0,W=0,w=N$(m,"workflows");if(Ky(w)){let B=N$(A,".contractspec","vibe","workflows");await SB(B,{recursive:!0});let S=await QB(w);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await BB(N$(w,Q),N$(B,Q)),y++}let j=N$(m,"templates");if(Ky(j)){let B=N$(A,".contractspec","vibe","templates");await SB(B,{recursive:!0});let S=await QB(j);for(let Q of S){let Z=N$(j,Q),X=N$(B,Q);if((await MY(Z)).isFile())await BB(Z,X),W++}}return{success:!0,workflowsInstalled:y,templatesInstalled:W}}import{loadSpecFromSource as DY}from"@contractspec/module.workspace";var YB=["product","eng","qa"];function NY($){return YB.includes($)}async function DM($,b){if(!NY(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${YB.join(", ")}`);let n,A,m;if(b.specFiles&&b.specFiles.length>0)n=b.specFiles;else{let W=await FY($,{baseline:b.baseline});if(A=W.totalSpecs,m=W.changedFilesCount,b.baseline){if(W.changedFilesCount===0)return{views:[],totalSpecs:A,changedFilesCount:0,status:"no_changes"};if(W.specFiles.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_changed_specs"}}n=W.specFiles}if(n.length===0)return{views:[],totalSpecs:A,changedFilesCount:m,status:"no_specs"};let y=[];for(let W of n){let w=await vY(W,b.audience,$);y.push({filePath:W,content:w})}return{views:y,totalSpecs:A,changedFilesCount:m,status:"success"}}async function FY($,b={}){let A=(await j$({fs:$.fs})).map((w)=>w.filePath),m=A.length;if(!b.baseline)return{specFiles:A,totalSpecs:m};let y=await $.git.diffFiles(b.baseline);if(y.length===0)return{specFiles:[],totalSpecs:m,changedFilesCount:0,hasChanges:!1};let W=A.filter((w)=>y.some((j)=>w.endsWith(j)||j.endsWith(w)||w.includes(j)||j.includes(w)));return{specFiles:W,totalSpecs:m,changedFilesCount:y.length,hasChanges:W.length>0}}async function vY($,b,n){if(!await n.fs.exists($))throw Error(`File not found: ${$}`);let A=await DY($);if(A.length===0)return`No specs found in ${$} (Parse result empty)`;return A.map((m)=>gY(m,b)).join(`
|
|
2154
2570
|
|
|
2155
2571
|
---
|
|
2156
2572
|
|
|
2157
|
-
`)}function
|
|
2158
|
-
`)}function
|
|
2573
|
+
`)}function gY($,b){let n=[];switch(b){case"product":PY($,n);break;case"eng":kY($,n);break;case"qa":rY($,n);break}return n.join(`
|
|
2574
|
+
`)}function PY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2159
2575
|
${$.meta.goal}
|
|
2160
|
-
`);if($.meta.context)
|
|
2576
|
+
`);if($.meta.context)b.push(`### Context
|
|
2161
2577
|
${$.meta.context}
|
|
2162
|
-
`);if($.specType==="feature"){if($.operations?.length)
|
|
2163
|
-
`);if($.testRefs?.length)
|
|
2164
|
-
`)}export{
|
|
2578
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((n)=>b.push(`- **${n.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- \u2705 Enforces Business Policies");if($.hasIo)b.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((n)=>b.push(`- **${n.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function kY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((n)=>b.push(`- \`${n.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function rY($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2579
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((n)=>b.push(`- \uD83E\uDDEA \`${n.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((n)=>b.push(`- [ ] Verify event \`${n.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((n)=>b.push(`- [ ] Test Operation flow: \`${n.name}\``));if($.presentations?.length)$.presentations.forEach((n)=>b.push(`- [ ] Test UI Component: \`${n.name}\``))}}function gM($,b,n,A){let{watcher:m,fs:y,logger:W}=$,w=m.watch(n),j=A?.validate??(async(S)=>{await l$(S,{fs:y,logger:W})}),B=A?.build??(async(S)=>{await yb(S,{fs:y,logger:W},b)});return w.on(async(S)=>{if(S.type!=="change")return;if(W.info("watchSpecs.changed",{path:S.path}),n.runValidate)await j(S.path);if(n.runBuild)if(n.dryRun)W.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),w}async function rM($,b,n={}){let A=(n.getWorkspaceInfo??cy)(b),m=$.join(A.workspaceRoot,".contractsrc.json"),y=$.join(A.packageRoot,".contractsrc.json"),W=await $.exists(m),w=A.workspaceRoot!==A.packageRoot?await $.exists(y):!1,j;if(W)try{let B=await $.readFile(m),S=JSON.parse(B);if(S.packages||S.excludePackages||S.recursive)j={packages:S.packages,excludePackages:S.excludePackages,recursive:S.recursive}}catch{}return{...A,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?y:void 0}}async function fM($,b){let n=[],A=$.join(b,".contractsrc.json");if(await $.exists(A))n.push(A);let m=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let y of m)if(y!==A)n.push(y);return n}async function cM($,b,n){let A={};if(b&&await $.exists(b))try{let m=await $.readFile(b);A=JSON.parse(m)}catch{}if(n&&await $.exists(n))try{let m=await $.readFile(n),y=JSON.parse(m);A=GB(A,y)}catch{}return A}function GB($,b){let n={...$};for(let A of Object.keys(b)){let m=$[A],y=b[A];if(typeof m==="object"&&m!==null&&!Array.isArray(m)&&typeof y==="object"&&y!==null&&!Array.isArray(y))n[A]=GB(m,y);else n[A]=y}return n}function hM($){let b=[];if(b.push(`Package Manager: ${$.packageManager}`),b.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(b.push("Monorepo: Yes"),b.push(`Package Root: ${$.packageRoot}`),$.packageName)b.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)b.push(`Package Patterns: ${$.packages.join(", ")}`)}else b.push("Monorepo: No");if($.workspaceConfigPath)b.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)b.push(`Package Config: ${$.packageConfigPath}`);return b.join(`
|
|
2580
|
+
`)}export{gM as watchSpecs,XB as vibe,nB as versioning,wX as verifyWithAIEnhanced,mn as verifyWithAI,yn as verifyStructure,CX as verifyService,N1 as verifySemanticFields,_7 as verifyImportedContracts,YR as verifyImplementationAgainstParsedSpec,DA as verifyBehavior,kx as validateTenantConfig,Dx as validateSpecs,l$ as validateSpec,$1 as validateScannedSpec,zx as validatePackageScaffold,Ox as validateImplementationWithAgent,nA as validateImplementationFiles,Tx as validateDiscoveredSpecs,Yx as validateBlueprint,NY as validateAudience,Ez as validateAgainstOpenApiService,aW as utils,z1 as upgrade,YI as updateSpec,QQ as toKebabCase,dW as templates,Cz as syncWithOpenApiService,px as syncSpecs,$X as stringToCacheKey,ny as setupUsageMd,ZA as setupGitignore,pm as setupAgentsMd,ZC as searchRegistry,a as safeParseJson,mI as runTests,yI as runTestSpecs,sC as runSetup,sR as runQuickstart,Jw as runDoctor,sU as runCIChecks,Aw as resolveSetupTargets,R$ as resolveSetupPreset,tm as resolveRegistryUrl,qQ as resolveImplementations,J0 as resolveDefaultBuildTargets,rj as resolveAuthoredModuleValue,Tw as resolveAllImplementations,$n as renderManagedMarkdownBlock,ey as prompts,ry as parseGitModules,Iw as parseExplicitImplementations,cw as packageDeclarations,k3 as operationRegistry,oj as onboarding,lm as normalizeMarkdownContent,FT as module,cM as mergeMonorepoConfigs,zA as mergeManagedMarkdown,T4 as mergeGitignoreContent,P as loadWorkspaceConfig,dV as loadPackageAuthoredDocBlocks,Pj as loadAuthoredModuleValue,IR as loadAuthoredModuleIfExists,UA as loadAuthoredModuleExports,y$ as loadAuthoredModule,hV as loadAuthoredDocBlocksFromSourceFiles,WI as listTests,FY as listSpecsForView,j$ as listSpecs,QC as listFromRegistry,G0 as listAgentTypes,Vb as isMonorepo,$C as isContractSpecInstalled,kO as isConnectPreset,PO as isBuilderPreset,Eb as inferSetupPresetFromConfig,SQ as inferImplementationType,H7 as importFromSourceService,zj as importFromOpenApiService,sw as impact,Fj as hooks,sJ as groupSpecsByType,bS as getWorkspacePackages,cy as getWorkspaceInfo,LG as getRunCommand,om as getProductionDependencies,g$ as getPackageName,AS as getMetaRepoInfo,hy as getInstallCommand,JJ as getImplementationSummary,UO as getGraphStats,rM as getExtendedWorkspaceInfo,RG as getExecCommand,im as getDevDependencies,um as getDependencies,xw as getConventionPaths,VO as getContractNode,ln as getClaudeDesktopConfigPath,T0 as getBuilderRuntimeModeForPreset,mw as getBuilderBootstrapPresetForSetupPreset,tW as getApiKey,fJ as getAllSpecs,AV as getAllLayerLocations,Ub as getAgentAdapter,m0 as getAIProvider,Cn as genericMCPAdapter,hW as generateWorkflowSpec,kn as generateWorkflowRunnerTemplate,Nn as generateWorkflowDevkitWorkflowTemplate,gn as generateWorkflowDevkitStreamRouteTemplate,Fn as generateWorkflowDevkitStartRouteTemplate,Pn as generateWorkflowDevkitGenericTemplate,vn as generateWorkflowDevkitFollowUpRouteTemplate,tn as generateVscodeSettings,HW as generateVisualizationSpec,DM as generateViews,vY as generateView,Sw as generateUsageGuide,YW as generateTranslationSpec,cW as generateThemeSpec,DW as generateTestTemplate,XW as generateTestSpec,fW as generateTelemetrySpec,OW as generateProductIntentSpec,rW as generatePresentationSpec,ZW as generatePolicySpec,kW as generateOperationSpec,PW as generateMigrationSpec,ZR as generateMermaidDiagram,U7 as generateMarkdownReport,vW as generateKnowledgeSpaceSpec,GW as generateJobSpec,FW as generateIntegrationSpec,JW as generateHarnessSuiteSpec,VW as generateHarnessScenarioSpec,MW as generateHandlerTemplate,I7 as generateGuideFromParsedSpec,EW as generateFormSpec,IW as generateFeatureSpec,VR as generateFeatureContextMarkdown,xW as generateExperimentSpec,In as generateExampleSpec,CW as generateEventSpec,_w as generateDocsFromSpecs,RW as generateDataViewSpec,Tn as generateDataViewRendererTemplate,E7 as generateCursorRulesFromParsedSpec,jw as generateCursorRules,Mb as generateCursorMcpConfig,Wb as generateContractsrcConfig,TW as generateComponentTemplate,K7 as generateCliReport,ww as generateClaudeMcpConfig,QW as generateCapabilitySpec,Lw as generateArtifacts,LW as generateAppBlueprintSpec,Bw as generateAgentsGuide,qW as generateAgentSpec,bW as formatters,hM as formatWorkspaceInfo,GR as formatVerificationReport,bC as formatQuickstartPreview,kj as formatModuleLoadError,N as formatJson,kL as formatFiles,TV as formatDoctorSummary,DV as formatCheckResult,Ej as fix,I as findWorkspaceRoot,c as findPackageRoot,fy as findMetaRepoRoot,fM as findAllConfigFiles,cJ as filterIssuesByType,hJ as filterIssuesBySeverity,Rj as features,Rw as extractSpecReferences,rz as extractContracts,JR as exportSpecForLLM,R6 as exportOpenApi,JO as exportGraphAsDot,oW as ensurePackageScaffold,cn as discoverSpecs,c$ as discoverSpecFiles,an as discoverLayers,AA as discoverImplementationsForSpec,GJ as discoverAllImplementations,Ew as determineStatus,mS as detectRepositoryType,a$ as detectPackageManager,Qz as deleteSpec,b$ as deepMergePreserve,D0 as deepMergeOverwrite,Ln as cursorCLIAdapter,PI as createWorkspaceStateCacheStorage,xS as createWorkspaceRegistry,RX as createVerifyService,iI as createVerificationCacheService,yz as createSpecCreator,yw as createSetupNextSteps,Ww as createSetupGitignorePatterns,jC as createRegeneratorService,TA as createQuickAIReview,rn as createPackageTargetSpecSource,Fy as createNoopLoggerAdapter,vy as createNodeWatcherAdapter,Dy as createNodeGitAdapter,Ey as createNodeFsAdapter,Ry as createNodeAiAdapter,YG as createNodeAdapters,vI as createInMemoryCacheStorage,NI as createFileSystemCacheStorage,O9 as createEmptyLayerInventory,Ny as createConsoleLoggerAdapter,JG as createBunFsAdapter,p8 as createBuilderWorkspaceId,W5 as createAgentGuideService,Vj as connect,E1 as computeContentHash,Yz as compareSpecs,wK as cleanArtifacts,_n as claudeCodeAdapter,M1 as cacheKeyToString,yb as buildSpec,dn as analyzeWorkspaceDocBlocks,mA as analyzeIntegrity,hL as analyzeGap,eW as analyzeDeps,w5 as agentGuideService,Y0 as agentAdapters,X0 as adoption,SC as addToRegistry,ER as __moduleLoaderInternals,x1 as WorkspaceStateCacheStorage,_3 as WorkspaceBundle,NA as VerifyService,T1 as VerificationCacheService,YB as VALID_AUDIENCES,X2 as TestGeneratorService,Uj as SpecCreatorService,qn as SimpleAgent,sW as SETUP_TARGET_LABELS,bw as SETUP_PRESET_LABELS,nw as SETUP_PRESET_DESCRIPTIONS,Ib as SETUP_GITIGNORE_PATTERNS,AZ as RuleSyncService,_A as RegistryClient,MS as PrActionService,Hn as OpenAICodexAgent,ij as MINIMAL_DEPENDENCIES,C1 as InMemoryCacheStorage,Rn as GenericMCPAdapter,R1 as FileSystemCacheStorage,a7 as FULL_DEPENDENCIES,IS as DriftActionService,q$ as DEFAULT_SPEC_PATTERNS,v$ as DEFAULT_FS_IGNORES,I1 as DEFAULT_CACHE_CONFIG,zn as CursorCLIAdapter,Gn as CursorAgent,Yn as ClaudeCodeAgent,Kn as ClaudeCodeAdapter,SZ as CONTRACTSPEC_USAGE_BLOCK_START,QZ as CONTRACTSPEC_USAGE_BLOCK_END,yZ as CONTRACTSPEC_AGENTS_BLOCK_START,WZ as CONTRACTSPEC_AGENTS_BLOCK_END,nK as CI_CHECK_CATEGORY_LABELS,Vw as CHECK_CATEGORY_LABELS,On as AgentOrchestrator,xn as AgentGuideService,xb as ALL_SETUP_TARGETS,$w as ALL_SETUP_PRESETS,bK as ALL_CI_CHECK_CATEGORIES,Ow as ALL_CHECK_CATEGORIES,GA as AIGenerator};
|