@contractspec/bundle.workspace 4.4.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +873 -552
- package/dist/node/index.js +873 -552
- 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 +3 -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/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/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/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/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 +10 -9
package/dist/node/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)){if(!
|
|
3
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
4
|
-
`).map((
|
|
1
|
+
import{createRequire as d1}from"node:module";var f1=Object.defineProperty;var h1=($)=>$;function c1($,b){this[$]=h1.bind(null,b)}var P=($,b)=>{for(var A in b)f1($,A,{get:b[A],enumerable:!0,configurable:!0,set:c1.bind(b,A)})};var $W=($,b)=>()=>($&&(b=$($=0)),b);var M$=d1(import.meta.url);import{ContractsrcSchema as k8,DEFAULT_CONTRACTSRC as MA}from"@contractspec/lib.contracts-spec/workspace-config";async function g($,b){let A=$.join(b??".",".contractsrc.json");if(!await $.exists(A))return MA;try{let n=await $.readFile(A),W=JSON.parse(n),w=k8.safeParse(W);return{...MA,...w.data,conventions:{...MA.conventions,...w.data?.conventions||{}}}}catch{return MA}}function Rw($){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 s=()=>{};var dj={};P(dj,{AIGenerator:()=>A0});import{createProvider as O4}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as V4,buildEventSpecPrompt as J4,buildFormPrompt as K4,buildHandlerPrompt as _4,buildOperationSpecPrompt as U4,buildPresentationSpecPrompt as z4,buildTestPrompt as L4,getCodeGenSystemPrompt as Pb,getSystemPrompt as wn}from"@contractspec/module.workspace";import{generateObject as jn,generateText as b0,streamText as R4}from"ai";import*as R from"zod";class A0{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,b=this.config.customApiKey||Rw(this.config.aiProvider),A={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:b,baseUrl:this.config.customEndpoint||void 0};return O4(A).getModel()}async generateOperationSpec($,b){let A=this.getModel(),m=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([])}),n=U4($,b);return(await jn({model:A,schema:m,prompt:n,system:wn()})).object}async generateEventSpec($){let b=this.getModel(),A=R.object({name:R.string().describe('Dot notation name like "domain.event_name"'),version:R.number().int().positive().default(1),description:R.string().describe("When this event is emitted"),stability:R.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:R.array(R.string()).default([]),tags:R.array(R.string()).default([]),payloadShape:R.string().describe("Description of event payload"),piiFields:R.array(R.string()).describe("PII field paths").default([])}),m=J4($);return(await jn({model:b,schema:A,prompt:m,system:wn()})).object}async generatePresentationSpec($,b){let A=this.getModel(),m=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()}),n=z4($,b);return(await jn({model:A,schema:m,prompt:n,system:wn()})).object}async generateHandler($){let b=this.getModel();return(await b0({model:b,prompt:_4($),system:Pb()})).text}async generateComponent($){let b=this.getModel();return(await b0({model:b,prompt:V4($),system:Pb()})).text}async generateForm($){let b=this.getModel();return(await b0({model:b,prompt:K4($),system:Pb()})).text}async generateTests($,b,A){let m=this.getModel();return(await b0({model:m,prompt:L4($,b,A),system:Pb()})).text}async streamCodeGeneration($,b){let A=this.getModel(),m=await R4({model:A,prompt:$,system:Pb()}),n="";for await(let W of m.textStream)n+=W,b(W);return n}}var m0=$W(()=>{s()});import*as Zx from"@contractspec/module.workspace";import{anthropic as u1}from"@ai-sdk/anthropic";import{openai as bW}from"@ai-sdk/openai";import{DEFAULT_MODELS as AW}from"@contractspec/lib.ai-providers/models";import{generateObject as o1,generateText as i1,streamText as l1}from"ai";import{ollama as t1}from"ollama-ai-provider";function mW($){return{async validateProvider(b){try{let{aiProvider:A}=b;if(A==="ollama")return{success:!0};if(A==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(A==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(A){return{success:!1,error:A instanceof Error?A.message:String(A)}}},async generateText(b){let A=N0($);return{text:(await i1({model:A,prompt:b.prompt,system:b.systemPrompt})).text}},async generateStructured(b){let m={model:N0($),schema:b.schema,prompt:b.prompt,system:b.systemPrompt};return{object:(await o1(m)).object}},async streamText(b,A){let m=N0($),n=await l1({model:m,prompt:b.prompt,system:b.systemPrompt}),W="";for await(let w of n.textStream)W+=w,A(w);return W}}}function N0($){let{aiProvider:b,aiModel:A,customEndpoint:m}=$;switch(b){case"claude":{let n=A??AW.anthropic;return u1(n)}case"openai":{let n=A??AW.openai;return bW(n)}case"ollama":return t1(A??"codellama");case"custom":{if(!m)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return bW(A??"default")}default:throw Error(`Unknown AI provider: ${b}`)}}import{DEFAULT_CONTRACTSRC as QB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as p1,stat as a1,mkdir as nW,readFile as e1,rm as s1,writeFile as $B}from"node:fs/promises";import{basename as bB,dirname as WW,isAbsolute as AB,join as mB,relative as nB,resolve as wW}from"node:path";import{glob as WB}from"glob";var X$=["**/*.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","**/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"],x$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function jW($){let b=$??process.cwd();return{async exists(m){try{return await p1(A(m)),!0}catch{return!1}},async readFile(m){return e1(A(m),"utf-8")},async writeFile(m,n){let W=A(m),w=WW(W);await nW(w,{recursive:!0}),await $B(W,n,"utf-8")},async remove(m){await s1(A(m),{recursive:!0,force:!0})},async stat(m){let n=await a1(A(m));return{size:n.size,isFile:n.isFile(),isDirectory:n.isDirectory(),mtime:n.mtime}},async mkdir(m){await nW(A(m),{recursive:!0})},async glob(m){let n=m.patterns??(m.pattern?[m.pattern]:X$),W=m.ignore??x$,w=m.cwd??b,j=m.absolute??!0;return(await WB(n,{cwd:w,ignore:W,absolute:j})).sort((B,S)=>B.localeCompare(S))},resolve(...m){let[n,...W]=m;if(!n)return b;return wW(b,n,...W)},dirname(m){return WW(m)},basename(m){return bB(m)},join(...m){return mB(...m)},relative(m,n){return nB(m,n)}};function A(m){return AB(m)?m:wW(b,m)}}import{execFileSync as Zb}from"node:child_process";import{access as wB}from"node:fs/promises";import{resolve as yW}from"node:path";function BW($){let b=$??process.cwd();return{async currentBranch(){try{let A=Zb("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();return A.length>0?A:void 0}catch{return}},async showFile(A,m){try{return Zb("git",["show",`${A}:${m}`],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}catch(n){throw Error(`Could not load ${m} at ref ${A}: ${n instanceof Error?n.message:String(n)}`)}},async clean(A){let m=[];if(A?.force)m.push("-f");if(A?.directories)m.push("-d");if(A?.ignored)m.push("-x");if(A?.dryRun)m.push("--dry-run");Zb("git",["clean",...m],{cwd:b,stdio:"inherit"})},async isGitRepo(A){let m=A?yW(b,A):b;try{return await wB(yW(m,".git")),!0}catch{return!1}},async log(A){let m=A??"HEAD~10",n="--format=%H|||%s|||%an|||%aI";try{let W=Zb("git",["log",`${m}..HEAD`,"--format=%H|||%s|||%an|||%aI"],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}),w=[];for(let j of W.trim().split(`
|
|
2
|
+
`)){if(!j)continue;let[y,B,S,Q]=j.split("|||");if(y&&B)w.push({hash:y,message:B,author:S,date:Q})}return w}catch{return[]}},async diffFiles(A,m){try{let n=m&&m.length>0?["--",...m]:[];return Zb("git",["diff","--name-only",`${A}...HEAD`,...n],{cwd:b,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim().split(`
|
|
3
|
+
`).filter(Boolean)}catch{return[]}}}}function SW(){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 jB()}}}function QW(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:yB}}function jB(){return{start($){console.warn(`⏳ ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`✅ ${$??"Done"}`)},fail($){console.error(`❌ ${$??"Failed"}`)},warn($){console.warn(`⚠️ ${$??"Warning"}`)},stop(){}}}function yB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import BB from"chokidar";var SB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function ZW($){let b=$??process.cwd();return{watch(A){let m=[],n,W=BB.watch(A.pattern,{cwd:b,ignored:A.ignore??SB,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),w=(j)=>{if(A.debounceMs&&A.debounceMs>0)clearTimeout(n),n=setTimeout(()=>{m.forEach((y)=>y(j))},A.debounceMs);else m.forEach((y)=>y(j))};return W.on("add",(j)=>{w({type:"add",path:j})}),W.on("change",(j)=>{w({type:"change",path:j})}),W.on("unlink",(j)=>{w({type:"unlink",path:j})}),{on(j){m.push(j)},async close(){clearTimeout(n),await W.close()}}}}}function HX($={}){let{cwd:b,config:A,silent:m}=$,n=A??QB;return{fs:jW(b),git:BW(b),watcher:ZW(b),ai:mW(n),logger:m?QW():SW()}}import{stat as ZB,mkdir as GB}from"node:fs/promises";import{basename as XB,dirname as YB,isAbsolute as HB,join as qB,relative as OB,resolve as GW}from"node:path";import{glob as VB}from"glob";function _X($){let b=$??process.cwd();return{async exists(m){let n=Bun.file(A(m));try{return await n.exists(),!0}catch{return!1}},async readFile(m){return Bun.file(A(m)).text()},async writeFile(m,n){let W=A(m);await Bun.write(W,n)},async remove(m){await Bun.file(A(m)).delete()},async stat(m){let n=await ZB(A(m));return{size:n.size,isFile:n.isFile(),isDirectory:n.isDirectory(),mtime:n.mtime}},async mkdir(m){await GB(A(m),{recursive:!0})},async glob(m){let n=m.patterns??(m.pattern?[m.pattern]:X$),W=m.ignore??x$,w=m.cwd??b,j=m.absolute??!0;return await VB(n,{cwd:w,ignore:W,absolute:j})},resolve(...m){let[n,...W]=m;if(!n)return b;return GW(b,n,...W)},dirname(m){return YB(m)},basename(m){return XB(m)},join(...m){return qB(...m)},relative(m,n){return OB(m,n)}};function A(m){return HB(m)?m:GW(b,m)}}import{existsSync as d,readFileSync as K$}from"node:fs";import{tmpdir as JB}from"node:os";import{dirname as F0,isAbsolute as KB,join as c,relative as _B,resolve as u$}from"node:path";var XW={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},YW=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function UB($,b){let A=_B(b,$);return A===""||!A.startsWith("..")&&!KB(A)}function v0($){let b=u$($),A=u$(JB());return UB(b,A)?A:void 0}function r($=process.cwd()){let b=u$($),A=v0($);while(!0){if(d(c(b,"package.json")))return b;let m=F0(b);if(m===b||b===A)break;b=m}return $}function M($=process.cwd()){let b=u$($),A=null,m=v0($);while(!0){for(let w of YW)if(d(c(b,w)))return b;let n=c(b,"package.json");if(d(n)){A=b;try{if(JSON.parse(K$(n,"utf-8")).workspaces)return b}catch{}}for(let w of Object.keys(XW))if(d(c(b,w)))return b;let W=F0(b);if(W===b||b===m)break;b=W}return A??$}function o$($=process.cwd()){let b=["bun","pnpm","yarn","npm"];for(let m of b){let n=Object.entries(XW).filter(([,W])=>W===m);for(let[W]of n)if(d(c($,W)))return m}let A=c($,"package.json");if(d(A))try{let m=JSON.parse(K$(A,"utf-8"));if(m.packageManager){let n=m.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(n)return n[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function Gb($=process.cwd()){for(let A of YW)if(d(c($,A)))return!0;let b=c($,"package.json");if(d(b))try{if(JSON.parse(K$(b,"utf-8")).workspaces)return!0}catch{}return!1}function zB($){let b=c($,"pnpm-workspace.yaml");if(d(b))try{let n=K$(b,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(n?.[1])return n[1].split(`
|
|
4
|
+
`).map((w)=>w.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let A=c($,"package.json");if(d(A))try{let m=JSON.parse(K$(A,"utf-8"));if(Array.isArray(m.workspaces))return m.workspaces;if(m.workspaces?.packages&&Array.isArray(m.workspaces.packages))return m.workspaces.packages}catch{}return}function T$($){let b=c($,"package.json");if(d(b))try{return JSON.parse(K$(b,"utf-8")).name}catch{}return}function HW($){let b=c($,".gitmodules");if(!d(b))return[];try{let A=K$(b,"utf-8"),m=[],n=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,W;while((W=n.exec(A))!==null){let[,w,j,y]=W;if(w&&j&&y){let B=c($,j),S=d(c(B,"package.json"))&&LB(B);m.push({name:w,path:j,url:y,absolutePath:B,hasWorkspaces:S})}}return m}catch{return[]}}function LB($){let b=c($,"package.json");if(d(b))try{let A=JSON.parse(K$(b,"utf-8"));return Boolean(A.workspaces)}catch{}return d(c($,"pnpm-workspace.yaml"))}function qW($){let b=u$($),A=v0($);while(!0){if(d(c(b,".gitmodules")))return b;let m=F0(b);if(m===b||b===A)break;b=m}return}function RB($){let b=qW($);if(!b)return;let A=HW(b);if(A.length===0)return;let m=u$($),n=A.find((W)=>m.startsWith(W.absolutePath));return{root:b,submodules:A,activeSubmodule:n}}function CB($,b){let A=qW($);if(A){if(HW(A).length>0)return"meta-repo"}if(b)return"monorepo";return"classic"}function OW($=process.cwd()){let b=r($),A=M($),m=o$(A),n=Gb(A),W=n?zB(A):void 0,w=T$(b),j=CB($,n),y=j==="meta-repo"?RB($):void 0;return{packageManager:m,workspaceRoot:A,packageRoot:b,isMonorepo:n,packages:W,packageName:w,repositoryType:j,metaRepo:y}}function CX($,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 IX($,b){switch($){case"bun":return`bunx ${b}`;case"pnpm":return`pnpm exec ${b}`;case"yarn":return`yarn ${b}`;case"npm":return`npx ${b}`}}function VW($,b=!1){let A=b?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${A}`.trim();case"pnpm":return`pnpm add ${A}`.trim();case"yarn":return`yarn add ${A}`.trim();case"npm":return`npm install ${A}`.trim()}}import{anthropic as JW}from"@ai-sdk/anthropic";import{generateText as KW}from"ai";class WA{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=JW("claude-3-7-sonnet-20250219"),A=this.buildSystemPrompt($),m=this.buildUserPrompt($),n=await KW({model:b,prompt:m,system:A,temperature:0.2});return{success:!0,code:this.extractCode(n.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:n.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=JW("claude-3-7-sonnet-20250219"),A=`
|
|
5
5
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
6
6
|
|
|
7
7
|
SPECIFICATION:
|
|
@@ -30,7 +30,7 @@ Provide a structured validation report:
|
|
|
30
30
|
- Are there any missing edge cases?
|
|
31
31
|
|
|
32
32
|
Be thorough and precise. Use a critical but constructive tone.
|
|
33
|
-
`,
|
|
33
|
+
`,m=await KW({model:b,prompt:A,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),n=this.detectIssues(m.text);return{success:!n,code:m.text,errors:n?this.extractErrors(m.text):[],warnings:this.extractWarnings(m.text),suggestions:this.extractSuggestions(m.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
34
34
|
|
|
35
35
|
Your code is:
|
|
36
36
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -50,7 +50,7 @@ Your code is:
|
|
|
50
50
|
- Following SOLID principles and best practices
|
|
51
51
|
- Modular and testable
|
|
52
52
|
|
|
53
|
-
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let
|
|
53
|
+
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let b={generate:`Generate a complete, production-ready implementation for this specification:
|
|
54
54
|
|
|
55
55
|
${$.specCode}
|
|
56
56
|
|
|
@@ -73,10 +73,10 @@ Spec:
|
|
|
73
73
|
${$.specCode}
|
|
74
74
|
|
|
75
75
|
Code:
|
|
76
|
-
${$.existingCode}`};return
|
|
77
|
-
`);for(let
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
76
|
+
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],A=$.toLowerCase();return b.some((m)=>A.includes(m))}extractErrors($){let b=[],A=$.split(`
|
|
77
|
+
`);for(let m of A){let n=m.toLowerCase();if(n.includes("error")||n.includes("bug")||n.includes("incorrect")||n.includes("missing"))b.push(m.trim())}return b.length>0?b:["Code review identified issues"]}extractWarnings($){let b=[],A=$.split(`
|
|
78
|
+
`);for(let m of A){let n=m.toLowerCase();if(n.includes("warning")||n.includes("should")||n.includes("consider"))b.push(m.trim())}return b}extractSuggestions($){let b=[],A=$.split(`
|
|
79
|
+
`);for(let m of A){let n=m.toLowerCase();if(n.includes("suggest")||n.includes("recommend")||n.includes("could")||n.includes("improvement"))b.push(m.trim())}return b}}import{spawn as IB}from"child_process";import{existsSync as _W}from"fs";import{mkdir as UW,readFile as EB,rm as MB,writeFile as Z$}from"fs/promises";import{homedir as g0,tmpdir as zW}from"os";import{join as u}from"path";class wA{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=u(zW(),`cursor-agent-${Date.now()}`);await UW(b,{recursive:!0});let A=await this.executeWithBestMethod($,b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=u(zW(),`cursor-validate-${Date.now()}`);await UW(b,{recursive:!0}),await this.setupValidationWorkspace($,b);let A=await this.executeWithBestMethod({...$,type:"validate"},b);return await this.cleanupWorkDir(b),A}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes("Cursor")||process.env.VSCODE_CWD?.includes("Windsurf"));let $=["/usr/local/bin/cursor","/Applications/Cursor.app/Contents/MacOS/Cursor","/Applications/Windsurf.app/Contents/MacOS/Windsurf",u(g0(),".cursor","cursor"),u(g0(),"AppData","Local","Programs","cursor","Cursor.exe"),u(g0(),"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(_W(b)){this.cursorPath=b;break}}catch{continue}}async executeWithBestMethod($,b){let A=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,b)},{name:"file-based",fn:()=>this.useFileBasedApproach($,b)}];for(let m of A)try{let n=await m.fn();if(n.success)return n}catch(n){continue}return{success:!1,warnings:["Cursor agent could not connect to IDE.","Ensure Cursor/Windsurf is running with API enabled.","Falling back to simple agent mode is recommended."],errors:["All Cursor integration methods failed"],metadata:{agentMode:"cursor",status:"unavailable",suggestion:"Use --agent-mode claude-code or --agent-mode simple"}}}async useCursorCLI($,b){if(!this.cursorPath)throw Error("Cursor executable not found");let A=u(b,"spec.ts"),m=u(b,"output.ts"),n=u(b,"INSTRUCTIONS.md");if(await Z$(A,$.specCode),await Z$(n,this.buildDetailedPrompt($)),$.existingCode)await Z$(u(b,"existing.ts"),$.existingCode);return new Promise((W,w)=>{let j=["--wait","--new-window",b],y=IB(this.cursorPath,j,{cwd:b,stdio:"pipe",detached:!1}),B="",S="";y.stdout?.on("data",(Q)=>{B+=Q.toString()}),y.stderr?.on("data",(Q)=>{S+=Q.toString()}),y.on("error",(Q)=>{w(Q)}),y.on("close",async(Q)=>{if(_W(m))try{let Z=await EB(m,"utf-8");W({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(()=>{y.kill(),w(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,b){let A=u(b,"SPECIFICATION.ts"),m=u(b,"INSTRUCTIONS.md"),n=u(b,"template.ts");return await Z$(A,$.specCode),await Z$(m,this.buildDetailedPrompt($)),await Z$(n,this.generateTemplate($)),await Z$(u(b,"README.md"),`# Cursor Agent Workspace
|
|
80
80
|
|
|
81
81
|
This workspace was prepared for Cursor AI code generation.
|
|
82
82
|
|
|
@@ -91,19 +91,19 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
91
91
|
3. Use Cursor AI to generate code based on the spec
|
|
92
92
|
4. Save the result as output.ts
|
|
93
93
|
|
|
94
|
-
Workspace path: ${
|
|
95
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${
|
|
94
|
+
Workspace path: ${b}
|
|
95
|
+
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await Z$(u(b,"specification.ts"),$.specCode),await Z$(u(b,"implementation.ts"),$.existingCode||"// No implementation"),await Z$(u(b,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,b){let A=[{path:"spec.ts",content:$.specCode}];if($.existingCode)A.push({path:"existing.ts",content:$.existingCode});return A}buildDetailedPrompt($){let b=`# AI Code Generation Task - Cursor Agent
|
|
96
96
|
|
|
97
97
|
**Task Type:** ${$.type}
|
|
98
98
|
**Generated:** ${new Date().toISOString()}
|
|
99
99
|
|
|
100
|
-
`,
|
|
100
|
+
`,A=`## Specification
|
|
101
101
|
|
|
102
102
|
\`\`\`typescript
|
|
103
103
|
${$.specCode}
|
|
104
104
|
\`\`\`
|
|
105
105
|
|
|
106
|
-
`,
|
|
106
|
+
`,m={generate:`## Task: Generate Implementation
|
|
107
107
|
|
|
108
108
|
### Requirements:
|
|
109
109
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -196,7 +196,7 @@ ${$.existingCode||""}
|
|
|
196
196
|
- Enhance error messages
|
|
197
197
|
|
|
198
198
|
### Output Format:
|
|
199
|
-
Refactored code that maintains functionality while improving quality.`};return
|
|
199
|
+
Refactored code that maintains functionality while improving quality.`};return b+A+(m[$.type]||m.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
200
200
|
|
|
201
201
|
## Specification
|
|
202
202
|
\`\`\`typescript
|
|
@@ -244,7 +244,7 @@ Provide detailed feedback for each failed item.
|
|
|
244
244
|
Suggest specific improvements with code examples where applicable.`}generateTemplate($){return`// Auto-generated template for ${$.type} task
|
|
245
245
|
// Specification:
|
|
246
246
|
${$.specCode.split(`
|
|
247
|
-
`).map((
|
|
247
|
+
`).map((b)=>`// ${b}`).join(`
|
|
248
248
|
`)}
|
|
249
249
|
|
|
250
250
|
// TODO: Implement according to specification
|
|
@@ -254,7 +254,7 @@ export function implementation() {
|
|
|
254
254
|
// Implementation goes here
|
|
255
255
|
throw new Error('Not implemented');
|
|
256
256
|
}
|
|
257
|
-
`}async cleanupWorkDir($){try{await
|
|
257
|
+
`}async cleanupWorkDir($){try{await MB($,{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 LW}from"@ai-sdk/openai";import{generateText as RW}from"ai";class jA{name="openai-codex";apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle($){return!!this.apiKey}async generate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set. OpenAI Codex agent requires API access."]};try{let A=this.isComplexTask($)?"o1":"gpt-5.4",m=LW(A),n=this.buildSystemPrompt($),W=this.buildUserPrompt($),w=await RW({model:m,prompt:W,system:n,temperature:0.2});return{success:!0,code:this.extractCode(w.text),metadata:{model:A,agentMode:"openai-codex",usage:w.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let b=LW("gpt-5.4"),A=`
|
|
258
258
|
Review this code implementation against its specification.
|
|
259
259
|
|
|
260
260
|
SPECIFICATION:
|
|
@@ -274,7 +274,7 @@ Provide a detailed validation report including:
|
|
|
274
274
|
4. Recommendations for improvement
|
|
275
275
|
|
|
276
276
|
Format as a structured report.
|
|
277
|
-
`,
|
|
277
|
+
`,m=await RW({model:b,prompt:A,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),n=this.detectIssues(m.text);return{success:!n,code:m.text,errors:n?this.extractErrors(m.text):[],warnings:this.extractWarnings(m.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}isComplexTask($){let b=["algorithm","optimization","complex logic","state management","concurrent","distributed"],A=($.specCode+($.existingCode||"")).toLowerCase();return b.some((m)=>A.includes(m))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
278
278
|
|
|
279
279
|
Generate production-quality code that is:
|
|
280
280
|
- Type-safe and well-typed
|
|
@@ -311,9 +311,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
311
311
|
${$.existingCode}
|
|
312
312
|
|
|
313
313
|
Spec:
|
|
314
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let
|
|
315
|
-
`);for(let
|
|
316
|
-
`);for(let
|
|
314
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],A=$.toLowerCase();return b.some((m)=>A.includes(m))}extractErrors($){let b=[],A=$.split(`
|
|
315
|
+
`);for(let m of A)if(m.toLowerCase().includes("error")||m.toLowerCase().includes("bug")||m.toLowerCase().includes("fails"))b.push(m.trim());return b}extractWarnings($){let b=[],A=$.split(`
|
|
316
|
+
`);for(let m of A)if(m.toLowerCase().includes("warning")||m.toLowerCase().includes("should")||m.toLowerCase().includes("consider"))b.push(m.trim());return b}}import D$ from"chalk";import DB from"ora";import{generateText as CW}from"ai";var c0={};P(c0,{getCodeGenSystemPrompt:()=>h0,buildTestPrompt:()=>f0,buildHandlerPrompt:()=>k0,buildFormPrompt:()=>r0,buildComponentPrompt:()=>P0});function k0($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
317
317
|
|
|
318
318
|
Here is the contract spec:
|
|
319
319
|
|
|
@@ -332,7 +332,7 @@ Generate a complete handler implementation that:
|
|
|
332
332
|
|
|
333
333
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
334
334
|
|
|
335
|
-
Return only the TypeScript code for the handler function.`}function
|
|
335
|
+
Return only the TypeScript code for the handler function.`}function P0($){return`You are a senior React developer creating a component for a presentation specification.
|
|
336
336
|
|
|
337
337
|
Here is the presentation spec:
|
|
338
338
|
|
|
@@ -351,7 +351,7 @@ Generate a complete React component that:
|
|
|
351
351
|
|
|
352
352
|
The component should follow Atomic Design principles and be reusable.
|
|
353
353
|
|
|
354
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
354
|
+
Return only the TypeScript/TSX code for the component.`}function r0($){return`You are a senior React developer creating a form component from a form specification.
|
|
355
355
|
|
|
356
356
|
Here is the form spec:
|
|
357
357
|
|
|
@@ -371,7 +371,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
371
371
|
|
|
372
372
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
373
373
|
|
|
374
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
374
|
+
Return only the TypeScript/TSX code for the form component.`}function f0($,b,A){return`You are a senior developer writing comprehensive tests.
|
|
375
375
|
|
|
376
376
|
Spec:
|
|
377
377
|
\`\`\`typescript
|
|
@@ -380,11 +380,11 @@ ${$}
|
|
|
380
380
|
|
|
381
381
|
Implementation:
|
|
382
382
|
\`\`\`typescript
|
|
383
|
-
${
|
|
383
|
+
${b}
|
|
384
384
|
\`\`\`
|
|
385
385
|
|
|
386
386
|
Generate complete test suite using Vitest that:
|
|
387
|
-
${
|
|
387
|
+
${A==="handler"?`
|
|
388
388
|
- Test all acceptance scenarios from the spec
|
|
389
389
|
- Test error cases defined in spec.io.errors
|
|
390
390
|
- Verify events are emitted correctly
|
|
@@ -398,7 +398,7 @@ ${j==="handler"?`
|
|
|
398
398
|
|
|
399
399
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
400
400
|
|
|
401
|
-
Return only the TypeScript test code.`}function
|
|
401
|
+
Return only the TypeScript test code.`}function h0(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
402
402
|
- Type-safe API design
|
|
403
403
|
- React and modern hooks
|
|
404
404
|
- Test-driven development
|
|
@@ -412,7 +412,7 @@ Generate production-ready code that is:
|
|
|
412
412
|
- Defensive and error-safe
|
|
413
413
|
- Easy to maintain and extend
|
|
414
414
|
|
|
415
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
415
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as xB}from"@contractspec/lib.ai-providers";function d0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return xB(b)}class yA{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let b=d0(this.config),A=this.buildPrompt($),m=await CW({model:b,prompt:A,system:h0()});return{success:!0,code:m.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:m.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){try{let b=d0(this.config),A=`
|
|
416
416
|
Review the following implementation against its specification.
|
|
417
417
|
|
|
418
418
|
Specification:
|
|
@@ -426,17 +426,17 @@ Provide a detailed validation report:
|
|
|
426
426
|
2. Are there any missing features?
|
|
427
427
|
3. Are there any bugs or issues?
|
|
428
428
|
4. Suggestions for improvement
|
|
429
|
-
`,
|
|
430
|
-
${$.specCode}`;case"test":return
|
|
431
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
429
|
+
`,m=await CW({model:b,prompt:A,system:"You are a code review expert. Provide thorough, constructive feedback."}),n=m.text.toLowerCase().includes("error")||m.text.toLowerCase().includes("missing")||m.text.toLowerCase().includes("incorrect");return{success:!n,code:m.text,warnings:n?["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 k0($.specCode);else if($.specCode.includes(".presentation."))return P0($.specCode);else if($.specCode.includes(".form."))return r0($.specCode);return`Generate implementation for:
|
|
430
|
+
${$.specCode}`;case"test":return f0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
431
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as TB}from"@contractspec/lib.ai-agent/agent/unified-agent";class u0{name;agent;constructor($,b,A={meta:{key:"workspace-agent",version:"1.0.0",description:"Workspace Agent",stability:"experimental",owners:[],tags:[]},instructions:"You are an expert software engineer implementing specifications.",tools:[]}){this.name=$;this.agent=TB(A,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),A=await this.agent.run(b);return{success:!0,code:A.text,metadata:{finishReason:A.finishReason,usage:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
432
432
|
${$.specCode}
|
|
433
433
|
|
|
434
|
-
`;if($.existingCode)
|
|
434
|
+
`;if($.existingCode)b+=`Existing Code:
|
|
435
435
|
${$.existingCode}
|
|
436
436
|
|
|
437
|
-
`;switch($.type){case"generate":
|
|
437
|
+
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class BA{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let b=new yA($),A=new wA,m=new WA,n=new jA;this.agents.set("simple",b),this.agents.set("cursor",A),this.agents.set("claude-code",m),this.agents.set("openai-codex",n),this.defaultAgent=b,this.agents.set("opencode-sdk",new u0("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let b=this.getAgentMode(),A=this.agents.get(b);if(!A)return console.log(D$.yellow(`⚠️ Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!A.canHandle($))return console.log(D$.yellow(`⚠️ Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let m=DB(`Executing with ${b} agent...`).start();try{let n=$.type==="validate"?await A.validate($):await A.generate($);if(n.success)return m.succeed(D$.green(`${b} agent completed successfully`)),n;m.warn(D$.yellow(`${b} agent failed, trying fallback...`));let W=this.getFallbackMode(b);if(W&&W!==b){let w=this.agents.get(W);if(w&&w.canHandle($))return $.type==="validate"?await w.validate($):await w.generate($)}return m.info(D$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(n){return m.fail(D$.red("Agent execution failed")),console.log(D$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,b){return this.executeTask({type:"generate",specCode:$,targetPath:b})}async generateTests($,b){return this.executeTask({type:"test",specCode:$,existingCode:b})}async validate($,b){return this.executeTask({type:"validate",specCode:$,existingCode:b})}async refactor($,b){return this.executeTask({type:"refactor",specCode:$,existingCode:b})}async getAvailableAgents(){let $=[];for(let[b,A]of this.agents){let m={type:"generate",specCode:"test"},n=A.canHandle(m);$.push({mode:b,available:n,reason:n?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 IW={};P(IW,{specCreation:()=>o0,codeGeneration:()=>c0});var o0={};P(o0,{getSystemPrompt:()=>gB,buildPresentationSpecPrompt:()=>vB,buildOperationSpecPrompt:()=>NB,buildEventSpecPrompt:()=>FB,addExampleContext:()=>kB});function NB($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
438
438
|
|
|
439
|
-
The operation is a ${
|
|
439
|
+
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
440
440
|
|
|
441
441
|
User description: ${$}
|
|
442
442
|
|
|
@@ -452,7 +452,7 @@ Create a complete contract specification following these guidelines:
|
|
|
452
452
|
8. **Feature Flags**: Any flags that gate this operation
|
|
453
453
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
454
454
|
|
|
455
|
-
Respond with a structured spec.`}function
|
|
455
|
+
Respond with a structured spec.`}function FB($){return`You are a senior software architect creating an event specification.
|
|
456
456
|
|
|
457
457
|
User description: ${$}
|
|
458
458
|
|
|
@@ -466,9 +466,9 @@ Create a complete event specification following these guidelines:
|
|
|
466
466
|
|
|
467
467
|
Events represent things that have already happened and should use past tense.
|
|
468
468
|
|
|
469
|
-
Respond with a structured spec.`}function
|
|
469
|
+
Respond with a structured spec.`}function vB($,b){return`You are a senior software architect creating a presentation specification.
|
|
470
470
|
|
|
471
|
-
This is a ${
|
|
471
|
+
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
472
472
|
|
|
473
473
|
User description: ${$}
|
|
474
474
|
|
|
@@ -478,13 +478,13 @@ Create a complete presentation specification following these guidelines:
|
|
|
478
478
|
2. **Version**: Start at 1
|
|
479
479
|
3. **Description**: What this presentation shows/provides
|
|
480
480
|
4. **Kind-specific details**:
|
|
481
|
-
${
|
|
481
|
+
${b==="web_component"?`- Component key (symbolic, resolved by host app)
|
|
482
482
|
- Props structure
|
|
483
|
-
- Analytics events to track`:
|
|
483
|
+
- Analytics events to track`:b==="markdown"?`- Content or resource URI
|
|
484
484
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
485
485
|
- Data structure description`}
|
|
486
486
|
|
|
487
|
-
Respond with a structured spec.`}function
|
|
487
|
+
Respond with a structured spec.`}function gB(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
488
488
|
|
|
489
489
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
490
490
|
|
|
@@ -494,111 +494,359 @@ Your specs are:
|
|
|
494
494
|
- Business-oriented (capturing the "why" not just "what")
|
|
495
495
|
- Designed for both humans and AI agents to understand
|
|
496
496
|
|
|
497
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
497
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function kB($,b){if(b.length===0)return $;return`${$}
|
|
498
498
|
|
|
499
499
|
Here are some good examples for reference:
|
|
500
500
|
|
|
501
|
-
${
|
|
501
|
+
${b.join(`
|
|
502
502
|
|
|
503
503
|
`)}
|
|
504
504
|
|
|
505
|
-
Follow this structure and quality level.`}var
|
|
506
|
-
`)}function
|
|
505
|
+
Follow this structure and quality level.`}var xW={};P(xW,{sarifToJson:()=>dB,formatAsTextLines:()=>MW,formatAsText:()=>uB,formatAsSarif:()=>fB,formatAsJson:()=>PB});function PB($,b={}){let{pretty:A=!0,driftResult:m}=b,n=$.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})),W=$.categories.filter((S)=>S.passed).length,w=$.totalErrors,j=$.totalWarnings,y=$.totalNotes,B={schemaVersion:"1.0",success:$.success,checks:n,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:m?.hasDrift?"detected":"none",files:m?.files??[]},summary:{pass:W,fail:w,warn:j,note:y,total:W+w+j+y,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return A?JSON.stringify(B,null,2):JSON.stringify(B)}var rB={"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 fB($,b={}){let{toolName:A="ContractSpec",toolVersion:m="1.0.0",toolUri:n="https://contractspec.io",repositoryUri:W,workingDirectory:w}=b,j=new Map,y=new Map,B=$.issues.filter((G)=>G.file);for(let G of B)if(!j.has(G.ruleId)){let X=rB[G.ruleId]??{name:G.ruleId,description:`Rule: ${G.ruleId}`},Y={id:G.ruleId,name:X.name,shortDescription:{text:X.description},defaultConfiguration:{level:EW(G.severity)}};if(X.helpUri)Y.helpUri=X.helpUri;y.set(G.ruleId,j.size),j.set(G.ruleId,Y)}let S=B.map((G)=>{let X={ruleId:G.ruleId,ruleIndex:y.get(G.ruleId)??0,level:EW(G.severity),message:{text:G.message}},Y={physicalLocation:{artifactLocation:{uri:hB(G.file),uriBaseId:"%SRCROOT%"}}};if(G.line!==void 0)Y.physicalLocation.region={startLine:G.line,startColumn:G.column??1,endLine:G.endLine??G.line,endColumn:G.endColumn};return X.locations=[Y],X.partialFingerprints={primaryLocationLineHash:cB(G)},X}),Q=[];if(W)Q.push({repositoryUri:W,revisionId:$.commitSha,branch:$.branch});let Z={tool:{driver:{name:A,version:m,informationUri:n,rules:Array.from(j.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 EW($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function hB($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function cB($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function dB($){return JSON.stringify($,null,2)}function MW($,b={}){let A=[],{verbose:m=!1,showTiming:n=!0,groupByFile:W=!1}=b;if(A.push({text:"",style:"normal"}),A.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),A.push({text:"",style:"normal"}),$.commitSha||$.branch){let j=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");A.push({text:`Git: ${j}`,style:"muted"})}A.push({text:"",style:"normal"}),A.push({text:"Check Results:",style:"bold"});for(let j of $.categories){let y=j.passed?"✓":"✗",B=j.passed?"success":"error",S=oB(j),Q=n?` (${j.durationMs}ms)`:"";A.push({text:` ${y} ${j.label}: ${S}${Q}`,style:B})}if($.issues.length>0)if(A.push({text:"",style:"normal"}),A.push({text:"Issues:",style:"bold"}),W){let j=iB($.issues);for(let[y,B]of j){A.push({text:"",style:"normal"}),A.push({text:` ${y||"(no file)"}`,style:"bold",indent:1});for(let S of B)A.push(...SA(S,m,2))}}else{let j=$.issues.filter((S)=>S.severity==="error"),y=$.issues.filter((S)=>S.severity==="warning"),B=$.issues.filter((S)=>S.severity==="note");if(j.length>0){A.push({text:"",style:"normal"}),A.push({text:" Errors:",style:"error",indent:1});for(let S of j)A.push(...SA(S,m,2))}if(y.length>0){A.push({text:"",style:"normal"}),A.push({text:" Warnings:",style:"warning",indent:1});for(let S of y)A.push(...SA(S,m,2))}if(B.length>0&&m){A.push({text:"",style:"normal"}),A.push({text:" Notes:",style:"muted",indent:1});for(let S of B)A.push(...SA(S,m,2))}}A.push({text:"",style:"normal"}),A.push({text:"─".repeat(50),style:"muted"});let w=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&m?`${$.totalNotes} note(s)`:null].filter(Boolean);if(w.length>0)A.push({text:`Found: ${w.join(", ")}`,style:$.success?"warning":"error"});if(n)A.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(A.push({text:"",style:"normal"}),$.success)A.push({text:"✅ All CI checks passed!",style:"success"});else A.push({text:"❌ CI checks failed",style:"error"});return A.push({text:"",style:"normal"}),A}function uB($,b={}){return MW($,b).map((m)=>" ".repeat(m.indent??0)+m.text).join(`
|
|
506
|
+
`)}function oB($){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 SA($,b,A){let m=[],n=$.severity==="error"?"✗":$.severity==="warning"?"⚠":"○",W=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",w=`${n} ${$.message}`;if($.file){let j=$.line?`:${$.line}`:"";w+=` (${$.file}${j})`}if(m.push({text:w,style:W,indent:A}),b&&$.context){let j=JSON.stringify($.context);if(j!=="{}")m.push({text:`Context: ${j}`,style:"muted",indent:A+1})}return m}function iB($){let b=new Map;for(let A of $){let m=A.file??"";if(!b.has(m))b.set(m,[]);let n=b.get(m);if(n)n.push(A)}return new Map([...b.entries()].sort(([A],[m])=>A.localeCompare(m)))}import{OperationSpecRegistry as lB}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as tB}from"@contractspec/lib.contracts-spec/operations/report";function pB(){let $=new lB;return tB($),$}var kY=pB();class aB{buildReportData($){let b=$.existingReportData||{};if(b.contracts=$.contractsJson,b.whatChanged={summary:"Drift check completed.",detailsPath:"",...b.whatChanged},b.risk={status:"unknown",breaking:0,nonBreaking:0,...b.risk},b.validation={status:"skipped",outputPath:"",...b.validation},b.drift={status:$.driftStatus,files:$.driftFiles},!b.nextSteps)b.nextSteps=[];if($.driftStatus==="fail")b.nextSteps.push("Run the generate command locally and commit drift fixes.");return b}finalizeResults($,b){let A=$.drift?.status==="fail",m=!1;if(A&&b==="fail")m=!0;return{driftDetected:A,shouldFail:m}}}function eB($){if(!$)return"—";let b=new Date($),m=new Date().getTime()-b.getTime(),n=Math.floor(m/86400000);if(n<1)return"today";if(n===1)return"yesterday";return`${n} days ago`}class sB{collectChanges($,b,A){if($){let m=$.endsWith("/")?$:`${$}/`;return A.filter((n)=>n.startsWith(m))}if(b){let m=new RegExp("^"+b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return A.filter((n)=>m.test(n))}return A}detectDrift($){let b=$.map((A)=>A.slice(3)).filter((A)=>A&&A.trim().length>0).filter((A)=>A!==".contractspec-ci"&&!A.startsWith(".contractspec-ci/"));return{files:b,status:b.length>0?"fail":"pass"}}deriveImpactStatus($){let b=$?.summary||{},A=b.breaking||0,m=b.nonBreaking||0,n=b.total;if(n===void 0)n=A+m;let W=$?.breaking||!1,w="unknown";if($){if(W||A>0)w="breaking",W=!0;else if(m>0)w="non-breaking";else if(n===0)w="no-impact"}return{status:w,breaking:W,breakingCount:A,nonBreakingCount:m,total:n||0}}buildReportData($){let b=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,A=this.deriveImpactStatus($.impactJson),m={contracts:$.contractsJson,whatChanged:{summary:b,detailsPath:".contractspec-ci/product-view.md"},risk:{status:A.status,breaking:A.breakingCount,nonBreaking:A.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(m.validation?.status==="fail")m.nextSteps?.push("Fix validation errors and rerun the workflow.");if(m.risk?.status==="breaking")m.nextSteps?.push("Review breaking changes and plan a migration.");if(m.risk?.status==="unknown")m.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(m.drift?.status==="fail")m.nextSteps?.push("Run the generate command locally and commit drift fixes.");let n=this.finalizeResults(m,$.failOn);if(n.shouldFail)m.nextSteps?.unshift(`CI failed: ${n.failReasons.join(", ")} (fail_on=${$.failOn}).`);return m}finalizeResults($,b){let A=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,m=$.drift?.status==="fail",n=$.validation?.status==="fail",W=$.risk?.status==="unknown",w=[],j=!1;if(b!=="never"){if(b==="breaking"){if(A)w.push("breaking changes detected");if(W)w.push("impact status unknown")}else if(b==="drift"){if(m)w.push("drift detected");if(W)w.push("impact status unknown")}else if(b==="any"){if(A)w.push("breaking changes detected");if(m)w.push("drift detected");if(n)w.push("validation failed");if(W)w.push("impact status unknown")}else w.push(`invalid fail_on value (${b})`);if(w.length>0)j=!0}return{driftDetected:m,breakingChangeDetected:A,validationFailed:n,shouldFail:j,failReasons:w}}generateReportMarkdown($,b){let A=(y,B=60000)=>{if(y.length<=B)return y;return`${y.slice(0,B)}
|
|
507
507
|
|
|
508
|
-
*(output truncated)*`},
|
|
509
|
-
`)},
|
|
508
|
+
*(output truncated)*`},m=(y)=>{if(!y||y.length===0)return"- None";return y.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
509
|
+
`)},n=A($.whatChanged?.detailsPath?b($.whatChanged.detailsPath):""),W=A($.validation?.outputPath?b($.validation.outputPath):""),w=$.drift?.files??[],j=[];if(j.push("## ContractSpec Report"),j.push(""),$.contracts&&$.contracts.length>0){j.push("### Overall verification status"),j.push(""),j.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),j.push("| --- | --- | --- | --- | --- |");for(let y of $.contracts){let B=y.lastVerifiedSha??"—",S=eB(y.lastVerifiedDate),Q=y.surfaces.join(", ");j.push(`| ${y.name} | ${S} | ${y.driftMismatches} | ${Q} | ${B} |`)}j.push("")}if(j.push("### 1) What changed"),$.whatChanged?.summary)j.push($.whatChanged.summary);else j.push("No contract changes detected.");if(n.trim().length>0)j.push(""),j.push("<details>"),j.push("<summary>Contract view (product)</summary>"),j.push(""),j.push(n),j.push(""),j.push("</details>");if(j.push(""),j.push("### 2) Risk classification"),$.risk?.status){let y=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);j.push(y.join(" | "))}else j.push("Impact analysis unavailable.");if(j.push(""),j.push("### 3) Validation results"),$.validation?.status){if(j.push(`Status: ${$.validation.status}`),W.trim().length>0)j.push(""),j.push("<details>"),j.push("<summary>Validation output</summary>"),j.push(""),j.push(W),j.push(""),j.push("</details>")}else j.push("Validation step not run.");if(j.push(""),j.push("### 4) Drift results"),$.drift?.status){if(j.push(`Status: ${$.drift.status}`),w.length>0)j.push(""),j.push("<details>"),j.push("<summary>Drifted files</summary>"),j.push(""),j.push(m(w)),j.push(""),j.push("</details>")}else j.push("Drift check not run.");if(j.push(""),j.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)j.push(m($.nextSteps));else j.push("- No action required.");return`${j.join(`
|
|
510
510
|
`)}
|
|
511
|
-
`}}import{AGENT_SYSTEM_PROMPTS as xQ}from"@contractspec/lib.contracts-spec/llm";class u0{agentType="claude-code";formatPlan($){let W=[];if(W.push(`# Implement: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files to Create/Modify"),W.push("");for(let j of $.fileStructure){let A=j.type==="create"?"\uD83D\uDCDD":"✏️";W.push(`${A} \`${j.path}\``),W.push(` ${j.purpose}`),W.push("")}}W.push("## Implementation Steps"),W.push("");for(let j of $.steps){W.push(`### ${j.order}. ${j.title}`),W.push(""),W.push(j.description),W.push(""),W.push("**Acceptance Criteria:**");for(let A of j.acceptanceCriteria)W.push(`- [ ] ${A}`);W.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("### Policy");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("### Security");for(let j of $.constraints.security)W.push(`- ⚠️ ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("### PII Handling"),W.push("The following fields contain personally identifiable information:");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}}W.push("## Verification Checklist"),W.push(""),W.push("Before submitting, verify:");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),W.push("## Instructions"),W.push(""),W.push("1. Implement each step in order"),W.push("2. Use TypeScript with strict typing (no `any`)"),W.push("3. Include JSDoc comments for public APIs"),W.push("4. Handle all error cases defined in the spec"),W.push("5. Emit events as specified"),W.push("6. Mark checklist items as you complete them"),W.push(""),{agent:"claude-code",systemPrompt:xQ["claude-code"],taskPrompt:W.join(`
|
|
512
|
-
`)}}
|
|
513
|
-
`)}
|
|
514
|
-
`)}
|
|
515
|
-
`)}
|
|
516
|
-
`)}}
|
|
517
|
-
`)}
|
|
511
|
+
`}}var s0={};P(s0,{uniqueTokens:()=>N$,tokenize:()=>i$,syncAdoptionCatalog:()=>K5,scanWorkspaceAdoptionCandidates:()=>p0,resolveAdoptionWorkspace:()=>l$,resolveAdoption:()=>Xb,overlap:()=>ZA,normalizeText:()=>gW,inferFamilyFromPath:()=>e0,hasLocalShadcnRegistry:()=>a0,getContractSpecAdoptionCatalog:()=>QA,createAdoptionCatalogDocument:()=>i0,candidateTokens:()=>l0});function E($,b,A,m,n,W,w,j,y={}){return{id:$,source:"contractspec",packageRef:b,family:A,packageKind:m,title:y.title??b,description:j,capabilityTags:W,preferredUseCases:w,avoidWhen:y.avoidWhen,platforms:y.platforms,replacementImportHints:y.replacementImportHints,resolutionPriority:n,runtimes:y.runtimes}}var TW=[E("contracts.spec","@contractspec/lib.contracts-spec","contracts","primitive",100,["contracts","specs","operations","events","policies"],["new contracts","spec-first APIs","shared contract registries"],"Core ContractSpec contract declarations, registries, policy, workflow, and shared spec types."),E("contracts.schema","@contractspec/lib.schema","contracts","primitive",90,["schema","validation","io-models","json-schema"],["shared schema models","multi-surface I/O definitions"],"Schema definitions for ContractSpec multi-surface consistency."),E("integrations.contracts","@contractspec/lib.contracts-integrations","integrations","primitive",100,["integrations","providers","capabilities","connections"],["provider contracts","integration metadata","runtime capability definitions"],"Integration definitions for providers, capabilities, connection models, and runtime metadata."),E("integrations.providers-impls","@contractspec/integration.providers-impls","integrations","adapter",90,["integrations","providers","implementations","sdk-bridges"],["provider implementations","existing vendor bridges"],"Concrete provider implementations layered over ContractSpec integration contracts."),E("integrations.runtime","@contractspec/integration.runtime","integrations","adapter",80,["runtime","integrations","managed","local","hybrid"],["runtime composition","integration execution","provider orchestration"],"Runtime composition helpers for integration execution.")];var DW=[E("runtime.react-client","@contractspec/lib.contracts-runtime-client-react","runtime","adapter",100,["runtime","react","forms","rendering"],["react client adapters","form rendering","feature rendering"],"React runtime adapters for ContractSpec forms and feature rendering.",{platforms:["web"]}),E("runtime.rest","@contractspec/lib.contracts-runtime-server-rest","runtime","adapter",95,["runtime","rest","server","http"],["REST handlers","HTTP adapters","server endpoints"],"REST server adapters for Next, Express, Elysia, and generic server code.",{runtimes:["node"]}),E("runtime.graphql","@contractspec/lib.contracts-runtime-server-graphql","runtime","adapter",95,["runtime","graphql","pothos","server"],["GraphQL adapters","typed GraphQL contract exposure"],"GraphQL runtime adapter for Pothos-based servers.",{runtimes:["node"]}),E("runtime.mcp","@contractspec/lib.contracts-runtime-server-mcp","runtime","adapter",95,["runtime","mcp","tools","resources","prompts"],["MCP servers","tool/resource registration"],"MCP runtime adapter for ContractSpec-backed tools, resources, and prompts.",{runtimes:["node"]}),E("runtime.presentation-react","@contractspec/lib.presentation-runtime-react","runtime","primitive",85,["runtime","presentation","react","tables"],["React presentation rendering","contract-backed view helpers"],"React presentation runtime helpers for ContractSpec-driven UI rendering."),E("runtime.presentation-core","@contractspec/lib.presentation-runtime-core","runtime","primitive",80,["runtime","presentation","transform","core"],["platform-agnostic presentation rendering","transform pipelines"],"Platform-agnostic presentation transform engine."),E("runtime.harness","@contractspec/lib.harness","runtime","primitive",75,["runtime","harness","replay","evaluation"],["proof-backed verification","evaluation workflows","replay"],"Harness orchestration, evidence, policy, replay, and evaluation runtime."),E("runtime.harness-runtime","@contractspec/integration.harness-runtime","runtime","adapter",70,["runtime","harness","browser","sandbox","mcp"],["browser and sandbox-backed harness targets"],"Runtime adapters for browser, sandbox, artifact, and MCP-backed harness targets.")];var NW=[E("shared.logger","@contractspec/lib.logger","sharedLibs","primitive",100,["shared","logger","observability"],["structured logging","app and service logging"],"Structured logger used across ContractSpec runtimes and apps."),E("shared.files","@contractspec/lib.files","sharedLibs","primitive",90,["shared","files","artifacts","storage"],["file abstractions","artifact handling"],"File and artifact helpers for reusable storage-facing workflows."),E("shared.testing","@contractspec/lib.testing","sharedLibs","primitive",90,["shared","testing","golden-tests","verification"],["golden tests","safe regeneration verification"],"Testing helpers for proof-oriented and golden regression workflows."),E("shared.observability","@contractspec/lib.observability","sharedLibs","primitive",85,["shared","observability","metrics","tracing"],["structured tracing","metrics","telemetry"],"Tracing, metrics, and structured logging helpers."),E("shared.identity","@contractspec/lib.identity-rbac","sharedLibs","primitive",80,["shared","identity","rbac","authz"],["identity and RBAC helpers","authorization models"],"Identity and RBAC helpers for policy-aware systems."),E("shared.accessibility","@contractspec/lib.accessibility","sharedLibs","primitive",75,["shared","accessibility","ui","a11y"],["accessibility primitives","cross-surface a11y helpers"],"Accessibility helpers layered on top of ContractSpec UI surfaces."),E("shared.ai-agent","@contractspec/lib.ai-agent","sharedLibs","primitive",70,["shared","ai","agent","mcp"],["tool-aware agent orchestration","approval-backed agent workflows"],"AI agent orchestration with contract governance."),E("shared.knowledge","@contractspec/lib.knowledge","sharedLibs","primitive",68,["shared","knowledge","retrieval","ingestion","spaces"],["knowledge spaces","retrieval flows","ingestion pipelines"],"Knowledge spaces, bindings, ingestion, and governed retrieval helpers."),E("shared.ai-providers","@contractspec/lib.ai-providers","sharedLibs","primitive",65,["shared","ai","providers","models"],["provider resolution","model catalogs","AI integrations"],"Shared AI provider abstractions and model metadata.")];var FW=[E("solutions.ai-chat","@contractspec/module.ai-chat","solutions","module",60,["solutions","module","chat","agent-ui"],["feature-complete AI chat surfaces","reusable chat modules"],"Reusably packaged AI chat system."),E("solutions.learning-journey","@contractspec/module.learning-journey","solutions","module",58,["solutions","module","learning","journey","onboarding"],["guided onboarding tracks","adaptive learning flows"],"Adaptive learning-journey runtime for onboarding, coaching, drills, and progression."),E("solutions.provider-ranking","@contractspec/module.provider-ranking","solutions","module",55,["solutions","module","provider-ranking","benchmarks"],["ranking pipelines","provider benchmark workflows"],"Provider ranking pipelines, storage, and orchestration."),E("solutions.bundle-workspace","@contractspec/bundle.workspace","solutions","bundle",50,["solutions","bundle","workspace","automation"],["workspace services","setup","doctor","connect"],"Workspace bundle powering CLI, validation, generation, and setup flows."),E("solutions.bundle-library","@contractspec/bundle.library","solutions","bundle",45,["solutions","bundle","docs","mcp","templates"],["docs surfaces","MCP handlers","library-style composed product surfaces"],"Library bundle for docs, templates, and MCP-facing product surfaces."),E("solutions.example-minimal","@contractspec/example.minimal","solutions","example",30,["solutions","example","starter","minimal"],["reference implementations","scaffolding references","how-to examples"],"Minimal example showing baseline ContractSpec usage.")];var vW=[E("ui.design-system","@contractspec/lib.design-system","ui","primitive",100,["ui","design-system","layout","forms","marketing"],["app surfaces","shared composed controls","web and native theming"],"Higher-level ContractSpec design system for composed UI surfaces.",{platforms:["web","native"],avoidWhen:["Need a lower-level platform leaf primitive only."],replacementImportHints:[{from:"@contractspec/lib.ui-kit-web/ui/button",to:"@contractspec/lib.design-system",note:"Prefer the composed design-system control in app code."}]}),E("ui.ui-kit-web","@contractspec/lib.ui-kit-web","ui","primitive",80,["ui","web","radix","next","components"],["web-only primitives","lower-level browser controls"],"Web-first ContractSpec UI kit for React and Next.js surfaces.",{platforms:["web"]}),E("ui.ui-kit-native","@contractspec/lib.ui-kit","ui","primitive",80,["ui","native","expo","react-native","components"],["native primitives","expo components","react-native controls"],"Native-first ContractSpec UI kit for Expo and React Native.",{platforms:["native"]})];var $5=[...vW,...TW,...DW,...NW,...FW];function QA(){return[...$5].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function i0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:QA()}}import{DEFAULT_CONTRACTSRC as B5}from"@contractspec/lib.contracts-spec/workspace-config";function gW($){return $.toLowerCase().trim()}function i$($){return gW($).split(/[^a-z0-9@./-]+/).flatMap((b)=>b.split(/[./_-]+/)).filter((b)=>b.length>1)}function N$($){return[...new Set($.flatMap((b)=>i$(b)))]}function l0($){let b=[$.id,$.title];if($.description)b.push($.description);if(b.push(...$.capabilityTags),b.push(...$.preferredUseCases),"packageRef"in $&&$.packageRef)b.push($.packageRef);if("filePath"in $&&$.filePath)b.push($.filePath);return N$(b)}function ZA($,b){let A=new Set(b);return $.filter((m)=>A.has(m)).length}import{resolve as b5}from"node:path";import{ContractsrcSchema as A5,DEFAULT_CONTRACTSRC as t0}from"@contractspec/lib.contracts-spec/workspace-config";async function l$($,b={}){let A=b5(b.cwd??process.cwd()),m=b.workspaceRoot??M(A),n=b.packageRoot??r(A),W=b.config?PW(t0,b.config):await m5($,m,n);return{adoption:W.connect?.adoption??t0.connect.adoption,config:W,cwd:A,packageRoot:n,workspaceRoot:m}}async function m5($,b,A){let m=t0;if(b!==A)m=await kW($,m,$.join(b,".contractsrc.json"));return kW($,m,$.join(A,".contractsrc.json"))}async function kW($,b,A){if(!await $.exists(A))return b;try{let m=JSON.parse(await $.readFile(A)),n=A5.safeParse(m);if(!n.success)return b;return PW(b,n.data)}catch{return b}}function PW($,b){return{...$,...b,connect:{...$.connect,...b.connect,adapters:{...$.connect?.adapters,...b.connect?.adapters},adoption:{...$.connect?.adoption,...b.connect?.adoption,catalog:{...$.connect?.adoption?.catalog,...b.connect?.adoption?.catalog},workspaceScan:{...$.connect?.adoption?.workspaceScan,...b.connect?.adoption?.workspaceScan},families:{...$.connect?.adoption?.families,...b.connect?.adoption?.families},thresholds:{...$.connect?.adoption?.thresholds,...b.connect?.adoption?.thresholds}},policy:{...$.connect?.policy,...b.connect?.policy,reviewThresholds:{...$.connect?.policy?.reviewThresholds,...b.connect?.policy?.reviewThresholds}},storage:{...$.connect?.storage,...b.connect?.storage}}}}var n5=["package.json","packages/*/package.json"];async function p0($,b){let[A,m]=await Promise.all([W5($,b),w5($,b)]);return{fileCandidates:m,packageCandidates:A}}async function a0($,b){let A=$.join(b.workspaceRoot,"components.json");if(await $.exists(A))return!0;return(await $.glob({patterns:["components/ui/**/*.{ts,tsx,js,jsx}","registry/**/*.json"],cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).length>0}async function W5($,b){let A=await $.glob({patterns:n5,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1}),m=[];for(let n of A)try{let W=JSON.parse(await $.readFile($.join(b.workspaceRoot,n))),w=e0(n);if(!w)continue;let j=W.name??$.dirname(n);m.push({id:`workspace.package.${j}`,source:"workspace",family:w,title:j,description:W.description??`Local reusable package at ${n}.`,packageKind:y5(n),packageRef:j,capabilityTags:N$([j,n]),preferredUseCases:[n],resolutionPriority:120})}catch{continue}return m}async function w5($,b){return(await $.glob({patterns:b.adoption.workspaceScan?.include,cwd:b.workspaceRoot,ignore:b.adoption.workspaceScan?.exclude,absolute:!1})).flatMap((m)=>{let n=e0(m);if(!n)return[];let W=m.split("/").pop()?.replace(/\.[^.]+$/,"")??m;return[{id:`workspace.file.${m}`,source:"workspace",family:n,title:W,description:`Local reusable source at ${m}.`,filePath:m,capabilityTags:i$(m),preferredUseCases:[m],resolutionPriority:j5(n,m)}]})}function e0($){let b=$.replaceAll("\\","/").toLowerCase();if(/\b(contract|contracts|spec|specs|operation|event|presentation|form)\b/.test(b))return"contracts";if(/\b(component|components|ui|screen|view|page)\b/.test(b)&&/\.(tsx|jsx)$/.test(b))return"ui";if(/\b(integration|integrations|provider|providers|adapter|adapters|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render|presentation-runtime)\b/.test(b))return"runtime";if(/\b(example|examples|template|templates|module|bundle|app)\b/.test(b))return"solutions";if(/\b(lib|libs|shared|core|utils|logger|schema|testing|identity|accessibility)\b/.test(b))return"sharedLibs";return null}function j5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function y5($){if($.startsWith("packages/modules/"))return"module";if($.startsWith("packages/bundles/"))return"bundle";if($.startsWith("packages/apps/"))return"app";if($.startsWith("packages/examples/"))return"example";if($.startsWith("packages/integrations/"))return"adapter";return"primitive"}async function Xb($,b){let A=await l$($.fs,b),m=O5(b),n=N$([m,b.symbol??"",...b.paths??[]]),W=await p0($.fs,A),w=await V5($,A),j=await a0($.fs,A),y=S5(A,n,b,[...W.packageCandidates,...W.fileCandidates,...w,...J5(b.family,b.platform,j)]),B=y[0]??null,S=y.length>1&&B!=null&&B.candidate.source===y[1].candidate.source&&Math.abs(B.score-y[1].score)<=40,Q=Y5(A,B,S,b.currentTarget);return{ambiguous:S,candidates:y,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:m,reason:q5(B,S),selected:B,verdict:Q}}function S5($,b,A,m){return m.filter((n)=>n.family===A.family&&G5($,n.family)).filter((n)=>X5(n,A.platform)).map((n)=>Q5(n,b,A.paths)).filter((n)=>n.score>40).sort((n,W)=>W.score-n.score).slice(0,8)}function Q5($,b,A){let m=l0($),n=N$(A??[]),W=[],w=ZA(b,m)*25,j=ZA(n,m)*10;if(w>0)W.push("query overlap");if(j>0)W.push("path overlap");return{candidate:$,matchReasons:W,score:Z5($.source)+($.resolutionPriority??0)+w+j}}function Z5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function G5($,b){return $.adoption.families?.[b]??!0}function X5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function Y5($,b,A,m){let n=$.adoption.thresholds??B5.connect.adoption.thresholds;if(A)return n.ambiguous??"require_review";if(!b)return n.newImplementation??"require_review";if(b.candidate.source==="workspace")return H5(b.candidate,m)?"permit":n.workspaceReuse??"rewrite";if(b.candidate.source==="contractspec")return n.contractspecReuse??"rewrite";if(b.candidate.id.startsWith("ecosystem.new"))return n.newImplementation??"require_review";return n.newExternalDependency??"require_review"}function H5($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function q5($,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 O5($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function V5($,b){let A=QA(),m=b.adoption.catalog?.overrideManifestPath;if(!m||!await $.fs.exists($.fs.join(b.workspaceRoot,m)))return A;try{let n=await $.fs.readFile($.fs.join(b.workspaceRoot,m)),W=JSON.parse(n);return[...A,...Array.isArray(W)?W:W.entries??[]]}catch{return A}}function J5($,b,A){if($==="ui"&&b==="web"&&A)return[t$("ecosystem.shadcn",$,"shadcn-local","Existing local shadcn registry",60)];if($==="contracts")return[t$("ecosystem.new-contract",$,"contractspec:create-spec","Create a ContractSpec spec before implementation",20)];if($==="integrations")return[t$("ecosystem.vendor-sdk",$,"ecosystem:vendor-sdk","Raw vendor SDK fallback",40)];if($==="runtime")return[t$("ecosystem.framework-native",$,"ecosystem:framework-native","Framework-native runtime fallback",35)];if($==="sharedLibs")return[t$("ecosystem.external-lib",$,"ecosystem:external-lib","External library fallback",30)];return[t$("ecosystem.new-implementation",$,"ecosystem:new-local","Create a new local implementation",10)]}function t$($,b,A,m,n){return{id:$,source:"ecosystem",packageRef:A,family:b,packageKind:"primitive",title:m,description:m,capabilityTags:i$(m),preferredUseCases:[m],resolutionPriority:n}}async function K5($,b={}){let A=await l$($.fs,b),m=i0(),n=$.fs.join(A.workspaceRoot,A.adoption.catalog?.indexPath??".contractspec/adoption/catalog.json");return await $.fs.writeFile(n,`${JSON.stringify(m,null,2)}
|
|
512
|
+
`),{catalog:m,catalogPath:n}}import{AGENT_SYSTEM_PROMPTS as _5}from"@contractspec/lib.contracts-spec/llm";class GA{agentType="claude-code";formatPlan($){let b=[];if(b.push(`# Implement: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files to Create/Modify"),b.push("");for(let A of $.fileStructure){let m=A.type==="create"?"\uD83D\uDCDD":"✏️";b.push(`${m} \`${A.path}\``),b.push(` ${A.purpose}`),b.push("")}}b.push("## Implementation Steps"),b.push("");for(let A of $.steps){b.push(`### ${A.order}. ${A.title}`),b.push(""),b.push(A.description),b.push(""),b.push("**Acceptance Criteria:**");for(let m of A.acceptanceCriteria)b.push(`- [ ] ${m}`);b.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("### Policy");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("### Security");for(let A of $.constraints.security)b.push(`- ⚠️ ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:_5["claude-code"],taskPrompt:b.join(`
|
|
513
|
+
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
514
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let A=[],m=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let n of m){let W=$.matchAll(n);for(let w of W)if(w[1])A.push(w[1])}if(A.length>0)return{errors:A};return{code:$}}}var XA=new GA;import{AGENT_SYSTEM_PROMPTS as U5}from"@contractspec/lib.contracts-spec/llm";class YA{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 m of $.fileStructure)b.push(`- ${m.type}: \`${m.path}\` - ${m.purpose}`);b.push("")}b.push("## Spec"),b.push(""),b.push($.specMarkdown),b.push(""),b.push("## Steps"),b.push("");for(let m of $.steps)b.push(`${m.order}. **${m.title}**: ${m.description}`);b.push("");let A=[...$.constraints.policy,...$.constraints.security.map((m)=>`⚠️ ${m}`)];if(A.length>0){b.push("## Constraints"),b.push("");for(let m of A)b.push(`- ${m}`);b.push("")}if($.constraints.pii.length>0)b.push("## PII Fields"),b.push(""),b.push(`Handle carefully: ${$.constraints.pii.map((m)=>`\`${m}\``).join(", ")}`),b.push("");return{agent:"cursor-cli",systemPrompt:U5["cursor-cli"],taskPrompt:b.join(`
|
|
515
|
+
`)}}generateConfig($){let b=$.meta,A=[];if(A.push("---"),A.push(`description: Implementation rules for ${b.key}.v${b.version}`),A.push(`globs: ["**/${b.key.replace(/\./g,"/")}/**"]`),A.push("alwaysApply: false"),A.push("---"),A.push(""),A.push(`# ${b.key} Implementation Rules`),A.push(""),A.push(`This ${b.kind} operation must follow the ContractSpec specification.`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Requirements"),A.push(""),A.push("1. Input/output types MUST match the spec schema exactly"),A.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)A.push("3. Events MUST be emitted as specified");if(A.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)A.push(`5. Idempotency: ${$.policy.idempotent}`);if(A.push(""),$.io.errors&&Object.keys($.io.errors).length>0){A.push("## Error Cases"),A.push("");for(let[m,n]of Object.entries($.io.errors))A.push(`- \`${m}\` (HTTP ${n.http??400}): ${n.when}`);A.push("")}if($.sideEffects?.emits?.length){A.push("## Events to Emit"),A.push("");for(let m of $.sideEffects.emits)if("ref"in m)A.push(`- \`${m.ref.key}.v${m.ref.version}\`: ${m.when}`);else A.push(`- \`${m.key}.v${m.version}\`: ${m.when}`);A.push("")}if($.policy.pii?.length){A.push("## PII Handling"),A.push(""),A.push("These fields contain PII and must be handled with care:");for(let m of $.policy.pii)A.push(`- \`${m}\``);A.push("")}if($.acceptance?.scenarios?.length){A.push("## Acceptance Scenarios"),A.push("");for(let m of $.acceptance.scenarios)A.push(`### ${m.key}`),A.push(`- Given: ${m.given.join("; ")}`),A.push(`- When: ${m.when.join("; ")}`),A.push(`- Then: ${m.then.join("; ")}`),A.push("")}return A.join(`
|
|
516
|
+
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var HA=new YA;import{AGENT_SYSTEM_PROMPTS as z5}from"@contractspec/lib.contracts-spec/llm";class qA{agentType="generic-mcp";formatPlan($){let b=[];if(b.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),b.push(""),b.push("## Task"),b.push(""),b.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.target.version}.`),b.push(""),b.push("## Context"),b.push(""),b.push(`**Goal:** ${$.context.goal}`),b.push(""),b.push(`**Description:** ${$.context.description}`),b.push(""),$.context.background)b.push("**Background:**"),b.push(""),b.push($.context.background),b.push("");if(b.push("## Specification"),b.push(""),b.push($.specMarkdown),b.push(""),$.fileStructure.length>0){b.push("## Files"),b.push(""),b.push("| Path | Action | Purpose |"),b.push("|------|--------|---------|");for(let A of $.fileStructure)b.push(`| \`${A.path}\` | ${A.type} | ${A.purpose} |`);b.push("")}b.push("## Implementation Steps"),b.push("");for(let A of $.steps)if(b.push(`### Step ${A.order}: ${A.title}`),b.push(""),b.push(A.description),b.push(""),A.acceptanceCriteria.length>0){b.push("**Acceptance Criteria:**"),b.push("");for(let m of A.acceptanceCriteria)b.push(`- ${m}`);b.push("")}if(b.push("## Constraints"),b.push(""),$.constraints.policy.length>0){b.push("**Policy:**");for(let A of $.constraints.policy)b.push(`- ${A}`);b.push("")}if($.constraints.security.length>0){b.push("**Security:**");for(let A of $.constraints.security)b.push(`- ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("**PII Fields (handle with care):**");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}b.push("## Verification"),b.push(""),b.push("After implementation, verify:"),b.push("");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),{agent:"generic-mcp",systemPrompt:z5["generic-mcp"],taskPrompt:b.join(`
|
|
517
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,A=[];return A.push(`# ${b.key} v${b.version}`),A.push(""),A.push(`**Type:** ${b.kind}`),A.push(`**Stability:** ${b.stability}`),A.push(""),A.push("## Goal"),A.push(""),A.push(b.goal),A.push(""),A.push("## Description"),A.push(""),A.push(b.description),A.push(""),A.join(`
|
|
518
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let A=JSON.parse($);if(typeof A.code==="string")return{code:A.code};if(typeof A.errors==="object")return{errors:Array.isArray(A.errors)?A.errors:[String(A.errors)]}}catch{}return{code:$}}}var OA=new qA;var $m={"claude-code":XA,"cursor-cli":HA,"generic-mcp":OA};function Yb($){let b=$m[$];if(!b)throw Error(`Unknown agent type: ${$}`);return b}function bm(){return Object.keys($m)}import{featureToMarkdown as Am,generateImplementationPlan as rW,operationSpecToAgentPrompt as L5,operationSpecToFullMarkdown as R5}from"@contractspec/lib.contracts-spec/llm";var C5={defaultAgent:"generic-mcp",verbose:!1};class VA{config;constructor($={}){this.config={...C5,...$}}generateGuide($,b={}){let A=b.agent??this.config.defaultAgent,m=Yb(A),n=rW($,{projectRoot:this.config.projectRoot,existingFiles:b.targetPath?[b.targetPath]:void 0}),W=m.formatPlan(n),w=R5($);return{plan:n,prompt:W,markdown:w}}generateFeatureGuide($,b,A={}){let m=A.agent??this.config.defaultAgent,n=Yb(m),W=$.operations?.[0],w=W?b.specs?.get(W.key,W.version):void 0,j;if(w)j=rW(w,{projectRoot:this.config.projectRoot}),j.target={type:"feature",key:$.meta.key,version:"1.0.0"},j.context.goal=$.meta.description??j.context.goal;else j={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:Am($,b),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(j.specMarkdown=Am($,b,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)j.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 y=n.formatPlan(j),B=Am($,b);return{plan:j,prompt:y,markdown:B}}generateAgentConfig($,b){return Yb(b??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,b,A="implement",m){return L5($,{taskType:A,existingCode:m})}listAgentTypes(){return bm()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function I5($){return new VA($)}var E5=new VA;import{detectAuthoringTarget as K8,generateComponentTemplate as _8,generateHandlerTemplate as U8,generateTestTemplate as z8,getAuthoringTargetDefinition as L8,inferSpecTypeFromFilePath as R8,scanSpecSource as C8}from"@contractspec/module.workspace";var Kw={};P(Kw,{generateWorkflowSpec:()=>Jw,generateWorkflowRunnerTemplate:()=>EA,generateWorkflowDevkitWorkflowTemplate:()=>zA,generateWorkflowDevkitStreamRouteTemplate:()=>CA,generateWorkflowDevkitStartRouteTemplate:()=>LA,generateWorkflowDevkitGenericTemplate:()=>IA,generateWorkflowDevkitFollowUpRouteTemplate:()=>RA,generateVisualizationSpec:()=>oW,generateTranslationSpec:()=>dW,generateThemeSpec:()=>Vw,generateTestTemplate:()=>Sw,generateTestSpec:()=>cW,generateTelemetrySpec:()=>Ow,generateProductIntentSpec:()=>tW,generatePresentationSpec:()=>qw,generatePolicySpec:()=>hW,generateOperationSpec:()=>Hw,generateMigrationSpec:()=>Yw,generateKnowledgeSpaceSpec:()=>Gw,generateJobSpec:()=>uW,generateIntegrationSpec:()=>Zw,generateHarnessSuiteSpec:()=>aW,generateHarnessScenarioSpec:()=>pW,generateHandlerTemplate:()=>yw,generateFormSpec:()=>jw,generateFeatureSpec:()=>ww,generateExperimentSpec:()=>Ww,generateExampleSpec:()=>iW,generateEventSpec:()=>nw,generateDataViewSpec:()=>mw,generateDataViewRendererTemplate:()=>_A,generateComponentTemplate:()=>Bw,generateCapabilitySpec:()=>fW,generateAppBlueprintSpec:()=>Aw,generateAgentSpec:()=>lW});function fW($){return`import { defineCapability } from '@contractspec/lib.contracts-spec/capabilities';
|
|
519
|
+
|
|
520
|
+
export const ${a$($.key)}Capability = defineCapability({
|
|
521
|
+
meta: {
|
|
522
|
+
key: '${$.key}',
|
|
523
|
+
version: '${$.version}',
|
|
524
|
+
kind: '${$.kind??"api"}',
|
|
525
|
+
title: '${k(p$($))}',
|
|
526
|
+
description: '${k($.description)}',
|
|
527
|
+
domain: '${k(F$($))}',
|
|
528
|
+
owners: [${W$($.owners)}],
|
|
529
|
+
tags: [${W$($.tags)}],
|
|
530
|
+
stability: '${$.stability}',
|
|
531
|
+
},
|
|
532
|
+
provides: [],
|
|
533
|
+
requires: [],
|
|
534
|
+
});
|
|
535
|
+
`}function hW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
536
|
+
|
|
537
|
+
export const ${a$($.key)}Policy = definePolicy({
|
|
538
|
+
meta: {
|
|
539
|
+
key: '${$.key}',
|
|
540
|
+
version: '${$.version}',
|
|
541
|
+
title: '${k(p$($))}',
|
|
542
|
+
description: '${k($.description)}',
|
|
543
|
+
domain: '${k(F$($))}',
|
|
544
|
+
owners: [${W$($.owners)}],
|
|
545
|
+
tags: [${W$($.tags)}],
|
|
546
|
+
stability: '${$.stability}',
|
|
547
|
+
scope: '${$.scope??"feature"}',
|
|
548
|
+
},
|
|
549
|
+
rules: [
|
|
550
|
+
{
|
|
551
|
+
effect: 'allow',
|
|
552
|
+
actions: ['read'],
|
|
553
|
+
resource: { type: '${k(F$($))}' },
|
|
554
|
+
reason: 'TODO: replace with real access rules',
|
|
555
|
+
},
|
|
556
|
+
],
|
|
557
|
+
});
|
|
558
|
+
`}function cW($){let b=$.targetVersion??"1.0.0",A=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
559
|
+
|
|
560
|
+
export const ${a$($.key)}TestSpec = defineTestSpec({
|
|
561
|
+
meta: {
|
|
562
|
+
key: '${$.key}',
|
|
563
|
+
version: '${$.version}',
|
|
564
|
+
title: '${k(p$($))}',
|
|
565
|
+
description: '${k($.description)}',
|
|
566
|
+
domain: '${k(F$($))}',
|
|
567
|
+
owners: [${W$($.owners)}],
|
|
568
|
+
tags: [${W$($.tags)}],
|
|
569
|
+
stability: '${$.stability}',
|
|
570
|
+
},
|
|
571
|
+
target: {
|
|
572
|
+
type: '${$.targetType}',
|
|
573
|
+
${$.targetType}: ${A},
|
|
574
|
+
},
|
|
575
|
+
scenarios: [
|
|
576
|
+
{
|
|
577
|
+
key: 'success',
|
|
578
|
+
when: { ${$.targetType}: { key: '${$.targetKey}' } },
|
|
579
|
+
then: [{ type: 'expectOutput', match: {} }],
|
|
580
|
+
},
|
|
581
|
+
],
|
|
582
|
+
});
|
|
583
|
+
`}function dW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
584
|
+
|
|
585
|
+
export const ${a$(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
586
|
+
meta: {
|
|
587
|
+
key: '${$.key}',
|
|
588
|
+
version: '${$.version}',
|
|
589
|
+
domain: '${k(F$($))}',
|
|
590
|
+
description: '${k($.description)}',
|
|
591
|
+
owners: [${W$($.owners)}],
|
|
592
|
+
tags: [${W$($.tags)}],
|
|
593
|
+
stability: '${$.stability}',
|
|
594
|
+
},
|
|
595
|
+
locale: '${$.locale}',
|
|
596
|
+
fallback: '${$.fallback??$.locale}',
|
|
597
|
+
messages: {
|
|
598
|
+
'${$.key}.title': {
|
|
599
|
+
value: '${k(p$($))}',
|
|
600
|
+
description: 'TODO: replace with a real localized message',
|
|
601
|
+
},
|
|
602
|
+
},
|
|
603
|
+
});
|
|
604
|
+
`}function uW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
|
|
605
|
+
|
|
606
|
+
export const ${a$($.key)}Job = defineJob({
|
|
607
|
+
meta: {
|
|
608
|
+
key: '${$.key}',
|
|
609
|
+
version: '${$.version}',
|
|
610
|
+
title: '${k(p$($))}',
|
|
611
|
+
description: '${k($.description)}',
|
|
612
|
+
domain: '${k(F$($))}',
|
|
613
|
+
owners: [${W$($.owners)}],
|
|
614
|
+
tags: [${W$($.tags)}],
|
|
615
|
+
stability: '${$.stability}',
|
|
616
|
+
},
|
|
617
|
+
payload: { schema: {} },
|
|
618
|
+
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
619
|
+
});
|
|
620
|
+
`}function oW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
621
|
+
|
|
622
|
+
export const ${a$($.key)}Visualization = defineVisualization({
|
|
623
|
+
meta: {
|
|
624
|
+
key: '${$.key}',
|
|
625
|
+
version: '${$.version}',
|
|
626
|
+
title: '${k(p$($))}',
|
|
627
|
+
description: '${k($.description)}',
|
|
628
|
+
goal: 'TODO: describe the decision this visualization supports',
|
|
629
|
+
context: 'TODO: describe where this visualization appears',
|
|
630
|
+
domain: '${k(F$($))}',
|
|
631
|
+
owners: [${W$($.owners)}],
|
|
632
|
+
tags: [${W$($.tags)}],
|
|
633
|
+
stability: '${$.stability}',
|
|
634
|
+
},
|
|
635
|
+
source: {
|
|
636
|
+
primary: {
|
|
637
|
+
key: '${$.sourceOperationKey}',
|
|
638
|
+
version: '${$.sourceOperationVersion??"1.0.0"}',
|
|
639
|
+
},
|
|
640
|
+
resultPath: 'data',
|
|
641
|
+
},
|
|
642
|
+
visualization: {
|
|
643
|
+
kind: 'metric',
|
|
644
|
+
measures: [{ key: 'value', label: 'Value', dataPath: 'value', format: 'number' }],
|
|
645
|
+
measure: 'value',
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
`}function p$($){return $.title??M5($.key.split(".").at(-1)??$.key)}function F$($){return $.domain??$.key.split(".")[0]??"contractspec"}function W$($){return $.map((b)=>`'${k(b)}'`).join(", ")}function a$($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function M5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function k($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function iW($){let b=$.packageName??`@contractspec/example.${T5($.key.split(".").at(-1)??$.key)}`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
649
|
+
|
|
650
|
+
export const ${Hb($.key)}Example = defineExample({
|
|
651
|
+
meta: {
|
|
652
|
+
key: '${$.key}',
|
|
653
|
+
version: '${$.version}',
|
|
654
|
+
title: '${i(JA($))}',
|
|
655
|
+
description: '${i($.description)}',
|
|
656
|
+
kind: 'template',
|
|
657
|
+
visibility: 'experimental',
|
|
658
|
+
stability: '${$.stability}',
|
|
659
|
+
owners: [${B$($.owners)}],
|
|
660
|
+
tags: [${B$($.tags)}],
|
|
661
|
+
},
|
|
662
|
+
surfaces: {
|
|
663
|
+
templates: true,
|
|
664
|
+
sandbox: { enabled: true, modes: ['playground', 'specs'] },
|
|
665
|
+
studio: { enabled: false, installable: false },
|
|
666
|
+
mcp: { enabled: false },
|
|
667
|
+
},
|
|
668
|
+
entrypoints: {
|
|
669
|
+
packageName: '${b}',
|
|
670
|
+
},
|
|
671
|
+
});
|
|
672
|
+
`}function lW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
673
|
+
|
|
674
|
+
export const ${Hb($.key)}Agent = defineAgent({
|
|
675
|
+
meta: {
|
|
676
|
+
key: '${$.key}',
|
|
677
|
+
version: '${$.version}',
|
|
678
|
+
description: '${i($.description)}',
|
|
679
|
+
owners: [${B$($.owners)}],
|
|
680
|
+
tags: [${B$($.tags)}],
|
|
681
|
+
stability: '${$.stability}',
|
|
682
|
+
},
|
|
683
|
+
instructions: '${i($.instructions)}',
|
|
684
|
+
tools: [{ name: 'todo' }],
|
|
685
|
+
});
|
|
686
|
+
`}function tW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
687
|
+
|
|
688
|
+
export const ${Hb($.key)}ProductIntent = defineProductIntentSpec({
|
|
689
|
+
id: '${$.id??`${$.key}-run`}',
|
|
690
|
+
meta: {
|
|
691
|
+
key: '${$.key}',
|
|
692
|
+
version: '${$.version}',
|
|
693
|
+
title: '${i(JA($))}',
|
|
694
|
+
description: '${i($.description)}',
|
|
695
|
+
goal: 'TODO: capture the desired product outcome',
|
|
696
|
+
context: 'TODO: capture the decision context',
|
|
697
|
+
stability: '${$.stability}',
|
|
698
|
+
owners: [${B$($.owners)}],
|
|
699
|
+
tags: [${B$($.tags)}],
|
|
700
|
+
},
|
|
701
|
+
question: '${i($.question)}',
|
|
702
|
+
insights: { insights: [] },
|
|
703
|
+
});
|
|
704
|
+
`}function pW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
705
|
+
|
|
706
|
+
export const ${Hb($.key)}HarnessScenario = defineHarnessScenario({
|
|
707
|
+
meta: {
|
|
708
|
+
key: '${$.key}',
|
|
709
|
+
version: '${$.version}',
|
|
710
|
+
title: '${i(JA($))}',
|
|
711
|
+
description: '${i($.description)}',
|
|
712
|
+
domain: '${i(eW($))}',
|
|
713
|
+
owners: [${B$($.owners)}],
|
|
714
|
+
tags: [${B$($.tags)}],
|
|
715
|
+
stability: '${$.stability}',
|
|
716
|
+
},
|
|
717
|
+
target: {
|
|
718
|
+
isolation: 'preview',
|
|
719
|
+
preferredTargets: ['preview'],
|
|
720
|
+
},
|
|
721
|
+
allowedModes: ['deterministic-browser'],
|
|
722
|
+
steps: [
|
|
723
|
+
{
|
|
724
|
+
key: 'open-home',
|
|
725
|
+
description: 'Open the target application',
|
|
726
|
+
actionClass: 'navigate',
|
|
727
|
+
intent: 'Navigate to the primary page under test.',
|
|
728
|
+
},
|
|
729
|
+
],
|
|
730
|
+
assertions: [
|
|
731
|
+
{
|
|
732
|
+
key: 'step-completes',
|
|
733
|
+
type: 'step-status',
|
|
734
|
+
description: 'TODO: replace with a real scenario assertion',
|
|
735
|
+
match: 'completed',
|
|
736
|
+
},
|
|
737
|
+
],
|
|
738
|
+
});
|
|
739
|
+
`}function aW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
740
|
+
|
|
741
|
+
export const ${Hb($.key)}HarnessSuite = defineHarnessSuite({
|
|
742
|
+
meta: {
|
|
743
|
+
key: '${$.key}',
|
|
744
|
+
version: '${$.version}',
|
|
745
|
+
title: '${i(JA($))}',
|
|
746
|
+
description: '${i($.description)}',
|
|
747
|
+
domain: '${i(eW($))}',
|
|
748
|
+
owners: [${B$($.owners)}],
|
|
749
|
+
tags: [${B$($.tags)}],
|
|
750
|
+
stability: '${$.stability}',
|
|
751
|
+
},
|
|
752
|
+
scenarios: [
|
|
753
|
+
{
|
|
754
|
+
scenario: {
|
|
755
|
+
key: '${$.scenarioKey}',
|
|
756
|
+
version: '${$.scenarioVersion??"1.0.0"}',
|
|
757
|
+
},
|
|
758
|
+
required: true,
|
|
759
|
+
weight: 1,
|
|
760
|
+
},
|
|
761
|
+
],
|
|
762
|
+
summary: '${i($.description)}',
|
|
763
|
+
tags: [${B$($.tags)}],
|
|
764
|
+
});
|
|
765
|
+
`}function JA($){return $.title??x5($.key.split(".").at(-1)??$.key)}function eW($){return $.domain??$.key.split(".")[0]??"contractspec"}function B$($){return $.map((b)=>`'${i(b)}'`).join(", ")}function Hb($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function x5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function T5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function i($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Aw($){let b=f5($.key.split(".").pop()??"App")+"AppConfig",A=D5($),m=N5($),n=sW("dataViews",$.dataViews),W=sW("workflows",$.workflows),w=F5($),j=v5($),y=g5($),B=k5($),S=P5($),Q=r5($),Z=$.notes?` notes: '${D($.notes)}',
|
|
518
766
|
`:"";return`import type { AppBlueprintSpec } from '@contractspec/lib.contracts-spec/app-config';
|
|
519
767
|
|
|
520
|
-
export const ${
|
|
768
|
+
export const ${b}: AppBlueprintSpec = {
|
|
521
769
|
meta: {
|
|
522
|
-
key: '${
|
|
523
|
-
version: ${$.version},
|
|
524
|
-
title: '${
|
|
525
|
-
description: '${
|
|
526
|
-
domain: '${
|
|
527
|
-
owners: [${$.owners.map((
|
|
528
|
-
tags: [${$.tags.map((
|
|
770
|
+
key: '${D($.key)}',
|
|
771
|
+
version: '${$.version}',
|
|
772
|
+
title: '${D($.title)}',
|
|
773
|
+
description: '${D($.description)}',
|
|
774
|
+
domain: '${D($.domain)}',
|
|
775
|
+
owners: [${$.owners.map((G)=>`'${D(G)}'`).join(", ")}],
|
|
776
|
+
tags: [${$.tags.map((G)=>`'${D(G)}'`).join(", ")}],
|
|
529
777
|
stability: '${$.stability}',
|
|
530
|
-
appId: '${
|
|
778
|
+
appId: '${D($.appId)}',
|
|
531
779
|
},
|
|
532
|
-
${
|
|
533
|
-
`}function
|
|
534
|
-
`:"",
|
|
780
|
+
${A}${m}${n}${W}${w}${j}${y}${B}${S}${Q}${Z}};
|
|
781
|
+
`}function D5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((m)=>$w(m)).join(", ")}],
|
|
782
|
+
`:"",A=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((m)=>$w(m)).join(", ")}],
|
|
535
783
|
`:"";return` capabilities: {
|
|
536
|
-
${
|
|
537
|
-
`}function
|
|
538
|
-
`:"",
|
|
784
|
+
${b}${A} },
|
|
785
|
+
`}function N5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((m)=>`{ key: '${D(m)}' }`).join(", ")}],
|
|
786
|
+
`:"",A=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((m)=>`{ key: '${D(m)}' }`).join(", ")}],
|
|
539
787
|
`:"";return` features: {
|
|
540
|
-
${
|
|
541
|
-
`}function
|
|
542
|
-
|
|
543
|
-
|
|
788
|
+
${b}${A} },
|
|
789
|
+
`}function sW($,b){if(b.length===0)return"";let A=b.map((m)=>` ${m.slot}: {
|
|
790
|
+
key: '${D(m.key)}'${m.version?`,
|
|
791
|
+
version: '${m.version}'`:""}
|
|
544
792
|
}`).join(`,
|
|
545
793
|
`);return` ${$}: {
|
|
546
|
-
${
|
|
794
|
+
${A}
|
|
547
795
|
},
|
|
548
|
-
`}function
|
|
549
|
-
${$.policyRefs.map((
|
|
550
|
-
|
|
551
|
-
version: '${
|
|
796
|
+
`}function F5($){if($.policyRefs.length===0)return"";return` policies: [
|
|
797
|
+
${$.policyRefs.map((A)=>` {
|
|
798
|
+
key: '${D(A.key)}'${A.version?`,
|
|
799
|
+
version: '${A.version}'`:""}
|
|
552
800
|
}`).join(`,
|
|
553
801
|
`)}
|
|
554
802
|
],
|
|
555
|
-
`}function
|
|
556
|
-
`,
|
|
803
|
+
`}function v5($){if(!$.theme)return"";let b=` primary: { key: '${D($.theme.key)}', version: '${$.theme.version}' },
|
|
804
|
+
`,A=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((m)=>`{ key: '${D(m.key)}', version: '${m.version}' }`).join(", ")}],
|
|
557
805
|
`:"";return` theme: {
|
|
558
|
-
${
|
|
559
|
-
`}function
|
|
806
|
+
${b}${A} },
|
|
807
|
+
`}function g5($){if(!$.telemetry)return"";return` telemetry: {
|
|
560
808
|
spec: {
|
|
561
|
-
|
|
809
|
+
key: '${D($.telemetry.key)}'${$.telemetry.version?`,
|
|
562
810
|
version: '${$.telemetry.version}'`:""}
|
|
563
811
|
},
|
|
564
812
|
},
|
|
565
|
-
`}function
|
|
566
|
-
`:"",
|
|
813
|
+
`}function k5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((m)=>bw(m)).join(", ")}],
|
|
814
|
+
`:"",A=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((m)=>bw(m)).join(", ")}],
|
|
567
815
|
`:"";return` experiments: {
|
|
568
|
-
${
|
|
569
|
-
`}function
|
|
570
|
-
${$.featureFlags.map((
|
|
571
|
-
key: '${
|
|
572
|
-
enabled: ${
|
|
573
|
-
${
|
|
574
|
-
${
|
|
816
|
+
${b}${A} },
|
|
817
|
+
`}function P5($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
818
|
+
${$.featureFlags.map((A)=>` {
|
|
819
|
+
key: '${D(A.key)}',
|
|
820
|
+
enabled: ${A.enabled},
|
|
821
|
+
${A.variant?`variant: '${D(A.variant)}',`:""}
|
|
822
|
+
${A.description?`description: '${D(A.description)}',`:""}
|
|
575
823
|
}`).join(`,
|
|
576
824
|
`)}
|
|
577
825
|
],
|
|
578
|
-
`}function
|
|
579
|
-
${$.routes.map((
|
|
826
|
+
`}function r5($){if($.routes.length===0)return"";return` routes: [
|
|
827
|
+
${$.routes.map((A)=>{return` { ${[`path: '${D(A.path)}'`,A.label?`label: '${D(A.label)}'`:null,A.dataView?`dataView: '${D(A.dataView)}'`:null,A.workflow?`workflow: '${D(A.workflow)}'`:null,A.guardKey?`guard: { key: '${D(A.guardKey)}'${A.guardVersion?`, version: '${A.guardVersion}'`:""} }`:null,A.featureFlag?`featureFlag: '${D(A.featureFlag)}'`:null,A.experimentKey?`experiment: { key: '${D(A.experimentKey)}'${A.experimentVersion?`, version: '${A.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
580
828
|
`)}
|
|
581
829
|
],
|
|
582
|
-
`}function
|
|
583
|
-
key: '${
|
|
584
|
-
label: '${
|
|
585
|
-
dataPath: '${
|
|
586
|
-
${
|
|
587
|
-
${
|
|
588
|
-
${
|
|
830
|
+
`}function $w($){return`{ key: '${D($)}' }`}function bw($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${D($.key)}'${b} }`}function f5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function D($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function mw($){let b=h5($.name.split(".").pop()??"DataView")+"DataView",A=$.fields.map((W)=>` {
|
|
831
|
+
key: '${W.key}',
|
|
832
|
+
label: '${KA(W.label)}',
|
|
833
|
+
dataPath: '${W.dataPath}',
|
|
834
|
+
${W.format?`format: '${W.format}',`:""}
|
|
835
|
+
${W.sortable?"sortable: true,":""}
|
|
836
|
+
${W.filterable?"filterable: true,":""}
|
|
589
837
|
}`).join(`,
|
|
590
|
-
`),
|
|
838
|
+
`),m=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((W)=>`'${W}'`).join(", ")}],`:"",n=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
591
839
|
|
|
592
|
-
export const ${
|
|
840
|
+
export const ${b}: DataViewSpec = {
|
|
593
841
|
meta: {
|
|
594
842
|
key: '${$.name}',
|
|
595
843
|
version: ${$.version},
|
|
596
844
|
entity: '${$.entity}',
|
|
597
|
-
title: '${
|
|
598
|
-
description: '${
|
|
599
|
-
domain: '${
|
|
600
|
-
owners: [${$.owners.map((
|
|
601
|
-
tags: [${$.tags.map((
|
|
845
|
+
title: '${KA($.title)}',
|
|
846
|
+
description: '${KA($.description||"Describe the purpose of this data view.")}',
|
|
847
|
+
domain: '${KA($.domain||$.entity)}',
|
|
848
|
+
owners: [${$.owners.map((W)=>`'${W}'`).join(", ")}],
|
|
849
|
+
tags: [${$.tags.map((W)=>`'${W}'`).join(", ")}],
|
|
602
850
|
stability: '${$.stability}',
|
|
603
851
|
},
|
|
604
852
|
source: {
|
|
@@ -606,7 +854,7 @@ export const ${W}: DataViewSpec = {
|
|
|
606
854
|
name: '${$.primaryOperation.name}',
|
|
607
855
|
version: ${$.primaryOperation.version},
|
|
608
856
|
},
|
|
609
|
-
${
|
|
857
|
+
${n}
|
|
610
858
|
refreshEvents: [
|
|
611
859
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
612
860
|
],
|
|
@@ -614,10 +862,10 @@ export const ${W}: DataViewSpec = {
|
|
|
614
862
|
view: {
|
|
615
863
|
kind: '${$.kind}',
|
|
616
864
|
fields: [
|
|
617
|
-
${
|
|
865
|
+
${A}
|
|
618
866
|
],
|
|
619
867
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
620
|
-
${
|
|
868
|
+
${m}
|
|
621
869
|
filters: [
|
|
622
870
|
// Example filter:
|
|
623
871
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -632,13 +880,13 @@ ${j}
|
|
|
632
880
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
633
881
|
},
|
|
634
882
|
};
|
|
635
|
-
`}function
|
|
883
|
+
`}function h5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function KA($){return $.replace(/'/g,"\\'")}function _A({exportName:$,specImportPath:b,rendererName:A,viewKind:m}){return`'use client';
|
|
636
884
|
|
|
637
885
|
import * as React from 'react';
|
|
638
886
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
639
|
-
import { ${$} } from '${
|
|
887
|
+
import { ${$} } from '${b}';
|
|
640
888
|
|
|
641
|
-
export interface ${
|
|
889
|
+
export interface ${A}Props {
|
|
642
890
|
items?: Record<string, unknown>[];
|
|
643
891
|
item?: Record<string, unknown> | null;
|
|
644
892
|
className?: string;
|
|
@@ -648,17 +896,17 @@ export interface ${j}Props {
|
|
|
648
896
|
}
|
|
649
897
|
|
|
650
898
|
/**
|
|
651
|
-
* Auto-generated renderer for the "${
|
|
899
|
+
* Auto-generated renderer for the "${m}" data view.
|
|
652
900
|
* Customize as needed for app-specific behaviour.
|
|
653
901
|
*/
|
|
654
|
-
export function ${
|
|
902
|
+
export function ${A}({
|
|
655
903
|
items = [],
|
|
656
904
|
item = null,
|
|
657
905
|
className,
|
|
658
906
|
renderActions,
|
|
659
907
|
onSelect,
|
|
660
908
|
onRowClick,
|
|
661
|
-
}: ${
|
|
909
|
+
}: ${A}Props) {
|
|
662
910
|
return (
|
|
663
911
|
<DataViewRenderer
|
|
664
912
|
spec={${$}}
|
|
@@ -671,93 +919,93 @@ export function ${j}({
|
|
|
671
919
|
/>
|
|
672
920
|
);
|
|
673
921
|
}
|
|
674
|
-
`}function
|
|
922
|
+
`}function nw($){let{name:b,version:A,description:m,stability:n,owners:W,tags:w,piiFields:j}=$,y=c5(b.replace(/\./g,"_"))+"V"+A,B=y+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
675
923
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
676
924
|
|
|
677
925
|
// TODO: Define event payload schema
|
|
678
|
-
export const ${
|
|
679
|
-
name: '${
|
|
680
|
-
description: 'Payload for ${
|
|
926
|
+
export const ${B} = new SchemaModel({
|
|
927
|
+
name: '${B}',
|
|
928
|
+
description: 'Payload for ${b}',
|
|
681
929
|
fields: {
|
|
682
930
|
// Add your payload fields here
|
|
683
931
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
684
932
|
},
|
|
685
933
|
});
|
|
686
934
|
|
|
687
|
-
export const ${
|
|
688
|
-
name: '${
|
|
689
|
-
name: '${
|
|
690
|
-
version: '${
|
|
691
|
-
description: '${
|
|
692
|
-
description: '${
|
|
693
|
-
stability: '${
|
|
694
|
-
owners: [${
|
|
695
|
-
tags: [${
|
|
696
|
-
${
|
|
697
|
-
payload: ${
|
|
935
|
+
export const ${y} = defineEvent({
|
|
936
|
+
name: '${b}',
|
|
937
|
+
name: '${b}',
|
|
938
|
+
version: '${A}',
|
|
939
|
+
description: '${m}',
|
|
940
|
+
description: '${m}',
|
|
941
|
+
stability: '${n}',
|
|
942
|
+
owners: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
943
|
+
tags: [${w.map((S)=>`'${S}'`).join(", ")}],
|
|
944
|
+
${j.length>0?`pii: [${j.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
945
|
+
payload: ${B},
|
|
698
946
|
});
|
|
699
|
-
`}function
|
|
700
|
-
${
|
|
701
|
-
type: '${
|
|
702
|
-
target: '${
|
|
703
|
-
${typeof
|
|
947
|
+
`}function c5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ww($){let b=u5($.name.split(".").pop()??"Experiment")+"Experiment",A=$.variants.map((W)=>{let w=W.overrides?.length?` overrides: [
|
|
948
|
+
${W.overrides.map((j)=>` {
|
|
949
|
+
type: '${j.type}',
|
|
950
|
+
target: '${f(j.target)}',
|
|
951
|
+
${typeof j.version==="string"?`version: ${j.version},`:""}
|
|
704
952
|
}`).join(`,
|
|
705
953
|
`)}
|
|
706
954
|
],`:"";return` {
|
|
707
|
-
id: '${
|
|
708
|
-
name: '${
|
|
709
|
-
${
|
|
710
|
-
${typeof
|
|
711
|
-
${
|
|
955
|
+
id: '${f(W.id)}',
|
|
956
|
+
name: '${f(W.name)}',
|
|
957
|
+
${W.description?`description: '${f(W.description)}',`:""}
|
|
958
|
+
${typeof W.weight==="number"?`weight: ${W.weight},`:""}
|
|
959
|
+
${w}
|
|
712
960
|
}`}).join(`,
|
|
713
|
-
`),
|
|
714
|
-
${$.successMetrics.map((
|
|
715
|
-
name: '${
|
|
716
|
-
telemetryEvent: { name: '${
|
|
717
|
-
aggregation: '${
|
|
718
|
-
${typeof
|
|
961
|
+
`),m=d5($.allocation),n=$.successMetrics?.length?` successMetrics: [
|
|
962
|
+
${$.successMetrics.map((W)=>` {
|
|
963
|
+
name: '${f(W.name)}',
|
|
964
|
+
telemetryEvent: { name: '${f(W.eventName)}', version: ${typeof W.eventVersion==="string"?`'${W.eventVersion}'`:W.eventVersion} },
|
|
965
|
+
aggregation: '${W.aggregation}',
|
|
966
|
+
${typeof W.target==="number"?`target: ${W.target},`:""}
|
|
719
967
|
}`).join(`,
|
|
720
968
|
`)}
|
|
721
969
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
722
970
|
|
|
723
|
-
export const ${
|
|
971
|
+
export const ${b}: ExperimentSpec = {
|
|
724
972
|
meta: {
|
|
725
|
-
key: '${
|
|
973
|
+
key: '${f($.name)}',
|
|
726
974
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
727
|
-
title: '${
|
|
728
|
-
description: '${
|
|
729
|
-
domain: '${
|
|
730
|
-
owners: [${$.owners.map((
|
|
731
|
-
tags: [${$.tags.map((
|
|
975
|
+
title: '${f($.name)} experiment',
|
|
976
|
+
description: '${f($.description||"Describe the experiment goal.")}',
|
|
977
|
+
domain: '${f($.domain)}',
|
|
978
|
+
owners: [${$.owners.map((W)=>`'${f(W)}'`).join(", ")}],
|
|
979
|
+
tags: [${$.tags.map((W)=>`'${f(W)}'`).join(", ")}],
|
|
732
980
|
stability: '${$.stability}',
|
|
733
981
|
},
|
|
734
|
-
controlVariant: '${
|
|
982
|
+
controlVariant: '${f($.controlVariant)}',
|
|
735
983
|
variants: [
|
|
736
|
-
${
|
|
984
|
+
${A}
|
|
737
985
|
],
|
|
738
|
-
allocation: ${
|
|
739
|
-
${
|
|
986
|
+
allocation: ${m},
|
|
987
|
+
${n}
|
|
740
988
|
};
|
|
741
|
-
`}function
|
|
989
|
+
`}function d5($){switch($.type){case"random":return`{
|
|
742
990
|
type: 'random',
|
|
743
|
-
${$.salt?`salt: '${
|
|
991
|
+
${$.salt?`salt: '${f($.salt)}',`:""}
|
|
744
992
|
}`;case"sticky":return`{
|
|
745
993
|
type: 'sticky',
|
|
746
994
|
attribute: '${$.attribute}',
|
|
747
|
-
${$.salt?`salt: '${
|
|
995
|
+
${$.salt?`salt: '${f($.salt)}',`:""}
|
|
748
996
|
}`;case"targeted":return`{
|
|
749
997
|
type: 'targeted',
|
|
750
998
|
rules: [
|
|
751
|
-
${$.rules.map((
|
|
752
|
-
variantId: '${
|
|
753
|
-
${typeof
|
|
754
|
-
${
|
|
755
|
-
${
|
|
999
|
+
${$.rules.map((b)=>` {
|
|
1000
|
+
variantId: '${f(b.variantId)}',
|
|
1001
|
+
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1002
|
+
${b.policy?`policy: { name: '${f(b.policy.name)}'${b.policy.version!==void 0?`, version: ${typeof b.policy.version==="string"?`'${b.policy.version}'`:b.policy.version}`:""} },`:""}
|
|
1003
|
+
${b.expression?`expression: '${f(b.expression)}',`:""}
|
|
756
1004
|
}`).join(`,
|
|
757
1005
|
`)}
|
|
758
1006
|
],
|
|
759
1007
|
fallback: '${$.fallback??"control"}',
|
|
760
|
-
}`;default:return
|
|
1008
|
+
}`;default:return o5($)}}function u5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function o5($){throw Error(`Unsupported allocation type ${$}`)}function i5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function ww($){let b=(A)=>A.map((m)=>` { key: '${m.key}', version: '${m.version}' },`).join(`
|
|
761
1009
|
`);return`/**
|
|
762
1010
|
* ${$.title} Feature
|
|
763
1011
|
*
|
|
@@ -766,35 +1014,35 @@ ${$.rules.map((W)=>` {
|
|
|
766
1014
|
|
|
767
1015
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
768
1016
|
|
|
769
|
-
export const ${
|
|
1017
|
+
export const ${i5($.key)}Feature = defineFeature({
|
|
770
1018
|
meta: {
|
|
771
1019
|
key: '${$.key}',
|
|
772
1020
|
version: '${$.version}',
|
|
773
1021
|
title: '${$.title}',
|
|
774
1022
|
description: '${$.description||"TODO: Add description"}',
|
|
775
1023
|
domain: '${$.domain}',
|
|
776
|
-
owners: [${$.owners.map((
|
|
777
|
-
tags: [${$.tags.map((
|
|
1024
|
+
owners: [${$.owners.map((A)=>`'${A}'`).join(", ")}],
|
|
1025
|
+
tags: [${$.tags.map((A)=>`'${A}'`).join(", ")}],
|
|
778
1026
|
stability: '${$.stability||"beta"}',
|
|
779
1027
|
},
|
|
780
1028
|
|
|
781
1029
|
operations: [
|
|
782
|
-
${
|
|
1030
|
+
${b($.operations)||" // Add operations here"}
|
|
783
1031
|
],
|
|
784
1032
|
|
|
785
1033
|
events: [
|
|
786
|
-
${
|
|
1034
|
+
${b($.events)||" // Add events here"}
|
|
787
1035
|
],
|
|
788
1036
|
|
|
789
1037
|
presentations: [
|
|
790
|
-
${
|
|
1038
|
+
${b($.presentations)||" // Add presentations here"}
|
|
791
1039
|
],
|
|
792
1040
|
|
|
793
1041
|
experiments: [
|
|
794
|
-
${
|
|
1042
|
+
${b($.experiments)||" // Add experiments here"}
|
|
795
1043
|
],
|
|
796
1044
|
});
|
|
797
|
-
`}function
|
|
1045
|
+
`}function l5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function jw($){let b=l5($.key),A=`${b}FormModel`,m=`${b}Form`;return`/**
|
|
798
1046
|
* ${$.title} Form
|
|
799
1047
|
*
|
|
800
1048
|
* Auto-generated form spec.
|
|
@@ -803,8 +1051,8 @@ ${W($.experiments)||" // Add experiments here"}
|
|
|
803
1051
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
804
1052
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
805
1053
|
|
|
806
|
-
const ${
|
|
807
|
-
name: '${
|
|
1054
|
+
const ${A} = defineSchemaModel({
|
|
1055
|
+
name: '${A}',
|
|
808
1056
|
description: '${$.description||"TODO: Add form model description"}',
|
|
809
1057
|
fields: {
|
|
810
1058
|
${$.primaryFieldKey}: {
|
|
@@ -814,18 +1062,18 @@ const ${j} = defineSchemaModel({
|
|
|
814
1062
|
},
|
|
815
1063
|
});
|
|
816
1064
|
|
|
817
|
-
export const ${
|
|
1065
|
+
export const ${m} = defineFormSpec({
|
|
818
1066
|
meta: {
|
|
819
1067
|
key: '${$.key}',
|
|
820
1068
|
version: '${$.version}',
|
|
821
1069
|
title: '${$.title}',
|
|
822
1070
|
description: '${$.description||"TODO: Add description"}',
|
|
823
1071
|
domain: '${$.domain}',
|
|
824
|
-
owners: [${$.owners.map((
|
|
825
|
-
tags: [${$.tags.map((
|
|
1072
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1073
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
826
1074
|
stability: '${$.stability||"beta"}',
|
|
827
1075
|
},
|
|
828
|
-
model: ${
|
|
1076
|
+
model: ${A},
|
|
829
1077
|
fields: [
|
|
830
1078
|
{
|
|
831
1079
|
kind: 'text',
|
|
@@ -850,17 +1098,17 @@ export const ${A} = defineFormSpec({
|
|
|
850
1098
|
form: 'react-hook-form',
|
|
851
1099
|
},
|
|
852
1100
|
});
|
|
853
|
-
`}function
|
|
854
|
-
import { ${
|
|
1101
|
+
`}function yw($,b){let A=t5($.split(".").pop()||"unknown")+"Handler",m=UA($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1102
|
+
import { ${m} } from '../contracts/${Qw($)}.contracts';
|
|
855
1103
|
|
|
856
1104
|
/**
|
|
857
1105
|
* Handler for ${$}
|
|
858
1106
|
*/
|
|
859
|
-
export const ${
|
|
1107
|
+
export const ${A}: ContractHandler<typeof ${m}> = async (
|
|
860
1108
|
input,
|
|
861
1109
|
context
|
|
862
1110
|
) => {
|
|
863
|
-
// TODO: Implement ${
|
|
1111
|
+
// TODO: Implement ${b} logic
|
|
864
1112
|
|
|
865
1113
|
try {
|
|
866
1114
|
// 1. Validate prerequisites
|
|
@@ -876,28 +1124,28 @@ export const ${j}: ContractHandler<typeof ${A}> = async (
|
|
|
876
1124
|
throw error;
|
|
877
1125
|
}
|
|
878
1126
|
};
|
|
879
|
-
`}function
|
|
1127
|
+
`}function Bw($,b){let A=UA($);return`import React from 'react';
|
|
880
1128
|
|
|
881
|
-
interface ${
|
|
1129
|
+
interface ${A}Props {
|
|
882
1130
|
// TODO: Define props based on presentation spec
|
|
883
1131
|
}
|
|
884
1132
|
|
|
885
1133
|
/**
|
|
886
|
-
* ${
|
|
1134
|
+
* ${b}
|
|
887
1135
|
*/
|
|
888
|
-
export const ${
|
|
1136
|
+
export const ${A}: React.FC<${A}Props> = (props) => {
|
|
889
1137
|
return (
|
|
890
1138
|
<div>
|
|
891
1139
|
{/* TODO: Implement component UI */}
|
|
892
|
-
<p>Component: ${
|
|
1140
|
+
<p>Component: ${A}</p>
|
|
893
1141
|
</div>
|
|
894
1142
|
);
|
|
895
1143
|
};
|
|
896
|
-
`}function
|
|
897
|
-
import { ${
|
|
1144
|
+
`}function Sw($,b){let A=b==="handler"?"../handlers":"../components",m=UA($);return`import { describe, it, expect } from 'bun:test';
|
|
1145
|
+
import { ${m} } from '${A}/${Qw($)}';
|
|
898
1146
|
|
|
899
|
-
describe('${
|
|
900
|
-
it('should ${
|
|
1147
|
+
describe('${m}', () => {
|
|
1148
|
+
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
901
1149
|
// TODO: Implement test
|
|
902
1150
|
expect(true).toBe(true);
|
|
903
1151
|
});
|
|
@@ -906,170 +1154,170 @@ describe('${A}', () => {
|
|
|
906
1154
|
// TODO: Test edge cases
|
|
907
1155
|
});
|
|
908
1156
|
|
|
909
|
-
${
|
|
1157
|
+
${b==="handler"?`it('should handle errors appropriately', async () => {
|
|
910
1158
|
// TODO: Test error scenarios
|
|
911
1159
|
});`:`it('should be accessible', async () => {
|
|
912
1160
|
// TODO: Test accessibility
|
|
913
1161
|
});`}
|
|
914
1162
|
});
|
|
915
|
-
`}function
|
|
916
|
-
`),
|
|
917
|
-
${$.capabilitiesRequired.map((
|
|
1163
|
+
`}function t5($){let b=UA($);return b.charAt(0).toLowerCase()+b.slice(1)}function UA($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Qw($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Zw($){let b=n8($.name.split(".").pop()??"Integration"),A=`${b}IntegrationSpec`,m=`register${b}Integration`,n=$.supportedModes.length?$.supportedModes:["managed"],W=n.map((Y)=>`'${Y}'`).join(", "),w=$.capabilitiesProvided.map((Y)=>` { key: '${Y.key}', version: '${Y.version}' }`).join(`,
|
|
1164
|
+
`),j=$.capabilitiesRequired.length>0?` requires: [
|
|
1165
|
+
${$.capabilitiesRequired.map((Y)=>{let V=Y.version!==void 0?`, version: '${Y.version}'`:"",O=Y.optional?", optional: true":"",K=Y.reason?`, reason: '${w$(Y.reason)}'`:"";return` { key: '${Y.key}'${V}${O}${K} }`}).join(`,
|
|
918
1166
|
`)}
|
|
919
|
-
],`:"",
|
|
920
|
-
`:"",
|
|
1167
|
+
],`:"",y=p5($.configFields),B=e5($.configFields),S=a5($.secretFields),Q=s5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
|
|
1168
|
+
`:"",G=$8($.rateLimitRpm,$.rateLimitRph),X=b8(n,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
921
1169
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
922
1170
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
923
1171
|
|
|
924
|
-
export const ${
|
|
1172
|
+
export const ${A}: IntegrationSpec = {
|
|
925
1173
|
meta: {
|
|
926
1174
|
key: '${$.name}',
|
|
927
1175
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
928
1176
|
category: '${$.category}',
|
|
929
|
-
displayName: '${
|
|
930
|
-
title: '${
|
|
931
|
-
description: '${
|
|
932
|
-
domain: '${
|
|
933
|
-
owners: [${$.owners.map((
|
|
934
|
-
tags: [${$.tags.map((
|
|
935
|
-
stability: StabilityEnum.${
|
|
936
|
-
},
|
|
937
|
-
supportedModes: [${
|
|
1177
|
+
displayName: '${w$($.displayName)}',
|
|
1178
|
+
title: '${w$($.title)}',
|
|
1179
|
+
description: '${w$($.description)}',
|
|
1180
|
+
domain: '${w$($.domain)}',
|
|
1181
|
+
owners: [${$.owners.map((Y)=>`'${w$(Y)}'`).join(", ")}],
|
|
1182
|
+
tags: [${$.tags.map((Y)=>`'${w$(Y)}'`).join(", ")}],
|
|
1183
|
+
stability: StabilityEnum.${m8($.stability)},
|
|
1184
|
+
},
|
|
1185
|
+
supportedModes: [${W}],
|
|
938
1186
|
capabilities: {
|
|
939
1187
|
provides: [
|
|
940
|
-
${
|
|
1188
|
+
${w}
|
|
941
1189
|
],
|
|
942
|
-
${
|
|
1190
|
+
${j.length>0?`${j}
|
|
943
1191
|
`:""} },
|
|
944
1192
|
configSchema: {
|
|
945
|
-
${
|
|
946
|
-
example: ${
|
|
1193
|
+
${y}
|
|
1194
|
+
example: ${B},
|
|
947
1195
|
},
|
|
948
1196
|
secretSchema: {
|
|
949
|
-
${
|
|
950
|
-
example: ${
|
|
1197
|
+
${S}
|
|
1198
|
+
example: ${Q},
|
|
951
1199
|
},
|
|
952
|
-
${
|
|
1200
|
+
${Z}${G}${X} healthCheck: {
|
|
953
1201
|
method: '${$.healthCheckMethod}',
|
|
954
1202
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
955
1203
|
},
|
|
956
1204
|
};
|
|
957
1205
|
|
|
958
|
-
export function ${
|
|
1206
|
+
export function ${m}(
|
|
959
1207
|
registry: IntegrationSpecRegistry
|
|
960
1208
|
): IntegrationSpecRegistry {
|
|
961
|
-
return registry.register(${
|
|
1209
|
+
return registry.register(${A});
|
|
962
1210
|
}
|
|
963
|
-
`}function
|
|
964
|
-
`:"",
|
|
1211
|
+
`}function p5($){let b=$.filter((n)=>n.required),A=b.length>0?` required: [${b.map((n)=>`'${n.key}'`).join(", ")}],
|
|
1212
|
+
`:"",m=$.length?$.map((n)=>{let W=n.description?`, description: '${w$(n.description)}'`:"";return` ${n.key}: { type: '${A8(n.type)}'${W} }`}).join(`,
|
|
965
1213
|
`):"";return` schema: {
|
|
966
1214
|
type: 'object',
|
|
967
|
-
${
|
|
968
|
-
${
|
|
1215
|
+
${A} properties: {
|
|
1216
|
+
${m||" "}
|
|
969
1217
|
},
|
|
970
1218
|
},
|
|
971
|
-
`}function
|
|
972
|
-
`:"",
|
|
1219
|
+
`}function a5($){let b=$.filter((n)=>n.required),A=b.length>0?` required: [${b.map((n)=>`'${n.key}'`).join(", ")}],
|
|
1220
|
+
`:"",m=$.length?$.map((n)=>{let W=n.description?`, description: '${w$(n.description)}'`:"";return` ${n.key}: { type: 'string'${W} }`}).join(`,
|
|
973
1221
|
`):"";return` schema: {
|
|
974
1222
|
type: 'object',
|
|
975
|
-
${
|
|
976
|
-
${
|
|
1223
|
+
${A} properties: {
|
|
1224
|
+
${m||" "}
|
|
977
1225
|
},
|
|
978
1226
|
},
|
|
979
|
-
`}function
|
|
980
|
-
${$.map((
|
|
1227
|
+
`}function e5($){if($.length===0)return"{}";return`{
|
|
1228
|
+
${$.map((A)=>{switch(A.type){case"number":return` ${A.key}: 0`;case"boolean":return` ${A.key}: true`;case"string":default:return` ${A.key}: '${A.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
981
1229
|
`)}
|
|
982
|
-
}`}function
|
|
983
|
-
${$.map((
|
|
1230
|
+
}`}function s5($){if($.length===0)return"{}";return`{
|
|
1231
|
+
${$.map((A)=>` ${A.key}: '${A.key.toUpperCase()}_SECRET'`).join(`,
|
|
984
1232
|
`)}
|
|
985
|
-
}`}function
|
|
1233
|
+
}`}function $8($,b){if($==null&&b==null)return"";let A=[];if($!=null)A.push(` rpm: ${$}`);if(b!=null)A.push(` rph: ${b}`);return` constraints: {
|
|
986
1234
|
rateLimit: {
|
|
987
|
-
${
|
|
1235
|
+
${A.join(`,
|
|
988
1236
|
`)}
|
|
989
1237
|
},
|
|
990
1238
|
},
|
|
991
|
-
`}function
|
|
992
|
-
`:"",
|
|
993
|
-
`:"";if(!
|
|
994
|
-
${
|
|
995
|
-
`}function
|
|
1239
|
+
`}function b8($,b,A){if(!$.includes("byok"))return"";let m=b?` setupInstructions: '${w$(b)}',
|
|
1240
|
+
`:"",n=A&&A.length?` requiredScopes: [${A.map((W)=>`'${w$(W)}'`).join(", ")}],
|
|
1241
|
+
`:"";if(!m&&!n)return"";return` byokSetup: {
|
|
1242
|
+
${m}${n} },
|
|
1243
|
+
`}function A8($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function m8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function n8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function w$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Gw($){let b=B8($.name.split(".").pop()??"KnowledgeSpace"),A=`${b}KnowledgeSpace`,m=`register${b}KnowledgeSpace`,n=W8($),W=w8($),w=j8($),j=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
996
1244
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
997
1245
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
998
1246
|
|
|
999
|
-
export const ${
|
|
1247
|
+
export const ${A}: KnowledgeSpaceSpec = {
|
|
1000
1248
|
meta: {
|
|
1001
1249
|
key: '${$.name}',
|
|
1002
1250
|
version: ${$.version},
|
|
1003
1251
|
category: '${$.category}',
|
|
1004
|
-
displayName: '${
|
|
1005
|
-
title: '${
|
|
1006
|
-
description: '${
|
|
1007
|
-
domain: '${
|
|
1008
|
-
owners: [${$.owners.map((
|
|
1009
|
-
tags: [${$.tags.map((
|
|
1010
|
-
stability: StabilityEnum.${
|
|
1011
|
-
},
|
|
1012
|
-
retention: ${
|
|
1252
|
+
displayName: '${Y$($.displayName)}',
|
|
1253
|
+
title: '${Y$($.title)}',
|
|
1254
|
+
description: '${Y$($.description)}',
|
|
1255
|
+
domain: '${Y$($.domain)}',
|
|
1256
|
+
owners: [${$.owners.map((y)=>`'${Y$(y)}'`).join(", ")}],
|
|
1257
|
+
tags: [${$.tags.map((y)=>`'${Y$(y)}'`).join(", ")}],
|
|
1258
|
+
stability: StabilityEnum.${y8($.stability)},
|
|
1259
|
+
},
|
|
1260
|
+
retention: ${n},
|
|
1013
1261
|
access: {
|
|
1014
|
-
${
|
|
1262
|
+
${W}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${j}
|
|
1015
1263
|
`:""} },
|
|
1016
|
-
${
|
|
1264
|
+
${w} description: '${Y$($.description||$.displayName)}',
|
|
1017
1265
|
};
|
|
1018
1266
|
|
|
1019
|
-
export function ${
|
|
1267
|
+
export function ${m}(
|
|
1020
1268
|
registry: KnowledgeSpaceRegistry
|
|
1021
1269
|
): KnowledgeSpaceRegistry {
|
|
1022
|
-
return registry.register(${
|
|
1270
|
+
return registry.register(${A});
|
|
1023
1271
|
}
|
|
1024
|
-
`}function
|
|
1025
|
-
`,
|
|
1026
|
-
`;return`${
|
|
1027
|
-
${
|
|
1272
|
+
`}function W8($){let b=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",A=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${b}${A} }`}function w8($){let b=` trustLevel: '${$.trustLevel}',
|
|
1273
|
+
`,A=` automationWritable: ${$.automationWritable},
|
|
1274
|
+
`;return`${b}${A}`}function j8($){let b=[];if($.embeddingModel)b.push(` embeddingModel: '${Y$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")b.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)b.push(` vectorDbIntegration: '${Y$($.vectorDbIntegration)}'`);if(b.length===0)return"";return` indexing: {
|
|
1275
|
+
${b.join(`,
|
|
1028
1276
|
`)}
|
|
1029
1277
|
},
|
|
1030
|
-
`}function
|
|
1278
|
+
`}function y8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function B8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Y$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Yw($){let A=`${S8($.name.split(".").pop()??"Migration")}Migration`,m=$.dependencies.length>0?`dependencies: [${$.dependencies.map((n)=>`'${n}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1031
1279
|
|
|
1032
|
-
export const ${
|
|
1280
|
+
export const ${A}: MigrationSpec = {
|
|
1033
1281
|
meta: {
|
|
1034
1282
|
key: '${$.name}',
|
|
1035
1283
|
version: ${$.version},
|
|
1036
|
-
title: '${
|
|
1037
|
-
description: '${
|
|
1038
|
-
domain: '${
|
|
1039
|
-
owners: [${$.owners.map((
|
|
1040
|
-
tags: [${$.tags.map((
|
|
1284
|
+
title: '${v$($.title)}',
|
|
1285
|
+
description: '${v$($.description??"")}',
|
|
1286
|
+
domain: '${v$($.domain)}',
|
|
1287
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1288
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
1041
1289
|
stability: '${$.stability}',
|
|
1042
1290
|
},
|
|
1043
1291
|
plan: {
|
|
1044
1292
|
up: [
|
|
1045
|
-
${
|
|
1293
|
+
${Xw($.up)}
|
|
1046
1294
|
],${$.down&&$.down.length?`
|
|
1047
1295
|
down: [
|
|
1048
|
-
${
|
|
1296
|
+
${Xw($.down)}
|
|
1049
1297
|
],`:""}
|
|
1050
1298
|
},
|
|
1051
|
-
${
|
|
1299
|
+
${m}
|
|
1052
1300
|
};
|
|
1053
|
-
`}function
|
|
1301
|
+
`}function Xw($){return $.map((b)=>{let A=b.description?`description: '${v$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1054
1302
|
kind: 'schema',
|
|
1055
|
-
${
|
|
1056
|
-
sql: \`${
|
|
1303
|
+
${A}
|
|
1304
|
+
sql: \`${v$(b.sql??"")}\`,
|
|
1057
1305
|
}`;case"data":return` {
|
|
1058
1306
|
kind: 'data',
|
|
1059
|
-
${
|
|
1060
|
-
script: \`${
|
|
1307
|
+
${A}
|
|
1308
|
+
script: \`${v$(b.script??"")}\`,
|
|
1061
1309
|
}`;case"validation":default:return` {
|
|
1062
1310
|
kind: 'validation',
|
|
1063
|
-
${
|
|
1064
|
-
assertion: \`${
|
|
1311
|
+
${A}
|
|
1312
|
+
assertion: \`${v$(b.assertion??"")}\`,
|
|
1065
1313
|
}`}}).join(`,
|
|
1066
|
-
`)}function
|
|
1314
|
+
`)}function S8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function v$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Hw($){let{name:b,version:A,kind:m,description:n,goal:W,context:w,stability:j,owners:y,tags:B,auth:S,flags:Q}=$,Z=Q8(b.split(".").pop()||"Unknown")+"Spec",G=Z.replace("Spec","Input"),X=Z.replace("Spec","Output");return`import { define${mm(m)} } from '@contractspec/lib.contracts-spec';
|
|
1067
1315
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1068
1316
|
|
|
1069
1317
|
// TODO: Define input schema
|
|
1070
|
-
export const ${
|
|
1071
|
-
name: '${
|
|
1072
|
-
description: 'Input for ${
|
|
1318
|
+
export const ${G} = new SchemaModel({
|
|
1319
|
+
name: '${G}',
|
|
1320
|
+
description: 'Input for ${b}',
|
|
1073
1321
|
fields: {
|
|
1074
1322
|
// Add your fields here
|
|
1075
1323
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
@@ -1077,32 +1325,32 @@ export const ${J} = new SchemaModel({
|
|
|
1077
1325
|
});
|
|
1078
1326
|
|
|
1079
1327
|
// TODO: Define output schema
|
|
1080
|
-
export const ${
|
|
1081
|
-
name: '${
|
|
1082
|
-
description: 'Output for ${
|
|
1328
|
+
export const ${X} = new SchemaModel({
|
|
1329
|
+
name: '${X}',
|
|
1330
|
+
description: 'Output for ${b}',
|
|
1083
1331
|
fields: {
|
|
1084
1332
|
// Add your fields here
|
|
1085
1333
|
ok: { type: ScalarTypeEnum.Boolean(), isOptional: false },
|
|
1086
1334
|
},
|
|
1087
1335
|
});
|
|
1088
1336
|
|
|
1089
|
-
export const ${
|
|
1337
|
+
export const ${Z} = define${mm(m)}({
|
|
1090
1338
|
meta: {
|
|
1091
|
-
key: '${
|
|
1092
|
-
key: '${
|
|
1093
|
-
version: '${
|
|
1094
|
-
stability: '${
|
|
1095
|
-
stability: '${
|
|
1096
|
-
owners: [${
|
|
1097
|
-
tags: [${
|
|
1098
|
-
description: '${
|
|
1099
|
-
goal: '${
|
|
1100
|
-
context: '${
|
|
1339
|
+
key: '${b}',
|
|
1340
|
+
key: '${b}',
|
|
1341
|
+
version: '${A}',
|
|
1342
|
+
stability: '${j}',
|
|
1343
|
+
stability: '${j}',
|
|
1344
|
+
owners: [${y.map((Y)=>`'${Y}'`).join(", ")}],
|
|
1345
|
+
tags: [${B.map((Y)=>`'${Y}'`).join(", ")}],
|
|
1346
|
+
description: '${n}',
|
|
1347
|
+
goal: '${W}',
|
|
1348
|
+
context: '${w}',
|
|
1101
1349
|
},
|
|
1102
1350
|
|
|
1103
1351
|
io: {
|
|
1104
|
-
input: ${
|
|
1105
|
-
output: ${
|
|
1352
|
+
input: ${G},
|
|
1353
|
+
output: ${X},
|
|
1106
1354
|
errors: {
|
|
1107
1355
|
// Define possible errors
|
|
1108
1356
|
// EXAMPLE_ERROR: {
|
|
@@ -1114,8 +1362,8 @@ export const ${G} = define${_1(A)}({
|
|
|
1114
1362
|
},
|
|
1115
1363
|
|
|
1116
1364
|
policy: {
|
|
1117
|
-
auth: '${
|
|
1118
|
-
${
|
|
1365
|
+
auth: '${S}',
|
|
1366
|
+
${Q.length>0?`flags: [${Q.map((Y)=>`'${Y}'`).join(", ")}],`:"// flags: [],"}
|
|
1119
1367
|
},
|
|
1120
1368
|
|
|
1121
1369
|
sideEffects: {
|
|
@@ -1129,9 +1377,9 @@ export const ${G} = define${_1(A)}({
|
|
|
1129
1377
|
},
|
|
1130
1378
|
|
|
1131
1379
|
transport: {
|
|
1132
|
-
rest: { method: '${
|
|
1133
|
-
gql: { field: '${
|
|
1134
|
-
mcp: { toolName: '${
|
|
1380
|
+
rest: { method: '${m==="command"?"POST":"GET"}' },
|
|
1381
|
+
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1382
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(A).replace(/\./g,"_")}' },
|
|
1135
1383
|
},
|
|
1136
1384
|
|
|
1137
1385
|
acceptance: {
|
|
@@ -1152,13 +1400,13 @@ export const ${G} = define${_1(A)}({
|
|
|
1152
1400
|
],
|
|
1153
1401
|
},
|
|
1154
1402
|
});
|
|
1155
|
-
`}function
|
|
1403
|
+
`}function mm($){return $.charAt(0).toUpperCase()+$.slice(1)}function Q8($){return $.split(/[-_.]/).map(mm).join("")}function qw($){let{name:b,version:A,description:m,stability:n,owners:W,tags:w,presentationKind:j}=$,y=Z8(b.replace(/\./g,"_"))+"Presentation",B="";switch(j){case"web_component":B=` content: {
|
|
1156
1404
|
kind: 'web_component',
|
|
1157
1405
|
framework: 'react',
|
|
1158
|
-
componentKey: '${
|
|
1406
|
+
componentKey: '${b.replace(/\./g,"_")}',
|
|
1159
1407
|
props: new SchemaModel({
|
|
1160
|
-
name: '${
|
|
1161
|
-
description: 'Props for ${
|
|
1408
|
+
name: '${y}Props',
|
|
1409
|
+
description: 'Props for ${b}',
|
|
1162
1410
|
fields: {
|
|
1163
1411
|
// TODO: Define component props
|
|
1164
1412
|
},
|
|
@@ -1166,20 +1414,20 @@ export const ${G} = define${_1(A)}({
|
|
|
1166
1414
|
analytics: [
|
|
1167
1415
|
// TODO: Define analytics events
|
|
1168
1416
|
],
|
|
1169
|
-
},`;break;case"markdown":
|
|
1417
|
+
},`;break;case"markdown":B=` content: {
|
|
1170
1418
|
kind: 'markdown',
|
|
1171
1419
|
content: \`
|
|
1172
|
-
# ${
|
|
1420
|
+
# ${m}
|
|
1173
1421
|
|
|
1174
1422
|
TODO: Add markdown content here
|
|
1175
1423
|
\`,
|
|
1176
|
-
// Or use resourceUri: 'feature://${
|
|
1177
|
-
},`;break;case"data":
|
|
1424
|
+
// Or use resourceUri: 'feature://${b}/guide.md'
|
|
1425
|
+
},`;break;case"data":B=` content: {
|
|
1178
1426
|
kind: 'data',
|
|
1179
1427
|
mimeType: 'application/json',
|
|
1180
1428
|
model: new SchemaModel({
|
|
1181
|
-
name: '${
|
|
1182
|
-
description: 'Data structure for ${
|
|
1429
|
+
name: '${y}Data',
|
|
1430
|
+
description: 'Data structure for ${b}',
|
|
1183
1431
|
fields: {
|
|
1184
1432
|
// TODO: Define data structure
|
|
1185
1433
|
},
|
|
@@ -1187,14 +1435,14 @@ TODO: Add markdown content here
|
|
|
1187
1435
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1188
1436
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1189
1437
|
|
|
1190
|
-
export const ${
|
|
1438
|
+
export const ${y}: PresentationSpec = {
|
|
1191
1439
|
meta: {
|
|
1192
|
-
key: '${
|
|
1193
|
-
version: ${
|
|
1194
|
-
stability: '${
|
|
1195
|
-
owners: [${
|
|
1196
|
-
tags: [${
|
|
1197
|
-
description: '${
|
|
1440
|
+
key: '${b}',
|
|
1441
|
+
version: ${A},
|
|
1442
|
+
stability: '${n}',
|
|
1443
|
+
owners: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1444
|
+
tags: [${w.map((S)=>`'${S}'`).join(", ")}],
|
|
1445
|
+
description: '${m}',
|
|
1198
1446
|
},
|
|
1199
1447
|
|
|
1200
1448
|
policy: {
|
|
@@ -1202,81 +1450,109 @@ export const ${B}: PresentationSpec = {
|
|
|
1202
1450
|
// pii: [],
|
|
1203
1451
|
},
|
|
1204
1452
|
|
|
1205
|
-
${
|
|
1453
|
+
${B}
|
|
1206
1454
|
};
|
|
1207
|
-
`}function
|
|
1208
|
-
${$.providers.map((
|
|
1209
|
-
type: '${
|
|
1210
|
-
config: ${
|
|
1455
|
+
`}function Z8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ow($){let b=G8($.name.split(".").pop()??"Telemetry")+"Telemetry",A=$.providers?.length?`providers: [
|
|
1456
|
+
${$.providers.map((n)=>` {
|
|
1457
|
+
type: '${n.type}',
|
|
1458
|
+
config: ${X8(n.config)},
|
|
1211
1459
|
}`).join(`,
|
|
1212
1460
|
`)}
|
|
1213
|
-
],`:"",
|
|
1214
|
-
type: '${
|
|
1215
|
-
${
|
|
1216
|
-
${
|
|
1217
|
-
${
|
|
1218
|
-
${
|
|
1461
|
+
],`:"",m=$.events.map((n)=>{let W=n.properties.map((j)=>` '${j.name}': {
|
|
1462
|
+
type: '${j.type}',
|
|
1463
|
+
${j.required?"required: true,":""}
|
|
1464
|
+
${j.pii?"pii: true,":""}
|
|
1465
|
+
${j.redact?"redact: true,":""}
|
|
1466
|
+
${j.description?`description: '${l(j.description)}',`:""}
|
|
1219
1467
|
}`).join(`,
|
|
1220
|
-
`),
|
|
1468
|
+
`),w=n.anomalyRules?.length?` anomalyDetection: {
|
|
1221
1469
|
enabled: true,
|
|
1222
|
-
${typeof
|
|
1470
|
+
${typeof n.anomalyMinimumSample==="number"?`minimumSample: ${n.anomalyMinimumSample},`:""}
|
|
1223
1471
|
thresholds: [
|
|
1224
|
-
${
|
|
1225
|
-
metric: '${
|
|
1226
|
-
${typeof
|
|
1227
|
-
${typeof
|
|
1472
|
+
${n.anomalyRules.map((j)=>` {
|
|
1473
|
+
metric: '${l(j.metric)}',
|
|
1474
|
+
${typeof j.min==="number"?`min: ${j.min},`:""}
|
|
1475
|
+
${typeof j.max==="number"?`max: ${j.max},`:""}
|
|
1228
1476
|
}`).join(`,
|
|
1229
1477
|
`)}
|
|
1230
1478
|
],
|
|
1231
|
-
actions: [${(
|
|
1232
|
-
},`:
|
|
1479
|
+
actions: [${(n.anomalyActions??[]).map((j)=>`'${j}'`).join(", ")}],
|
|
1480
|
+
},`:n.anomalyEnabled?` anomalyDetection: {
|
|
1233
1481
|
enabled: true,
|
|
1234
|
-
${typeof
|
|
1482
|
+
${typeof n.anomalyMinimumSample==="number"?`minimumSample: ${n.anomalyMinimumSample},`:""}
|
|
1235
1483
|
},`:"";return` {
|
|
1236
|
-
name: '${n
|
|
1237
|
-
version: ${
|
|
1484
|
+
name: '${l(n.name)}',
|
|
1485
|
+
version: ${n.version},
|
|
1238
1486
|
semantics: {
|
|
1239
|
-
what: '${n
|
|
1240
|
-
${
|
|
1241
|
-
${
|
|
1487
|
+
what: '${l(n.what)}',
|
|
1488
|
+
${n.who?`who: '${l(n.who)}',`:""}
|
|
1489
|
+
${n.why?`why: '${l(n.why)}',`:""}
|
|
1242
1490
|
},
|
|
1243
|
-
privacy: '${
|
|
1491
|
+
privacy: '${n.privacy}',
|
|
1244
1492
|
properties: {
|
|
1245
|
-
${
|
|
1493
|
+
${W}
|
|
1246
1494
|
},
|
|
1247
|
-
${typeof
|
|
1248
|
-
${typeof
|
|
1249
|
-
${
|
|
1250
|
-
${
|
|
1495
|
+
${typeof n.retentionDays==="number"?`retention: { days: ${n.retentionDays}, ${n.retentionPolicy?`policy: '${n.retentionPolicy}'`:""} },`:""}
|
|
1496
|
+
${typeof n.samplingRate==="number"?`sampling: { rate: ${n.samplingRate}${n.samplingConditions?`, conditions: ['${l(n.samplingConditions)}']`:""} },`:""}
|
|
1497
|
+
${w}
|
|
1498
|
+
${n.tags?.length?`tags: [${n.tags.map((j)=>`'${l(j)}'`).join(", ")}],`:""}
|
|
1251
1499
|
}`}).join(`,
|
|
1252
1500
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1253
1501
|
|
|
1254
|
-
export const ${
|
|
1502
|
+
export const ${b}: TelemetrySpec = {
|
|
1255
1503
|
meta: {
|
|
1256
|
-
key: '${
|
|
1504
|
+
key: '${l($.name)}',
|
|
1257
1505
|
version: ${$.version},
|
|
1258
|
-
title: '${
|
|
1259
|
-
description: '${
|
|
1260
|
-
domain: '${
|
|
1261
|
-
owners: [${$.owners.map((
|
|
1262
|
-
tags: [${$.tags.map((
|
|
1506
|
+
title: '${l($.name)} telemetry',
|
|
1507
|
+
description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1508
|
+
domain: '${l($.domain)}',
|
|
1509
|
+
owners: [${$.owners.map((n)=>`'${l(n)}'`).join(", ")}],
|
|
1510
|
+
tags: [${$.tags.map((n)=>`'${l(n)}'`).join(", ")}],
|
|
1263
1511
|
stability: '${$.stability}',
|
|
1264
1512
|
},
|
|
1265
1513
|
config: {
|
|
1266
1514
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1267
1515
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1268
1516
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1269
|
-
${
|
|
1517
|
+
${A}
|
|
1270
1518
|
},
|
|
1271
1519
|
events: [
|
|
1272
|
-
${
|
|
1520
|
+
${m}
|
|
1273
1521
|
],
|
|
1274
1522
|
};
|
|
1275
|
-
`}function
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1523
|
+
`}function G8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function X8($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function Y8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Vw($){return`/**
|
|
1524
|
+
* ${$.title} Theme
|
|
1525
|
+
*
|
|
1526
|
+
* Auto-generated theme spec.
|
|
1527
|
+
*/
|
|
1528
|
+
|
|
1529
|
+
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1530
|
+
|
|
1531
|
+
export const ${Y8($.key)}Theme = defineTheme({
|
|
1532
|
+
meta: {
|
|
1533
|
+
key: '${$.key}',
|
|
1534
|
+
version: '${$.version}',
|
|
1535
|
+
title: '${$.title}',
|
|
1536
|
+
description: '${$.description}',
|
|
1537
|
+
domain: '${$.domain}',
|
|
1538
|
+
owners: [${$.owners.map((b)=>`'${b}'`).join(", ")}],
|
|
1539
|
+
tags: [${$.tags.map((b)=>`'${b}'`).join(", ")}],
|
|
1540
|
+
stability: '${$.stability}',
|
|
1541
|
+
scopes: [${$.scopes.map((b)=>`'${b}'`).join(", ")}],
|
|
1542
|
+
},
|
|
1543
|
+
tokens: {
|
|
1544
|
+
colors: {
|
|
1545
|
+
primary: { value: '#2563eb' },
|
|
1546
|
+
background: { value: '#ffffff' },
|
|
1547
|
+
foreground: { value: '#111827' },
|
|
1548
|
+
},
|
|
1549
|
+
},
|
|
1550
|
+
});
|
|
1551
|
+
`}function Jw($){let b=q8($.name.split(".").pop()??"Workflow")+"Workflow",A=$.steps.map((n)=>H8(n)).join(`,
|
|
1552
|
+
`),m=$.transitions.map((n)=>` {
|
|
1553
|
+
from: '${n.from}',
|
|
1554
|
+
to: '${n.to}',
|
|
1555
|
+
${n.condition?` condition: '${e$(n.condition)}',`:""}
|
|
1280
1556
|
}`).join(`,
|
|
1281
1557
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1282
1558
|
|
|
@@ -1288,36 +1564,36 @@ ${Q.condition?` condition: '${h$(Q.condition)}',`:""}
|
|
|
1288
1564
|
* - Provide form renderers for human steps.
|
|
1289
1565
|
* - Add guards/conditions as needed.
|
|
1290
1566
|
*/
|
|
1291
|
-
export const ${
|
|
1567
|
+
export const ${b}: WorkflowSpec = {
|
|
1292
1568
|
meta: {
|
|
1293
1569
|
key: '${$.name}',
|
|
1294
1570
|
version: ${$.version},
|
|
1295
|
-
title: '${
|
|
1296
|
-
description: '${
|
|
1297
|
-
domain: '${
|
|
1571
|
+
title: '${e$($.title)}',
|
|
1572
|
+
description: '${e$($.description)}',
|
|
1573
|
+
domain: '${e$($.domain)}',
|
|
1298
1574
|
stability: '${$.stability}',
|
|
1299
|
-
owners: [${$.owners.map((
|
|
1300
|
-
tags: [${$.tags.map((
|
|
1575
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1576
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
1301
1577
|
},
|
|
1302
1578
|
definition: {
|
|
1303
1579
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1304
1580
|
`:""} steps: [
|
|
1305
|
-
${
|
|
1581
|
+
${A}
|
|
1306
1582
|
],
|
|
1307
1583
|
transitions: [
|
|
1308
|
-
${
|
|
1584
|
+
${m}
|
|
1309
1585
|
],
|
|
1310
1586
|
},
|
|
1311
1587
|
${$.policyFlags.length>0?`policy: {
|
|
1312
|
-
flags: [${$.policyFlags.map((
|
|
1588
|
+
flags: [${$.policyFlags.map((n)=>`'${n}'`).join(", ")}],
|
|
1313
1589
|
},`:"// policy: { flags: [] },"}
|
|
1314
1590
|
};
|
|
1315
|
-
`}function
|
|
1316
|
-
`)}function
|
|
1591
|
+
`}function H8($){let b=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${e$($.label)}',`];if($.description)b.push(` description: '${e$($.description)}',`);let A=[];if($.operation)A.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)A.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(A.length)b.push(` action: { ${A.join(", ")} },`);return b.push(" }"),b.join(`
|
|
1592
|
+
`)}function q8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function e$($){return $.replace(/'/g,"\\'")}function zA({exportName:$,specImportPath:b,workflowFunctionName:A}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1317
1593
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1318
|
-
import { ${$} } from '${
|
|
1594
|
+
import { ${$} } from '${b}';
|
|
1319
1595
|
|
|
1320
|
-
export async function ${
|
|
1596
|
+
export async function ${A}(input = {}, bridge = {}) {
|
|
1321
1597
|
"use workflow";
|
|
1322
1598
|
|
|
1323
1599
|
// Keep the workflow function deterministic.
|
|
@@ -1334,29 +1610,29 @@ export async function ${j}(input = {}, bridge = {}) {
|
|
|
1334
1610
|
},
|
|
1335
1611
|
});
|
|
1336
1612
|
}
|
|
1337
|
-
`}function
|
|
1338
|
-
import { ${
|
|
1613
|
+
`}function LA($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1614
|
+
import { ${b} } from '${$}';
|
|
1339
1615
|
|
|
1340
1616
|
export const POST = createWorkflowDevkitStartRoute({
|
|
1341
|
-
workflow: ${
|
|
1617
|
+
workflow: ${b},
|
|
1342
1618
|
async buildArgs(body) {
|
|
1343
1619
|
return [body];
|
|
1344
1620
|
},
|
|
1345
1621
|
});
|
|
1346
|
-
`}function
|
|
1622
|
+
`}function RA(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1347
1623
|
|
|
1348
1624
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1349
1625
|
resolveToken({ runId }) {
|
|
1350
1626
|
return \`workflow-session:\${runId}\`;
|
|
1351
1627
|
},
|
|
1352
1628
|
});
|
|
1353
|
-
`}function
|
|
1629
|
+
`}function CA(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1354
1630
|
|
|
1355
1631
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1356
|
-
`}function
|
|
1632
|
+
`}function IA($,b){return`import { ${b} } from '${$}';
|
|
1357
1633
|
|
|
1358
1634
|
export const workflowDevkitBootstrap = {
|
|
1359
|
-
workflow: ${
|
|
1635
|
+
workflow: ${b},
|
|
1360
1636
|
createBridge() {
|
|
1361
1637
|
return {
|
|
1362
1638
|
executeAutomationStep: async () => {
|
|
@@ -1365,13 +1641,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1365
1641
|
};
|
|
1366
1642
|
},
|
|
1367
1643
|
};
|
|
1368
|
-
`}function
|
|
1644
|
+
`}function EA({exportName:$,specImportPath:b,runnerName:A,workflowName:m}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1369
1645
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1370
1646
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1371
|
-
import { ${$} } from '${
|
|
1647
|
+
import { ${$} } from '${b}';
|
|
1372
1648
|
|
|
1373
1649
|
/**
|
|
1374
|
-
* Runner wiring for ${
|
|
1650
|
+
* Runner wiring for ${m}.
|
|
1375
1651
|
*
|
|
1376
1652
|
* TODO:
|
|
1377
1653
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1383,7 +1659,7 @@ registry.register(${$});
|
|
|
1383
1659
|
|
|
1384
1660
|
const stateStore = new InMemoryStateStore();
|
|
1385
1661
|
|
|
1386
|
-
export const ${
|
|
1662
|
+
export const ${A} = new WorkflowRunner({
|
|
1387
1663
|
registry,
|
|
1388
1664
|
stateStore,
|
|
1389
1665
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1405,12 +1681,12 @@ export const ${j} = new WorkflowRunner({
|
|
|
1405
1681
|
// console.log(event, payload);
|
|
1406
1682
|
},
|
|
1407
1683
|
});
|
|
1408
|
-
`}import{getAuthoringTargetDefinition as
|
|
1409
|
-
`],[
|
|
1684
|
+
`}import{getAuthoringTargetDefinition as O8}from"@contractspec/module.workspace";var _w={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function Uw($,b){let A=V8($,b.specPath),m=J8($,b.target,A),n=$.join(A,"package.json"),W=$.join(A,"README.md"),w=$.join(A,"src"),j=$.join(w,"index.ts"),y=nm($.relative(w,b.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(w);let B=[[n,JSON.stringify({name:m,version:"0.1.0",description:_w[b.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1685
|
+
`],[W,`# ${m}
|
|
1410
1686
|
|
|
1411
|
-
${
|
|
1412
|
-
`],[
|
|
1413
|
-
`],[
|
|
1687
|
+
${_w[b.target]}.
|
|
1688
|
+
`],[j,`export * from "./${y.startsWith(".")?y:`./${y}`}";
|
|
1689
|
+
`],[b.specPath,b.specCode]],S={packageRoot:A,files:B.map(([Q])=>Q),created:[],skipped:[]};for(let[Q,Z]of B){if(await $.exists(Q)&&!b.overwrite){S.skipped.push(Q);continue}await $.writeFile(Q,Z),S.created.push(Q)}return S}function zw($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1414
1690
|
|
|
1415
1691
|
export const ${$.exportName} = defineModuleBundle({
|
|
1416
1692
|
meta: {
|
|
@@ -1471,22 +1747,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1471
1747
|
supportedArtifactTypes: ["patch"],
|
|
1472
1748
|
knownConstraints: [],
|
|
1473
1749
|
};
|
|
1474
|
-
`}}function
|
|
1750
|
+
`}}function V8($,b){let A=nm(b),m="/src/",n=A.lastIndexOf("/src/");if(n===-1)return $.dirname(b);return A.slice(0,n)}function J8($,b,A){let m=O8(b),n=nm($.basename(A));return`${m.defaultPackagePrefix??(b==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${n}`}function nm($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function $b($,b,A,m={}){let{fs:n,logger:W,workspace:w}=b,j=w?.scanSpecSource??C8,y=w?.inferSpecTypeFromFilePath??R8,B=w?.generateHandlerTemplate??U8,S=w?.generateComponentTemplate??_8,Q=w?.generateTestTemplate??z8,{targets:Z=void 0,outputDir:G=A.outputDir,overwrite:X=!1,dryRun:Y=!1,includeTests:V=!1,runtimeGeneration:O}=m,K=await n.readFile($),J=j(K,$),_=K8(K,$),H=_==="unknown"?y($):_,q=Z??wm(H,{includeTests:V});W.info(`Building from spec: ${$}`,{targetId:H});let U=[],z={};for(let L of q)try{let I=await I8(L,$,K,J,H,{fs:n,logger:W},G,X,Y,O,z,{genHandler:B,genComponent:S,genTest:Q});if(U.push(I),I.success&&I.generatedCode)z[L]=I.generatedCode}catch(I){U.push({target:L,outputPath:"",success:!1,error:I instanceof Error?I.message:String(I),skipped:!1})}return{specPath:$,specInfo:J,targetId:H,results:U}}async function I8($,b,A,m,n,W,w,j,y,B,S,Q){let{fs:Z,logger:G}=W,{genHandler:X,genComponent:Y,genTest:V}=Q,O,K,J=[];switch($){case"handler":{if(n!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${n})`};let q=m.kind==="command"||m.kind==="query"?m.kind:"command",U=X(e(A,m,b),q);K=s$(b,w,"handlers",e(A,m,b),".handler.ts",W.fs),O=await B?.generateArtifact?.({kind:"handler",specCode:A,outputPath:K,fallbackCode:U})??U;break}case"component":{if(n!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${n})`};let q=Y(e(A,m,b),m.description??"");K=s$(b,w,"components",e(A,m,b),".tsx",W.fs),O=await B?.generateArtifact?.({kind:"component",specCode:A,outputPath:K,fallbackCode:q})??q;break}case"test":{let q=n==="operation"?"handler":"component",U=n==="operation"?S.handler??"":n==="presentation"?S.component??"":n==="form"?S.form??"":"",z=V(e(A,m,b),q);K=s$(b,w,"__tests__",e(A,m,b),".test.ts",W.fs),O=await B?.generateTest?.({kind:q,specCode:A,outputPath:K,existingCode:U,fallbackCode:z})??z;break}case"form":{if(n!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${n})`};let q=`import * as React from "react";
|
|
1475
1751
|
|
|
1476
|
-
export interface ${
|
|
1752
|
+
export interface ${H$(e(A,m,b))}Props {
|
|
1477
1753
|
className?: string;
|
|
1478
1754
|
}
|
|
1479
1755
|
|
|
1480
|
-
export function ${
|
|
1756
|
+
export function ${H$(e(A,m,b))}Form({
|
|
1481
1757
|
className,
|
|
1482
|
-
}: ${
|
|
1483
|
-
return <form className={className}>TODO: implement ${
|
|
1758
|
+
}: ${H$(e(A,m,b))}Props) {
|
|
1759
|
+
return <form className={className}>TODO: implement ${e(A,m,b)}</form>;
|
|
1484
1760
|
}
|
|
1485
|
-
`;
|
|
1761
|
+
`;K=s$(b,w,"forms",e(A,m,b),".form.tsx",W.fs),O=await B?.generateArtifact?.({kind:"form",specCode:A,outputPath:K,fallbackCode:q})??q;break}case"workflow-runner":{if(n!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${n})`};let q=e(A,m,b),U=T8(A)??`${H$(q)}Workflow`,z=`${H$(q)}Runner`,L=jm(q);if(K=s$(b,w,"workflows",q,".runner.ts",W.fs),O=EA({exportName:U,specImportPath:Wm(W.fs,K,b),runnerName:z,workflowName:q}),F8(A)){let I=`${H$(q)}WorkflowDevkit`,C=qb(W.fs,K,`${L}.workflow-devkit.ts`),F=qb(W.fs,K,`${L}.workflow-devkit.start.route.ts`),x=qb(W.fs,K,`${L}.workflow-devkit.follow-up.route.ts`),h=qb(W.fs,K,`${L}.workflow-devkit.stream.route.ts`),nA=qb(W.fs,K,`${L}.workflow-devkit.generic.ts`);J=[{path:C,code:zA({exportName:U,specImportPath:Wm(W.fs,C,b),workflowFunctionName:I})},{path:F,code:LA(Lw(W.fs,F,C),I)},{path:x,code:RA()},{path:h,code:CA()},{path:nA,code:IA(Lw(W.fs,nA,C),I)}]}break}case"data-view-renderer":{if(n!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${n})`};let q=e(A,m,b),U=D8(A)??`${H$(q)}DataView`,z=`${H$(q)}Renderer`;K=s$(b,w,"data-views",q,".renderer.tsx",W.fs),O=_A({exportName:U,specImportPath:Wm(W.fs,K,b),rendererName:z,viewKind:N8(A)??"table"});break}case"package-scaffold":{if(n!=="module-bundle"&&n!=="builder-spec"&&n!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${n})`};if(y){let z=M8(b);return G.info(`[dry-run] Would scaffold package: ${z}`),{target:$,outputPath:z,success:!0}}let q=A.trim().length>0?A:zw({target:n,key:m.key??W.fs.basename(b),title:m.key??W.fs.basename(b),description:m.description??L8(n).title,exportName:H$(m.key??W.fs.basename(b))});return K=(await Uw(W.fs,{target:n,specPath:b,specCode:q,overwrite:j})).packageRoot,G.info(`Generated package scaffold: ${K}`),{target:$,outputPath:K,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let _=[{path:K,code:O},...J],H=j?void 0:await E8(_,Z);if(H)return{target:$,outputPath:H,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(y){for(let q of _)G.info(`[dry-run] Would write: ${q.path}`);return{target:$,outputPath:K,success:!0,generatedCode:_[0]?.code}}for(let q of _)await Z.mkdir(Z.dirname(q.path)),await Z.writeFile(q.path,v8(q.code)),G.info(`Generated: ${q.path}`);return{target:$,outputPath:K,success:!0}}function wm($,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 s$($,b,A,m,n,W){let w=jm(m.split(".").pop()??"unknown"),j;if(b.startsWith("."))j=W.resolve(W.dirname($),"..",b,A);else j=W.resolve(b,A);return W.join(j,`${w}${n}`)}async function E8($,b){for(let A of $)if(await b.exists(A.path))return A.path;return}function jm($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function H$($){return jm($).split("-").filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function ym($){return $.replace(/\.[^.]+$/,"")}function M8($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Wm($,b,A){let m=ym($.relative($.dirname(b),A));return m.startsWith(".")?m:`./${m}`}function Lw($,b,A){let m=ym($.relative($.dirname(b),A));return m.startsWith(".")?m:`./${m}`}function qb($,b,A){return $.join($.dirname(b),A)}function e($,b,A){return x8($,"name")??b.key??ym(g8(A))}function x8($,b){let A=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(A)?.[1]??null}function T8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function D8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function N8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function F8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function v8($){return $.endsWith(`
|
|
1486
1762
|
`)?$:`${$}
|
|
1487
|
-
`}function nZ($){return $.replaceAll("\\","/").split("/").pop()??$}i();import{scanAllSpecsFromSource as pZ,scanSpecSource as tZ}from"@contractspec/module.workspace";import aZ from"micromatch";var K8={};h(K8,{validators:()=>iZ,urlSchema:()=>oZ,isValidVersion:()=>rZ,isValidIdentifier:()=>b8,isValidDotName:()=>w8,isTestFile:()=>j0,isLibraryDefinitionFile:()=>A0,emailSchema:()=>lZ});import I1 from"micromatch";function j0($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return I1.isMatch($,j)}function A0($){let W=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(I1.isMatch($,W))return!1;let j=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return I1.isMatch($,j)}import*as H$ from"zod";function b8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function w8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function rZ($){return Number.isInteger($)&&$>0}var lZ=H$.string().email(),oZ=H$.string().url(),iZ={specName:H$.string().refine(w8,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:H$.number().int().positive(),identifier:H$.string().refine(b8,{message:"Must be a valid TypeScript identifier"}),owner:H$.string().startsWith("@"),tag:H$.string().min(1)};function Q0($){return($??"").split("|").map((W)=>W.trim().replace(/^\.?\//,"")).filter(Boolean)}function sZ($){let W=$?.packages&&$.packages.length>0?$.packages:["**"],j=[...Q0($?.conventions.models),...Q0($?.conventions.operations),...Q0($?.conventions.events),...Q0($?.conventions.presentations),...Q0($?.conventions.forms)];return[...new Set(W.flatMap((A)=>{let Q=A==="**"?"":`${A}/`,Z=Y$.map((Y)=>`${Q}${Y}`),X=j.map((Y)=>`${Q}${Y}/**/*.ts`);return[...Z,...X]}))]}function eZ($,W,j){if($.specType==="unknown")return!1;if(W.type&&!j.includes($.specType))return!1;return!0}function $6($,W){let j=$.filePath.localeCompare(W.filePath);if(j!==0)return j;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(W.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(W.discoveryId??W.key??"")}async function N$($,W={}){if(W.paths&&W.paths.length>0)return[...new Set(W.paths)].sort((j,A)=>j.localeCompare(A));if(W.pattern)return $.glob({cwd:W.cwd,pattern:W.pattern});return $.glob({cwd:W.cwd,patterns:sZ(W.config)})}async function QW($,W={}){let j=await N$($.fs,W),A=W.type?Array.isArray(W.type)?W.type:[W.type]:[],Q=[];for(let Z of j){if(W.config?.excludePackages&&aZ.isMatch(Z,W.config.excludePackages,{contains:!0}))continue;if(Z.includes("node_modules")||Z.includes("/dist/")||j0(Z,W.config)||A0(Z))continue;try{let X=await $.fs.readFile(Z),Y=pZ(X,Z),B=Y.length>0?Y:[tZ(X,Z)];for(let q of B)if(eZ(q,W,A))Q.push(q)}catch{}}return Q.sort($6)}function J$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function ZW($){let W=JSON.parse($),j=new Map,A=0,Q=0,Z=0,X=0,Y=0,B=0,q=0,H=0;for(let[G,J]of Object.entries(W)){let b=W6(G,J);j.set(G,b),A+=b.statements.total,Q+=b.statements.covered,Z+=b.branches.total,X+=b.branches.covered,Y+=b.functions.total,B+=b.functions.covered,q+=b.lines.total,H+=b.lines.covered}let V={statements:{covered:Q,total:A,pct:J$(Q,A)},branches:{covered:X,total:Z,pct:J$(X,Z)},functions:{covered:B,total:Y,pct:J$(B,Y)},lines:{covered:H,total:q,pct:J$(H,q)}};return{files:j,total:V}}function W6($,W){let j=Object.keys(W.statementMap).length,A=Object.values(W.s).filter((H)=>H>0).length,Q=Object.keys(W.fnMap).length,Z=Object.values(W.f).filter((H)=>H>0).length,X=0,Y=0;for(let H of Object.values(W.b))X+=H.length,Y+=H.filter((V)=>V>0).length;let B=new Set,q=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(B.add(G),(W.s[H]??0)>0)q.add(G);return{path:$,statements:{covered:A,total:j,pct:J$(A,j)},branches:{covered:Y,total:X,pct:J$(Y,X)},functions:{covered:Z,total:Q,pct:J$(Z,Q)},lines:{covered:q.size,total:B.size,pct:J$(q.size,B.size)}}}function M1($){switch($){case"istanbul":return{parse:ZW};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function E1($,W){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&W?.includes("cobertura"))return"cobertura";return"istanbul"}function N1($,W,j,A){let Q=[];if(j.statements!==void 0&&A.statements.pct<j.statements)Q.push({metric:"statements",required:j.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&A.branches.pct<j.branches)Q.push({metric:"branches",required:j.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&A.functions.pct<j.functions)Q.push({metric:"functions",required:j.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&A.lines.pct<j.lines)Q.push({metric:"lines",required:j.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Q.push({metric:"mutations",required:j.mutations,actual:0,message:`Mutation coverage required (${j.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:W,requirement:j,actual:A,passed:Q.length===0,failures:Q}}async function R1($,W,j){let{fs:A,logger:Q}=$,Z=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],B,q;for(let J of Y)if(await A.exists(J)){B=await A.readFile(J),q=J;break}if(!B)return Q.info("No coverage report found, skipping coverage checks"),Z;let H=E1(q??"coverage.json"),G=M1(H).parse(B);for(let J of W){if(J.specType!=="test-spec"||!J.key||!J.version||!J.sourceBlock)continue;let b=J.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!b||!b[1])continue;let w=b[1],L={},z=w.match(/statements\s*:\s*(\d+)/);if(z&&z[1])L.statements=parseInt(z[1],10);let S=w.match(/branches\s*:\s*(\d+)/);if(S&&S[1])L.branches=parseInt(S[1],10);let U=w.match(/functions\s*:\s*(\d+)/);if(U&&U[1])L.functions=parseInt(U[1],10);let O=w.match(/lines\s*:\s*(\d+)/);if(O&&O[1])L.lines=parseInt(O[1],10);if(Object.keys(L).length===0)continue;let K=N1(J.key,J.version,L,G.total);for(let _ of K.failures)Z.push({ruleId:"coverage-below-threshold",severity:"error",message:_.message,category:"coverage",file:J.filePath,context:{specKey:J.key,specVersion:J.version,metric:_.metric,required:_.required,actual:_.actual}})}return Z}import{addContractNode as j6,buildReverseEdges as A6,createContractGraph as Q6,detectCycles as Z6,findMissingDependencies as X6,parseImportedSpecNames as Y6,toDot as B6}from"@contractspec/module.workspace";async function _8($,W={}){let{fs:j}=$,A=await N$(j,{config:W.config,pattern:W.pattern}),Q=Q6();for(let Y of A){let B=await j.readFile(Y),q=j.relative(".",Y),H=j.basename(Y).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",V=Y6(B,Y);j6(Q,H,q,V)}A6(Q);let Z=Z6(Q),X=X6(Q);return{graph:Q,total:Q.size,cycles:Z,missing:X}}function aJ($,W){return $.get(W)}function sJ($){return B6($)}function eJ($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),A=W.filter((X)=>X.dependencies.length===0),Q=W.filter((X)=>X.dependents.length>0),Z=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:A.length,used:Q.length,unused:Z.length}}i();async function C1($,W){let j=[],A=await m($.fs),Q=await _8($,{config:A,pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" → ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let X of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${X}`,category:"deps",context:{contract:Z.contract,missing:X}});return j}import{analyzePackageDocBlocks as q6}from"@contractspec/module.workspace";var H6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function V6($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:H6}),A=new Map;for(let X of j){let Y=$.dirname(X),B=$.join(Y,"src");if(!await $.exists(B))continue;try{let q=JSON.parse(await $.readFile(X));A.set(Y,{packageName:q.name??$.relative(W,Y),packageRoot:Y,srcRoot:B})}catch{continue}}let Q=$.join(W,"package.json"),Z=$.join(W,"src");if(await $.exists(Q)&&await $.exists(Z))try{let X=JSON.parse(await $.readFile(Q));A.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:Z})}catch{}return[...A.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function XW($,W){let j=[],A=await V6($,W);for(let Q of A){let Z=q6({packageName:Q.packageName,srcRoot:Q.srcRoot});for(let X of Z.diagnostics)j.push({...X,packageName:Q.packageName,packageRoot:Q.packageRoot,srcRoot:Q.srcRoot})}return j}async function D1($,W){let j=W.workspaceRoot??process.cwd();return(await XW($.fs,j)).map((Q)=>({ruleId:Q.ruleId,severity:Q.severity==="warning"?"warning":"error",message:Q.message,category:"docs",file:Q.file,line:Q.line,column:Q.column,context:{packageName:Q.packageName,packageRoot:Q.packageRoot,...Q.context}}))}async function T1($,W,j){let A=[],Q=await G6($,W);if(A.push(Q),Q.status==="pass")A.push(await J6($,W,j));return A}async function G6($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");try{if(!await $.exists(j))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let Q=await $.readFile(j),Z=JSON.parse(Q),X=Z.aiProvider??"claude",Y=Z.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${X}, Model: ${Y}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function J6($,W,j){let A=$.join(W.workspaceRoot,".contractsrc.json");try{let Q=await $.readFile(A),X=JSON.parse(Q).aiProvider??"claude",B={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!B)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[B])return{category:"ai",name:"API Key",status:"pass",message:`${B} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${B} not set`,details:`Set ${B} in your environment to use AI features`,fix:j?{description:`Set ${B} environment variable`,apply:async()=>{let H=await j.input(`Enter your ${X} API key:`,{password:!0});if(!H)return{success:!1,message:"No API key provided"};let V=$.join(W.workspaceRoot,".env");try{let G="";if(await $.exists(V)){if(G=await $.readFile(V),G.includes(`${B}=`))return{success:!1,message:`${B} already in .env, update manually`};G+=`
|
|
1488
|
-
`}return
|
|
1489
|
-
`,await $.writeFile(
|
|
1763
|
+
`}function g8($){return $.replaceAll("\\","/").split("/").pop()??$}s();import{scanAllSpecsFromSource as c8,scanSpecSource as d8}from"@contractspec/module.workspace";import u8 from"micromatch";var Ew={};P(Ew,{validators:()=>h8,urlSchema:()=>f8,isValidVersion:()=>P8,isValidIdentifier:()=>Cw,isValidDotName:()=>Iw,isTestFile:()=>Ob,isLibraryDefinitionFile:()=>Vb,emailSchema:()=>r8});import Bm from"micromatch";function Ob($,b){let A=b?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return Bm.isMatch($,A)}function Vb($){let b=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(Bm.isMatch($,b))return!1;let A=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return Bm.isMatch($,A)}import*as q$ from"zod";function Cw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function Iw($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function P8($){return Number.isInteger($)&&$>0}var r8=q$.string().email(),f8=q$.string().url(),h8={specName:q$.string().refine(Iw,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:q$.number().int().positive(),identifier:q$.string().refine(Cw,{message:"Must be a valid TypeScript identifier"}),owner:q$.string().startsWith("@"),tag:q$.string().min(1)};function Jb($){return($??"").split("|").map((b)=>b.trim().replace(/^\.?\//,"")).filter(Boolean)}function o8($){let b=$?.packages&&$.packages.length>0?$.packages:["**"],A=[...Jb($?.conventions.models),...Jb($?.conventions.operations),...Jb($?.conventions.events),...Jb($?.conventions.presentations),...Jb($?.conventions.forms)];return[...new Set(b.flatMap((m)=>{let n=m==="**"?"":`${m}/`,W=X$.map((j)=>`${n}${j}`),w=A.map((j)=>`${n}${j}/**/*.ts`);return[...W,...w]}))]}function i8($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function l8($,b){let A=$.filePath.localeCompare(b.filePath);if(A!==0)return A;let m=($.declarationLine??Number.MAX_SAFE_INTEGER)-(b.declarationLine??Number.MAX_SAFE_INTEGER);if(m!==0)return m;return($.discoveryId??$.key??"").localeCompare(b.discoveryId??b.key??"")}async function g$($,b={}){if(b.paths&&b.paths.length>0)return[...new Set(b.paths)].sort((A,m)=>A.localeCompare(m));if(b.pattern)return $.glob({cwd:b.cwd,pattern:b.pattern});return $.glob({cwd:b.cwd,patterns:o8(b.config)})}async function xA($,b={}){let A=await g$($.fs,b),m=b.type?Array.isArray(b.type)?b.type:[b.type]:[],n=[];for(let W of A){if(b.config?.excludePackages&&u8.isMatch(W,b.config.excludePackages,{contains:!0}))continue;if(W.includes("node_modules")||W.includes("/dist/")||Ob(W,b.config)||Vb(W))continue;try{let w=await $.fs.readFile(W),j=c8(w,W),y=j.length>0?j:[d8(w,W)];for(let B of y)if(i8(B,b,m))n.push(B)}catch{}}return n.sort(l8)}function _$($,b){if(b===0)return 100;return Math.round($/b*100*100)/100}function TA($){let b=JSON.parse($),A=new Map,m=0,n=0,W=0,w=0,j=0,y=0,B=0,S=0;for(let[Z,G]of Object.entries(b)){let X=t8(Z,G);A.set(Z,X),m+=X.statements.total,n+=X.statements.covered,W+=X.branches.total,w+=X.branches.covered,j+=X.functions.total,y+=X.functions.covered,B+=X.lines.total,S+=X.lines.covered}let Q={statements:{covered:n,total:m,pct:_$(n,m)},branches:{covered:w,total:W,pct:_$(w,W)},functions:{covered:y,total:j,pct:_$(y,j)},lines:{covered:S,total:B,pct:_$(S,B)}};return{files:A,total:Q}}function t8($,b){let A=Object.keys(b.statementMap).length,m=Object.values(b.s).filter((S)=>S>0).length,n=Object.keys(b.fnMap).length,W=Object.values(b.f).filter((S)=>S>0).length,w=0,j=0;for(let S of Object.values(b.b))w+=S.length,j+=S.filter((Q)=>Q>0).length;let y=new Set,B=new Set;for(let[S,Q]of Object.entries(b.statementMap))for(let Z=Q.start.line;Z<=Q.end.line;Z++)if(y.add(Z),(b.s[S]??0)>0)B.add(Z);return{path:$,statements:{covered:m,total:A,pct:_$(m,A)},branches:{covered:j,total:w,pct:_$(j,w)},functions:{covered:W,total:n,pct:_$(W,n)},lines:{covered:B.size,total:y.size,pct:_$(B.size,y.size)}}}function Sm($){switch($){case"istanbul":return{parse:TA};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function Qm($,b){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&b?.includes("cobertura"))return"cobertura";return"istanbul"}function Zm($,b,A,m){let n=[];if(A.statements!==void 0&&m.statements.pct<A.statements)n.push({metric:"statements",required:A.statements,actual:m.statements.pct,message:`Statement coverage ${m.statements.pct}% is below required ${A.statements}%`});if(A.branches!==void 0&&m.branches.pct<A.branches)n.push({metric:"branches",required:A.branches,actual:m.branches.pct,message:`Branch coverage ${m.branches.pct}% is below required ${A.branches}%`});if(A.functions!==void 0&&m.functions.pct<A.functions)n.push({metric:"functions",required:A.functions,actual:m.functions.pct,message:`Function coverage ${m.functions.pct}% is below required ${A.functions}%`});if(A.lines!==void 0&&m.lines.pct<A.lines)n.push({metric:"lines",required:A.lines,actual:m.lines.pct,message:`Line coverage ${m.lines.pct}% is below required ${A.lines}%`});if(A.mutations!==void 0)n.push({metric:"mutations",required:A.mutations,actual:0,message:`Mutation coverage required (${A.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:b,requirement:A,actual:m,passed:n.length===0,failures:n}}async function Gm($,b,A){let{fs:m,logger:n}=$,W=[],w=A.workspaceRoot?`${A.workspaceRoot}/coverage`:"./coverage",j=[`${w}/coverage-final.json`,`${w}/coverage.json`,`${w}/coverage-summary.json`],y,B;for(let G of j)if(await m.exists(G)){y=await m.readFile(G),B=G;break}if(!y)return n.info("No coverage report found, skipping coverage checks"),W;let S=Qm(B??"coverage.json"),Z=Sm(S).parse(y);for(let G of b){if(G.specType!=="test-spec"||!G.key||!G.version||!G.sourceBlock)continue;let X=G.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!X||!X[1])continue;let Y=X[1],V={},O=Y.match(/statements\s*:\s*(\d+)/);if(O&&O[1])V.statements=parseInt(O[1],10);let K=Y.match(/branches\s*:\s*(\d+)/);if(K&&K[1])V.branches=parseInt(K[1],10);let J=Y.match(/functions\s*:\s*(\d+)/);if(J&&J[1])V.functions=parseInt(J[1],10);let _=Y.match(/lines\s*:\s*(\d+)/);if(_&&_[1])V.lines=parseInt(_[1],10);if(Object.keys(V).length===0)continue;let H=Zm(G.key,G.version,V,Z.total);for(let q of H.failures)W.push({ruleId:"coverage-below-threshold",severity:"error",message:q.message,category:"coverage",file:G.filePath,context:{specKey:G.key,specVersion:G.version,metric:q.metric,required:q.required,actual:q.actual}})}return W}s();import{addContractNode as p8,buildReverseEdges as a8,createContractGraph as e8,detectCycles as s8,findMissingDependencies as $9,parseImportedSpecNames as b9,toDot as A9}from"@contractspec/module.workspace";async function Mw($,b={}){let{fs:A}=$,m=await g$(A,{config:b.config,pattern:b.pattern}),n=e8();for(let j of m){let y=await A.readFile(j),B=A.relative(".",j),S=A.basename(j).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",Q=b9(y,j);p8(n,S,B,Q)}a8(n);let W=s8(n),w=$9(n);return{graph:n,total:n.size,cycles:W,missing:w}}function Oq($,b){return $.get(b)}function Vq($){return A9($)}function Jq($){let b=Array.from($.values()),A=b.filter((w)=>w.dependencies.length>0),m=b.filter((w)=>w.dependencies.length===0),n=b.filter((w)=>w.dependents.length>0),W=b.filter((w)=>w.dependents.length===0);return{total:$.size,withDeps:A.length,withoutDeps:m.length,used:n.length,unused:W.length}}async function Xm($,b){let A=[],m=await g($.fs),n=await Mw($,{config:m,pattern:b.pattern});for(let W of n.cycles)A.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${W.join(" → ")}`,category:"deps",context:{cycle:W}});for(let W of n.missing)for(let w of W.missing)A.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${W.contract} requires ${w}`,category:"deps",context:{contract:W.contract,missing:w}});return A}import{analyzePackageDocBlocks as m9}from"@contractspec/module.workspace";var n9=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function W9($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:n9}),m=new Map;for(let w of A){let j=$.dirname(w),y=$.join(j,"src");if(!await $.exists(y))continue;try{let B=JSON.parse(await $.readFile(w));m.set(j,{packageName:B.name??$.relative(b,j),packageRoot:j,srcRoot:y})}catch{continue}}let n=$.join(b,"package.json"),W=$.join(b,"src");if(await $.exists(n)&&await $.exists(W))try{let w=JSON.parse(await $.readFile(n));m.set(b,{packageName:w.name??b,packageRoot:b,srcRoot:W})}catch{}return[...m.values()].sort((w,j)=>w.packageRoot.localeCompare(j.packageRoot))}async function DA($,b){let A=[],m=await W9($,b);for(let n of m){let W=m9({packageName:n.packageName,srcRoot:n.srcRoot});for(let w of W.diagnostics)A.push({...w,packageName:n.packageName,packageRoot:n.packageRoot,srcRoot:n.srcRoot})}return A}async function Ym($,b){let A=b.workspaceRoot??process.cwd();return(await DA($.fs,A)).map((n)=>({ruleId:n.ruleId,severity:n.severity==="warning"?"warning":"error",message:n.message,category:"docs",file:n.file,line:n.line,column:n.column,context:{packageName:n.packageName,packageRoot:n.packageRoot,...n.context}}))}async function Hm($,b,A){let m=[],n=await w9($,b);if(m.push(n),n.status==="pass")m.push(await j9($,b,A));return m}async function w9($,b){let A=$.join(b.workspaceRoot,".contractsrc.json");try{if(!await $.exists(A))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let n=await $.readFile(A),W=JSON.parse(n),w=W.aiProvider??"claude",j=W.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${w}, Model: ${j}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function j9($,b,A){let m=$.join(b.workspaceRoot,".contractsrc.json");try{let n=await $.readFile(m),w=JSON.parse(n).aiProvider??"claude",y={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[w];if(!y)return{category:"ai",name:"API Key",status:"pass",message:`${w} does not require an API key`};if(!!process.env[y])return{category:"ai",name:"API Key",status:"pass",message:`${y} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${y} not set`,details:`Set ${y} in your environment to use AI features`,fix:A?{description:`Set ${y} environment variable`,apply:async()=>{let S=await A.input(`Enter your ${w} API key:`,{password:!0});if(!S)return{success:!1,message:"No API key provided"};let Q=$.join(b.workspaceRoot,".env");try{let Z="";if(await $.exists(Q)){if(Z=await $.readFile(Q),Z.includes(`${y}=`))return{success:!1,message:`${y} already in .env, update manually`};Z+=`
|
|
1764
|
+
`}return Z+=`${y}=${S}
|
|
1765
|
+
`,await $.writeFile(Q,Z),{success:!0,message:`Added ${y} 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 y9}from"node:child_process";import{promisify as B9}from"node:util";var NA=B9(y9);async function qm($,b){let A=[];return A.push(await S9(b)),A.push(await Q9(b)),A.push(await Z9($,b)),A}async function S9($){try{return await NA("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 NA("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 Q9($){try{let{stdout:b}=await NA("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 Z9($,b){let A=$.join(b.workspaceRoot,"package.json");try{if(!await $.exists(A))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot){let j=$.join(b.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(j))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let n=await $.readFile(A),W=JSON.parse(n);if(W.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||W.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 NA("npm install -D @contractspec/app.cli-contractspec",{cwd:b.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(j){return{success:!1,message:`Failed to install: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}s();import{DEFAULT_CONTRACTSRC as FA}from"@contractspec/lib.contracts-spec/workspace-config";import{join as G9,relative as X9}from"node:path";var Y9="contractspec",H9="contractsrc.schema.json";function q9($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Kb($){return q9(X9($.configRoot,G9($.workspaceRoot,"node_modules",Y9,H9)))}var _b=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md","usage-md"],xw={"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)"},Tw=["core","connect","builder-managed","builder-local","builder-hybrid"],Dw={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 Ub={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function zb($){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 U$($){return $.preset??"core"}function Fw($,b){if(b.length>0)return b;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return _b}}function Om($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function vw($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function gq($){return $.startsWith("builder-")}function kq($){return $==="connect"}function gw($){let b=U$($),A=O9($.projectName);switch(b){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset managed-mvp`,`contractspec builder status --workspace-id ${A}`];case"builder-local":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return["contractspec doctor",`contractspec builder init --workspace-id ${A} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${A} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function O9($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function kw($){let b=U$($),A=[Ub.verificationCache];if(b==="connect")A.unshift(Ub.connect);return A}function bb($){let b=$.isMonorepo&&$.scope==="package",A=b&&$.packageRoot?$.packageRoot:$.workspaceRoot,m=V9($),n=J9($);return{$schema:Kb({configRoot:A,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...m?{connect:m}:{},...n?{builder:n}:{},...b&&$.packageName?{package:$.packageName}:{}}}function vA($){let b=U$($),A={"editor.formatOnSave":!0,"editor.defaultFormatter":"biomejs.biome","editor.codeActionsOnSave":{"source.organizeImports.biome":"explicit"},"[javascript]":{"editor.defaultFormatter":"biomejs.biome"},"[typescript]":{"editor.defaultFormatter":"biomejs.biome"},"[javascriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[typescriptreact]":{"editor.defaultFormatter":"biomejs.biome"},"[json]":{"editor.defaultFormatter":"biomejs.biome"},"contractspec.validation.onSave":!0,"contractspec.validation.onOpen":!0,"contractspec.registry.baseUrl":"https://registry.contractspec.io","contractspec.specsExplorer.groupBy":"type"};if(Om(b))A["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return A}function Lb(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function Pw(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function rw($){let b=$.projectName??"this project",m=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1490
1766
|
|
|
1491
1767
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1492
1768
|
|
|
@@ -1507,10 +1783,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1507
1783
|
## Contract Locations
|
|
1508
1784
|
|
|
1509
1785
|
Contracts are located in:
|
|
1510
|
-
- \`${
|
|
1511
|
-
- \`${
|
|
1512
|
-
- \`${
|
|
1513
|
-
- \`${
|
|
1786
|
+
- \`${m}/operations/\` - Command and query specs
|
|
1787
|
+
- \`${m}/events/\` - Event specs
|
|
1788
|
+
- \`${m}/presentations/\` - UI presentation specs
|
|
1789
|
+
- \`${m}/features/\` - Feature module specs
|
|
1514
1790
|
|
|
1515
1791
|
## When Making Changes
|
|
1516
1792
|
|
|
@@ -1519,6 +1795,14 @@ Contracts are located in:
|
|
|
1519
1795
|
3. **If no contract**: Create a new contract using \`contractspec create\`.
|
|
1520
1796
|
4. **After changes**: Validate with \`contractspec validate\`.
|
|
1521
1797
|
|
|
1798
|
+
## Adoption Engine
|
|
1799
|
+
|
|
1800
|
+
- Reuse existing workspace code before inventing a new local surface.
|
|
1801
|
+
- Prefer ContractSpec OSS packages before reaching for raw framework or vendor primitives.
|
|
1802
|
+
- Use \`contractspec connect adoption sync\` to mirror the local catalog.
|
|
1803
|
+
- Use \`contractspec connect adoption resolve --family <family> --stdin\` to resolve the recommended reuse target.
|
|
1804
|
+
- If Connect says \`rewrite\`, reuse the existing workspace or ContractSpec candidate instead of creating a duplicate.
|
|
1805
|
+
|
|
1522
1806
|
## Key Commands
|
|
1523
1807
|
|
|
1524
1808
|
- \`contractspec create\` - Scaffold new specs
|
|
@@ -1538,13 +1822,13 @@ defineCommand({
|
|
|
1538
1822
|
});
|
|
1539
1823
|
\`\`\`
|
|
1540
1824
|
|
|
1541
|
-
## Rules for ${
|
|
1825
|
+
## Rules for ${b}
|
|
1542
1826
|
|
|
1543
1827
|
- All API endpoints must have a corresponding operation contract.
|
|
1544
1828
|
- Events must be declared in contracts before being emitted.
|
|
1545
1829
|
- UI components should reference presentation contracts.
|
|
1546
1830
|
- Feature flags should be defined in feature modules.
|
|
1547
|
-
`}function
|
|
1831
|
+
`}function fw($){let b=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package",m=U$($),n=A&&$.packageName?`${$.packageName} package`:b,W="src/contracts",w=$.isMonorepo?A?`
|
|
1548
1832
|
## Monorepo Scope
|
|
1549
1833
|
|
|
1550
1834
|
This guide is scoped to the current package.
|
|
@@ -1558,7 +1842,7 @@ This guide is scoped to the workspace root.
|
|
|
1558
1842
|
- Prefer the nearest package guide when working inside a specific package.
|
|
1559
1843
|
`:"";return`# ContractSpec AI Guide
|
|
1560
1844
|
|
|
1561
|
-
Scope: \`${
|
|
1845
|
+
Scope: \`${n}\`
|
|
1562
1846
|
|
|
1563
1847
|
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1564
1848
|
|
|
@@ -1568,7 +1852,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
|
|
|
1568
1852
|
- Validate contracts after changes with \`contractspec validate\`.
|
|
1569
1853
|
- Regenerate derived artifacts before considering the work complete.
|
|
1570
1854
|
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1571
|
-
${
|
|
1855
|
+
${w}
|
|
1572
1856
|
## Contract Locations
|
|
1573
1857
|
|
|
1574
1858
|
- \`src/contracts/operations/\` - command and query specs
|
|
@@ -1595,20 +1879,55 @@ ${X}
|
|
|
1595
1879
|
- Keep changes spec-first, deterministic, and reviewable.
|
|
1596
1880
|
- Do not change generated outputs without updating their source contract.
|
|
1597
1881
|
- When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
|
|
1882
|
+
- Reuse existing workspace code before creating new files, packages, or dependencies.
|
|
1883
|
+
- Prefer ContractSpec OSS packages by family:
|
|
1884
|
+
- UI: local reusable UI -> \`@contractspec/lib.design-system\` -> platform ui-kit -> shadcn/web fallback
|
|
1885
|
+
- Contracts: existing local spec -> \`@contractspec/lib.contracts-spec\` / \`@contractspec/lib.schema\`
|
|
1886
|
+
- Integrations/runtime/shared libs: existing workspace surface -> ContractSpec OSS catalog -> reviewed fallback
|
|
1887
|
+
- Use \`contractspec connect adoption sync\` and \`contractspec connect adoption resolve --family <family>\` when the right reusable surface is unclear.
|
|
1598
1888
|
|
|
1599
1889
|
## Initialization Preset
|
|
1600
1890
|
|
|
1601
|
-
- This workspace was initialized with the \`${
|
|
1602
|
-
`}function
|
|
1603
|
-
`}async function v1($,W){let j=[];return j.push(await R6($,W)),j.push(await C6($,W)),j.push(await D6($,W)),j.push(await T6($,W)),j.push(await F6($,W)),j.push(await x6($,W)),j.push(await y6($,W)),j}async function R$($,W){if(W.packageRoot&&W.packageRoot!==W.workspaceRoot&&await $.exists($.join(W.packageRoot,".contractsrc.json")))return W.packageRoot;return W.workspaceRoot}async function R6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(await $.exists(j))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let Q=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(Q)),{success:!0,message:"Created .contractsrc.json"}}catch(Q){return{success:!1,message:`Failed to create: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function C6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j);return JSON.parse(Q),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Q){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Q instanceof Error?Q.message:String(Q),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function D6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=[];if(!Z.outputDir)X.push("outputDir");if(!Z.conventions)X.push("conventions");if(X.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${X.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let Y=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let B of X)if(Y[B]!==void 0)Z[B]=Y[B];return await $.writeFile(j,F(Z)),{success:!0,message:"Added missing fields"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function T6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:Z.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return Z.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,F(Z)),{success:!0,message:"Added versioning configuration"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function F6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.hooks){let B=Z.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(B).length} git hook(s) configured`}}let X=$.join(W.workspaceRoot,".husky");if(await $.exists(X))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return Z.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,F(Z)),{success:!0,message:"Added hooks configuration"}}catch(B){return{success:!1,message:`Failed: ${B instanceof Error?B.message:String(B)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function x6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(Q==="connect"){let Y=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((H)=>H!==null),B=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(Y.length===0&&!B)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...Y,...B?["connect.studio.endpoint"]:[]].join(", ")}`}}let Z=[],X=A.builder?.api?.controlPlaneTokenEnvVar;if((Q==="builder-managed"||Q==="builder-hybrid")&&!A.builder?.api?.baseUrl)Z.push("builder.api.baseUrl");if((Q==="builder-managed"||Q==="builder-hybrid")&&!X)Z.push("builder.api.controlPlaneTokenEnvVar");if((Q==="builder-managed"||Q==="builder-hybrid")&&X&&!process.env[X])Z.push(`env:${X}`);if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)Z.push("builder.localRuntime.runtimeId");if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)Z.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:Z.length===0?"pass":"warn",message:Z.length===0?`Builder preset inferred (${Q}) and required config is present`:`Builder preset inferred (${Q}) but setup is missing ${Z.join(", ")}`}}async function y6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q!=="builder-managed"&&Q!=="builder-hybrid")return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder managed/hybrid preset is not enabled"};let Z=$.join(j,".vscode","settings.json"),X=A.builder?.api?.baseUrl;if(!X)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let Y=await $.readFile(Z).catch(()=>""),B=Y?r(Y):void 0;if(B?.["contractspec.api.baseUrl"]===X)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let H=$.join(j,".vscode");if(!await $.exists(H))await $.mkdir(H);let V={...B??{},...BW({workspaceRoot:W.workspaceRoot,packageRoot:W.packageRoot,isMonorepo:W.isMonorepo,packageName:W.packageName,interactive:!1,preset:Q,targets:[],builderApiBaseUrl:X})};return await $.writeFile(Z,F(V)),{success:!0,message:"Updated VS Code settings mirror"}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}}}import{exec as v6}from"node:child_process";import{promisify as m6}from"node:util";var C$=m6(v6);async function m1($,W){let j=[];return j.push(await P6(W)),j.push(await k6(W)),j.push(await h6($,W)),j.push(await g6($,W)),j.push(await f6($,W)),j}async function P6($){try{let{stdout:W}=await C$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${W.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function k6($){try{let{stdout:W}=await C$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${W.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function h6($,W){let j=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:Q,name:Z}of j){let X=$.join(W.workspaceRoot,Q);if(await $.exists(X)){A=Z;break}}if(!A){let Q=$.join(W.workspaceRoot,".."),Z=$.join(W.workspaceRoot,"../.."),X=[Q,Z];for(let Y of X){for(let{file:B,name:q}of j){let H=$.join(Y,B);if(await $.exists(H)){A=q;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await C$(`${A} --version`,{cwd:W.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function g6($,W){let j=$.join(W.workspaceRoot,"node_modules");if(await $.exists(j))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await C$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function f6($,W){let j=$.join(W.workspaceRoot,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A),Z={...Q.dependencies,...Q.devDependencies};if("@contractspec/lib.contracts-spec"in Z)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${Z["@contractspec/lib.contracts-spec"]})`};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await C$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function P1($,W){let j=await XW($,W.workspaceRoot);if(j.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return j.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(W.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as u6,isFeatureFile as d6,scanAllSpecsFromSource as n6,scanExampleSource as c6,scanFeatureSource as r6}from"@contractspec/module.workspace";function l6(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function VW($,W={}){let{fs:j,logger:A}=$,Q=l6(),Z=W.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let X=await j.glob({pattern:Z});for(let B of X){if(B.includes("node_modules")||B.includes("/dist/"))continue;try{let q=await j.readFile(B);if(d6(B)){let H=r6(q,B);Q.features.set(H.key,H);continue}if(u6(B)){let H=c6(q,B);Q.examples.set(H.key,H);continue}if(B.includes(".app-config.")||B.includes(".blueprint.")){let H=n6(q,B);for(let V of H)if(V.specType==="app-config"&&V.key)Q.appConfigs.set(V.key,V)}}catch{}}try{let B=await j.glob({pattern:"**/.contractsrc.json"});for(let q of B){if(q.includes("node_modules"))continue;try{let H=await j.readFile(q),V=JSON.parse(H);Q.workspaceConfigs.set(q,{file:q,config:V,valid:!0,errors:[]})}catch(H){Q.workspaceConfigs.set(q,{file:q,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Q.features.size,examples:Q.examples.size,appConfigs:Q.appConfigs.size,workspaceConfigs:Q.workspaceConfigs.size,total:Q.features.size+Q.examples.size+Q.appConfigs.size+Q.workspaceConfigs.size};return A.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Q,stats:Y}}function mb($){let W=[];for(let[j,A]of $.features)W.push({key:j,file:A.filePath,type:"feature"});for(let[j,A]of $.examples)W.push({key:j,version:A.version,file:A.filePath,type:"example"});for(let[j,A]of $.appConfigs)W.push({key:j,version:A.version,file:A.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function GW($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function k1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function JW($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let A=await $.readFile(j),Q=JSON.parse(A);return{version:typeof Q.version==="number"&&Number.isFinite(Q.version)?Q.version:1,criticalPackages:k1(Q.criticalPackages).map(GW),criticalFeatureKeys:k1(Q.criticalFeatureKeys),smokePackages:k1(Q.smokePackages)}}catch{return}}function T8($,W){let j=GW($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function F8($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function d$($){return GW(`${GW($)}/config/stability-policy.json`)}async function h1($,W){let j=[],A=await JW($,W.workspaceRoot),Q=await VW({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(o6(Q.stats.features)),j.push(i6(Q.stats.examples)),j.push(p6(Q.inventory.features,A,W)),j.push(t6(Q.inventory.examples)),j.push(a6(Q.inventory.workspaceConfigs)),j}function o6($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function i6($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function p6($,W,j){let A=[],Q=[];for(let[Z,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(F8(Z,W))Q.push(Z);else A.push(Z);if(Q.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Q.length>0?"fail":"warn",message:Q.length>0?`${Q.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:Q.length>0?`Critical features: ${Q.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:Q,missingFeatures:A}}}function t6($){let W=[];for(let[j,A]of $)if(!A.entrypoints.packageName)W.push(j);if(W.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${W.length} example(s) missing packageName`,details:`Examples: ${W.join(", ")}`}}function a6($){let W=[];for(let[,j]of $)if(!j.valid)W.push(j.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(W.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${W.length} workspace config(s) invalid`,details:`Files: ${W.join(", ")}`}}async function g1($,W){let j=[];return j.push(await s6($,W)),j.push(await e6($,W)),j.push(await $7($,W)),j}async function s6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(await $.exists(j))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let Q=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Q))await $.mkdir(Q);let Z=q0();return await $.writeFile(j,F(Z)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function e6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(!await $.exists(j))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let Y=q0(),B=p(Z,Y);return await $.writeFile(j,F(B)),{success:!0,message:"Registered MCP server"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function $7($,W){let j=qW();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Q=await $.readFile(j);if(JSON.parse(Q).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var W7=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],x8=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function j7($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,A])=>{if(typeof A==="string")W[j]=A;return W},{})}function A7($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function Q7($,W,j){let A=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:x8}),Q=[];for(let Z of A){let X=$.dirname(Z),Y=$.relative(W,X);try{let B=JSON.parse(await $.readFile(Z)),q=j7(B.scripts),H=await $.glob({patterns:W7,cwd:X,ignore:x8});Q.push({packageName:B.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof q.build==="string",hasTypecheckScript:typeof q.typecheck==="string",hasLintScript:typeof q.lint==="string"||typeof q["lint:check"]==="string",hasTestScript:typeof q.test==="string",usesPassWithNoTests:A7(q),testFileCount:H.length,tier:T8(Y,j)})}catch{continue}}return Q}function Z7($){let W=[];if(!$.hasBuildScript)W.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)W.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)W.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)W.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)W.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)W.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return W}function X7($){let W=[];if($.testFileCount>0&&!$.hasTestScript)W.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)W.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return W}async function y8($,W,j){let A=await Q7($,W,j),Q=[];for(let X of A){if(X.tier==="critical")Q.push(...Z7(X));Q.push(...X7(X))}let Z=A.filter((X)=>X.tier==="critical").map((X)=>({packageName:X.packageName,packagePath:X.packagePath,hasBuildScript:X.hasBuildScript,hasTypecheckScript:X.hasTypecheckScript,hasLintScript:X.hasLintScript,hasTestScript:X.hasTestScript,usesPassWithNoTests:X.usesPassWithNoTests,testFileCount:X.testFileCount}));return{findings:Q,criticalPackages:Z}}function m8($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function v8($,W,j,A){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let Q=W.filter((Z)=>{return Z.tier==="critical"||j.has(Z.code)});return{category:"workspace",name:$,status:Q.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:m8(W),context:{findings:W}}}async function P8($,W){let j=await JW($,W.workspaceRoot);if(!j)return[];let A=await y8($,W.workspaceRoot,j),Q=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),Z=A.findings.filter((B)=>Q.has(B.code)),X=A.findings.filter((B)=>B.code==="tests-without-test-script"),Y=A.findings.filter((B)=>B.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:Z.length>0?"fail":"pass",message:Z.length>0?`${Z.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:Z.length>0?m8(Z):W.verbose?`Policy: ${d$(W.workspaceRoot)}`:void 0,context:{policyPath:d$(W.workspaceRoot),criticalPackages:A.criticalPackages,findings:Z}},v8("Package Test Scripts",X,new Set,"All tested packages expose a test script"),v8("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var Y7=["src/contracts","contracts","src/specs","specs"];async function f1($,W){let j=[];return j.push(B7(W)),j.push(await q7($,W)),j.push(await H7($,W)),j.push(await V7($,W)),j.push(await J7($,W)),j.push(...await P8($,W)),j}function B7($){if($.isMonorepo){let W=$.packageName?` in package "${$.packageName}"`:"",j=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${W}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${j}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function q7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let A of j){let Q=$.join(A,"package.json");if(await $.exists(Q))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function H7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],A=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of Y7){let B=$.join(X,Y);if(await $.exists(B)){let q=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${q} level`:void 0}}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let Q=W.isMonorepo?"src/contracts":"src/contracts",Z=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Q}/${Z} to organize your specs`,fix:{description:`Create ${Q}/ directory${Z}`,apply:async()=>{try{let X=$.join(A,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Q}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function V7($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=W.isMonorepo?W.packageRoot:W.workspaceRoot,Q=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:A});if(Q.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Q.length} contract file(s)${X}`,details:W.verbose?Q.slice(0,5).join(", "):void 0}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:W.isMonorepo?`No contract files found in package "${W.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function G7($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let A=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:W.packageRoot,level:"package"}}let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{path:j,root:W.workspaceRoot,level:"workspace"};return null}async function J7($,W){try{let j=await G7($,W);if(!j)return{category:"workspace",name:"Output Directory",status:"skip",message:W.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(j.path),Q=JSON.parse(A),Z=Q.outputDir??"./src",X=$.join(j.root,Z),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${Z}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let q=Z==="./src"||Z==="src",H=Array.isArray(Q.packages)&&Q.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&q&&(H||j.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:W.verbose?`Resolved default output to packages via ${j.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${Z}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${Z} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${Z}`}}catch(V){return{success:!1,message:`Failed: ${V instanceof Error?V.message:String(V)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var k8=["cli","config","mcp","deps","docs","workspace","ai","layers"],h8={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var b7={checks:{runCliChecks:F1,runConfigChecks:v1,runMcpChecks:g1,runDepsChecks:m1,runDocChecks:P1,runWorkspaceChecks:f1,runAiChecks:T1,runLayerChecks:h1},workspace:{findWorkspaceRoot:D,findPackageRoot:f,isMonorepo:e$,getPackageName:I$}},w7={confirm:async()=>!1,input:async()=>""};async function g8($,W,j=w7,A=b7){let{fs:Q,logger:Z}=$,X=W.categories??k8,{checks:Y,workspace:B}=A,q=B.findWorkspaceRoot(W.workspaceRoot),H=B.findPackageRoot(W.workspaceRoot),V=B.isMonorepo(q),G=V?B.getPackageName(H):void 0,J={workspaceRoot:q,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let U=G?` (package: ${G})`:"";Z.info(`Detected monorepo${U}`)}let b=[];for(let U of X){if(W.skipAi&&U==="ai")continue;Z.info(`Checking ${h8[U]}...`);let O=await K7(U,Q,J,j,Y);for(let K of O){if(K.fix&&(K.status==="fail"||K.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${K.name}"? ${K.fix.description}`)){Z.info(`Applying fix: ${K.fix.description}`);let I=await K.fix.apply();if(I.success)Z.info(`✓ ${I.message}`),K.status="pass",K.message=`Fixed: ${I.message}`,K.fix=void 0;else Z.warn(`✗ ${I.message}`)}}b.push(K)}}let w=b.filter((U)=>U.status==="pass").length,L=b.filter((U)=>U.status==="warn").length,z=b.filter((U)=>U.status==="fail").length,S=b.filter((U)=>U.status==="skip").length;return{checks:b,passed:w,warnings:L,failures:z,skipped:S,healthy:z===0}}async function K7($,W,j,A,Q){switch($){case"cli":return Q.runCliChecks(W,j);case"config":return Q.runConfigChecks(W,j);case"mcp":return Q.runMcpChecks(W,j);case"deps":return Q.runDepsChecks(W,j);case"docs":return Q.runDocChecks(W,j);case"workspace":return Q.runWorkspaceChecks(W,j);case"ai":return Q.runAiChecks(W,j,A);case"layers":return Q.runLayerChecks(W,j);default:return[]}}function Hw($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("✓ All checks passed!");else W.push("✗ Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
`).length},X,Y=new RegExp(V0.contractHandler);while((X=Y.exec($))!==null)if(X[1])Q(X[1],"handler",Z(X.index));let B=new RegExp(V0.typeofSpec);while((X=B.exec($))!==null)if(X[1])Q(X[1],"typeof",Z(X.index));let q=new RegExp(V0.namedImport);while((X=q.exec($))!==null){let J=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(J)for(let b of J)Q(b,"import",Z(X.index))}let H=new RegExp(V0.defaultImport);while((X=H.exec($))!==null)if(X[1])Q(X[1],"import",Z(X.index));let V=new RegExp(V0.specAssignment);while((X=V.exec($))!==null)if(X[1])Q(X[1],"unknown",Z(X.index));return j}var l8=["**/*.ts(x)"];async function _W($,W,j={}){let{fs:A}=W,Q=j.includePatterns??l8,Z=j.excludePatterns??[...new Set([...S$,...Y$])],X=[];for(let Y of Q){let B=await A.glob({pattern:Y,ignore:Z});for(let q of B)try{let H=await A.readFile(q),G=r8(H,q).filter((J)=>J.specKey===$);X.push(...G)}catch{}}return X}async function ow($,W={}){let{fs:j}=$,A=W.includePatterns??l8,Q=W.excludePatterns??[...new Set([...S$,...Y$])],Z=new Map;for(let X of A){let Y=await j.glob({pattern:X,ignore:Q});for(let B of Y)try{let q=await j.readFile(B),H=r8(q,B);for(let V of H){let G=Z.get(V.specKey)??[];G.push(V),Z.set(V.specKey,G)}}catch{}}return Z}function g7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o8($,W,j){let A=g7(W),Q=[];if($==="operation")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")Q.push({path:`${j}/components/${A}.tsx`,type:"component"}),Q.push({path:`${j}/components/${A}.test.tsx`,type:"test"});if($==="form")Q.push({path:`${j}/forms/${A}.form.tsx`,type:"form"}),Q.push({path:`${j}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});return Q}import{Node as c,Project as f7,SyntaxKind as u7}from"ts-morph";function i8($){let W=[],A=new f7({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Q=(B)=>{if(!c.isObjectLiteralExpression(B))return;let q=B.getProperty("implementations");if(q&&c.isPropertyAssignment(q)){let H=q.getInitializer();if(H&&c.isArrayLiteralExpression(H)){for(let V of H.getElements())if(c.isObjectLiteralExpression(V)){let G,J,b,w=V.getProperty("path");if(w&&c.isPropertyAssignment(w)){let S=w.getInitializer();if(c.isStringLiteral(S))G=S.getLiteralText()}let L=V.getProperty("type");if(L&&c.isPropertyAssignment(L)){let S=L.getInitializer();if(c.isStringLiteral(S))J=S.getLiteralText()}let z=V.getProperty("description");if(z&&c.isPropertyAssignment(z)){let S=z.getInitializer();if(c.isStringLiteral(S))b=S.getLiteralText()}if(G&&J)W.push({path:G,type:J,description:b})}}}},Z=A.getDescendantsOfKind(u7.CallExpression);for(let B of Z){let q=B.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(q)){let H=B.getArguments();if(H.length>0&&c.isObjectLiteralExpression(H[0]))return Q(H[0]),W}}let X=A.getVariableStatements();for(let B of X)if(B.isExported())for(let q of B.getDeclarations()){let H=q.getInitializer();if(H&&c.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Q(H),W}}let Y=A.getExportAssignment((B)=>!B.isExportEquals());if(Y){let B=Y.getExpression();if(c.isObjectLiteralExpression(B))Q(B);else if(c.isAsExpression(B)&&c.isObjectLiteralExpression(B.getExpression()))Q(B.getExpression())}return W}function p8($){if($.length===0)return"missing";let W=$.filter((Q)=>Q.exists),j=$.filter((Q)=>Q.type!=="test");if(W.filter((Q)=>Q.type!=="test").length===0)return"missing";if($.every((Q)=>Q.exists))return"implemented";return"partial"}function sw($){let W=$.filter((Q)=>Q.status==="implemented").length,j=$.filter((Q)=>Q.status==="partial").length,A=$.filter((Q)=>Q.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:A,coverage:$.length>0?Math.round(W/$.length*100):100}}var c7={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function t8($){return d7("sha256").update($).digest("hex")}async function r7($,W,j,A={},Q){let Z={...c7,...A},X=Z.computeHashes?t8($.sourceBlock||""):void 0,Y=$.key??n7.basename($.filePath).replace(/\.[jt]s$/,""),B=$.version??"1.0.0",{fs:q}=W,H=[],V=new Set,G=async(b,w,L,z)=>{if(V.has(b))return;V.add(b);let S=await q.exists(b),U=void 0,O=void 0;if(S&&Z.computeHashes)try{U=await q.readFile(b),O=t8(U)}catch{}H.push({path:b,type:w,source:L,exists:S,implementationSourceContent:U,implementationSourceHash:O,description:z})};if(Z.includeExplicit&&$.sourceBlock){if(Q)Q.suffixText="Discover explicit implementations";let b=i8($.sourceBlock);for(let w of b)await G(w.path,w.type,"explicit",w.description)}if(Z.includeDiscovered){if(Q)Q.suffixText="Discover implementations";let b=await _W(Y,W,Z);for(let w of b){if(w.filePath===$.filePath)continue;await G(w.filePath,w.inferredType,"discovered")}}if(Z.includeConvention){if(Q)Q.suffixText="Discover implementations based on conventions";let b=Z.outputDir??j.outputDir??"./src",w=o8($.specType,Y,b);for(let{path:L,type:z}of w)await G(L,z,"convention")}if(Q)Q.suffixText="Determine implementation status";let J=p8(H);return{specKey:Y,specVersion:B,specPath:$.filePath,specType:$.specType,implementations:H,status:J,specHash:X}}async function a8($,W,j,A={},Q){let Z=[];for(let X of $){if(Q)Q.text=`Resolving implementation... (${Z.length}/${$.length})`;try{let Y=await r7(X,W,j,A,Q);Z.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return Z}async function o1($,W,j){let{fs:A}=$,Q=[],Z=await m(A),X=j.implementation??{},Y=W.filter((q)=>q.specType==="operation"),B=await a8(Y,{fs:A},Z,{computeHashes:X.useCache??!0});for(let q of B){if(X.requireImplemented&&q.status==="missing")Q.push({ruleId:"impl-missing",severity:"error",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});else if(q.status==="missing")Q.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});if(!X.allowPartial&&q.status==="partial"){let V=q.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Q.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${q.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status,missingFiles:V}})}let H=q.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Q.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${q.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,missingTests:H.map((V)=>V.path)}})}return Q}import{isFeatureFile as i7,scanAllSpecsFromSource as p7,scanFeatureSource as t7}from"@contractspec/module.workspace";function l7($,W){return`${$}.v${W}`}function i1($,W,j,A,Q,Z={}){let{treatMissingAsError:X=!0}=Z;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],B=[],q=[];for(let H of A){let V=l7(H.key,H.version);if(Q.has(V))Y.push(H);else if(B.push(H),X)q.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:B.length===0,foundTests:Y,missingTests:B,errors:q,specFile:$}}function s8($,W){return`${$}.v${W}`}function e8($,W){let j=new Map,A=new Map,Q=[],Z=[];for(let X of $){if(!X.key||!X.version)continue;let Y=s8(X.key,X.version);if(!X.testTarget){Z.push(Y);continue}let{type:B,key:q,version:H}=X.testTarget,V=H??X.version,G=s8(q,V),J=o7(W,B);if(!J||!J.has(G)){Q.push(Y);continue}if(A.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:A,orphanedTests:Q,testsWithoutTarget:Z}}function o7($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function t($,W){return`${$}.v${W}`}function a7(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function p1($,W){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[W]}async function zW($,W={}){let{fs:j,logger:A}=$;A.info("Starting integrity analysis...",{options:W});let Q=await N$(j,{config:W.config,cwd:W.cwd,pattern:W.pattern}),Z=a7(),X=[],Y=[];for(let K of Q){if((await j.stat(K)).isDirectory)continue;let I=await j.readFile(K);if(i7(K)){let M=t7(I,K);X.push(M)}else{let M=p7(I,K);for(let E of M)if(E.specType!=="unknown"&&E.specType!=="feature"){let C=p1(Z,E.specType);if(C&&E.key&&E.version!==void 0){let R=t(E.key,E.version);C.set(R,{key:E.key,version:E.version,file:E.filePath,type:E.specType,stability:E.stability,testTarget:E.testTarget,testCoverage:E.testCoverage})}}}}let B=W.featureKey?X.filter((K)=>K.key===W.featureKey):X,q=new Set;for(let K of B){for(let _ of K.operations){let I=t(_.key,_.version);if(q.add(`operation:${I}`),!Z.operations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_})}for(let _ of K.events){let I=t(_.key,_.version);if(q.add(`event:${I}`),!Z.events.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"event",ref:_})}for(let _ of K.presentations){let I=t(_.key,_.version);if(q.add(`presentation:${I}`),!Z.presentations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_})}for(let _ of K.experiments){let I=t(_.key,_.version);if(q.add(`experiment:${I}`),!Z.experiments.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"experiment",ref:_})}for(let _ of K.capabilities.provides){let I=t(_.key,_.version);if(q.add(`capability:${I}`),!Z.capabilities.has(I))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"capability",ref:_})}for(let _ of K.capabilities.requires){let I=t(_.key,_.version);q.add(`capability:${I}`)}for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=t(_.pres.key,_.pres.version);if(!Z.operations.has(I))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${_.op.key}.v${_.op.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op});if(!Z.presentations.has(M))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${_.pres.key}.v${_.pres.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_.pres})}if(K.presentationsTargets)for(let _ of K.presentationsTargets){let I=t(_.key,_.version);if(!Z.presentations.has(I))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:{key:_.key,version:_.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let K of V){let _=p1(Z,K);if(!_)continue;for(let[I,M]of _)if(!q.has(`${K}:${I}`))H.push(M),Y.push({severity:"warning",type:"orphaned",message:`${K} ${M.key}.v${M.version} is not linked to any feature`,file:M.file,specKey:M.key,specType:M.type})}let G=[];for(let[,K]of Z.testSpecs)G.push({filePath:K.file,specType:"test-spec",key:K.key,version:K.version,testTarget:K.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let J=e8(G,Z);for(let K of B)for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=J.targetToTests.get(I),E=!1,C=!1;if(M)for(let R of M){let v=Z.testSpecs.get(R);if(v?.testCoverage){if(v.testCoverage.hasSuccess)E=!0;if(v.testCoverage.hasError)C=!0}}if(!M||!E||!C){let R=[];if(!E)R.push("success scenario");if(!C)R.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${_.op.key}.v${_.op.version} linked to presentation requires tests covering: ${R.join(", ")}`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op})}}let b={},w=0;for(let K of V){let _=p1(Z,K);if(!_)continue;let I=_.size,M=0,E=0,C=W.requireTestsFor?.includes(K);for(let[R,v]of _){if(q.has(`${K}:${R}`))M++;if(C){let x=t(v.key,v.version),L$=J.targetToTests.has(x),v0=`${v.key}.test`,zA=Z.testSpecs.has(t(v0,v.version));if(!L$&&!zA)E++,w++,Y.push({severity:"warning",type:"missing-test",message:`${K} ${v.key}.v${v.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:v.file,specKey:v.key,specType:v.type})}}b[K]={total:I,covered:M,orphaned:I-M,missingTest:C?E:0}}let L=Object.values(b).reduce((K,_)=>K+_.total,0),z=Object.values(b).reduce((K,_)=>K+_.covered,0),S={total:L,linkedToFeature:z,orphaned:L-z,missingTest:w,byType:b},O=!Y.some((K)=>K.severity==="error");return A.info("Integrity analysis complete",{features:X.length,totalSpecs:L,orphaned:H.length,issues:Y.length,healthy:O}),{inventory:Z,features:B,coverage:S,issues:Y,orphanedSpecs:H,healthy:O}}function UK($){let W=[];for(let j of Object.values($))for(let A of j.values())W.push(A);return W}function LK($,W){return $.filter((j)=>j.type===W)}function OK($,W){return $.filter((j)=>j.severity===W)}i();async function t1($,W){let j=[],A=await m($.fs),Q=await zW($,{config:A,pattern:W.pattern,all:!0});for(let Z of Q.issues)j.push({ruleId:`integrity-${Z.type}`,severity:Z.severity==="error"?"error":"warning",message:Z.message,category:"integrity",file:Z.file,context:{specKey:Z.specKey,specType:Z.specType,featureKey:Z.featureKey,ref:Z.ref}});return j}async function a1($,W){let j=[],A=await VW($,{});for(let[Q,Z]of A.inventory.features){if(!Z.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Q}' missing 'owners' field`,category:"layers",file:Z.filePath,context:{key:Q}});if(Z.operations.length===0&&Z.events.length===0&&Z.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Q}' has no operations, events, or presentations`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let[Q,Z]of A.inventory.examples){if(!Z.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Q}' missing 'packageName' in entrypoints`,category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.surfaces.templates&&!Z.surfaces.sandbox.enabled&&!Z.surfaces.studio.enabled&&!Z.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Q}' has no enabled surfaces`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let Q of A.inventory.workspaceConfigs.values())if(!Q.valid)for(let Z of Q.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${Z}`,category:"layers",file:Q.file});return j}i();import{ContractsrcSchema as e7,DEFAULT_CONTRACTSRC as UW}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as s7}from"@contractspec/module.workspace";async function $$($,W={}){let{fs:j,scan:A=s7}=$,Q=await N$(j,W),Z=[],X=Array.isArray(W.type)?W.type:[W.type];for(let Y of Q){if(j0(Y,W.config))continue;if(A0(Y))continue;try{let B=await j.readFile(Y),q=A(B,Y);if(q.specType==="unknown")continue;if(W.type&&!X.includes(q.specType))continue;Z.push(q)}catch{}}return Z}function FK($){let W=new Map;for(let j of $){let A=W.get(j.specType)??[];A.push(j),W.set(j.specType,A)}return W}var $X=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,WX=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,jX=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,AX=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,QX=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,ZX=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,XX=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function LW($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function YX($,W){let j=$.replaceAll("\\","/"),A=new Set(["contracts","features",...LW(W?.conventions?.operations),...LW(W?.conventions?.events),...LW(W?.conventions?.presentations),...LW(W?.conventions?.forms)]);return j.split("/").some((Q)=>A.has(Q))}function BX($,W,j){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||QX.test(A)||AX.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(W.has(A))return!1;if(YX(A,j))return!1;return $X.test(A)}function $4($){return $.replaceAll("\\","/").match(ZX)?.[1]??null}function qX($){let W=$.split(`
|
|
1610
|
-
`).map((j)=>j.trim()).filter((j)=>j.length>0&&!j.startsWith("//")&&!j.startsWith("/*")&&!j.startsWith("*")&&!j.startsWith("*/"));return W.length>0&&W.every((j)=>j.startsWith("import ")||j.startsWith("export *")||j.startsWith("export {")||j.startsWith("export type {")||j==="'use client';"||j==='"use client";'||j==="'use server';"||j==='"use server";')}function HX($){if(!$)return UW;let W=e7.safeParse($),j=W.success?W.data:{};return{...UW,...j,conventions:{...UW.conventions,...j.conventions??{}},ci:{...UW.ci,...j.ci??{}}}}async function s1($,W){let{fs:j,logger:A}=$,Q=[],Z=W.config?HX(W.config):await m(j),X=await $$({fs:j},{config:Z}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),B=new Set(X.map((H)=>$4(H.filePath)).filter((H)=>Boolean(H))),q=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of q){if(!BX(H,Y,Z))continue;try{let V=await j.readFile(H);if(qX(V))continue;let G=$4(H);if(!(G!==null&&XX.test(G)&&B.has(G))&&!jX.test(V))continue;if(WX.test(V))continue;Q.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:H})}catch(V){A.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Q}import{validateSpecStructure as VX}from"@contractspec/module.workspace";async function e1($){let W=[];for(let j of $){let A=VX(j);for(let Q of A.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Q,category:"structure",file:j.filePath});for(let Q of A.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Q,category:"structure",file:j.filePath})}return W}async function $j($){let W=[],j=new Map,A=new Map;for(let Q of $){if(!Q.key||!Q.version)continue;if(Q.specType==="test-spec"){let Z=`${Q.key}.v${Q.version}`;j.set(Z,{key:Q.key,version:Q.version,file:Q.filePath,type:"test-spec"})}if(Q.testRefs&&Q.testRefs.length>0){if(!A.has(Q.filePath))A.set(Q.filePath,[]);A.get(Q.filePath)?.push({key:Q.key,version:Q.version,testRefs:Q.testRefs})}}for(let[Q,Z]of A)for(let X of Z){if(!X.testRefs)continue;let Y=i1(Q,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let B of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:B,category:"test-refs",file:Q,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}i();async function Wj($,W){let{fs:j}=$,A=[],Q=await m(j);for(let Z of W){if(Z.specType!=="operation")continue;let X=await KW(Z,{fs:j},Q,{checkTests:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:Z.filePath})}return A}function l($,W,j){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},Q=W.filter((Y)=>Y.severity==="error").length,Z=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:A[$],errors:Q,warnings:Z,notes:X,passed:Q===0,durationMs:j}}async function W4($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),A=j.match(/^ref: (.+)$/m);if(A){let Z=A[1]?.replace("refs/heads/",""),X=`.git/${A[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:Z};return{branch:Z}}return{commitSha:j.trim()}}catch{return{}}}function j4($){let W=$.config?.ci?.checks,j=W&&W.length>0?[...W]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)j.push("handlers");if($.checkTests)j.push("tests");if($.implementation)j.push("implementation");if($.checkDrift)j.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return j.filter((A)=>!$.skip?.includes(A));return j}async function q_($,W={}){let j=Date.now(),{fs:A,logger:Q}=$,Z=[],X=[],Y=j4(W);Q.info("Starting CI checks...",{checks:Y});let B=await m(A),q=await QW($,{config:B,pattern:W.pattern});if(Y.includes("structure")){let L=Date.now(),z=await e1(q);Z.push(...z),X.push(l("structure",z,Date.now()-L))}if(Y.includes("integrity")){let L=Date.now(),z=await t1($,W);Z.push(...z),X.push(l("integrity",z,Date.now()-L))}if(Y.includes("deps")){let L=Date.now(),z=await C1($,W);Z.push(...z),X.push(l("deps",z,Date.now()-L))}if(Y.includes("doctor")){let L=Date.now(),z=await u1($,W);Z.push(...z),X.push(l("doctor",z,Date.now()-L))}if(Y.includes("docs")){let L=Date.now(),z=await D1($,W);Z.push(...z),X.push(l("docs",z,Date.now()-L))}if(Y.includes("policy")){let L=Date.now(),z=await s1($,W);Z.push(...z),X.push(l("policy",z,Date.now()-L))}if(Y.includes("handlers")||W.checkHandlers){let L=Date.now(),z=await l1($,q);Z.push(...z),X.push(l("handlers",z,Date.now()-L))}if(Y.includes("tests")||W.checkTests){let L=Date.now(),z=await Wj($,q);Z.push(...z),X.push(l("tests",z,Date.now()-L))}if(Y.includes("test-refs")){let L=Date.now(),z=await $j(q);Z.push(...z),X.push(l("test-refs",z,Date.now()-L))}if(Y.includes("coverage")){let L=Date.now(),z=await R1($,q,W);Z.push(...z),X.push(l("coverage",z,Date.now()-L))}if(Y.includes("implementation")){let L=Date.now(),z=await o1($,q,W);Z.push(...z),X.push(l("implementation",z,Date.now()-L))}if(Y.includes("layers")){let L=Date.now(),z=await a1($,W);Z.push(...z),X.push(l("layers",z,Date.now()-L))}if(Y.includes("drift")){let L=Date.now(),z=await r1($,W);Z.push(...z),X.push(l("drift",z,Date.now()-L))}let H=Z.filter((L)=>L.severity==="error").length,V=Z.filter((L)=>L.severity==="warning").length,G=Z.filter((L)=>L.severity==="note").length,J=W.failOnWarnings?H===0&&V===0:H===0,b=await W4(A),w={success:J,totalErrors:H,totalWarnings:V,totalNotes:G,issues:Z,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...b};return Q.info("CI checks complete",{success:J,errors:H,warnings:V,durationMs:w.durationMs}),w}var V_=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],G_={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function __($,W={}){let{fs:j,logger:A}=$,Q=(W.outputDir??"./src").replace(/\\/g,"/"),Z=["generated/**","dist/**",".turbo/**"],X=[`${Q}/handlers/**/*.handler.ts`,`${Q}/handlers/**/*.handler.test.ts`,`${Q}/components/**/*.tsx`,`${Q}/components/**/*.test.tsx`,`${Q}/forms/**/*.form.tsx`,`${Q}/forms/**/*.form.test.tsx`,`${Q}/**/*.runner.ts`,`${Q}/**/*.renderer.tsx`],Y=W.generatedOnly?[...Z,...X]:[...Z,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],B=await j.glob({patterns:Y,ignore:["node_modules/**"]}),q=[],H=[];for(let V of B)try{let G=await j.stat(V),J=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&J<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)A.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),A.info("clean.removed",{path:V,size:G.size});q.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:q,skipped:H}}i();var C4={};h(C4,{writeReviewPacket:()=>_j,writeDecisionEnvelope:()=>z0,withBranch:()=>x$,verifyConnectMutation:()=>K2,resolveWorkspace:()=>d,resolveStoragePaths:()=>A$,replayConnectDecision:()=>tX,persistLatestArtifacts:()=>wj,persistDecisionArtifacts:()=>_0,normalizeEvalInput:()=>uX,matchConfiguredPath:()=>G0,loadStoredDecision:()=>U0,listStoredReviewPackets:()=>zj,listConnectReviewPackets:()=>aX,isReviewCommand:()=>jj,isDeniedCommand:()=>Aj,isAllowedCommand:()=>OW,initConnectWorkspace:()=>lX,inferSurfaces:()=>w0,evaluateConnectDecision:()=>gX,ensureStorage:()=>K0,defaultActor:()=>b0,decisionArtifactRefs:()=>r$,createConnectControlPlaneRuntime:()=>Y2,connectVerdictToPolicy:()=>n$,configuredThreshold:()=>D$,compileConnectPlanPacket:()=>Uj,buildConnectContextPack:()=>bj,assessConnectPolicy:()=>J0,assertConnectEnabled:()=>a,artifactRef:()=>V$,appendAuditRecord:()=>Kj,analyzeConnectImpact:()=>y$,CONTROL_PLANE_TRACE_GET_REF:()=>SW,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>IW,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Yj,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Xj,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Zj,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>T$,AGENT_APPROVALS_REF:()=>MW,ACP_TERMINAL_EXEC_REF:()=>wX,ACP_FS_ACCESS_REF:()=>bX});import GX from"micromatch";function a($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function G0($,W,j){if(!j||j.length===0)return!1;let A=W.replaceAll("\\","/");return GX.isMatch(A,j,{contains:!0})}function D$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function OW($,W){return Qj($.config.connect?.commands?.allow,W)}function jj($,W){return Qj($.config.connect?.commands?.review,W)}function Aj($,W){return Qj($.config.connect?.commands?.deny,W)}function Qj($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function Q4($,W){if(W.length===0)return{state:"none"};for(let A of W)if(Aj($,A))return{commandMatch:A,state:"deny"};for(let A of W)if(jj($,A))return{commandMatch:A,state:"review"};if(W.every((A)=>OW($,A)))return{state:"allow"};let j=W.find(JX);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((A)=>!OW($,A)),state:"unknown"}}function JX($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return A4(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return A4(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function A4($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var Zj={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Xj={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Yj={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},SW={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},IW={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},T$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},bX={key:"acp.fs.access",version:"1.0.0",kind:"command"},wX={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},MW={key:"agent.approvals",version:"1.0.0",kind:"command"};function J0($,W){let j=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.immutablePaths)),A=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.protectedPaths)),Q=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:Z,state:X}=Q4($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,B=W.impactAnalysis.driftFiles.length>0,q=KX({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:B,generatedPath:Boolean(Q),immutable:Boolean(j),protectedPath:Boolean(A),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=_X({breakingChange:W.impactAnalysis.breakingChange,commandMatch:Z,commandState:X,contractDrift:B,protectedPath:A,unknownPaths:W.impactAnalysis.unknownPaths}),V=n$(q);return{commandMatch:Z,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Q,immutablePath:j,protectedPath:A,requiredApprovals:V.requiresApproval?[{capability:T$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:q}}function n$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function KX($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(D$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(D$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(D$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(D$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(D$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(zX)[0]??"permit"}function _X($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function zX($,W){return Z4($)-Z4(W)}function Z4($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as kX}from"crypto";var H4={};h(H4,{formatPrComment:()=>X4,formatMinimalComment:()=>Bj,formatJson:()=>B4,formatCheckRun:()=>Y4,detectImpact:()=>F$,ImpactDetectionOverviewDocBlock:()=>MX});function X4($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)j.push("⚠️ **Contract changed (non-breaking)**");else j.push("✅ **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| ➖ Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let A=$.deltas.filter((Z)=>Z.severity==="breaking"),Q=$.deltas.filter((Z)=>Z.severity==="non_breaking");if(A.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let Z of A)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}if(Q.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let Z of Q)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let A of $.addedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let A of $.removedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### ⚠️ Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let A of W.drift.files)j.push(`- \`${A}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### ✅ No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
|
|
1611
|
-
|
|
1891
|
+
- This workspace was initialized with the \`${m}\` setup preset.
|
|
1892
|
+
`}function hw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1893
|
+
|
|
1894
|
+
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1895
|
+
|
|
1896
|
+
This workspace uses ContractSpec to keep contracts, generated artifacts, and AI guidance aligned.
|
|
1897
|
+
|
|
1898
|
+
## Start Here
|
|
1899
|
+
|
|
1900
|
+
1. Run \`contractspec onboard\` to generate a track-aware onboarding guide for this repo.
|
|
1901
|
+
2. Run \`contractspec validate\` after changing contracts or generated outputs.
|
|
1902
|
+
3. Run \`contractspec doctor\` if local setup or tooling looks unhealthy.
|
|
1903
|
+
|
|
1904
|
+
## Recommended Commands
|
|
1905
|
+
|
|
1906
|
+
- \`contractspec onboard\` - generate repo-local onboarding guidance and next steps
|
|
1907
|
+
- \`contractspec create\` - scaffold a new contract or package target
|
|
1908
|
+
- \`contractspec generate\` - refresh derived docs and artifacts
|
|
1909
|
+
- \`contractspec validate\` - validate contracts, package scaffolds, and integrity
|
|
1910
|
+
- \`contractspec connect adoption resolve --family <family> --stdin\` - reuse existing ContractSpec or workspace surfaces before building new ones
|
|
1911
|
+
|
|
1912
|
+
## Builder / Connect
|
|
1913
|
+
|
|
1914
|
+
- Use \`contractspec init --preset connect\` when you want local Connect artifacts and reuse guidance in the repo.
|
|
1915
|
+
- Use \`contractspec init --preset builder-managed\`, \`builder-local\`, or \`builder-hybrid\` when you want Builder control-plane defaults.
|
|
1916
|
+
|
|
1917
|
+
## Notes
|
|
1918
|
+
|
|
1919
|
+
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1920
|
+
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1921
|
+
`}function V9($){if(U$($)!=="connect")return;return{...FA.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:{...FA.connect?.adoption,enabled:!0},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:FA.connect?.studio}}function J9($){let b=Om(U$($)),A=vw(U$($));if(!b||!A)return;let m=!0,n=b==="local"||b==="hybrid";return{...FA.builder,enabled:!0,runtimeMode:b,bootstrapPreset:A,api:m?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:n?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function gA(){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){let A={...$};for(let m of Object.keys(b)){let n=$[m],W=b[m];if(n===void 0)A[m]=W;else if(kA(n)&&kA(W))A[m]=$$(n,W)}return A}function Vm($,b){let A={...$};for(let m of Object.keys(b)){let n=$[m],W=b[m];if(W===void 0)continue;if(kA(n)&&kA(W))A[m]=Vm(n,W);else A[m]=W}return A}function kA($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function p($){try{return JSON.parse($)}catch{return null}}function N($){return JSON.stringify($,null,2)+`
|
|
1922
|
+
`}async function Jm($,b){let A=[];return A.push(await K9($,b)),A.push(await _9($,b)),A.push(await U9($,b)),A.push(await z9($,b)),A.push(await L9($,b)),A.push(await R9($,b)),A.push(await C9($,b)),A}async function k$($,b){if(b.packageRoot&&b.packageRoot!==b.workspaceRoot&&await $.exists($.join(b.packageRoot,".contractsrc.json")))return b.packageRoot;return b.workspaceRoot}async function K9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(await $.exists(A))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let n=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,N(n)),{success:!0,message:"Created .contractsrc.json"}}catch(n){return{success:!1,message:`Failed to create: ${n instanceof Error?n.message:String(n)}`}}}}}}async function _9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A);return JSON.parse(n),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(n){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:n instanceof Error?n.message:String(n),fix:{description:"Replace with valid default config",apply:async()=>{try{let w=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(A,N(w)),{success:!0,message:"Replaced with valid config"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}}async function U9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n),w=[];if(!W.outputDir)w.push("outputDir");if(!W.conventions)w.push("conventions");if(w.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${w.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let j=bb({workspaceRoot:b.workspaceRoot,interactive:!1,targets:[]});for(let y of w)if(j[y]!==void 0)W[y]=j[y];return await $.writeFile(A,N(W)),{success:!0,message:"Added missing fields"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function z9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:W.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return W.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(A,N(W)),{success:!0,message:"Added versioning configuration"}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function L9($,b){let A=$.join(await k$($,b),".contractsrc.json");if(!await $.exists(A))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.hooks){let y=W.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(y).length} git hook(s) configured`}}let w=$.join(b.workspaceRoot,".husky");if(await $.exists(w))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return W.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(A,N(W)),{success:!0,message:"Added hooks configuration"}}catch(y){return{success:!1,message:`Failed: ${y instanceof Error?y.message:String(y)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function R9($,b){let A=await k$($,b),m=await g($,A),n=zb(m);if(n==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(n==="connect"){let j=[m.connect?.storage?.root?null:"storage.root",m.connect?.storage?.contextPack?null:"storage.contextPack",m.connect?.storage?.planPacket?null:"storage.planPacket",m.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((S)=>S!==null),y=m.connect?.studio?.enabled&&m.connect?.studio?.mode==="review-bridge"&&!m.connect?.studio?.endpoint;if(j.length===0&&!y)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...j,...y?["connect.studio.endpoint"]:[]].join(", ")}`}}let W=[],w=m.builder?.api?.controlPlaneTokenEnvVar;if(n.startsWith("builder-")&&!m.builder?.api?.baseUrl)W.push("builder.api.baseUrl");if(n.startsWith("builder-")&&!w)W.push("builder.api.controlPlaneTokenEnvVar");if(n.startsWith("builder-")&&w&&!process.env[w])W.push(`env:${w}`);if((n==="builder-local"||n==="builder-hybrid")&&!m.builder?.localRuntime?.runtimeId)W.push("builder.localRuntime.runtimeId");if((n==="builder-local"||n==="builder-hybrid")&&!m.builder?.localRuntime?.grantedTo)W.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:W.length===0?"pass":"warn",message:W.length===0?`Builder preset inferred (${n}) and required config is present`:`Builder preset inferred (${n}) but setup is missing ${W.join(", ")}`}}async function C9($,b){let A=await k$($,b),m=await g($,A),n=zb(m);if(!n.startsWith("builder-"))return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder preset is not enabled"};let W=$.join(A,".vscode","settings.json"),w=m.builder?.api?.baseUrl;if(!w)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let j=await $.readFile(W).catch(()=>""),y=j?p(j):void 0;if(y?.["contractspec.api.baseUrl"]===w)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let S=$.join(A,".vscode");if(!await $.exists(S))await $.mkdir(S);let Q={...y??{},...vA({workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot,isMonorepo:b.isMonorepo,packageName:b.packageName,interactive:!1,preset:n,targets:[],builderApiBaseUrl:w})};return await $.writeFile(W,N(Q)),{success:!0,message:"Updated VS Code settings mirror"}}catch(S){return{success:!1,message:S instanceof Error?S.message:String(S)}}}}}}import{exec as I9}from"node:child_process";import{promisify as E9}from"node:util";var P$=E9(I9);async function Km($,b){let A=[];return A.push(await M9(b)),A.push(await x9(b)),A.push(await T9($,b)),A.push(await D9($,b)),A.push(await N9($,b)),A}async function M9($){try{let{stdout:b}=await P$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${b.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function x9($){try{let{stdout:b}=await P$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${b.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function T9($,b){let A=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],m=null;for(let{file:n,name:W}of A){let w=$.join(b.workspaceRoot,n);if(await $.exists(w)){m=W;break}}if(!m){let n=$.join(b.workspaceRoot,".."),W=$.join(b.workspaceRoot,"../.."),w=[n,W];for(let j of w){for(let{file:y,name:B}of A){let S=$.join(j,y);if(await $.exists(S)){m=B;break}}if(m)break}}if(!m)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await P$(`${m} --version`,{cwd:b.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${m}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${m} detected but not available`,details:`Install ${m} or use a different package manager`}}}async function D9($,b){let A=$.join(b.workspaceRoot,"node_modules");if(await $.exists(A))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await P$("bun install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await P$("npm install",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(n){return{success:!1,message:`Failed: ${n instanceof Error?n.message:String(n)}`}}}}}}async function N9($,b){let A=$.join(b.workspaceRoot,"package.json");try{let m=await $.readFile(A),n=JSON.parse(m),W={...n.dependencies,...n.devDependencies};if("@contractspec/lib.contracts-spec"in W)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${W["@contractspec/lib.contracts-spec"]})`};if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await P$("bun add @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await P$("npm install @contractspec/lib.contracts-spec zod",{cwd:b.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function _m($,b){let A=await DA($,b.workspaceRoot);if(A.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return A.map((m)=>({category:"docs",name:`Same-File DocBlocks (${m.packageName})`,status:m.severity==="warning"?"warn":"fail",message:m.message,details:$.relative(b.workspaceRoot,m.file),context:{ruleId:m.ruleId,file:m.file,line:m.line,column:m.column,packageName:m.packageName}}))}import{isExampleFile as F9,isFeatureFile as v9,scanAllSpecsFromSource as g9,scanExampleSource as k9,scanFeatureSource as P9}from"@contractspec/module.workspace";function r9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function PA($,b={}){let{fs:A,logger:m}=$,n=r9(),W=b.pattern??"**/*.{ts,tsx}";m.info("Scanning for contract layer files...");let w=await A.glob({pattern:W});for(let y of w){if(y.includes("node_modules")||y.includes("/dist/"))continue;try{let B=await A.readFile(y);if(v9(y)){let S=P9(B,y);n.features.set(S.key,S);continue}if(F9(y)){let S=k9(B,y);n.examples.set(S.key,S);continue}if(y.includes(".app-config.")||y.includes(".blueprint.")){let S=g9(B,y);for(let Q of S)if(Q.specType==="app-config"&&Q.key)n.appConfigs.set(Q.key,Q)}}catch{}}try{let y=await A.glob({pattern:"**/.contractsrc.json"});for(let B of y){if(B.includes("node_modules"))continue;try{let S=await A.readFile(B),Q=JSON.parse(S);n.workspaceConfigs.set(B,{file:B,config:Q,valid:!0,errors:[]})}catch(S){n.workspaceConfigs.set(B,{file:B,config:{},valid:!1,errors:[S instanceof Error?S.message:"Parse error"]})}}}catch{}let j={features:n.features.size,examples:n.examples.size,appConfigs:n.appConfigs.size,workspaceConfigs:n.workspaceConfigs.size,total:n.features.size+n.examples.size+n.appConfigs.size+n.workspaceConfigs.size};return m.info(`Discovered ${j.features} features, ${j.examples} examples, ${j.appConfigs} app configs, ${j.workspaceConfigs} workspace configs`),{inventory:n,stats:j}}function AO($){let b=[];for(let[A,m]of $.features)b.push({key:A,file:m.filePath,type:"feature"});for(let[A,m]of $.examples)b.push({key:A,version:m.version,file:m.filePath,type:"example"});for(let[A,m]of $.appConfigs)b.push({key:A,version:m.version,file:m.filePath,type:"app-config"});for(let[,A]of $.workspaceConfigs)b.push({key:A.file,file:A.file,type:"workspace-config"});return b}function rA($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function Um($){if(!Array.isArray($))return[];return $.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean)}async function fA($,b){let A=$.join(b,"config/stability-policy.json");if(!await $.exists(A))return;try{let m=await $.readFile(A),n=JSON.parse(m);return{version:typeof n.version==="number"&&Number.isFinite(n.version)?n.version:1,criticalPackages:Um(n.criticalPackages).map(rA),criticalFeatureKeys:Um(n.criticalFeatureKeys),smokePackages:Um(n.smokePackages)}}catch{return}}function cw($,b){let A=rA($);if(b?.criticalPackages.includes(A))return"critical";return"non-critical"}function dw($,b){return Boolean($&&b?.criticalFeatureKeys.includes($))}function Ab($){return rA(`${rA($)}/config/stability-policy.json`)}async function zm($,b){let A=[],m=await fA($,b.workspaceRoot),n=await PA({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return A.push(f9(n.stats.features)),A.push(h9(n.stats.examples)),A.push(c9(n.inventory.features,m,b)),A.push(d9(n.inventory.examples)),A.push(u9(n.inventory.workspaceConfigs)),A}function f9($){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 h9($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function c9($,b,A){let m=[],n=[];for(let[W,w]of $)if(!(Boolean(w.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(w.sourceBlock??"")))if(dw(W,b))n.push(W);else m.push(W);if(n.length===0&&m.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:b?Ab(A.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:n.length>0?"fail":"warn",message:n.length>0?`${n.length} critical feature(s) missing owners`:`${m.length} feature(s) missing owners`,details:n.length>0?`Critical features: ${n.join(", ")}`:`Features: ${m.slice(0,3).join(", ")}${m.length>3?"...":""}`,context:{policyPath:b?Ab(A.workspaceRoot):void 0,criticalMissingFeatures:n,missingFeatures:m}}}function d9($){let b=[];for(let[A,m]of $)if(!m.entrypoints.packageName)b.push(A);if(b.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${b.length} example(s) missing packageName`,details:`Examples: ${b.join(", ")}`}}function u9($){let b=[];for(let[,A]of $)if(!A.valid)b.push(A.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(b.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${b.length} workspace config(s) invalid`,details:`Files: ${b.join(", ")}`}}async function Lm($,b){let A=[];return A.push(await o9($,b)),A.push(await i9($,b)),A.push(await l9($,b)),A}async function o9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(await $.exists(A))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let n=$.join(b.workspaceRoot,".cursor");if(!await $.exists(n))await $.mkdir(n);let W=Lb();return await $.writeFile(A,N(W)),{success:!0,message:"Created .cursor/mcp.json"}}catch(n){return{success:!1,message:`Failed: ${n instanceof Error?n.message:String(n)}`}}}}}}async function i9($,b){let A=$.join(b.workspaceRoot,".cursor","mcp.json");if(!await $.exists(A))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let n=await $.readFile(A),W=JSON.parse(n);if(W.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let j=Lb(),y=$$(W,j);return await $.writeFile(A,N(y)),{success:!0,message:"Registered MCP server"}}catch(j){return{success:!1,message:`Failed: ${j instanceof Error?j.message:String(j)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function l9($,b){let A=gA();try{if(!await $.exists(A))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let n=await $.readFile(A);if(JSON.parse(n).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var t9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],uw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function p9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,m])=>{if(typeof m==="string")b[A]=m;return b},{})}function a9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function e9($,b,A){let m=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:uw}),n=[];for(let W of m){let w=$.dirname(W),j=$.relative(b,w);try{let y=JSON.parse(await $.readFile(W)),B=p9(y.scripts),S=await $.glob({patterns:t9,cwd:w,ignore:uw});n.push({packageName:y.name??j,packagePath:j.replace(/\\/g,"/"),hasBuildScript:typeof B.build==="string",hasTypecheckScript:typeof B.typecheck==="string",hasLintScript:typeof B.lint==="string"||typeof B["lint:check"]==="string",hasTestScript:typeof B.test==="string",usesPassWithNoTests:a9(B),testFileCount:S.length,tier:cw(j,A)})}catch{continue}}return n}function s9($){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 $S($){let b=[];if($.testFileCount>0&&!$.hasTestScript)b.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)b.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return b}async function ow($,b,A){let m=await e9($,b,A),n=[];for(let w of m){if(w.tier==="critical")n.push(...s9(w));n.push(...$S(w))}let W=m.filter((w)=>w.tier==="critical").map((w)=>({packageName:w.packageName,packagePath:w.packagePath,hasBuildScript:w.hasBuildScript,hasTypecheckScript:w.hasTypecheckScript,hasLintScript:w.hasLintScript,hasTestScript:w.hasTestScript,usesPassWithNoTests:w.usesPassWithNoTests,testFileCount:w.testFileCount}));return{findings:n,criticalPackages:W}}function lw($){return $.slice(0,5).map((b)=>`${b.packagePath}: ${b.message}`).join("; ")}function iw($,b,A,m){if(b.length===0)return{category:"workspace",name:$,status:"pass",message:m,context:{findings:[]}};let n=b.filter((W)=>{return W.tier==="critical"||A.has(W.code)});return{category:"workspace",name:$,status:n.length>0?"fail":"warn",message:`${b.length} package issue(s) found`,details:lw(b),context:{findings:b}}}async function tw($,b){let A=await fA($,b.workspaceRoot);if(!A)return[];let m=await ow($,b.workspaceRoot,A),n=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),W=m.findings.filter((y)=>n.has(y.code)),w=m.findings.filter((y)=>y.code==="tests-without-test-script"),j=m.findings.filter((y)=>y.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:W.length>0?"fail":"pass",message:W.length>0?`${W.length} critical package gate failure(s)`:`All ${m.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:W.length>0?lw(W):b.verbose?`Policy: ${Ab(b.workspaceRoot)}`:void 0,context:{policyPath:Ab(b.workspaceRoot),criticalPackages:m.criticalPackages,findings:W}},iw("Package Test Scripts",w,new Set,"All tested packages expose a test script"),iw("Buildable Packages Without Tests",j,new Set,"All buildable packages have tests or explicit test scripts")]}var bS=["src/contracts","contracts","src/specs","specs"];async function Rm($,b){let A=[];return A.push(AS(b)),A.push(await mS($,b)),A.push(await nS($,b)),A.push(await WS($,b)),A.push(await jS($,b)),A.push(...await tw($,b)),A}function AS($){if($.isMonorepo){let b=$.packageName?` in package "${$.packageName}"`:"",A=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${b}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${A}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function mS($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot];for(let m of A){let n=$.join(m,"package.json");if(await $.exists(n))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:b.verbose&&b.isMonorepo?`Found at: ${m}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function nS($,b){let A=b.isMonorepo?[b.packageRoot,b.workspaceRoot]:[b.workspaceRoot],m=b.isMonorepo?b.packageRoot:b.workspaceRoot;for(let w of A)for(let j of bS){let y=$.join(w,j);if(await $.exists(y)){let B=w===b.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${j}`,details:b.isMonorepo?`Found at ${B} level`:void 0}}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let n=b.isMonorepo?"src/contracts":"src/contracts",W=b.isMonorepo?` in package "${b.packageName??b.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${n}/${W} to organize your specs`,fix:{description:`Create ${n}/ directory${W}`,apply:async()=>{try{let w=$.join(m,"src","contracts");return await $.mkdir(w),{success:!0,message:`Created ${n}/`}}catch(w){return{success:!1,message:`Failed: ${w instanceof Error?w.message:String(w)}`}}}}}}async function WS($,b){try{let A=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],m=b.isMonorepo?b.packageRoot:b.workspaceRoot,n=await $.glob({patterns:A,ignore:["node_modules/**","dist/**"],cwd:m});if(n.length>0){let w=b.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${n.length} contract file(s)${w}`,details:b.verbose?n.slice(0,5).join(", "):void 0}}if(b.isMonorepo&&b.packageRoot===b.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:b.isMonorepo?`No contract files found in package "${b.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function wS($,b){if(b.isMonorepo&&b.packageRoot!==b.workspaceRoot){let m=$.join(b.packageRoot,".contractsrc.json");if(await $.exists(m))return{path:m,root:b.packageRoot,level:"package"}}let A=$.join(b.workspaceRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:b.workspaceRoot,level:"workspace"};return null}async function jS($,b){try{let A=await wS($,b);if(!A)return{category:"workspace",name:"Output Directory",status:"skip",message:b.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let m=await $.readFile(A.path),n=JSON.parse(m),W=n.outputDir??"./src",w=$.join(A.root,W),j=b.isMonorepo?` (${A.level} level)`:"";if(await $.exists(w))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${W}${j}`,details:b.verbose?`Resolved to: ${w}`:void 0};let B=W==="./src"||W==="src",S=Array.isArray(n.packages)&&n.packages.length>0;if(b.isMonorepo&&b.packageRoot===b.workspaceRoot&&B&&(S||A.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:b.verbose?`Resolved default output to packages via ${A.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${W}${j}`,details:b.verbose?`Expected at: ${w}`:void 0,fix:{description:`Create ${W} directory`,apply:async()=>{try{return await $.mkdir(w),{success:!0,message:`Created ${W}`}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var pw=["cli","config","mcp","deps","docs","workspace","ai","layers"],aw={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var yS={checks:{runCliChecks:qm,runConfigChecks:Jm,runMcpChecks:Lm,runDepsChecks:Km,runDocChecks:_m,runWorkspaceChecks:Rm,runAiChecks:Hm,runLayerChecks:zm},workspace:{findWorkspaceRoot:M,findPackageRoot:r,isMonorepo:Gb,getPackageName:T$}},BS={confirm:async()=>!1,input:async()=>""};async function ew($,b,A=BS,m=yS){let{fs:n,logger:W}=$,w=b.categories??pw,{checks:j,workspace:y}=m,B=y.findWorkspaceRoot(b.workspaceRoot),S=y.findPackageRoot(b.workspaceRoot),Q=y.isMonorepo(B),Z=Q?y.getPackageName(S):void 0,G={workspaceRoot:B,packageRoot:S,isMonorepo:Q,packageName:Z,verbose:b.verbose??!1};if(Q){let J=Z?` (package: ${Z})`:"";W.info(`Detected monorepo${J}`)}let X=[];for(let J of w){if(b.skipAi&&J==="ai")continue;W.info(`Checking ${aw[J]}...`);let _=await SS(J,n,G,A,j);for(let H of _){if(H.fix&&(H.status==="fail"||H.status==="warn")){if(b.autoFix?!0:await A.confirm(`Fix "${H.name}"? ${H.fix.description}`)){W.info(`Applying fix: ${H.fix.description}`);let U=await H.fix.apply();if(U.success)W.info(`✓ ${U.message}`),H.status="pass",H.message=`Fixed: ${U.message}`,H.fix=void 0;else W.warn(`✗ ${U.message}`)}}X.push(H)}}let Y=X.filter((J)=>J.status==="pass").length,V=X.filter((J)=>J.status==="warn").length,O=X.filter((J)=>J.status==="fail").length,K=X.filter((J)=>J.status==="skip").length;return{checks:X,passed:Y,warnings:V,failures:O,skipped:K,healthy:O===0}}async function SS($,b,A,m,n){switch($){case"cli":return n.runCliChecks(b,A);case"config":return n.runConfigChecks(b,A);case"mcp":return n.runMcpChecks(b,A);case"deps":return n.runDepsChecks(b,A);case"docs":return n.runDocChecks(b,A);case"workspace":return n.runWorkspaceChecks(b,A);case"ai":return n.runAiChecks(b,A,m);case"layers":return n.runLayerChecks(b,A);default:return[]}}function xO($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("✓ All checks passed!");else b.push("✗ Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1923
|
+
`)}function TO($){let A=`${$.status==="pass"?"✓":$.status==="warn"?"⚠":$.status==="fail"?"✗":"○"} ${$.name}: ${$.message}`;if($.details)A+=`
|
|
1924
|
+
${$.details}`;if($.fix)A+=`
|
|
1925
|
+
Fix available: ${$.fix.description}`;return A}async function Cm($,b){let A=[],m=b.workspaceRoot??process.cwd(),n=await ew($,{workspaceRoot:m,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let W of n.checks)if(W.status==="fail")A.push({ruleId:`doctor-${W.category}-${W.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${W.name}: ${W.message}`,category:"doctor",context:{details:W.details,...W.context??{}}});else if(W.status==="warn")A.push({ruleId:`doctor-${W.category}-${W.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${W.name}: ${W.message}`,category:"doctor",context:{details:W.details,...W.context??{}}});return A}s();import{mkdtemp as RS,rm as CS}from"node:fs/promises";import{tmpdir as IS}from"node:os";import Rb from"path";import{DEFAULT_CONTRACTSRC as OS}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as VS}from"@contractspec/module.workspace";import JS from"path";import{packageDocBlocks as QS}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as ZS,convertSpecToDocBlock as GS,extractModuleDocData as XS,loadSpecFromSource as YS,scanAllSpecsFromSource as HS,scanSpecSource as qS}from"@contractspec/module.workspace";import Em from"path";import{dirname as sw,sep as hA}from"path";class Im{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let b of $){let A;if(b.specType==="app-config")A="app-config";else if(b.specType==="example")A="example";else if(b.specType==="feature")A="feature";if(A&&b.key){let m=sw(b.filePath);this.modules.push({type:A,key:b.key,dirPath:m})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let b=sw($),A=this.modules.filter((m)=>{let n=m.dirPath.endsWith(hA)?m.dirPath:m.dirPath+hA;return(b.endsWith(hA)?b:b+hA).startsWith(n)||b===m.dirPath});if(A.length===0)return;return A.sort((m,n)=>{let W={"app-config":3,example:2,feature:1},w=W[m.type],j=W[n.type];if(w!==j)return j-w;return n.dirPath.length-m.dirPath.length}),A[0]}}async function bj($,b,A){let{fs:m,logger:n}=A,W=[];if(n.info(`Generating docs for ${$.length} files...`),b.outputDir)await m.mkdir(b.outputDir);let w=new Im(A),j=[];for(let B of $)try{let S=await m.readFile(B),Q=HS(S,B);if(Q.length>0)j.push(...Q);else{let Z=qS(S,B);if(Z.specType!=="unknown")j.push(Z)}}catch(S){}w.initialize(j);let y=await Aj($,A);for(let B of y)if(W.push(B.entry.block),n.debug(`Loaded authored doc ${B.entry.id}`),b.outputDir)await $j(B.entry.block,B.filePath,b.outputDir,w,m);for(let B of $)try{let S=await YS(B);if(!S?.length){n.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=GS(Q,{rootPath:b.rootPath});if(W.push(Z),n.debug(`Generated doc for ${Z.id}`),!b.outputDir)continue;await $j(Z,B,b.outputDir,w,m)}}catch(S){n.error(`Error processing ${B}: ${S instanceof Error?S.message:String(S)}`)}if(b.outputDir)n.info(`Wrote ${W.length} doc files to ${b.outputDir}`);return{blocks:W,count:W.length}}async function hO($,b){return(await Aj($,b)).map(({entry:m})=>m.block)}function cO($,b){return QS(ZS({packageName:$,srcRoot:b}))}async function Aj($,b){let A=[...new Set($)].sort((n,W)=>n.localeCompare(W)),m=[];for(let n of A){let W=await b.fs.readFile(n),w=n.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),j=XS(W,n,w);for(let y of j.entries)m.push({entry:y,filePath:n})}return m}async function $j($,b,A,m,n){let W=m.resolve(b),w=W?Em.join(A,W.key):Em.join(A,"_common");await n.mkdir(w);let j=Em.join(w,`${$.id}.md`),y=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1926
|
+
|
|
1927
|
+
${$.body}`;await n.writeFile(j,y)}async function mj($,b,A,m,n={}){let W=n.config,w=await xA($,{cwd:n.specSearchRoot,config:W,pattern:n.specPattern??_S(b,n)});if(w.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let j=JS.join(US(A,W),"docs"),y=await bj(w.map((S)=>S.filePath),{outputDir:j,format:"markdown",rootPath:m},$),B=0;for(let S of w){let Q=KS(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await $b(S.filePath,$,W??OS,{targets:wm(S.specType,{includeTests:Boolean(n.includeRuntimeTests)}),outputDir:W?.outputDir??"./src",overwrite:!1});B+=Z.results.filter((G)=>G.success).length}return{specsCount:w.length,docsCount:y.count,materializedCount:B}}function KS($){return VS($.specType)}function _S($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${Mm($)}/**/*.ts`:void 0}function US($,b){let A=(b?.connect?.policy?.generatedPaths??[]).map(LS).filter(Boolean);if(A.length>0)return A[0];if(b?.outputDir&&b.outputDir!=="./src")return Mm(b.outputDir);return $}function zS($){return Mm($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function LS($){let b=zS($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function Mm($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function cA($,b,A,m={}){let n=await RS(Rb.join(IS(),"contractspec-drift-"));try{await mj($,b,n,m.rootPath,m.generation);let W=[],w=await import("node:fs/promises");async function j(Z){let G=await w.readdir(Z,{withFileTypes:!0}),X=[];for(let Y of G){let V=Rb.resolve(Z,Y.name);if(Y.isDirectory())X.push(...await j(V));else X.push(V)}return X}let y=async(Z)=>{if(!await w.stat(Z).catch(()=>!1))return[];return(await j(Z)).map((X)=>Rb.relative(Z,X)).sort()},B=await y(n),S=await y(A),Q=new Set([...B,...S]);for(let Z of Q){if(!S.includes(Z)){W.push(Z);continue}if(!B.includes(Z)){W.push(Z);continue}let G=await w.readFile(Rb.join(n,Z)),X=await w.readFile(Rb.join(A,Z));if(!G.equals(X))W.push(Z)}return{hasDrift:W.length>0,files:W}}finally{await CS(n,{recursive:!0,force:!0})}}async function xm($,b){let{fs:A,logger:m}=$,n=[],W=await g(A);if(!W.outputDir)return m.info("No outputDir configured, skipping drift checks"),n;let w="./contracts",j=W.outputDir;if(!await A.exists(j))return m.info("Generated directory does not exist, skipping drift checks"),n;try{let y=await cA($,w,j);if(y.hasDrift)for(let B of y.files)n.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${B}`,category:"drift",file:`${j}/${B}`,context:{file:B}})}catch(y){m.warn("Drift detection failed",{error:y instanceof Error?y.message:String(y)})}return n}s();function ES($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function MS($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}async function dA($,b,A,m={}){let{fs:n}=b,W=[],w=[],j=$.key??n.basename($.filePath).replace(/\.[jt]s$/,""),y=m.outputDir??A.outputDir??"./src",B=ES(j),S={};if($.specType==="operation")S.handlerPath=n.join(y,"handlers",`${B}.handler.ts`),S.handlerTestPath=n.join(y,"handlers",`${B}.handler.test.ts`);if($.specType==="presentation")S.componentPath=n.join(y,"components",`${B}.tsx`),S.componentTestPath=n.join(y,"components",`${B}.test.tsx`);if($.specType==="form")S.formPath=n.join(y,"forms",`${B}.form.tsx`),S.formTestPath=n.join(y,"forms",`${B}.form.test.tsx`);if(m.checkHandlers&&S.handlerPath)if(!await n.exists(S.handlerPath))W.push(`Missing handler file: ${S.handlerPath}`);else{let Z=await n.readFile(S.handlerPath),G=`${MS(j.split(".").pop()??j)}Spec`,X=/ContractHandler<\s*typeof\s+\w+\s*>/.test(Z),Y=new RegExp(`typeof\\s+${G}\\b`).test(Z);if(!X)w.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${S.handlerPath}`);else if(!Y)w.push(`Handler ContractHandler typing does not reference expected spec var (${G}): ${S.handlerPath}`)}if(m.checkTests){let Q=[S.handlerTestPath,S.componentTestPath,S.formTestPath].filter((Z)=>typeof Z==="string");for(let Z of Q)if(!await n.exists(Z))W.push(`Missing test file: ${Z}`)}return{valid:W.length===0,errors:W,warnings:w,expected:S}}async function Tm($,b){let{fs:A}=$,m=[],n=await g(A);for(let W of b){if(W.specType!=="operation")continue;let w=await dA(W,{fs:A},n,{checkHandlers:!0,outputDir:n.outputDir});for(let j of w.errors)m.push({ruleId:"handler-missing",severity:"warning",message:j,category:"handlers",file:W.filePath});for(let j of w.warnings)m.push({ruleId:"handler-warning",severity:"warning",message:j,category:"handlers",file:W.filePath})}return m}s();import{createHash as vS}from"crypto";import gS from"path";var Cb={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},xS={".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 TS($){let b=$.toLowerCase();for(let[A,m]of Object.entries(xS))if(b.endsWith(A))return m;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 nj($,b){let A=[],m=new Set,n=(Z,G,X)=>{let Y=`${Z}:${G}`;if(m.has(Y))return;m.add(Y),A.push({filePath:b,specKey:Z,referenceType:G,lineNumber:X,inferredType:TS(b)})},W=(Z)=>{return $.substring(0,Z).split(`
|
|
1928
|
+
`).length},w,j=new RegExp(Cb.contractHandler);while((w=j.exec($))!==null)if(w[1])n(w[1],"handler",W(w.index));let y=new RegExp(Cb.typeofSpec);while((w=y.exec($))!==null)if(w[1])n(w[1],"typeof",W(w.index));let B=new RegExp(Cb.namedImport);while((w=B.exec($))!==null){let G=w[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(G)for(let X of G)n(X,"import",W(w.index))}let S=new RegExp(Cb.defaultImport);while((w=S.exec($))!==null)if(w[1])n(w[1],"import",W(w.index));let Q=new RegExp(Cb.specAssignment);while((w=Q.exec($))!==null)if(w[1])n(w[1],"unknown",W(w.index));return A}var Wj=["**/*.ts(x)"];async function uA($,b,A={}){let{fs:m}=b,n=A.includePatterns??Wj,W=A.excludePatterns??[...new Set([...x$,...X$])],w=[];for(let j of n){let y=await m.glob({pattern:j,ignore:W});for(let B of y)try{let S=await m.readFile(B),Z=nj(S,B).filter((G)=>G.specKey===$);w.push(...Z)}catch{}}return w}async function XV($,b={}){let{fs:A}=$,m=b.includePatterns??Wj,n=b.excludePatterns??[...new Set([...x$,...X$])],W=new Map;for(let w of m){let j=await A.glob({pattern:w,ignore:n});for(let y of j)try{let B=await A.readFile(y),S=nj(B,y);for(let Q of S){let Z=W.get(Q.specKey)??[];Z.push(Q),W.set(Q.specKey,Z)}}catch{}}return W}function DS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function wj($,b,A){let m=DS(b),n=[];if($==="operation")n.push({path:`${A}/handlers/${m}.handler.ts`,type:"handler"}),n.push({path:`${A}/handlers/${m}.handler.test.ts`,type:"test"});if($==="presentation")n.push({path:`${A}/components/${m}.tsx`,type:"component"}),n.push({path:`${A}/components/${m}.test.tsx`,type:"test"});if($==="form")n.push({path:`${A}/forms/${m}.form.tsx`,type:"form"}),n.push({path:`${A}/forms/${m}.form.test.tsx`,type:"test"});if($==="event")n.push({path:`${A}/handlers/${m}.handler.ts`,type:"handler"}),n.push({path:`${A}/handlers/${m}.handler.test.ts`,type:"test"});return n}import{Node as t,Project as NS,SyntaxKind as FS}from"ts-morph";function jj($){let b=[],m=new NS({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),n=(y)=>{if(!t.isObjectLiteralExpression(y))return;let B=y.getProperty("implementations");if(B&&t.isPropertyAssignment(B)){let S=B.getInitializer();if(S&&t.isArrayLiteralExpression(S)){for(let Q of S.getElements())if(t.isObjectLiteralExpression(Q)){let Z,G,X,Y=Q.getProperty("path");if(Y&&t.isPropertyAssignment(Y)){let K=Y.getInitializer();if(t.isStringLiteral(K))Z=K.getLiteralText()}let V=Q.getProperty("type");if(V&&t.isPropertyAssignment(V)){let K=V.getInitializer();if(t.isStringLiteral(K))G=K.getLiteralText()}let O=Q.getProperty("description");if(O&&t.isPropertyAssignment(O)){let K=O.getInitializer();if(t.isStringLiteral(K))X=K.getLiteralText()}if(Z&&G)b.push({path:Z,type:G,description:X})}}}},W=m.getDescendantsOfKind(FS.CallExpression);for(let y of W){let B=y.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(B)){let S=y.getArguments();if(S.length>0&&t.isObjectLiteralExpression(S[0]))return n(S[0]),b}}let w=m.getVariableStatements();for(let y of w)if(y.isExported())for(let B of y.getDeclarations()){let S=B.getInitializer();if(S&&t.isObjectLiteralExpression(S)){if(S.getProperty("implementations"))return n(S),b}}let j=m.getExportAssignment((y)=>!y.isExportEquals());if(j){let y=j.getExpression();if(t.isObjectLiteralExpression(y))n(y);else if(t.isAsExpression(y)&&t.isObjectLiteralExpression(y.getExpression()))n(y.getExpression())}return b}function yj($){if($.length===0)return"missing";let b=$.filter((n)=>n.exists),A=$.filter((n)=>n.type!=="test");if(b.filter((n)=>n.type!=="test").length===0)return"missing";if($.every((n)=>n.exists))return"implemented";return"partial"}function VV($){let b=$.filter((n)=>n.status==="implemented").length,A=$.filter((n)=>n.status==="partial").length,m=$.filter((n)=>n.status==="missing").length;return{total:$.length,implemented:b,partial:A,missing:m,coverage:$.length>0?Math.round(b/$.length*100):100}}var kS={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Bj($){return vS("sha256").update($).digest("hex")}async function PS($,b,A,m={},n){let W={...kS,...m},w=W.computeHashes?Bj($.sourceBlock||""):void 0,j=$.key??gS.basename($.filePath).replace(/\.[jt]s$/,""),y=$.version??"1.0.0",{fs:B}=b,S=[],Q=new Set,Z=async(X,Y,V,O)=>{if(Q.has(X))return;Q.add(X);let K=await B.exists(X),J=void 0,_=void 0;if(K&&W.computeHashes)try{J=await B.readFile(X),_=Bj(J)}catch{}S.push({path:X,type:Y,source:V,exists:K,implementationSourceContent:J,implementationSourceHash:_,description:O})};if(W.includeExplicit&&$.sourceBlock){if(n)n.suffixText="Discover explicit implementations";let X=jj($.sourceBlock);for(let Y of X)await Z(Y.path,Y.type,"explicit",Y.description)}if(W.includeDiscovered){if(n)n.suffixText="Discover implementations";let X=await uA(j,b,W);for(let Y of X){if(Y.filePath===$.filePath)continue;await Z(Y.filePath,Y.inferredType,"discovered")}}if(W.includeConvention){if(n)n.suffixText="Discover implementations based on conventions";let X=W.outputDir??A.outputDir??"./src",Y=wj($.specType,j,X);for(let{path:V,type:O}of Y)await Z(V,O,"convention")}if(n)n.suffixText="Determine implementation status";let G=yj(S);return{specKey:j,specVersion:y,specPath:$.filePath,specType:$.specType,implementations:S,status:G,specHash:w}}async function Sj($,b,A,m={},n){let W=[];for(let w of $){if(n)n.text=`Resolving implementation... (${W.length}/${$.length})`;try{let j=await PS(w,b,A,m,n);W.push(j)}catch(j){console.error(`Failed to resolve implementations for ${w}:`,j)}}return W}async function Dm($,b,A){let{fs:m}=$,n=[],W=await g(m),w=A.implementation??{},j=b.filter((B)=>B.specType==="operation"),y=await Sj(j,{fs:m},W,{computeHashes:w.useCache??!0});for(let B of y){if(w.requireImplemented&&B.status==="missing")n.push({ruleId:"impl-missing",severity:"error",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});else if(B.status==="missing")n.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${B.specKey} has no implementation`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status}});if(!w.allowPartial&&B.status==="partial"){let Q=B.implementations.filter((Z)=>!Z.exists&&Z.type!=="test").map((Z)=>Z.path);n.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${B.specKey} has partial implementation: missing ${Q.join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,specVersion:B.specVersion,status:B.status,missingFiles:Q}})}let S=B.implementations.filter((Q)=>!Q.exists&&Q.type==="test");if(S.length>0)n.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${B.specKey} missing test files: ${S.map((Q)=>Q.path).join(", ")}`,category:"implementation",file:B.specPath,context:{specKey:B.specKey,missingTests:S.map((Q)=>Q.path)}})}return n}s();import{isFeatureFile as hS,scanAllSpecsFromSource as cS,scanFeatureSource as dS}from"@contractspec/module.workspace";function rS($,b){return`${$}.v${b}`}function Nm($,b,A,m,n,W={}){let{treatMissingAsError:w=!0}=W;if(!m||m.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let j=[],y=[],B=[];for(let S of m){let Q=rS(S.key,S.version);if(n.has(Q))j.push(S);else if(y.push(S),w)B.push(`Spec ${b}.v${A} references test ${S.key}.v${S.version} which does not exist`)}return{valid:y.length===0,foundTests:j,missingTests:y,errors:B,specFile:$}}function Qj($,b){return`${$}.v${b}`}function Zj($,b){let A=new Map,m=new Map,n=[],W=[];for(let w of $){if(!w.key||!w.version)continue;let j=Qj(w.key,w.version);if(!w.testTarget){W.push(j);continue}let{type:y,key:B,version:S}=w.testTarget,Q=S??w.version,Z=Qj(B,Q),G=fS(b,y);if(!G||!G.has(Z)){n.push(j);continue}if(m.set(j,Z),!A.has(Z))A.set(Z,new Set);A.get(Z)?.add(j)}return{targetToTests:A,testToTarget:m,orphanedTests:n,testsWithoutTarget:W}}function fS($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function b$($,b){return`${$}.v${b}`}function uS(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function Fm($,b){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[b]}async function oA($,b={}){let{fs:A,logger:m}=$;m.info("Starting integrity analysis...",{options:b});let n=await g$(A,{config:b.config,cwd:b.cwd,pattern:b.pattern}),W=uS(),w=[],j=[];for(let H of n){if((await A.stat(H)).isDirectory)continue;let U=await A.readFile(H);if(hS(H)){let z=dS(U,H);w.push(z)}else{let z=cS(U,H);for(let L of z)if(L.specType!=="unknown"&&L.specType!=="feature"){let I=Fm(W,L.specType);if(I&&L.key&&L.version!==void 0){let C=b$(L.key,L.version);I.set(C,{key:L.key,version:L.version,file:L.filePath,type:L.specType,stability:L.stability,testTarget:L.testTarget,testCoverage:L.testCoverage})}}}}let y=b.featureKey?w.filter((H)=>H.key===b.featureKey):w,B=new Set;for(let H of y){for(let q of H.operations){let U=b$(q.key,q.version);if(B.add(`operation:${U}`),!W.operations.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Operation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q})}for(let q of H.events){let U=b$(q.key,q.version);if(B.add(`event:${U}`),!W.events.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Event ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"event",ref:q})}for(let q of H.presentations){let U=b$(q.key,q.version);if(B.add(`presentation:${U}`),!W.presentations.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q})}for(let q of H.experiments){let U=b$(q.key,q.version);if(B.add(`experiment:${U}`),!W.experiments.has(U))j.push({severity:"error",type:"unresolved-ref",message:`Experiment ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"experiment",ref:q})}for(let q of H.capabilities.provides){let U=b$(q.key,q.version);if(B.add(`capability:${U}`),!W.capabilities.has(U))j.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"capability",ref:q})}for(let q of H.capabilities.requires){let U=b$(q.key,q.version);B.add(`capability:${U}`)}for(let q of H.opToPresentationLinks){let U=b$(q.op.key,q.op.version),z=b$(q.pres.key,q.pres.version);if(!W.operations.has(U))j.push({severity:"error",type:"broken-link",message:`Linked operation ${q.op.key}.v${q.op.version} not found`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op});if(!W.presentations.has(z))j.push({severity:"error",type:"broken-link",message:`Linked presentation ${q.pres.key}.v${q.pres.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:q.pres})}if(H.presentationsTargets)for(let q of H.presentationsTargets){let U=b$(q.key,q.version);if(!W.presentations.has(U))j.push({severity:"error",type:"broken-link",message:`Targeted presentation ${q.key}.v${q.version} not found`,file:H.filePath,featureKey:H.key,specType:"presentation",ref:{key:q.key,version:q.version}})}}let S=[],Q=["operation","event","presentation","experiment"];for(let H of Q){let q=Fm(W,H);if(!q)continue;for(let[U,z]of q)if(!B.has(`${H}:${U}`))S.push(z),j.push({severity:"warning",type:"orphaned",message:`${H} ${z.key}.v${z.version} is not linked to any feature`,file:z.file,specKey:z.key,specType:z.type})}let Z=[];for(let[,H]of W.testSpecs)Z.push({filePath:H.file,specType:"test-spec",key:H.key,version:H.version,testTarget:H.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let G=Zj(Z,W);for(let H of y)for(let q of H.opToPresentationLinks){let U=b$(q.op.key,q.op.version),z=G.targetToTests.get(U),L=!1,I=!1;if(z)for(let C of z){let F=W.testSpecs.get(C);if(F?.testCoverage){if(F.testCoverage.hasSuccess)L=!0;if(F.testCoverage.hasError)I=!0}}if(!z||!L||!I){let C=[];if(!L)C.push("success scenario");if(!I)C.push("error scenario");j.push({severity:"error",type:"missing-test-coverage",message:`Operation ${q.op.key}.v${q.op.version} linked to presentation requires tests covering: ${C.join(", ")}`,file:H.filePath,featureKey:H.key,specType:"operation",ref:q.op})}}let X={},Y=0;for(let H of Q){let q=Fm(W,H);if(!q)continue;let U=q.size,z=0,L=0,I=b.requireTestsFor?.includes(H);for(let[C,F]of q){if(B.has(`${H}:${C}`))z++;if(I){let x=b$(F.key,F.version),h=G.targetToTests.has(x),nA=`${F.key}.test`,r1=W.testSpecs.has(b$(nA,F.version));if(!h&&!r1)L++,Y++,j.push({severity:"warning",type:"missing-test",message:`${H} ${F.key}.v${F.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:F.file,specKey:F.key,specType:F.type})}}X[H]={total:U,covered:z,orphaned:U-z,missingTest:I?L:0}}let V=Object.values(X).reduce((H,q)=>H+q.total,0),O=Object.values(X).reduce((H,q)=>H+q.covered,0),K={total:V,linkedToFeature:O,orphaned:V-O,missingTest:Y,byType:X},_=!j.some((H)=>H.severity==="error");return m.info("Integrity analysis complete",{features:w.length,totalSpecs:V,orphaned:S.length,issues:j.length,healthy:_}),{inventory:W,features:y,coverage:K,issues:j,orphanedSpecs:S,healthy:_}}function rV($){let b=[];for(let A of Object.values($))for(let m of A.values())b.push(m);return b}function fV($,b){return $.filter((A)=>A.type===b)}function hV($,b){return $.filter((A)=>A.severity===b)}async function vm($,b){let A=[],m=await g($.fs),n=await oA($,{config:m,pattern:b.pattern,all:!0});for(let W of n.issues)A.push({ruleId:`integrity-${W.type}`,severity:W.severity==="error"?"error":"warning",message:W.message,category:"integrity",file:W.file,context:{specKey:W.specKey,specType:W.specType,featureKey:W.featureKey,ref:W.ref}});return A}async function gm($,b){let A=[],m=await PA($,{});for(let[n,W]of m.inventory.features){if(!W.key)A.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:W.filePath,context:{key:n}});if(!W.owners?.length)A.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${n}' missing 'owners' field`,category:"layers",file:W.filePath,context:{key:n}});if(W.operations.length===0&&W.events.length===0&&W.presentations.length===0)A.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${n}' has no operations, events, or presentations`,category:"layers",file:W.filePath,context:{key:n}})}for(let[n,W]of m.inventory.examples){if(!W.entrypoints.packageName)A.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${n}' missing 'packageName' in entrypoints`,category:"layers",file:W.filePath,context:{key:n}});if(!W.surfaces.templates&&!W.surfaces.sandbox.enabled&&!W.surfaces.studio.enabled&&!W.surfaces.mcp.enabled)A.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${n}' has no enabled surfaces`,category:"layers",file:W.filePath,context:{key:n}})}for(let n of m.inventory.workspaceConfigs.values())if(!n.valid)for(let W of n.errors)A.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${W}`,category:"layers",file:n.file});return A}s();import{ContractsrcSchema as iS,DEFAULT_CONTRACTSRC as iA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as oS}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:A,scan:m=oS}=$,n=await g$(A,b),W=[],w=Array.isArray(b.type)?b.type:[b.type];for(let j of n){if(Ob(j,b.config))continue;if(Vb(j))continue;try{let y=await A.readFile(j),B=m(y,j);if(B.specType==="unknown")continue;if(b.type&&!w.includes(B.specType))continue;W.push(B)}catch{}}return W}function eV($){let b=new Map;for(let A of $){let m=b.get(A.specType)??[];m.push(A),b.set(A.specType,m)}return b}var lS=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,tS=/@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?)?['"]/,pS=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,aS=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,eS=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,sS=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,$Q=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function lA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function bQ($,b){let A=$.replaceAll("\\","/"),m=new Set(["contracts","features",...lA(b?.conventions?.operations),...lA(b?.conventions?.events),...lA(b?.conventions?.presentations),...lA(b?.conventions?.forms)]);return A.split("/").some((n)=>m.has(n))}function AQ($,b,A){let m=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(m))return!1;if(m.includes("/node_modules/")||m.includes("/dist/")||eS.test(m)||aS.test(m)||m.endsWith(".d.ts")||m.endsWith(".test.ts")||m.endsWith(".spec.ts"))return!1;if(b.has(m))return!1;if(bQ(m,A))return!1;return lS.test(m)}function Gj($){return $.replaceAll("\\","/").match(sS)?.[1]??null}function mQ($){let b=$.split(`
|
|
1929
|
+
`).map((A)=>A.trim()).filter((A)=>A.length>0&&!A.startsWith("//")&&!A.startsWith("/*")&&!A.startsWith("*")&&!A.startsWith("*/"));return b.length>0&&b.every((A)=>A.startsWith("import ")||A.startsWith("export *")||A.startsWith("export {")||A.startsWith("export type {")||A==="'use client';"||A==='"use client";'||A==="'use server';"||A==='"use server";')}function nQ($){if(!$)return iA;let b=iS.safeParse($),A=b.success?b.data:{};return{...iA,...A,conventions:{...iA.conventions,...A.conventions??{}},ci:{...iA.ci,...A.ci??{}}}}async function km($,b){let{fs:A,logger:m}=$,n=[],W=b.config?nQ(b.config):await g(A),w=await j$({fs:A},{config:W}),j=new Set(w.map((S)=>S.filePath.replaceAll("\\","/"))),y=new Set(w.map((S)=>Gj(S.filePath)).filter((S)=>Boolean(S))),B=await A.glob({pattern:"**/*.{ts,tsx}"});for(let S of B){if(!AQ(S,j,W))continue;try{let Q=await A.readFile(S);if(mQ(Q))continue;let Z=Gj(S);if(!(Z!==null&&$Q.test(Z)&&y.has(Z))&&!pS.test(Q))continue;if(tS.test(Q))continue;n.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:S})}catch(Q){m.warn("Policy scan failed for file",{file:S,error:Q instanceof Error?Q.message:String(Q)})}}return n}import{validateSpecStructure as WQ}from"@contractspec/module.workspace";async function Pm($){let b=[];for(let A of $){let m=WQ(A);for(let n of m.errors)b.push({ruleId:"spec-structure-error",severity:"error",message:n,category:"structure",file:A.filePath});for(let n of m.warnings)b.push({ruleId:"spec-structure-warning",severity:"warning",message:n,category:"structure",file:A.filePath})}return b}async function rm($){let b=[],A=new Map,m=new Map;for(let n of $){if(!n.key||!n.version)continue;if(n.specType==="test-spec"){let W=`${n.key}.v${n.version}`;A.set(W,{key:n.key,version:n.version,file:n.filePath,type:"test-spec"})}if(n.testRefs&&n.testRefs.length>0){if(!m.has(n.filePath))m.set(n.filePath,[]);m.get(n.filePath)?.push({key:n.key,version:n.version,testRefs:n.testRefs})}}for(let[n,W]of m)for(let w of W){if(!w.testRefs)continue;let j=Nm(n,w.key,w.version,w.testRefs,A,{treatMissingAsError:!0});for(let y of j.errors)b.push({ruleId:"test-ref-missing",severity:"error",message:y,category:"test-refs",file:n,context:{specKey:w.key,specVersion:w.version,missingTests:j.missingTests}})}return b}s();async function fm($,b){let{fs:A}=$,m=[],n=await g(A);for(let W of b){if(W.specType!=="operation")continue;let w=await dA(W,{fs:A},n,{checkTests:!0,outputDir:n.outputDir});for(let j of w.errors)m.push({ruleId:"test-missing",severity:"warning",message:j,category:"tests",file:W.filePath});for(let j of w.warnings)m.push({ruleId:"test-warning",severity:"warning",message:j,category:"tests",file:W.filePath})}return m}function a($,b,A){let m={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},n=b.filter((j)=>j.severity==="error").length,W=b.filter((j)=>j.severity==="warning").length,w=b.filter((j)=>j.severity==="note").length;return{category:$,label:m[$],errors:n,warnings:W,notes:w,passed:n===0,durationMs:A}}async function Xj($){try{if(!await $.exists(".git/HEAD"))return{};let A=await $.readFile(".git/HEAD"),m=A.match(/^ref: (.+)$/m);if(m){let W=m[1]?.replace("refs/heads/",""),w=`.git/${m[1]}`;if(await $.exists(w))return{commitSha:(await $.readFile(w)).trim(),branch:W};return{branch:W}}return{commitSha:A.trim()}}catch{return{}}}function Yj($){let b=$.config?.ci?.checks,A=b&&b.length>0?[...b]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)A.push("handlers");if($.checkTests)A.push("tests");if($.implementation)A.push("implementation");if($.checkDrift)A.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return A.filter((m)=>!$.skip?.includes(m));return A}async function MJ($,b={}){let A=Date.now(),{fs:m,logger:n}=$,W=[],w=[],j=Yj(b);n.info("Starting CI checks...",{checks:j});let y=await g(m),B=await xA($,{config:y,pattern:b.pattern});if(j.includes("structure")){let V=Date.now(),O=await Pm(B);W.push(...O),w.push(a("structure",O,Date.now()-V))}if(j.includes("integrity")){let V=Date.now(),O=await vm($,b);W.push(...O),w.push(a("integrity",O,Date.now()-V))}if(j.includes("deps")){let V=Date.now(),O=await Xm($,b);W.push(...O),w.push(a("deps",O,Date.now()-V))}if(j.includes("doctor")){let V=Date.now(),O=await Cm($,b);W.push(...O),w.push(a("doctor",O,Date.now()-V))}if(j.includes("docs")){let V=Date.now(),O=await Ym($,b);W.push(...O),w.push(a("docs",O,Date.now()-V))}if(j.includes("policy")){let V=Date.now(),O=await km($,b);W.push(...O),w.push(a("policy",O,Date.now()-V))}if(j.includes("handlers")||b.checkHandlers){let V=Date.now(),O=await Tm($,B);W.push(...O),w.push(a("handlers",O,Date.now()-V))}if(j.includes("tests")||b.checkTests){let V=Date.now(),O=await fm($,B);W.push(...O),w.push(a("tests",O,Date.now()-V))}if(j.includes("test-refs")){let V=Date.now(),O=await rm(B);W.push(...O),w.push(a("test-refs",O,Date.now()-V))}if(j.includes("coverage")){let V=Date.now(),O=await Gm($,B,b);W.push(...O),w.push(a("coverage",O,Date.now()-V))}if(j.includes("implementation")){let V=Date.now(),O=await Dm($,B,b);W.push(...O),w.push(a("implementation",O,Date.now()-V))}if(j.includes("layers")){let V=Date.now(),O=await gm($,b);W.push(...O),w.push(a("layers",O,Date.now()-V))}if(j.includes("drift")){let V=Date.now(),O=await xm($,b);W.push(...O),w.push(a("drift",O,Date.now()-V))}let S=W.filter((V)=>V.severity==="error").length,Q=W.filter((V)=>V.severity==="warning").length,Z=W.filter((V)=>V.severity==="note").length,G=b.failOnWarnings?S===0&&Q===0:S===0,X=await Xj(m),Y={success:G,totalErrors:S,totalWarnings:Q,totalNotes:Z,issues:W,categories:w,durationMs:Date.now()-A,timestamp:new Date().toISOString(),...X};return n.info("CI checks complete",{success:G,errors:S,warnings:Q,durationMs:Y.durationMs}),Y}var TJ=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],DJ={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 kJ($,b={}){let{fs:A,logger:m}=$,n=(b.outputDir??"./src").replace(/\\/g,"/"),W=["generated/**","dist/**",".turbo/**"],w=[`${n}/handlers/**/*.handler.ts`,`${n}/handlers/**/*.handler.test.ts`,`${n}/components/**/*.tsx`,`${n}/components/**/*.test.tsx`,`${n}/forms/**/*.form.tsx`,`${n}/forms/**/*.form.test.tsx`,`${n}/**/*.runner.ts`,`${n}/**/*.renderer.tsx`],j=b.generatedOnly?[...W,...w]:[...W,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...w],y=await A.glob({patterns:j,ignore:["node_modules/**"]}),B=[],S=[];for(let Q of y)try{let Z=await A.stat(Q),G=(Date.now()-Z.mtime.getTime())/86400000;if(typeof b.olderThanDays==="number"&&G<b.olderThanDays){S.push({path:Q,reason:`younger_than_${b.olderThanDays}_days`});continue}if(b.dryRun)m.info("[dry-run] clean would remove",{path:Q,size:Z.size});else await A.remove(Q),m.info("clean.removed",{path:Q,size:Z.size});B.push({path:Q,size:Z.size})}catch(Z){S.push({path:Q,reason:Z instanceof Error?Z.message:String(Z)})}return{removed:B,skipped:S}}s();var cj={};P(cj,{writeReviewPacket:()=>An,writeDecisionEnvelope:()=>Fb,withBranch:()=>f$,verifyConnectMutation:()=>Z4,resolveWorkspace:()=>o,resolveStoragePaths:()=>Q$,replayConnectDecision:()=>dQ,persistLatestArtifacts:()=>$n,persistDecisionArtifacts:()=>Nb,normalizeEvalInput:()=>FQ,matchConfiguredPath:()=>Ib,loadStoredDecision:()=>vb,listStoredReviewPackets:()=>mn,listConnectReviewPackets:()=>uQ,isReviewCommand:()=>hm,isDeniedCommand:()=>cm,isAllowedCommand:()=>tA,initConnectWorkspace:()=>rQ,inferSurfaces:()=>xb,evaluateConnectDecision:()=>DQ,ensureStorage:()=>Db,defaultActor:()=>Mb,decisionArtifactRefs:()=>nb,createConnectControlPlaneRuntime:()=>b4,connectVerdictToPolicy:()=>z$,configuredThreshold:()=>r$,compileConnectPlanPacket:()=>gb,buildConnectContextPack:()=>Tb,assessConnectPolicy:()=>Eb,assertConnectEnabled:()=>A$,artifactRef:()=>J$,appendAuditRecord:()=>bn,analyzeConnectImpact:()=>h$,CONTROL_PLANE_TRACE_GET_REF:()=>pA,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>aA,CONTROL_PLANE_PLAN_VERIFY_REF:()=>im,CONTROL_PLANE_PLAN_COMPILE_REF:()=>om,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>um,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>O$,AGENT_APPROVALS_REF:()=>eA,ACP_TERMINAL_EXEC_REF:()=>BQ,ACP_FS_ACCESS_REF:()=>yQ});import wQ from"micromatch";function A$($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function Ib($,b,A){if(!A||A.length===0)return!1;let m=b.replaceAll("\\","/");return wQ.isMatch(m,A,{contains:!0})}function r$($,b,A){return $.config.connect?.policy?.reviewThresholds?.[b]??A}function tA($,b){return dm($.config.connect?.commands?.allow,b)}function hm($,b){return dm($.config.connect?.commands?.review,b)}function cm($,b){return dm($.config.connect?.commands?.deny,b)}function dm($,b){if(!$||$.length===0)return!1;return $.some((A)=>b===A||b.startsWith(`${A} `))}function qj($,b){if(b.length===0)return{state:"none"};for(let m of b)if(cm($,m))return{commandMatch:m,state:"deny"};for(let m of b)if(hm($,m))return{commandMatch:m,state:"review"};if(b.every((m)=>tA($,m)))return{state:"allow"};let A=b.find(jQ);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((m)=>!tA($,m)),state:"unknown"}}function jQ($){let b=$.trim().toLowerCase();if(b.startsWith("rm "))return Hj(b,["-r","-f"])||b.includes("--recursive")&&b.includes("--force");if(b.startsWith("git reset "))return b.includes("--hard");if(b.startsWith("git clean "))return Hj(b,["-f","-d"]);if(b.startsWith("git push "))return b.includes("--force")||/\s-f(\s|$)/.test(b);return!1}function Hj($,b){return b.every((A)=>$.includes(A)||$.includes(A.replace("-","")))}var um={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},om={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},im={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},pA={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},aA={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},O$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},yQ={key:"acp.fs.access",version:"1.0.0",kind:"command"},BQ={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},eA={key:"agent.approvals",version:"1.0.0",kind:"command"};function Eb($,b){let A=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.immutablePaths)),m=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.protectedPaths)),n=b.touchedPaths.find((Z)=>Ib($,Z,$.config.connect?.policy?.generatedPaths)),{commandMatch:W,state:w}=qj($,b.commands??[]),j=b.impactAnalysis.unknownPaths.length>0,y=b.impactAnalysis.driftFiles.length>0,B=SQ({breakingChange:b.impactAnalysis.breakingChange,destructiveCommand:w==="destructive",commandState:w,contractDrift:y,generatedPath:Boolean(n),immutable:Boolean(A),protectedPath:Boolean(m),smokeFailed:b.smokeFailed===!0,unknownImpact:j,workspace:$}),S=QQ({breakingChange:b.impactAnalysis.breakingChange,commandMatch:W,commandState:w,contractDrift:y,protectedPath:m,unknownPaths:b.impactAnalysis.unknownPaths}),Q=z$(B);return{commandMatch:W,commandState:w,controlPlaneVerdict:Q.controlPlaneVerdict,generatedPath:n,immutablePath:A,protectedPath:m,requiredApprovals:Q.requiresApproval?[{capability:O$.key,reason:S??"Connect policy requires human review before continuing."}]:[],requiresApproval:Q.requiresApproval,reviewReason:S,verificationStatus:Q.verificationStatus,verdict:B}}function z$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function SQ($){if($.immutable||$.commandState==="deny")return"deny";let b=[];if($.protectedPath)b.push(r$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)b.push(r$($.workspace,"breakingChange","require_review"));if($.contractDrift)b.push(r$($.workspace,"contractDrift","require_review"));if($.unknownImpact)b.push(r$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")b.push("require_review");if($.destructiveCommand)b.push(r$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)b.push("rewrite");return b.sort(ZQ)[0]??"permit"}function QQ($){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 ZQ($,b){return Oj($)-Oj(b)}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as xQ}from"crypto";var Uj={};P(Uj,{formatPrComment:()=>Vj,formatMinimalComment:()=>lm,formatJson:()=>Kj,formatCheckRun:()=>Jj,detectImpact:()=>V$,ImpactDetectionOverviewDocBlock:()=>OQ});function Vj($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)A.push("⚠️ **Contract changed (non-breaking)**");else A.push("✅ **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| ➖ Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let m=$.deltas.filter((W)=>W.severity==="breaking"),n=$.deltas.filter((W)=>W.severity==="non_breaking");if(m.length>0){A.push("#### \uD83D\uDD34 Breaking Changes"),A.push("");for(let W of m)A.push(`- **${W.specKey}**: ${W.description}`);A.push("")}if(n.length>0){A.push("#### \uD83D\uDFE1 Non-breaking Changes"),A.push("");for(let W of n)A.push(`- **${W.specKey}**: ${W.description}`);A.push("")}}if($.addedSpecs.length>0){A.push("### Added Specs"),A.push("");for(let m of $.addedSpecs)A.push(`- \`${m.key}\` v${m.version} (${m.type})`);A.push("")}if($.removedSpecs.length>0){A.push("### Removed Specs"),A.push("");for(let m of $.removedSpecs)A.push(`- \`${m.key}\` v${m.version} (${m.type})`);A.push("")}if(b.drift)if(b.drift.hasDrift){A.push("### ⚠️ Drift Detected"),A.push(""),A.push("The following generated files are out of sync with their specs:"),A.push("");for(let m of b.drift.files)A.push(`- \`${m}\``);A.push(""),A.push("Run `contractspec generate` to regenerate artifacts."),A.push("")}else A.push("### ✅ No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
1930
|
+
`)}function lm($){if($.hasBreaking)return`❌ **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`⚠️ **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"✅ **No contract impact**"}function Jj($,b,A={}){let m=A.key??"ContractSpec Impact",n=A.failOnBreaking??!0,W,w;if($.hasBreaking)W=n?"failure":"neutral",w=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)W="success",w=`Non-breaking changes (${$.summary.nonBreaking})`;else W="success",w="No contract impact";let j=lm($);return{name:m,headSha:b,conclusion:W,title:w,summary:j,annotations:$.deltas.filter((y)=>y.severity==="breaking").slice(0,50).map((y)=>({path:y.path,startLine:1,endLine:1,annotationLevel:"failure",message:y.description,title:`Breaking: ${y.rule}`}))}}function Kj($){let b={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((A)=>({type:A.rule,path:A.specKey,summary:A.description,severity:A.severity==="breaking"?"breaking":A.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(b,null,2)}import{classifyImpact as GQ,computeIoDiff as XQ,generateSnapshot as _j}from"@contractspec/module.workspace";async function V$($,b={}){let{fs:A,git:m,logger:n}=$,W=b.workspaceRoot??process.cwd();n.info("Starting impact detection...",{baseline:b.baseline});let j=(await A.glob({pattern:b.pattern??"**/*.{operation,event}.ts",cwd:W})).filter((G)=>!G.includes(".test.")&&!G.includes(".spec.")&&!G.includes("node_modules"));n.debug(`Found ${j.length} spec files`);let y=await YQ(A,j,W),B=_j(y),S;if(b.baseline){let G=await HQ(A,m,j,b.baseline,W);S=_j(G)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=qQ(S.specs,B.specs),Z=GQ(S.specs,B.specs,Q);return n.info("Impact detection complete",{status:Z.status,breaking:Z.summary.breaking,nonBreaking:Z.summary.nonBreaking}),{...Z,workspaceRoot:W,specsAnalyzed:j.length,baseRef:b.baseline}}async function YQ($,b,A){let m=[];for(let n of b){let W=await $.readFile(n);m.push({path:n,content:W})}return m}async function HQ($,b,A,m,n){let W=[];for(let w of A)try{let j=await b.showFile(m,w);W.push({path:w,content:j})}catch{}return W}function qQ($,b){let A=[],m=new Map($.map((W)=>[`${W.key}@${W.version}`,W])),n=new Map(b.map((W)=>[`${W.key}@${W.version}`,W]));for(let[W,w]of n){let j=m.get(W);if(j&&w.type==="operation"&&j.type==="operation"){let y=XQ(j.io,w.io);A.push(...y)}}return A}var OQ={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1612
1931
|
# Contract Impact Detection
|
|
1613
1932
|
|
|
1614
1933
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -1654,49 +1973,49 @@ The system consists of three layers:
|
|
|
1654
1973
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1655
1974
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1656
1975
|
3. **Integrations**: CLI command + GitHub Action
|
|
1657
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
1658
|
-
`;await $.writeFile(
|
|
1659
|
-
`)}async function
|
|
1660
|
-
`);if(
|
|
1661
|
-
`)?
|
|
1976
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as Lj,readFileSync as Rj}from"node:fs";import{basename as VQ,join as tm,resolve as JQ}from"node:path";import{ContractsrcSchema as KQ,DEFAULT_CONTRACTSRC as _Q}from"@contractspec/lib.contracts-spec/workspace-config";function o($={}){let b=JQ($.cwd??process.cwd()),A=$.workspaceRoot??M(b),m=$.packageRoot??r(b),n=$.config??UQ(A,m),W=zQ(m,A);return{cwd:b,workspaceRoot:A,packageRoot:m,config:n,repoId:W,branch:"unknown"}}function f$($,b){return{...$,branch:b&&b.length>0?b:"unknown"}}function Mb($,b){return b??{id:`cli:${$}`,type:"human"}}function xb($){let b=new Set;for(let A of $){if(A.includes("/cli-")||A.includes("/apps/cli-"))b.add("cli");if(A.includes("/contracts-spec/")||A.includes("/specs/"))b.add("contract");if(A.includes("/components/")||A.includes("/ui/")||A.endsWith(".tsx")||A.endsWith(".jsx"))b.add("ui");if(A.includes("/integrations/")||A.includes("/provider"))b.add("integration");if(A.includes("/libs/")||A.includes("/shared/")||A.includes("/utils/"))b.add("library");if(A.includes("/modules/")||A.includes("/bundles/")||A.includes("/examples/"))b.add("solution");if(A.includes("/runtime/"))b.add("runtime");if(A.includes("/harness"))b.add("harness");if(A.includes("/ai-agent/"))b.add("agent");if(A.includes("/knowledge/"))b.add("knowledge");if(A.includes("/mcp/"))b.add("mcp")}if(b.size===0)b.add("runtime");return b.add("audit"),[...b].sort()}function UQ($,b){let A={..._Q};if($!==b)A=zj(A,tm($,".contractsrc.json"));return zj(A,tm(b,".contractsrc.json"))}function zj($,b){if(!Lj(b))return $;try{let A=Rj(b,"utf-8"),m=JSON.parse(A),n=KQ.safeParse(m);if(!n.success)return $;return{...$,...n.data}}catch{return $}}function zQ($,b){let A=tm($,"package.json");if(Lj(A))try{let m=JSON.parse(Rj(A,"utf-8"));if(m.name)return m.name}catch{}return VQ(b)}async function h$($,b){let A=await j$({fs:$.fs},{config:b.workspace.config}),m=new Map(A.filter((y)=>typeof y.key==="string").map((y)=>[y.key,y])),n=b.touchedPaths.map((y)=>LQ($.fs,b.workspace,y,A,m)),W=b.baseline!=null?await V$({...$,logger:$.logger??Ij},{baseline:b.baseline,workspaceRoot:b.workspace.workspaceRoot}):void 0,w=await RQ($,b.workspace,b.touchedPaths),j=sm([...n.flatMap((y)=>y.contracts),...(W?.deltas??[]).map((y)=>({key:y.specKey,version:y.specVersion,kind:y.specType==="event"?"event":"command"}))]);return{breakingChange:W?.hasBreaking===!0,driftFiles:w,impactResult:W,impactedContracts:j,pathImpacts:n,unknownPaths:n.filter((y)=>y.contracts.length===0).map((y)=>y.path)}}function LQ($,b,A,m,n){let W=$.resolve(b.workspaceRoot,A),w=em(A),j=m.map((X)=>{let Y=m$($.relative(b.workspaceRoot,X.filePath));return{score:EQ(A,w,Y,X.key),spec:X}}).filter((X)=>X.score>=45).sort((X,Y)=>Y.score-X.score).slice(0,3),y=m.find((X)=>X.filePath===W),B=y?[{score:100,spec:y}]:j,S=B.filter((X)=>typeof X.spec.key==="string").map((X)=>am(X.spec.key,X.spec.version,X.spec.kind)),Q=B.flatMap((X)=>[...X.spec.emittedEvents??[],...X.spec.policyRefs??[],...X.spec.testRefs??[]].map((Y)=>n.get(Y.key)).filter(Boolean).map((Y)=>am(Y.key,Y.version,Y.kind))),Z=sm([...S,...Q]),G=sm([{key:"connect.policy",version:"1.0.0",kind:"policy"},...B.flatMap((X)=>X.spec.policyRefs??[]).map((X)=>am(X.key,X.version,"policy"))]);return{confidence:B[0]?.score===100?"exact":(B[0]?.score??0)>=70?"high":B.length>0?"medium":"none",contracts:Z,path:A,policies:G,reasons:B.map((X)=>`${X.spec.key??X.spec.filePath} matched with score ${X.score}`),surfaces:xb([A])}}async function RQ($,b,A){let m=CQ($.fs,b,A),n=await Promise.all(m.map(async(W)=>{let w=$.fs.resolve(b.packageRoot,W.comparisonRoot),j=await cA({...$,logger:$.logger??Ij},b.workspaceRoot,w,{generation:{scanAllSpecs:!0,specSearchRoot:b.workspaceRoot},rootPath:b.workspaceRoot}),y=W.filterPrefix&&W.filterPrefix!==W.comparisonRoot?m$($.fs.relative(W.comparisonRoot,W.filterPrefix)):void 0;return j.files.filter((B)=>y?m$(B)===y||m$(B).startsWith(`${y}/`):!0).map((B)=>m$($.fs.join(W.comparisonRoot,B)))}));return[...new Set(n.flat())].sort()}function CQ($,b,A){let m=(b.config.connect?.policy?.generatedPaths??[]).map(MQ).filter(Boolean),n=b.config.outputDir&&b.config.outputDir!=="./src"?m$(b.config.outputDir):void 0,W=new Map;for(let w of A){let j=m$(w);if(n&&j.startsWith(n))W.set(n,{comparisonRoot:n});for(let y of m)if(j.startsWith(y)){let B=IQ($,n,y);W.set(`${B}::${y}`,{comparisonRoot:B,filterPrefix:y})}}return[...W.values()]}function IQ($,b,A){if(b&&A.startsWith(b))return b;return $.basename(A)==="docs"?m$($.dirname(A)):A}function EQ($,b,A,m){if(m$($)===m$(A))return 100;let n=em(A),W=em(m??""),w=Cj($)===Cj(A)?40:0,j=pm($.split("/"),A.split("/"),5),y=pm(b,n,5),B=pm(b,W,4);return w+j+y+B}function pm($,b,A){let m=new Set(b);return $.filter((n)=>m.has(n)).length*A}function em($){return m$($).split(/[\/._-]+/).filter(Boolean)}function Cj($){return m$($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function MQ($){return m$($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function m$($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function am($,b,A){return{key:$,version:String(b??"1.0.0"),kind:A==="query"||A==="event"||A==="policy"||A==="capability"?A:"command"}}function sm($){return[...new Map($.map((b)=>[`${b.key}@${b.version}`,b])).values()]}var Ij={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function Tb($,b){let A=o(b);A$(A),A=f$(A,await $.git.currentBranch());let m=Mb(b.taskId,b.actor),n=await TQ($,A.workspaceRoot,b),W=await h$($,{baseline:b.baseline,touchedPaths:n,workspace:A}),w=A.config.connect?.canonPacks??[];return{id:`connect.ctx_${xQ()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:m,knowledge:w.map((j)=>({spaceKey:j.ref,category:"canonical",trustLevel:j.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:W.impactedContracts,affectedSurfaces:W.pathImpacts.length>0?[...new Set(W.pathImpacts.flatMap((j)=>j.surfaces))].sort():xb(n),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...w.map((j)=>({key:j.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...w.map((j)=>({kind:"canon-pack",ref:j.ref}))],acceptanceChecks:A.config.connect?.policy?.smokeChecks??[]}}async function TQ($,b,A){let m=A.paths??[];if(m.length>0)return m.map((W)=>Ej($.fs,b,W));if(!A.baseline)return[];return(await $.git.diffFiles(A.baseline)).map((W)=>Ej($.fs,b,W))}function Ej($,b,A){let m=$.resolve(b,A);return $.relative(b,m).replaceAll("\\","/")}import{resolve as c$}from"node:path";function Q$($){let b=$.config.connect?.storage,A=c$($.packageRoot,b?.root??".contractspec/connect");return{root:A,contextPack:c$($.packageRoot,b?.contextPack??".contractspec/connect/context-pack.json"),planPacket:c$($.packageRoot,b?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:c$($.packageRoot,b?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:c$($.packageRoot,b?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:c$($.packageRoot,b?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:c$(A,"decisions")}}async function Db($,b){await $.mkdir(b.root),await $.mkdir(b.reviewPacketsDir),await $.mkdir(b.decisionsDir)}async function $n($,b,A){if(A.contextPack)await S$($,b.contextPack,A.contextPack);if(A.planPacket)await S$($,b.planPacket,A.planPacket);if(A.patchVerdict)await S$($,b.patchVerdict,A.patchVerdict)}async function Nb($,b,A,m){let n=$.join(b.decisionsDir,A);if(await $.mkdir(n),m.contextPack)await S$($,$.join(n,"context-pack.json"),m.contextPack);if(m.planPacket)await S$($,$.join(n,"plan-packet.json"),m.planPacket);if(m.patchVerdict)await S$($,$.join(n,"patch-verdict.json"),m.patchVerdict);if(m.reviewPacket)await S$($,$.join(n,"review-packet.json"),m.reviewPacket);if(m.evaluationResult!==void 0)await S$($,$.join(n,"evaluation-result.json"),m.evaluationResult);if(m.replayBundle!==void 0)await S$($,$.join(n,"replay-bundle.json"),m.replayBundle);return n}async function Fb($,b,A,m){let n=$.join(b.decisionsDir,A,"decision-envelope.json");return await S$($,n,m),n}async function bn($,b,A){let m=await Mj($,b.auditFile)??"",n=`${JSON.stringify(A)}
|
|
1977
|
+
`;await $.writeFile(b.auditFile,`${m}${n}`)}async function An($,b,A){let m=$.join(b.reviewPacketsDir,`${A.id}.json`);return await S$($,m,A),m}async function vb($,b,A){let m=$.join(b.decisionsDir,A);return{historyDir:m,contextPack:await mb($,$.join(m,"context-pack.json")),planPacket:await mb($,$.join(m,"plan-packet.json")),patchVerdict:await mb($,$.join(m,"patch-verdict.json")),reviewPacket:await mb($,$.join(m,"review-packet.json")),envelope:await mb($,$.join(m,"decision-envelope.json"))}}async function mn($,b){let A=await $.glob({pattern:"*.json",cwd:b.reviewPacketsDir,absolute:!0}),m=[];for(let n of A){let W=await mb($,n);if(W)m.push({filePath:n,packet:W})}return m.sort((n,W)=>n.packet.id.localeCompare(W.packet.id))}function J$($,b,A){return $.relative(b.packageRoot,$.resolve(A)).replaceAll("\\","/")}function nb($,b,A,m,n){let W=$.join(A.decisionsDir,m);return{contextPack:J$($,b,$.join(W,"context-pack.json")),planPacket:J$($,b,$.join(W,"plan-packet.json")),patchVerdict:J$($,b,$.join(W,"patch-verdict.json")),reviewPacket:n.reviewPacket?J$($,b,$.join(W,"review-packet.json")):void 0,evaluationResult:n.evaluationResult?J$($,b,$.join(W,"evaluation-result.json")):void 0,replayBundle:n.replayBundle?J$($,b,$.join(W,"replay-bundle.json")):void 0}}async function S$($,b,A){await $.writeFile(b,`${JSON.stringify(A,null,2)}
|
|
1978
|
+
`)}async function mb($,b){let A=await Mj($,b);if(!A)return;try{return JSON.parse(A)}catch{return}}async function Mj($,b){if(!await $.exists(b))return;try{return await $.readFile(b)}catch{return}}async function DQ($,b,A){let m=o(b);if(A$(m),!b.scenarioKey&&!b.suiteKey||b.scenarioKey&&b.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let n=Q$(m),W=await vb($.fs,n,b.decisionId),w=NQ(m,W),j=b.scenarioKey?await A.runScenarioEvaluation({scenarioKey:b.scenarioKey,version:b.version,context:w}):await A.runSuiteEvaluation({suiteKey:b.suiteKey??"",version:b.version,context:w}),y=await Nb($.fs,n,b.decisionId,{evaluationResult:j}),B=await $.fs.exists($.fs.join(y,"replay-bundle.json")),S={artifacts:nb($.fs,m,n,b.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:B,reviewPacket:Boolean(W.reviewPacket)}),connectDecisionId:b.decisionId,createdAt:W.envelope?.createdAt??new Date().toISOString(),runtimeLink:W.envelope?.runtimeLink,taskId:W.contextPack?.taskId??b.decisionId,verdict:W.patchVerdict?.verdict??"permit"};return await Fb($.fs,n,b.decisionId,S),{historyDir:y,evaluation:j,context:w}}function NQ($,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 FQ($){return $}import{DEFAULT_CONTRACTSRC as PQ}from"@contractspec/lib.contracts-spec/workspace-config";async function sA($,b){let A=$.join(b.root,".gitignore"),m=b.behavior??"auto",n=Dj(b.patterns);if(n.length===0||m==="skip")return{target:"gitignore",filePath:A,action:"skipped",message:m==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(m==="auto"&&b.interactive&&b.prompts&&!await b.prompts.confirm(`Add recommended ContractSpec ignore rules to ${A}?`,!0))return{target:"gitignore",filePath:A,action:"skipped",message:"User skipped ContractSpec gitignore update"};let W=await $.exists(A),w=W?await $.readFile(A):"",j=vQ(w,n);if(Tj(w)===Tj(j))return{target:"gitignore",filePath:A,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(A,j),{target:"gitignore",filePath:A,action:W?"merged":"created",message:W?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(W){return{target:"gitignore",filePath:A,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}function vQ($,b){let A=gQ(b),m=kQ(),n=$.replace(/\r\n/g,`
|
|
1979
|
+
`);if(m.test(n))return n.replace(m,A);if(n.trim().length===0)return A;return`${n.endsWith(`
|
|
1980
|
+
`)?n:`${n}
|
|
1662
1981
|
`}
|
|
1663
|
-
${
|
|
1982
|
+
${A}`}function gQ($){return`# contractspec:init:gitignore:start
|
|
1664
1983
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1665
|
-
${
|
|
1984
|
+
${Dj($).join(`
|
|
1666
1985
|
`)}
|
|
1667
1986
|
# contractspec:init:gitignore:end
|
|
1668
|
-
`}function
|
|
1669
|
-
`).trimEnd()}function L4($){return[...new Set($.map((W)=>W.trim()).filter(Boolean))]}async function lX($,W={}){let j=d(W),A=W.scope==="package"?j.packageRoot:j.workspaceRoot,Q=$.join(A,".contractsrc.json"),Z={connect:{...rX.connect,enabled:!0}},X="created";if(await $.exists(Q)){let q=r(await $.readFile(Q)),H=p(q??{},Z);if(q?.connect&&typeof q.connect==="object")H.connect.enabled=!0;await $.writeFile(Q,F(H)),X="merged"}else await $.writeFile(Q,F(Z));let Y=A$(d({...W,workspaceRoot:A,packageRoot:A}));await K0($,Y);let B=await EW($,{behavior:W.gitignoreBehavior,interactive:W.interactive??!1,patterns:[Y0.connect,Y0.verificationCache],prompts:W.prompts,root:j.workspaceRoot});return{configPath:Q,targetRoot:A,action:X,gitignore:B}}import{randomUUID as NW}from"crypto";async function Uj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let{commands:A,touchedPaths:Q}=oX(W.candidate),Z=await bj($,{...W,paths:Q}),X=b0(W.taskId,W.actor),Y=iX(W.candidate.steps,W.candidate),B=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),q=J0(j,{commands:A,impactAnalysis:B,touchedPaths:Q}),H={id:`connect.plan_${NW()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:Z.impactedContracts,affectedSurfaces:Z.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:q.requiredApprovals,riskScore:pX(Q.length,A.length),verificationStatus:q.verificationStatus,controlPlane:{intentSubmit:Zj,planCompile:Xj,planVerify:Yj,traceId:X.traceId},acpActions:[...Q.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:Z,planPacket:H}}function oX($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let Q of A.paths??[])W.add(Q);for(let Q of A.commands??[])j.add(Q)}return{commands:[...j],touchedPaths:[...W]}}function iX($,W){if(!$||$.length===0)return[{id:`step_${NW()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${NW()}`,summary:j}:{id:`step_${NW()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function pX($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function tX($,W,j){let A=d(W);a(A);let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X={decisionId:Z.envelope?.runtimeLink?.decisionId,traceId:Z.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,B=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:Z.historyDir,contextPack:Z.contextPack,planPacket:Z.planPacket,patchVerdict:Z.patchVerdict,reviewPacket:Z.reviewPacket,trace:Y??void 0,replay:B??void 0,source:Y?"local+control-plane":"local"}}async function aX($,W={}){let j=d(W);return a(j),zj($.fs,A$(j))}import{buildChannelPlanTrace as sX,compileChannelPlan as eX,finalizeChannelPlan as $2,replayExecutionTrace as W2,resolveChannelExecutionActor as j2}from"@contractspec/integration.runtime/channel";import{createHash as A2}from"crypto";var L0="connect.local",Q2="connect.runtime-link.v1",Z2="connect.adapter.v1",X2="connect-control-plane-bridge";function Y2($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:A,patchVerdict:Q,planPacket:Z,workspace:X})=>{let Y=new Date(j),B=JSON.stringify({connectDecisionId:W,objective:Z.objective,taskId:Z.taskId,tool:A.tool,verdict:Q.verdict}),q={workspaceId:X.repoId,providerKey:L0,externalEventId:W,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Q.controlPlane.traceId,thread:{externalThreadId:`connect:${Z.taskId}`,externalUserId:Z.actor.id},message:{text:V2(Z.objective,A)},metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`}),rawPayload:B},H=await $.store.claimEventReceipt({workspaceId:q.workspaceId,providerKey:q.providerKey,externalEventId:q.externalEventId,eventType:q.eventType,signatureValid:!0,payloadHash:G2(B),traceId:q.traceId});if(H.duplicate)return B2($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:q.workspaceId,providerKey:q.providerKey,externalThreadId:q.thread.externalThreadId,externalUserId:q.thread.externalUserId,occurredAt:Y}),G=j2(q,{actorId:Z.actor.id,actorType:Z.actor.type,capabilityGrants:H2(Q.verdict),capabilitySource:"connect",sessionId:Z.actor.sessionId}),J=eX({event:q,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),b=$2({plan:J,decision:q2(Q),approvalTimeoutMs:900000,now:Y}),w=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:b.policy?.verdict??"blocked",riskTier:b.policy?.riskTier??"blocked",confidence:b.policy?.confidence??0.5,modelName:X2,promptVersion:Q2,policyVersion:Z2,toolTrace:sX(b),actionPlan:b,requiresApproval:b.approval.required,approvalStatus:b.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:b.approval.required?"pending":"processed",decisionId:w.id,receiptId:H.receiptId,traceId:b.traceId,workspaceId:X.repoId,providerKey:L0,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`,metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,tool:A.tool})}),{approvalStatus:w.approvalStatus,decisionId:w.id,planId:b.id,providerKey:L0,receiptId:H.receiptId,threadId:V.id,traceId:b.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>O4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await O4($.traceService,W);return j?W2(j):null}}}async function B2($,W,j){let Q=(await $.listDecisions({externalEventId:j,limit:1,providerKey:L0,workspaceId:W}))[0];return Q?{approvalStatus:Q.approvalStatus,decisionId:Q.id,planId:Q.actionPlan.id,providerKey:L0,receiptId:Q.receiptId,threadId:Q.threadId,traceId:Q.actionPlan.traceId,workspaceId:W}:null}async function O4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function q2($){let W=n$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((j)=>`${j.status}:${j.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:W.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:W.controlPlaneVerdict}}function H2($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function V2($,W){return`${$} [${W.tool}]`}function G2($){return A2("sha256").update($).digest("hex")}function S4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as w2}from"crypto";function I4($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as J2}from"crypto";function M4($,W,j){let A=$?`Immutable path: ${$}`:W?`Protected path: ${W}`:j?`Generated path: ${j}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":W||j?"warn":"pass",detail:A}}function E4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:A}}function N4($,W,j){return{id:"impact-analysis",status:$?"fail":W||j?"warn":"pass",detail:$?"Breaking change detected.":W?"Generated-path drift detected.":j?"Impact could not be resolved.":"Impact resolved."}}function R4($,W,j,A,Q,Z){let X=Z.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${Z.runtimeLink.decisionId}`:Z.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${Z.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${J2()}`,sourceDecisionId:W,objective:A.objective,reason:Z.reason,summary:{paths:Q,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:Z.artifactRefs.contextPack},{type:"plan-packet",ref:Z.artifactRefs.planPacket},{type:"patch-verdict",ref:Z.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:T$.key,reason:Z.reason}],controlPlane:{traceQuery:SW,policyExplain:IW,approvalStatus:Z.runtimeLink?.approvalStatus,decisionId:Z.runtimeLink?.decisionId,traceId:Z.runtimeLink?.traceId??j.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Lj($,W,j,A,Q,Z,X,Y,B){let q=n$(X);return{decisionId:$,summary:A.objective,action:W.tool==="acp.fs.access"?{actionType:W.operation==="write"?"write_file":"edit_file",tool:W.tool,target:W.path}:{actionType:"run_command",tool:W.tool,cwd:W.cwd},impacted:Q,checks:Z,verdict:X,controlPlane:{verdict:q.controlPlaneVerdict,requiresApproval:q.requiresApproval,approvalStatus:B?.approvalStatus,decisionId:B?.decisionId,traceId:B?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${T$.key}@${T$.version}`,`${MW.key}@${MW.version}`]:void 0,remediation:b2(X),reviewPacketRef:Y,replay:{traceQuery:SW,policyExplain:IW}}}function b2($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function K2($,W,j={}){let A=d(W);a(A),A=x$(A,await $.git.currentBranch());let Q=`connect.dec_${w2()}`,Z=(j.now??(()=>new Date))().toISOString(),X=A$(A);await K0($.fs,X);let{contextPack:Y,planPacket:B}=await Uj($,{...W,candidate:_2(W)}),q=z2(W),H=await y$($,{baseline:W.baseline,touchedPaths:q,workspace:A}),V=await U2(j,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),G=V.some((M)=>M.id.startsWith("smoke:")&&M.status==="fail"),J=J0(A,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:q}),b=[M4(J.immutablePath,J.protectedPath,J.generatedPath),E4(J.commandState,J.commandMatch),N4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],w=r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0}),L=H.pathImpacts.length>0?H.pathImpacts.map((M)=>({file:M.path,contracts:M.contracts,policies:M.policies,surfaces:M.surfaces})):q.map((M)=>({file:M,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),z=Lj(Q,W,Y,B,L,b,J.verdict,void 0),S=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Q,createdAt:Z,input:W,patchVerdict:z,planPacket:B,workspace:A}):null,U=S?{...B,controlPlane:{...B.controlPlane,decisionId:S.decisionId,traceId:S.traceId??B.controlPlane.traceId}}:B,O=J.verdict==="require_review"?R4(A,Q,Y,U,q,{artifactRefs:w,reason:J.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:S}):void 0,K=Lj(Q,W,Y,U,L,b,J.verdict,O?V$($.fs,A,$.fs.join(X.reviewPacketsDir,`${O.id}.json`)):void 0,S);if(await wj($.fs,X,{contextPack:Y,planPacket:U,patchVerdict:K}),O)await _j($.fs,X,O);let _=await _0($.fs,X,Q,{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O}),I={artifacts:r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(O)}),connectDecisionId:Q,createdAt:Z,runtimeLink:S??void 0,taskId:W.taskId,verdict:J.verdict};return await z0($.fs,X,Q,I),await Kj($.fs,X,I4({contextPack:Y,createdAt:Z,envelope:I,reviewPacket:O,verifyInput:W,workspace:A})),{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O,historyDir:_}}function _2($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function z2($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function U2($,W,j){if(!$.runCommand)return[];let A=[];for(let Q of W){let Z=await $.runCommand(Q,{cwd:j});A.push({id:`smoke:${Q}`,status:Z.exitCode===0?"pass":"fail",detail:Z.exitCode===0?`Passed: ${Q}`:`Failed (${Z.exitCode}): ${Q}`})}return A}DW();var Ij={};h(Ij,{generateWorkflowSpec:()=>Y8,generateWorkflowRunnerTemplate:()=>jW,generateWorkflowDevkitWorkflowTemplate:()=>a0,generateWorkflowDevkitStreamRouteTemplate:()=>$W,generateWorkflowDevkitStartRouteTemplate:()=>s0,generateWorkflowDevkitGenericTemplate:()=>WW,generateWorkflowDevkitFollowUpRouteTemplate:()=>e0,generateTestTemplate:()=>s5,generateTelemetrySpec:()=>X8,generatePresentationSpec:()=>Z8,generateOperationSpec:()=>Q8,generateMigrationSpec:()=>A8,generateKnowledgeSpaceSpec:()=>W8,generateIntegrationSpec:()=>$8,generateHandlerTemplate:()=>t5,generateFormSpec:()=>p5,generateFeatureSpec:()=>i5,generateExperimentSpec:()=>o5,generateEventSpec:()=>l5,generateDataViewSpec:()=>r5,generateDataViewRendererTemplate:()=>p0,generateComponentTemplate:()=>a5,generateAppBlueprintSpec:()=>c5});DW();class T4{ai;templates=Ij;constructor($){this.ai=new CW($)}}function GU($){return new T4($)}import{scanSpecSource as D2}from"@contractspec/module.workspace";function F4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function zU($,W,j={}){let{fs:A,logger:Q}=W,Z=await A.exists($);if(!Z&&!j.force)return{specPath:$,specInfo:F4($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let X=F4($),Y;if(Z)try{let q=await A.readFile($);X=D2(q,$),Y=X.key}catch{}let B=[];if(j.clean&&Y)try{let q=await _W(Y,{fs:A});for(let H of q)try{await A.remove(H.filePath),B.push(H.filePath),Q.info(`Removed artifact: ${H.filePath}`)}catch{Q.warn(`Could not remove artifact: ${H.filePath}`)}}catch{Q.warn("Could not discover implementations for cleanup")}if(Z)await A.remove($),Q.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:X,deleted:!0,cleanedFiles:B,errors:[]}}import{computeSemanticDiff as T2}from"@contractspec/module.workspace";async function OU($,W,j,A={}){let{fs:Q,git:Z}=j;if(!await Q.exists($))throw Error(`Spec file not found: ${$}`);let Y=await Q.readFile($),B,q;if(A.baseline)B=await Z.showFile(A.baseline,$),q=`${A.baseline}:${$}`;else{if(!await Q.exists(W))throw Error(`Spec file not found: ${W}`);B=await Q.readFile(W),q=W}let H=T2(Y,$,B,q,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:q,differences:H}}i();import{openApiForRegistry as F2}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Mj}from"@contractspec/lib.contracts-spec/operations";async function x2($,W){let{fs:j,logger:A}=W,{registryPath:Q,outputPath:Z="./openapi.json"}=$;A.info("Loading registry...",{registryPath:Q});let X=await y2(Q,j);A.info("Generating OpenAPI document...");let Y=F2(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),B=JSON.stringify(Y,null,2)+`
|
|
1670
|
-
`,
|
|
1987
|
+
`}function kQ(){return new RegExp(`${xj("# contractspec:init:gitignore:start")}[\\s\\S]*?${xj("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function xj($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tj($){return $.replace(/\r\n/g,`
|
|
1988
|
+
`).trimEnd()}function Dj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function rQ($,b={}){let A=o(b),m=b.scope==="package"?A.packageRoot:A.workspaceRoot,n=$.join(m,".contractsrc.json"),W={connect:{...PQ.connect,enabled:!0}},w="created";if(await $.exists(n)){let B=p(await $.readFile(n)),S=$$(B??{},W);if(B?.connect&&typeof B.connect==="object")S.connect.enabled=!0;await $.writeFile(n,N(S)),w="merged"}else await $.writeFile(n,N(W));let j=Q$(o({...b,workspaceRoot:m,packageRoot:m}));await Db($,j);let y=await sA($,{behavior:b.gitignoreBehavior,interactive:b.interactive??!1,patterns:[Ub.connect,Ub.verificationCache],prompts:b.prompts,root:A.workspaceRoot});return{configPath:n,targetRoot:m,action:w,gitignore:y}}import{randomUUID as $0}from"crypto";async function gb($,b){let A=o(b);A$(A),A=f$(A,await $.git.currentBranch());let{commands:m,touchedPaths:n}=fQ(b.candidate),W=await Tb($,{...b,paths:n}),w=Mb(b.taskId,b.actor),j=hQ(b.candidate.steps,b.candidate),y=await h$($,{baseline:b.baseline,touchedPaths:n,workspace:A}),B=Eb(A,{commands:m,impactAnalysis:y,touchedPaths:n}),S={id:`connect.plan_${$0()}`,taskId:b.taskId,repoId:A.repoId,branch:A.branch,actor:w,objective:b.candidate.objective,steps:j,impactedContracts:W.impactedContracts,affectedSurfaces:W.affectedSurfaces,requiredChecks:A.config.connect?.policy?.smokeChecks??[],requiredApprovals:B.requiredApprovals,riskScore:cQ(n.length,m.length),verificationStatus:B.verificationStatus,controlPlane:{intentSubmit:um,planCompile:om,planVerify:im,traceId:w.traceId},acpActions:[...n.length>0?["acp.fs.access"]:[],...m.length>0?["acp.terminal.exec"]:[]]};return{contextPack:W,planPacket:S}}function fQ($){let b=new Set($.touchedPaths??[]),A=new Set($.commands??[]);for(let m of $.steps??[]){if(typeof m==="string")continue;for(let n of m.paths??[])b.add(n);for(let n of m.commands??[])A.add(n)}return{commands:[...A],touchedPaths:[...b]}}function hQ($,b){if(!$||$.length===0)return[{id:`step_${$0()}`,summary:b.objective,paths:b.touchedPaths,commands:b.commands}];return $.map((A)=>typeof A==="string"?{id:`step_${$0()}`,summary:A}:{id:`step_${$0()}`,summary:A.summary,paths:A.paths,commands:A.commands,contractRefs:A.contractRefs})}function cQ($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function dQ($,b,A){let m=o(b);A$(m);let n=Q$(m),W=await vb($.fs,n,b.decisionId),w={decisionId:W.envelope?.runtimeLink?.decisionId,traceId:W.envelope?.runtimeLink?.traceId},j=A&&(w.decisionId||w.traceId)?await A.getExecutionTrace(w):null,y=A&&j?await A.replayExecutionTrace(w):null;return{decisionId:b.decisionId,historyDir:W.historyDir,contextPack:W.contextPack,planPacket:W.planPacket,patchVerdict:W.patchVerdict,reviewPacket:W.reviewPacket,trace:j??void 0,replay:y??void 0,source:j?"local+control-plane":"local"}}async function uQ($,b={}){let A=o(b);return A$(A),mn($.fs,Q$(A))}import{buildChannelPlanTrace as oQ,compileChannelPlan as iQ,finalizeChannelPlan as lQ,replayExecutionTrace as tQ,resolveChannelExecutionActor as pQ}from"@contractspec/integration.runtime/channel";import{createHash as aQ}from"crypto";var kb="connect.local",eQ="connect.runtime-link.v1",sQ="connect.adapter.v1",$4="connect-control-plane-bridge";function b4($){return{linkDecision:async({connectDecisionId:b,createdAt:A,input:m,patchVerdict:n,planPacket:W,workspace:w})=>{let j=new Date(A),y=JSON.stringify({connectDecisionId:b,objective:W.objective,taskId:W.taskId,tool:m.tool,verdict:n.verdict}),B={workspaceId:w.repoId,providerKey:kb,externalEventId:b,eventType:m.tool==="acp.fs.access"?`connect.fs.${m.operation}`:"connect.terminal.exec",occurredAt:j,signatureValid:!0,traceId:n.controlPlane.traceId,thread:{externalThreadId:`connect:${W.taskId}`,externalUserId:W.actor.id},message:{text:W4(W.objective,m)},metadata:Fj({connectDecisionId:b,connectVerdict:n.verdict,sessionId:W.actor.sessionId,workflowId:`connect:${W.taskId}`}),rawPayload:y},S=await $.store.claimEventReceipt({workspaceId:B.workspaceId,providerKey:B.providerKey,externalEventId:B.externalEventId,eventType:B.eventType,signatureValid:!0,payloadHash:w4(y),traceId:B.traceId});if(S.duplicate)return A4($.store,w.repoId,b);let Q=await $.store.upsertThread({workspaceId:B.workspaceId,providerKey:B.providerKey,externalThreadId:B.thread.externalThreadId,externalUserId:B.thread.externalUserId,occurredAt:j}),Z=pQ(B,{actorId:W.actor.id,actorType:W.actor.type,capabilityGrants:n4(n.verdict),capabilitySource:"connect",sessionId:W.actor.sessionId}),G=iQ({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:j}),X=lQ({plan:G,decision:m4(n),approvalTimeoutMs:900000,now:j}),Y=await $.store.saveDecision({receiptId:S.receiptId,threadId:Q.id,policyMode:X.policy?.verdict??"blocked",riskTier:X.policy?.riskTier??"blocked",confidence:X.policy?.confidence??0.5,modelName:$4,promptVersion:eQ,policyVersion:sQ,toolTrace:oQ(X),actionPlan:X,requiresApproval:X.approval.required,approvalStatus:X.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:X.approval.required?"pending":"processed",decisionId:Y.id,receiptId:S.receiptId,traceId:X.traceId,workspaceId:w.repoId,providerKey:kb,sessionId:W.actor.sessionId,workflowId:`connect:${W.taskId}`,metadata:Fj({connectDecisionId:b,connectVerdict:n.verdict,tool:m.tool})}),{approvalStatus:Y.approvalStatus,decisionId:Y.id,planId:X.id,providerKey:kb,receiptId:S.receiptId,threadId:Q.id,traceId:X.traceId,workspaceId:w.repoId}},getExecutionTrace:(b)=>Nj($.traceService,b),replayExecutionTrace:async(b)=>{if(b.decisionId)return $.traceService.replayExecutionTrace(b.decisionId);let A=await Nj($.traceService,b);return A?tQ(A):null}}}async function A4($,b,A){let n=(await $.listDecisions({externalEventId:A,limit:1,providerKey:kb,workspaceId:b}))[0];return n?{approvalStatus:n.approvalStatus,decisionId:n.id,planId:n.actionPlan.id,providerKey:kb,receiptId:n.receiptId,threadId:n.threadId,traceId:n.actionPlan.traceId,workspaceId:b}:null}async function Nj($,b){if(b.decisionId)return $.getExecutionTrace(b.decisionId);if(!b.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:b.traceId}))[0]??null}function m4($){let b=z$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((A)=>`${A.status}:${A.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:b.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:b.controlPlaneVerdict}}function n4($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function W4($,b){return`${$} [${b.tool}]`}function w4($){return aQ("sha256").update($).digest("hex")}function Fj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as Q4}from"crypto";async function vj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=j4(b);if(!A)return{};let m=await Xb({fs:$.fs},{config:b.config,cwd:b.cwd,currentTarget:b.tool==="acp.fs.access"?b.path:void 0,family:A,paths:b.tool==="acp.fs.access"?[b.path]:b.touchedPaths??[],platform:A==="ui"?y4(b):void 0,query:nn(b),workspaceRoot:b.workspaceRoot,packageRoot:b.packageRoot});return{check:{id:"adoption-resolution",status:m.verdict==="permit"?"pass":m.verdict==="rewrite"?"warn":"fail",detail:m.reason},reason:m.reason,remediation:m.selected!=null?[`Prefer ${m.selected.candidate.source} candidate ${m.selected.candidate.title}.`]:["No reusable candidate matched; create the smallest viable surface."],resolution:m,verdict:m.verdict}}function j4($){let b=nn($).toLowerCase();if(/\b(contract|operation|event|spec|presentation|form)\b/.test(b))return"contracts";if(/\b(integration|provider|sdk|adapter|bridge)\b/.test(b))return"integrations";if(/\b(runtime|mcp|graphql|rest|harness|render)\b/.test(b))return"runtime";if(/\b(component|ui|screen|view|page|tsx|jsx)\b/.test(b))return"ui";if(/\b(module|bundle|example|template)\b/.test(b))return"solutions";if(/\b(logger|schema|testing|observability|identity|utility|shared|lib)\b/.test(b))return"sharedLibs";return null}function nn($){return $.tool==="acp.fs.access"?`${$.operation} ${$.path}`:`${$.command} ${($.touchedPaths??[]).join(" ")}`.trim()}function y4($){let b=nn($).toLowerCase();return/\b(native|expo|react-native)\b/.test(b)?"native":"web"}function gj($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as B4}from"crypto";function kj($,b,A){let m=$?`Immutable path: ${$}`:b?`Protected path: ${b}`:A?`Generated path: ${A}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":b||A?"warn":"pass",detail:m}}function Pj($,b){let A=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",m=b?`Command policy: ${$} (${b})`:`Command policy: ${$}`;return{id:"command-policy",status:A,detail:m}}function rj($,b,A){return{id:"impact-analysis",status:$?"fail":b||A?"warn":"pass",detail:$?"Breaking change detected.":b?"Generated-path drift detected.":A?"Impact could not be resolved.":"Impact resolved."}}function fj($,b,A,m,n,W){let w=W.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${W.runtimeLink.decisionId}`:W.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${W.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${b}`;return{id:`review_${B4()}`,sourceDecisionId:b,objective:m.objective,reason:W.reason,summary:{paths:n,impactedContracts:A.impactedContracts,affectedSurfaces:A.affectedSurfaces,requiredChecks:m.requiredChecks},evidence:[{type:"context-pack",ref:W.artifactRefs.contextPack},{type:"plan-packet",ref:W.artifactRefs.planPacket},{type:"patch-verdict",ref:W.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:w}],requiredApprovals:[{capability:O$.key,reason:W.reason}],controlPlane:{traceQuery:pA,policyExplain:aA,approvalStatus:W.runtimeLink?.approvalStatus,decisionId:W.runtimeLink?.decisionId,traceId:W.runtimeLink?.traceId??A.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Wn($,b,A,m,n,W,w,j,y){let B=z$(w);return{decisionId:$,summary:m.objective,action:b.tool==="acp.fs.access"?{actionType:b.operation==="write"?"write_file":"edit_file",tool:b.tool,target:b.path}:{actionType:"run_command",tool:b.tool,cwd:b.cwd},impacted:n,checks:W,verdict:w,controlPlane:{verdict:B.controlPlaneVerdict,requiresApproval:B.requiresApproval,approvalStatus:y?.approvalStatus,decisionId:y?.decisionId,traceId:y?.traceId??A.actor.traceId},approvalOperationRefs:w==="require_review"?[`${O$.key}@${O$.version}`,`${eA.key}@${eA.version}`]:void 0,remediation:S4(w),reviewPacketRef:j,replay:{traceQuery:pA,policyExplain:aA}}}function S4($){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 Z4($,b,A={}){let m=o(b);A$(m),m=f$(m,await $.git.currentBranch());let n=`connect.dec_${Q4()}`,W=(A.now??(()=>new Date))().toISOString(),w=Q$(m);await Db($.fs,w);let{contextPack:j,planPacket:y}=await gb($,{...b,candidate:Y4(b)}),B=H4(b),S=await h$($,{baseline:b.baseline,touchedPaths:B,workspace:m}),Q=await q4(A,m.config.connect?.policy?.smokeChecks??[],m.workspaceRoot),Z=Q.some((h)=>h.id.startsWith("smoke:")&&h.status==="fail"),G=Eb(m,{commands:b.tool==="acp.terminal.exec"?[b.command]:[],impactAnalysis:S,smokeFailed:Z,touchedPaths:B}),X=await vj($,b),Y=[kj(G.immutablePath,G.protectedPath,G.generatedPath),Pj(G.commandState,G.commandMatch),rj(S.breakingChange,S.driftFiles.length>0,S.unknownPaths.length>0),...X.check?[X.check]:[],...Q],V=G4(G,X.verdict),O=z$(V),K=X.reason??G.reviewReason??"Connect policy requires human review before continuing.",J=O.requiresApproval?G.requiredApprovals.length>0?G.requiredApprovals:[{capability:O$.key,reason:K}]:[],_={...y,requiredApprovals:J,verificationStatus:O.verificationStatus},H=nb($.fs,m,w,n,{contextPack:!0,patchVerdict:!0,planPacket:!0}),q=S.pathImpacts.length>0?S.pathImpacts.map((h)=>({file:h.path,contracts:h.contracts,policies:h.policies,surfaces:h.surfaces})):B.map((h)=>({file:h,contracts:j.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:j.affectedSurfaces})),U=Wn(n,b,j,_,q,Y,V,void 0),z=A.controlPlane?await A.controlPlane.linkDecision({connectDecisionId:n,createdAt:W,input:b,patchVerdict:U,planPacket:_,workspace:m}):null,L=z?{...y,requiredApprovals:J,verificationStatus:O.verificationStatus,controlPlane:{...y.controlPlane,decisionId:z.decisionId,traceId:z.traceId??y.controlPlane.traceId}}:_,I=V==="require_review"?fj(m,n,j,L,B,{artifactRefs:H,reason:K,runtimeLink:z}):void 0,C=Wn(n,b,j,L,q,Y,V,I?J$($.fs,m,$.fs.join(w.reviewPacketsDir,`${I.id}.json`)):void 0,z);if(X.remediation?.length)C.remediation=X.remediation;if(await $n($.fs,w,{contextPack:j,planPacket:L,patchVerdict:C}),I)await An($.fs,w,I);let F=await Nb($.fs,w,n,{contextPack:j,planPacket:L,patchVerdict:C,reviewPacket:I}),x={artifacts:nb($.fs,m,w,n,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:n,createdAt:W,runtimeLink:z??void 0,taskId:b.taskId,verdict:V};return await Fb($.fs,w,n,x),await bn($.fs,w,gj({contextPack:j,createdAt:W,envelope:x,reviewPacket:I,verifyInput:b,workspace:m})),{contextPack:j,planPacket:L,patchVerdict:C,reviewPacket:I,historyDir:F}}function G4($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return X4($.verdict,b)}function X4($,b){if(!b)return $;return hj($)<=hj(b)?$:b}function hj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function Y4($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function H4($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function q4($,b,A){if(!$.runCommand)return[];let m=[];for(let n of b){let W=await $.runCommand(n,{cwd:A});m.push({id:`smoke:${n}`,status:W.exitCode===0?"pass":"fail",detail:W.exitCode===0?`Passed: ${n}`:`Failed (${W.exitCode}): ${n}`})}return m}m0();var yn={};P(yn,{generateWorkflowSpec:()=>Jw,generateWorkflowRunnerTemplate:()=>EA,generateWorkflowDevkitWorkflowTemplate:()=>zA,generateWorkflowDevkitStreamRouteTemplate:()=>CA,generateWorkflowDevkitStartRouteTemplate:()=>LA,generateWorkflowDevkitGenericTemplate:()=>IA,generateWorkflowDevkitFollowUpRouteTemplate:()=>RA,generateVisualizationSpec:()=>oW,generateTranslationSpec:()=>dW,generateThemeSpec:()=>Vw,generateTestTemplate:()=>Sw,generateTestSpec:()=>cW,generateTelemetrySpec:()=>Ow,generateProductIntentSpec:()=>tW,generatePresentationSpec:()=>qw,generatePolicySpec:()=>hW,generateOperationSpec:()=>Hw,generateMigrationSpec:()=>Yw,generateKnowledgeSpaceSpec:()=>Gw,generateJobSpec:()=>uW,generateIntegrationSpec:()=>Zw,generateHarnessSuiteSpec:()=>aW,generateHarnessScenarioSpec:()=>pW,generateHandlerTemplate:()=>yw,generateFormSpec:()=>jw,generateFeatureSpec:()=>ww,generateExperimentSpec:()=>Ww,generateExampleSpec:()=>iW,generateEventSpec:()=>nw,generateDataViewSpec:()=>mw,generateDataViewRendererTemplate:()=>_A,generateComponentTemplate:()=>Bw,generateCapabilitySpec:()=>fW,generateAppBlueprintSpec:()=>Aw,generateAgentSpec:()=>lW});m0();class uj{ai;templates=yn;constructor($){this.ai=new A0($)}}function v_($){return new uj($)}import{scanSpecSource as C4}from"@contractspec/module.workspace";function oj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function h_($,b,A={}){let{fs:m,logger:n}=b,W=await m.exists($);if(!W&&!A.force)return{specPath:$,specInfo:oj($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let w=oj($),j;if(W)try{let B=await m.readFile($);w=C4(B,$),j=w.key}catch{}let y=[];if(A.clean&&j)try{let B=await uA(j,{fs:m});for(let S of B)try{await m.remove(S.filePath),y.push(S.filePath),n.info(`Removed artifact: ${S.filePath}`)}catch{n.warn(`Could not remove artifact: ${S.filePath}`)}}catch{n.warn("Could not discover implementations for cleanup")}if(W)await m.remove($),n.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:w,deleted:!0,cleanedFiles:y,errors:[]}}import{computeSemanticDiff as I4}from"@contractspec/module.workspace";async function u_($,b,A,m={}){let{fs:n,git:W}=A;if(!await n.exists($))throw Error(`Spec file not found: ${$}`);let j=await n.readFile($),y,B;if(m.baseline)y=await W.showFile(m.baseline,$),B=`${m.baseline}:${$}`;else{if(!await n.exists(b))throw Error(`Spec file not found: ${b}`);y=await n.readFile(b),B=b}let S=I4(j,$,y,B,{breakingOnly:m.breakingOnly});return{spec1:$,spec2:B,differences:S}}s();import{openApiForRegistry as E4}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Bn}from"@contractspec/lib.contracts-spec/operations";async function M4($,b){let{fs:A,logger:m}=b,{registryPath:n,outputPath:W="./openapi.json"}=$;m.info("Loading registry...",{registryPath:n});let w=await x4(n,A);m.info("Generating OpenAPI document...");let j=E4(w,{title:$.title,version:$.version,description:$.description,servers:$.servers}),y=JSON.stringify(j,null,2)+`
|
|
1989
|
+
`,B=A.resolve(W);return await A.mkdir(A.dirname(B)),await A.writeFile(B,y),m.info(`OpenAPI document written to ${B}`),{document:j,outputPath:B,json:y}}async function x4($,b){let m=await import(b.resolve($));if(m instanceof Bn)return m;if(m.registry instanceof Bn)return m.registry;let n=typeof m.createRegistry==="function"?m.createRegistry:typeof m.default==="function"?m.default:void 0;if(n){let W=await n();if(W instanceof Bn)return W}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as T4,parseOpenApi as D4}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Sn,dirname as ij,join as Wb}from"path";function N4($,b,A){if(b.outputDir)return b.outputDir;let{outputDir:m,conventions:n}=A;switch($){case"operation":return Wb(m,n.operations.split("|")[0]??"operations");case"event":return Wb(m,n.events);case"model":return Wb(m,"models");default:return m}}async function lj($,b,A){let{fs:m,logger:n}=A,{source:W,prefix:w,tags:j,exclude:y,defaultStability:B,defaultOwners:S,defaultAuth:Q,dryRun:Z=!1}=b;n.info(`Importing from OpenAPI: ${W}`);let G=await D4(W,{fetch:globalThis.fetch,readFile:(J)=>m.readFile(J)});if(G.warnings.length>0)for(let J of G.warnings)n.warn(`Parse warning: ${J}`);n.info(`Parsed ${G.operations.length} operations from ${G.info.title} v${G.info.version}`);let X=T4(G,$,{prefix:w,tags:j,exclude:y,defaultStability:B,defaultOwners:S,defaultAuth:Q});n.info(`Import result: ${X.summary.imported} imported, ${X.summary.skipped} skipped, ${X.summary.errors} errors`);let Y=[],V=[],O=[],K=new Map;for(let J of X.operationSpecs){let _="operation",H=null;if(J.code.includes("defineEvent("))_="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("))_="model";else _="operation",H=J.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let q=N4(_,b,$),U=Wb(q,J.fileName);if(!H&&_==="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)n.info(`[DRY RUN] Would create: ${U}`);else{let z=ij(U);if(!await m.exists(z))await m.mkdir(z);await m.writeFile(U,J.code),n.info(`Created: ${U}`)}if(Y.push({path:U,operationId:J.source.sourceId,specName:J.fileName.replace(".ts","")}),H){let z=ij(U),L=K.get(z)||[];L.push({file:Sn(U),name:H[1],type:_}),K.set(z,L)}}if(!Z&&Y.length>0)for(let[J,_]of K.entries()){if(_.length===0)continue;let H=_.map((x)=>x.type),q=H.every((x)=>x==="operation"),U=H.every((x)=>x==="event"),z=H.every((x)=>x==="model"),L=`/**
|
|
1671
1990
|
* Auto-generated registry file.
|
|
1672
1991
|
*/
|
|
1673
|
-
`;
|
|
1674
|
-
`}),
|
|
1675
|
-
`;let
|
|
1992
|
+
`;_.forEach((x)=>{let h=`./${Sn(x.file,".ts")}`;L+=`import { ${x.name} } from '${h}';
|
|
1993
|
+
`}),L+=`
|
|
1994
|
+
`;let I=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1676
1995
|
|
|
1677
|
-
`,
|
|
1678
|
-
`,
|
|
1679
|
-
`}),
|
|
1996
|
+
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
1997
|
+
`,_.forEach((x)=>{L+=`operationRegistry.register(${x.name});
|
|
1998
|
+
`}),I=!0;else if(U)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
1680
1999
|
|
|
1681
|
-
`,
|
|
1682
|
-
`,
|
|
1683
|
-
`}),
|
|
2000
|
+
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2001
|
+
`,_.forEach((x)=>{L+=`eventRegistry.register(${x.name});
|
|
2002
|
+
`}),I=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
1684
2003
|
|
|
1685
|
-
`,
|
|
1686
|
-
`,
|
|
1687
|
-
`}),
|
|
2004
|
+
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2005
|
+
`,_.forEach((x)=>{L+=`modelRegistry.register(${x.name});
|
|
2006
|
+
`}),I=!0;if(I){let x=Wb(J,"registry.ts");await m.writeFile(x,L),n.info(`Created/Updated registry: ${x}`)}let C=`/**
|
|
1688
2007
|
* Auto-generated barrel file.
|
|
1689
2008
|
*/
|
|
1690
2009
|
|
|
1691
|
-
`;if(
|
|
1692
|
-
`}),C
|
|
1693
|
-
`;let
|
|
1694
|
-
{ key: '${
|
|
2010
|
+
`;if(_.forEach((x)=>{let h=`./${Sn(x.file,".ts")}`;C+=`export * from '${h}';
|
|
2011
|
+
`}),I)C+=`export * from './registry';
|
|
2012
|
+
`;let F=Wb(J,"index.ts");await m.writeFile(F,C),n.info(`Created/Updated index: ${F}`)}for(let J of X.skipped)V.push({operationId:J.sourceId,reason:J.reason}),n.debug(`Skipped: ${J.sourceId} - ${J.reason}`);for(let J of X.errors)O.push({operationId:J.sourceId,error:J.error}),n.error(`Error: ${J.sourceId} - ${J.error}`);return{imported:X.summary.imported,skipped:X.summary.skipped,errors:X.summary.errors,files:Y,skippedOperations:V,errorMessages:O}}import{importFromOpenApi as F4,parseOpenApi as v4}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as g4,join as k4}from"path";async function nU($,b,A){let{fs:m,logger:n}=A,{sources:W,sourceName:w,interactive:j,force:y,dryRun:B}=$,{outputDir:S}=b,Q=W??b.openapi?.sources??[];if(w){if(Q=Q.filter((G)=>G.name===w),Q.length===0)throw Error(`Source not found: ${w}`)}if(Q.length===0)return n.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 G of Q){n.info(`Syncing with source: ${G.name}`);let X=G.url??G.file;if(!X){n.warn(`Source ${G.name} has no url or file configured`);continue}let Y=await v4(X,{fetch:globalThis.fetch,readFile:(O)=>m.readFile(O)});n.info(`Parsed ${Y.operations.length} operations from ${G.name}`);let V=F4(Y,b,{prefix:G.prefix,tags:G.tags,exclude:G.exclude,defaultStability:G.defaultStability,defaultAuth:G.defaultAuth});for(let O of V.operationSpecs){let K=k4(S,O.fileName);if(!await m.exists(K)){if(!B){let _=g4(K);await m.mkdir(_),await m.writeFile(K,O.code)}Z.added++,Z.changes.push({operationId:O.source.sourceId,action:"added",path:K}),n.info(`Added: ${O.source.sourceId}`)}else if(await m.readFile(K)===O.code)Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K});else if(y==="openapi"){if(!B)await m.writeFile(K,O.code);Z.updated++,Z.changes.push({operationId:O.source.sourceId,action:"updated",path:K}),n.info(`Updated: ${O.source.sourceId}`)}else if(y==="contractspec")Z.unchanged++,Z.changes.push({operationId:O.source.sourceId,action:"unchanged",path:K}),n.info(`Kept: ${O.source.sourceId}`);else if(j)Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),n.warn(`Conflict: ${O.source.sourceId} - needs resolution`);else Z.conflicts++,Z.changes.push({operationId:O.source.sourceId,action:"conflict",path:K}),n.warn(`Conflict: ${O.source.sourceId}`)}}return n.info(`Sync complete: ${Z.added} added, ${Z.updated} updated, ${Z.unchanged} unchanged, ${Z.conflicts} conflicts`),Z}import{parseOpenApi as P4}from"@contractspec/lib.contracts-transformers/openapi";async function jU($,b){let{fs:A,logger:m}=b,{specPath:n,openApiSource:W,ignoreDescriptions:w,ignoreTags:j,ignoreTransport:y}=$;m.info(`Validating specs against OpenAPI: ${W}`);let B=await P4(W,{fetch:globalThis.fetch,readFile:(O)=>A.readFile(O)});m.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,G=0,X=await A.stat(n),Y=[];if(X.isDirectory){let O=await A.glob({pattern:"**/*.ts",cwd:n,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});Y.push(...O)}else Y.push(n);m.info(`Found ${Y.length} spec files to validate`);for(let O of Y)try{let K=await A.readFile(O),J=K.match(/operationId:\s*['"]([^'"]+)['"]/)||K.match(/name:\s*['"]([^'"]+)['"]/)||K.match(/export\s+const\s+(\w+)Spec\s*=/);if(!J||!J[1]){m.debug(`Could not extract operationId from ${O}`);continue}let _=J[1];Z++;let H;if(H=S.get(_),!H){let z=_.replace(/([A-Z])/g,"_$1").toLowerCase();H=S.get(z)}if(!H){for(let[z,L]of S)if(z.toLowerCase().includes(_.toLowerCase())||_.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: ${_}`}]}),G++;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(!y){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(!y){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 U=q.length===0;if(!U)G++;Q.push({specPath:O,operationId:H.operationId,valid:U,diffs:q})}catch(K){m.error(`Error validating ${O}: ${K}`),Q.push({specPath:O,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${K instanceof Error?K.message:String(K)}`}]}),G++}let V=G===0;return m.info(`Validation ${V?"passed":"failed"}: ${Z} specs checked, ${G} with differences`),{valid:V,specsValidated:Z,specsWithDiffs:G,results:Q}}async function qU($,b,A){let{fs:m,logger:n}=$,{source:W,outputDir:w}=b,j=m.resolve(A??process.cwd(),W);if(!await m.exists(j))throw Error(`Source file not found: ${j}`);let B={...await g(m,A),outputDir:w};return n.info(`Extracting contracts from ${j} to ${w}`),lj(B,{source:j,outputDir:w,dryRun:!1},$)}var pj={};P(pj,{validateFeatureRefs:()=>h4,getArrayNameForSpecType:()=>tj,detectFeatureContext:()=>r4,computeAddSpecEdit:()=>f4});function r4($,b){let A=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],m=null;for(let{type:Q,regex:Z,specType:G}of A){let X;Z.lastIndex=0;while((X=Z.exec($))!==null)if(!m||X.index>m.index)m={type:Q,specType:G,index:X.index}}if(!m)return null;let n=$.slice(m.index)+b,W=m.type;new RegExp(`${W}\\s*:\\s*\\[`).exec(n);let j=$.slice(m.index),y=0,B=!1,S="";for(let Q=0;Q<j.length;Q++){let Z=j[Q],G=Q>0?j[Q-1]:"";if((Z==='"'||Z==="'"||Z==="`")&&G!=="\\"){if(!B)B=!0,S=Z;else if(Z===S)B=!1;continue}if(B)continue;if(Z==="[")y++;else if(Z==="]"){if(y--,y===0)return null}}if(y>0)return{type:m.type,specType:m.specType};return null}function f4($,b){let A=tj(b.type),n=new RegExp(`${A}\\s*:\\s*\\[`,"g").exec($);if(n){let W=n.index+n[0].length,w=typeof b.version==="string"?`'${b.version}'`:b.version,j=`
|
|
2013
|
+
{ key: '${b.key}', version: ${w} },`;return{index:W,text:j}}return null}function tj($){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 h4($,b){let A=[],m=(n,W,w)=>{for(let j of n){let y=`${j.key}.v${j.version}`;if(!W.has(y))A.push({key:j.key,version:j.version,type:w,message:`${w} ${j.key}.v${j.version} not found`})}};return m($.operations,b.operations,"Operation"),m($.events,b.events,"Event"),m($.presentations,b.presentations,"Presentation"),m($.experiments,b.experiments,"Experiment"),A}var $y={};P($y,{removeReferenceStrategy:()=>j0,implementSkeletonStrategy:()=>w0,implementAiStrategy:()=>W0,generateFixLinks:()=>c4,FixService:()=>sj,FIX_STRATEGY_STABILITY:()=>db,FIX_STRATEGY_LABELS:()=>t4,CiOutputSchema:()=>w6});function c4($,b){let A=[];if(!$.ref||!$.file)return A;if(b.includeCli)A.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(b.includeVscode){let m=$.file.startsWith("/")?$.file:`/${$.file}`,n=$.ref,W=n.line||1,w=n.column||1;A.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${m}:${W}:${w}`})}if(b.includeGithubIssue&&b.repository){let m=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),n=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
1695
2014
|
|
|
1696
2015
|
> ${$.message}
|
|
1697
2016
|
|
|
1698
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
1699
|
-
`)}function
|
|
2017
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);A.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${b.repository}/issues/new?title=${m}&body=${n}`})}return A}import p4 from"node:path";function L$($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function R$($,b){let A=$.enrichment?.owners?.length?$.enrichment.owners.map((w)=>`'${w}'`).join(", "):"'@team'",m=$.enrichment?.tags?.length?$.enrichment.tags.map((w)=>`'${w}'`).join(", "):"",n=$.description||`TODO: Add description for ${$.key}`,W=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(b)Object.entries(b).forEach(([w,j])=>{if(j!==void 0)W.push(`${w}: ${j}`)});return W.push(`owners: [${A}]`),W.push(`tags: [${m}]`),W.push(`description: '${n}'`),W.join(`,
|
|
2018
|
+
`)}function rb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"Spec",m=R$($,{kind:"'api'"});return`/**
|
|
1700
2019
|
* Capability: ${$.key}
|
|
1701
2020
|
*
|
|
1702
2021
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1707,9 +2026,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",labe
|
|
|
1707
2026
|
|
|
1708
2027
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
1709
2028
|
|
|
1710
|
-
export const ${
|
|
2029
|
+
export const ${A} = defineCapability({
|
|
1711
2030
|
meta: {
|
|
1712
|
-
${
|
|
2031
|
+
${m}
|
|
1713
2032
|
},
|
|
1714
2033
|
|
|
1715
2034
|
provides: [
|
|
@@ -1733,7 +2052,7 @@ export const ${j} = defineCapability({
|
|
|
1733
2052
|
// }
|
|
1734
2053
|
],
|
|
1735
2054
|
});
|
|
1736
|
-
`}function
|
|
2055
|
+
`}function fb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"EventSpec",m=A.replace("Spec","Payload"),n=R$($);return`/**
|
|
1737
2056
|
* Event: ${$.key}
|
|
1738
2057
|
*
|
|
1739
2058
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1746,8 +2065,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
1746
2065
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1747
2066
|
|
|
1748
2067
|
// TODO: Define event payload schema
|
|
1749
|
-
export const ${
|
|
1750
|
-
name: '${
|
|
2068
|
+
export const ${m} = new SchemaModel({
|
|
2069
|
+
name: '${m}',
|
|
1751
2070
|
description: 'Payload for ${$.key} event',
|
|
1752
2071
|
fields: {
|
|
1753
2072
|
// Add your payload fields here
|
|
@@ -1757,12 +2076,12 @@ export const ${A} = new SchemaModel({
|
|
|
1757
2076
|
},
|
|
1758
2077
|
});
|
|
1759
2078
|
|
|
1760
|
-
export const ${
|
|
2079
|
+
export const ${A} = defineEvent({
|
|
1761
2080
|
meta: {
|
|
1762
|
-
${
|
|
2081
|
+
${n}
|
|
1763
2082
|
},
|
|
1764
2083
|
|
|
1765
|
-
payload: ${
|
|
2084
|
+
payload: ${m},
|
|
1766
2085
|
|
|
1767
2086
|
// TODO: Specify PII fields if any
|
|
1768
2087
|
// piiFields: ['user.email'],
|
|
@@ -1773,7 +2092,7 @@ export const ${j} = defineEvent({
|
|
|
1773
2092
|
// policy: 'archive',
|
|
1774
2093
|
// },
|
|
1775
2094
|
});
|
|
1776
|
-
`}function
|
|
2095
|
+
`}function d4($){let b=$.toLowerCase(),A=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let m of A)if(b.includes(m))return"query";return"command"}function hb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"Spec",m=A.replace("Spec","Input"),n=A.replace("Spec","Output"),W=d4($.key),w=W==="query"?"defineQuery":"defineCommand",j=$.enrichment?.goal||"TODO: Define the business goal",y=$.enrichment?.context||"TODO: Provide context",B=R$($,{goal:`'${j}'`,context:`'${y}'`});return`/**
|
|
1777
2096
|
* Operation: ${$.key}
|
|
1778
2097
|
*
|
|
1779
2098
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1782,12 +2101,12 @@ export const ${j} = defineEvent({
|
|
|
1782
2101
|
* Referenced by feature: ${$.featureKey||"unknown"}
|
|
1783
2102
|
*/
|
|
1784
2103
|
|
|
1785
|
-
import { ${
|
|
2104
|
+
import { ${w} } from '@contractspec/lib.contracts-spec';
|
|
1786
2105
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1787
2106
|
|
|
1788
2107
|
// TODO: Define input schema
|
|
1789
|
-
export const ${
|
|
1790
|
-
name: '${
|
|
2108
|
+
export const ${m} = new SchemaModel({
|
|
2109
|
+
name: '${m}',
|
|
1791
2110
|
description: 'Input for ${$.key}',
|
|
1792
2111
|
fields: {
|
|
1793
2112
|
// Add your input fields here
|
|
@@ -1796,8 +2115,8 @@ export const ${A} = new SchemaModel({
|
|
|
1796
2115
|
});
|
|
1797
2116
|
|
|
1798
2117
|
// TODO: Define output schema
|
|
1799
|
-
export const ${
|
|
1800
|
-
name: '${
|
|
2118
|
+
export const ${n} = new SchemaModel({
|
|
2119
|
+
name: '${n}',
|
|
1801
2120
|
description: 'Output for ${$.key}',
|
|
1802
2121
|
fields: {
|
|
1803
2122
|
// Add your output fields here
|
|
@@ -1805,14 +2124,14 @@ export const ${Q} = new SchemaModel({
|
|
|
1805
2124
|
},
|
|
1806
2125
|
});
|
|
1807
2126
|
|
|
1808
|
-
export const ${
|
|
2127
|
+
export const ${A} = ${w}({
|
|
1809
2128
|
meta: {
|
|
1810
|
-
${
|
|
2129
|
+
${B}
|
|
1811
2130
|
},
|
|
1812
2131
|
|
|
1813
2132
|
io: {
|
|
1814
|
-
input: ${
|
|
1815
|
-
output: ${
|
|
2133
|
+
input: ${m},
|
|
2134
|
+
output: ${n},
|
|
1816
2135
|
errors: {
|
|
1817
2136
|
// TODO: Define possible errors
|
|
1818
2137
|
// EXAMPLE_ERROR: {
|
|
@@ -1834,7 +2153,7 @@ export const ${j} = ${X}({
|
|
|
1834
2153
|
},
|
|
1835
2154
|
|
|
1836
2155
|
transport: {
|
|
1837
|
-
rest: { method: '${
|
|
2156
|
+
rest: { method: '${W==="command"?"POST":"GET"}' },
|
|
1838
2157
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
1839
2158
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
1840
2159
|
},
|
|
@@ -1851,7 +2170,7 @@ export const ${j} = ${X}({
|
|
|
1851
2170
|
examples: [],
|
|
1852
2171
|
},
|
|
1853
2172
|
});
|
|
1854
|
-
`}function
|
|
2173
|
+
`}function u4($){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 cb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"PresentationSpec",m=u4($.key),n=R$($);return`/**
|
|
1855
2174
|
* Presentation: ${$.key}
|
|
1856
2175
|
*
|
|
1857
2176
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1862,12 +2181,12 @@ export const ${j} = ${X}({
|
|
|
1862
2181
|
|
|
1863
2182
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
1864
2183
|
|
|
1865
|
-
export const ${
|
|
2184
|
+
export const ${A} = definePresentation({
|
|
1866
2185
|
meta: {
|
|
1867
|
-
${
|
|
2186
|
+
${n}
|
|
1868
2187
|
},
|
|
1869
2188
|
|
|
1870
|
-
kind: '${
|
|
2189
|
+
kind: '${m}',
|
|
1871
2190
|
|
|
1872
2191
|
// TODO: Define content structure
|
|
1873
2192
|
content: {
|
|
@@ -1891,7 +2210,7 @@ export const ${j} = definePresentation({
|
|
|
1891
2210
|
// focusable: true,
|
|
1892
2211
|
// },
|
|
1893
2212
|
});
|
|
1894
|
-
`}import X$ from"node:path";function TW($,W){if(W.outputDir)return Nj(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=i2($.featureFile);if(j)return Nj(j,$.ref.key,$.specType)}return Nj(X$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function i2($){let W=X$.dirname($),j=X$.parse($).root,A=0;while(W!==j&&A<50){if(X$.basename(W)==="src")return W;W=X$.dirname(W),A++}W=X$.dirname($),A=0;while(W!==j&&A<50)W=X$.dirname(W),A++;let Q=$.lastIndexOf(`${X$.sep}src${X$.sep}`);if(Q!==-1)return $.substring(0,Q+5);return null}function Nj($,W,j){let A=W.replace(/\./g,"-").toLowerCase(),Q=p2(j),Z=t2(j);return X$.join($,Z,`${A}${Q}`)}function p2($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function t2($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var a2={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},N0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function FW($,W,j){let{fs:A,logger:Q}=j,{ref:Z,specType:X,featureKey:Y}=$;try{let B={key:Z.key,version:Z.version,specType:X,stability:N0["implement-ai"],featureKey:Y},q=B;if(W.aiConfig)try{q=await e2(B,W,Q)}catch(J){Q.warn("AI enrichment failed, falling back to skeleton",{error:J instanceof Error?J.message:String(J)})}else Q.info("No AI config provided, using skeleton with experimental stability");let H=jY(q);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=TW($,W),G=[];if(!W.dryRun){let J=s2.dirname(V);await A.mkdir(J),await A.writeFile(V,H),G.push({path:V,action:"created"})}else G.push({path:V,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:G}}catch(B){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:B instanceof Error?B.message:String(B)}}}async function e2($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Q}=await Promise.resolve().then(() => (DW(),D4)),Z=$Y(W),X=new Q(Z),Y=$.specType==="operation"?"command":$.specType,B=`${P4($.specType)} for ${$.key}`;if($.specType==="operation"){let q=await X.generateOperationSpec(B,Y);return{...$,description:q.description,enrichment:{goal:q.goal,context:q.context,owners:q.owners,tags:q.tags}}}if($.specType==="event"){let q=await X.generateEventSpec(B);return{...$,description:q.description,enrichment:{goal:`Emit ${$.key} event`,context:q.description,owners:["@team"],tags:q.tags}}}}catch(Q){j.warn("AIGenerator call failed, falling back to heuristics",{error:Q instanceof Error?Q.message:String(Q)})}let A=WY($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function $Y($){let W=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[W?.provider??"openai"]??"openai",aiModel:W?.model??"gpt-4-turbo",customApiKey:W?.apiKey??"",customEndpoint:W?.endpoint??""}}function WY($,W){let j=$.split("."),A=j[0]||"unknown",Q=j.slice(1).join(" ").replace(/_/g," "),Z=[A],X=Q.toLowerCase().split(" "),B=["auth","user","admin","api","data","search","create","update","delete"].filter((q)=>X.some((H)=>H.includes(q)));return{description:`${P4(W)} for ${A} ${Q}`,goal:`Enable ${Q} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...Z,...B]}}function jY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}function P4($){return $.charAt(0).toUpperCase()+$.slice(1)}import AY from"node:path";async function xW($,W,j){let{fs:A}=j,{ref:Q,specType:Z,featureKey:X}=$;try{let Y={key:Q.key,version:Q.version,specType:Z,stability:N0["implement-skeleton"],description:`Skeleton spec for ${Q.key}`,featureKey:X},B=QY(Y);if(!B)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${Z}`};let q=TW($,W),H=[];if(!W.dryRun){let V=AY.dirname(q);await A.mkdir(V),await A.writeFile(q,B),H.push({path:q,action:"created"})}else H.push({path:q,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function QY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}async function yW($,W,j){let{fs:A}=j,{ref:Q,featureFile:Z,specType:X}=$;try{let Y=await A.readFile(Z),B=Y,q=ZY(Y,Q,X);if(q===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Q.key}.v${Q.version} in ${Z}`};let H=[];if(!W.dryRun)await A.writeFile(Z,q),H.push({path:Z,action:"modified",previousContent:B});else H.push({path:Z,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function ZY($,W,j){if(!XY(j))return $;let Q=k4(W.key),Z=k4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Q}['"],\\s*version:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${Z}['"],\\s*key:\\s*['"]${Q}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let B of X)Y=Y.replace(B,"");return Y=YY(Y),Y}function XY($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function k4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YY($){return $.replace(/,(\s*)\]/g,"$1]")}class h4{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(W,j)=>yW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(W,j)=>xW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(W,j)=>FW(W,j,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let W=[];if($.type==="unresolved-ref")W.push("remove-reference"),W.push("implement-skeleton"),W.push("implement-ai");else if($.type==="broken-link")W.push("remove-reference"),W.push("implement-skeleton");return W}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,W){let j=this.strategies.get(W.strategy);if(!j)return{success:!1,strategy:W.strategy,issue:$,filesChanged:[],error:`Strategy ${W.strategy} not found`};return this.adapters.logger.info(`Applying fix ${W.strategy} for ${$.ref.key}`,{dryRun:W.dryRun}),j.fix($,W)}async batchFix($){let W=[],j=0,A=0;for(let Q of $.issues)try{let Z=await this.fixIssue(Q,$.options);if(W.push(Z),Z.success)j++;else A++}catch(Z){A++,W.push({success:!1,strategy:$.options.strategy,issue:Q,filesChanged:[],error:Z instanceof Error?Z.message:String(Z)})}return{total:$.issues.length,succeeded:j,failed:A,results:W}}async scanAndGetFixables($={}){return(await zW(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((j)=>this.getToFix(j)).filter((j)=>j!==null)}getToFix($){let W=this.getStrategiesForIssue($);if(W.length===0)return null;let j=this.parseFixableIssue($);if(!j)return null;return{...j,availableStrategies:W,strategies:[]}}resolveStrategy($,W){let{forceStrategy:j,preferAi:A,select:Q}=W;if(j)return Promise.resolve(j);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof Q==="function")return Q($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((W)=>{return this.getToFix(W)}).filter((W)=>W!==null)}}import{z as o$}from"zod";var BY=o$.union([o$.array(o$.unknown()),o$.object({issues:o$.array(o$.unknown())}).transform(($)=>$.issues)]);import{exec as qY}from"node:child_process";import{promisify as HY}from"node:util";var VY=HY(qY),f4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function lL($,W,j={}){if($.length===0)return;let A=j.cwd??process.cwd(),Q=f4[j.type??"biome"]??f4.biome,Z=50;for(let X=0;X<$.length;X+=Z){let B=$.slice(X,X+Z).map((q)=>`"${q}"`).join(" ");try{await VY(`${Q} ${B}`,{cwd:A})}catch(q){}}}import _$ from"path";async function tL($,W){let j=_$.join(W,"contracts"),A=_$.join(W,"generated"),Q=_$.join(A,"docs"),Z=await $.fs.exists(j),X=await $.fs.exists(A);if(!Z)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await $$($,{pattern:"contracts/**/*.ts"}),B=[];if(X)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts"),w=_$.join(Q,`${b}.md`);if(!await $.fs.exists(w))B.push(b)}else if(Y.length>0)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts");B.push(b)}let q=_$.join(j,"index.ts"),H=_$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(q),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:B,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var c4={};h(c4,{runHook:()=>u4,getAvailableHooks:()=>d4});import{exec as GY}from"node:child_process";import{promisify as JY}from"node:util";var bY=JY(GY);async function u4($,W){let{fs:j,logger:A}=$,{hookName:Q,dryRun:Z=!1}=W,X=D(W.workspaceRoot);A.info(`Running hook: ${Q}`,{workspaceRoot:X,dryRun:Z});let Y=await n4(j,X);if(!Y)return{hookName:Q,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let B=Y[Q];if(!B||B.length===0)return{hookName:Q,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Q}`};A.info(`Found ${B.length} command(s) for ${Q}`);let q=[],H=!0;for(let G of B){if(Z){A.info(`[DRY RUN] Would execute: ${G}`),q.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${G}`);try{let{stdout:J,stderr:b}=await bY(G,{cwd:X,timeout:300000});q.push({command:G,success:!0,exitCode:0,stdout:J,stderr:b}),A.info(`✓ ${G}`)}catch(J){H=!1;let b=J;q.push({command:G,success:!1,exitCode:b.code??1,stdout:b.stdout??"",stderr:b.stderr??b.message??String(J)}),A.error(`✗ ${G}`,{exitCode:b.code,stderr:b.stderr});break}}let V=q.filter((G)=>G.success).length;return{hookName:Q,success:H,commandResults:q,totalCommands:B.length,successfulCommands:V,summary:H?`✓ All ${B.length} command(s) passed`:`✗ ${V}/${B.length} command(s) passed`}}async function d4($,W){let j=await n4($.fs,W);return j?Object.keys(j):[]}async function n4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let A=await $.readFile(j);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as wY,extractFromProject as KY}from"@contractspec/lib.source-extractors";import{generateOperations as _Y,generateRegistry as zY,generateSchemas as UY}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as LY}from"@contractspec/lib.source-extractors/extractors";import{dirname as OY,join as Rj}from"path";async function SY($,W,j,A){let{fs:Q,logger:Z}=j,X=A??process.cwd();LY(),Z.info(`Scanning source code in ${X}...`);let Y={readFile:(O)=>Q.readFile(O),glob:(O,K)=>Q.glob({pattern:O,cwd:K?.cwd}),exists:(O)=>Q.exists(O)},B=await wY(X,{readFile:(O)=>Q.readFile(O),glob:(O)=>Q.glob({pattern:O})});if(B.frameworks.length===0)return Z.warn("No supported frameworks detected"),{success:!1,report:IY(),errors:["No supported frameworks detected in project"]};Z.info(`Detected frameworks: ${B.frameworks.map((O)=>O.name).join(", ")}`);let{extractorRegistry:q}=await import("@contractspec/lib.source-extractors");for(let O of q.getAll())if("setFs"in O&&typeof O.setFs==="function")O.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await KY(B,H);if(!V.success||!V.ir)return{success:!1,report:MY(V.errors??[]),errors:V.errors?.map((O)=>O.message)};let G=V.ir;if(Z.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:EY(G)};let J=W.outputDir??Rj($.outputDir,"generated"),b={outputDir:J,defaultAuth:"user"},w=_Y(G,b),L=UY(G,b),z=zY(w),S=[...w,...L,z];if(!W.dryRun)for(let O of S){let K=Rj(J,O.path),_=OY(K);if(!await Q.exists(_))await Q.mkdir(_);await Q.writeFile(K,O.content),Z.info(`Created: ${K}`)}else for(let O of S)Z.info(`[DRY RUN] Would create: ${Rj(J,O.path)}`);let U={files:S,operationsGenerated:w.length,schemasGenerated:L.length,warnings:[]};return{success:!0,ir:G,generation:U,report:NY(G,U,W)}}function IY(){return`# Import Report
|
|
2213
|
+
`}import G$ from"node:path";function n0($,b){if(b.outputDir)return Qn(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=o4($.featureFile);if(A)return Qn(A,$.ref.key,$.specType)}return Qn(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function o4($){let b=G$.dirname($),A=G$.parse($).root,m=0;while(b!==A&&m<50){if(G$.basename(b)==="src")return b;b=G$.dirname(b),m++}b=G$.dirname($),m=0;while(b!==A&&m<50)b=G$.dirname(b),m++;let n=$.lastIndexOf(`${G$.sep}src${G$.sep}`);if(n!==-1)return $.substring(0,n+5);return null}function Qn($,b,A){let m=b.replace(/\./g,"-").toLowerCase(),n=i4(A),W=l4(A);return G$.join($,W,`${m}${n}`)}function i4($){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 l4($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var t4={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},db={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function W0($,b,A){let{fs:m,logger:n}=A,{ref:W,specType:w,featureKey:j}=$;try{let y={key:W.key,version:W.version,specType:w,stability:db["implement-ai"],featureKey:j},B=y;if(b.aiConfig)try{B=await a4(y,b,n)}catch(G){n.warn("AI enrichment failed, falling back to skeleton",{error:G instanceof Error?G.message:String(G)})}else n.info("No AI config provided, using skeleton with experimental stability");let S=$6(B);if(!S)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${w}`};let Q=n0($,b),Z=[];if(!b.dryRun){let G=p4.dirname(Q);await m.mkdir(G),await m.writeFile(Q,S),Z.push({path:Q,action:"created"})}else Z.push({path:Q,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:Z}}catch(y){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:y instanceof Error?y.message:String(y)}}}async function a4($,b,A){if(A.info("Generating AI content for spec",{key:$.key,type:$.specType}),b.aiConfig)try{let{AIGenerator:n}=await Promise.resolve().then(() => (m0(),dj)),W=e4(b),w=new n(W),j=$.specType==="operation"?"command":$.specType,y=`${aj($.specType)} for ${$.key}`;if($.specType==="operation"){let B=await w.generateOperationSpec(y,j);return{...$,description:B.description,enrichment:{goal:B.goal,context:B.context,owners:B.owners,tags:B.tags}}}if($.specType==="event"){let B=await w.generateEventSpec(y);return{...$,description:B.description,enrichment:{goal:`Emit ${$.key} event`,context:B.description,owners:["@team"],tags:B.tags}}}}catch(n){A.warn("AIGenerator call failed, falling back to heuristics",{error:n instanceof Error?n.message:String(n)})}let m=s4($.key,$.specType);return{...$,description:m.description,enrichment:{goal:m.goal,context:m.context,owners:["@team"],tags:m.tags}}}function e4($){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 s4($,b){let A=$.split("."),m=A[0]||"unknown",n=A.slice(1).join(" ").replace(/_/g," "),W=[m],w=n.toLowerCase().split(" "),y=["auth","user","admin","api","data","search","create","update","delete"].filter((B)=>w.some((S)=>S.includes(B)));return{description:`${aj(b)} for ${m} ${n}`,goal:`Enable ${n} functionality in the ${m} domain`,context:`Part of the ${m} feature set. Generated by ContractSpec AI fix.`,tags:[...W,...y]}}function $6($){switch($.specType){case"operation":return hb($);case"event":return fb($);case"presentation":return cb($);case"capability":return rb($);default:return}}function aj($){return $.charAt(0).toUpperCase()+$.slice(1)}import b6 from"node:path";async function w0($,b,A){let{fs:m}=A,{ref:n,specType:W,featureKey:w}=$;try{let j={key:n.key,version:n.version,specType:W,stability:db["implement-skeleton"],description:`Skeleton spec for ${n.key}`,featureKey:w},y=A6(j);if(!y)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${W}`};let B=n0($,b),S=[];if(!b.dryRun){let Q=b6.dirname(B);await m.mkdir(Q),await m.writeFile(B,y),S.push({path:B,action:"created"})}else S.push({path:B,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:S}}catch(j){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}function A6($){switch($.specType){case"operation":return hb($);case"event":return fb($);case"presentation":return cb($);case"capability":return rb($);default:return}}async function j0($,b,A){let{fs:m}=A,{ref:n,featureFile:W,specType:w}=$;try{let j=await m.readFile(W),y=j,B=m6(j,n,w);if(B===j)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${n.key}.v${n.version} in ${W}`};let S=[];if(!b.dryRun)await m.writeFile(W,B),S.push({path:W,action:"modified",previousContent:y});else S.push({path:W,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:S}}catch(j){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:j instanceof Error?j.message:String(j)}}}function m6($,b,A){if(!n6(A))return $;let n=ej(b.key),W=ej(b.version),w=[new RegExp(`\\{\\s*key:\\s*['"]${n}['"],\\s*version:\\s*['"]${W}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${W}['"],\\s*key:\\s*['"]${n}['"]\\s*\\},?\\s*`,"g")],j=$;for(let y of w)j=j.replace(y,"");return j=W6(j),j}function n6($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function ej($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W6($){return $.replace(/,(\s*)\]/g,"$1]")}class sj{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(b,A)=>j0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(b,A)=>w0(b,A,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(b,A)=>W0(b,A,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let b=[];if($.type==="unresolved-ref")b.push("remove-reference"),b.push("implement-skeleton"),b.push("implement-ai");else if($.type==="broken-link")b.push("remove-reference"),b.push("implement-skeleton");return b}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,b){let A=this.strategies.get(b.strategy);if(!A)return{success:!1,strategy:b.strategy,issue:$,filesChanged:[],error:`Strategy ${b.strategy} not found`};return this.adapters.logger.info(`Applying fix ${b.strategy} for ${$.ref.key}`,{dryRun:b.dryRun}),A.fix($,b)}async batchFix($){let b=[],A=0,m=0;for(let n of $.issues)try{let W=await this.fixIssue(n,$.options);if(b.push(W),W.success)A++;else m++}catch(W){m++,b.push({success:!1,strategy:$.options.strategy,issue:n,filesChanged:[],error:W instanceof Error?W.message:String(W)})}return{total:$.issues.length,succeeded:A,failed:m,results:b}}async scanAndGetFixables($={}){return(await oA(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((A)=>this.getToFix(A)).filter((A)=>A!==null)}getToFix($){let b=this.getStrategiesForIssue($);if(b.length===0)return null;let A=this.parseFixableIssue($);if(!A)return null;return{...A,availableStrategies:b,strategies:[]}}resolveStrategy($,b){let{forceStrategy:A,preferAi:m,select:n}=b;if(A)return Promise.resolve(A);if(m&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof n==="function")return n($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((b)=>{return this.getToFix(b)}).filter((b)=>b!==null)}}import{z as wb}from"zod";var w6=wb.union([wb.array(wb.unknown()),wb.object({issues:wb.array(wb.unknown())}).transform(($)=>$.issues)]);import{exec as j6}from"node:child_process";import{promisify as y6}from"node:util";var B6=y6(j6),by={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function Hz($,b,A={}){if($.length===0)return;let m=A.cwd??process.cwd(),n=by[A.type??"biome"]??by.biome,W=50;for(let w=0;w<$.length;w+=W){let y=$.slice(w,w+W).map((B)=>`"${B}"`).join(" ");try{await B6(`${n} ${y}`,{cwd:m})}catch(B){}}}import C$ from"path";async function Jz($,b){let A=C$.join(b,"contracts"),m=C$.join(b,"generated"),n=C$.join(m,"docs"),W=await $.fs.exists(A),w=await $.fs.exists(m);if(!W)return{hasContracts:!1,hasGenerated:w,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let j=await j$($,{pattern:"contracts/**/*.ts"}),y=[];if(w)for(let G of j){let X=G.key||C$.basename(G.filePath,".ts"),Y=C$.join(n,`${X}.md`);if(!await $.fs.exists(Y))y.push(X)}else if(j.length>0)for(let G of j){let X=G.key||C$.basename(G.filePath,".ts");y.push(X)}let B=C$.join(A,"index.ts"),S=C$.join(A,"registry.ts"),Q=j.length>0&&!await $.fs.exists(B),Z=j.length>0&&!await $.fs.exists(S);return{hasContracts:!0,hasGenerated:w,missingDocs:y,missingIndex:Q,missingRegistry:Z,totalSpecs:j.length}}var Wy={};P(Wy,{runHook:()=>Ay,getAvailableHooks:()=>my});import{exec as S6}from"node:child_process";import{promisify as Q6}from"node:util";var Z6=Q6(S6);async function Ay($,b){let{fs:A,logger:m}=$,{hookName:n,dryRun:W=!1}=b,w=M(b.workspaceRoot);m.info(`Running hook: ${n}`,{workspaceRoot:w,dryRun:W});let j=await ny(A,w);if(!j)return{hookName:n,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let y=j[n];if(!y||y.length===0)return{hookName:n,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${n}`};m.info(`Found ${y.length} command(s) for ${n}`);let B=[],S=!0;for(let Z of y){if(W){m.info(`[DRY RUN] Would execute: ${Z}`),B.push({command:Z,success:!0,exitCode:0,stdout:"",stderr:""});continue}m.info(`Executing: ${Z}`);try{let{stdout:G,stderr:X}=await Z6(Z,{cwd:w,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:G,stderr:X}),m.info(`✓ ${Z}`)}catch(G){S=!1;let X=G;B.push({command:Z,success:!1,exitCode:X.code??1,stdout:X.stdout??"",stderr:X.stderr??X.message??String(G)}),m.error(`✗ ${Z}`,{exitCode:X.code,stderr:X.stderr});break}}let Q=B.filter((Z)=>Z.success).length;return{hookName:n,success:S,commandResults:B,totalCommands:y.length,successfulCommands:Q,summary:S?`✓ All ${y.length} command(s) passed`:`✗ ${Q}/${y.length} command(s) passed`}}async function my($,b){let A=await ny($.fs,b);return A?Object.keys(A):[]}async function ny($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return null;try{let m=await $.readFile(A);return JSON.parse(m).hooks??null}catch{return null}}import{detectFramework as G6,extractFromProject as X6}from"@contractspec/lib.source-extractors";import{generateOperations as Y6,generateRegistry as H6,generateSchemas as q6}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as O6}from"@contractspec/lib.source-extractors/extractors";import{dirname as V6,join as Zn}from"path";async function J6($,b,A,m){let{fs:n,logger:W}=A,w=m??process.cwd();O6(),W.info(`Scanning source code in ${w}...`);let j={readFile:(_)=>n.readFile(_),glob:(_,H)=>n.glob({pattern:_,cwd:H?.cwd}),exists:(_)=>n.exists(_)},y=await G6(w,{readFile:(_)=>n.readFile(_),glob:(_)=>n.glob({pattern:_})});if(y.frameworks.length===0)return W.warn("No supported frameworks detected"),{success:!1,report:K6(),errors:["No supported frameworks detected in project"]};W.info(`Detected frameworks: ${y.frameworks.map((_)=>_.name).join(", ")}`);let{extractorRegistry:B}=await import("@contractspec/lib.source-extractors");for(let _ of B.getAll())if("setFs"in _&&typeof _.setFs==="function")_.setFs(j);let S={scope:b.scope,framework:b.framework},Q=await X6(y,S);if(!Q.success||!Q.ir)return{success:!1,report:_6(Q.errors??[]),errors:Q.errors?.map((_)=>_.message)};let Z=Q.ir;if(W.info(`Extracted ${Z.endpoints.length} endpoints, ${Z.schemas.length} schemas`),b.analyzeOnly)return{success:!0,ir:Z,report:U6(Z)};let G=b.outputDir??Zn($.outputDir,"generated"),X={outputDir:G,defaultAuth:"user"},Y=Y6(Z,X),V=q6(Z,X),O=H6(Y),K=[...Y,...V,O];if(!b.dryRun)for(let _ of K){let H=Zn(G,_.path),q=V6(H);if(!await n.exists(q))await n.mkdir(q);await n.writeFile(H,_.content),W.info(`Created: ${H}`)}else for(let _ of K)W.info(`[DRY RUN] Would create: ${Zn(G,_.path)}`);let J={files:K,operationsGenerated:Y.length,schemasGenerated:V.length,warnings:[]};return{success:!0,ir:Z,generation:J,report:z6(Z,J,b)}}function K6(){return`# Import Report
|
|
1895
2214
|
|
|
1896
2215
|
## ❌ No Supported Frameworks Detected
|
|
1897
2216
|
|
|
@@ -1908,13 +2227,13 @@ No supported frameworks were detected in the project.
|
|
|
1908
2227
|
- Next.js API Routes
|
|
1909
2228
|
|
|
1910
2229
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
1911
|
-
`}function
|
|
2230
|
+
`}function _6($){return`# Import Report
|
|
1912
2231
|
|
|
1913
2232
|
## ❌ Extraction Failed
|
|
1914
2233
|
|
|
1915
|
-
${$.map((
|
|
2234
|
+
${$.map((b)=>`- ${b.message}`).join(`
|
|
1916
2235
|
`)}
|
|
1917
|
-
`}function
|
|
2236
|
+
`}function U6($){return`# Import Analysis Report
|
|
1918
2237
|
|
|
1919
2238
|
## Summary
|
|
1920
2239
|
|
|
@@ -1934,19 +2253,19 @@ ${$.map((W)=>`- ${W.message}`).join(`
|
|
|
1934
2253
|
|
|
1935
2254
|
## Detected Frameworks
|
|
1936
2255
|
|
|
1937
|
-
${$.project.frameworks.map((
|
|
2256
|
+
${$.project.frameworks.map((b)=>`- ${b.name} (${b.confidence})`).join(`
|
|
1938
2257
|
`)}
|
|
1939
2258
|
|
|
1940
2259
|
## Endpoints
|
|
1941
2260
|
|
|
1942
|
-
${$.endpoints.map((
|
|
2261
|
+
${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).join(`
|
|
1943
2262
|
`)}
|
|
1944
2263
|
|
|
1945
2264
|
## Ambiguities (Require Review)
|
|
1946
2265
|
|
|
1947
|
-
${$.ambiguities.length>0?$.ambiguities.map((
|
|
2266
|
+
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
1948
2267
|
`):"None"}
|
|
1949
|
-
`}function
|
|
2268
|
+
`}function z6($,b,A){return`# Import Report${A.dryRun?" (Dry Run)":""}
|
|
1950
2269
|
|
|
1951
2270
|
## ✅ Import Successful
|
|
1952
2271
|
|
|
@@ -1958,9 +2277,9 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1958
2277
|
|
|
1959
2278
|
### Generation Summary
|
|
1960
2279
|
|
|
1961
|
-
- **Operations Generated**: ${
|
|
1962
|
-
- **Schemas Generated**: ${
|
|
1963
|
-
- **Total Files**: ${
|
|
2280
|
+
- **Operations Generated**: ${b.operationsGenerated}
|
|
2281
|
+
- **Schemas Generated**: ${b.schemasGenerated}
|
|
2282
|
+
- **Total Files**: ${b.files.length}
|
|
1964
2283
|
|
|
1965
2284
|
### Confidence Breakdown
|
|
1966
2285
|
|
|
@@ -1972,41 +2291,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1972
2291
|
|
|
1973
2292
|
### Next Steps
|
|
1974
2293
|
|
|
1975
|
-
1. Review generated contracts in \`${
|
|
2294
|
+
1. Review generated contracts in \`${A.outputDir??"generated/"}\`
|
|
1976
2295
|
2. Fill in TODO placeholders with business context
|
|
1977
2296
|
3. Run \`contractspec validate\` to verify contracts
|
|
1978
2297
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
1979
|
-
`}function
|
|
1980
|
-
`)}function
|
|
1981
|
-
`)}async function
|
|
1982
|
-
`)}function
|
|
1983
|
-
`)}function
|
|
1984
|
-
`)}function
|
|
1985
|
-
`);
|
|
1986
|
-
`)}function
|
|
1987
|
-
`)}async function
|
|
2298
|
+
`}function L6($,b,A={}){let m=[];if(m.push("# Import Report"),m.push(""),m.push(`**Generated**: ${new Date().toISOString()}`),m.push(""),m.push("## Summary"),m.push(""),m.push("| Metric | Count |"),m.push("|--------|-------|"),m.push(`| Files Scanned | ${$.stats.filesScanned} |`),m.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),m.push(`| Schemas Found | ${$.stats.schemasFound} |`),m.push(`| Errors Found | ${$.stats.errorsFound} |`),m.push(`| Events Found | ${$.stats.eventsFound} |`),m.push(""),A.includeStats!==!1)m.push("### Confidence"),m.push(""),m.push("| Level | Count |"),m.push("|-------|-------|"),m.push(`| High | ${$.stats.highConfidence} |`),m.push(`| Medium | ${$.stats.mediumConfidence} |`),m.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),m.push("");m.push("### Frameworks Detected"),m.push("");for(let n of $.project.frameworks)m.push(`- **${n.name}** (${n.confidence})`);if(m.push(""),A.includeEndpoints!==!1&&$.endpoints.length>0){m.push("## Endpoints"),m.push(""),m.push("| Method | Path | Kind | Confidence |"),m.push("|--------|------|------|------------|");for(let n of $.endpoints)m.push(`| ${n.method} | \`${n.path}\` | ${n.kind} | ${n.confidence.level} |`);m.push("")}if(A.includeSchemas!==!1&&$.schemas.length>0){m.push("## Schemas"),m.push(""),m.push("| Name | Type | Confidence |"),m.push("|------|------|------------|");for(let n of $.schemas)m.push(`| ${n.name} | ${n.schemaType} | ${n.confidence.level} |`);m.push("")}if(b&&A.includeIssues!==!1){m.push("## Verification"),m.push(""),m.push("| Status | Count |"),m.push("|--------|-------|"),m.push(`| Valid | ${b.summary.validEndpoints} |`),m.push(`| Warnings | ${b.summary.warningEndpoints} |`),m.push(`| Errors | ${b.summary.errorEndpoints} |`),m.push("");let n=b.endpointResults.filter((W)=>W.issues.length>0);if(n.length>0){m.push("### Issues"),m.push("");for(let W of n){m.push(`#### ${W.endpoint.method} ${W.endpoint.path}`);for(let w of W.issues){let j=w.severity==="error"?"❌":w.severity==="warning"?"⚠️":"ℹ️";if(m.push(`- ${j} **${w.code}**: ${w.message}`),w.suggestion)m.push(` - *Suggestion*: ${w.suggestion}`)}m.push("")}}}if(A.includeAmbiguities!==!1&&$.ambiguities.length>0){m.push("## Ambiguities (Require Review)"),m.push("");for(let n of $.ambiguities)if(m.push(`- **${n.type}** (${n.itemId}): ${n.description}`),n.suggestion)m.push(` - *Suggestion*: ${n.suggestion}`);m.push("")}return m.push("## Next Steps"),m.push(""),m.push("1. Review generated contracts in the output directory"),m.push("2. Fill in TODO placeholders with business context"),m.push("3. Run `contractspec validate` to verify contracts"),m.push("4. Move stable contracts from `generated/` to `curated/`"),m.push(""),m.join(`
|
|
2299
|
+
`)}function R6($,b){let A=[];A.push(""),A.push("\uD83D\uDCCA Summary"),A.push(` Files scanned: ${$.stats.filesScanned}`),A.push(` Endpoints: ${$.stats.endpointsFound}`),A.push(` Schemas: ${$.stats.schemasFound}`),A.push(""),A.push("\uD83D\uDCC8 Confidence"),A.push(` High: ${$.stats.highConfidence}`),A.push(` Medium: ${$.stats.mediumConfidence}`),A.push(` Low: ${$.stats.lowConfidence}`),A.push(""),A.push("\uD83D\uDD27 Frameworks");for(let m of $.project.frameworks)A.push(` • ${m.name}`);if(A.push(""),b)A.push("✅ Verification"),A.push(` Valid: ${b.summary.validEndpoints}`),A.push(` Warnings: ${b.summary.warningEndpoints}`),A.push(` Errors: ${b.summary.errorEndpoints}`),A.push("");return A.join(`
|
|
2300
|
+
`)}async function C6($,b,A){let{logger:m}=A,n=[],W=[...$.ambiguities];m.info(`Verifying ${$.endpoints.length} endpoints...`);for(let j of $.endpoints){let y=[];if(j.confidence.level==="low"||j.confidence.level==="ambiguous")y.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${j.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!j.input&&(j.method==="POST"||j.method==="PUT"||j.method==="PATCH"))y.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!j.output)y.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!==j.id&&Q.path===j.path&&Q.method===j.method).length>0)y.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${j.method} ${j.path} found`,severity:"error"})}if(b.checkConflicts){let S=I6(j,$.endpoints);for(let Q of S)y.push({code:"PATH_CONFLICT",message:`Path may conflict with ${Q.method} ${Q.path}`,severity:"warning"})}let B=y.some((S)=>S.severity==="error")?"error":y.some((S)=>S.severity==="warning")?"warning":"valid";n.push({endpoint:j,status:B,issues:y})}if(b.validateSchemas){for(let j of $.schemas)if(!j.fields||j.fields.length===0)W.push({type:"schema",itemId:j.id,description:`Schema ${j.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:j.source})}let w={totalEndpoints:n.length,validEndpoints:n.filter((j)=>j.status==="valid").length,warningEndpoints:n.filter((j)=>j.status==="warning").length,errorEndpoints:n.filter((j)=>j.status==="error").length,totalIssues:n.reduce((j,y)=>j+y.issues.length,0)};return m.info(`Verification complete: ${w.validEndpoints} valid, ${w.warningEndpoints} warnings, ${w.errorEndpoints} errors`),{valid:w.errorEndpoints===0,endpointResults:n,ambiguities:W,summary:w}}function I6($,b){let A=[],m=$.path.split("/").filter(Boolean);for(let n of b){if(n.id===$.id)continue;if(n.method!==$.method)continue;let W=n.path.split("/").filter(Boolean);if(W.length!==m.length)continue;let w=!0;for(let j=0;j<m.length;j++){let y=m[j]??"",B=W[j]??"",S=y.startsWith(":")||y.startsWith("{"),Q=B.startsWith(":")||B.startsWith("{");if(!S&&!Q&&y!==B){w=!1;break}}if(w&&$.path!==n.path)A.push(n)}return A}function cz($,b="feature-map",A={}){switch(b){case"feature-map":return Yn($,A);case"orphans":return E6($,A);case"dependencies":return M6($,A);case"full":return x6($,A);default:return Yn($,A)}}function Yn($,b){let{direction:A="LR",showVersions:m=!0,maxNodes:n=50}=b,W=[`flowchart ${A}`],w=$.features;if(b.featureKeys&&b.featureKeys.length>0)w=w.filter((Z)=>b.featureKeys?.includes(Z.key));let j=0,y=!1;if(w.length>0){W.push(" subgraph features [Features]");for(let Z of w){if(j>=n)break;let G=v(`F_${Z.key}`),X=Z.title??Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}let B=Gn(w,"operations",$.inventory);if(B.length>0&&j<n){W.push(" subgraph ops [Operations]");for(let Z of B){if(j>=n)break;let G=v(`O_${Z.key}_v${Z.version}`),X=m?`${Z.key}.v${Z.version}`:Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}let S=Gn(w,"events",$.inventory);if(S.length>0&&j<n){W.push(" subgraph events [Events]");for(let Z of S){if(j>=n)break;let G=v(`E_${Z.key}_v${Z.version}`),X=m?`${Z.key}.v${Z.version}`:Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}let Q=Gn(w,"presentations",$.inventory);if(Q.length>0&&j<n){W.push(" subgraph presentations [Presentations]");for(let Z of Q){if(j>=n)break;let G=v(`P_${Z.key}_v${Z.version}`),X=m?`${Z.key}.v${Z.version}`:Z.key;W.push(` ${G}["${y$(X)}"]`),j++}W.push(" end")}for(let Z of w){let G=v(`F_${Z.key}`);for(let X of Z.operations){let Y=v(`O_${X.key}_v${X.version}`);W.push(` ${G} --> ${Y}`)}for(let X of Z.events){let Y=v(`E_${X.key}_v${X.version}`);W.push(` ${G} -.-> ${Y}`)}for(let X of Z.presentations){let Y=v(`P_${X.key}_v${X.version}`);W.push(` ${G} --> ${Y}`)}}if(y)W.push(` note["... and more (truncated at ${n} nodes)"]`);return W.join(`
|
|
2301
|
+
`)}function E6($,b){let{direction:A="TB",showVersions:m=!0,maxNodes:n=50}=b,W=[`flowchart ${A}`],w=new Set,j=new Set,y=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)j.add(`${Z.key}.v${Z.version}`);for(let Z of Q.presentations)y.add(`${Z.key}.v${Z.version}`)}let B=0;if($.features.length>0){W.push(" subgraph features [Features]");for(let Q of $.features){if(B>=n)break;let Z=v(`F_${Q.key}`);W.push(` ${Z}["${y$(Q.title??Q.key)}"]`),B++}W.push(" end")}if($.orphanedSpecs.length>0){W.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs){if(B>=n)break;let Z=v(`orphan_${Q.type}_${Q.key}_v${Q.version}`),G=m?`${Q.key}.v${Q.version}`:Q.key;W.push(` ${Z}["${y$(G)}"]`),B++}W.push(" end")}let S=[];for(let Q of w){let[Z,G]=Xn(Q);if(Z&&G)S.push({type:"operation",key:Z,version:G})}for(let Q of j){let[Z,G]=Xn(Q);if(Z&&G)S.push({type:"event",key:Z,version:G})}for(let Q of y){let[Z,G]=Xn(Q);if(Z&&G)S.push({type:"presentation",key:Z,version:G})}if(S.length>0&&B<n){W.push(" subgraph linked [Linked Specs]");for(let Q of S){if(B>=n)break;let Z=v(`${Q.type}_${Q.key}_v${Q.version}`),G=m?`${Q.key}.v${Q.version}`:Q.key;W.push(` ${Z}["${y$(G)}"]`),B++}W.push(" end")}for(let Q of $.features){let Z=v(`F_${Q.key}`);for(let G of Q.operations){let X=v(`operation_${G.key}_v${G.version}`);W.push(` ${Z} --> ${X}`)}for(let G of Q.events){let X=v(`event_${G.key}_v${G.version}`);W.push(` ${Z} -.-> ${X}`)}for(let G of Q.presentations){let X=v(`presentation_${G.key}_v${G.version}`);W.push(` ${Z} --> ${X}`)}}return W.join(`
|
|
2302
|
+
`)}function M6($,b){let{direction:A="TB",showVersions:m=!0,maxNodes:n=50}=b,W=[`flowchart ${A}`],w=0;for(let j of $.features){if(w>=n)break;let y=v(`F_${j.key}`);W.push(` ${y}["${y$(j.title??j.key)}"]`),w++;for(let B of j.operations){if(w>=n)break;let S=v(`O_${B.key}_v${B.version}`),Q=m?`${B.key}.v${B.version}`:B.key;W.push(` ${S}["${y$(Q)}"]`),W.push(` ${y} --> ${S}`),w++}for(let B of j.events){if(w>=n)break;let S=v(`E_${B.key}_v${B.version}`),Q=m?`${B.key}.v${B.version}`:B.key;W.push(` ${S}["${y$(Q)}"]`),W.push(` ${y} -.-> ${S}`),w++}for(let B of j.presentations){if(w>=n)break;let S=v(`P_${B.key}_v${B.version}`),Q=m?`${B.key}.v${B.version}`:B.key;W.push(` ${S}["${y$(Q)}"]`),W.push(` ${y} --> ${S}`),w++}for(let B of j.opToPresentationLinks){let S=v(`O_${B.op.key}_v${B.op.version}`),Q=v(`P_${B.pres.key}_v${B.pres.version}`);W.push(` ${S} --> ${Q}`)}}return W.join(`
|
|
2303
|
+
`)}function x6($,b){let A=Yn($,b);if($.orphanedSpecs.length===0)return A;let m=A.split(`
|
|
2304
|
+
`);m.push(" subgraph orphaned [Orphaned Specs]");for(let n of $.orphanedSpecs.slice(0,20)){let W=v(`orphan_${n.type}_${n.key}_v${n.version}`),w=`${n.key}.v${n.version}`;m.push(` ${W}["${y$(w)}"]:::orphan`)}return m.push(" end"),m.push(" classDef orphan stroke-dasharray: 5 5"),m.join(`
|
|
2305
|
+
`)}function Gn($,b,A){let m=new Set,n=[];for(let W of $)for(let w of W[b]){let j=`${w.key}.v${w.version}`;if(!m.has(j))m.add(j),n.push(w)}return n}function Xn($){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 y$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as T6,specToMarkdown as I$}from"@contractspec/module.workspace";function uz($,b,A){let m=[];if(A.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(b))m.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!b.includes($.meta.key))m.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(A.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(b))m.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(b))m.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))m.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return m}function oz($,b){let A=[];A.push(`# Verification Report: ${$.meta.key}`),A.push("");let m=b.filter((w)=>w.severity==="error"),n=b.filter((w)=>w.severity==="warning"),W=b.filter((w)=>w.severity==="info");if(A.push("## Summary"),A.push(""),A.push(`- Errors: ${m.length}`),A.push(`- Warnings: ${n.length}`),A.push(`- Info: ${W.length}`),A.push(""),m.length>0){A.push("## Errors"),A.push("");for(let w of m)A.push(`- ❌ **${w.category}**: ${w.message}`);A.push("")}if(n.length>0){A.push("## Warnings"),A.push("");for(let w of n)A.push(`- ⚠️ **${w.category}**: ${w.message}`);A.push("")}if(W.length>0){A.push("## Info"),A.push("");for(let w of W)A.push(`- ℹ️ **${w.category}**: ${w.message}`);A.push("")}return A.join(`
|
|
2306
|
+
`)}async function pz($,b){let A=[];A.push(I$($,"context"));let m=await j$(b),n=async(W)=>{let w=m.find((y)=>y.key===W.name&&y.version===W.version);if(!w)return null;return(await T6(w.filePath)).find((y)=>y.meta.key===W.name)??null};if($.operations?.length){A.push(`
|
|
1988
2307
|
## Operations (${$.operations.length})
|
|
1989
|
-
`);for(let
|
|
2308
|
+
`);for(let W of $.operations){let w=await n(W);if(w)A.push(I$(w,"full"));else A.push(`### ${W.name} (v${W.version})
|
|
1990
2309
|
|
|
1991
|
-
*Spec not found*`);
|
|
2310
|
+
*Spec not found*`);A.push("---")}}if($.events?.length){A.push(`
|
|
1992
2311
|
## Events (${$.events.length})
|
|
1993
|
-
`);for(let
|
|
2312
|
+
`);for(let W of $.events){let w=await n(W);if(w)A.push(I$(w,"full"));else A.push(`### ${W.name} (v${W.version})
|
|
1994
2313
|
|
|
1995
|
-
*Spec not found*`);
|
|
2314
|
+
*Spec not found*`);A.push("---")}}if($.presentations?.length){A.push(`
|
|
1996
2315
|
## Presentations (${$.presentations.length})
|
|
1997
|
-
`);for(let
|
|
1998
|
-
|
|
1999
|
-
*Spec not found*`);
|
|
2000
|
-
`)}function
|
|
2001
|
-
`)}function
|
|
2002
|
-
`)}function
|
|
2003
|
-
`)}
|
|
2004
|
-
`).
|
|
2005
|
-
${
|
|
2006
|
-
${
|
|
2007
|
-
${
|
|
2008
|
-
|
|
2009
|
-
`).trimEnd()}function $3(){return new RegExp(`${e4($9)}[\\s\\S]*?${e4(W9)}(?:\\r?\\n)?`)}function e4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{generateArtifactsForAudience as W3,generateBiomePreset as j3}from"@contractspec/biome-config";async function kj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"biome.jsonc"),Z=$.join(A,".contractspec","biome"),X=$.join(Z,"plugins"),Y=$.join(Z,"ai"),B=W3("consumer");try{let q=await $.exists(Q);if(q&&W.interactive){if(!await j.confirm(`${Q} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Q,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Q,j3("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(B.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),B.aiRules),{target:"biome-config",filePath:Q,action:q?"merged":"created",message:q?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(q){return{target:"biome-config",filePath:Q,action:"error",message:q instanceof Error?q.message:"Unknown error"}}}async function hj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".contractsrc.json");try{let Z=await $.exists(Q),X=u$(W);if(Z){let Y=await $.readFile(Q),B=r(Y);if(!B)return{target:"cli-config",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Q,action:"skipped",message:"User skipped merge"}}let q=p(B,X);if((W.preset==="connect"||W.preset?.startsWith("builder-"))&&typeof X==="object"&&X!==null){let H={};if("connect"in X)H.connect=X.connect;if("builder"in X)H.builder=X.builder;await $.writeFile(Q,F(y1(q,H)))}else await $.writeFile(Q,F(q));return{target:"cli-config",filePath:Q,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Q,F(X)),{target:"cli-config",filePath:Q,action:"created",message:"Created CLI configuration"}}catch(Z){return{target:"cli-config",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function gj($,W,j){let A=$.join(W.workspaceRoot,".cursor","rules"),Q=$.join(A,"contractspec.mdc");try{let Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=C8(W);if(X)if(W.interactive){if(!await j.confirm(`${Q} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Q,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Q,action:"skipped",message:"File already exists"};return await $.writeFile(Q,Y),{target:"cursor-rules",filePath:Q,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(Z){return{target:"cursor-rules",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function fj($,W,j){let A=qW();try{let Q=await $.exists(A),Z=R8();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Q){let B=await $.readFile(A),q=r(B);if(!q)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let H=p(q,Z);return await $.writeFile(A,F(H)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(A,F(Z)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(Q){return{target:"mcp-claude",filePath:A,action:"error",message:Q instanceof Error?Q.message:"Unknown error"}}}async function uj($,W,j){let A=$.join(W.workspaceRoot,".cursor"),Q=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=q0();if(X){let B=await $.readFile(Q),q=r(B);if(!q)return{target:"mcp-cursor",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Q,action:"skipped",message:"User skipped merge"}}let H=p(q,Y);return await $.writeFile(Q,F(H)),{target:"mcp-cursor",filePath:Q,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Q,F(Y)),{target:"mcp-cursor",filePath:Q,action:"created",message:"Created Cursor MCP configuration"}}catch(Z){return{target:"mcp-cursor",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function dj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".vscode"),Z=$.join(Q,"settings.json");try{if(!await $.exists(Q))await $.mkdir(Q);let Y=await $.exists(Z),B=BW(W);if(Y){let q=await $.readFile(Z),H=r(q);if(!H)return{target:"vscode-settings",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:Z,action:"skipped",message:"User skipped merge"}}let V=p(H,B);if((W.preset==="builder-managed"||W.preset==="builder-hybrid")&&"contractspec.api.baseUrl"in B)V["contractspec.api.baseUrl"]=B["contractspec.api.baseUrl"];return await $.writeFile(Z,F(V)),{target:"vscode-settings",filePath:Z,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(Z,F(B)),{target:"vscode-settings",filePath:Z,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:Z,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var A3={confirm:async($,W)=>W??!0,select:async($,W)=>{return W.find((j)=>j.selected)?.value??W[0]?.value??""},multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function hS($,W,j=A3){let A=[],Q=W.targets.length>0?W.targets:X0,Z=W.workspaceRoot,X=D(Z),Y=W.packageRoot??f(Z),B=W.isMonorepo??e$(X),q=W.packageName??(B?I$(Y):void 0),H=await A9($,[Y,X]),V=W.preset??B0(H);if(W.interactive&&!W.preset)V=await j.select("Select initialization preset:",U8.map((R)=>({value:R,label:L8[R],description:O8[R],selected:R===V})));let G=W.scope??"workspace",J=Y!==X;if(B&&W.interactive&&J)G=await j.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${q??Y})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${X})`,description:"Create config files at the workspace root"}]);let b=B&&G==="package"?Y:X,w=await A9($,[b]),L={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:B,scope:G,packageName:q,preset:V,builderApiBaseUrl:W.builderApiBaseUrl??w?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:W.builderControlPlaneTokenEnvVar??w?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:W.builderLocalRuntimeId??w?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:W.builderLocalGrantedTo??w?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:W.builderLocalProviderIds??w?.builder?.localRuntime?.providerIds,connectStudioEndpoint:W.connectStudioEndpoint??w?.connect?.studio?.endpoint,connectStudioQueue:W.connectStudioQueue??w?.connect?.studio?.queue},z=S8(V,Q);if(W.interactive)z=await j.multiSelect("Select components to configure:",X0.map((R)=>({value:R,label:z8[R],selected:z.includes(R)})));let S=L.projectName;if(W.interactive&&!S){let R=G==="package"&&q?q:b.split("/").pop()??"my-project";S=await j.input("Project name:",R)}let U=L.builderApiBaseUrl;if(W.interactive&&(V==="builder-managed"||V==="builder-hybrid"))U=await j.input("Builder API base URL:",U??"https://api.contractspec.io");let{builderLocalRuntimeId:O,builderLocalGrantedTo:K}=L;if(W.interactive&&(V==="builder-local"||V==="builder-hybrid"))O=await j.input("Default local runtime target id:",O??"rt_local_daemon"),K=await j.input("Default local runtime grant target:",K??"local:operator");let _={...L,projectName:S,targets:z,builderApiBaseUrl:U,builderLocalRuntimeId:O,builderLocalGrantedTo:K};for(let R of z){let v=await Q3($,R,_,j);A.push(v)}let I=await EW($,{behavior:_.gitignoreBehavior,interactive:_.interactive,patterns:N8({preset:V}),prompts:j,root:X});if(_.gitignoreBehavior!=="skip"||I.action!=="skipped")A.push(I);let M=A.filter((R)=>R.action!=="error").length,E=A.filter((R)=>R.action==="error").length,C=B?` (${G} level)`:"";return{success:E===0,preset:V,files:A,summary:`Setup complete${C}: ${M} configured, ${E} failed.`,nextSteps:E8(_)}}async function Q3($,W,j,A){switch(W){case"agents-md":return Pj($,j,A);case"cli-config":return hj($,j,A);case"biome-config":return kj($,j,A);case"vscode-settings":return dj($,j,A);case"mcp-cursor":return uj($,j,A);case"mcp-claude":return fj($,j,A);case"cursor-rules":return gj($,j,A);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}async function A9($,W){for(let j of W){let A=$.join(j,".contractsrc.json");if(!await $.exists(A))continue;let Q=r(await $.readFile(A));if(Q)return Q}return null}import{validateBlueprint as Z3}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as X3}from"path";async function tS($,W){let{fs:j}=W,A=X3(process.cwd(),$);if(!await j.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let Q=await Q$(A),Z=Y3(Q.exports),X=Z3(Z);return{spec:Z,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Q){return{valid:!1,errors:[Q instanceof Error?Q.message:String(Q)]}}}function Y3($){let W=Object.values($).filter(B3);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function B3($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as q3,dirname as nj,join as R0}from"path";async function $I($,W,j,A,Q){let{fs:Z}=Q,X=A.implementationPath;if(!X){let H=nj($),V=q3($,".ts"),G=[R0(H,V.replace(".contracts",".handler")+".ts"),R0(H,V.replace(".presentation","")+".tsx"),R0(H,V.replace(".form",".form")+".tsx"),R0(nj(H),"handlers",V.replace(".contracts",".handler")+".ts"),R0(nj(H),"components",V.replace(".presentation","")+".tsx")];for(let J of G)if(await Z.exists(J)){X=J;break}}if(!X||!await Z.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await Z.readFile(X),q=await new g0(j).validate(W,Y);return{success:q.success,errors:q.errors||[],warnings:q.warnings||[],suggestions:q.suggestions||[],report:q.code}}import{validateBuilderBlueprint as H3,validateBuilderReadinessReport as V3,validateBuilderWorkspace as G3,validateBuilderWorkspaceSnapshot as J3}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as b3,validateExternalPatchProposal as w3,validateProviderRoutingPolicy as K3,validateRuntimeTarget as _3}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as z3,validateLayoutSlots as U3}from"@contractspec/lib.surface-runtime/spec";async function XI($,W){if(!M3($.specType))return{valid:!0,errors:[],warnings:[]};let j=v3($.filePath),A=[`${j}/package.json`,`${j}/README.md`,`${j}/src/index.ts`,$.filePath],Q=[];for(let Y of A)if(!await W.exists(Y))Q.push(`Missing package scaffold file: ${Y}`);if(Q.length>0)return{valid:!1,errors:Q,warnings:[]};let Z;try{Z=(await Q$($.filePath)).exports}catch(Y){return{valid:!1,errors:[Y instanceof Error?Y.message:String(Y)],warnings:[]}}let X=$.specType==="module-bundle"?L3(Z):$.specType==="builder-spec"?O3(Z):S3(Z);return{valid:Q.length===0&&X.errors.length===0,errors:[...Q,...X.errors],warnings:X.warnings.map((Y)=>`[${$.filePath}] ${Y}`)}}function L3($){let W=[],j=[],A=I3($,E3);if(A.length===0)return j.push(cj("module-bundle","bundle")),{errors:W,warnings:j};for(let Q of A){let Z=Object.values(Q.value.surfaces);for(let X of Z){try{U3(X)}catch(Y){W.push(`[${Q.exportName}] ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of z3(X).warnings)j.push(`[${Q.exportName}] ${Y}`)}}return{errors:W,warnings:j}}function O3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(N3(Z)){A+=1,W.push(...PW(Q,G3(Z)));continue}if(R3(Z)){A+=1,W.push(...PW(Q,H3(Z)));continue}if(C3(Z)){A+=1,W.push(...PW(Q,V3(Z)));continue}if(D3(Z))A+=1,W.push(...PW(Q,J3(Z)))}if(A===0)j.push(cj("builder-spec","builder"));return{errors:W,warnings:j}}function S3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(T3(Z)){A+=1,W.push(...kW(Q,_3(Z)));continue}if(F3(Z)){A+=1,W.push(...kW(Q,K3(Z)));continue}if(x3(Z)){A+=1,W.push(...kW(Q,b3(Z)));continue}if(y3(Z))A+=1,W.push(...kW(Q,w3(Z)))}if(A===0)j.push(cj("provider-spec","provider"));return{errors:W,warnings:j}}function I3($,W){return Object.entries($).filter(([j,A])=>j!=="__esModule"&&W(A)).map(([j,A])=>({exportName:j,value:A}))}function PW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function kW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function M3($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function E3($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function N3($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function R3($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function C3($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function D3($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function T3($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function F3($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function x3($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function y3($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function v3($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function cj($,W){return`No recognized ${W} exports were found for ${$} deep validation.`}import{validateSpecStructure as m3}from"@contractspec/module.workspace";function Q9($,W={}){let j=[],A=[],Q;if(!W.skipStructure)Q=m3($),j.push(...Q.errors),A.push(...Q.warnings);return{valid:j.length===0,structureResult:Q,errors:j,warnings:A,code:$.sourceBlock}}async function HI($,W={}){return $.map((j)=>({spec:j,...Q9(j,W)}))}async function m$($,W,j={}){let{fs:A}=W;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let Z=await A.readFile($),X=[],Y=[],B=void 0;if(!j.skipStructure){let q=await $$(W,{pattern:$});for(let H of q){let V=Q9(H,j);B=V.structureResult,X.push(...V.errors),Y.push(...V.warnings)}}return{valid:X.length===0,structureResult:B,errors:X,warnings:Y,code:Z}}async function VI($,W,j={}){let A=new Map;for(let Q of $){let Z=await m$(Q,W,j);A.set(Q,Z)}return A}import{validateConfig as P3}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as lj}from"fs/promises";import{resolve as hW}from"path";async function _I($,W,j,A){let{fs:Q}=A,Z=hW(process.cwd(),W);if(!await Q.exists(Z))return{valid:!1,errors:[`Tenant config file not found: ${Z}`]};try{let X=await k3(Z),Y=await h3(j.connections,Q),B=await g3(j.translationCatalog,Q),q=await f3(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(B)H.translationCatalogs={blueprint:[B],platform:[]};if(q)H.integrationSpecs=q;let V=P3($,X,H);return{config:X,report:V,valid:V.valid,errors:V.errors.map((G)=>`[${G.code}] ${G.path}: ${G.message}`)}}catch(X){return{valid:!1,errors:[X instanceof Error?X.message:String(X)]}}}async function k3($){if($.endsWith(".json")){let A=await lj($,"utf-8"),Q=JSON.parse(A);if(!Z9(Q))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Q}let W=await Q$($),j=Object.values(W.exports).filter(Z9);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function Z9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function q9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function h3($,W){let j=q9($);if(!j.length)return[];let A=[];for(let Q of j){let Z=hW(process.cwd(),Q);if(!await W.exists(Z)){console.warn(`Warning: Connection file not found: ${Z}`);continue}if(Z.endsWith(".json")){let Y=await lj(Z,"utf-8"),B=JSON.parse(Y);A.push(...rj(B));continue}let X=await Q$(Z);A.push(...rj(X.exports))}return A}function rj($){if(Array.isArray($)){let W=$.filter(X9);if(W.length)return W}if(X9($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((A)=>rj(A));if(j.length)return j}return[]}function X9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function g3($,W){if(!$)return;let j=hW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let Z=await lj(j,"utf-8"),X=JSON.parse(Z);if(Y9(X))return B9(X);return}let A=await Q$(j),Q=Object.values(A.exports).filter(Y9);if(Q.length===0)return;return B9(Q[0])}function Y9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function B9($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function f3($){let W=q9($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),A=new j;for(let Q of W){let{modulePath:Z,exportName:X}=u3(Q);if(!Z)continue;let Y=hW(process.cwd(),Z);try{let B=await Q$(Y),q=d3(B.exports,X);if(q)await q(A)}catch(B){console.warn(`Failed to load registrar from ${Y}: ${B}`)}}return A}function u3($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),A=W?.trim()??null,Q=j?.trim();return{modulePath:A,exportName:Q}}function d3($,W){if(W){let j=$[W];if(typeof j==="function")return j;return}if(typeof $.default==="function")return $.default;for(let j of Object.values($))if(typeof j==="function")return j;return}async function CI($,W,j={},A){let{fs:Q,logger:Z}=$,X=await Q.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],B=[],q=A?.validate??((V)=>m$(V,{fs:Q,logger:Z})),H=A?.build??((V,G)=>f$(V,{fs:Q,logger:Z},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let J={specPath:V,outputDir:G};if(j.validate)try{J.validation=await q(V)}catch(b){J.error={phase:"validate",message:b instanceof Error?b.message:String(b)},B.push(J);continue}if(!j.dryRun)try{J.build=await H(V,G)}catch(b){J.error={phase:"build",message:b instanceof Error?b.message:String(b)},B.push(J);continue}else Z.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});B.push(J)}return{specs:X,runs:B}}import{generateText as n3}from"ai";var c3=`
|
|
2316
|
+
`);for(let W of $.presentations){let w=await n(W);if(w)A.push(I$(w,"full"));else A.push(`### ${W.name} (v${W.version})
|
|
2317
|
+
|
|
2318
|
+
*Spec not found*`);A.push("---")}}return A.join(`
|
|
2319
|
+
`)}function D6($,b){let A=[];if(A.push(`# Implementation Guide: ${$.meta.key}`),A.push(""),A.push(`**Target Agent**: ${b}`),A.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),A.push(""),$.meta.description)A.push("## Overview"),A.push(""),A.push($.meta.description),A.push("");if($.meta.goal)A.push("## Goal"),A.push(""),A.push($.meta.goal),A.push("");if($.meta.context)A.push("## Context"),A.push(""),A.push($.meta.context),A.push("");if(A.push("## Implementation Steps"),A.push(""),$.specType==="operation"){if(A.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)A.push("2. Implement input validation according to the schema"),A.push("3. Implement the core business logic"),A.push("4. Return output matching the expected schema");if($.hasPolicy)A.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){A.push("6. Emit events on success:");for(let m of $.emittedEvents)A.push(` - \`${m.name}\` (v${m.version})`)}A.push("7. Add error handling for expected failure cases"),A.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(A.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){A.push("2. Implement operations:");for(let m of $.operations)A.push(` - \`${m.name}\` (v${m.version})`)}if($.presentations&&$.presentations.length>0){A.push("3. Implement presentations:");for(let m of $.presentations)A.push(` - \`${m.name}\` (v${m.version})`)}A.push("4. Wire up feature exports"),A.push("5. Add integration tests")}else A.push("1. Review the spec requirements"),A.push("2. Implement the core logic"),A.push("3. Add tests"),A.push("4. Document the implementation");if(A.push(""),A.push("## Constraints"),A.push(""),A.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)A.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)A.push(`- Tags: ${$.meta.tags.join(", ")}`);if(A.push(""),b==="cursor-cli")A.push("## Cursor Notes"),A.push(""),A.push("- Use Composer mode for multi-file changes"),A.push("- Reference this guide in your cursor rules"),A.push("- Break implementation into small, focused commits");else if(b==="claude-code")A.push("## Claude Code Notes"),A.push(""),A.push("- Use extended thinking for complex logic"),A.push("- Ask for clarification on ambiguous requirements"),A.push("- Provide step-by-step reasoning");else if(b==="generic-mcp")A.push("## General Notes"),A.push(""),A.push("- Use inline comments to guide generation"),A.push("- Review generated code carefully");return A.push(""),A.push("## Spec Definition"),A.push(""),A.push(I$($,"full")),A.join(`
|
|
2320
|
+
`)}function N6($){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(`
|
|
2321
|
+
`)}function az($,b,A="generic-mcp"){switch(b){case"guide":return D6($,A);case"rules":return N6($);case"prompt":return I$($,"prompt");case"context":return I$($,"context");case"full":default:return I$($,"full")}}import{readFile as F6}from"node:fs/promises";import{createRequire as v6}from"node:module";import{dirname as g6,resolve as jy}from"node:path";import{pathToFileURL as k6}from"node:url";import wy from"node:vm";import Hn from"typescript";async function n$($,b={}){let A=jy(process.cwd(),$),m=b.runtime??f6();try{let n=m==="bun"?await P6(A):await r6(A);return{modulePath:A,exports:n}}catch(n){throw Error(By(A,n))}}async function wL($,b){let A=jy(process.cwd(),$);if(!await b.exists(A))return null;return n$(A)}async function y0($,b={}){return(await n$($,b)).exports}async function yy($,b){let A=await y0($);return Sy(A,$,b)}function By($,b){return`Failed to load authored module at ${$}: ${b instanceof Error?b.message:String(b)}`}async function Sy($,b,A){if(A.isValue($))return $;for(let m of A.instanceKeys??[])if(A.isValue($[m]))return $[m];for(let m of A.factoryKeys??[]){let n=$[m];if(typeof n!=="function")continue;let W=await n();if(A.isValue(W))return W}throw Error(`${A.description} module ${b} must export a supported instance or factory.`)}async function P6($){return await import(k6($).href)}async function r6($){return await h6($)??{}}function f6(){return typeof globalThis.Bun<"u"?"bun":"node"}var jL={formatModuleLoadError:By,resolveAuthoredModuleValue:Sy};async function h6($){let b=await F6($,"utf-8"),A=Hn.transpileModule(b,{compilerOptions:{module:Hn.ModuleKind.CommonJS,target:Hn.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),m={},n={exports:m},W=v6($),w=wy.createContext({module:n,exports:m,require:W,__dirname:g6($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new wy.Script(A.outputText,{filename:$}).runInContext(w),n.exports}var Hy={};P(Hy,{renderOnboardingGuides:()=>Vn,listOnboardingTracks:()=>B0,getOnboardingTrack:()=>On,createOnboardingConnectArtifacts:()=>s6,buildOnboardingPlan:()=>e6,ONBOARDING_TRACKS:()=>qn});var qn=[{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 B0(){return qn}function On($){return qn.find((b)=>b.id===$)}function Vn($){return{agentGuide:c6($),humanGuide:u6($)}}function c6($){let b=["# ContractSpec Onboarding Guide","",`Primary track: \`${$.primaryTrack.id}\``,"","Use the repo-local onboarding tracks before inventing new abstractions.","","## Workflow","","- Run `contractspec connect adoption resolve --family <family> --stdin` before adding new surfaces.","- Prefer the starter example and the listed ContractSpec packages for the active track.","- Treat `USAGE.md` as the human-facing implementation path and this file as AI operating guidance.","- When Builder is not configured, recommend `contractspec init --preset builder-managed|builder-local|builder-hybrid` instead of inventing a runtime target model.","","## Recommended Tracks",""];for(let A of $.recommendations)b.push(...d6(A.track,A.reason));return b.join(`
|
|
2322
|
+
`)}function d6($,b){let A=[`### ${$.title}`,"",`Reason: ${b}`,`Reuse family: \`${$.reuseFamily}\``,`Primary docs: \`${$.primaryDocsRoute}\``,`Starter example: \`${$.starterExample.key}\` (${$.starterExample.packageRef})`,"Commands:"];for(let m of $.recommendedCommands)A.push(`- \`${m}\``);return[...A,""]}function u6($){let b=["# ContractSpec Repo Onboarding","",`Primary track: **${$.primaryTrack.title}**`,"",$.primaryTrack.summary,"","## Start Here","",...$.nextCommands.map((A,m)=>`${m+1}. \`${A}\``),"","## Track Guide",""];for(let A of $.recommendations)b.push(...o6(A.track,A.reason));if($.builderNextSteps.length>0){b.push("## Builder Paths","");for(let A of $.builderNextSteps)b.push(`- \`${A}\``);b.push("")}return b.join(`
|
|
2323
|
+
`)}function o6($,b){let A=[`### ${$.title}`,"",$.description,"",`Why it is recommended here: ${b}`,"",`Primary docs: ${$.primaryDocsRoute}`];if($.secondaryDocsRoutes.length>0)A.push(`More docs: ${$.secondaryDocsRoutes.join(", ")}`);if(A.push(`Starter example: ${$.starterExample.title} (\`${$.starterExample.key}\`)`,`Example package: \`${$.starterExample.packageRef}\``),$.advancedExample)A.push(`Advanced example: ${$.advancedExample.title} (\`${$.advancedExample.key}\`)`);A.push("","Commands:");for(let m of $.recommendedCommands)A.push(`- \`${m}\``);return A.push("",`Packages: ${$.packages.map((m)=>`\`${m}\``).join(", ")}`,""),A}import{buildContext as i6}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as l6}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as t6}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function Qy($,b,A,m){let n=i6({capabilities:$.packages,device:"desktop",mode:"guided",preferences:{control:"standard",dataDepth:"detailed",density:"standard",guidance:"wizard",media:"text",narrative:"top-down",pace:"balanced"},route:`/onboard/${$.id}`,tenantId:A,workspaceId:m}),W=await l6(t6(p6(b)),n);return{journeyContext:n,journeyPlan:W}}function Zy($){if(!$||$.length===0)return[...B0()];return $.map((b)=>{let A=On(b);if(!A)throw Error(`Unknown onboarding track: ${b}`);return A})}function Gy($){if(!$.builder?.enabled)return"none";switch($.builder.runtimeMode){case"local":return"local";case"hybrid":return"hybrid";default:return"managed"}}function Xy($){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 Yy($,b){if(!b)return $.starterExample;if($.starterExample.key===b)return $.starterExample;if($.advancedExample?.key===b)return $.advancedExample;for(let A of B0()){if(A.starterExample.key===b)return A.starterExample;if(A.advancedExample?.key===b)return A.advancedExample}return}function Jn($,b){return a6($,b.flatMap((A)=>A.track.connectSurfaces))}function p6($){return{meta:{key:"contractspec.onboarding",version:"1.0.0",title:"ContractSpec Onboarding Journey"},routes:$.map((A)=>({defaultSurface:A.id,path:`/onboard/${A.id}`,routeId:`onboard-${A.id}`})),surfaces:Object.fromEntries($.map((A)=>[A.id,{commands:A.recommendedCommands.map((m,n)=>({commandId:`${A.id}-${n}`,intent:`Run ${m}`,title:m})),data:[{hydrateInto:"track",recipeId:`track-${A.id}`,source:{entityType:`onboarding.${A.id}`,kind:"entity"}}],kind:"workbench",layouts:[{layoutId:`${A.id}-guided`,root:{slotId:"primary",type:"slot"}}],slots:[{accepts:["rich-doc","assistant-panel"],cardinality:"many",role:"primary",slotId:"primary"}],surfaceId:A.id,title:A.title,verification:{dimensions:{control:"Guided onboarding stays within repo-local safe commands.",dataDepth:"Track explains starter and advanced examples.",density:"Readable onboarding layout supports quick scanning.",guidance:"Wizard posture remains explicit and progressive.",media:"Text-first guidance remains valid for CLI and MCP.",narrative:"Top-down journey starts with the primary track and expands outward.",pace:"Progression stays incremental and bounded."}}}]))}}function a6($,b){return[...new Set([...$,...b])].sort()}async function e6($,b={}){let A=await l$($.fs,b),m=Zy(b.selectedTracks),n=Gy(A.config),w=[...await Promise.all(m.map(async(X)=>{let Y=await Xb($,{config:A.config,cwd:A.cwd,family:X.reuseFamily,packageRoot:A.packageRoot,platform:X.adoptionPlatform,query:X.adoptionQuery,workspaceRoot:A.workspaceRoot});return{reason:Y.reason,resolution:Y,score:Y.selected?.score??0,selected:!1,track:X}}))].sort((X,Y)=>Y.score-X.score).map((X,Y)=>({...X,selected:Y===0})),j=w[0]?.track;if(!j)throw Error("No onboarding tracks are available.");let{journeyContext:y,journeyPlan:B}=await Qy(j,m,A.workspaceRoot,A.packageRoot),S=Yy(j,b.forcedExampleKey)??j.starterExample,Q=$7(["contractspec onboard",...j.recommendedCommands,"contractspec doctor"]),Z=Xy(n),G={agentGuidePath:b.agentGuidePath??"AGENTS.md",builderMode:n,builderNextSteps:Z,config:A.config,cwd:A.cwd,humanGuidePath:b.humanGuidePath??"USAGE.md",journeyContext:y,journeyPlan:B,nextCommands:Q,packageRoot:A.packageRoot,primaryTrack:j,recommendations:w,selectedExample:S,workspaceRoot:A.workspaceRoot};return{...G,guides:Vn(G)}}async function s6($,b){if(!b.config.connect?.enabled)return;let A=`task_onboard_${b.primaryTrack.id.replaceAll("-","_")}`,m=[b.agentGuidePath,b.humanGuidePath],n=await Tb($,{config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:m,taskId:A,workspaceRoot:b.workspaceRoot}),W=await gb($,{candidate:{objective:`Onboard this repository for ${b.recommendations.map((w)=>w.track.id).join(", ")}`,steps:b.recommendations.map((w)=>({commands:w.track.recommendedCommands,paths:m,summary:`Adopt ${w.track.title}`})),touchedPaths:m},config:b.config,cwd:b.cwd,packageRoot:b.packageRoot,paths:m,taskId:A,workspaceRoot:b.workspaceRoot});return{contextPack:{...n,affectedSurfaces:Jn(n.affectedSurfaces,b.recommendations)},planPacket:{...W.planPacket,affectedSurfaces:Jn(W.planPacket.affectedSurfaces,b.recommendations)}}}function $7($){return[...new Set($)]}var qy=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],b7=[...qy,{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 Kn($){return $==="minimal"?qy:b7}function _n($){return $.filter((b)=>!b.dev)}function Un($){return $.filter((b)=>b.dev)}import{exec as A7}from"node:child_process";import{promisify as m7}from"node:util";var n7=m7(A7),W7={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function ML($,b,A=W7){let m=Kn(b.mode),n=_n(m),W=Un(m),w=[],j=[],y=[],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),G=new Set([...Object.keys(Z.dependencies??{}),...Object.keys(Z.devDependencies??{})]),X=o$(b.workspaceRoot),Y=n.filter((J)=>{if(G.has(J.name)&&!b.force)return j.push({name:J.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),V=W.filter((J)=>{if(G.has(J.name)&&!b.force)return j.push({name:J.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(b.dryRun){let J=[...Y,...V];return{success:!0,installed:J.map((_)=>({name:_.name,action:"installed",message:`Would install: ${_.description}`,dev:_.dev})),skipped:j,errors:[],summary:`Dry run: would install ${J.length} package(s), skip ${j.length}.`}}if(!b.skipPrompts&&(Y.length>0||V.length>0)){let J=Y.length+V.length;if(!await A.confirm(`Install ${J} package(s) using ${X}?`))return{success:!0,installed:[],skipped:[...j,...Y.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(Y.length>0){let J=await Oy(Y,X,b.workspaceRoot,!1);for(let _ of J)if(_.action==="installed")w.push(_);else y.push(_)}if(V.length>0){let J=await Oy(V,X,b.workspaceRoot,!0);for(let _ of J)if(_.action==="installed")w.push(_);else y.push(_)}let O=y.length===0,K=O?`Successfully installed ${w.length} package(s), skipped ${j.length}.`:`Installed ${w.length}, skipped ${j.length}, failed ${y.length}.`;return{success:O,installed:w,skipped:j,errors:y,summary:K}}async function Oy($,b,A,m){let n=[],W=$.map((w)=>w.version?`${w.name}@${w.version}`:w.name);try{let j=`${VW(b,m)} ${W.join(" ")}`;await n7(j,{cwd:A,timeout:120000});for(let y of $)n.push({name:y.name,action:"installed",message:y.description,dev:m})}catch(w){let j=w instanceof Error?w.message:String(w);for(let y of $)n.push({name:y.name,action:"error",message:`Failed to install: ${j}`,dev:m})}return n}async function xL($,b){let A=$.join(b,"package.json");try{let m=await $.readFile(A),n=JSON.parse(m);return"@contractspec/lib.contracts-spec"in{...n.dependencies,...n.devDependencies}}catch{return!1}}function TL($){let b=Kn($),A=[];A.push(`ContractSpec ${$} installation:`),A.push("");let m=_n(b);if(m.length>0){A.push("Dependencies:");for(let W of m)A.push(` • ${W.name} - ${W.description}`)}let n=Un(b);if(n.length>0){A.push(""),A.push("Dev Dependencies:");for(let W of n)A.push(` • ${W.name} - ${W.description}`)}return A.join(`
|
|
2324
|
+
`)}import{RegeneratorService as w7}from"@contractspec/lib.contracts-spec/regenerator";function PL($){return new w7({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class S0{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let b=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,A;try{A=await fetch(b,{method:"GET",headers:{Accept:"application/json"}})}catch(m){throw Error(`Registry request failed: ${b} (${m instanceof Error?m.message:String(m)})`)}if(!A.ok){let m=await A.text().catch(()=>"");throw Error(`Registry request failed: ${A.status} ${A.statusText} ${m}`)}return await A.json()}}function zn($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function fL($,b,A){let{logger:m}=A,n=zn(b.registryUrl);m.info(`Adding spec to registry: ${$}`,{registryUrl:n}),await new S0({registryUrl:n}).getJson(`/specs/add?path=${encodeURIComponent($)}`),m.info("Spec added to registry successfully")}async function hL($,b){let{logger:A}=b,m=zn($.registryUrl);A.info("Listing specs from registry",{registryUrl:m});let n=new S0({registryUrl:m}),W=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",w=await n.getJson(`/specs${W}`);return A.info(`Found ${w.length} specs`),w}async function cL($,b,A){let{logger:m}=A,n=zn(b.registryUrl);m.info(`Searching registry: ${$}`,{registryUrl:n});let w=await new S0({registryUrl:n}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return m.info(`Found ${w.length} results`),w}class j7{fs;logger;constructor($,b){this.fs=$;this.logger=b}async sync($){let{config:b,cwd:A}=$,m=$.targets??b.targets??[];if(!b.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${m.join(", ")}...`);try{let n=this.fs.join(A,b.rulesDir??".rules");if(!await this.fs.exists(n))return{success:!1,files:[],errors:[`Rules directory not found: ${n}`]};let w=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${w}`);let j=[];for(let y of m){let B=this.getTargetFileName(y);if(B){let S=this.fs.join(A,B);j.push(S)}}return{success:!0,files:j,logs:[`Successfully synchronized rules to ${j.length} targets.`]}}catch(n){let W=n instanceof Error?n.message:String(n);return this.logger.error(`Rule synchronization failed: ${W}`),{success:!1,files:[],errors:[W]}}}async generateConfig($){let{config:b}=$,A={rules:(b.rules??[]).map((m)=>this.fs.join(b.rulesDir??".rules",m)),targets:$.targets||b.targets};return JSON.stringify(A,null,2)}getTargetFileName($){switch($){case"cursor":return".cursorrules";case"windsurf":return".windsurfrules";case"cline":return".clinerules";case"claude-code":return"CLAUDE.md";case"copilot":return".github/copilot-instructions.md";case"subagent":return".subagent";case"skill":return".skill";default:return}}}function Q0($,b,A,m){let n=ub(b,A),W=y7(A);if(W.test($))return $.replace(W,n);if(m&&Ln($)===Ln(m))return n;return`${n}${$}`}function ub($,b){let A=Ln($);return`${b.startMarker}
|
|
2325
|
+
${b.note}
|
|
2326
|
+
${A}
|
|
2327
|
+
${b.endMarker}
|
|
2328
|
+
`}function Ln($){return $.replace(/\r\n/g,`
|
|
2329
|
+
`).trimEnd()}function y7($){return new RegExp(`${Vy($.startMarker)}[\\s\\S]*?${Vy($.endMarker)}(?:\\r?\\n)?`)}function Vy($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var B7="<!-- contractspec:init:agents:start -->",S7="<!-- contractspec:init:agents:end -->",Q7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Jy={endMarker:S7,note:Q7,startMarker:B7};async function Rn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"AGENTS.md");try{let W=await $.exists(n),w=fw(b);if(W){let j=await $.readFile(n);if(b.interactive){if(!await A.confirm(`${n} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:n,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(n,Q0(j,w,Jy,w)),{target:"agents-md",filePath:n,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(n,ub(w,Jy)),{target:"agents-md",filePath:n,action:"created",message:"Created AI agent guide"}}catch(W){return{target:"agents-md",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}import{generateArtifactsForAudience as Z7,generateBiomePreset as G7}from"@contractspec/biome-config";async function Cn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"biome.jsonc"),W=$.join(m,".contractspec","biome"),w=$.join(W,"plugins"),j=$.join(W,"ai"),y=Z7("consumer");try{let B=await $.exists(n);if(B&&b.interactive){if(!await A.confirm(`${n} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:n,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(w),await $.mkdir(j),await $.writeFile(n,G7("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[S,Q]of Object.entries(y.plugins))await $.writeFile($.join(w,S),Q);return await $.writeFile($.join(j,"consumer.md"),y.aiRules),{target:"biome-config",filePath:n,action:B?"merged":"created",message:B?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(B){return{target:"biome-config",filePath:n,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function In($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,".contractsrc.json");try{let W=await $.exists(n),w=bb(b);if(W){let j=await $.readFile(n),y=p(j);if(!y)return{target:"cli-config",filePath:n,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${n} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:n,action:"skipped",message:"User skipped merge"}}let B=$$(y,w);if((b.preset==="connect"||b.preset?.startsWith("builder-"))&&typeof w==="object"&&w!==null){let S={};if("connect"in w)S.connect=w.connect;if("builder"in w)S.builder=w.builder;await $.writeFile(n,N(Vm(B,S)))}else await $.writeFile(n,N(B));return{target:"cli-config",filePath:n,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(n,N(w)),{target:"cli-config",filePath:n,action:"created",message:"Created CLI configuration"}}catch(W){return{target:"cli-config",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function En($,b,A){let m=$.join(b.workspaceRoot,".cursor","rules"),n=$.join(m,"contractspec.mdc");try{let W=$.join(b.workspaceRoot,".cursor");if(!await $.exists(W))await $.mkdir(W);if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(n),j=rw(b);if(w)if(b.interactive){if(!await A.confirm(`${n} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:n,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:n,action:"skipped",message:"File already exists"};return await $.writeFile(n,j),{target:"cursor-rules",filePath:n,action:w?"merged":"created",message:w?"Updated Cursor rules":"Created Cursor rules"}}catch(W){return{target:"cursor-rules",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function Mn($,b,A){let m=gA();try{let n=await $.exists(m),W=Pw();if(b.interactive){if(!await A.confirm(`Configure Claude Desktop at ${m}?`))return{target:"mcp-claude",filePath:m,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(n){let y=await $.readFile(m),B=p(y);if(!B)return{target:"mcp-claude",filePath:m,action:"error",message:"Existing file is not valid JSON"};let S=$$(B,W);return await $.writeFile(m,N(S)),{target:"mcp-claude",filePath:m,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let w=m.substring(0,m.lastIndexOf("/"));if(!await $.exists(w))await $.mkdir(w);return await $.writeFile(m,N(W)),{target:"mcp-claude",filePath:m,action:"created",message:"Created Claude Desktop configuration"}}catch(n){return{target:"mcp-claude",filePath:m,action:"error",message:n instanceof Error?n.message:"Unknown error"}}}async function xn($,b,A){let m=$.join(b.workspaceRoot,".cursor"),n=$.join(m,"mcp.json");try{if(!await $.exists(m))await $.mkdir(m);let w=await $.exists(n),j=Lb();if(w){let y=await $.readFile(n),B=p(y);if(!B)return{target:"mcp-cursor",filePath:n,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${n} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:n,action:"skipped",message:"User skipped merge"}}let S=$$(B,j);return await $.writeFile(n,N(S)),{target:"mcp-cursor",filePath:n,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(n,N(j)),{target:"mcp-cursor",filePath:n,action:"created",message:"Created Cursor MCP configuration"}}catch(W){return{target:"mcp-cursor",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}var X7="<!-- contractspec:init:usage:start -->",Y7="<!-- contractspec:init:usage:end -->",H7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Ky={endMarker:Y7,note:H7,startMarker:X7};async function Tn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,"USAGE.md");try{let W=await $.exists(n),w=hw(b);if(W){let j=await $.readFile(n);if(b.interactive){if(!await A.confirm(`${n} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"usage-md",filePath:n,action:"skipped",message:"User skipped usage guide merge"}}return await $.writeFile(n,Q0(j,w,Ky,w)),{target:"usage-md",filePath:n,action:"merged",message:"Added or updated the ContractSpec-managed USAGE.md section"}}return await $.writeFile(n,ub(w,Ky)),{target:"usage-md",filePath:n,action:"created",message:"Created usage guide"}}catch(W){return{target:"usage-md",filePath:n,action:"error",message:W instanceof Error?W.message:"Unknown error"}}}async function Dn($,b,A){let m=b.isMonorepo&&b.scope==="package"?b.packageRoot??b.workspaceRoot:b.workspaceRoot,n=$.join(m,".vscode"),W=$.join(n,"settings.json");try{if(!await $.exists(n))await $.mkdir(n);let j=await $.exists(W),y=vA(b);if(j){let B=await $.readFile(W),S=p(B);if(!S)return{target:"vscode-settings",filePath:W,action:"error",message:"Existing file is not valid JSON"};if(b.interactive){if(!await A.confirm(`${W} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:W,action:"skipped",message:"User skipped merge"}}let Q=$$(S,y);if("contractspec.api.baseUrl"in y)Q["contractspec.api.baseUrl"]=y["contractspec.api.baseUrl"];return await $.writeFile(W,N(Q)),{target:"vscode-settings",filePath:W,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(W,N(y)),{target:"vscode-settings",filePath:W,action:"created",message:"Created VS Code settings"}}catch(w){return{target:"vscode-settings",filePath:W,action:"error",message:w instanceof Error?w.message:"Unknown error"}}}var q7={confirm:async($,b)=>b??!0,select:async($,b)=>{return b.find((A)=>A.selected)?.value??b[0]?.value??""},multiSelect:async($,b)=>b.filter((A)=>A.selected!==!1).map((A)=>A.value),input:async($,b)=>b??""};async function MR($,b,A=q7){let m=[],n=b.targets.length>0?b.targets:_b,W=b.workspaceRoot,w=M(W),j=b.packageRoot??r(W),y=b.isMonorepo??Gb(w),B=b.packageName??(y?T$(j):void 0),S=await _y($,[j,w]),Q=b.preset??zb(S);if(b.interactive&&!b.preset)Q=await A.select("Select initialization preset:",Tw.map((C)=>({value:C,label:Dw[C],description:Nw[C],selected:C===Q})));let Z=b.scope??"workspace",G=j!==w;if(y&&b.interactive&&G)Z=await A.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${B??j})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${w})`,description:"Create config files at the workspace root"}]);let X=y&&Z==="package"?j:w,Y=await _y($,[X]),V={...b,workspaceRoot:w,packageRoot:j,isMonorepo:y,scope:Z,packageName:B,preset:Q,builderApiBaseUrl:b.builderApiBaseUrl??Y?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:b.builderControlPlaneTokenEnvVar??Y?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:b.builderLocalRuntimeId??Y?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:b.builderLocalGrantedTo??Y?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:b.builderLocalProviderIds??Y?.builder?.localRuntime?.providerIds,connectStudioEndpoint:b.connectStudioEndpoint??Y?.connect?.studio?.endpoint,connectStudioQueue:b.connectStudioQueue??Y?.connect?.studio?.queue},O=Fw(Q,n);if(b.interactive)O=await A.multiSelect("Select components to configure:",_b.map((C)=>({value:C,label:xw[C],selected:O.includes(C)})));let K=V.projectName;if(b.interactive&&!K){let C=Z==="package"&&B?B:X.split("/").pop()??"my-project";K=await A.input("Project name:",C)}let J=V.builderApiBaseUrl;if(b.interactive&&Q.startsWith("builder-"))J=await A.input("Builder API base URL:",J??"https://api.contractspec.io");let{builderLocalRuntimeId:_,builderLocalGrantedTo:H}=V;if(b.interactive&&(Q==="builder-local"||Q==="builder-hybrid"))_=await A.input("Default local runtime target id:",_??"rt_local_daemon"),H=await A.input("Default local runtime grant target:",H??"local:operator");let q={...V,projectName:K,targets:O,builderApiBaseUrl:J,builderLocalRuntimeId:_,builderLocalGrantedTo:H};for(let C of O){let F=await O7($,C,q,A);m.push(F)}let U=await sA($,{behavior:q.gitignoreBehavior,interactive:q.interactive,patterns:kw({preset:Q}),prompts:A,root:w});if(q.gitignoreBehavior!=="skip"||U.action!=="skipped")m.push(U);let z=m.filter((C)=>C.action!=="error").length,L=m.filter((C)=>C.action==="error").length,I=y?` (${Z} level)`:"";return{success:L===0,preset:Q,files:m,summary:`Setup complete${I}: ${z} configured, ${L} failed.`,nextSteps:gw(q)}}async function O7($,b,A,m){switch(b){case"agents-md":return Rn($,A,m);case"cli-config":return In($,A,m);case"biome-config":return Cn($,A,m);case"vscode-settings":return Dn($,A,m);case"mcp-cursor":return xn($,A,m);case"mcp-claude":return Mn($,A,m);case"cursor-rules":return En($,A,m);case"usage-md":return Tn($,A,m);default:return{target:b,filePath:"",action:"error",message:`Unknown target: ${b}`}}}async function _y($,b){for(let A of b){let m=$.join(A,".contractsrc.json");if(!await $.exists(m))continue;let n=p(await $.readFile(m));if(n)return n}return null}import{validateBlueprint as V7}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as J7}from"path";async function uR($,b){let{fs:A}=b,m=J7(process.cwd(),$);if(!await A.exists(m))return{valid:!1,errors:[`Blueprint file not found: ${m}`]};try{let n=await n$(m),W=K7(n.exports),w=V7(W);return{spec:W,report:w,valid:w.valid,errors:w.errors.map((j)=>`[${j.code}] ${j.path}: ${j.message}`)}}catch(n){return{valid:!1,errors:[n instanceof Error?n.message:String(n)]}}}function K7($){let b=Object.values($).filter(_7);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function _7($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as U7,dirname as Nn,join as ob}from"path";async function tR($,b,A,m,n){let{fs:W}=n,w=m.implementationPath;if(!w){let S=Nn($),Q=U7($,".ts"),Z=[ob(S,Q.replace(".contracts",".handler")+".ts"),ob(S,Q.replace(".presentation","")+".tsx"),ob(S,Q.replace(".form",".form")+".tsx"),ob(Nn(S),"handlers",Q.replace(".contracts",".handler")+".ts"),ob(Nn(S),"components",Q.replace(".presentation","")+".tsx")];for(let G of Z)if(await W.exists(G)){w=G;break}}if(!w||!await W.exists(w))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let j=await W.readFile(w),B=await new BA(A).validate(b,j);return{success:B.success,errors:B.errors||[],warnings:B.warnings||[],suggestions:B.suggestions||[],report:B.code}}import{validateBuilderBlueprint as z7,validateBuilderReadinessReport as L7,validateBuilderWorkspace as R7,validateBuilderWorkspaceSnapshot as C7}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as I7,validateExternalPatchProposal as E7,validateProviderRoutingPolicy as M7,validateRuntimeTarget as x7}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as T7,validateLayoutSlots as D7}from"@contractspec/lib.surface-runtime/spec";async function bC($,b){if(!k7($.specType))return{valid:!0,errors:[],warnings:[]};let A=l7($.filePath),m=[`${A}/package.json`,`${A}/README.md`,`${A}/src/index.ts`,$.filePath],n=[];for(let j of m)if(!await b.exists(j))n.push(`Missing package scaffold file: ${j}`);if(n.length>0)return{valid:!1,errors:n,warnings:[]};let W;try{W=(await n$($.filePath)).exports}catch(j){return{valid:!1,errors:[j instanceof Error?j.message:String(j)],warnings:[]}}let w=$.specType==="module-bundle"?N7(W):$.specType==="builder-spec"?F7(W):v7(W);return{valid:n.length===0&&w.errors.length===0,errors:[...n,...w.errors],warnings:w.warnings.map((j)=>`[${$.filePath}] ${j}`)}}function N7($){let b=[],A=[],m=g7($,P7);if(m.length===0)return A.push(Fn("module-bundle","bundle")),{errors:b,warnings:A};for(let n of m){let W=Object.values(n.value.surfaces);for(let w of W){try{D7(w)}catch(j){b.push(`[${n.exportName}] ${j instanceof Error?j.message:String(j)}`)}for(let j of T7(w).warnings)A.push(`[${n.exportName}] ${j}`)}}return{errors:b,warnings:A}}function F7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(r7(W)){m+=1,b.push(...Z0(n,R7(W)));continue}if(f7(W)){m+=1,b.push(...Z0(n,z7(W)));continue}if(h7(W)){m+=1,b.push(...Z0(n,L7(W)));continue}if(c7(W))m+=1,b.push(...Z0(n,C7(W)))}if(m===0)A.push(Fn("builder-spec","builder"));return{errors:b,warnings:A}}function v7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(d7(W)){m+=1,b.push(...G0(n,x7(W)));continue}if(u7(W)){m+=1,b.push(...G0(n,M7(W)));continue}if(o7(W)){m+=1,b.push(...G0(n,I7(W)));continue}if(i7(W))m+=1,b.push(...G0(n,E7(W)))}if(m===0)A.push(Fn("provider-spec","provider"));return{errors:b,warnings:A}}function g7($,b){return Object.entries($).filter(([A,m])=>A!=="__esModule"&&b(m)).map(([A,m])=>({exportName:A,value:m}))}function Z0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function G0($,b){return b.map((A)=>`[${$}] ${A.path}: ${A.message}`)}function k7($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function P7($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function r7($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function f7($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function h7($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function c7($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function d7($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function u7($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function o7($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function i7($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function l7($){let b=$.replaceAll("\\","/"),A=b.lastIndexOf("/src/");return A===-1?b.replace(/\/[^/]+$/,""):b.slice(0,A)}function Fn($,b){return`No recognized ${b} exports were found for ${$} deep validation.`}import{validateBlueprint as t7}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as p7}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as a7}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as e7}from"@contractspec/module.workspace";async function zy($,b={}){let A=[],m=[],n;if(!b.skipStructure){n=e7($),A.push(...n.errors),m.push(...n.warnings);let W=await s7($);A.push(...W.errors),m.push(...W.warnings)}return{valid:A.length===0,structureResult:n,errors:A,warnings:m,code:$.sourceBlock}}async function BC($,b={}){return Promise.all($.map(async(A)=>({spec:A,...await zy(A,b)})))}async function d$($,b,A={}){let{fs:m}=b;if(!await m.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let W=await m.readFile($),w=[],j=[],y=void 0;if(!A.skipStructure){let B=await j$(b,{pattern:$});for(let S of B){let Q=await zy(S,A);y=Q.structureResult,w.push(...Q.errors),j.push(...Q.warnings)}}return{valid:w.length===0,structureResult:y,errors:w,warnings:j,code:W}}async function SC($,b,A={}){let m=new Map;for(let n of $){let W=await d$(n,b,A);m.set(n,W)}return m}async function s7($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await n$($.filePath);if($.specType==="app-config"){let n=$Z(b.exports,$),W=t7(n);return{errors:W.errors.map((w)=>Uy(w)),warnings:[...W.warnings,...W.info].map((w)=>Uy(w))}}if($.specType==="feature"){let n=bZ(b.exports,$),W=p7(n);return{errors:W.issues.filter((w)=>w.level==="error").map((w)=>X0(w)),warnings:W.issues.filter((w)=>w.level!=="error").map((w)=>X0(w))}}let A=AZ(b.exports,$),m=a7(A);return{errors:m.issues.filter((n)=>n.level==="error").map((n)=>X0(n)),warnings:m.issues.filter((n)=>n.level!=="error").map((n)=>X0(n))}}catch(b){return{errors:[b instanceof Error?b.message:`Validation failed: ${String(b)}`],warnings:[]}}}function $Z($,b){return vn($,b.exportName,mZ)}function bZ($,b){return vn($,b.exportName,nZ)}function AZ($,b){return vn($,b.exportName,WZ)}function vn($,b,A){if(b&&A($[b]))return $[b];let m=Object.values($).find(A);if(!m)throw Error("Expected authored module to export a compatible spec value.");return m}function mZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function nZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function WZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&"tokens"in $}function Uy($){let b=$.code?`[${$.code}] `:"",A=$.path?`${$.path}: `:"";return`${b}${A}${$.message}`}function X0($){return $.path?`${$.path}: ${$.message}`:$.message}import{validateConfig as wZ}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as kn}from"fs/promises";import{resolve as Y0}from"path";async function HC($,b,A,m){let{fs:n}=m,W=Y0(process.cwd(),b);if(!await n.exists(W))return{valid:!1,errors:[`Tenant config file not found: ${W}`]};try{let w=await jZ(W),j=await yZ(A.connections,n),y=await BZ(A.translationCatalog,n),B=await SZ(A.integrationRegistrars),S={};if(j.length>0)S.tenantConnections=j;if(y)S.translationCatalogs={blueprint:[y],platform:[]};if(B)S.integrationSpecs=B;let Q=wZ($,w,S);return{config:w,report:Q,valid:Q.valid,errors:Q.errors.map((Z)=>`[${Z.code}] ${Z.path}: ${Z.message}`)}}catch(w){return{valid:!1,errors:[w instanceof Error?w.message:String(w)]}}}async function jZ($){if($.endsWith(".json")){let m=await kn($,"utf-8"),n=JSON.parse(m);if(!Ly(n))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return n}let b=await n$($),A=Object.values(b.exports).filter(Ly);if(A.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return A[0]}function Ly($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function Ey($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((A)=>A.trim()).filter(Boolean)}async function yZ($,b){let A=Ey($);if(!A.length)return[];let m=[];for(let n of A){let W=Y0(process.cwd(),n);if(!await b.exists(W)){console.warn(`Warning: Connection file not found: ${W}`);continue}if(W.endsWith(".json")){let j=await kn(W,"utf-8"),y=JSON.parse(j);m.push(...gn(y));continue}let w=await n$(W);m.push(...gn(w.exports))}return m}function gn($){if(Array.isArray($)){let b=$.filter(Ry);if(b.length)return b}if(Ry($))return[$];if($&&typeof $==="object"){let A=Object.values($).flatMap((m)=>gn(m));if(A.length)return A}return[]}function Ry($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function BZ($,b){if(!$)return;let A=Y0(process.cwd(),$);if(!await b.exists(A))return;if(A.endsWith(".json")){let W=await kn(A,"utf-8"),w=JSON.parse(W);if(Cy(w))return Iy(w);return}let m=await n$(A),n=Object.values(m.exports).filter(Cy);if(n.length===0)return;return Iy(n[0])}function Cy($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function Iy($){let b=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:b}}async function SZ($){let b=Ey($);if(!b.length)return;let{IntegrationSpecRegistry:A}=await import("@contractspec/lib.contracts-integrations"),m=new A;for(let n of b){let{modulePath:W,exportName:w}=QZ(n);if(!W)continue;let j=Y0(process.cwd(),W);try{let y=await n$(j),B=ZZ(y.exports,w);if(B)await B(m)}catch(y){console.warn(`Failed to load registrar from ${j}: ${y}`)}}return m}function QZ($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),m=b?.trim()??null,n=A?.trim();return{modulePath:m,exportName:n}}function ZZ($,b){if(b){let A=$[b];if(typeof A==="function")return A;return}if(typeof $.default==="function")return $.default;for(let A of Object.values($))if(typeof A==="function")return A;return}async function CC($,b,A={},m){let{fs:n,logger:W}=$,w=await n.glob({pattern:A.pattern}),j=A.outputDirs?.length?A.outputDirs:[void 0],y=[],B=m?.validate??((Q)=>d$(Q,{fs:n,logger:W})),S=m?.build??((Q,Z)=>$b(Q,{fs:n,logger:W},Z?{...b,outputDir:Z}:b,{...A.buildOptions??{},outputDir:Z}));for(let Q of w)for(let Z of j){let G={specPath:Q,outputDir:Z};if(A.validate)try{G.validation=await B(Q)}catch(X){G.error={phase:"validate",message:X instanceof Error?X.message:String(X)},y.push(G);continue}if(!A.dryRun)try{G.build=await S(Q,Z)}catch(X){G.error={phase:"build",message:X instanceof Error?X.message:String(X)},y.push(G);continue}else W.info("[dry-run] syncSpecs skipped build",{specPath:Q,outputDir:Z});y.push(G)}return{specs:w,runs:y}}import{generateText as GZ}from"ai";var XZ=`
|
|
2010
2330
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2011
2331
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2012
2332
|
|
|
@@ -2024,7 +2344,7 @@ Generate scenarios covering:
|
|
|
2024
2344
|
- Happy path (valid input, successful execution)
|
|
2025
2345
|
- Edge cases (boundary values, optional fields)
|
|
2026
2346
|
- Error cases (invalid input, business rule violations)
|
|
2027
|
-
`.trim();class
|
|
2347
|
+
`.trim();class YZ{logger;defaultModel;constructor($,b){this.logger=$;this.defaultModel=b}async generateTests($,b={}){let A=b.model??this.defaultModel;if(!A)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let m=`
|
|
2028
2348
|
Generate a TestSpec for the following Operation:
|
|
2029
2349
|
|
|
2030
2350
|
\`\`\`json
|
|
@@ -2033,23 +2353,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2033
2353
|
|
|
2034
2354
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2035
2355
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2036
|
-
`.trim();try{let{text:
|
|
2037
|
-
`)}function
|
|
2038
|
-
`)}function
|
|
2039
|
-
`);for(let
|
|
2040
|
-
`)}function
|
|
2356
|
+
`.trim();try{let{text:n,usage:W}=await GZ({model:A,system:XZ,prompt:m});this.logUsage(W);let w=this.parseResponse(n);return this.enrichSpec(w,$)}catch(n){throw this.logger.error("Failed to generate tests",{error:n}),n}}parseResponse($){try{let b=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(b)}catch(b){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,b){let A={key:`${b.meta.key}.test`,version:b.meta.version??"0.0.1",owners:b.meta.owners??[]},m={type:"operation",operation:{key:b.meta.key,version:b.meta.version}};return{meta:A,target:m,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 My}from"@contractspec/lib.contracts-spec";import{TestRunner as xy}from"@contractspec/lib.contracts-spec/tests";import{resolve as Pn}from"path";async function FC($,b){let A=new xy({registry:b}),m=[],n=0,W=0;for(let w of $){let j=await A.run(w);m.push(j),n+=j.passed,W+=j.failed}return{results:m,passed:n,failed:W}}async function vC($,b,A){let{logger:m}=A,n;if(b.registry)n=await qZ(Pn(b.registry));else n=new My,m.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let W=new xy({registry:n}),w=[],j=!0;for(let y of $)try{let B=Pn(y),S=await y0(B),Q=Ty(S);if(Q.length===0){m.warn(`No TestSpec exports found in ${y}`);continue}for(let Z of Q){m.info(`Running ${Z.meta.key}...`);let G=await W.run(Z);if(w.push(G),G.failed>0)j=!1,m.error(`${Z.meta.key} failed (${G.failed}/${G.scenarios.length})`);else m.info(`${Z.meta.key} passed (${G.passed}/${G.scenarios.length})`)}}catch(B){m.error(`Failed to load/run spec ${y}: ${B instanceof Error?B.message:String(B)}`),j=!1}return{results:w,passed:j}}async function gC($,b){let A=[];for(let m of $)try{let n=Pn(m),W=await y0(n),w=Ty(W);A.push(...w)}catch(n){b.logger.warn(`Failed to load tests from ${m}: ${n instanceof Error?n.message:String(n)}`)}return A}function Ty($){let b=[];for(let A of Object.values($))if(HZ(A))b.push(A);return b}function HZ($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function qZ($){return yy($,{description:"OperationSpecRegistry",isValue:(b)=>b instanceof My,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as ib}from"@contractspec/module.workspace";import{IndentationText as OZ,Node as jb,Project as VZ,QuoteKind as JZ,SyntaxKind as KZ}from"ts-morph";function _Z($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function uC($,b,A={}){let{fs:m,logger:n}=b;if(!await m.exists($))return{specPath:$,specInfo:_Z($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let w=await m.readFile($),j;if(A.content!==void 0)j=A.content;else if(A.fields?.length)j=UZ(w,A.fields);else return{specPath:$,specInfo:ib(w,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!A.skipValidation){await m.writeFile($,j);let y=await d$($,b);if(y.errors.length>0)return await m.writeFile($,w),{specPath:$,specInfo:ib(j,$),updated:!1,errors:y.errors,warnings:y.warnings};if(y.warnings.length>0&&!A.allowWarnings)return await m.writeFile($,w),{specPath:$,specInfo:ib(j,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:y.warnings};return n.info(`Updated spec: ${$}`),{specPath:$,specInfo:ib(j,$),updated:!0,errors:[],warnings:y.warnings}}return await m.writeFile($,j),n.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:ib(j,$),updated:!0,errors:[],warnings:[]}}function UZ($,b){let m=new VZ({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:OZ.TwoSpaces,quoteKind:JZ.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),n=LZ(m);if(!n)return $;for(let W of b)zZ(n,W);return m.getFullText()}function zZ($,b){let A=b.key.split(".").map((j)=>j.trim()).filter(Boolean);if(A.length===0)return;let m=$;for(let j of A.slice(0,-1)){if(!m.getProperty(j))m.addPropertyAssignment({name:j,initializer:"{}"});let B=m.getPropertyOrThrow(j);if(!jb.isPropertyAssignment(B))return;let S=B.getInitializer();if(!S||!jb.isObjectLiteralExpression(S))B.setInitializer("{}");let Q=B.getInitializerIfKind(KZ.ObjectLiteralExpression);if(!Q)return;m=Q}let n=A[A.length-1];if(!n)return;let W=RZ(b.value),w=m.getProperty(n);if(w&&jb.isPropertyAssignment(w)){w.setInitializer(W);return}m.addPropertyAssignment({name:n,initializer:W})}function LZ($){for(let b of $.getVariableDeclarations()){let A=b.getInitializer();if(!A)continue;if(jb.isObjectLiteralExpression(A))return A;if(jb.isCallExpression(A)){let m=A.getArguments()[0];if(m&&jb.isObjectLiteralExpression(m))return m}}return}function RZ($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var ly={};P(ly,{getPackageUpgradeCommand:()=>hy,getDefaultVersioningConfig:()=>q0,getDefaultHooksConfig:()=>O0,applyGuidedUpgrade:()=>iy,applyConfigUpgrades:()=>fy,analyzeUpgrades:()=>H0,analyzeGuidedUpgrade:()=>cn});import{GeneratedReleaseManifestSchema as uy}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as FZ,DEFAULT_CONTRACTSRC as vZ}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function Dy($){return $.packages.map((b)=>{let A=b.version?`@${b.version}`:"";return`- ${b.name}${A} (${b.releaseType})`})}function Ny($){return $.map((b)=>` - ${b}`)}function rn($,b){return $.audiences.filter((A)=>b.includes(A.kind)).map((A)=>`- ${CZ(A.kind)}: ${A.summary}`)}function Fy($){let b=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...Dy($),...rn($,["maintainer"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));return b.join(`
|
|
2357
|
+
`)}function vy($){let b=[`### ${$.summary}`,...Dy($),...rn($,["customer","integrator"])];if($.deprecations.length>0)b.push("- Deprecations:"),b.push(...$.deprecations.map((A)=>` - ${A}`));for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`);return b.join(`
|
|
2358
|
+
`)}function gy($){let b=[`### ${$.summary}`,...rn($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2359
|
+
`);for(let A of $.migrationInstructions)b.push(`- ${A.title}: ${A.summary}`),b.push(...Ny(A.steps));if($.upgradeSteps.length>0){b.push("- Upgrade steps:");for(let A of $.upgradeSteps)b.push(` - [${A.level}] ${A.title}: ${A.summary}`),b.push(...A.instructions.map((m)=>` - ${m}`))}return b.join(`
|
|
2360
|
+
`)}function fn($){return["# Patch Notes","",...$.releases.map(Fy)].join(`
|
|
2041
2361
|
|
|
2042
|
-
`)}function
|
|
2362
|
+
`)}function hn($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[vy(b),"",gy(b)])].join(`
|
|
2043
2363
|
|
|
2044
|
-
`)}function
|
|
2364
|
+
`)}function ky($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((b)=>[`- [${b.level}] ${b.title}: ${b.summary}`,...Ny(b.instructions)].join(`
|
|
2045
2365
|
`)).join(`
|
|
2046
|
-
`)}function
|
|
2047
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2048
|
-
`)}import{compareVersions as
|
|
2049
|
-
`),
|
|
2050
|
-
`),!0}async function
|
|
2051
|
-
`),!0}async function
|
|
2052
|
-
`),
|
|
2366
|
+
`)}function yb($,b){let A=b.targetPackages.map((m)=>`${m.name}: ${m.currentVersion??"unknown"} -> ${m.targetVersion??"latest"}`).join(`
|
|
2367
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",A||"- No package version targets were inferred.","","Required steps:",ky(b)].join(`
|
|
2368
|
+
`)}function CZ($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as ry,countUpgradePlanStepLevels as IZ,createAgentPromptBundles as EZ,dedupeUpgradePlanSteps as MZ,sortReleaseManifest as Py}from"@contractspec/lib.contracts-spec";function xZ($,b){if(b.length===0)return Py($);let A=new Map(b.map((m)=>[m.name,m.currentVersion??"0.0.0"]));return Py({...$,releases:$.releases.filter((m)=>m.packages.some((n)=>{let W=A.get(n.name);if(!W||!n.version)return!1;return ry(n.version,W)===1}))})}function lb($,b,A,m){let n=xZ($,b),W=TZ(n,b),w=MZ(n.flatMap((S)=>S.upgradeSteps)),j=IZ(w),y={generatedAt:new Date().toISOString(),targetPackages:W,releases:n,steps:w,autofixCount:j.auto,manualCount:j.manual,assistedCount:j.assisted,agentPrompts:[]},B=EZ(y,A,m);return{...y,agentPrompts:B}}function TZ($,b){let A=new Map(b.map((n)=>[n.name,n.currentVersion])),m=new Map;for(let n of $)for(let W of n.packages){let w=A.get(W.name),j=m.get(W.name);if(!j){m.set(W.name,{name:W.name,currentVersion:w,targetVersion:W.version});continue}if(W.version&&j.targetVersion&&ry(W.version,j.targetVersion)===1)j.targetVersion=W.version}return Array.from(m.values()).sort((n,W)=>n.name.localeCompare(W.name))}async function H0($,b){let{fs:A,logger:m}=$,n=r(b.workspaceRoot),W=M(b.workspaceRoot),w=o$(W);m.info("Analyzing available upgrades...",{workspaceRoot:W,packageRoot:n,packageManager:w});let j=await DZ(A,n),y=await NZ(A,n,W),B=j.length>0||y.length>0;return{packageManager:w,packages:j,configUpgrades:y,hasUpgrades:B}}async function DZ($,b){let A=$.join(b,"package.json");if(!await $.exists(A))return[];try{let m=await $.readFile(A),n=JSON.parse(m),W=n.dependencies??{},w=n.devDependencies??{},j=[],y={...W,...w};for(let[B,S]of Object.entries(y))if(B.startsWith("@contractspec/")||B==="contractspec"||B.startsWith("@lssm/"))j.push({name:B,currentVersion:S,isDevDependency:!!w[B]});return j}catch{return[]}}async function NZ($,b,A){let m=$.join(b,".contractsrc.json"),n=Kb({configRoot:b,workspaceRoot:A});if(!await $.exists(m))return[];try{let W=await $.readFile(m),w=JSON.parse(W),j=[],y=w.$schema;if(!y||y!==n)j.push({key:"$schema",currentValue:y,suggestedValue:n,isNew:!y});if(!w.versioning)j.push({key:"versioning",currentValue:void 0,suggestedValue:q0(),isNew:!0});else if(w.versioning.integrateWithChangesets===void 0)j.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!w.hooks)j.push({key:"hooks",currentValue:void 0,suggestedValue:O0(),isNew:!0});if(!w.release)j.push({key:"release",currentValue:void 0,suggestedValue:cy(),isNew:!0});if(!w.upgrade)j.push({key:"upgrade",currentValue:void 0,suggestedValue:dy(),isNew:!0});return j}catch{return[]}}async function fy($,b){let{fs:A,logger:m}=$,n=r(b.workspaceRoot),W=M(b.workspaceRoot),w=Kb({configRoot:n,workspaceRoot:W});if(b.dryRun)m.info("Dry run - no changes will be made");let j=A.join(n,".contractsrc.json");if(!await A.exists(j))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let y=await A.readFile(j),B=JSON.parse(y),S=0,Q=B.$schema;if(!Q||Q!==w)B.$schema=w,S++;if(!B.versioning)B.versioning=q0(),S++;else{let Z=B.versioning;if(Z.integrateWithChangesets===void 0)Z.integrateWithChangesets=!1,S++}if(!B.hooks)B.hooks=O0(),S++;if(!B.release)B.release=cy(),S++;if(!B.upgrade)B.upgrade=dy(),S++;if(S===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!b.dryRun)await A.writeFile(j,JSON.stringify(B,null,2)+`
|
|
2369
|
+
`),m.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(y){let B=y instanceof Error?y.message:String(y);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:B,summary:`Failed to upgrade config: ${B}`}}}function hy($,b,A){let m=A?b.map((n)=>`${n.name}@latest`).join(" "):b.map((n)=>n.name).join(" ");switch($){case"bun":return`bun add ${m}`;case"pnpm":return`pnpm add ${m}`;case"yarn":return`yarn add ${m}`;default:return`npm install ${m}`}}function q0(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function O0(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function cy(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function dy(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var gZ="**/*.{ts,tsx,js,jsx,mjs,cjs}",oy=vZ.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function cn($,b){let{fs:A}=$,m=r(b.workspaceRoot),n=M(b.workspaceRoot),W=await PZ(A,m,n),w=await kZ(A,m,n,b.manifestPaths??W.manifestPaths),j=await H0($,{workspaceRoot:m,dryRun:b.dryRun}),y=[b.agentTarget??W.defaultAgentTarget??"codex"],B=lb(w.manifest,j.packages.map((Q)=>({name:Q.name,currentVersion:Q.currentVersion})),y,yb),S=rZ(B,j.packages,j.configUpgrades);return{packageManager:j.packageManager,manifestPath:w.path,plan:S,humanChecklist:fZ(S)}}async function iy($,b){let{fs:A,logger:m}=$,n=r(b.workspaceRoot),W=await cn($,b),w=[];if(!b.dryRun){for(let y of W.plan.steps){if(y.level!=="auto")continue;for(let B of y.autofixes??[])if(await hZ(A,n,B))w.push(B.id)}m.info("Applied guided upgrade autofixes",{count:w.length,workspaceRoot:n})}let j=W.plan.steps.filter((y)=>y.level!=="auto");return{success:!0,packagesUpgraded:w.filter((y)=>y.startsWith("pkg:")).length,configSectionsUpgraded:w.filter((y)=>y.startsWith("config:")).length,summary:b.dryRun?`Would apply ${W.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${w.length} deterministic upgrade autofix(es)`,appliedAutofixes:w,remainingSteps:j,humanChecklist:W.humanChecklist,promptBundle:W.plan.agentPrompts[0],plan:W.plan,manifestPath:W.manifestPath}}async function kZ($,b,A,m){let n=m??["generated/releases/upgrade-manifest.json"],W=Array.from(new Set([b,A]));for(let w of n){let j=w.startsWith("/")?[w]:W.map((y)=>$.join(y,w));for(let y of j){if(!await $.exists(y))continue;let B=uy.parse(JSON.parse(await $.readFile(y)));return{path:y,manifest:B}}}return{manifest:uy.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function PZ($,b,A){for(let m of Array.from(new Set([$.join(b,".contractsrc.json"),$.join(A,".contractsrc.json")]))){if(!await $.exists(m))continue;try{let n=JSON.parse(await $.readFile(m)),W=FZ.safeParse(n);if(W.success)return{...oy,...W.data.upgrade}}catch{continue}}return oy}function rZ($,b,A){let m=[];for(let S of b){let Q=$.targetPackages.find((Z)=>Z.name===S.name);if(!Q?.targetVersion||Q.targetVersion===S.currentVersion)continue;m.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 n=A.map((S)=>({id:`config:${S.key}`,kind:"contractsrc",title:`Update ${S.key}`,summary:`Update .contractsrc.json at ${S.key}`,configPath:S.key,value:S.suggestedValue})),W=[];if(m.length>0)W.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:m.map((S)=>`${S.packageName}: ${S.from??"current"} -> ${S.to??"latest"}`),packages:m.map((S)=>S.packageName??""),autofixes:m});if(n.length>0)W.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:n.map((S)=>`${S.configPath} -> updated`),autofixes:n});let w=[...W,...$.steps],j=w.filter((S)=>S.level==="auto").length,y=w.filter((S)=>S.level==="assisted").length,B=w.filter((S)=>S.level==="manual").length;return{...$,steps:w,autofixCount:j,assistedCount:y,manualCount:B,agentPrompts:lb({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((S)=>({name:S.name,currentVersion:S.currentVersion})),$.agentPrompts.map((S)=>S.agent),yb).agentPrompts}}function fZ($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function hZ($,b,A){switch(A.kind){case"package-json":return cZ($,b,A);case"contractsrc":return dZ($,b,A);case"import-rewrite":return uZ($,b,A);case"codemod":return!1}}async function cZ($,b,A){let m=$.join(b,"package.json");if(!await $.exists(m))return!1;let n=JSON.parse(await $.readFile(m)),W=A.dependencyType??"dependencies",w=n[W]??{};if(!A.packageName||!A.to||!w[A.packageName])return!1;return w[A.packageName]=A.to,n[W]=w,await $.writeFile(m,JSON.stringify(n,null,2)+`
|
|
2370
|
+
`),!0}async function dZ($,b,A){let m=$.join(b,".contractsrc.json"),n=await $.exists(m)?JSON.parse(await $.readFile(m)):{};if(!A.configPath)return!1;return oZ(n,A.configPath,A.value),await $.writeFile(m,JSON.stringify(n,null,2)+`
|
|
2371
|
+
`),!0}async function uZ($,b,A){if(!A.from||!A.to)return!1;let m=await $.glob({pattern:A.path??gZ,cwd:b,absolute:!0}),n=!1;for(let W of m){let w=await $.readFile(W);if(!w.includes(A.from))continue;await $.writeFile(W,w.split(A.from).join(A.to)),n=!0}return n}function oZ($,b,A){let m=b.split("."),n=$;for(let w of m.slice(0,-1)){let j=n[w];if(!j||typeof j!=="object"||Array.isArray(j))n[w]={};n=n[w]}let W=m.at(-1);if(W)n[W]=A}import{existsSync as dn,mkdirSync as iZ,readFileSync as lZ,renameSync as tZ,statSync as pZ,writeFileSync as aZ}from"fs";import{dirname as eZ,join as sZ}from"path";var $G=".contractspec/verification-cache.json",ty=1;class py{filePath;cache;isDirty=!1;constructor($,b){let A=b??process.cwd();this.filePath=$??sZ(A,$G),this.cache=new Map,this.loadSync()}loadSync(){try{if(!dn(this.filePath))return;let $=lZ(this.filePath,"utf-8"),b=JSON.parse($);if(b.version!==ty)return;for(let[A,m]of Object.entries(b.entries))this.cache.set(A,m)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=eZ(this.filePath);if(!dn($))iZ($,{recursive:!0});let b={version:ty,entries:Object.fromEntries(this.cache.entries())},A=`${this.filePath}.tmp`;aZ(A,JSON.stringify(b,null,2),"utf-8"),tZ(A,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b),this.isDirty=!0,this.saveSync()}async delete($){let b=this.cache.delete($);if(b)this.isDirty=!0,this.saveSync();return b}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let $=0;try{if(dn(this.filePath))$=pZ(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function QI($,b){return new py($,b)}class ay{cache=new Map;async get($){return this.cache.get($)??null}async set($,b){this.cache.set($,b)}async delete($){return this.cache.delete($)}async has($){return this.cache.has($)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let $=0;for(let[b,A]of this.cache.entries())$+=b.length*2,$+=JSON.stringify(A).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function GI(){return new ay}class ey{store;keyIndex;constructor($){this.store=$,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get("contractspec.verification-cache.__index__")??[]}catch{return[]}}async saveKeyIndex(){await this.store.update("contractspec.verification-cache.__index__",Array.from(this.keyIndex))}getStorageKey($){return`contractspec.verification-cache.${$}`}async get($){let b=this.getStorageKey($);return this.store.get(b)??null}async set($,b){let A=this.getStorageKey($);if(await this.store.update(A,b),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let b=this.getStorageKey($),A=this.keyIndex.has($);if(A)await this.store.update(b,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return A}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let b=this.getStorageKey($);await this.store.update(b,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function YI($){return new ey($)}import{createHash as bG}from"crypto";var sy={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function $1($){return bG("sha256").update($).digest("hex")}function b1($){let b=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)b.push(`model:${$.aiModelVersion}`);return b.join("|")}function AG($){try{let b=$.split("|"),A=new Map;for(let w of b){let[j,y]=w.split(":");if(j&&y)A.set(j,y)}let m=A.get("spec"),n=A.get("impl"),W=A.get("tier");if(!m||!n||!W)return null;return{specHash:m,implHash:n,tier:W,aiModelVersion:A.get("model")}}catch{return null}}function mG($,b){switch($){case"structure":return b.structureTtlMs;case"behavior":return b.behaviorTtlMs;case"ai_review":return b.aiTtlMs;default:return b.defaultTtlMs}}class A1{storage;config;stats;constructor($,b={}){this.storage=$,this.config={...sy,...b},this.stats={hits:0,misses:0}}createKey($,b,A,m){return{specHash:$1($),implHash:$1(b),tier:A,aiModelVersion:A==="ai_review"?m:void 0}}async lookup($){let b=b1($),A=await this.storage.get(b);if(!A)return this.stats.misses++,{hit:!1,reason:"not_found"};if(A.meta.expiresAt){let m=new Date(A.meta.expiresAt).getTime();if(Date.now()>m)return this.stats.misses++,await this.storage.delete(b),{hit:!1,reason:"expired"}}if(A.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(A.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&A.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:A}}async store($,b,A={}){let m=b1($),n=mG($.tier,this.config),W={key:$,result:b,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+n).toISOString(),dependencies:A.dependencies??[],specName:A.specName,implPath:A.implPath}};await this.storage.set(m,W),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let b=await this.storage.keys(),A=0;for(let m of b){let n=await this.storage.get(m);if(!n)continue;if(n.meta.dependencies.includes($))await this.storage.delete(m),A++;if(n.meta.specName===$||n.meta.implPath===$)await this.storage.delete(m),A++}return A}async invalidateForSpec($){let b=await this.storage.keys(),A=0;for(let m of b){let n=AG(m);if(n&&n.specHash.startsWith($.substring(0,16)))await this.storage.delete(m),A++}return A}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let $=await this.storage.stats?.();return{totalEntries:$?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:$?.memoryUsage}}async pruneIfNeeded(){let $=await this.storage.keys();if($.length<=this.config.maxEntries)return;let b=[];for(let m of $){let n=await this.storage.get(m);if(n)b.push({key:m,createdAt:new Date(n.meta.createdAt).getTime()})}b.sort((m,n)=>m.createdAt-n.createdAt);let A=b.length-this.config.maxEntries;for(let m=0;m<A;m++){let n=b[m];if(n)await this.storage.delete(n.key)}}}function zI($,b){return new A1($,b)}import{generateVerificationPrompt as nG}from"@contractspec/lib.contracts-spec/llm";function WG($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let y=JSON.parse(b[1]);return{compliant:y.passed??!1,confidence:(y.score??0)/100,findings:(y.issues??[]).map((B)=>({category:String(B.category??"semantic"),severity:String(B.severity??"warning"),message:String(B.message??""),location:B.location?String(B.location):void 0,suggestion:B.suggestion?String(B.suggestion):void 0})),rawResponse:$}}catch{}let A=[],m=$.split(`
|
|
2372
|
+
`),n="info";for(let y of m){let B=y.toLowerCase();if(B.includes("error")||B.includes("critical"))n="error";else if(B.includes("warning")||B.includes("should"))n="warning";else if(B.includes("info")||B.includes("note"))n="info";let S=y.match(/^[-*•]\s*(.+)$/),Q=y.match(/^\d+\.\s*(.+)$/);if(S||Q){let Z=S?.[1]??Q?.[1]??"";if(Z.length>10)A.push({category:"semantic",severity:n,message:Z})}}let W=A.some((y)=>y.severity==="error"),w=!W,j=W?0.3:A.length===0?0.9:0.7;return{compliant:w,confidence:j,findings:A,rawResponse:$}}async function m1($,b){if(!b.aiApiKey)return`\`\`\`json
|
|
2053
2373
|
{
|
|
2054
2374
|
"passed": true,
|
|
2055
2375
|
"score": 50,
|
|
@@ -2066,23 +2386,23 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2066
2386
|
],
|
|
2067
2387
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2068
2388
|
}
|
|
2069
|
-
\`\`\``;try{let
|
|
2389
|
+
\`\`\``;try{let A=b.aiProvider??"anthropic";if(A==="anthropic"){let{anthropic:m}=await import("@ai-sdk/anthropic"),{generateText:n}=await import("ai");return(await n({model:m("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(A==="openai"){let{openai:m}=await import("@ai-sdk/openai"),{generateText:n}=await import("ai");return(await n({model:m("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${A}`)}catch(A){return`\`\`\`json
|
|
2070
2390
|
{
|
|
2071
2391
|
"passed": false,
|
|
2072
2392
|
"score": 0,
|
|
2073
2393
|
"issues": [
|
|
2074
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2394
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${A instanceof Error?A.message:"Unknown error"}" }
|
|
2075
2395
|
],
|
|
2076
2396
|
"summary": "AI verification encountered an error"
|
|
2077
2397
|
}
|
|
2078
|
-
\`\`\``}}async function
|
|
2398
|
+
\`\`\``}}async function tb($,b={}){let{spec:A,implementationCode:m,implementationPath:n}=$,W=Date.now(),w=nG(A,m),j=await m1(w.taskPrompt,b),y=WG(j),B=y.findings.map((G)=>({severity:G.severity,category:"semantic",message:G.message,location:G.location?{file:G.location}:n?{file:n}:void 0,suggestion:G.suggestion})),S=Math.round(y.confidence*100),Q=y.compliant,Z=y.findings.filter((G)=>G.suggestion).map((G)=>G.suggestion);return{tier:"ai_review",passed:Q,score:S,issues:B,suggestions:Z,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Q?1:0}},meta:{specName:A.meta.key,specVersion:A.meta.version,implementationPath:n??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-W}}}function V0($){let{spec:b,implementationCode:A,implementationPath:m}=$,n=Date.now(),W=[];if(A.includes("console.log"))W.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(A.includes("// TODO")||A.includes("// FIXME"))W.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(b.policy.auth!=="anonymous"&&!A.includes("auth"))W.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=W.filter((y)=>y.severity==="error").length===0?80:40,j=W.filter((y)=>y.severity==="error").length===0;return{tier:"ai_review",passed:j,score:w,issues:W,suggestions:W.filter((y)=>y.suggestion).map((y)=>y.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:j?1:0}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-n}}}function wG($,b){return`You are analyzing a code implementation against its specification.
|
|
2079
2399
|
|
|
2080
2400
|
## Spec Schema Fields
|
|
2081
2401
|
${$}
|
|
2082
2402
|
|
|
2083
2403
|
## Implementation Code
|
|
2084
2404
|
\`\`\`typescript
|
|
2085
|
-
${
|
|
2405
|
+
${b}
|
|
2086
2406
|
\`\`\`
|
|
2087
2407
|
|
|
2088
2408
|
## Task
|
|
@@ -2122,42 +2442,43 @@ Match types:
|
|
|
2122
2442
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2123
2443
|
- "mismatch": Different meaning despite similar naming
|
|
2124
2444
|
- "missing": Spec field not found in implementation
|
|
2125
|
-
`}function
|
|
2126
|
-
`)}function
|
|
2127
|
-
`),
|
|
2128
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,
|
|
2129
|
-
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function
|
|
2130
|
-
`)}function
|
|
2131
|
-
`)}function
|
|
2132
|
-
`),
|
|
2133
|
-
`).trim()||void 0,
|
|
2134
|
-
${
|
|
2445
|
+
`}function jG($){let b=[],A=(m,n)=>{try{let w=m?._def?.shape;if(w&&typeof w==="function"){let j=w();for(let[y,B]of Object.entries(j)){let Q=B?._def?.typeName??"unknown";b.push(`- ${y}: ${String(Q).replace("Zod","").toLowerCase()} (${n})`)}}}catch{b.push(`- [unable to extract ${n} fields]`)}};if($.io.input)A($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))A($.io.output,"output");if(b.length===0)return"- [no schema fields could be extracted]";return b.join(`
|
|
2446
|
+
`)}function yG($){let b=$.match(/```json\n?([\s\S]*?)\n?```/);if(b?.[1])try{let A=JSON.parse(b[1]);return{fieldMappings:(A.fieldMappings??[]).map((m)=>({specField:String(m.specField??""),specType:String(m.specType??"unknown"),implementationField:m.implementationField?String(m.implementationField):void 0,implementationType:m.implementationType?String(m.implementationType):void 0,match:m.match??"missing",aiConfidence:typeof m.aiConfidence==="number"?m.aiConfidence:0.5,suggestion:m.suggestion?String(m.suggestion):void 0})),intentAlignment:{score:typeof A.intentAlignment?.score==="number"?A.intentAlignment.score:50,issues:Array.isArray(A.intentAlignment?.issues)?A.intentAlignment.issues:[],suggestions:Array.isArray(A.intentAlignment?.suggestions)?A.intentAlignment.suggestions:[]},semanticIssues:(A.semanticIssues??[]).map((m)=>({category:String(m.category??"semantic"),severity:m.severity??"warning",message:String(m.message??""),suggestion:m.suggestion?String(m.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:A,implementationCode:m}=$,n=jG(A),W=wG(n,m),w=await m1(W,b);return yG(w)}async function BG($,b={}){let{spec:A,implementationCode:m,implementationPath:n}=$,W=Date.now(),w=await tb($,b),j;if(b.aiApiKey)try{j=await n1($,b)}catch{}if(j){let y=[];for(let Z of j.fieldMappings)if(Z.match==="missing")y.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")y.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)y.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 j.intentAlignment.issues)y.push({severity:"warning",category:"semantic",message:Z});for(let Z of j.semanticIssues)y.push({severity:Z.severity,category:"semantic",message:Z.message,suggestion:Z.suggestion});w.issues=[...w.issues,...y];let B=j.fieldMappings.length,S=j.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(y.some((Z)=>Z.severity==="error"))w.passed=!1;w.suggestions=[...w.suggestions,...j.intentAlignment.suggestions]}return w.meta={...w.meta,duration:Date.now()-W},w}import{isEmitDeclRef as SG}from"@contractspec/lib.contracts-spec/operations";function QG($,b){let A=[...b.given,...b.when,...b.then].flatMap((B)=>B.toLowerCase().split(/\s+/).filter((S)=>S.length>3)),m=$.toLowerCase(),n=A.filter((B)=>m.includes(B)),W=A.length>0?n.length/A.length:0,w=b.key.toLowerCase().replace(/\s+/g,""),j=m.includes(w)||m.includes(`test('${b.key.toLowerCase()}'`)||m.includes(`it('${b.key.toLowerCase()}'`)||m.includes(`describe('${b.key.toLowerCase()}'`),y=W>=0.3||j;return{name:b.key,type:"scenario",passed:y,expected:`Given: ${b.given.join("; ")}; When: ${b.when.join("; ")}; Then: ${b.then.join("; ")}`,details:y?void 0:`Scenario keywords not found in implementation (${Math.round(W*100)}% coverage)`}}function ZG($,b){let A=JSON.stringify(b.input),m=JSON.stringify(b.output),n=W1(b.input),W=W1(b.output),w=$.toLowerCase(),j=n.filter((G)=>w.includes(G.toLowerCase())),y=W.filter((G)=>w.includes(G.toLowerCase())),B=n.length>0?j.length/n.length:1,S=W.length>0?y.length/W.length:1,Q=(B+S)/2,Z=Q>=0.2;return{name:b.key,type:"example",passed:Z,expected:`Input: ${A.slice(0,100)}...; Output: ${m.slice(0,100)}...`,details:Z?void 0:`Example values not found in implementation (${Math.round(Q*100)}% coverage)`}}function W1($){let b=[];function A(m){if(typeof m==="string"&&m.length>2)b.push(m);else if(Array.isArray(m))m.forEach(A);else if(m&&typeof m==="object")Object.values(m).forEach(A)}return A($),b}function GG($,b,A){let m=$.includes(b),n=A.http?$.includes(String(A.http)):!0,W=A.when.toLowerCase().split(/\s+/).filter((S)=>S.length>3),w=$.toLowerCase(),j=W.filter((S)=>w.includes(S)),y=W.length>0?j.length/W.length:1,B=m&&(n||y>=0.3);return{name:`Error: ${b}`,type:"error",passed:B,expected:`When: ${A.when}; Return: ${b} (HTTP ${A.http??400})`,details:B?void 0:!m?`Error code '${b}' not found in implementation`:"Error condition not properly implemented"}}function XG($,b){let A=b.sideEffects?.emits??[],m=[];for(let n of A){let W=SG(n)?n.ref.key:n.key,w=n.when,j=w.toLowerCase().split(/\s+/).filter((Z)=>Z.length>3),y=$.toLowerCase(),B=y.includes(W.toLowerCase()),S=j.filter((Z)=>y.includes(Z)),Q=j.length>0?S.length/j.length:1;m.push({name:`Event: ${W}`,type:"scenario",passed:B&&Q>=0.3,expected:`Emit ${W} when: ${w}`,details:!B?`Event '${W}' not found`:Q<0.3?"Event condition not properly implemented":void 0})}return m}function YG($,b){if(b.policy.idempotent===void 0)return null;if(!b.policy.idempotent)return null;let A=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],m=$.toLowerCase(),n=A.some((W)=>m.includes(W));return{name:"Idempotency",type:"scenario",passed:n,expected:"Operation should be idempotent (safe to retry)",details:n?void 0:"No idempotency pattern found for idempotent operation"}}function J0($){let{spec:b,implementationCode:A,implementationPath:m}=$,n=Date.now(),W=[];for(let X of b.acceptance?.scenarios??[])W.push(QG(A,X));for(let X of b.acceptance?.examples??[])W.push(ZG(A,X));for(let[X,Y]of Object.entries(b.io.errors??{}))W.push(GG(A,X,Y));W.push(...XG(A,b));let w=YG(A,b);if(w)W.push(w);let j=W.filter((X)=>!X.passed).map((X)=>({severity:X.type==="error"?"error":"warning",category:X.type==="scenario"?"scenario":X.type==="example"?"scenario":"error_handling",message:X.details??`${X.type} not covered: ${X.name}`,location:m?{file:m}:void 0,suggestion:X.expected?`Expected: ${X.expected}`:void 0})),y=W.filter((X)=>X.type==="scenario"),B=W.filter((X)=>X.type==="error"),S=W.filter((X)=>X.passed).length,Q=W.length>0?Math.round(S/W.length*100):100,Z=j.filter((X)=>X.severity==="error").length===0,G=W.filter((X)=>!X.passed&&X.expected).map((X)=>`${X.name}: ${X.expected}`);return{tier:"behavior",passed:Z,score:Q,issues:j,suggestions:G,coverage:{scenarios:{total:y.length,covered:y.filter((X)=>X.passed).length},errors:{total:B.length,handled:B.filter((X)=>X.passed).length},fields:{total:W.length,implemented:S}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-n}}}import{isEmitDeclRef as HG}from"@contractspec/lib.contracts-spec/operations";function qG($){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 OG($){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 VG($,b){if(OG(b))return{name:"contracts_import",passed:!0};let A=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function JG($,b){if(!(b.io.input!==null||b.io.output!==null))return{name:"schema_import",passed:!0};let m=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:m,details:m?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function KG($){let b=/:\s*any\b|as\s+any\b|<any>/,A=$.split(`
|
|
2447
|
+
`),m=[];for(let n=0;n<A.length;n++){let W=A[n]??"";if(W.trim().startsWith("//")||W.trim().startsWith("*"))continue;if(b.test(W))m.push(n+1)}return{name:"no_any_type",passed:m.length===0,details:m.length>0?`Found 'any' type on lines: ${m.slice(0,5).join(", ")}${m.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function _G($,b){let A=b.io.errors;if(!A||Object.keys(A).length===0)return{name:"error_handling",passed:!0};let m=Object.keys(A),n=[];for(let W of m)if(!$.includes(W))n.push(W);return{name:"error_handling",passed:n.length===0,details:n.length>0?`Missing error handling for: ${n.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function UG($,b){let A=b.sideEffects?.emits;if(!A||A.length===0)return{name:"event_emission",passed:!0};let m=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),n=A.map((w)=>{if(HG(w))return w.ref.key;return w.key}),W=n.filter((w)=>$.includes(w));return{name:"event_emission",passed:m&&W.length>0,details:!m?"No event emission pattern found":W.length===0?`Events not referenced: ${n.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function zG($,b){if(!b.io.input)return{name:"input_validation",passed:!0};let A=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:A,details:A?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function LG($,b){let A=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(b.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:A,details:A?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function pb($){let{spec:b,implementationCode:A,implementationPath:m}=$,n=Date.now(),W=[qG(A),VG(A,m),JG(A,b),KG(A),_G(A,b),UG(A,b),zG(A,b),LG(A,b)],w=W.filter((G)=>!G.passed).map((G)=>({severity:G.name==="no_any_type"?"warning":"error",category:G.name.includes("import")?"import":G.name.includes("export")?"export":"type",message:G.details??`Check failed: ${G.name}`,location:m?{file:m}:void 0,suggestion:G.suggestion})),j=W.filter((G)=>G.passed).length,y=Math.round(j/W.length*100),B=w.filter((G)=>G.severity==="error").length===0,S=W.filter((G)=>!G.passed&&G.suggestion).map((G)=>G.suggestion),Q=Object.keys(b.io.errors??{}).length,Z=W.find((G)=>G.name==="error_handling")?.passed?Q:0;return{tier:"structure",passed:B,score:y,issues:w,suggestions:S,coverage:{scenarios:{total:0,covered:0},errors:{total:Q,handled:Z},fields:{total:W.length,implemented:j}},meta:{specName:b.meta.key,specVersion:b.meta.version,implementationPath:m??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-n}}}var RG={verbose:!1},CG=["structure","behavior","ai_review"];class K0{config;constructor($={}){this.config={...RG,...$}}async verify($,b,A={}){let m=Date.now(),n=new Map,W=[],w={spec:$,implementationCode:b},j=A.tiers??["structure","behavior"];for(let Z of CG){if(!j.includes(Z))continue;let G;switch(Z){case"structure":G=pb(w);break;case"behavior":G=J0(w);break;case"ai_review":if(this.config.aiApiKey)G=await tb(w,this.config);else G=V0(w);break;default:continue}if(n.set(Z,G),W.push(...G.issues),A.failFast&&!G.passed)break}let y=Array.from(n.values()),B=y.every((Z)=>Z.passed),S=y.length>0?Math.round(y.reduce((Z,G)=>Z+G.score,0)/y.length):100,Q=this.generateSummary(y,W);return{passed:B,score:S,reports:n,allIssues:W,summary:Q,duration:Date.now()-m}}verifyStructure($,b,A){return pb({spec:$,implementationCode:b,implementationPath:A})}verifyBehavior($,b,A){return J0({spec:$,implementationCode:b,implementationPath:A})}async verifyAI($,b,A){let m={spec:$,implementationCode:b,implementationPath:A};if(this.config.aiApiKey)return tb(m,this.config);return V0(m)}quickVerify($,b){return pb({spec:$,implementationCode:b})}formatAsMarkdown($){let b=[];b.push("# Verification Report"),b.push(""),b.push(`**Status:** ${$.passed?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${$.score}/100`),b.push(`**Duration:** ${$.duration}ms`),b.push("");for(let[m,n]of $.reports){if(b.push(`## ${this.formatTierName(m)}`),b.push(""),b.push(`**Status:** ${n.passed?"✓ Passed":"✗ Failed"}`),b.push(`**Score:** ${n.score}/100`),b.push(""),n.issues.length>0){b.push("### Issues"),b.push("");for(let W of n.issues){let w=W.severity==="error"?"❌":W.severity==="warning"?"⚠️":"ℹ️";if(b.push(`${w} **${W.category}**: ${W.message}`),W.suggestion)b.push(` - Suggestion: ${W.suggestion}`)}b.push("")}if(n.coverage.scenarios.total>0)b.push(`**Scenarios:** ${n.coverage.scenarios.covered}/${n.coverage.scenarios.total}`);if(n.coverage.errors.total>0)b.push(`**Errors handled:** ${n.coverage.errors.handled}/${n.coverage.errors.total}`);b.push("")}let A=Array.from($.reports.values()).flatMap((m)=>m.suggestions);if(A.length>0){b.push("## Suggestions"),b.push("");for(let m of A.slice(0,10))b.push(`- ${m}`);if(A.length>10)b.push(`- ... and ${A.length-10} more`);b.push("")}return b.join(`
|
|
2448
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,b){let A=[],m=$.every((y)=>y.passed),n=$.length>0?Math.round($.reduce((y,B)=>y+B.score,0)/$.length):100;A.push(m?"✓ Verification passed":"✗ Verification failed"),A.push(`Score: ${n}/100`),A.push("");for(let y of $){let B=y.passed?"✓":"✗";A.push(`${B} ${y.tier}: ${y.score}/100`)}A.push("");let W=b.filter((y)=>y.severity==="error"),w=b.filter((y)=>y.severity==="warning"),j=b.filter((y)=>y.severity==="info");if(W.length>0)A.push(`Errors: ${W.length}`);if(w.length>0)A.push(`Warnings: ${w.length}`);if(j.length>0)A.push(`Info: ${j.length}`);return A.join(`
|
|
2449
|
+
`)}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 IG($){return new K0($)}var EG=new K0;var R1={};P(R1,{saveReleaseDraft:()=>O1,renderUpgradePrompt:()=>yb,renderUpgradeChecklist:()=>ky,renderPatchNotes:()=>fn,renderMigrationGuide:()=>gy,renderMaintainerSummary:()=>Fy,renderCustomerPatchNote:()=>vy,renderCustomerGuide:()=>hn,prepareReleaseAuthoring:()=>q1,parseConventionalCommit:()=>z0,isConventionalCommit:()=>vG,initReleaseArtifacts:()=>_1,getHighestBumpType:()=>on,getBumpTypeFromCommit:()=>un,generateChangelogs:()=>H1,formatKeepAChangelog:()=>ab,formatConventionalChangelog:()=>j1,formatChangelogJson:()=>_0,filterCommitsByScope:()=>gG,filterBumpableCommits:()=>kG,commitsToChangeEntries:()=>ln,commitToChangeEntry:()=>B1,checkReleaseArtifacts:()=>z1,buildReleaseArtifacts:()=>U1,applyVersionBump:()=>Y1,analyzeVersionsFromCommits:()=>Bb,analyzeVersions:()=>AA,DEFAULT_COMMIT_TYPE_MAP:()=>U0});import{basename as MG,dirname as xG}from"node:path";function ab($){let b=["# Changelog","","All notable changes to this project will be documented in this file.","","The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),","and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).",""],A=[...$].sort((m,n)=>y1(m.version,n.version));for(let m of A){b.push(`## [${m.version}] - ${m.date}`),b.push("");let n=m.changes.filter((Q)=>Q.type==="added"),W=m.changes.filter((Q)=>Q.type==="changed"),w=m.changes.filter((Q)=>Q.type==="deprecated"),j=m.changes.filter((Q)=>Q.type==="removed"),y=m.changes.filter((Q)=>Q.type==="fixed"),B=m.changes.filter((Q)=>Q.type==="security"),S=m.breakingChanges??m.changes.filter((Q)=>Q.type==="breaking");if(S.length>0)b.push("### ⚠️ Breaking Changes"),S.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(n.length>0)b.push("### Added"),n.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(W.length>0)b.push("### Changed"),W.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(j.length>0)b.push("### Removed"),j.forEach((Q)=>{b.push(`- ${Q.description}${Q.path?` (${Q.path})`:""}`)}),b.push("");if(y.length>0)b.push("### Fixed"),y.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(`
|
|
2450
|
+
`)}function j1($){let b=["# Changelog",""],A=[...$].sort((m,n)=>y1(m.version,n.version));for(let m of A){let n=m.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":m.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";b.push(`## ${m.version} (${m.date}) - ${n}`),b.push("");let W={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let w of m.changes){let j=W[w.type]??"chore",y=w.path?`(${w.path})`:"",B=w.type==="breaking"?"!":"";b.push(`- **${j}${y}${B}**: ${w.description}`)}b.push("")}return b.join(`
|
|
2451
|
+
`)}function _0($,b){let A=$.analyses.filter((W)=>W.needsBump),m=new Date().toISOString(),n=m.split("T")[0]??"";return{generatedAt:m,baseline:b,specs:A.map((W)=>({key:W.specKey,version:W.suggestedVersion,path:W.specPath,entries:[{version:W.suggestedVersion,date:n,bumpType:W.bumpType,changes:W.changes,breakingChanges:W.changes.filter((w)=>w.type==="breaking")}]})),libraries:DG(A,n)}}function TG($){let b=$.split("/"),A=b.lastIndexOf("packages");if(A>=0&&A+2<b.length)return b.slice(0,A+3).join("/");return xG($)}var w1={major:3,minor:2,patch:1};function DG($,b){let A=new Map;for(let m of $){let n=TG(m.specPath),W=A.get(n);if(W)W.push(m);else A.set(n,[m])}return Array.from(A.entries()).flatMap(([m,n])=>{let W=n[0];if(!W)return[];let w=n.reduce((j,y)=>{return(w1[y.bumpType]??0)>(w1[j.bumpType]??0)?y:j},W);return[{name:MG(m),path:m,version:w.suggestedVersion,entries:[{version:w.suggestedVersion,date:b,bumpType:w.bumpType,changes:n.flatMap((j)=>j.changes),breakingChanges:n.flatMap((j)=>j.changes).filter((j)=>j.type==="breaking")}]}]})}function y1($,b){let A=(W)=>{return W.split(".").map((j)=>parseInt(j,10)||0)},m=A($),n=A(b);for(let W=0;W<3;W++){let w=m[W]??0,j=n[W]??0;if(w!==j)return j-w}return 0}var U0={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},NG=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,FG=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function z0($){let b=$.split(`
|
|
2452
|
+
`),A=b[0]?.trim();if(!A)return null;let m=A.match(NG);if(!m)return null;let[,n,W,w,j]=m;if(!n||!j)return null;let y=b.slice(1).join(`
|
|
2453
|
+
`).trim()||void 0,B=y?.match(FG),S=B?.[1];return{type:n.toLowerCase(),scope:W?.toLowerCase(),breaking:!!w||!!B,description:j.trim(),body:y,breakingDescription:S,raw:$}}function vG($){return z0($)!==null}function un($,b=U0){if($.breaking)return"major";return b[$.type]??null}function on($,b=U0){let A=["major","minor","patch"],m=null;for(let n of $){let W=un(n,b);if(!W)continue;if(!m){m=W;continue}let w=A.indexOf(m);if(A.indexOf(W)<w)m=W}return m}function B1($){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 ln($){return $.map(B1)}function gG($,b){return $.filter((A)=>A.scope?.toLowerCase()===b.toLowerCase())}function kG($,b=U0){return $.filter((A)=>un(A,b)!==null)}import{z as T}from"zod";import{ReleaseCapsuleSchema as S1}from"@contractspec/lib.contracts-spec";import{dump as PG,load as rG}from"js-yaml";var fG=".changeset/*.md",hG=".changeset/*.release.yaml",cG=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,dG=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function uG($,b){return(await $.glob({pattern:fG,cwd:b,absolute:!0})).filter((m)=>$.basename(m)!=="README.md")}async function eb($,b){let A=await uG($,b),m=[];for(let n of A){let W=await $.readFile(n);m.push(oG($.basename(n),W))}return m}async function sb($,b,A){let m=await $.glob({pattern:hG,cwd:b,absolute:!0}),n=new Map(A.map((j)=>[j.slug,j.packages])),W=new Map,w=[];for(let j of m){let y=$.basename(j).replace(/\.release\.yaml$/,"");try{let B=rG(await $.readFile(j)),S=iG(B,y,n.get(y)??[]);W.set(y,S)}catch(B){w.push(lG(j,y,B))}}return{capsules:W,issues:w}}async function $A($,b){let A=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:b,absolute:!0}),m=[];for(let n of A){let W=JSON.parse(await $.readFile(n));if(!W.name||!W.version||W.private===!0)continue;let w=$.relative(b,$.dirname(n))||".";m.push({name:W.name,dir:w,version:W.version})}return m.sort((n,W)=>n.dir.localeCompare(W.dir))}function L0($,b){let A=new Set;for(let m of $){let n=b.find((W)=>W.dir==="."?!m.startsWith("packages/"):m===W.dir||m.startsWith(`${W.dir}/`));if(n)A.add(n.name)}return Array.from(A).sort((m,n)=>m.localeCompare(n))}function R0($,b){return`---
|
|
2454
|
+
${b.map((m)=>`"${m.name}": ${m.releaseType}`).join(`
|
|
2135
2455
|
`)}
|
|
2136
2456
|
---
|
|
2137
2457
|
|
|
2138
2458
|
${$}
|
|
2139
|
-
`}function
|
|
2140
|
-
`)
|
|
2141
|
-
`)}function
|
|
2142
|
-
|
|
2459
|
+
`}function C0($){return PG(S1.parse($),{noRefs:!0,lineWidth:100})}function bA($){return $.map((b)=>{let A=b.line&&b.column?`:${b.line}:${b.column}`:b.line?`:${b.line}`:"",m=b.suggestion?` ${b.suggestion}`:"";return`${b.filePath}${A} ${b.message}.${m}`.trim()}).join(`
|
|
2460
|
+
`)}function oG($,b){let A=$.replace(/\.md$/,""),m=b.match(cG);if(!m)return{slug:A,summary:b.trim(),packages:[]};let n=m[1]??"",W=(m[2]??"").trim(),w=[];for(let j of n.split(`
|
|
2461
|
+
`)){let y=j.trim().match(dG);if(!y)continue;let B=y[1],S=y[2];if(!B||S==="none")continue;w.push({name:B,releaseType:S})}return{slug:A,summary:W,packages:w}}function iG($,b,A){let m=typeof $==="object"&&$!==null?$:{},n=Array.isArray(m.packageNames)?m.packageNames.filter((W)=>typeof W==="string").map((W)=>({name:W,releaseType:m.releaseType??"patch"})):[];return S1.parse({...m,slug:b,packages:Array.isArray(m.packages)&&m.packages.length>0?m.packages:n.length>0?n:A})}function lG($,b,A){let m=typeof A==="object"&&A!==null?A:null,n=Array.isArray(m?.issues)?m.issues.map((w)=>w.message).filter((w)=>typeof w==="string"):[],W=n.length>0?`Release capsule validation failed: ${n.join("; ")}`:typeof m?.reason==="string"?`Release capsule YAML parse failed: ${m.reason}`:`Release capsule parse failed: ${A instanceof Error?A.message:String(A)}`;return{slug:b,filePath:$,message:W,line:typeof m?.mark?.line==="number"?m.mark.line+1:void 0,column:typeof m?.mark?.column==="number"?m.mark.column+1:void 0,suggestion:`Re-run \`contractspec release edit ${b}\` to rewrite the capsule safely.`}}import{bumpVersion as X1,determineBumpType as tG}from"@contractspec/lib.contracts-spec";async function AA($,b={}){let{fs:A,git:m,logger:n}=$,W=b.workspaceRoot??process.cwd();n.info("Starting version analysis...",{baseline:b.baseline});let w=b.pattern??"**/*.{operation,event,presentation}.ts",y=(await A.glob({pattern:w,cwd:W})).filter((G)=>!G.includes(".test.")&&!G.includes(".spec.")&&!G.includes("node_modules"));n.debug(`Found ${y.length} spec files`);let B=[],S=0,Q=0;for(let G of y)try{let X=await A.readFile(G),Y=I0(X);if(!Y)continue;let V=null;if(b.baseline)try{V=await m.showFile(b.baseline,G)}catch{V=null}let O=pG(X,V),K=O.some((U)=>U.type==="breaking"),J=O.length>0&&!K,_=O.length>0;if(K)S++;if(J)Q++;let H=tG(K,J),q=_?X1(Y.version,H):Y.version;B.push({specPath:G,specKey:Y.key,currentVersion:Y.version,suggestedVersion:q,bumpType:H,changes:O,hasBreaking:K,needsBump:_})}catch(X){n.warn(`Failed to analyze ${G}:`,{error:X instanceof Error?X.message:String(X)})}let Z=B.filter((G)=>G.needsBump).length;return n.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 Bb($,b={}){let{git:A,logger:m}=$,n=b.baseline??"HEAD~10";m.info("Analyzing commits for version bump...",{baseline:n});try{let W=await A.log(n),w=[],j=[];for(let Q of W){let Z=z0(Q.message);if(Z)w.push({hash:Q.hash,message:Q.message,type:Z.type,scope:Z.scope,breaking:Z.breaking}),j.push(Z)}let y=on(j),B=ln(j),S=w.filter((Q)=>Q.breaking).length;return m.info("Commit analysis complete",{totalCommits:w.length,breakingCommits:S,suggestedBumpType:y}),{suggestedBumpType:y,commits:w,changes:B,totalCommits:w.length,breakingCommits:S}}catch(W){return m.warn("Failed to analyze commits",{error:W instanceof Error?W.message:String(W)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function Y1($,b){let{fs:A,logger:m}=$,{specPath:n,dryRun:W=!1,config:w}=b;m.info("Applying version bump...",{specPath:n,bumpType:b.bumpType});try{let j=await A.readFile(n),y=I0(j);if(!y)return{success:!1,specPath:n,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:Z1(),error:"Could not extract spec metadata"};let B=b.bumpType??"patch",S=X1(y.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((G)=>G.type==="breaking")};if(!W){let G=eG(j,y.version,S);await A.writeFile(n,G)}if(m.info("Version bump applied",{specPath:n,previousVersion:y.version,newVersion:S}),w?.integrateWithChangesets)await b2($,{specPath:n,bumpType:B,summary:b.changeDescription??`Bump ${y.key} to ${S}`,dryRun:W});return{success:!0,specPath:n,specKey:y.key,previousVersion:y.version,newVersion:S,bumpType:B,changelogEntry:Z}}catch(j){let y=j instanceof Error?j.message:String(j);return m.error("Version bump failed",{specPath:n,error:y}),{success:!1,specPath:n,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:b.bumpType??"patch",changelogEntry:Z1(),error:y}}}async function H1($,b={}){let{logger:A}=$,m=b.tiers??["spec","library","monorepo"],n=b.format??"keep-a-changelog";A.info("Generating changelogs...",{tiers:m,format:n});let W=await AA($,{baseline:b.baseline,workspaceRoot:b.workspaceRoot}),w=[],j=new Map,y="",B=0;if(m.includes("spec"))for(let Q of W.analyses.filter((Z)=>Z.needsBump)){let Z={id:`changelog.${Q.specKey}`,title:`Changelog for ${Q.specKey}`,body:sG(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((G)=>G.type==="breaking")}]};w.push(Z),B++}if(m.includes("library")){let Q=$2(W.analyses);for(let[Z,G]of Q){let X=G.filter((Y)=>Y.needsBump);if(X.length>0)j.set(Z,ab(X.map(G1))),B+=X.length}}if(m.includes("monorepo")){let Q=W.analyses.filter((Z)=>Z.needsBump).map(G1);y=ab(Q)}let S=_0(W,b.baseline);return A.info("Changelog generation complete",{totalEntries:B}),{specChangelogs:w,libraryMarkdown:j,monorepoMarkdown:y,json:S,totalEntries:B}}function I0($){let b=$.match(/key:\s*['"`]([^'"`]+)['"`]/),A=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!b||!A)return null;let m=b[1],n=A[1];if(!m||!n)return null;return{key:m,version:n}}function pG($,b){let A=[];if(!b)return A.push({type:"added",description:"New spec added"}),A;let m=I0($),n=I0(b);if(!m||!n)return A;if(m.version!==n.version)A.push({type:"changed",description:`Version updated from ${n.version} to ${m.version}`,path:"meta.version"});let W=aG($,b);if(W.breaking)A.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(W.nonBreaking)A.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return A}function aG($,b){let A=/io:\s*\{[\s\S]*?\}/,m=$.match(A)?.[0]??"",n=b.match(A)?.[0]??"";if(m===n)return{breaking:!1,nonBreaking:!1};let W=Q1(m),w=Q1(n),j=w.filter((B)=>!W.includes(B)),y=W.filter((B)=>!w.includes(B));return{breaking:j.length>0,nonBreaking:y.length>0&&j.length===0}}function Q1($){let b=/(\w+):/g;return[...$.matchAll(b)].map((m)=>m[1]).filter((m)=>!!m)}function eG($,b,A){return $.replace(new RegExp(`version:\\s*['"\`]${b}['"\`]`),`version: '${A}'`)}function Z1(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function sG($){let b=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],A=$.changes.filter((W)=>W.type==="breaking"),m=$.changes.filter((W)=>W.type==="changed"),n=$.changes.filter((W)=>W.type==="added");if(A.length>0)b.push("### Breaking Changes"),A.forEach((W)=>b.push(`- ${W.description}`)),b.push("");if(n.length>0)b.push("### Added"),n.forEach((W)=>b.push(`- ${W.description}`)),b.push("");if(m.length>0)b.push("### Changed"),m.forEach((W)=>b.push(`- ${W.description}`)),b.push("");return b.join(`
|
|
2462
|
+
`)}function $2($){let b=new Map;for(let A of $){let W=A.specPath.match(/(.+?\/src\/)/)?.[1]??A.specPath,w=b.get(W)??[];w.push(A),b.set(W,w)}return b}function G1($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((b)=>b.type==="breaking")}}async function b2($,b){let{fs:A,logger:m}=$,{specPath:n,bumpType:W,summary:w,dryRun:j}=b;try{let y=r(n),B=T$(y);if(!B){m.warn("Could not determine package name for changeset",{specPath:n});return}let S=y,Q=null;while(!0){let Y=A.join(S,".changeset");if(await A.exists(Y)){Q=Y;break}let V=A.dirname(S);if(V===S)break;S=V}if(!Q){m.warn("No .changeset directory found, skipping changeset generation");return}let Z=`${A2()}.md`,G=A.join(Q,Z),X=`---
|
|
2463
|
+
"${B}": ${W}
|
|
2143
2464
|
---
|
|
2144
2465
|
|
|
2145
|
-
${
|
|
2146
|
-
`;if(!Y)await j.writeFile(J,b),A.info("Generated changeset",{filePath:J});else A.info("Would generate changeset",{filePath:J,content:b})}catch(B){A.error("Failed to generate changeset",{error:B instanceof Error?B.message:String(B)})}}function Fq(){let $=["neat","calm","wild","soft","bold","fair","cool"],W=["fox","cat","dog","bat","ant","elk","owl"],j=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],Q=W[Math.floor(Math.random()*W.length)],Z=j[Math.floor(Math.random()*j.length)],X=Math.floor(Math.random()*1000);return`${A}-${Q}-${Z}-${X}`}var e9="generated/releases",tW=vq.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function $A($,W={}){let{fs:j,git:A,logger:Q}=$,Z=D(W.workspaceRoot),X=await A5(j,Z),Y=W.baseline?await A.diffFiles(W.baseline):[],B=W.packages&&W.packages.length>0?W.packages:c9(Y,X),q=W.baseline?await pW($,{baseline:W.baseline,workspaceRoot:Z}):null,H=W.baseline?await F$($,{baseline:W.baseline,workspaceRoot:Z}):null,V=(H?.summary.breaking??0)>0?"major":q?.suggestedBumpType??mq(B),G=W.releaseType??V,J=W.summary??`Describe the ${G} release for ${B[0]??"the workspace"}`,b=W.slug??kq(J),w=B.map((K)=>({name:K,releaseType:G,version:X.find((_)=>_.name===K)?.version})),L={schemaVersion:"1",slug:b,summary:J,isBreaking:G==="major"||(H?.summary.breaking??0)>0,packages:w,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:J},{kind:"customer",summary:J}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},z=j.join(Z,".changeset",`${b}.md`),S=j.join(Z,".changeset",`${b}.release.yaml`);if(!W.force){if(await j.exists(z))throw Error(`Changeset already exists: ${z}`);if(await j.exists(S))throw Error(`Release capsule already exists: ${S}`)}let U=r9(J,w),O=l9(L);if(!W.dryRun)await j.writeFile(z,U),await j.writeFile(S,O);return Q.info("Initialized release artifacts",{slug:b,workspaceRoot:Z}),{slug:b,changesetPath:z,capsulePath:S,changesetContent:U,capsuleContent:O,packages:w,releaseType:G,isBreaking:L.isBreaking}}async function WA($,W={}){let{fs:j,logger:A}=$,Q=D(W.workspaceRoot),Z=await AA(j,Q),X=j.join(Q,W.outputDir??e9),Y=await W5(j,Q),B=await j5(j,Q,Y),q=await A5(j,Q),H=await Promise.all(Array.from(B.entries()).map(async([U,O])=>{let K=j.join(Q,".changeset",`${U}.release.yaml`),_=await j.stat(K);return{slug:U,version:Pq(O,q),summary:O.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:O.isBreaking,packages:O.packages.map((I)=>({...I,version:q.find((M)=>M.name===I.name)?.version??I.version})),affectedRuntimes:[...O.affectedRuntimes],affectedFrameworks:[...O.affectedFrameworks],audiences:[...O.audiences],deprecations:[...O.deprecations],migrationInstructions:[...O.migrationInstructions],upgradeSteps:[...O.upgradeSteps],validation:O.validation}})),V=xq.parse({generatedAt:new Date().toISOString(),releases:H}),G=W.agentTargets??Z.agentTargets??["codex"],J=D0(V,[],G,p$),b=j.join(X,"manifest.json"),w=j.join(X,"upgrade-manifest.json"),L=j.join(X,"patch-notes.md"),z=j.join(X,"customer-guide.md"),S=Object.fromEntries(J.agentPrompts.map((U)=>[U.agent,j.join(X,"prompts",`${U.agent}.md`)]));if(!W.dryRun){await j.writeFile(b,JSON.stringify(V,null,2)),await j.writeFile(w,JSON.stringify(V,null,2)),await j.writeFile(L,ij(V)),await j.writeFile(z,pj(V));for(let U of J.agentPrompts)await j.writeFile(S[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:X,releasesBuilt:V.releases.length}),{outputDir:X,manifestPath:b,upgradeManifestPath:w,patchNotesPath:L,customerGuidePath:z,promptPaths:S,manifest:V,upgradePlan:J,releasesBuilt:V.releases.length}}async function jA($,W={}){let{fs:j}=$,A=D(W.workspaceRoot),Q=await AA(j,A),Z=j.join(A,W.outputDir??e9),X=[],Y=[],B=[],q=await W5(j,A),H=await j5(j,A,q),V=q.length>0,G=!V&&H.size>0;t$(X,V||G,"changesets",V?`Found ${q.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let J of q)if(!H.has(J.slug)&&Q.requireReleaseCapsule)B.push(`Missing release capsule for changeset ${J.slug}.`);for(let[J,b]of H){if(b.isBreaking&&b.migrationInstructions.length===0)B.push(`Breaking release ${J} is missing migration instructions.`);if(b.validation.commands.length===0)B.push(`Release capsule ${J} is missing validation commands.`);if(b.validation.evidence.length===0)B.push(`Release capsule ${J} is missing validation evidence.`)}if(W.baseline){try{let J=await F$($,{baseline:W.baseline,workspaceRoot:A});if(t$(X,!0,"impact",`Impact status: ${J.status}`),J.summary.breaking>0&&!Array.from(H.values()).some((b)=>b.isBreaking))B.push("Breaking impact detected without a breaking release capsule.")}catch(J){t$(X,!1,"impact",aW(J)),B.push(`Impact detection failed: ${aW(J)}`)}try{let J=await y0($,{baseline:W.baseline,workspaceRoot:A});t$(X,!0,"versioning",`${J.specsNeedingBump} spec(s) need version review.`)}catch(J){t$(X,!1,"versioning",aW(J)),B.push(`Version analysis failed: ${aW(J)}`)}}if(W.strict)for(let J of Q.publishArtifacts??[]){let b=j.join(Z,J);if(!await j.exists(b))B.push(`Missing generated release artifact: ${b}`)}if(t$(X,B.length===0,"capsules",B.length===0?"All release capsules are complete.":B[0]??""),!V&&!G)Y.push("No pending release changesets were found.");return{success:B.length===0,errors:B,warnings:Y,checks:X}}async function AA($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return tW;try{let A=JSON.parse(await $.readFile(j)),Q=yq.safeParse(A);return Q.success?{...tW,...Q.data.release}:tW}catch{return tW}}function mq($){return $.length>0?"minor":"patch"}function Pq($,W){return $.packages.map((A)=>W.find((Q)=>Q.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function kq($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function t$($,W,j,A){$.push({name:j,ok:W,message:A})}function aW($){return $ instanceof Error?$.message:String($)}var wA={};h(wA,{silentLogger:()=>YA,runWorkflow:()=>BA,loadWorkflows:()=>X5,loadVibeConfig:()=>eW,installPack:()=>bA,getWorkflow:()=>HA,exportContext:()=>XA,consoleLogger:()=>Z5,builtinWorkflows:()=>$1,DEFAULT_VIBE_CONFIG:()=>sW});import{existsSync as hq}from"node:fs";import{readFile as gq}from"node:fs/promises";import{join as Q5}from"node:path";import fq from"js-yaml";var sW={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function eW($){let W=$??process.cwd(),j=D(W)??W,A=[Q5(j,".contractspec","vibe","config.json"),Q5(j,".contractspec","vibe","config.yaml"),Q5(j,".contractspec","vibe","config.yml")],Q={};for(let Z of A)if(hq(Z))try{let X=await gq(Z,"utf-8");if(Z.endsWith(".json"))Q=JSON.parse(X);else Q=fq.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${Z}`,X)}return{...sW,...Q}}import{existsSync as uq}from"node:fs";import{copyFile as dq,mkdir as ZA,readFile as nq,writeFile as cq}from"node:fs/promises";import{dirname as rq,join as a$}from"node:path";import{glob as lq}from"glob";var oq=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function XA($){let W=$??process.cwd(),j=D(W)??W,A=await eW(W),Q=a$(j,".contractspec","context"),Z=a$(Q,"files"),X=[...oq],Y=a$(j,".gitignore");if(uq(Y)){let w=(await nq(Y,"utf-8")).split(`
|
|
2147
|
-
`).map((
|
|
2466
|
+
${w}
|
|
2467
|
+
`;if(!j)await A.writeFile(G,X),m.info("Generated changeset",{filePath:G});else m.info("Would generate changeset",{filePath:G,content:X})}catch(y){m.error("Failed to generate changeset",{error:y instanceof Error?y.message:String(y)})}}function A2(){let $=["neat","calm","wild","soft","bold","fair","cool"],b=["fox","cat","dog","bat","ant","elk","owl"],A=["run","fly","hop","eat","nap","cry","sing"],m=$[Math.floor(Math.random()*$.length)],n=b[Math.floor(Math.random()*b.length)],W=A[Math.floor(Math.random()*A.length)],w=Math.floor(Math.random()*1000);return`${m}-${n}-${W}-${w}`}var m2=T.object({summary:T.string(),maintainerSummary:T.string(),customerSummary:T.string(),integratorSummary:T.string(),deprecations:T.array(T.string()).default([]),migrationInstructions:T.array(T.object({id:T.string(),title:T.string(),summary:T.string(),required:T.boolean().default(!1),when:T.string().optional(),steps:T.array(T.string()).default([])})).default([]),upgradeSteps:T.array(T.object({id:T.string(),title:T.string(),summary:T.string(),level:T.enum(["auto","assisted","manual"]).default("manual"),instructions:T.array(T.string()).default([])})).default([]),validationCommands:T.array(T.string()).default([]),validationEvidence:T.array(T.string()).default([])});async function q1($,b={}){let{fs:A,git:m,logger:n,ai:W}=$,w=M(b.workspaceRoot),j=await $A(A,w),y=b.baseline?await m.diffFiles(b.baseline):[],B=await eb(A,w),S=await sb(A,w,B),Q=b.packages&&b.packages.length>0?b.packages:L0(y,j),Z=b.baseline?await Bb($,{baseline:b.baseline,workspaceRoot:w}):null,G=b.baseline?await V$($,{baseline:b.baseline,workspaceRoot:w}):null,X=b.slug??y2(B,S.capsules,Q),Y=X?A.join(w,".changeset",`${X}.md`):void 0,V=X?A.join(w,".changeset",`${X}.release.yaml`):void 0,O=X?B.find((q)=>q.slug===X):void 0,K=X?S.capsules.get(X):void 0,J=b.releaseType??K?.packages[0]?.releaseType??O?.packages[0]?.releaseType??((G?.summary.breaking??0)>0?"major":Z?.suggestedBumpType??B2(Q)),_=(Y?await A.exists(Y):!1)||(V?await A.exists(V):!1),H=await W2(W,n2({existingCapsule:K,existingChangeset:O,packageNames:Q,releaseType:J,summary:b.summary,workspacePackages:j,isBreaking:J==="major"||(G?.summary.breaking??0)>0,selectedSlug:X}),{changedFiles:y,commitMessages:b.baseline?(await m.log(b.baseline)).map((q)=>q.message):[],parseIssues:S.issues.map((q)=>q.message)},n);return{workspaceRoot:w,source:_?"existing":"created",changesetPath:Y??A.join(w,".changeset",`${H.slug}.md`),capsulePath:V??A.join(w,".changeset",`${H.slug}.release.yaml`),draft:H,warnings:S.issues.length?[`Some release capsules could not be parsed. ${bA(S.issues)}`]:[],parseIssues:S.issues,aiAssisted:W!==void 0}}async function O1($,b){let{fs:A}=$,m=M(b.workspaceRoot),n=mA(b.draft),W=A.join(m,".changeset",`${n.slug}.md`),w=A.join(m,".changeset",`${n.slug}.release.yaml`),j=await A.exists(W)||await A.exists(w)?"updated":"created",y=R0(n.summary,n.packages),B=C0(j2(n));return await A.writeFile(W,y),await A.writeFile(w,B),{source:j,changesetPath:W,capsulePath:w,changesetContent:y,capsuleContent:B}}function n2($){if($.existingCapsule)return mA({...$.existingCapsule,releaseType:$.releaseType});let b=$.existingChangeset?.packages.length?$.existingChangeset.packages.map((m)=>({...m,version:$.workspacePackages.find((n)=>n.name===m.name)?.version??m.version})):$.packageNames.map((m)=>({name:m,releaseType:$.releaseType,version:$.workspacePackages.find((n)=>n.name===m)?.version})),A=$.summary??$.existingChangeset?.summary??`Describe the ${$.releaseType} release for ${b[0]?.name??"the workspace"}`;return mA({slug:$.selectedSlug??S2(A),summary:A,releaseType:$.releaseType,isBreaking:$.isBreaking,packages:b,affectedRuntimes:[],affectedFrameworks:[],audiences:V1(A),deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}})}async function W2($,b,A,m){if(!$)return b;try{let n=await $.generateStructured({schema:m2,systemPrompt:"You write structured release metadata for a TypeScript monorepo. Be concise, concrete, and safe for public release notes.",prompt:JSON.stringify({draft:b,changedFiles:A.changedFiles.slice(0,40),commitMessages:A.commitMessages.slice(0,20),parseIssues:A.parseIssues})});return w2(b,n.object)}catch(n){return m.warn("Release AI suggestions unavailable, falling back to heuristics.",{error:n instanceof Error?n.message:String(n)}),b}}function w2($,b){let A=[...$.audiences];return tn(A,"maintainer",b.maintainerSummary),tn(A,"customer",b.customerSummary),tn(A,"integrator",b.integratorSummary),mA({...$,summary:J1($.summary)?b.summary:$.summary,audiences:A,deprecations:$.deprecations.length?$.deprecations:b.deprecations,migrationInstructions:$.migrationInstructions.length?$.migrationInstructions:b.migrationInstructions,upgradeSteps:$.upgradeSteps.length?$.upgradeSteps:b.upgradeSteps,validation:{commands:$.validation.commands.length?$.validation.commands:b.validationCommands,evidence:$.validation.evidence.length?$.validation.evidence:b.validationEvidence}})}function mA($){return{...$,packages:$.packages.map((b)=>({...b,releaseType:$.releaseType})),isBreaking:$.isBreaking||$.releaseType==="major",affectedRuntimes:[...$.affectedRuntimes],affectedFrameworks:[...$.affectedFrameworks],audiences:$.audiences.length?$.audiences:V1($.summary),validation:{commands:[...$.validation.commands],evidence:[...$.validation.evidence]}}}function j2($){let{releaseType:b,...A}=mA($);return{schemaVersion:"1",...A}}function V1($){return[{kind:"maintainer",summary:$},{kind:"customer",summary:$},{kind:"integrator",summary:`Upgrade affected packages and review the release guidance for: ${$}`}]}function tn($,b,A){let m=$.find((n)=>n.kind===b);if(m&&!J1(m.summary))return;if(m){m.summary=A;return}$.push({kind:b,summary:A})}function y2($,b,A){let m=new Set([...$.map((W)=>W.slug),...b.keys()].filter((W)=>W!=="auto-dependent-bumps"));if(m.size===1)return Array.from(m)[0];if(A.length===0)return;let n=Array.from(m).filter((W)=>{let w=b.get(W),j=$.find((B)=>B.slug===W);return(w?.packages.map((B)=>B.name)??j?.packages.map((B)=>B.name)??[]).some((B)=>A.includes(B))});return n.length===1?n[0]:void 0}function B2($){return $.length>0?"minor":"patch"}function J1($){return $.trim().startsWith("Describe the ")}function S2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as Q2}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as Z2,DEFAULT_CONTRACTSRC as G2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var K1="generated/releases",E0=G2.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function _1($,b={}){let{fs:A,git:m,logger:n}=$,W=M(b.workspaceRoot),w=await $A(A,W),j=b.baseline?await m.diffFiles(b.baseline):[],y=b.packages&&b.packages.length>0?b.packages:L0(j,w),B=b.baseline?await Bb($,{baseline:b.baseline,workspaceRoot:W}):null,S=b.baseline?await V$($,{baseline:b.baseline,workspaceRoot:W}):null,Q=(S?.summary.breaking??0)>0?"major":B?.suggestedBumpType??X2(y),Z=b.releaseType??Q,G=b.summary??`Describe the ${Z} release for ${y[0]??"the workspace"}`,X=b.slug??H2(G),Y=y.map((H)=>({name:H,releaseType:Z,version:w.find((q)=>q.name===H)?.version})),V={schemaVersion:"1",slug:X,summary:G,isBreaking:Z==="major"||(S?.summary.breaking??0)>0,packages:Y,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:G},{kind:"customer",summary:G}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},O=A.join(W,".changeset",`${X}.md`),K=A.join(W,".changeset",`${X}.release.yaml`);if(!b.force){if(await A.exists(O))throw Error(`Changeset already exists: ${O}`);if(await A.exists(K))throw Error(`Release capsule already exists: ${K}`)}let J=R0(G,Y),_=C0(V);if(!b.dryRun)await A.writeFile(O,J),await A.writeFile(K,_);return n.info("Initialized release artifacts",{slug:X,workspaceRoot:W}),{slug:X,changesetPath:O,capsulePath:K,changesetContent:J,capsuleContent:_,packages:Y,releaseType:Z,isBreaking:V.isBreaking}}async function U1($,b={}){let{fs:A,logger:m}=$,n=M(b.workspaceRoot),W=await L1(A,n),w=A.join(n,b.outputDir??K1),j=await eb(A,n),y=await sb(A,n,j);if(y.issues.length>0)throw Error(bA(y.issues));let B=y.capsules,S=await $A(A,n),Q=await Promise.all(Array.from(B.entries()).map(async([_,H])=>{let q=A.join(n,".changeset",`${_}.release.yaml`),U=await A.stat(q);return{slug:_,version:Y2(H,S),summary:H.summary,date:U.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:H.isBreaking,packages:H.packages.map((z)=>({...z,version:S.find((L)=>L.name===z.name)?.version??z.version})),affectedRuntimes:[...H.affectedRuntimes],affectedFrameworks:[...H.affectedFrameworks],audiences:[...H.audiences],deprecations:[...H.deprecations],migrationInstructions:[...H.migrationInstructions],upgradeSteps:[...H.upgradeSteps],validation:H.validation}})),Z=Q2.parse({generatedAt:new Date().toISOString(),releases:Q}),G=b.agentTargets??W.agentTargets??["codex"],X=lb(Z,[],G,yb),Y=A.join(w,"manifest.json"),V=A.join(w,"upgrade-manifest.json"),O=A.join(w,"patch-notes.md"),K=A.join(w,"customer-guide.md"),J=Object.fromEntries(X.agentPrompts.map((_)=>[_.agent,A.join(w,"prompts",`${_.agent}.md`)]));if(!b.dryRun){await A.writeFile(Y,JSON.stringify(Z,null,2)),await A.writeFile(V,JSON.stringify(Z,null,2)),await A.writeFile(O,fn(Z)),await A.writeFile(K,hn(Z));for(let _ of X.agentPrompts)await A.writeFile(J[_.agent]??"",_.prompt)}return m.info("Built release artifacts",{outputDir:w,releasesBuilt:Z.releases.length}),{outputDir:w,manifestPath:Y,upgradeManifestPath:V,patchNotesPath:O,customerGuidePath:K,promptPaths:J,manifest:Z,upgradePlan:X,releasesBuilt:Z.releases.length}}async function z1($,b={}){let{fs:A}=$,m=M(b.workspaceRoot),n=await L1(A,m),W=A.join(m,b.outputDir??K1),w=[],j=[],y=[],B=await eb(A,m),S=await sb(A,m,B),Q=S.capsules,Z=B.length>0,G=!Z&&Q.size>0;y.push(...S.issues.map((X)=>bA([X]))),Sb(w,Z||G,"changesets",Z?`Found ${B.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let X of B)if(!Q.has(X.slug)&&n.requireReleaseCapsule)y.push(`Missing release capsule for changeset ${X.slug}.`);for(let[X,Y]of Q){if(Y.isBreaking&&Y.migrationInstructions.length===0)y.push(`Breaking release ${X} is missing migration instructions.`);if(Y.validation.commands.length===0)y.push(`Release capsule ${X} is missing validation commands.`);if(Y.validation.evidence.length===0)y.push(`Release capsule ${X} is missing validation evidence.`)}if(b.baseline){try{let X=await V$($,{baseline:b.baseline,workspaceRoot:m});if(Sb(w,!0,"impact",`Impact status: ${X.status}`),X.summary.breaking>0&&!Array.from(Q.values()).some((Y)=>Y.isBreaking))y.push("Breaking impact detected without a breaking release capsule.")}catch(X){Sb(w,!1,"impact",M0(X)),y.push(`Impact detection failed: ${M0(X)}`)}try{let X=await AA($,{baseline:b.baseline,workspaceRoot:m});Sb(w,!0,"versioning",`${X.specsNeedingBump} spec(s) need version review.`)}catch(X){Sb(w,!1,"versioning",M0(X)),y.push(`Version analysis failed: ${M0(X)}`)}}if(b.strict)for(let X of n.publishArtifacts??[]){let Y=A.join(W,X);if(!await A.exists(Y))y.push(`Missing generated release artifact: ${Y}`)}if(Sb(w,y.length===0,"capsules",y.length===0?"All release capsules are complete.":y[0]??""),!Z&&!G)j.push("No pending release changesets were found.");return{success:y.length===0,errors:y,warnings:j,checks:w}}async function L1($,b){let A=$.join(b,".contractsrc.json");if(!await $.exists(A))return E0;try{let m=JSON.parse(await $.readFile(A)),n=Z2.safeParse(m);return n.success?{...E0,...n.data.release}:E0}catch{return E0}}function X2($){return $.length>0?"minor":"patch"}function Y2($,b){return $.packages.map((m)=>b.find((n)=>n.name===m.name)?.version??m.version).find((m)=>typeof m==="string")??"0.0.0"}function H2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Sb($,b,A,m){$.push({name:A,ok:b,message:m})}function M0($){return $ instanceof Error?$.message:String($)}var g1={};P(g1,{silentLogger:()=>E1,runWorkflow:()=>M1,loadWorkflows:()=>en,loadVibeConfig:()=>T0,installPack:()=>v1,getWorkflow:()=>T1,exportContext:()=>I1,consoleLogger:()=>an,builtinWorkflows:()=>D0,DEFAULT_VIBE_CONFIG:()=>x0});import{existsSync as q2}from"node:fs";import{readFile as O2}from"node:fs/promises";import{join as pn}from"node:path";import V2 from"js-yaml";var x0={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function T0($){let b=$??process.cwd(),A=M(b)??b,m=[pn(A,".contractspec","vibe","config.json"),pn(A,".contractspec","vibe","config.yaml"),pn(A,".contractspec","vibe","config.yml")],n={};for(let W of m)if(q2(W))try{let w=await O2(W,"utf-8");if(W.endsWith(".json"))n=JSON.parse(w);else n=V2.load(w);break}catch(w){console.warn(`Warning: Failed to parse ${W}`,w)}return{...x0,...n}}import{existsSync as J2}from"node:fs";import{copyFile as K2,mkdir as C1,readFile as _2,writeFile as U2}from"node:fs/promises";import{dirname as z2,join as Qb}from"node:path";import{glob as L2}from"glob";var R2=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function I1($){let b=$??process.cwd(),A=M(b)??b,m=await T0(b),n=Qb(A,".contractspec","context"),W=Qb(n,"files"),w=[...R2],j=Qb(A,".gitignore");if(J2(j)){let Y=(await _2(j,"utf-8")).split(`
|
|
2468
|
+
`).map((V)=>V.trim()).filter((V)=>V&&!V.startsWith("#"));w=[...w,...Y]}let y=m.contextExportAllowlist.length>0?m.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],B=[];for(let X of y){let Y=await L2(X,{cwd:A,ignore:w,nodir:!0,dot:!0});B.push(...Y)}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 C1(W,{recursive:!0});let Q=[];for(let X of S){let Y=Qb(A,X),V=Qb(W,X);await C1(z2(V),{recursive:!0}),await K2(Y,V),Q.push({path:X,size:0})}let Z=Qb(n,"index.json"),G={generatedAt:new Date().toISOString(),files:Q.map((X)=>X.path),config:{allowlist:m.contextExportAllowlist,ignores:w.length}};return await U2(Z,JSON.stringify(G,null,2)),{success:!0,files:S,indexPath:Z}}var D0=[{id:"brownfield.openapi-import",name:"Brownfield: OpenAPI Import",description:"Import OpenAPI into draft contracts, review, and generate artifacts.",steps:[{id:"extract",label:"Extract Drafts",command:"contractspec extract --from openapi --out .contractspec/work/openapi-import"},{id:"review",label:"Review Drafts",manualCheckpoint:!0,manualMessage:`Drafts extracted to .contractspec/work/openapi-import.
|
|
2148
2469
|
Please review them and move selected files to contracts/ directory.
|
|
2149
|
-
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"
|
|
2150
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2151
|
-
`);let
|
|
2152
|
-
\uD83D\uDC49 Step: ${
|
|
2470
|
+
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 C2}from"node:child_process";var E1={log:()=>{},warn:()=>{},error:()=>{}},an={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function M1($,b,A){let m=A?.logger??an,n=A?.prompter;if(m.log(`
|
|
2471
|
+
Running Workflow: ${$.name}`),$.description)m.log($.description);if(m.log(`Track: ${b.track}`),b.dryRun)m.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2472
|
+
`);let W={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let w of $.steps){let j={id:w.id,name:w.label,status:"skip",command:w.command};if(w.tracks&&!w.tracks.includes(b.track)){W.steps.push(j);continue}if(w.condition){if(!await w.condition(b)){W.steps.push(j);continue}}if(m.log(`
|
|
2473
|
+
\uD83D\uDC49 Step: ${w.label}`),b.dryRun&&w.command)m.log(` Command: ${w.command}`);if(w.manualCheckpoint){if(b.dryRun)m.warn(" [Manual Checkpoint] Would pause here for user input.");else if(n){if(w.manualMessage)m.log(w.manualMessage);let y=await n.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(y==="abort")return m.warn("Workflow aborted by user."),W.success=!1,W.steps.push({...j,status:"skip",error:"Aborted by user"}),W;if(y==="skip"){m.warn(" → Skipped by user."),W.steps.push(j);continue}}}if(!b.dryRun)try{if(w.execute)await w.execute(b);else if(w.command)await I2(w.command,b.root);j.status="pass",W.stepsExecuted.push(w.id),W.steps.push(j),m.log(" ✓ Completed")}catch(y){let B=y instanceof Error?y.message:String(y);return m.error(` ❌ Failed: ${B}`),W.success=!1,W.error=y instanceof Error?y:Error(String(y)),j.status="fail",j.error=B,W.stepsExecuted.push(w.id),W.steps.push(j),W}else W.steps.push(j)}return W}async function I2($,b){let A=$.split(" "),m=A[0],n=A.slice(1);if(!m)throw Error("Invalid command");return new Promise((W,w)=>{let j=C2(m,n,{cwd:b,stdio:"inherit",shell:!0});j.on("error",w),j.on("exit",(y)=>{if(y===0)W();else w(Error(`Command exited with code ${y}`))})})}import{existsSync as E2}from"node:fs";import{readdir as M2,readFile as x2}from"node:fs/promises";import{join as x1}from"node:path";import T2 from"js-yaml";async function en($){let b=[...D0],A=$??process.cwd(),m=M(A)??A,n=x1(m,".contractspec","vibe","workflows");if(E2(n))try{let W=await M2(n);for(let w of W)if(w.endsWith(".json")||w.endsWith(".yaml")||w.endsWith(".yml")){let j=await x2(x1(n,w),"utf-8");try{let y;if(w.endsWith(".json"))y=JSON.parse(j);else y=T2.load(j);if(y.id&&y.steps)b.push(y)}catch(y){console.warn(`Failed to parse workflow ${w}:`,y)}}}catch(W){console.warn("Error loading user workflows:",W)}return b}async function T1($,b){return(await en(b)).find((m)=>m.id===$)}import{existsSync as sn}from"node:fs";import{copyFile as D1,mkdir as N1,readdir as F1,stat as D2}from"node:fs/promises";import{join as E$,resolve as N2}from"node:path";async function v1($,b){let A=b??process.cwd(),m=M(A)??A;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let n=N2(A,$);if(!sn(n))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${n}`};let W=0,w=0,j=E$(n,"workflows");if(sn(j)){let B=E$(m,".contractspec","vibe","workflows");await N1(B,{recursive:!0});let S=await F1(j);for(let Q of S)if(Q.endsWith(".json")||Q.endsWith(".yaml")||Q.endsWith(".yml"))await D1(E$(j,Q),E$(B,Q)),W++}let y=E$(n,"templates");if(sn(y)){let B=E$(m,".contractspec","vibe","templates");await N1(B,{recursive:!0});let S=await F1(y);for(let Q of S){let Z=E$(y,Q),G=E$(B,Q);if((await D2(Z)).isFile())await D1(Z,G),w++}}return{success:!0,workflowsInstalled:W,templatesInstalled:w}}import{loadSpecFromSource as F2}from"@contractspec/module.workspace";var k1=["product","eng","qa"];function v2($){return k1.includes($)}async function SM($,b){if(!v2(b.audience))throw Error(`Invalid audience: ${b.audience}. Must be one of: ${k1.join(", ")}`);let A,m,n;if(b.specFiles&&b.specFiles.length>0)A=b.specFiles;else{let w=await g2($,{baseline:b.baseline});if(m=w.totalSpecs,n=w.changedFilesCount,b.baseline){if(w.changedFilesCount===0)return{views:[],totalSpecs:m,changedFilesCount:0,status:"no_changes"};if(w.specFiles.length===0)return{views:[],totalSpecs:m,changedFilesCount:n,status:"no_changed_specs"}}A=w.specFiles}if(A.length===0)return{views:[],totalSpecs:m,changedFilesCount:n,status:"no_specs"};let W=[];for(let w of A){let j=await k2(w,b.audience,$);W.push({filePath:w,content:j})}return{views:W,totalSpecs:m,changedFilesCount:n,status:"success"}}async function g2($,b={}){let m=(await j$({fs:$.fs})).map((j)=>j.filePath),n=m.length;if(!b.baseline)return{specFiles:m,totalSpecs:n};let W=await $.git.diffFiles(b.baseline);if(W.length===0)return{specFiles:[],totalSpecs:n,changedFilesCount:0,hasChanges:!1};let w=m.filter((j)=>W.some((y)=>j.endsWith(y)||y.endsWith(j)||j.includes(y)||y.includes(j)));return{specFiles:w,totalSpecs:n,changedFilesCount:W.length,hasChanges:w.length>0}}async function k2($,b,A){if(!await A.fs.exists($))throw Error(`File not found: ${$}`);let m=await F2($);if(m.length===0)return`No specs found in ${$} (Parse result empty)`;return m.map((n)=>P2(n,b)).join(`
|
|
2153
2474
|
|
|
2154
2475
|
---
|
|
2155
2476
|
|
|
2156
|
-
`)}function
|
|
2157
|
-
`)}function
|
|
2477
|
+
`)}function P2($,b){let A=[];switch(b){case"product":r2($,A);break;case"eng":f2($,A);break;case"qa":h2($,A);break}return A.join(`
|
|
2478
|
+
`)}function r2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2158
2479
|
${$.meta.goal}
|
|
2159
|
-
`);if($.meta.context)
|
|
2480
|
+
`);if($.meta.context)b.push(`### Context
|
|
2160
2481
|
${$.meta.context}
|
|
2161
|
-
`);if($.specType==="feature"){if($.operations?.length)
|
|
2162
|
-
`);if($.testRefs?.length)
|
|
2163
|
-
`)}export{
|
|
2482
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- ✅ Enforces Business Policies");if($.hasIo)b.push("- ✅ Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((A)=>b.push(`- **${A.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function f2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"✅ Defined":"❌ Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"✅ Defined":"❌ None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function h2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2483
|
+
`);if($.testRefs?.length)b.push("### Linked Scenarios"),$.testRefs.forEach((A)=>b.push(`- \uD83E\uDDEA \`${A.name}\``)),b.push("");else b.push("### Linked Scenarios"),b.push("_(No explicit test refs found)_"),b.push("");if(b.push("### Verification Checklist"),$.specType==="operation"){if(b.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)b.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((A)=>b.push(`- [ ] Verify event \`${A.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((A)=>b.push(`- [ ] Test Operation flow: \`${A.name}\``));if($.presentations?.length)$.presentations.forEach((A)=>b.push(`- [ ] Test UI Component: \`${A.name}\``))}}function XM($,b,A,m){let{watcher:n,fs:W,logger:w}=$,j=n.watch(A),y=m?.validate??(async(S)=>{await d$(S,{fs:W,logger:w})}),B=m?.build??(async(S)=>{await $b(S,{fs:W,logger:w},b)});return j.on(async(S)=>{if(S.type!=="change")return;if(w.info("watchSpecs.changed",{path:S.path}),A.runValidate)await y(S.path);if(A.runBuild)if(A.dryRun)w.info("[dry-run] watchSpecs skipped build",{path:S.path});else await B(S.path)}),j}async function qM($,b){let A=OW(b),m=$.join(A.workspaceRoot,".contractsrc.json"),n=$.join(A.packageRoot,".contractsrc.json"),W=await $.exists(m),w=A.workspaceRoot!==A.packageRoot?await $.exists(n):!1,j;if(W)try{let y=await $.readFile(m),B=JSON.parse(y);if(B.packages||B.excludePackages||B.recursive)j={packages:B.packages,excludePackages:B.excludePackages,recursive:B.recursive}}catch{}return{...A,monorepoConfig:j,workspaceConfigPath:W?m:void 0,packageConfigPath:w?n:void 0}}async function OM($,b){let A=[],m=$.join(b,".contractsrc.json");if(await $.exists(m))A.push(m);let n=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let W of n)if(W!==m)A.push(W);return A}async function VM($,b,A){let m={};if(b&&await $.exists(b))try{let n=await $.readFile(b);m=JSON.parse(n)}catch{}if(A&&await $.exists(A))try{let n=await $.readFile(A),W=JSON.parse(n);m=P1(m,W)}catch{}return m}function P1($,b){let A={...$};for(let m of Object.keys(b)){let n=$[m],W=b[m];if(typeof n==="object"&&n!==null&&!Array.isArray(n)&&typeof W==="object"&&W!==null&&!Array.isArray(W))A[m]=P1(n,W);else A[m]=W}return A}function JM($){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(`
|
|
2484
|
+
`)}export{XM as watchSpecs,g1 as vibe,R1 as versioning,BG as verifyWithAIEnhanced,tb as verifyWithAI,pb as verifyStructure,EG as verifyService,n1 as verifySemanticFields,C6 as verifyImportedContracts,uz as verifyImplementationAgainstParsedSpec,J0 as verifyBehavior,HC as validateTenantConfig,SC as validateSpecs,d$ as validateSpec,zy as validateScannedSpec,bC as validatePackageScaffold,tR as validateImplementationWithAgent,dA as validateImplementationFiles,BC as validateDiscoveredSpecs,uR as validateBlueprint,v2 as validateAudience,jU as validateAgainstOpenApiService,Ew as utils,ly as upgrade,uC as updateSpec,DS as toKebabCase,Kw as templates,nU as syncWithOpenApiService,CC as syncSpecs,AG as stringToCacheKey,Tn as setupUsageMd,sA as setupGitignore,Rn as setupAgentsMd,cL as searchRegistry,p as safeParseJson,FC as runTests,vC as runTestSpecs,MR as runSetup,ML as runQuickstart,ew as runDoctor,MJ as runCIChecks,Fw as resolveSetupTargets,U$ as resolveSetupPreset,zn as resolveRegistryUrl,PS as resolveImplementations,wm as resolveDefaultBuildTargets,Sy as resolveAuthoredModuleValue,Sj as resolveAllImplementations,ub as renderManagedMarkdownBlock,IW as prompts,HW as parseGitModules,jj as parseExplicitImplementations,kY as operationRegistry,Hy as onboarding,Ln as normalizeMarkdownContent,Zx as module,VM as mergeMonorepoConfigs,Q0 as mergeManagedMarkdown,vQ as mergeGitignoreContent,g as loadWorkspaceConfig,cO as loadPackageAuthoredDocBlocks,yy as loadAuthoredModuleValue,wL as loadAuthoredModuleIfExists,y0 as loadAuthoredModuleExports,n$ as loadAuthoredModule,hO as loadAuthoredDocBlocksFromSourceFiles,gC as listTests,g2 as listSpecsForView,j$ as listSpecs,hL as listFromRegistry,bm as listAgentTypes,Gb as isMonorepo,xL as isContractSpecInstalled,kq as isConnectPreset,gq as isBuilderPreset,zb as inferSetupPresetFromConfig,TS as inferImplementationType,J6 as importFromSourceService,lj as importFromOpenApiService,Uj as impact,Wy as hooks,eV as groupSpecsByType,zB as getWorkspacePackages,OW as getWorkspaceInfo,CX as getRunCommand,_n as getProductionDependencies,T$ as getPackageName,RB as getMetaRepoInfo,VW as getInstallCommand,VV as getImplementationSummary,Jq as getGraphStats,qM as getExtendedWorkspaceInfo,IX as getExecCommand,Un as getDevDependencies,Kn as getDependencies,wj as getConventionPaths,Oq as getContractNode,gA as getClaudeDesktopConfigPath,Om as getBuilderRuntimeModeForPreset,vw as getBuilderBootstrapPresetForSetupPreset,Rw as getApiKey,rV as getAllSpecs,AO as getAllLayerLocations,Yb as getAgentAdapter,d0 as getAIProvider,OA as genericMCPAdapter,Jw as generateWorkflowSpec,EA as generateWorkflowRunnerTemplate,zA as generateWorkflowDevkitWorkflowTemplate,CA as generateWorkflowDevkitStreamRouteTemplate,LA as generateWorkflowDevkitStartRouteTemplate,IA as generateWorkflowDevkitGenericTemplate,RA as generateWorkflowDevkitFollowUpRouteTemplate,vA as generateVscodeSettings,oW as generateVisualizationSpec,SM as generateViews,k2 as generateView,hw as generateUsageGuide,dW as generateTranslationSpec,Vw as generateThemeSpec,Sw as generateTestTemplate,cW as generateTestSpec,Ow as generateTelemetrySpec,tW as generateProductIntentSpec,qw as generatePresentationSpec,hW as generatePolicySpec,Hw as generateOperationSpec,Yw as generateMigrationSpec,cz as generateMermaidDiagram,L6 as generateMarkdownReport,Gw as generateKnowledgeSpaceSpec,uW as generateJobSpec,Zw as generateIntegrationSpec,aW as generateHarnessSuiteSpec,pW as generateHarnessScenarioSpec,yw as generateHandlerTemplate,D6 as generateGuideFromParsedSpec,jw as generateFormSpec,ww as generateFeatureSpec,pz as generateFeatureContextMarkdown,Ww as generateExperimentSpec,iW as generateExampleSpec,nw as generateEventSpec,bj as generateDocsFromSpecs,mw as generateDataViewSpec,_A as generateDataViewRendererTemplate,N6 as generateCursorRulesFromParsedSpec,rw as generateCursorRules,Lb as generateCursorMcpConfig,bb as generateContractsrcConfig,Bw as generateComponentTemplate,R6 as generateCliReport,Pw as generateClaudeMcpConfig,fW as generateCapabilitySpec,mj as generateArtifacts,Aw as generateAppBlueprintSpec,fw as generateAgentsGuide,lW as generateAgentSpec,xW as formatters,JM as formatWorkspaceInfo,oz as formatVerificationReport,TL as formatQuickstartPreview,By as formatModuleLoadError,N as formatJson,Hz as formatFiles,xO as formatDoctorSummary,TO as formatCheckResult,$y as fix,M as findWorkspaceRoot,r as findPackageRoot,qW as findMetaRepoRoot,OM as findAllConfigFiles,fV as filterIssuesByType,hV as filterIssuesBySeverity,pj as features,nj as extractSpecReferences,qU as extractContracts,az as exportSpecForLLM,M4 as exportOpenApi,Vq as exportGraphAsDot,Uw as ensurePackageScaffold,xA as discoverSpecs,g$ as discoverSpecFiles,PA as discoverLayers,uA as discoverImplementationsForSpec,XV as discoverAllImplementations,yj as determineStatus,CB as detectRepositoryType,o$ as detectPackageManager,h_ as deleteSpec,$$ as deepMergePreserve,Vm as deepMergeOverwrite,HA as cursorCLIAdapter,YI as createWorkspaceStateCacheStorage,pB as createWorkspaceRegistry,IG as createVerifyService,zI as createVerificationCacheService,v_ as createSpecCreator,gw as createSetupNextSteps,kw as createSetupGitignorePatterns,PL as createRegeneratorService,V0 as createQuickAIReview,zw as createPackageTargetSpecSource,QW as createNoopLoggerAdapter,ZW as createNodeWatcherAdapter,BW as createNodeGitAdapter,jW as createNodeFsAdapter,mW as createNodeAiAdapter,HX as createNodeAdapters,GI as createInMemoryCacheStorage,QI as createFileSystemCacheStorage,r9 as createEmptyLayerInventory,SW as createConsoleLoggerAdapter,_X as createBunFsAdapter,O9 as createBuilderWorkspaceId,I5 as createAgentGuideService,cj as connect,$1 as computeContentHash,u_ as compareSpecs,kJ as cleanArtifacts,XA as claudeCodeAdapter,b1 as cacheKeyToString,$b as buildSpec,DA as analyzeWorkspaceDocBlocks,oA as analyzeIntegrity,Jz as analyzeGap,Mw as analyzeDeps,E5 as agentGuideService,$m as agentAdapters,s0 as adoption,fL as addToRegistry,jL as __moduleLoaderInternals,ey as WorkspaceStateCacheStorage,K0 as VerifyService,A1 as VerificationCacheService,k1 as VALID_AUDIENCES,YZ as TestGeneratorService,uj as SpecCreatorService,yA as SimpleAgent,xw as SETUP_TARGET_LABELS,Dw as SETUP_PRESET_LABELS,Nw as SETUP_PRESET_DESCRIPTIONS,Ub as SETUP_GITIGNORE_PATTERNS,j7 as RuleSyncService,S0 as RegistryClient,sB as PrActionService,jA as OpenAICodexAgent,qy as MINIMAL_DEPENDENCIES,ay as InMemoryCacheStorage,qA as GenericMCPAdapter,py as FileSystemCacheStorage,b7 as FULL_DEPENDENCIES,aB as DriftActionService,X$ as DEFAULT_SPEC_PATTERNS,x$ as DEFAULT_FS_IGNORES,sy as DEFAULT_CACHE_CONFIG,YA as CursorCLIAdapter,wA as CursorAgent,WA as ClaudeCodeAgent,GA as ClaudeCodeAdapter,X7 as CONTRACTSPEC_USAGE_BLOCK_START,Y7 as CONTRACTSPEC_USAGE_BLOCK_END,B7 as CONTRACTSPEC_AGENTS_BLOCK_START,S7 as CONTRACTSPEC_AGENTS_BLOCK_END,DJ as CI_CHECK_CATEGORY_LABELS,aw as CHECK_CATEGORY_LABELS,BA as AgentOrchestrator,VA as AgentGuideService,_b as ALL_SETUP_TARGETS,Tw as ALL_SETUP_PRESETS,TJ as ALL_CI_CHECK_CATEGORIES,pw as ALL_CHECK_CATEGORIES,A0 as AIGenerator};
|