@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/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)){if(!
|
|
4
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
5
|
-
`).map((
|
|
2
|
+
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$=import.meta.require;import{ContractsrcSchema as g8,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=g8.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 q4}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as O4,buildEventSpecPrompt as V4,buildFormPrompt as J4,buildHandlerPrompt as K4,buildOperationSpecPrompt as _4,buildPresentationSpecPrompt as U4,buildTestPrompt as z4,getCodeGenSystemPrompt as Pb,getSystemPrompt as wn}from"@contractspec/module.workspace";import{generateObject as jn,generateText as b0,streamText as L4}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 q4(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=_4($,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=V4($);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=U4($,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:K4($),system:Pb()})).text}async generateComponent($){let b=this.getModel();return(await b0({model:b,prompt:O4($),system:Pb()})).text}async generateForm($){let b=this.getModel();return(await b0({model:b,prompt:J4($),system:Pb()})).text}async generateTests($,b,A){let m=this.getModel();return(await b0({model:m,prompt:z4($,b,A),system:Pb()})).text}async streamCodeGeneration($,b){let A=this.getModel(),m=await L4({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 Sx from"@contractspec/module.workspace";import{anthropic as d1}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 u1,generateText as o1,streamText as i1}from"ai";import{ollama as l1}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 o1({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 u1(m)).object}},async streamText(b,A){let m=N0($),n=await i1({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 d1(n)}case"openai":{let n=A??AW.openai;return bW(n)}case"ollama":return l1(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 SB}from"@contractspec/lib.contracts-spec/workspace-config";import{access as t1,stat as p1,mkdir as nW,readFile as a1,rm as e1,writeFile as s1}from"fs/promises";import{basename as $B,dirname as WW,isAbsolute as bB,join as AB,relative as mB,resolve as wW}from"path";import{glob as nB}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 t1(A(m)),!0}catch{return!1}},async readFile(m){return a1(A(m),"utf-8")},async writeFile(m,n){let W=A(m),w=WW(W);await nW(w,{recursive:!0}),await s1(W,n,"utf-8")},async remove(m){await e1(A(m),{recursive:!0,force:!0})},async stat(m){let n=await p1(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 nB(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 $B(m)},join(...m){return AB(...m)},relative(m,n){return mB(m,n)}};function A(m){return bB(m)?m:wW(b,m)}}import{execFileSync as Zb}from"child_process";import{access as WB}from"fs/promises";import{resolve as yW}from"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(`
|
|
3
|
+
`)){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(`
|
|
4
|
+
`).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 wB()}}}function QW(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:jB}}function wB(){return{start($){console.warn(`\u23F3 ${$}`)},update($){let b=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${b}`)},succeed($){console.warn(`\u2705 ${$??"Done"}`)},fail($){console.error(`\u274C ${$??"Failed"}`)},warn($){console.warn(`\u26A0\uFE0F ${$??"Warning"}`)},stop(){}}}function jB(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import yB from"chokidar";var BB=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function ZW($){let b=$??process.cwd();return{watch(A){let m=[],n,W=yB.watch(A.pattern,{cwd:b,ignored:A.ignore??BB,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 XX($={}){let{cwd:b,config:A,silent:m}=$,n=A??SB;return{fs:jW(b),git:BW(b),watcher:ZW(b),ai:mW(n),logger:m?QW():SW()}}import{stat as QB,mkdir as ZB}from"fs/promises";import{basename as GB,dirname as XB,isAbsolute as YB,join as HB,relative as qB,resolve as GW}from"path";import{glob as OB}from"glob";function JX($){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 QB(A(m));return{size:n.size,isFile:n.isFile(),isDirectory:n.isDirectory(),mtime:n.mtime}},async mkdir(m){await ZB(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 OB(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 XB(m)},basename(m){return GB(m)},join(...m){return HB(...m)},relative(m,n){return qB(m,n)}};function A(m){return YB(m)?m:GW(b,m)}}import{existsSync as d,readFileSync as K$}from"fs";import{tmpdir as VB}from"os";import{dirname as F0,isAbsolute as JB,join as c,relative as KB,resolve as u$}from"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 _B($,b){let A=KB(b,$);return A===""||!A.startsWith("..")&&!JB(A)}function v0($){let b=u$($),A=u$(VB());return _B(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 UB($){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(`
|
|
5
|
+
`).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"))&&zB(B);m.push({name:w,path:j,url:y,absolutePath:B,hasWorkspaces:S})}}return m}catch{return[]}}function zB($){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 LB($){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 RB($,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?UB(A):void 0,w=T$(b),j=RB($,n),y=j==="meta-repo"?LB($):void 0;return{packageManager:m,workspaceRoot:A,packageRoot:b,isMonorepo:n,packages:W,packageName:w,repositoryType:j,metaRepo:y}}function LX($,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 RX($,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=`
|
|
6
6
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
7
7
|
|
|
8
8
|
SPECIFICATION:
|
|
@@ -31,7 +31,7 @@ Provide a structured validation report:
|
|
|
31
31
|
- Are there any missing edge cases?
|
|
32
32
|
|
|
33
33
|
Be thorough and precise. Use a critical but constructive tone.
|
|
34
|
-
`,
|
|
34
|
+
`,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.
|
|
35
35
|
|
|
36
36
|
Your code is:
|
|
37
37
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -51,7 +51,7 @@ Your code is:
|
|
|
51
51
|
- Following SOLID principles and best practices
|
|
52
52
|
- Modular and testable
|
|
53
53
|
|
|
54
|
-
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let
|
|
54
|
+
Generate clean, idiomatic TypeScript code that exactly matches the specification.`}buildUserPrompt($){let b={generate:`Generate a complete, production-ready implementation for this specification:
|
|
55
55
|
|
|
56
56
|
${$.specCode}
|
|
57
57
|
|
|
@@ -74,10 +74,10 @@ Spec:
|
|
|
74
74
|
${$.specCode}
|
|
75
75
|
|
|
76
76
|
Code:
|
|
77
|
-
${$.existingCode}`};return
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
80
|
-
`);for(let
|
|
77
|
+
${$.existingCode}`};return b[$.type]||b.generate}extractCode($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b&&b[1])return b[1];return $}detectIssues($){let b=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],A=$.toLowerCase();return b.some((m)=>A.includes(m))}extractErrors($){let b=[],A=$.split(`
|
|
78
|
+
`);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(`
|
|
79
|
+
`);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(`
|
|
80
|
+
`);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 CB}from"child_process";import{existsSync as _W}from"fs";import{mkdir as UW,readFile as IB,rm as EB,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=CB(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 IB(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
|
|
81
81
|
|
|
82
82
|
This workspace was prepared for Cursor AI code generation.
|
|
83
83
|
|
|
@@ -92,19 +92,19 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
92
92
|
3. Use Cursor AI to generate code based on the spec
|
|
93
93
|
4. Save the result as output.ts
|
|
94
94
|
|
|
95
|
-
Workspace path: ${
|
|
96
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${
|
|
95
|
+
Workspace path: ${b}
|
|
96
|
+
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${b}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:b}}}async setupValidationWorkspace($,b){await 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
|
|
97
97
|
|
|
98
98
|
**Task Type:** ${$.type}
|
|
99
99
|
**Generated:** ${new Date().toISOString()}
|
|
100
100
|
|
|
101
|
-
`,
|
|
101
|
+
`,A=`## Specification
|
|
102
102
|
|
|
103
103
|
\`\`\`typescript
|
|
104
104
|
${$.specCode}
|
|
105
105
|
\`\`\`
|
|
106
106
|
|
|
107
|
-
`,
|
|
107
|
+
`,m={generate:`## Task: Generate Implementation
|
|
108
108
|
|
|
109
109
|
### Requirements:
|
|
110
110
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -197,7 +197,7 @@ ${$.existingCode||""}
|
|
|
197
197
|
- Enhance error messages
|
|
198
198
|
|
|
199
199
|
### Output Format:
|
|
200
|
-
Refactored code that maintains functionality while improving quality.`};return
|
|
200
|
+
Refactored code that maintains functionality while improving quality.`};return b+A+(m[$.type]||m.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
201
201
|
|
|
202
202
|
## Specification
|
|
203
203
|
\`\`\`typescript
|
|
@@ -245,7 +245,7 @@ Provide detailed feedback for each failed item.
|
|
|
245
245
|
Suggest specific improvements with code examples where applicable.`}generateTemplate($){return`// Auto-generated template for ${$.type} task
|
|
246
246
|
// Specification:
|
|
247
247
|
${$.specCode.split(`
|
|
248
|
-
`).map((
|
|
248
|
+
`).map((b)=>`// ${b}`).join(`
|
|
249
249
|
`)}
|
|
250
250
|
|
|
251
251
|
// TODO: Implement according to specification
|
|
@@ -255,7 +255,7 @@ export function implementation() {
|
|
|
255
255
|
// Implementation goes here
|
|
256
256
|
throw new Error('Not implemented');
|
|
257
257
|
}
|
|
258
|
-
`}async cleanupWorkDir($){try{await
|
|
258
|
+
`}async cleanupWorkDir($){try{await EB($,{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=`
|
|
259
259
|
Review this code implementation against its specification.
|
|
260
260
|
|
|
261
261
|
SPECIFICATION:
|
|
@@ -275,7 +275,7 @@ Provide a detailed validation report including:
|
|
|
275
275
|
4. Recommendations for improvement
|
|
276
276
|
|
|
277
277
|
Format as a structured report.
|
|
278
|
-
`,
|
|
278
|
+
`,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.
|
|
279
279
|
|
|
280
280
|
Generate production-quality code that is:
|
|
281
281
|
- Type-safe and well-typed
|
|
@@ -312,9 +312,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
312
312
|
${$.existingCode}
|
|
313
313
|
|
|
314
314
|
Spec:
|
|
315
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let
|
|
316
|
-
`);for(let
|
|
317
|
-
`);for(let
|
|
315
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return b&&b[1]?b[1]:$}detectIssues($){let b=["issue","problem","bug","error","incorrect","missing","fails","violation"],A=$.toLowerCase();return b.some((m)=>A.includes(m))}extractErrors($){let b=[],A=$.split(`
|
|
316
|
+
`);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(`
|
|
317
|
+
`);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 TB 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.
|
|
318
318
|
|
|
319
319
|
Here is the contract spec:
|
|
320
320
|
|
|
@@ -333,7 +333,7 @@ Generate a complete handler implementation that:
|
|
|
333
333
|
|
|
334
334
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
335
335
|
|
|
336
|
-
Return only the TypeScript code for the handler function.`}function
|
|
336
|
+
Return only the TypeScript code for the handler function.`}function P0($){return`You are a senior React developer creating a component for a presentation specification.
|
|
337
337
|
|
|
338
338
|
Here is the presentation spec:
|
|
339
339
|
|
|
@@ -352,7 +352,7 @@ Generate a complete React component that:
|
|
|
352
352
|
|
|
353
353
|
The component should follow Atomic Design principles and be reusable.
|
|
354
354
|
|
|
355
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
355
|
+
Return only the TypeScript/TSX code for the component.`}function r0($){return`You are a senior React developer creating a form component from a form specification.
|
|
356
356
|
|
|
357
357
|
Here is the form spec:
|
|
358
358
|
|
|
@@ -372,7 +372,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
372
372
|
|
|
373
373
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
374
374
|
|
|
375
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
375
|
+
Return only the TypeScript/TSX code for the form component.`}function f0($,b,A){return`You are a senior developer writing comprehensive tests.
|
|
376
376
|
|
|
377
377
|
Spec:
|
|
378
378
|
\`\`\`typescript
|
|
@@ -381,11 +381,11 @@ ${$}
|
|
|
381
381
|
|
|
382
382
|
Implementation:
|
|
383
383
|
\`\`\`typescript
|
|
384
|
-
${
|
|
384
|
+
${b}
|
|
385
385
|
\`\`\`
|
|
386
386
|
|
|
387
387
|
Generate complete test suite using Vitest that:
|
|
388
|
-
${
|
|
388
|
+
${A==="handler"?`
|
|
389
389
|
- Test all acceptance scenarios from the spec
|
|
390
390
|
- Test error cases defined in spec.io.errors
|
|
391
391
|
- Verify events are emitted correctly
|
|
@@ -399,7 +399,7 @@ ${j==="handler"?`
|
|
|
399
399
|
|
|
400
400
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
401
401
|
|
|
402
|
-
Return only the TypeScript test code.`}function
|
|
402
|
+
Return only the TypeScript test code.`}function h0(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
403
403
|
- Type-safe API design
|
|
404
404
|
- React and modern hooks
|
|
405
405
|
- Test-driven development
|
|
@@ -413,7 +413,7 @@ Generate production-ready code that is:
|
|
|
413
413
|
- Defensive and error-safe
|
|
414
414
|
- Easy to maintain and extend
|
|
415
415
|
|
|
416
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
416
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as MB}from"@contractspec/lib.ai-providers";function d0($){let b={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return MB(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=`
|
|
417
417
|
Review the following implementation against its specification.
|
|
418
418
|
|
|
419
419
|
Specification:
|
|
@@ -427,17 +427,17 @@ Provide a detailed validation report:
|
|
|
427
427
|
2. Are there any missing features?
|
|
428
428
|
3. Are there any bugs or issues?
|
|
429
429
|
4. Suggestions for improvement
|
|
430
|
-
`,
|
|
431
|
-
${$.specCode}`;case"test":return
|
|
432
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
430
|
+
`,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:
|
|
431
|
+
${$.specCode}`;case"test":return f0($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
432
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as xB}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=xB(A,b)}canHandle($){return!0}async generate($){try{let b=this.buildPrompt($),A=await this.agent.run(b);return{success:!0,code:A.text,metadata:{finishReason:A.finishReason,usage:A.usage}}}catch(b){return{success:!1,errors:[b instanceof Error?b.message:String(b)]}}}async validate($){return this.generate($)}buildPrompt($){let b="";if($.specCode)b+=`Specification:
|
|
433
433
|
${$.specCode}
|
|
434
434
|
|
|
435
|
-
`;if($.existingCode)
|
|
435
|
+
`;if($.existingCode)b+=`Existing Code:
|
|
436
436
|
${$.existingCode}
|
|
437
437
|
|
|
438
|
-
`;switch($.type){case"generate":
|
|
438
|
+
`;switch($.type){case"generate":b+="Generate implementation code based on the specification above.";break;case"validate":b+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":b+="Refactor the existing code to better match the specification and improve quality.";break;case"test":b+="Generate tests for the existing code based on the specification.";break}return b}}class 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(`\u26A0\uFE0F Agent '${b}' not found, using simple agent`)),this.defaultAgent.generate($);if(!A.canHandle($))return console.log(D$.yellow(`\u26A0\uFE0F Agent '${b}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let m=TB(`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:()=>vB,buildPresentationSpecPrompt:()=>FB,buildOperationSpecPrompt:()=>DB,buildEventSpecPrompt:()=>NB,addExampleContext:()=>gB});function DB($,b){return`You are a senior software architect creating a contract specification for an operation.
|
|
439
439
|
|
|
440
|
-
The operation is a ${
|
|
440
|
+
The operation is a ${b} (${b==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
441
441
|
|
|
442
442
|
User description: ${$}
|
|
443
443
|
|
|
@@ -453,7 +453,7 @@ Create a complete contract specification following these guidelines:
|
|
|
453
453
|
8. **Feature Flags**: Any flags that gate this operation
|
|
454
454
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
455
455
|
|
|
456
|
-
Respond with a structured spec.`}function
|
|
456
|
+
Respond with a structured spec.`}function NB($){return`You are a senior software architect creating an event specification.
|
|
457
457
|
|
|
458
458
|
User description: ${$}
|
|
459
459
|
|
|
@@ -467,9 +467,9 @@ Create a complete event specification following these guidelines:
|
|
|
467
467
|
|
|
468
468
|
Events represent things that have already happened and should use past tense.
|
|
469
469
|
|
|
470
|
-
Respond with a structured spec.`}function
|
|
470
|
+
Respond with a structured spec.`}function FB($,b){return`You are a senior software architect creating a presentation specification.
|
|
471
471
|
|
|
472
|
-
This is a ${
|
|
472
|
+
This is a ${b} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[b]}.
|
|
473
473
|
|
|
474
474
|
User description: ${$}
|
|
475
475
|
|
|
@@ -479,13 +479,13 @@ Create a complete presentation specification following these guidelines:
|
|
|
479
479
|
2. **Version**: Start at 1
|
|
480
480
|
3. **Description**: What this presentation shows/provides
|
|
481
481
|
4. **Kind-specific details**:
|
|
482
|
-
${
|
|
482
|
+
${b==="web_component"?`- Component key (symbolic, resolved by host app)
|
|
483
483
|
- Props structure
|
|
484
|
-
- Analytics events to track`:
|
|
484
|
+
- Analytics events to track`:b==="markdown"?`- Content or resource URI
|
|
485
485
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
486
486
|
- Data structure description`}
|
|
487
487
|
|
|
488
|
-
Respond with a structured spec.`}function
|
|
488
|
+
Respond with a structured spec.`}function vB(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
489
489
|
|
|
490
490
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
491
491
|
|
|
@@ -495,111 +495,359 @@ Your specs are:
|
|
|
495
495
|
- Business-oriented (capturing the "why" not just "what")
|
|
496
496
|
- Designed for both humans and AI agents to understand
|
|
497
497
|
|
|
498
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
498
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function gB($,b){if(b.length===0)return $;return`${$}
|
|
499
499
|
|
|
500
500
|
Here are some good examples for reference:
|
|
501
501
|
|
|
502
|
-
${
|
|
502
|
+
${b.join(`
|
|
503
503
|
|
|
504
504
|
`)}
|
|
505
505
|
|
|
506
|
-
Follow this structure and quality level.`}var
|
|
507
|
-
`)}function
|
|
506
|
+
Follow this structure and quality level.`}var xW={};P(xW,{sarifToJson:()=>cB,formatAsTextLines:()=>MW,formatAsText:()=>dB,formatAsSarif:()=>rB,formatAsJson:()=>kB});function kB($,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 PB={"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 rB($,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=PB[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:fB(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:hB(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 fB($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function hB($){let b=[$.ruleId,$.file??"",$.message];return Buffer.from(b.join("|")).toString("base64").slice(0,16)}function cB($){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?"\u2713":"\u2717",B=j.passed?"success":"error",S=uB(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=oB($.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:"\u2500".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:"\u2705 All CI checks passed!",style:"success"});else A.push({text:"\u274C CI checks failed",style:"error"});return A.push({text:"",style:"normal"}),A}function dB($,b={}){return MW($,b).map((m)=>" ".repeat(m.indent??0)+m.text).join(`
|
|
507
|
+
`)}function uB($){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"?"\u2717":$.severity==="warning"?"\u26A0":"\u25CB",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 oB($){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 iB}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as lB}from"@contractspec/lib.contracts-spec/operations/report";function tB(){let $=new iB;return lB($),$}var vY=tB();class pB{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 aB($){if(!$)return"\u2014";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 eB{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)}
|
|
508
508
|
|
|
509
|
-
*(output truncated)*`},
|
|
510
|
-
`)},
|
|
509
|
+
*(output truncated)*`},m=(y)=>{if(!y||y.length===0)return"- None";return y.slice(0,20).map((B)=>`- ${B}`).join(`
|
|
510
|
+
`)},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??"\u2014",S=aB(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(`
|
|
511
511
|
`)}
|
|
512
|
-
`}}import{AGENT_SYSTEM_PROMPTS as FQ}from"@contractspec/lib.contracts-spec/llm";class u0{agentType="claude-code";formatPlan($){let W=[];if(W.push(`# Implement: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files to Create/Modify"),W.push("");for(let j of $.fileStructure){let A=j.type==="create"?"\uD83D\uDCDD":"\u270F\uFE0F";W.push(`${A} \`${j.path}\``),W.push(` ${j.purpose}`),W.push("")}}W.push("## Implementation Steps"),W.push("");for(let j of $.steps){W.push(`### ${j.order}. ${j.title}`),W.push(""),W.push(j.description),W.push(""),W.push("**Acceptance Criteria:**");for(let A of j.acceptanceCriteria)W.push(`- [ ] ${A}`);W.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("### Policy");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("### Security");for(let j of $.constraints.security)W.push(`- \u26A0\uFE0F ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("### PII Handling"),W.push("The following fields contain personally identifiable information:");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}}W.push("## Verification Checklist"),W.push(""),W.push("Before submitting, verify:");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),W.push("## Instructions"),W.push(""),W.push("1. Implement each step in order"),W.push("2. Use TypeScript with strict typing (no `any`)"),W.push("3. Include JSDoc comments for public APIs"),W.push("4. Handle all error cases defined in the spec"),W.push("5. Emit events as specified"),W.push("6. Mark checklist items as you complete them"),W.push(""),{agent:"claude-code",systemPrompt:FQ["claude-code"],taskPrompt:W.join(`
|
|
513
|
-
`)}}
|
|
514
|
-
`)}
|
|
515
|
-
`)}
|
|
516
|
-
`)}
|
|
517
|
-
`)}}
|
|
518
|
-
`)}
|
|
512
|
+
`}}var s0={};P(s0,{uniqueTokens:()=>N$,tokenize:()=>i$,syncAdoptionCatalog:()=>J5,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 sB=[...vW,...TW,...DW,...NW,...FW];function QA(){return[...sB].sort(($,b)=>b.resolutionPriority-$.resolutionPriority)}function i0($=new Date){return{version:1,generatedAt:$.toISOString(),entries:QA()}}import{DEFAULT_CONTRACTSRC as y5}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 $5}from"path";import{ContractsrcSchema as b5,DEFAULT_CONTRACTSRC as t0}from"@contractspec/lib.contracts-spec/workspace-config";async function l$($,b={}){let A=$5(b.cwd??process.cwd()),m=b.workspaceRoot??M(A),n=b.packageRoot??r(A),W=b.config?PW(t0,b.config):await A5($,m,n);return{adoption:W.connect?.adoption??t0.connect.adoption,config:W,cwd:A,packageRoot:n,workspaceRoot:m}}async function A5($,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=b5.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 m5=["package.json","packages/*/package.json"];async function p0($,b){let[A,m]=await Promise.all([n5($,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 n5($,b){let A=await $.glob({patterns:m5,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:j5(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:w5(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 w5($,b){return $==="ui"&&/\/components\//.test(b)?180:140}function j5($){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=q5(b),n=N$([m,b.symbol??"",...b.paths??[]]),W=await p0($.fs,A),w=await O5($,A),j=await a0($.fs,A),y=B5(A,n,b,[...W.packageCandidates,...W.fileCandidates,...w,...V5(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=X5(A,B,S,b.currentTarget);return{ambiguous:S,candidates:y,currentTarget:b.currentTarget,exhausted:B?.candidate.source==="ecosystem",family:b.family,query:m,reason:H5(B,S),selected:B,verdict:Q}}function B5($,b,A,m){return m.filter((n)=>n.family===A.family&&Z5($,n.family)).filter((n)=>G5(n,A.platform)).map((n)=>S5(n,b,A.paths)).filter((n)=>n.score>40).sort((n,W)=>W.score-n.score).slice(0,8)}function S5($,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:Q5($.source)+($.resolutionPriority??0)+w+j}}function Q5($){if($==="workspace")return 300;if($==="contractspec")return 200;return 100}function Z5($,b){return $.adoption.families?.[b]??!0}function G5($,b){return!b||!("platforms"in $)||!$.platforms||$.platforms.includes(b)}function X5($,b,A,m){let n=$.adoption.thresholds??y5.connect.adoption.thresholds;if(A)return n.ambiguous??"require_review";if(!b)return n.newImplementation??"require_review";if(b.candidate.source==="workspace")return Y5(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 Y5($,b){return Boolean(b&&"filePath"in $&&$.filePath&&$.filePath===b)}function H5($,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 q5($){if($.query?.trim())return $.query.trim();if($.symbol?.trim())return $.symbol.trim();if($.paths?.length)return $.paths.join(" ");return $.family}async function O5($,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 V5($,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 J5($,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)}
|
|
513
|
+
`),{catalog:m,catalogPath:n}}import{AGENT_SYSTEM_PROMPTS as K5}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":"\u270F\uFE0F";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(`- \u26A0\uFE0F ${A}`);b.push("")}if($.constraints.pii.length>0){b.push("### PII Handling"),b.push("The following fields contain personally identifiable information:");for(let A of $.constraints.pii)b.push(`- \`${A}\``);b.push("")}}b.push("## Verification Checklist"),b.push(""),b.push("Before submitting, verify:");for(let A of $.verificationChecklist)b.push(`- [ ] ${A}`);return b.push(""),b.push("## Instructions"),b.push(""),b.push("1. Implement each step in order"),b.push("2. Use TypeScript with strict typing (no `any`)"),b.push("3. Include JSDoc comments for public APIs"),b.push("4. Handle all error cases defined in the spec"),b.push("5. Emit events as specified"),b.push("6. Mark checklist items as you complete them"),b.push(""),{agent:"claude-code",systemPrompt:K5["claude-code"],taskPrompt:b.join(`
|
|
514
|
+
`)}}generateConfig($){let b=[];return b.push("# ContractSpec Implementation Context"),b.push(""),b.push("This codebase uses ContractSpec for spec-first development."),b.push(""),b.push("## Spec Details"),b.push(""),b.push(`- **Name:** ${$.meta.key}`),b.push(`- **Version:** ${$.meta.version}`),b.push(`- **Kind:** ${$.meta.kind}`),b.push(`- **Stability:** ${$.meta.stability}`),b.push(""),b.push("## Implementation Requirements"),b.push(""),b.push("1. Match input/output types exactly"),b.push("2. Handle all defined error cases"),b.push("3. Emit events as specified"),b.push("4. Respect policy constraints"),b.push(""),b.join(`
|
|
515
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};let 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 _5}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)=>`\u26A0\uFE0F ${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:_5["cursor-cli"],taskPrompt:b.join(`
|
|
516
|
+
`)}}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(`
|
|
517
|
+
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};return{code:$}}}var HA=new YA;import{AGENT_SYSTEM_PROMPTS as U5}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:U5["generic-mcp"],taskPrompt:b.join(`
|
|
518
|
+
`)}}formatAsResource($){return{uri:`spec://${$.target.key}/v${$.target.version}/plan`,mimeType:"application/json",data:JSON.stringify({target:$.target,context:$.context,fileStructure:$.fileStructure,steps:$.steps,constraints:$.constraints,verificationChecklist:$.verificationChecklist},null,2)}}formatAsPromptMessage($){return{role:"user",content:{type:"text",text:this.formatPlan($).taskPrompt}}}generateConfig($){let b=$.meta,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(`
|
|
519
|
+
`)}parseOutput($){let b=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(b?.[1])return{code:b[1]};try{let 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 z5,operationSpecToFullMarkdown as L5}from"@contractspec/lib.contracts-spec/llm";var R5={defaultAgent:"generic-mcp",verbose:!1};class VA{config;constructor($={}){this.config={...R5,...$}}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=L5($);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 z5($,{taskType:A,existingCode:m})}listAgentTypes(){return bm()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function C5($){return new VA($)}var I5=new VA;import{detectAuthoringTarget as J8,generateComponentTemplate as K8,generateHandlerTemplate as _8,generateTestTemplate as U8,getAuthoringTargetDefinition as z8,inferSpecTypeFromFilePath as L8,scanSpecSource as R8}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';
|
|
520
|
+
|
|
521
|
+
export const ${a$($.key)}Capability = defineCapability({
|
|
522
|
+
meta: {
|
|
523
|
+
key: '${$.key}',
|
|
524
|
+
version: '${$.version}',
|
|
525
|
+
kind: '${$.kind??"api"}',
|
|
526
|
+
title: '${k(p$($))}',
|
|
527
|
+
description: '${k($.description)}',
|
|
528
|
+
domain: '${k(F$($))}',
|
|
529
|
+
owners: [${W$($.owners)}],
|
|
530
|
+
tags: [${W$($.tags)}],
|
|
531
|
+
stability: '${$.stability}',
|
|
532
|
+
},
|
|
533
|
+
provides: [],
|
|
534
|
+
requires: [],
|
|
535
|
+
});
|
|
536
|
+
`}function hW($){return`import { definePolicy } from '@contractspec/lib.contracts-spec/policy';
|
|
537
|
+
|
|
538
|
+
export const ${a$($.key)}Policy = definePolicy({
|
|
539
|
+
meta: {
|
|
540
|
+
key: '${$.key}',
|
|
541
|
+
version: '${$.version}',
|
|
542
|
+
title: '${k(p$($))}',
|
|
543
|
+
description: '${k($.description)}',
|
|
544
|
+
domain: '${k(F$($))}',
|
|
545
|
+
owners: [${W$($.owners)}],
|
|
546
|
+
tags: [${W$($.tags)}],
|
|
547
|
+
stability: '${$.stability}',
|
|
548
|
+
scope: '${$.scope??"feature"}',
|
|
549
|
+
},
|
|
550
|
+
rules: [
|
|
551
|
+
{
|
|
552
|
+
effect: 'allow',
|
|
553
|
+
actions: ['read'],
|
|
554
|
+
resource: { type: '${k(F$($))}' },
|
|
555
|
+
reason: 'TODO: replace with real access rules',
|
|
556
|
+
},
|
|
557
|
+
],
|
|
558
|
+
});
|
|
559
|
+
`}function cW($){let b=$.targetVersion??"1.0.0",A=`{ key: '${$.targetKey}', version: '${b}' }`;return`import { defineTestSpec } from '@contractspec/lib.contracts-spec/tests';
|
|
560
|
+
|
|
561
|
+
export const ${a$($.key)}TestSpec = defineTestSpec({
|
|
562
|
+
meta: {
|
|
563
|
+
key: '${$.key}',
|
|
564
|
+
version: '${$.version}',
|
|
565
|
+
title: '${k(p$($))}',
|
|
566
|
+
description: '${k($.description)}',
|
|
567
|
+
domain: '${k(F$($))}',
|
|
568
|
+
owners: [${W$($.owners)}],
|
|
569
|
+
tags: [${W$($.tags)}],
|
|
570
|
+
stability: '${$.stability}',
|
|
571
|
+
},
|
|
572
|
+
target: {
|
|
573
|
+
type: '${$.targetType}',
|
|
574
|
+
${$.targetType}: ${A},
|
|
575
|
+
},
|
|
576
|
+
scenarios: [
|
|
577
|
+
{
|
|
578
|
+
key: 'success',
|
|
579
|
+
when: { ${$.targetType}: { key: '${$.targetKey}' } },
|
|
580
|
+
then: [{ type: 'expectOutput', match: {} }],
|
|
581
|
+
},
|
|
582
|
+
],
|
|
583
|
+
});
|
|
584
|
+
`}function dW($){return`import { defineTranslation } from '@contractspec/lib.contracts-spec/translations';
|
|
585
|
+
|
|
586
|
+
export const ${a$(`${$.key}.${$.locale}`)}Translation = defineTranslation({
|
|
587
|
+
meta: {
|
|
588
|
+
key: '${$.key}',
|
|
589
|
+
version: '${$.version}',
|
|
590
|
+
domain: '${k(F$($))}',
|
|
591
|
+
description: '${k($.description)}',
|
|
592
|
+
owners: [${W$($.owners)}],
|
|
593
|
+
tags: [${W$($.tags)}],
|
|
594
|
+
stability: '${$.stability}',
|
|
595
|
+
},
|
|
596
|
+
locale: '${$.locale}',
|
|
597
|
+
fallback: '${$.fallback??$.locale}',
|
|
598
|
+
messages: {
|
|
599
|
+
'${$.key}.title': {
|
|
600
|
+
value: '${k(p$($))}',
|
|
601
|
+
description: 'TODO: replace with a real localized message',
|
|
602
|
+
},
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
`}function uW($){return`import { defineJob } from '@contractspec/lib.contracts-spec/jobs';
|
|
606
|
+
|
|
607
|
+
export const ${a$($.key)}Job = defineJob({
|
|
608
|
+
meta: {
|
|
609
|
+
key: '${$.key}',
|
|
610
|
+
version: '${$.version}',
|
|
611
|
+
title: '${k(p$($))}',
|
|
612
|
+
description: '${k($.description)}',
|
|
613
|
+
domain: '${k(F$($))}',
|
|
614
|
+
owners: [${W$($.owners)}],
|
|
615
|
+
tags: [${W$($.tags)}],
|
|
616
|
+
stability: '${$.stability}',
|
|
617
|
+
},
|
|
618
|
+
payload: { schema: {} },
|
|
619
|
+
schedule: { intervalMs: ${$.intervalMs??60000} },
|
|
620
|
+
});
|
|
621
|
+
`}function oW($){return`import { defineVisualization } from '@contractspec/lib.contracts-spec/visualizations';
|
|
622
|
+
|
|
623
|
+
export const ${a$($.key)}Visualization = defineVisualization({
|
|
624
|
+
meta: {
|
|
625
|
+
key: '${$.key}',
|
|
626
|
+
version: '${$.version}',
|
|
627
|
+
title: '${k(p$($))}',
|
|
628
|
+
description: '${k($.description)}',
|
|
629
|
+
goal: 'TODO: describe the decision this visualization supports',
|
|
630
|
+
context: 'TODO: describe where this visualization appears',
|
|
631
|
+
domain: '${k(F$($))}',
|
|
632
|
+
owners: [${W$($.owners)}],
|
|
633
|
+
tags: [${W$($.tags)}],
|
|
634
|
+
stability: '${$.stability}',
|
|
635
|
+
},
|
|
636
|
+
source: {
|
|
637
|
+
primary: {
|
|
638
|
+
key: '${$.sourceOperationKey}',
|
|
639
|
+
version: '${$.sourceOperationVersion??"1.0.0"}',
|
|
640
|
+
},
|
|
641
|
+
resultPath: 'data',
|
|
642
|
+
},
|
|
643
|
+
visualization: {
|
|
644
|
+
kind: 'metric',
|
|
645
|
+
measures: [{ key: 'value', label: 'Value', dataPath: 'value', format: 'number' }],
|
|
646
|
+
measure: 'value',
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
`}function p$($){return $.title??E5($.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 E5($){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.${x5($.key.split(".").at(-1)??$.key)}`;return`import { defineExample } from '@contractspec/lib.contracts-spec/examples';
|
|
650
|
+
|
|
651
|
+
export const ${Hb($.key)}Example = defineExample({
|
|
652
|
+
meta: {
|
|
653
|
+
key: '${$.key}',
|
|
654
|
+
version: '${$.version}',
|
|
655
|
+
title: '${i(JA($))}',
|
|
656
|
+
description: '${i($.description)}',
|
|
657
|
+
kind: 'template',
|
|
658
|
+
visibility: 'experimental',
|
|
659
|
+
stability: '${$.stability}',
|
|
660
|
+
owners: [${B$($.owners)}],
|
|
661
|
+
tags: [${B$($.tags)}],
|
|
662
|
+
},
|
|
663
|
+
surfaces: {
|
|
664
|
+
templates: true,
|
|
665
|
+
sandbox: { enabled: true, modes: ['playground', 'specs'] },
|
|
666
|
+
studio: { enabled: false, installable: false },
|
|
667
|
+
mcp: { enabled: false },
|
|
668
|
+
},
|
|
669
|
+
entrypoints: {
|
|
670
|
+
packageName: '${b}',
|
|
671
|
+
},
|
|
672
|
+
});
|
|
673
|
+
`}function lW($){return`import { defineAgent } from '@contractspec/lib.contracts-spec/agent';
|
|
674
|
+
|
|
675
|
+
export const ${Hb($.key)}Agent = defineAgent({
|
|
676
|
+
meta: {
|
|
677
|
+
key: '${$.key}',
|
|
678
|
+
version: '${$.version}',
|
|
679
|
+
description: '${i($.description)}',
|
|
680
|
+
owners: [${B$($.owners)}],
|
|
681
|
+
tags: [${B$($.tags)}],
|
|
682
|
+
stability: '${$.stability}',
|
|
683
|
+
},
|
|
684
|
+
instructions: '${i($.instructions)}',
|
|
685
|
+
tools: [{ name: 'todo' }],
|
|
686
|
+
});
|
|
687
|
+
`}function tW($){return`import { defineProductIntentSpec } from '@contractspec/lib.contracts-spec/product-intent';
|
|
688
|
+
|
|
689
|
+
export const ${Hb($.key)}ProductIntent = defineProductIntentSpec({
|
|
690
|
+
id: '${$.id??`${$.key}-run`}',
|
|
691
|
+
meta: {
|
|
692
|
+
key: '${$.key}',
|
|
693
|
+
version: '${$.version}',
|
|
694
|
+
title: '${i(JA($))}',
|
|
695
|
+
description: '${i($.description)}',
|
|
696
|
+
goal: 'TODO: capture the desired product outcome',
|
|
697
|
+
context: 'TODO: capture the decision context',
|
|
698
|
+
stability: '${$.stability}',
|
|
699
|
+
owners: [${B$($.owners)}],
|
|
700
|
+
tags: [${B$($.tags)}],
|
|
701
|
+
},
|
|
702
|
+
question: '${i($.question)}',
|
|
703
|
+
insights: { insights: [] },
|
|
704
|
+
});
|
|
705
|
+
`}function pW($){return`import { defineHarnessScenario } from '@contractspec/lib.contracts-spec/harness';
|
|
706
|
+
|
|
707
|
+
export const ${Hb($.key)}HarnessScenario = defineHarnessScenario({
|
|
708
|
+
meta: {
|
|
709
|
+
key: '${$.key}',
|
|
710
|
+
version: '${$.version}',
|
|
711
|
+
title: '${i(JA($))}',
|
|
712
|
+
description: '${i($.description)}',
|
|
713
|
+
domain: '${i(eW($))}',
|
|
714
|
+
owners: [${B$($.owners)}],
|
|
715
|
+
tags: [${B$($.tags)}],
|
|
716
|
+
stability: '${$.stability}',
|
|
717
|
+
},
|
|
718
|
+
target: {
|
|
719
|
+
isolation: 'preview',
|
|
720
|
+
preferredTargets: ['preview'],
|
|
721
|
+
},
|
|
722
|
+
allowedModes: ['deterministic-browser'],
|
|
723
|
+
steps: [
|
|
724
|
+
{
|
|
725
|
+
key: 'open-home',
|
|
726
|
+
description: 'Open the target application',
|
|
727
|
+
actionClass: 'navigate',
|
|
728
|
+
intent: 'Navigate to the primary page under test.',
|
|
729
|
+
},
|
|
730
|
+
],
|
|
731
|
+
assertions: [
|
|
732
|
+
{
|
|
733
|
+
key: 'step-completes',
|
|
734
|
+
type: 'step-status',
|
|
735
|
+
description: 'TODO: replace with a real scenario assertion',
|
|
736
|
+
match: 'completed',
|
|
737
|
+
},
|
|
738
|
+
],
|
|
739
|
+
});
|
|
740
|
+
`}function aW($){return`import { defineHarnessSuite } from '@contractspec/lib.contracts-spec/harness';
|
|
741
|
+
|
|
742
|
+
export const ${Hb($.key)}HarnessSuite = defineHarnessSuite({
|
|
743
|
+
meta: {
|
|
744
|
+
key: '${$.key}',
|
|
745
|
+
version: '${$.version}',
|
|
746
|
+
title: '${i(JA($))}',
|
|
747
|
+
description: '${i($.description)}',
|
|
748
|
+
domain: '${i(eW($))}',
|
|
749
|
+
owners: [${B$($.owners)}],
|
|
750
|
+
tags: [${B$($.tags)}],
|
|
751
|
+
stability: '${$.stability}',
|
|
752
|
+
},
|
|
753
|
+
scenarios: [
|
|
754
|
+
{
|
|
755
|
+
scenario: {
|
|
756
|
+
key: '${$.scenarioKey}',
|
|
757
|
+
version: '${$.scenarioVersion??"1.0.0"}',
|
|
758
|
+
},
|
|
759
|
+
required: true,
|
|
760
|
+
weight: 1,
|
|
761
|
+
},
|
|
762
|
+
],
|
|
763
|
+
summary: '${i($.description)}',
|
|
764
|
+
tags: [${B$($.tags)}],
|
|
765
|
+
});
|
|
766
|
+
`}function JA($){return $.title??M5($.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 M5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join(" ")}function x5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function i($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Aw($){let b=r5($.key.split(".").pop()??"App")+"AppConfig",A=T5($),m=D5($),n=sW("dataViews",$.dataViews),W=sW("workflows",$.workflows),w=N5($),j=F5($),y=v5($),B=g5($),S=k5($),Q=P5($),Z=$.notes?` notes: '${D($.notes)}',
|
|
519
767
|
`:"";return`import type { AppBlueprintSpec } from '@contractspec/lib.contracts-spec/app-config';
|
|
520
768
|
|
|
521
|
-
export const ${
|
|
769
|
+
export const ${b}: AppBlueprintSpec = {
|
|
522
770
|
meta: {
|
|
523
|
-
key: '${
|
|
524
|
-
version: ${$.version},
|
|
525
|
-
title: '${
|
|
526
|
-
description: '${
|
|
527
|
-
domain: '${
|
|
528
|
-
owners: [${$.owners.map((
|
|
529
|
-
tags: [${$.tags.map((
|
|
771
|
+
key: '${D($.key)}',
|
|
772
|
+
version: '${$.version}',
|
|
773
|
+
title: '${D($.title)}',
|
|
774
|
+
description: '${D($.description)}',
|
|
775
|
+
domain: '${D($.domain)}',
|
|
776
|
+
owners: [${$.owners.map((G)=>`'${D(G)}'`).join(", ")}],
|
|
777
|
+
tags: [${$.tags.map((G)=>`'${D(G)}'`).join(", ")}],
|
|
530
778
|
stability: '${$.stability}',
|
|
531
|
-
appId: '${
|
|
779
|
+
appId: '${D($.appId)}',
|
|
532
780
|
},
|
|
533
|
-
${
|
|
534
|
-
`}function
|
|
535
|
-
`:"",
|
|
781
|
+
${A}${m}${n}${W}${w}${j}${y}${B}${S}${Q}${Z}};
|
|
782
|
+
`}function T5($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let b=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((m)=>$w(m)).join(", ")}],
|
|
783
|
+
`:"",A=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((m)=>$w(m)).join(", ")}],
|
|
536
784
|
`:"";return` capabilities: {
|
|
537
|
-
${
|
|
538
|
-
`}function
|
|
539
|
-
`:"",
|
|
785
|
+
${b}${A} },
|
|
786
|
+
`}function D5($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let b=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((m)=>`{ key: '${D(m)}' }`).join(", ")}],
|
|
787
|
+
`:"",A=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((m)=>`{ key: '${D(m)}' }`).join(", ")}],
|
|
540
788
|
`:"";return` features: {
|
|
541
|
-
${
|
|
542
|
-
`}function
|
|
543
|
-
|
|
544
|
-
|
|
789
|
+
${b}${A} },
|
|
790
|
+
`}function sW($,b){if(b.length===0)return"";let A=b.map((m)=>` ${m.slot}: {
|
|
791
|
+
key: '${D(m.key)}'${m.version?`,
|
|
792
|
+
version: '${m.version}'`:""}
|
|
545
793
|
}`).join(`,
|
|
546
794
|
`);return` ${$}: {
|
|
547
|
-
${
|
|
795
|
+
${A}
|
|
548
796
|
},
|
|
549
|
-
`}function
|
|
550
|
-
${$.policyRefs.map((
|
|
551
|
-
|
|
552
|
-
version: '${
|
|
797
|
+
`}function N5($){if($.policyRefs.length===0)return"";return` policies: [
|
|
798
|
+
${$.policyRefs.map((A)=>` {
|
|
799
|
+
key: '${D(A.key)}'${A.version?`,
|
|
800
|
+
version: '${A.version}'`:""}
|
|
553
801
|
}`).join(`,
|
|
554
802
|
`)}
|
|
555
803
|
],
|
|
556
|
-
`}function
|
|
557
|
-
`,
|
|
804
|
+
`}function F5($){if(!$.theme)return"";let b=` primary: { key: '${D($.theme.key)}', version: '${$.theme.version}' },
|
|
805
|
+
`,A=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((m)=>`{ key: '${D(m.key)}', version: '${m.version}' }`).join(", ")}],
|
|
558
806
|
`:"";return` theme: {
|
|
559
|
-
${
|
|
560
|
-
`}function
|
|
807
|
+
${b}${A} },
|
|
808
|
+
`}function v5($){if(!$.telemetry)return"";return` telemetry: {
|
|
561
809
|
spec: {
|
|
562
|
-
|
|
810
|
+
key: '${D($.telemetry.key)}'${$.telemetry.version?`,
|
|
563
811
|
version: '${$.telemetry.version}'`:""}
|
|
564
812
|
},
|
|
565
813
|
},
|
|
566
|
-
`}function
|
|
567
|
-
`:"",
|
|
814
|
+
`}function g5($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let b=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((m)=>bw(m)).join(", ")}],
|
|
815
|
+
`:"",A=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((m)=>bw(m)).join(", ")}],
|
|
568
816
|
`:"";return` experiments: {
|
|
569
|
-
${
|
|
570
|
-
`}function
|
|
571
|
-
${$.featureFlags.map((
|
|
572
|
-
key: '${
|
|
573
|
-
enabled: ${
|
|
574
|
-
${
|
|
575
|
-
${
|
|
817
|
+
${b}${A} },
|
|
818
|
+
`}function k5($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
819
|
+
${$.featureFlags.map((A)=>` {
|
|
820
|
+
key: '${D(A.key)}',
|
|
821
|
+
enabled: ${A.enabled},
|
|
822
|
+
${A.variant?`variant: '${D(A.variant)}',`:""}
|
|
823
|
+
${A.description?`description: '${D(A.description)}',`:""}
|
|
576
824
|
}`).join(`,
|
|
577
825
|
`)}
|
|
578
826
|
],
|
|
579
|
-
`}function
|
|
580
|
-
${$.routes.map((
|
|
827
|
+
`}function P5($){if($.routes.length===0)return"";return` routes: [
|
|
828
|
+
${$.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(`,
|
|
581
829
|
`)}
|
|
582
830
|
],
|
|
583
|
-
`}function
|
|
584
|
-
key: '${
|
|
585
|
-
label: '${
|
|
586
|
-
dataPath: '${
|
|
587
|
-
${
|
|
588
|
-
${
|
|
589
|
-
${
|
|
831
|
+
`}function $w($){return`{ key: '${D($)}' }`}function bw($){let b=$.version?`, version: '${$.version}'`:"";return`{ key: '${D($.key)}'${b} }`}function r5($){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=f5($.name.split(".").pop()??"DataView")+"DataView",A=$.fields.map((W)=>` {
|
|
832
|
+
key: '${W.key}',
|
|
833
|
+
label: '${KA(W.label)}',
|
|
834
|
+
dataPath: '${W.dataPath}',
|
|
835
|
+
${W.format?`format: '${W.format}',`:""}
|
|
836
|
+
${W.sortable?"sortable: true,":""}
|
|
837
|
+
${W.filterable?"filterable: true,":""}
|
|
590
838
|
}`).join(`,
|
|
591
|
-
`),
|
|
839
|
+
`),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';
|
|
592
840
|
|
|
593
|
-
export const ${
|
|
841
|
+
export const ${b}: DataViewSpec = {
|
|
594
842
|
meta: {
|
|
595
843
|
key: '${$.name}',
|
|
596
844
|
version: ${$.version},
|
|
597
845
|
entity: '${$.entity}',
|
|
598
|
-
title: '${
|
|
599
|
-
description: '${
|
|
600
|
-
domain: '${
|
|
601
|
-
owners: [${$.owners.map((
|
|
602
|
-
tags: [${$.tags.map((
|
|
846
|
+
title: '${KA($.title)}',
|
|
847
|
+
description: '${KA($.description||"Describe the purpose of this data view.")}',
|
|
848
|
+
domain: '${KA($.domain||$.entity)}',
|
|
849
|
+
owners: [${$.owners.map((W)=>`'${W}'`).join(", ")}],
|
|
850
|
+
tags: [${$.tags.map((W)=>`'${W}'`).join(", ")}],
|
|
603
851
|
stability: '${$.stability}',
|
|
604
852
|
},
|
|
605
853
|
source: {
|
|
@@ -607,7 +855,7 @@ export const ${W}: DataViewSpec = {
|
|
|
607
855
|
name: '${$.primaryOperation.name}',
|
|
608
856
|
version: ${$.primaryOperation.version},
|
|
609
857
|
},
|
|
610
|
-
${
|
|
858
|
+
${n}
|
|
611
859
|
refreshEvents: [
|
|
612
860
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
613
861
|
],
|
|
@@ -615,10 +863,10 @@ export const ${W}: DataViewSpec = {
|
|
|
615
863
|
view: {
|
|
616
864
|
kind: '${$.kind}',
|
|
617
865
|
fields: [
|
|
618
|
-
${
|
|
866
|
+
${A}
|
|
619
867
|
],
|
|
620
868
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
621
|
-
${
|
|
869
|
+
${m}
|
|
622
870
|
filters: [
|
|
623
871
|
// Example filter:
|
|
624
872
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -633,13 +881,13 @@ ${j}
|
|
|
633
881
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
634
882
|
},
|
|
635
883
|
};
|
|
636
|
-
`}function
|
|
884
|
+
`}function f5($){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';
|
|
637
885
|
|
|
638
886
|
import * as React from 'react';
|
|
639
887
|
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
640
|
-
import { ${$} } from '${
|
|
888
|
+
import { ${$} } from '${b}';
|
|
641
889
|
|
|
642
|
-
export interface ${
|
|
890
|
+
export interface ${A}Props {
|
|
643
891
|
items?: Record<string, unknown>[];
|
|
644
892
|
item?: Record<string, unknown> | null;
|
|
645
893
|
className?: string;
|
|
@@ -649,17 +897,17 @@ export interface ${j}Props {
|
|
|
649
897
|
}
|
|
650
898
|
|
|
651
899
|
/**
|
|
652
|
-
* Auto-generated renderer for the "${
|
|
900
|
+
* Auto-generated renderer for the "${m}" data view.
|
|
653
901
|
* Customize as needed for app-specific behaviour.
|
|
654
902
|
*/
|
|
655
|
-
export function ${
|
|
903
|
+
export function ${A}({
|
|
656
904
|
items = [],
|
|
657
905
|
item = null,
|
|
658
906
|
className,
|
|
659
907
|
renderActions,
|
|
660
908
|
onSelect,
|
|
661
909
|
onRowClick,
|
|
662
|
-
}: ${
|
|
910
|
+
}: ${A}Props) {
|
|
663
911
|
return (
|
|
664
912
|
<DataViewRenderer
|
|
665
913
|
spec={${$}}
|
|
@@ -672,93 +920,93 @@ export function ${j}({
|
|
|
672
920
|
/>
|
|
673
921
|
);
|
|
674
922
|
}
|
|
675
|
-
`}function
|
|
923
|
+
`}function nw($){let{name:b,version:A,description:m,stability:n,owners:W,tags:w,piiFields:j}=$,y=h5(b.replace(/\./g,"_"))+"V"+A,B=y+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
676
924
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
677
925
|
|
|
678
926
|
// TODO: Define event payload schema
|
|
679
|
-
export const ${
|
|
680
|
-
name: '${
|
|
681
|
-
description: 'Payload for ${
|
|
927
|
+
export const ${B} = new SchemaModel({
|
|
928
|
+
name: '${B}',
|
|
929
|
+
description: 'Payload for ${b}',
|
|
682
930
|
fields: {
|
|
683
931
|
// Add your payload fields here
|
|
684
932
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
685
933
|
},
|
|
686
934
|
});
|
|
687
935
|
|
|
688
|
-
export const ${
|
|
689
|
-
name: '${
|
|
690
|
-
name: '${
|
|
691
|
-
version: '${
|
|
692
|
-
description: '${
|
|
693
|
-
description: '${
|
|
694
|
-
stability: '${
|
|
695
|
-
owners: [${
|
|
696
|
-
tags: [${
|
|
697
|
-
${
|
|
698
|
-
payload: ${
|
|
936
|
+
export const ${y} = defineEvent({
|
|
937
|
+
name: '${b}',
|
|
938
|
+
name: '${b}',
|
|
939
|
+
version: '${A}',
|
|
940
|
+
description: '${m}',
|
|
941
|
+
description: '${m}',
|
|
942
|
+
stability: '${n}',
|
|
943
|
+
owners: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
944
|
+
tags: [${w.map((S)=>`'${S}'`).join(", ")}],
|
|
945
|
+
${j.length>0?`pii: [${j.map((S)=>`'${S}'`).join(", ")}],`:"// pii: [],"}
|
|
946
|
+
payload: ${B},
|
|
699
947
|
});
|
|
700
|
-
`}function
|
|
701
|
-
${
|
|
702
|
-
type: '${
|
|
703
|
-
target: '${
|
|
704
|
-
${typeof
|
|
948
|
+
`}function h5($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ww($){let b=d5($.name.split(".").pop()??"Experiment")+"Experiment",A=$.variants.map((W)=>{let w=W.overrides?.length?` overrides: [
|
|
949
|
+
${W.overrides.map((j)=>` {
|
|
950
|
+
type: '${j.type}',
|
|
951
|
+
target: '${f(j.target)}',
|
|
952
|
+
${typeof j.version==="string"?`version: ${j.version},`:""}
|
|
705
953
|
}`).join(`,
|
|
706
954
|
`)}
|
|
707
955
|
],`:"";return` {
|
|
708
|
-
id: '${
|
|
709
|
-
name: '${
|
|
710
|
-
${
|
|
711
|
-
${typeof
|
|
712
|
-
${
|
|
956
|
+
id: '${f(W.id)}',
|
|
957
|
+
name: '${f(W.name)}',
|
|
958
|
+
${W.description?`description: '${f(W.description)}',`:""}
|
|
959
|
+
${typeof W.weight==="number"?`weight: ${W.weight},`:""}
|
|
960
|
+
${w}
|
|
713
961
|
}`}).join(`,
|
|
714
|
-
`),
|
|
715
|
-
${$.successMetrics.map((
|
|
716
|
-
name: '${
|
|
717
|
-
telemetryEvent: { name: '${
|
|
718
|
-
aggregation: '${
|
|
719
|
-
${typeof
|
|
962
|
+
`),m=c5($.allocation),n=$.successMetrics?.length?` successMetrics: [
|
|
963
|
+
${$.successMetrics.map((W)=>` {
|
|
964
|
+
name: '${f(W.name)}',
|
|
965
|
+
telemetryEvent: { name: '${f(W.eventName)}', version: ${typeof W.eventVersion==="string"?`'${W.eventVersion}'`:W.eventVersion} },
|
|
966
|
+
aggregation: '${W.aggregation}',
|
|
967
|
+
${typeof W.target==="number"?`target: ${W.target},`:""}
|
|
720
968
|
}`).join(`,
|
|
721
969
|
`)}
|
|
722
970
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
723
971
|
|
|
724
|
-
export const ${
|
|
972
|
+
export const ${b}: ExperimentSpec = {
|
|
725
973
|
meta: {
|
|
726
|
-
key: '${
|
|
974
|
+
key: '${f($.name)}',
|
|
727
975
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
728
|
-
title: '${
|
|
729
|
-
description: '${
|
|
730
|
-
domain: '${
|
|
731
|
-
owners: [${$.owners.map((
|
|
732
|
-
tags: [${$.tags.map((
|
|
976
|
+
title: '${f($.name)} experiment',
|
|
977
|
+
description: '${f($.description||"Describe the experiment goal.")}',
|
|
978
|
+
domain: '${f($.domain)}',
|
|
979
|
+
owners: [${$.owners.map((W)=>`'${f(W)}'`).join(", ")}],
|
|
980
|
+
tags: [${$.tags.map((W)=>`'${f(W)}'`).join(", ")}],
|
|
733
981
|
stability: '${$.stability}',
|
|
734
982
|
},
|
|
735
|
-
controlVariant: '${
|
|
983
|
+
controlVariant: '${f($.controlVariant)}',
|
|
736
984
|
variants: [
|
|
737
|
-
${
|
|
985
|
+
${A}
|
|
738
986
|
],
|
|
739
|
-
allocation: ${
|
|
740
|
-
${
|
|
987
|
+
allocation: ${m},
|
|
988
|
+
${n}
|
|
741
989
|
};
|
|
742
|
-
`}function
|
|
990
|
+
`}function c5($){switch($.type){case"random":return`{
|
|
743
991
|
type: 'random',
|
|
744
|
-
${$.salt?`salt: '${
|
|
992
|
+
${$.salt?`salt: '${f($.salt)}',`:""}
|
|
745
993
|
}`;case"sticky":return`{
|
|
746
994
|
type: 'sticky',
|
|
747
995
|
attribute: '${$.attribute}',
|
|
748
|
-
${$.salt?`salt: '${
|
|
996
|
+
${$.salt?`salt: '${f($.salt)}',`:""}
|
|
749
997
|
}`;case"targeted":return`{
|
|
750
998
|
type: 'targeted',
|
|
751
999
|
rules: [
|
|
752
|
-
${$.rules.map((
|
|
753
|
-
variantId: '${
|
|
754
|
-
${typeof
|
|
755
|
-
${
|
|
756
|
-
${
|
|
1000
|
+
${$.rules.map((b)=>` {
|
|
1001
|
+
variantId: '${f(b.variantId)}',
|
|
1002
|
+
${typeof b.percentage==="number"?`percentage: ${b.percentage},`:""}
|
|
1003
|
+
${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}`:""} },`:""}
|
|
1004
|
+
${b.expression?`expression: '${f(b.expression)}',`:""}
|
|
757
1005
|
}`).join(`,
|
|
758
1006
|
`)}
|
|
759
1007
|
],
|
|
760
1008
|
fallback: '${$.fallback??"control"}',
|
|
761
|
-
}`;default:return
|
|
1009
|
+
}`;default:return u5($)}}function d5($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function f($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function u5($){throw Error(`Unsupported allocation type ${$}`)}function o5($){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(`
|
|
762
1010
|
`);return`/**
|
|
763
1011
|
* ${$.title} Feature
|
|
764
1012
|
*
|
|
@@ -767,35 +1015,35 @@ ${$.rules.map((W)=>` {
|
|
|
767
1015
|
|
|
768
1016
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
769
1017
|
|
|
770
|
-
export const ${
|
|
1018
|
+
export const ${o5($.key)}Feature = defineFeature({
|
|
771
1019
|
meta: {
|
|
772
1020
|
key: '${$.key}',
|
|
773
1021
|
version: '${$.version}',
|
|
774
1022
|
title: '${$.title}',
|
|
775
1023
|
description: '${$.description||"TODO: Add description"}',
|
|
776
1024
|
domain: '${$.domain}',
|
|
777
|
-
owners: [${$.owners.map((
|
|
778
|
-
tags: [${$.tags.map((
|
|
1025
|
+
owners: [${$.owners.map((A)=>`'${A}'`).join(", ")}],
|
|
1026
|
+
tags: [${$.tags.map((A)=>`'${A}'`).join(", ")}],
|
|
779
1027
|
stability: '${$.stability||"beta"}',
|
|
780
1028
|
},
|
|
781
1029
|
|
|
782
1030
|
operations: [
|
|
783
|
-
${
|
|
1031
|
+
${b($.operations)||" // Add operations here"}
|
|
784
1032
|
],
|
|
785
1033
|
|
|
786
1034
|
events: [
|
|
787
|
-
${
|
|
1035
|
+
${b($.events)||" // Add events here"}
|
|
788
1036
|
],
|
|
789
1037
|
|
|
790
1038
|
presentations: [
|
|
791
|
-
${
|
|
1039
|
+
${b($.presentations)||" // Add presentations here"}
|
|
792
1040
|
],
|
|
793
1041
|
|
|
794
1042
|
experiments: [
|
|
795
|
-
${
|
|
1043
|
+
${b($.experiments)||" // Add experiments here"}
|
|
796
1044
|
],
|
|
797
1045
|
});
|
|
798
|
-
`}function
|
|
1046
|
+
`}function i5($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function jw($){let b=i5($.key),A=`${b}FormModel`,m=`${b}Form`;return`/**
|
|
799
1047
|
* ${$.title} Form
|
|
800
1048
|
*
|
|
801
1049
|
* Auto-generated form spec.
|
|
@@ -804,8 +1052,8 @@ ${W($.experiments)||" // Add experiments here"}
|
|
|
804
1052
|
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
805
1053
|
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
806
1054
|
|
|
807
|
-
const ${
|
|
808
|
-
name: '${
|
|
1055
|
+
const ${A} = defineSchemaModel({
|
|
1056
|
+
name: '${A}',
|
|
809
1057
|
description: '${$.description||"TODO: Add form model description"}',
|
|
810
1058
|
fields: {
|
|
811
1059
|
${$.primaryFieldKey}: {
|
|
@@ -815,18 +1063,18 @@ const ${j} = defineSchemaModel({
|
|
|
815
1063
|
},
|
|
816
1064
|
});
|
|
817
1065
|
|
|
818
|
-
export const ${
|
|
1066
|
+
export const ${m} = defineFormSpec({
|
|
819
1067
|
meta: {
|
|
820
1068
|
key: '${$.key}',
|
|
821
1069
|
version: '${$.version}',
|
|
822
1070
|
title: '${$.title}',
|
|
823
1071
|
description: '${$.description||"TODO: Add description"}',
|
|
824
1072
|
domain: '${$.domain}',
|
|
825
|
-
owners: [${$.owners.map((
|
|
826
|
-
tags: [${$.tags.map((
|
|
1073
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1074
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
827
1075
|
stability: '${$.stability||"beta"}',
|
|
828
1076
|
},
|
|
829
|
-
model: ${
|
|
1077
|
+
model: ${A},
|
|
830
1078
|
fields: [
|
|
831
1079
|
{
|
|
832
1080
|
kind: 'text',
|
|
@@ -851,17 +1099,17 @@ export const ${A} = defineFormSpec({
|
|
|
851
1099
|
form: 'react-hook-form',
|
|
852
1100
|
},
|
|
853
1101
|
});
|
|
854
|
-
`}function
|
|
855
|
-
import { ${
|
|
1102
|
+
`}function yw($,b){let A=l5($.split(".").pop()||"unknown")+"Handler",m=UA($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
1103
|
+
import { ${m} } from '../contracts/${Qw($)}.contracts';
|
|
856
1104
|
|
|
857
1105
|
/**
|
|
858
1106
|
* Handler for ${$}
|
|
859
1107
|
*/
|
|
860
|
-
export const ${
|
|
1108
|
+
export const ${A}: ContractHandler<typeof ${m}> = async (
|
|
861
1109
|
input,
|
|
862
1110
|
context
|
|
863
1111
|
) => {
|
|
864
|
-
// TODO: Implement ${
|
|
1112
|
+
// TODO: Implement ${b} logic
|
|
865
1113
|
|
|
866
1114
|
try {
|
|
867
1115
|
// 1. Validate prerequisites
|
|
@@ -877,28 +1125,28 @@ export const ${j}: ContractHandler<typeof ${A}> = async (
|
|
|
877
1125
|
throw error;
|
|
878
1126
|
}
|
|
879
1127
|
};
|
|
880
|
-
`}function
|
|
1128
|
+
`}function Bw($,b){let A=UA($);return`import React from 'react';
|
|
881
1129
|
|
|
882
|
-
interface ${
|
|
1130
|
+
interface ${A}Props {
|
|
883
1131
|
// TODO: Define props based on presentation spec
|
|
884
1132
|
}
|
|
885
1133
|
|
|
886
1134
|
/**
|
|
887
|
-
* ${
|
|
1135
|
+
* ${b}
|
|
888
1136
|
*/
|
|
889
|
-
export const ${
|
|
1137
|
+
export const ${A}: React.FC<${A}Props> = (props) => {
|
|
890
1138
|
return (
|
|
891
1139
|
<div>
|
|
892
1140
|
{/* TODO: Implement component UI */}
|
|
893
|
-
<p>Component: ${
|
|
1141
|
+
<p>Component: ${A}</p>
|
|
894
1142
|
</div>
|
|
895
1143
|
);
|
|
896
1144
|
};
|
|
897
|
-
`}function
|
|
898
|
-
import { ${
|
|
1145
|
+
`}function Sw($,b){let A=b==="handler"?"../handlers":"../components",m=UA($);return`import { describe, it, expect } from 'bun:test';
|
|
1146
|
+
import { ${m} } from '${A}/${Qw($)}';
|
|
899
1147
|
|
|
900
|
-
describe('${
|
|
901
|
-
it('should ${
|
|
1148
|
+
describe('${m}', () => {
|
|
1149
|
+
it('should ${b==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
902
1150
|
// TODO: Implement test
|
|
903
1151
|
expect(true).toBe(true);
|
|
904
1152
|
});
|
|
@@ -907,170 +1155,170 @@ describe('${A}', () => {
|
|
|
907
1155
|
// TODO: Test edge cases
|
|
908
1156
|
});
|
|
909
1157
|
|
|
910
|
-
${
|
|
1158
|
+
${b==="handler"?`it('should handle errors appropriately', async () => {
|
|
911
1159
|
// TODO: Test error scenarios
|
|
912
1160
|
});`:`it('should be accessible', async () => {
|
|
913
1161
|
// TODO: Test accessibility
|
|
914
1162
|
});`}
|
|
915
1163
|
});
|
|
916
|
-
`}function
|
|
917
|
-
`),
|
|
918
|
-
${$.capabilitiesRequired.map((
|
|
1164
|
+
`}function l5($){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=m8($.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(`,
|
|
1165
|
+
`),j=$.capabilitiesRequired.length>0?` requires: [
|
|
1166
|
+
${$.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(`,
|
|
919
1167
|
`)}
|
|
920
|
-
],`:"",
|
|
921
|
-
`:"",
|
|
1168
|
+
],`:"",y=t5($.configFields),B=a5($.configFields),S=p5($.secretFields),Q=e5($.secretFields),Z=$.docsUrl?` docsUrl: '${w$($.docsUrl)}',
|
|
1169
|
+
`:"",G=s5($.rateLimitRpm,$.rateLimitRph),X=$8(n,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
922
1170
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
923
1171
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
924
1172
|
|
|
925
|
-
export const ${
|
|
1173
|
+
export const ${A}: IntegrationSpec = {
|
|
926
1174
|
meta: {
|
|
927
1175
|
key: '${$.name}',
|
|
928
1176
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
929
1177
|
category: '${$.category}',
|
|
930
|
-
displayName: '${
|
|
931
|
-
title: '${
|
|
932
|
-
description: '${
|
|
933
|
-
domain: '${
|
|
934
|
-
owners: [${$.owners.map((
|
|
935
|
-
tags: [${$.tags.map((
|
|
936
|
-
stability: StabilityEnum.${
|
|
937
|
-
},
|
|
938
|
-
supportedModes: [${
|
|
1178
|
+
displayName: '${w$($.displayName)}',
|
|
1179
|
+
title: '${w$($.title)}',
|
|
1180
|
+
description: '${w$($.description)}',
|
|
1181
|
+
domain: '${w$($.domain)}',
|
|
1182
|
+
owners: [${$.owners.map((Y)=>`'${w$(Y)}'`).join(", ")}],
|
|
1183
|
+
tags: [${$.tags.map((Y)=>`'${w$(Y)}'`).join(", ")}],
|
|
1184
|
+
stability: StabilityEnum.${A8($.stability)},
|
|
1185
|
+
},
|
|
1186
|
+
supportedModes: [${W}],
|
|
939
1187
|
capabilities: {
|
|
940
1188
|
provides: [
|
|
941
|
-
${
|
|
1189
|
+
${w}
|
|
942
1190
|
],
|
|
943
|
-
${
|
|
1191
|
+
${j.length>0?`${j}
|
|
944
1192
|
`:""} },
|
|
945
1193
|
configSchema: {
|
|
946
|
-
${
|
|
947
|
-
example: ${
|
|
1194
|
+
${y}
|
|
1195
|
+
example: ${B},
|
|
948
1196
|
},
|
|
949
1197
|
secretSchema: {
|
|
950
|
-
${
|
|
951
|
-
example: ${
|
|
1198
|
+
${S}
|
|
1199
|
+
example: ${Q},
|
|
952
1200
|
},
|
|
953
|
-
${
|
|
1201
|
+
${Z}${G}${X} healthCheck: {
|
|
954
1202
|
method: '${$.healthCheckMethod}',
|
|
955
1203
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
956
1204
|
},
|
|
957
1205
|
};
|
|
958
1206
|
|
|
959
|
-
export function ${
|
|
1207
|
+
export function ${m}(
|
|
960
1208
|
registry: IntegrationSpecRegistry
|
|
961
1209
|
): IntegrationSpecRegistry {
|
|
962
|
-
return registry.register(${
|
|
1210
|
+
return registry.register(${A});
|
|
963
1211
|
}
|
|
964
|
-
`}function
|
|
965
|
-
`:"",
|
|
1212
|
+
`}function t5($){let b=$.filter((n)=>n.required),A=b.length>0?` required: [${b.map((n)=>`'${n.key}'`).join(", ")}],
|
|
1213
|
+
`:"",m=$.length?$.map((n)=>{let W=n.description?`, description: '${w$(n.description)}'`:"";return` ${n.key}: { type: '${b8(n.type)}'${W} }`}).join(`,
|
|
966
1214
|
`):"";return` schema: {
|
|
967
1215
|
type: 'object',
|
|
968
|
-
${
|
|
969
|
-
${
|
|
1216
|
+
${A} properties: {
|
|
1217
|
+
${m||" "}
|
|
970
1218
|
},
|
|
971
1219
|
},
|
|
972
|
-
`}function
|
|
973
|
-
`:"",
|
|
1220
|
+
`}function p5($){let b=$.filter((n)=>n.required),A=b.length>0?` required: [${b.map((n)=>`'${n.key}'`).join(", ")}],
|
|
1221
|
+
`:"",m=$.length?$.map((n)=>{let W=n.description?`, description: '${w$(n.description)}'`:"";return` ${n.key}: { type: 'string'${W} }`}).join(`,
|
|
974
1222
|
`):"";return` schema: {
|
|
975
1223
|
type: 'object',
|
|
976
|
-
${
|
|
977
|
-
${
|
|
1224
|
+
${A} properties: {
|
|
1225
|
+
${m||" "}
|
|
978
1226
|
},
|
|
979
1227
|
},
|
|
980
|
-
`}function
|
|
981
|
-
${$.map((
|
|
1228
|
+
`}function a5($){if($.length===0)return"{}";return`{
|
|
1229
|
+
${$.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(`,
|
|
982
1230
|
`)}
|
|
983
|
-
}`}function
|
|
984
|
-
${$.map((
|
|
1231
|
+
}`}function e5($){if($.length===0)return"{}";return`{
|
|
1232
|
+
${$.map((A)=>` ${A.key}: '${A.key.toUpperCase()}_SECRET'`).join(`,
|
|
985
1233
|
`)}
|
|
986
|
-
}`}function
|
|
1234
|
+
}`}function s5($,b){if($==null&&b==null)return"";let A=[];if($!=null)A.push(` rpm: ${$}`);if(b!=null)A.push(` rph: ${b}`);return` constraints: {
|
|
987
1235
|
rateLimit: {
|
|
988
|
-
${
|
|
1236
|
+
${A.join(`,
|
|
989
1237
|
`)}
|
|
990
1238
|
},
|
|
991
1239
|
},
|
|
992
|
-
`}function
|
|
993
|
-
`:"",
|
|
994
|
-
`:"";if(!
|
|
995
|
-
${
|
|
996
|
-
`}function
|
|
1240
|
+
`}function $8($,b,A){if(!$.includes("byok"))return"";let m=b?` setupInstructions: '${w$(b)}',
|
|
1241
|
+
`:"",n=A&&A.length?` requiredScopes: [${A.map((W)=>`'${w$(W)}'`).join(", ")}],
|
|
1242
|
+
`:"";if(!m&&!n)return"";return` byokSetup: {
|
|
1243
|
+
${m}${n} },
|
|
1244
|
+
`}function b8($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function A8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function m8($){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=y8($.name.split(".").pop()??"KnowledgeSpace"),A=`${b}KnowledgeSpace`,m=`register${b}KnowledgeSpace`,n=n8($),W=W8($),w=w8($),j=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
997
1245
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
998
1246
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
999
1247
|
|
|
1000
|
-
export const ${
|
|
1248
|
+
export const ${A}: KnowledgeSpaceSpec = {
|
|
1001
1249
|
meta: {
|
|
1002
1250
|
key: '${$.name}',
|
|
1003
1251
|
version: ${$.version},
|
|
1004
1252
|
category: '${$.category}',
|
|
1005
|
-
displayName: '${
|
|
1006
|
-
title: '${
|
|
1007
|
-
description: '${
|
|
1008
|
-
domain: '${
|
|
1009
|
-
owners: [${$.owners.map((
|
|
1010
|
-
tags: [${$.tags.map((
|
|
1011
|
-
stability: StabilityEnum.${
|
|
1012
|
-
},
|
|
1013
|
-
retention: ${
|
|
1253
|
+
displayName: '${Y$($.displayName)}',
|
|
1254
|
+
title: '${Y$($.title)}',
|
|
1255
|
+
description: '${Y$($.description)}',
|
|
1256
|
+
domain: '${Y$($.domain)}',
|
|
1257
|
+
owners: [${$.owners.map((y)=>`'${Y$(y)}'`).join(", ")}],
|
|
1258
|
+
tags: [${$.tags.map((y)=>`'${Y$(y)}'`).join(", ")}],
|
|
1259
|
+
stability: StabilityEnum.${j8($.stability)},
|
|
1260
|
+
},
|
|
1261
|
+
retention: ${n},
|
|
1014
1262
|
access: {
|
|
1015
|
-
${
|
|
1263
|
+
${W}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${j}
|
|
1016
1264
|
`:""} },
|
|
1017
|
-
${
|
|
1265
|
+
${w} description: '${Y$($.description||$.displayName)}',
|
|
1018
1266
|
};
|
|
1019
1267
|
|
|
1020
|
-
export function ${
|
|
1268
|
+
export function ${m}(
|
|
1021
1269
|
registry: KnowledgeSpaceRegistry
|
|
1022
1270
|
): KnowledgeSpaceRegistry {
|
|
1023
|
-
return registry.register(${
|
|
1271
|
+
return registry.register(${A});
|
|
1024
1272
|
}
|
|
1025
|
-
`}function
|
|
1026
|
-
`,
|
|
1027
|
-
`;return`${
|
|
1028
|
-
${
|
|
1273
|
+
`}function n8($){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}',
|
|
1274
|
+
`,A=` automationWritable: ${$.automationWritable},
|
|
1275
|
+
`;return`${b}${A}`}function w8($){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: {
|
|
1276
|
+
${b.join(`,
|
|
1029
1277
|
`)}
|
|
1030
1278
|
},
|
|
1031
|
-
`}function
|
|
1279
|
+
`}function j8($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function y8($){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=`${B8($.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';
|
|
1032
1280
|
|
|
1033
|
-
export const ${
|
|
1281
|
+
export const ${A}: MigrationSpec = {
|
|
1034
1282
|
meta: {
|
|
1035
1283
|
key: '${$.name}',
|
|
1036
1284
|
version: ${$.version},
|
|
1037
|
-
title: '${
|
|
1038
|
-
description: '${
|
|
1039
|
-
domain: '${
|
|
1040
|
-
owners: [${$.owners.map((
|
|
1041
|
-
tags: [${$.tags.map((
|
|
1285
|
+
title: '${v$($.title)}',
|
|
1286
|
+
description: '${v$($.description??"")}',
|
|
1287
|
+
domain: '${v$($.domain)}',
|
|
1288
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1289
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
1042
1290
|
stability: '${$.stability}',
|
|
1043
1291
|
},
|
|
1044
1292
|
plan: {
|
|
1045
1293
|
up: [
|
|
1046
|
-
${
|
|
1294
|
+
${Xw($.up)}
|
|
1047
1295
|
],${$.down&&$.down.length?`
|
|
1048
1296
|
down: [
|
|
1049
|
-
${
|
|
1297
|
+
${Xw($.down)}
|
|
1050
1298
|
],`:""}
|
|
1051
1299
|
},
|
|
1052
|
-
${
|
|
1300
|
+
${m}
|
|
1053
1301
|
};
|
|
1054
|
-
`}function
|
|
1302
|
+
`}function Xw($){return $.map((b)=>{let A=b.description?`description: '${v$(b.description)}',`:"";switch(b.kind){case"schema":return` {
|
|
1055
1303
|
kind: 'schema',
|
|
1056
|
-
${
|
|
1057
|
-
sql: \`${
|
|
1304
|
+
${A}
|
|
1305
|
+
sql: \`${v$(b.sql??"")}\`,
|
|
1058
1306
|
}`;case"data":return` {
|
|
1059
1307
|
kind: 'data',
|
|
1060
|
-
${
|
|
1061
|
-
script: \`${
|
|
1308
|
+
${A}
|
|
1309
|
+
script: \`${v$(b.script??"")}\`,
|
|
1062
1310
|
}`;case"validation":default:return` {
|
|
1063
1311
|
kind: 'validation',
|
|
1064
|
-
${
|
|
1065
|
-
assertion: \`${
|
|
1312
|
+
${A}
|
|
1313
|
+
assertion: \`${v$(b.assertion??"")}\`,
|
|
1066
1314
|
}`}}).join(`,
|
|
1067
|
-
`)}function
|
|
1315
|
+
`)}function B8($){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=S8(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';
|
|
1068
1316
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1069
1317
|
|
|
1070
1318
|
// TODO: Define input schema
|
|
1071
|
-
export const ${
|
|
1072
|
-
name: '${
|
|
1073
|
-
description: 'Input for ${
|
|
1319
|
+
export const ${G} = new SchemaModel({
|
|
1320
|
+
name: '${G}',
|
|
1321
|
+
description: 'Input for ${b}',
|
|
1074
1322
|
fields: {
|
|
1075
1323
|
// Add your fields here
|
|
1076
1324
|
// example: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
@@ -1078,32 +1326,32 @@ export const ${J} = new SchemaModel({
|
|
|
1078
1326
|
});
|
|
1079
1327
|
|
|
1080
1328
|
// TODO: Define output schema
|
|
1081
|
-
export const ${
|
|
1082
|
-
name: '${
|
|
1083
|
-
description: 'Output for ${
|
|
1329
|
+
export const ${X} = new SchemaModel({
|
|
1330
|
+
name: '${X}',
|
|
1331
|
+
description: 'Output for ${b}',
|
|
1084
1332
|
fields: {
|
|
1085
1333
|
// Add your fields here
|
|
1086
1334
|
ok: { type: ScalarTypeEnum.Boolean(), isOptional: false },
|
|
1087
1335
|
},
|
|
1088
1336
|
});
|
|
1089
1337
|
|
|
1090
|
-
export const ${
|
|
1338
|
+
export const ${Z} = define${mm(m)}({
|
|
1091
1339
|
meta: {
|
|
1092
|
-
key: '${
|
|
1093
|
-
key: '${
|
|
1094
|
-
version: '${
|
|
1095
|
-
stability: '${
|
|
1096
|
-
stability: '${
|
|
1097
|
-
owners: [${
|
|
1098
|
-
tags: [${
|
|
1099
|
-
description: '${
|
|
1100
|
-
goal: '${
|
|
1101
|
-
context: '${
|
|
1340
|
+
key: '${b}',
|
|
1341
|
+
key: '${b}',
|
|
1342
|
+
version: '${A}',
|
|
1343
|
+
stability: '${j}',
|
|
1344
|
+
stability: '${j}',
|
|
1345
|
+
owners: [${y.map((Y)=>`'${Y}'`).join(", ")}],
|
|
1346
|
+
tags: [${B.map((Y)=>`'${Y}'`).join(", ")}],
|
|
1347
|
+
description: '${n}',
|
|
1348
|
+
goal: '${W}',
|
|
1349
|
+
context: '${w}',
|
|
1102
1350
|
},
|
|
1103
1351
|
|
|
1104
1352
|
io: {
|
|
1105
|
-
input: ${
|
|
1106
|
-
output: ${
|
|
1353
|
+
input: ${G},
|
|
1354
|
+
output: ${X},
|
|
1107
1355
|
errors: {
|
|
1108
1356
|
// Define possible errors
|
|
1109
1357
|
// EXAMPLE_ERROR: {
|
|
@@ -1115,8 +1363,8 @@ export const ${G} = define${_1(A)}({
|
|
|
1115
1363
|
},
|
|
1116
1364
|
|
|
1117
1365
|
policy: {
|
|
1118
|
-
auth: '${
|
|
1119
|
-
${
|
|
1366
|
+
auth: '${S}',
|
|
1367
|
+
${Q.length>0?`flags: [${Q.map((Y)=>`'${Y}'`).join(", ")}],`:"// flags: [],"}
|
|
1120
1368
|
},
|
|
1121
1369
|
|
|
1122
1370
|
sideEffects: {
|
|
@@ -1130,9 +1378,9 @@ export const ${G} = define${_1(A)}({
|
|
|
1130
1378
|
},
|
|
1131
1379
|
|
|
1132
1380
|
transport: {
|
|
1133
|
-
rest: { method: '${
|
|
1134
|
-
gql: { field: '${
|
|
1135
|
-
mcp: { toolName: '${
|
|
1381
|
+
rest: { method: '${m==="command"?"POST":"GET"}' },
|
|
1382
|
+
gql: { field: '${b.replace(/\./g,"_")}' },
|
|
1383
|
+
mcp: { toolName: '${b.replace(/\./g,"_")}-v${String(A).replace(/\./g,"_")}' },
|
|
1136
1384
|
},
|
|
1137
1385
|
|
|
1138
1386
|
acceptance: {
|
|
@@ -1153,13 +1401,13 @@ export const ${G} = define${_1(A)}({
|
|
|
1153
1401
|
],
|
|
1154
1402
|
},
|
|
1155
1403
|
});
|
|
1156
|
-
`}function
|
|
1404
|
+
`}function mm($){return $.charAt(0).toUpperCase()+$.slice(1)}function S8($){return $.split(/[-_.]/).map(mm).join("")}function qw($){let{name:b,version:A,description:m,stability:n,owners:W,tags:w,presentationKind:j}=$,y=Q8(b.replace(/\./g,"_"))+"Presentation",B="";switch(j){case"web_component":B=` content: {
|
|
1157
1405
|
kind: 'web_component',
|
|
1158
1406
|
framework: 'react',
|
|
1159
|
-
componentKey: '${
|
|
1407
|
+
componentKey: '${b.replace(/\./g,"_")}',
|
|
1160
1408
|
props: new SchemaModel({
|
|
1161
|
-
name: '${
|
|
1162
|
-
description: 'Props for ${
|
|
1409
|
+
name: '${y}Props',
|
|
1410
|
+
description: 'Props for ${b}',
|
|
1163
1411
|
fields: {
|
|
1164
1412
|
// TODO: Define component props
|
|
1165
1413
|
},
|
|
@@ -1167,20 +1415,20 @@ export const ${G} = define${_1(A)}({
|
|
|
1167
1415
|
analytics: [
|
|
1168
1416
|
// TODO: Define analytics events
|
|
1169
1417
|
],
|
|
1170
|
-
},`;break;case"markdown":
|
|
1418
|
+
},`;break;case"markdown":B=` content: {
|
|
1171
1419
|
kind: 'markdown',
|
|
1172
1420
|
content: \`
|
|
1173
|
-
# ${
|
|
1421
|
+
# ${m}
|
|
1174
1422
|
|
|
1175
1423
|
TODO: Add markdown content here
|
|
1176
1424
|
\`,
|
|
1177
|
-
// Or use resourceUri: 'feature://${
|
|
1178
|
-
},`;break;case"data":
|
|
1425
|
+
// Or use resourceUri: 'feature://${b}/guide.md'
|
|
1426
|
+
},`;break;case"data":B=` content: {
|
|
1179
1427
|
kind: 'data',
|
|
1180
1428
|
mimeType: 'application/json',
|
|
1181
1429
|
model: new SchemaModel({
|
|
1182
|
-
name: '${
|
|
1183
|
-
description: 'Data structure for ${
|
|
1430
|
+
name: '${y}Data',
|
|
1431
|
+
description: 'Data structure for ${b}',
|
|
1184
1432
|
fields: {
|
|
1185
1433
|
// TODO: Define data structure
|
|
1186
1434
|
},
|
|
@@ -1188,14 +1436,14 @@ TODO: Add markdown content here
|
|
|
1188
1436
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1189
1437
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1190
1438
|
|
|
1191
|
-
export const ${
|
|
1439
|
+
export const ${y}: PresentationSpec = {
|
|
1192
1440
|
meta: {
|
|
1193
|
-
key: '${
|
|
1194
|
-
version: ${
|
|
1195
|
-
stability: '${
|
|
1196
|
-
owners: [${
|
|
1197
|
-
tags: [${
|
|
1198
|
-
description: '${
|
|
1441
|
+
key: '${b}',
|
|
1442
|
+
version: ${A},
|
|
1443
|
+
stability: '${n}',
|
|
1444
|
+
owners: [${W.map((S)=>`'${S}'`).join(", ")}],
|
|
1445
|
+
tags: [${w.map((S)=>`'${S}'`).join(", ")}],
|
|
1446
|
+
description: '${m}',
|
|
1199
1447
|
},
|
|
1200
1448
|
|
|
1201
1449
|
policy: {
|
|
@@ -1203,81 +1451,109 @@ export const ${B}: PresentationSpec = {
|
|
|
1203
1451
|
// pii: [],
|
|
1204
1452
|
},
|
|
1205
1453
|
|
|
1206
|
-
${
|
|
1454
|
+
${B}
|
|
1207
1455
|
};
|
|
1208
|
-
`}function
|
|
1209
|
-
${$.providers.map((
|
|
1210
|
-
type: '${
|
|
1211
|
-
config: ${
|
|
1456
|
+
`}function Q8($){return $.split(/[-_.]/).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Ow($){let b=Z8($.name.split(".").pop()??"Telemetry")+"Telemetry",A=$.providers?.length?`providers: [
|
|
1457
|
+
${$.providers.map((n)=>` {
|
|
1458
|
+
type: '${n.type}',
|
|
1459
|
+
config: ${G8(n.config)},
|
|
1212
1460
|
}`).join(`,
|
|
1213
1461
|
`)}
|
|
1214
|
-
],`:"",
|
|
1215
|
-
type: '${
|
|
1216
|
-
${
|
|
1217
|
-
${
|
|
1218
|
-
${
|
|
1219
|
-
${
|
|
1462
|
+
],`:"",m=$.events.map((n)=>{let W=n.properties.map((j)=>` '${j.name}': {
|
|
1463
|
+
type: '${j.type}',
|
|
1464
|
+
${j.required?"required: true,":""}
|
|
1465
|
+
${j.pii?"pii: true,":""}
|
|
1466
|
+
${j.redact?"redact: true,":""}
|
|
1467
|
+
${j.description?`description: '${l(j.description)}',`:""}
|
|
1220
1468
|
}`).join(`,
|
|
1221
|
-
`),
|
|
1469
|
+
`),w=n.anomalyRules?.length?` anomalyDetection: {
|
|
1222
1470
|
enabled: true,
|
|
1223
|
-
${typeof
|
|
1471
|
+
${typeof n.anomalyMinimumSample==="number"?`minimumSample: ${n.anomalyMinimumSample},`:""}
|
|
1224
1472
|
thresholds: [
|
|
1225
|
-
${
|
|
1226
|
-
metric: '${
|
|
1227
|
-
${typeof
|
|
1228
|
-
${typeof
|
|
1473
|
+
${n.anomalyRules.map((j)=>` {
|
|
1474
|
+
metric: '${l(j.metric)}',
|
|
1475
|
+
${typeof j.min==="number"?`min: ${j.min},`:""}
|
|
1476
|
+
${typeof j.max==="number"?`max: ${j.max},`:""}
|
|
1229
1477
|
}`).join(`,
|
|
1230
1478
|
`)}
|
|
1231
1479
|
],
|
|
1232
|
-
actions: [${(
|
|
1233
|
-
},`:
|
|
1480
|
+
actions: [${(n.anomalyActions??[]).map((j)=>`'${j}'`).join(", ")}],
|
|
1481
|
+
},`:n.anomalyEnabled?` anomalyDetection: {
|
|
1234
1482
|
enabled: true,
|
|
1235
|
-
${typeof
|
|
1483
|
+
${typeof n.anomalyMinimumSample==="number"?`minimumSample: ${n.anomalyMinimumSample},`:""}
|
|
1236
1484
|
},`:"";return` {
|
|
1237
|
-
name: '${n
|
|
1238
|
-
version: ${
|
|
1485
|
+
name: '${l(n.name)}',
|
|
1486
|
+
version: ${n.version},
|
|
1239
1487
|
semantics: {
|
|
1240
|
-
what: '${n
|
|
1241
|
-
${
|
|
1242
|
-
${
|
|
1488
|
+
what: '${l(n.what)}',
|
|
1489
|
+
${n.who?`who: '${l(n.who)}',`:""}
|
|
1490
|
+
${n.why?`why: '${l(n.why)}',`:""}
|
|
1243
1491
|
},
|
|
1244
|
-
privacy: '${
|
|
1492
|
+
privacy: '${n.privacy}',
|
|
1245
1493
|
properties: {
|
|
1246
|
-
${
|
|
1494
|
+
${W}
|
|
1247
1495
|
},
|
|
1248
|
-
${typeof
|
|
1249
|
-
${typeof
|
|
1250
|
-
${
|
|
1251
|
-
${
|
|
1496
|
+
${typeof n.retentionDays==="number"?`retention: { days: ${n.retentionDays}, ${n.retentionPolicy?`policy: '${n.retentionPolicy}'`:""} },`:""}
|
|
1497
|
+
${typeof n.samplingRate==="number"?`sampling: { rate: ${n.samplingRate}${n.samplingConditions?`, conditions: ['${l(n.samplingConditions)}']`:""} },`:""}
|
|
1498
|
+
${w}
|
|
1499
|
+
${n.tags?.length?`tags: [${n.tags.map((j)=>`'${l(j)}'`).join(", ")}],`:""}
|
|
1252
1500
|
}`}).join(`,
|
|
1253
1501
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1254
1502
|
|
|
1255
|
-
export const ${
|
|
1503
|
+
export const ${b}: TelemetrySpec = {
|
|
1256
1504
|
meta: {
|
|
1257
|
-
key: '${
|
|
1505
|
+
key: '${l($.name)}',
|
|
1258
1506
|
version: ${$.version},
|
|
1259
|
-
title: '${
|
|
1260
|
-
description: '${
|
|
1261
|
-
domain: '${
|
|
1262
|
-
owners: [${$.owners.map((
|
|
1263
|
-
tags: [${$.tags.map((
|
|
1507
|
+
title: '${l($.name)} telemetry',
|
|
1508
|
+
description: '${l($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1509
|
+
domain: '${l($.domain)}',
|
|
1510
|
+
owners: [${$.owners.map((n)=>`'${l(n)}'`).join(", ")}],
|
|
1511
|
+
tags: [${$.tags.map((n)=>`'${l(n)}'`).join(", ")}],
|
|
1264
1512
|
stability: '${$.stability}',
|
|
1265
1513
|
},
|
|
1266
1514
|
config: {
|
|
1267
1515
|
${typeof $.defaultRetentionDays==="number"?`defaultRetentionDays: ${$.defaultRetentionDays},`:""}
|
|
1268
1516
|
${typeof $.defaultSamplingRate==="number"?`defaultSamplingRate: ${$.defaultSamplingRate},`:""}
|
|
1269
1517
|
${$.anomalyEnabled?`anomalyDetection: { enabled: true${typeof $.anomalyCheckIntervalMs==="number"?`, checkIntervalMs: ${$.anomalyCheckIntervalMs}`:""} },`:""}
|
|
1270
|
-
${
|
|
1518
|
+
${A}
|
|
1271
1519
|
},
|
|
1272
1520
|
events: [
|
|
1273
|
-
${
|
|
1521
|
+
${m}
|
|
1274
1522
|
],
|
|
1275
1523
|
};
|
|
1276
|
-
`}function
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1524
|
+
`}function Z8($){return $.split(/[-_.]/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function l($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function G8($){let b=$.trim();if(!b)return"{}";if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))return b;return`'${l(b)}'`}function X8($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}function Vw($){return`/**
|
|
1525
|
+
* ${$.title} Theme
|
|
1526
|
+
*
|
|
1527
|
+
* Auto-generated theme spec.
|
|
1528
|
+
*/
|
|
1529
|
+
|
|
1530
|
+
import { defineTheme } from '@contractspec/lib.contracts-spec/themes';
|
|
1531
|
+
|
|
1532
|
+
export const ${X8($.key)}Theme = defineTheme({
|
|
1533
|
+
meta: {
|
|
1534
|
+
key: '${$.key}',
|
|
1535
|
+
version: '${$.version}',
|
|
1536
|
+
title: '${$.title}',
|
|
1537
|
+
description: '${$.description}',
|
|
1538
|
+
domain: '${$.domain}',
|
|
1539
|
+
owners: [${$.owners.map((b)=>`'${b}'`).join(", ")}],
|
|
1540
|
+
tags: [${$.tags.map((b)=>`'${b}'`).join(", ")}],
|
|
1541
|
+
stability: '${$.stability}',
|
|
1542
|
+
scopes: [${$.scopes.map((b)=>`'${b}'`).join(", ")}],
|
|
1543
|
+
},
|
|
1544
|
+
tokens: {
|
|
1545
|
+
colors: {
|
|
1546
|
+
primary: { value: '#2563eb' },
|
|
1547
|
+
background: { value: '#ffffff' },
|
|
1548
|
+
foreground: { value: '#111827' },
|
|
1549
|
+
},
|
|
1550
|
+
},
|
|
1551
|
+
});
|
|
1552
|
+
`}function Jw($){let b=H8($.name.split(".").pop()??"Workflow")+"Workflow",A=$.steps.map((n)=>Y8(n)).join(`,
|
|
1553
|
+
`),m=$.transitions.map((n)=>` {
|
|
1554
|
+
from: '${n.from}',
|
|
1555
|
+
to: '${n.to}',
|
|
1556
|
+
${n.condition?` condition: '${e$(n.condition)}',`:""}
|
|
1281
1557
|
}`).join(`,
|
|
1282
1558
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1283
1559
|
|
|
@@ -1289,36 +1565,36 @@ ${Q.condition?` condition: '${h$(Q.condition)}',`:""}
|
|
|
1289
1565
|
* - Provide form renderers for human steps.
|
|
1290
1566
|
* - Add guards/conditions as needed.
|
|
1291
1567
|
*/
|
|
1292
|
-
export const ${
|
|
1568
|
+
export const ${b}: WorkflowSpec = {
|
|
1293
1569
|
meta: {
|
|
1294
1570
|
key: '${$.name}',
|
|
1295
1571
|
version: ${$.version},
|
|
1296
|
-
title: '${
|
|
1297
|
-
description: '${
|
|
1298
|
-
domain: '${
|
|
1572
|
+
title: '${e$($.title)}',
|
|
1573
|
+
description: '${e$($.description)}',
|
|
1574
|
+
domain: '${e$($.domain)}',
|
|
1299
1575
|
stability: '${$.stability}',
|
|
1300
|
-
owners: [${$.owners.map((
|
|
1301
|
-
tags: [${$.tags.map((
|
|
1576
|
+
owners: [${$.owners.map((n)=>`'${n}'`).join(", ")}],
|
|
1577
|
+
tags: [${$.tags.map((n)=>`'${n}'`).join(", ")}],
|
|
1302
1578
|
},
|
|
1303
1579
|
definition: {
|
|
1304
1580
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
1305
1581
|
`:""} steps: [
|
|
1306
|
-
${
|
|
1582
|
+
${A}
|
|
1307
1583
|
],
|
|
1308
1584
|
transitions: [
|
|
1309
|
-
${
|
|
1585
|
+
${m}
|
|
1310
1586
|
],
|
|
1311
1587
|
},
|
|
1312
1588
|
${$.policyFlags.length>0?`policy: {
|
|
1313
|
-
flags: [${$.policyFlags.map((
|
|
1589
|
+
flags: [${$.policyFlags.map((n)=>`'${n}'`).join(", ")}],
|
|
1314
1590
|
},`:"// policy: { flags: [] },"}
|
|
1315
1591
|
};
|
|
1316
|
-
`}function
|
|
1317
|
-
`)}function
|
|
1592
|
+
`}function Y8($){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(`
|
|
1593
|
+
`)}function H8($){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';
|
|
1318
1594
|
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1319
|
-
import { ${$} } from '${
|
|
1595
|
+
import { ${$} } from '${b}';
|
|
1320
1596
|
|
|
1321
|
-
export async function ${
|
|
1597
|
+
export async function ${A}(input = {}, bridge = {}) {
|
|
1322
1598
|
"use workflow";
|
|
1323
1599
|
|
|
1324
1600
|
// Keep the workflow function deterministic.
|
|
@@ -1335,29 +1611,29 @@ export async function ${j}(input = {}, bridge = {}) {
|
|
|
1335
1611
|
},
|
|
1336
1612
|
});
|
|
1337
1613
|
}
|
|
1338
|
-
`}function
|
|
1339
|
-
import { ${
|
|
1614
|
+
`}function LA($,b){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1615
|
+
import { ${b} } from '${$}';
|
|
1340
1616
|
|
|
1341
1617
|
export const POST = createWorkflowDevkitStartRoute({
|
|
1342
|
-
workflow: ${
|
|
1618
|
+
workflow: ${b},
|
|
1343
1619
|
async buildArgs(body) {
|
|
1344
1620
|
return [body];
|
|
1345
1621
|
},
|
|
1346
1622
|
});
|
|
1347
|
-
`}function
|
|
1623
|
+
`}function RA(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1348
1624
|
|
|
1349
1625
|
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1350
1626
|
resolveToken({ runId }) {
|
|
1351
1627
|
return \`workflow-session:\${runId}\`;
|
|
1352
1628
|
},
|
|
1353
1629
|
});
|
|
1354
|
-
`}function
|
|
1630
|
+
`}function CA(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1355
1631
|
|
|
1356
1632
|
export const GET = createWorkflowDevkitStreamRoute();
|
|
1357
|
-
`}function
|
|
1633
|
+
`}function IA($,b){return`import { ${b} } from '${$}';
|
|
1358
1634
|
|
|
1359
1635
|
export const workflowDevkitBootstrap = {
|
|
1360
|
-
workflow: ${
|
|
1636
|
+
workflow: ${b},
|
|
1361
1637
|
createBridge() {
|
|
1362
1638
|
return {
|
|
1363
1639
|
executeAutomationStep: async () => {
|
|
@@ -1366,13 +1642,13 @@ export const workflowDevkitBootstrap = {
|
|
|
1366
1642
|
};
|
|
1367
1643
|
},
|
|
1368
1644
|
};
|
|
1369
|
-
`}function
|
|
1645
|
+
`}function EA({exportName:$,specImportPath:b,runnerName:A,workflowName:m}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1370
1646
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1371
1647
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1372
|
-
import { ${$} } from '${
|
|
1648
|
+
import { ${$} } from '${b}';
|
|
1373
1649
|
|
|
1374
1650
|
/**
|
|
1375
|
-
* Runner wiring for ${
|
|
1651
|
+
* Runner wiring for ${m}.
|
|
1376
1652
|
*
|
|
1377
1653
|
* TODO:
|
|
1378
1654
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1384,7 +1660,7 @@ registry.register(${$});
|
|
|
1384
1660
|
|
|
1385
1661
|
const stateStore = new InMemoryStateStore();
|
|
1386
1662
|
|
|
1387
|
-
export const ${
|
|
1663
|
+
export const ${A} = new WorkflowRunner({
|
|
1388
1664
|
registry,
|
|
1389
1665
|
stateStore,
|
|
1390
1666
|
opExecutor: async (operation, input, ctx) => {
|
|
@@ -1406,12 +1682,12 @@ export const ${j} = new WorkflowRunner({
|
|
|
1406
1682
|
// console.log(event, payload);
|
|
1407
1683
|
},
|
|
1408
1684
|
});
|
|
1409
|
-
`}import{getAuthoringTargetDefinition as
|
|
1410
|
-
`],[
|
|
1685
|
+
`}import{getAuthoringTargetDefinition as q8}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=O8($,b.specPath),m=V8($,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)+`
|
|
1686
|
+
`],[W,`# ${m}
|
|
1411
1687
|
|
|
1412
|
-
${
|
|
1413
|
-
`],[
|
|
1414
|
-
`],[
|
|
1688
|
+
${_w[b.target]}.
|
|
1689
|
+
`],[j,`export * from "./${y.startsWith(".")?y:`./${y}`}";
|
|
1690
|
+
`],[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";
|
|
1415
1691
|
|
|
1416
1692
|
export const ${$.exportName} = defineModuleBundle({
|
|
1417
1693
|
meta: {
|
|
@@ -1472,22 +1748,22 @@ export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
|
1472
1748
|
supportedArtifactTypes: ["patch"],
|
|
1473
1749
|
knownConstraints: [],
|
|
1474
1750
|
};
|
|
1475
|
-
`}}function
|
|
1751
|
+
`}}function O8($,b){let A=nm(b),m="/src/",n=A.lastIndexOf("/src/");if(n===-1)return $.dirname(b);return A.slice(0,n)}function V8($,b,A){let m=q8(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??R8,y=w?.inferSpecTypeFromFilePath??L8,B=w?.generateHandlerTemplate??_8,S=w?.generateComponentTemplate??K8,Q=w?.generateTestTemplate??U8,{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,$),_=J8(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 C8(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 C8($,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";
|
|
1476
1752
|
|
|
1477
|
-
export interface ${
|
|
1753
|
+
export interface ${H$(e(A,m,b))}Props {
|
|
1478
1754
|
className?: string;
|
|
1479
1755
|
}
|
|
1480
1756
|
|
|
1481
|
-
export function ${
|
|
1757
|
+
export function ${H$(e(A,m,b))}Form({
|
|
1482
1758
|
className,
|
|
1483
|
-
}: ${
|
|
1484
|
-
return <form className={className}>TODO: implement ${
|
|
1759
|
+
}: ${H$(e(A,m,b))}Props) {
|
|
1760
|
+
return <form className={className}>TODO: implement ${e(A,m,b)}</form>;
|
|
1485
1761
|
}
|
|
1486
|
-
`;
|
|
1762
|
+
`;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=x8(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}),N8(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=T8(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:D8(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=E8(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??z8(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 I8(_,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,F8(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 I8($,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 E8($){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 M8($,"name")??b.key??ym(v8(A))}function M8($,b){let A=new RegExp(`${b}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(A)?.[1]??null}function x8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function T8($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function D8($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function N8($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function F8($){return $.endsWith(`
|
|
1487
1763
|
`)?$:`${$}
|
|
1488
|
-
`}function dZ($){return $.replaceAll("\\","/").split("/").pop()??$}i();import{scanAllSpecsFromSource as iZ,scanSpecSource as pZ}from"@contractspec/module.workspace";import tZ from"micromatch";var K8={};h(K8,{validators:()=>oZ,urlSchema:()=>lZ,isValidVersion:()=>cZ,isValidIdentifier:()=>b8,isValidDotName:()=>w8,isTestFile:()=>j0,isLibraryDefinitionFile:()=>A0,emailSchema:()=>rZ});import I1 from"micromatch";function j0($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return I1.isMatch($,j)}function A0($){let W=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(I1.isMatch($,W))return!1;let j=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return I1.isMatch($,j)}import*as H$ from"zod";function b8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function w8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function cZ($){return Number.isInteger($)&&$>0}var rZ=H$.string().email(),lZ=H$.string().url(),oZ={specName:H$.string().refine(w8,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:H$.number().int().positive(),identifier:H$.string().refine(b8,{message:"Must be a valid TypeScript identifier"}),owner:H$.string().startsWith("@"),tag:H$.string().min(1)};function Q0($){return($??"").split("|").map((W)=>W.trim().replace(/^\.?\//,"")).filter(Boolean)}function aZ($){let W=$?.packages&&$.packages.length>0?$.packages:["**"],j=[...Q0($?.conventions.models),...Q0($?.conventions.operations),...Q0($?.conventions.events),...Q0($?.conventions.presentations),...Q0($?.conventions.forms)];return[...new Set(W.flatMap((A)=>{let Q=A==="**"?"":`${A}/`,Z=Y$.map((Y)=>`${Q}${Y}`),X=j.map((Y)=>`${Q}${Y}/**/*.ts`);return[...Z,...X]}))]}function sZ($,W,j){if($.specType==="unknown")return!1;if(W.type&&!j.includes($.specType))return!1;return!0}function eZ($,W){let j=$.filePath.localeCompare(W.filePath);if(j!==0)return j;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(W.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(W.discoveryId??W.key??"")}async function N$($,W={}){if(W.paths&&W.paths.length>0)return[...new Set(W.paths)].sort((j,A)=>j.localeCompare(A));if(W.pattern)return $.glob({cwd:W.cwd,pattern:W.pattern});return $.glob({cwd:W.cwd,patterns:aZ(W.config)})}async function QW($,W={}){let j=await N$($.fs,W),A=W.type?Array.isArray(W.type)?W.type:[W.type]:[],Q=[];for(let Z of j){if(W.config?.excludePackages&&tZ.isMatch(Z,W.config.excludePackages,{contains:!0}))continue;if(Z.includes("node_modules")||Z.includes("/dist/")||j0(Z,W.config)||A0(Z))continue;try{let X=await $.fs.readFile(Z),Y=iZ(X,Z),B=Y.length>0?Y:[pZ(X,Z)];for(let q of B)if(sZ(q,W,A))Q.push(q)}catch{}}return Q.sort(eZ)}function J$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function ZW($){let W=JSON.parse($),j=new Map,A=0,Q=0,Z=0,X=0,Y=0,B=0,q=0,H=0;for(let[G,J]of Object.entries(W)){let b=$6(G,J);j.set(G,b),A+=b.statements.total,Q+=b.statements.covered,Z+=b.branches.total,X+=b.branches.covered,Y+=b.functions.total,B+=b.functions.covered,q+=b.lines.total,H+=b.lines.covered}let V={statements:{covered:Q,total:A,pct:J$(Q,A)},branches:{covered:X,total:Z,pct:J$(X,Z)},functions:{covered:B,total:Y,pct:J$(B,Y)},lines:{covered:H,total:q,pct:J$(H,q)}};return{files:j,total:V}}function $6($,W){let j=Object.keys(W.statementMap).length,A=Object.values(W.s).filter((H)=>H>0).length,Q=Object.keys(W.fnMap).length,Z=Object.values(W.f).filter((H)=>H>0).length,X=0,Y=0;for(let H of Object.values(W.b))X+=H.length,Y+=H.filter((V)=>V>0).length;let B=new Set,q=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(B.add(G),(W.s[H]??0)>0)q.add(G);return{path:$,statements:{covered:A,total:j,pct:J$(A,j)},branches:{covered:Y,total:X,pct:J$(Y,X)},functions:{covered:Z,total:Q,pct:J$(Z,Q)},lines:{covered:q.size,total:B.size,pct:J$(q.size,B.size)}}}function M1($){switch($){case"istanbul":return{parse:ZW};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function E1($,W){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&W?.includes("cobertura"))return"cobertura";return"istanbul"}function N1($,W,j,A){let Q=[];if(j.statements!==void 0&&A.statements.pct<j.statements)Q.push({metric:"statements",required:j.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&A.branches.pct<j.branches)Q.push({metric:"branches",required:j.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&A.functions.pct<j.functions)Q.push({metric:"functions",required:j.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&A.lines.pct<j.lines)Q.push({metric:"lines",required:j.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Q.push({metric:"mutations",required:j.mutations,actual:0,message:`Mutation coverage required (${j.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:W,requirement:j,actual:A,passed:Q.length===0,failures:Q}}async function R1($,W,j){let{fs:A,logger:Q}=$,Z=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],B,q;for(let J of Y)if(await A.exists(J)){B=await A.readFile(J),q=J;break}if(!B)return Q.info("No coverage report found, skipping coverage checks"),Z;let H=E1(q??"coverage.json"),G=M1(H).parse(B);for(let J of W){if(J.specType!=="test-spec"||!J.key||!J.version||!J.sourceBlock)continue;let b=J.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!b||!b[1])continue;let w=b[1],L={},z=w.match(/statements\s*:\s*(\d+)/);if(z&&z[1])L.statements=parseInt(z[1],10);let S=w.match(/branches\s*:\s*(\d+)/);if(S&&S[1])L.branches=parseInt(S[1],10);let U=w.match(/functions\s*:\s*(\d+)/);if(U&&U[1])L.functions=parseInt(U[1],10);let O=w.match(/lines\s*:\s*(\d+)/);if(O&&O[1])L.lines=parseInt(O[1],10);if(Object.keys(L).length===0)continue;let K=N1(J.key,J.version,L,G.total);for(let _ of K.failures)Z.push({ruleId:"coverage-below-threshold",severity:"error",message:_.message,category:"coverage",file:J.filePath,context:{specKey:J.key,specVersion:J.version,metric:_.metric,required:_.required,actual:_.actual}})}return Z}import{addContractNode as W6,buildReverseEdges as j6,createContractGraph as A6,detectCycles as Q6,findMissingDependencies as Z6,parseImportedSpecNames as X6,toDot as Y6}from"@contractspec/module.workspace";async function _8($,W={}){let{fs:j}=$,A=await N$(j,{config:W.config,pattern:W.pattern}),Q=A6();for(let Y of A){let B=await j.readFile(Y),q=j.relative(".",Y),H=j.basename(Y).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",V=X6(B,Y);W6(Q,H,q,V)}j6(Q);let Z=Q6(Q),X=Z6(Q);return{graph:Q,total:Q.size,cycles:Z,missing:X}}function pJ($,W){return $.get(W)}function tJ($){return Y6($)}function aJ($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),A=W.filter((X)=>X.dependencies.length===0),Q=W.filter((X)=>X.dependents.length>0),Z=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:A.length,used:Q.length,unused:Z.length}}i();async function C1($,W){let j=[],A=await m($.fs),Q=await _8($,{config:A,pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" \u2192 ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let X of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${X}`,category:"deps",context:{contract:Z.contract,missing:X}});return j}import{analyzePackageDocBlocks as B6}from"@contractspec/module.workspace";var q6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function H6($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:q6}),A=new Map;for(let X of j){let Y=$.dirname(X),B=$.join(Y,"src");if(!await $.exists(B))continue;try{let q=JSON.parse(await $.readFile(X));A.set(Y,{packageName:q.name??$.relative(W,Y),packageRoot:Y,srcRoot:B})}catch{continue}}let Q=$.join(W,"package.json"),Z=$.join(W,"src");if(await $.exists(Q)&&await $.exists(Z))try{let X=JSON.parse(await $.readFile(Q));A.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:Z})}catch{}return[...A.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function XW($,W){let j=[],A=await H6($,W);for(let Q of A){let Z=B6({packageName:Q.packageName,srcRoot:Q.srcRoot});for(let X of Z.diagnostics)j.push({...X,packageName:Q.packageName,packageRoot:Q.packageRoot,srcRoot:Q.srcRoot})}return j}async function D1($,W){let j=W.workspaceRoot??process.cwd();return(await XW($.fs,j)).map((Q)=>({ruleId:Q.ruleId,severity:Q.severity==="warning"?"warning":"error",message:Q.message,category:"docs",file:Q.file,line:Q.line,column:Q.column,context:{packageName:Q.packageName,packageRoot:Q.packageRoot,...Q.context}}))}async function T1($,W,j){let A=[],Q=await V6($,W);if(A.push(Q),Q.status==="pass")A.push(await G6($,W,j));return A}async function V6($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");try{if(!await $.exists(j))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let Q=await $.readFile(j),Z=JSON.parse(Q),X=Z.aiProvider??"claude",Y=Z.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${X}, Model: ${Y}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function G6($,W,j){let A=$.join(W.workspaceRoot,".contractsrc.json");try{let Q=await $.readFile(A),X=JSON.parse(Q).aiProvider??"claude",B={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!B)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[B])return{category:"ai",name:"API Key",status:"pass",message:`${B} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${B} not set`,details:`Set ${B} in your environment to use AI features`,fix:j?{description:`Set ${B} environment variable`,apply:async()=>{let H=await j.input(`Enter your ${X} API key:`,{password:!0});if(!H)return{success:!1,message:"No API key provided"};let V=$.join(W.workspaceRoot,".env");try{let G="";if(await $.exists(V)){if(G=await $.readFile(V),G.includes(`${B}=`))return{success:!1,message:`${B} already in .env, update manually`};G+=`
|
|
1489
|
-
`}return
|
|
1490
|
-
`,await $.writeFile(
|
|
1764
|
+
`}function v8($){return $.replaceAll("\\","/").split("/").pop()??$}s();import{scanAllSpecsFromSource as h8,scanSpecSource as c8}from"@contractspec/module.workspace";import d8 from"micromatch";var Ew={};P(Ew,{validators:()=>f8,urlSchema:()=>r8,isValidVersion:()=>k8,isValidIdentifier:()=>Cw,isValidDotName:()=>Iw,isTestFile:()=>Ob,isLibraryDefinitionFile:()=>Vb,emailSchema:()=>P8});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 k8($){return Number.isInteger($)&&$>0}var P8=q$.string().email(),r8=q$.string().url(),f8={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 u8($){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 o8($,b,A){if($.specType==="unknown")return!1;if(b.type&&!A.includes($.specType))return!1;return!0}function i8($,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:u8(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&&d8.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=h8(w,W),y=j.length>0?j:[c8(w,W)];for(let B of y)if(o8(B,b,m))n.push(B)}catch{}}return n.sort(i8)}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=l8(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 l8($,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 t8,buildReverseEdges as p8,createContractGraph as a8,detectCycles as e8,findMissingDependencies as s8,parseImportedSpecNames as $9,toDot as b9}from"@contractspec/module.workspace";async function Mw($,b={}){let{fs:A}=$,m=await g$(A,{config:b.config,pattern:b.pattern}),n=a8();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=$9(y,j);t8(n,S,B,Q)}p8(n);let W=e8(n),w=s8(n);return{graph:n,total:n.size,cycles:W,missing:w}}function Hq($,b){return $.get(b)}function qq($){return b9($)}function Oq($){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(" \u2192 ")}`,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 A9}from"@contractspec/module.workspace";var m9=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function n9($,b){let A=await $.glob({pattern:"packages/**/package.json",cwd:b,ignore:m9}),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 n9($,b);for(let n of m){let W=A9({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 w9($,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 w9($,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+=`
|
|
1765
|
+
`}return Z+=`${y}=${S}
|
|
1766
|
+
`,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 j9}from"child_process";import{promisify as y9}from"util";var NA=y9(j9);async function qm($,b){let A=[];return A.push(await B9(b)),A.push(await S9(b)),A.push(await Q9($,b)),A}async function B9($){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 S9($){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 Q9($,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 Z9,relative as G9}from"path";var X9="contractspec",Y9="contractsrc.schema.json";function H9($){let b=$.replaceAll("\\","/");return b.startsWith(".")?b:`./${b}`}function Kb($){return H9(G9($.configRoot,Z9($.workspaceRoot,"node_modules",X9,Y9)))}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 Fq($){return $.startsWith("builder-")}function vq($){return $==="connect"}function gw($){let b=U$($),A=q9($.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 q9($){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=O9($),n=V9($);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
|
|
1491
1767
|
|
|
1492
1768
|
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1493
1769
|
|
|
@@ -1508,10 +1784,10 @@ Check the appropriate level based on the feature scope.
|
|
|
1508
1784
|
## Contract Locations
|
|
1509
1785
|
|
|
1510
1786
|
Contracts are located in:
|
|
1511
|
-
- \`${
|
|
1512
|
-
- \`${
|
|
1513
|
-
- \`${
|
|
1514
|
-
- \`${
|
|
1787
|
+
- \`${m}/operations/\` - Command and query specs
|
|
1788
|
+
- \`${m}/events/\` - Event specs
|
|
1789
|
+
- \`${m}/presentations/\` - UI presentation specs
|
|
1790
|
+
- \`${m}/features/\` - Feature module specs
|
|
1515
1791
|
|
|
1516
1792
|
## When Making Changes
|
|
1517
1793
|
|
|
@@ -1520,6 +1796,14 @@ Contracts are located in:
|
|
|
1520
1796
|
3. **If no contract**: Create a new contract using \`contractspec create\`.
|
|
1521
1797
|
4. **After changes**: Validate with \`contractspec validate\`.
|
|
1522
1798
|
|
|
1799
|
+
## Adoption Engine
|
|
1800
|
+
|
|
1801
|
+
- Reuse existing workspace code before inventing a new local surface.
|
|
1802
|
+
- Prefer ContractSpec OSS packages before reaching for raw framework or vendor primitives.
|
|
1803
|
+
- Use \`contractspec connect adoption sync\` to mirror the local catalog.
|
|
1804
|
+
- Use \`contractspec connect adoption resolve --family <family> --stdin\` to resolve the recommended reuse target.
|
|
1805
|
+
- If Connect says \`rewrite\`, reuse the existing workspace or ContractSpec candidate instead of creating a duplicate.
|
|
1806
|
+
|
|
1523
1807
|
## Key Commands
|
|
1524
1808
|
|
|
1525
1809
|
- \`contractspec create\` - Scaffold new specs
|
|
@@ -1539,13 +1823,13 @@ defineCommand({
|
|
|
1539
1823
|
});
|
|
1540
1824
|
\`\`\`
|
|
1541
1825
|
|
|
1542
|
-
## Rules for ${
|
|
1826
|
+
## Rules for ${b}
|
|
1543
1827
|
|
|
1544
1828
|
- All API endpoints must have a corresponding operation contract.
|
|
1545
1829
|
- Events must be declared in contracts before being emitted.
|
|
1546
1830
|
- UI components should reference presentation contracts.
|
|
1547
1831
|
- Feature flags should be defined in feature modules.
|
|
1548
|
-
`}function
|
|
1832
|
+
`}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?`
|
|
1549
1833
|
## Monorepo Scope
|
|
1550
1834
|
|
|
1551
1835
|
This guide is scoped to the current package.
|
|
@@ -1559,7 +1843,7 @@ This guide is scoped to the workspace root.
|
|
|
1559
1843
|
- Prefer the nearest package guide when working inside a specific package.
|
|
1560
1844
|
`:"";return`# ContractSpec AI Guide
|
|
1561
1845
|
|
|
1562
|
-
Scope: \`${
|
|
1846
|
+
Scope: \`${n}\`
|
|
1563
1847
|
|
|
1564
1848
|
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1565
1849
|
|
|
@@ -1569,7 +1853,7 @@ This project uses ContractSpec for spec-first development. Treat contracts as th
|
|
|
1569
1853
|
- Validate contracts after changes with \`contractspec validate\`.
|
|
1570
1854
|
- Regenerate derived artifacts before considering the work complete.
|
|
1571
1855
|
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1572
|
-
${
|
|
1856
|
+
${w}
|
|
1573
1857
|
## Contract Locations
|
|
1574
1858
|
|
|
1575
1859
|
- \`src/contracts/operations/\` - command and query specs
|
|
@@ -1596,20 +1880,55 @@ ${X}
|
|
|
1596
1880
|
- Keep changes spec-first, deterministic, and reviewable.
|
|
1597
1881
|
- Do not change generated outputs without updating their source contract.
|
|
1598
1882
|
- When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
|
|
1883
|
+
- Reuse existing workspace code before creating new files, packages, or dependencies.
|
|
1884
|
+
- Prefer ContractSpec OSS packages by family:
|
|
1885
|
+
- UI: local reusable UI -> \`@contractspec/lib.design-system\` -> platform ui-kit -> shadcn/web fallback
|
|
1886
|
+
- Contracts: existing local spec -> \`@contractspec/lib.contracts-spec\` / \`@contractspec/lib.schema\`
|
|
1887
|
+
- Integrations/runtime/shared libs: existing workspace surface -> ContractSpec OSS catalog -> reviewed fallback
|
|
1888
|
+
- Use \`contractspec connect adoption sync\` and \`contractspec connect adoption resolve --family <family>\` when the right reusable surface is unclear.
|
|
1599
1889
|
|
|
1600
1890
|
## Initialization Preset
|
|
1601
1891
|
|
|
1602
|
-
- This workspace was initialized with the \`${
|
|
1603
|
-
`}function
|
|
1604
|
-
`}async function v1($,W){let j=[];return j.push(await N6($,W)),j.push(await R6($,W)),j.push(await C6($,W)),j.push(await D6($,W)),j.push(await T6($,W)),j.push(await F6($,W)),j.push(await x6($,W)),j}async function R$($,W){if(W.packageRoot&&W.packageRoot!==W.workspaceRoot&&await $.exists($.join(W.packageRoot,".contractsrc.json")))return W.packageRoot;return W.workspaceRoot}async function N6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(await $.exists(j))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let Q=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(Q)),{success:!0,message:"Created .contractsrc.json"}}catch(Q){return{success:!1,message:`Failed to create: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function R6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j);return JSON.parse(Q),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Q){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Q instanceof Error?Q.message:String(Q),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function C6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=[];if(!Z.outputDir)X.push("outputDir");if(!Z.conventions)X.push("conventions");if(X.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${X.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let Y=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let B of X)if(Y[B]!==void 0)Z[B]=Y[B];return await $.writeFile(j,F(Z)),{success:!0,message:"Added missing fields"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function D6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:Z.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return Z.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,F(Z)),{success:!0,message:"Added versioning configuration"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function T6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.hooks){let B=Z.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(B).length} git hook(s) configured`}}let X=$.join(W.workspaceRoot,".husky");if(await $.exists(X))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return Z.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,F(Z)),{success:!0,message:"Added hooks configuration"}}catch(B){return{success:!1,message:`Failed: ${B instanceof Error?B.message:String(B)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function F6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(Q==="connect"){let Y=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((H)=>H!==null),B=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(Y.length===0&&!B)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...Y,...B?["connect.studio.endpoint"]:[]].join(", ")}`}}let Z=[],X=A.builder?.api?.controlPlaneTokenEnvVar;if((Q==="builder-managed"||Q==="builder-hybrid")&&!A.builder?.api?.baseUrl)Z.push("builder.api.baseUrl");if((Q==="builder-managed"||Q==="builder-hybrid")&&!X)Z.push("builder.api.controlPlaneTokenEnvVar");if((Q==="builder-managed"||Q==="builder-hybrid")&&X&&!process.env[X])Z.push(`env:${X}`);if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)Z.push("builder.localRuntime.runtimeId");if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)Z.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:Z.length===0?"pass":"warn",message:Z.length===0?`Builder preset inferred (${Q}) and required config is present`:`Builder preset inferred (${Q}) but setup is missing ${Z.join(", ")}`}}async function x6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q!=="builder-managed"&&Q!=="builder-hybrid")return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder managed/hybrid preset is not enabled"};let Z=$.join(j,".vscode","settings.json"),X=A.builder?.api?.baseUrl;if(!X)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let Y=await $.readFile(Z).catch(()=>""),B=Y?r(Y):void 0;if(B?.["contractspec.api.baseUrl"]===X)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let H=$.join(j,".vscode");if(!await $.exists(H))await $.mkdir(H);let V={...B??{},...BW({workspaceRoot:W.workspaceRoot,packageRoot:W.packageRoot,isMonorepo:W.isMonorepo,packageName:W.packageName,interactive:!1,preset:Q,targets:[],builderApiBaseUrl:X})};return await $.writeFile(Z,F(V)),{success:!0,message:"Updated VS Code settings mirror"}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}}}import{exec as y6}from"child_process";import{promisify as v6}from"util";var C$=v6(y6);async function m1($,W){let j=[];return j.push(await m6(W)),j.push(await P6(W)),j.push(await k6($,W)),j.push(await h6($,W)),j.push(await g6($,W)),j}async function m6($){try{let{stdout:W}=await C$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${W.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function P6($){try{let{stdout:W}=await C$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${W.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function k6($,W){let j=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:Q,name:Z}of j){let X=$.join(W.workspaceRoot,Q);if(await $.exists(X)){A=Z;break}}if(!A){let Q=$.join(W.workspaceRoot,".."),Z=$.join(W.workspaceRoot,"../.."),X=[Q,Z];for(let Y of X){for(let{file:B,name:q}of j){let H=$.join(Y,B);if(await $.exists(H)){A=q;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await C$(`${A} --version`,{cwd:W.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function h6($,W){let j=$.join(W.workspaceRoot,"node_modules");if(await $.exists(j))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await C$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function g6($,W){let j=$.join(W.workspaceRoot,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A),Z={...Q.dependencies,...Q.devDependencies};if("@contractspec/lib.contracts-spec"in Z)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${Z["@contractspec/lib.contracts-spec"]})`};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await C$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function P1($,W){let j=await XW($,W.workspaceRoot);if(j.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return j.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(W.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as f6,isFeatureFile as u6,scanAllSpecsFromSource as d6,scanExampleSource as n6,scanFeatureSource as c6}from"@contractspec/module.workspace";function r6(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function VW($,W={}){let{fs:j,logger:A}=$,Q=r6(),Z=W.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let X=await j.glob({pattern:Z});for(let B of X){if(B.includes("node_modules")||B.includes("/dist/"))continue;try{let q=await j.readFile(B);if(u6(B)){let H=c6(q,B);Q.features.set(H.key,H);continue}if(f6(B)){let H=n6(q,B);Q.examples.set(H.key,H);continue}if(B.includes(".app-config.")||B.includes(".blueprint.")){let H=d6(q,B);for(let V of H)if(V.specType==="app-config"&&V.key)Q.appConfigs.set(V.key,V)}}catch{}}try{let B=await j.glob({pattern:"**/.contractsrc.json"});for(let q of B){if(q.includes("node_modules"))continue;try{let H=await j.readFile(q),V=JSON.parse(H);Q.workspaceConfigs.set(q,{file:q,config:V,valid:!0,errors:[]})}catch(H){Q.workspaceConfigs.set(q,{file:q,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Q.features.size,examples:Q.examples.size,appConfigs:Q.appConfigs.size,workspaceConfigs:Q.workspaceConfigs.size,total:Q.features.size+Q.examples.size+Q.appConfigs.size+Q.workspaceConfigs.size};return A.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Q,stats:Y}}function yb($){let W=[];for(let[j,A]of $.features)W.push({key:j,file:A.filePath,type:"feature"});for(let[j,A]of $.examples)W.push({key:j,version:A.version,file:A.filePath,type:"example"});for(let[j,A]of $.appConfigs)W.push({key:j,version:A.version,file:A.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function GW($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function k1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function JW($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let A=await $.readFile(j),Q=JSON.parse(A);return{version:typeof Q.version==="number"&&Number.isFinite(Q.version)?Q.version:1,criticalPackages:k1(Q.criticalPackages).map(GW),criticalFeatureKeys:k1(Q.criticalFeatureKeys),smokePackages:k1(Q.smokePackages)}}catch{return}}function T8($,W){let j=GW($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function F8($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function d$($){return GW(`${GW($)}/config/stability-policy.json`)}async function h1($,W){let j=[],A=await JW($,W.workspaceRoot),Q=await VW({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(l6(Q.stats.features)),j.push(o6(Q.stats.examples)),j.push(i6(Q.inventory.features,A,W)),j.push(p6(Q.inventory.examples)),j.push(t6(Q.inventory.workspaceConfigs)),j}function l6($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function o6($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function i6($,W,j){let A=[],Q=[];for(let[Z,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(F8(Z,W))Q.push(Z);else A.push(Z);if(Q.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Q.length>0?"fail":"warn",message:Q.length>0?`${Q.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:Q.length>0?`Critical features: ${Q.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:Q,missingFeatures:A}}}function p6($){let W=[];for(let[j,A]of $)if(!A.entrypoints.packageName)W.push(j);if(W.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${W.length} example(s) missing packageName`,details:`Examples: ${W.join(", ")}`}}function t6($){let W=[];for(let[,j]of $)if(!j.valid)W.push(j.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(W.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${W.length} workspace config(s) invalid`,details:`Files: ${W.join(", ")}`}}async function g1($,W){let j=[];return j.push(await a6($,W)),j.push(await s6($,W)),j.push(await e6($,W)),j}async function a6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(await $.exists(j))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let Q=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Q))await $.mkdir(Q);let Z=q0();return await $.writeFile(j,F(Z)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function s6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(!await $.exists(j))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let Y=q0(),B=p(Z,Y);return await $.writeFile(j,F(B)),{success:!0,message:"Registered MCP server"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function e6($,W){let j=qW();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Q=await $.readFile(j);if(JSON.parse(Q).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var $7=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],x8=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function W7($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,A])=>{if(typeof A==="string")W[j]=A;return W},{})}function j7($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function A7($,W,j){let A=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:x8}),Q=[];for(let Z of A){let X=$.dirname(Z),Y=$.relative(W,X);try{let B=JSON.parse(await $.readFile(Z)),q=W7(B.scripts),H=await $.glob({patterns:$7,cwd:X,ignore:x8});Q.push({packageName:B.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof q.build==="string",hasTypecheckScript:typeof q.typecheck==="string",hasLintScript:typeof q.lint==="string"||typeof q["lint:check"]==="string",hasTestScript:typeof q.test==="string",usesPassWithNoTests:j7(q),testFileCount:H.length,tier:T8(Y,j)})}catch{continue}}return Q}function Q7($){let W=[];if(!$.hasBuildScript)W.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)W.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)W.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)W.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)W.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)W.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return W}function Z7($){let W=[];if($.testFileCount>0&&!$.hasTestScript)W.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)W.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return W}async function y8($,W,j){let A=await A7($,W,j),Q=[];for(let X of A){if(X.tier==="critical")Q.push(...Q7(X));Q.push(...Z7(X))}let Z=A.filter((X)=>X.tier==="critical").map((X)=>({packageName:X.packageName,packagePath:X.packagePath,hasBuildScript:X.hasBuildScript,hasTypecheckScript:X.hasTypecheckScript,hasLintScript:X.hasLintScript,hasTestScript:X.hasTestScript,usesPassWithNoTests:X.usesPassWithNoTests,testFileCount:X.testFileCount}));return{findings:Q,criticalPackages:Z}}function m8($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function v8($,W,j,A){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let Q=W.filter((Z)=>{return Z.tier==="critical"||j.has(Z.code)});return{category:"workspace",name:$,status:Q.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:m8(W),context:{findings:W}}}async function P8($,W){let j=await JW($,W.workspaceRoot);if(!j)return[];let A=await y8($,W.workspaceRoot,j),Q=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),Z=A.findings.filter((B)=>Q.has(B.code)),X=A.findings.filter((B)=>B.code==="tests-without-test-script"),Y=A.findings.filter((B)=>B.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:Z.length>0?"fail":"pass",message:Z.length>0?`${Z.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:Z.length>0?m8(Z):W.verbose?`Policy: ${d$(W.workspaceRoot)}`:void 0,context:{policyPath:d$(W.workspaceRoot),criticalPackages:A.criticalPackages,findings:Z}},v8("Package Test Scripts",X,new Set,"All tested packages expose a test script"),v8("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var X7=["src/contracts","contracts","src/specs","specs"];async function f1($,W){let j=[];return j.push(Y7(W)),j.push(await B7($,W)),j.push(await q7($,W)),j.push(await H7($,W)),j.push(await G7($,W)),j.push(...await P8($,W)),j}function Y7($){if($.isMonorepo){let W=$.packageName?` in package "${$.packageName}"`:"",j=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${W}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${j}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function B7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let A of j){let Q=$.join(A,"package.json");if(await $.exists(Q))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function q7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],A=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of X7){let B=$.join(X,Y);if(await $.exists(B)){let q=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${q} level`:void 0}}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let Q=W.isMonorepo?"src/contracts":"src/contracts",Z=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Q}/${Z} to organize your specs`,fix:{description:`Create ${Q}/ directory${Z}`,apply:async()=>{try{let X=$.join(A,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Q}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function H7($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=W.isMonorepo?W.packageRoot:W.workspaceRoot,Q=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:A});if(Q.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Q.length} contract file(s)${X}`,details:W.verbose?Q.slice(0,5).join(", "):void 0}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:W.isMonorepo?`No contract files found in package "${W.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function V7($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let A=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:W.packageRoot,level:"package"}}let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{path:j,root:W.workspaceRoot,level:"workspace"};return null}async function G7($,W){try{let j=await V7($,W);if(!j)return{category:"workspace",name:"Output Directory",status:"skip",message:W.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(j.path),Q=JSON.parse(A),Z=Q.outputDir??"./src",X=$.join(j.root,Z),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${Z}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let q=Z==="./src"||Z==="src",H=Array.isArray(Q.packages)&&Q.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&q&&(H||j.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:W.verbose?`Resolved default output to packages via ${j.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${Z}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${Z} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${Z}`}}catch(V){return{success:!1,message:`Failed: ${V instanceof Error?V.message:String(V)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var k8=["cli","config","mcp","deps","docs","workspace","ai","layers"],h8={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var J7={checks:{runCliChecks:F1,runConfigChecks:v1,runMcpChecks:g1,runDepsChecks:m1,runDocChecks:P1,runWorkspaceChecks:f1,runAiChecks:T1,runLayerChecks:h1},workspace:{findWorkspaceRoot:D,findPackageRoot:f,isMonorepo:e$,getPackageName:I$}},b7={confirm:async()=>!1,input:async()=>""};async function g8($,W,j=b7,A=J7){let{fs:Q,logger:Z}=$,X=W.categories??k8,{checks:Y,workspace:B}=A,q=B.findWorkspaceRoot(W.workspaceRoot),H=B.findPackageRoot(W.workspaceRoot),V=B.isMonorepo(q),G=V?B.getPackageName(H):void 0,J={workspaceRoot:q,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let U=G?` (package: ${G})`:"";Z.info(`Detected monorepo${U}`)}let b=[];for(let U of X){if(W.skipAi&&U==="ai")continue;Z.info(`Checking ${h8[U]}...`);let O=await w7(U,Q,J,j,Y);for(let K of O){if(K.fix&&(K.status==="fail"||K.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${K.name}"? ${K.fix.description}`)){Z.info(`Applying fix: ${K.fix.description}`);let I=await K.fix.apply();if(I.success)Z.info(`\u2713 ${I.message}`),K.status="pass",K.message=`Fixed: ${I.message}`,K.fix=void 0;else Z.warn(`\u2717 ${I.message}`)}}b.push(K)}}let w=b.filter((U)=>U.status==="pass").length,L=b.filter((U)=>U.status==="warn").length,z=b.filter((U)=>U.status==="fail").length,S=b.filter((U)=>U.status==="skip").length;return{checks:b,passed:w,warnings:L,failures:z,skipped:S,healthy:z===0}}async function w7($,W,j,A,Q){switch($){case"cli":return Q.runCliChecks(W,j);case"config":return Q.runConfigChecks(W,j);case"mcp":return Q.runMcpChecks(W,j);case"deps":return Q.runDepsChecks(W,j);case"docs":return Q.runDocChecks(W,j);case"workspace":return Q.runWorkspaceChecks(W,j);case"ai":return Q.runAiChecks(W,j,A);case"layers":return Q.runLayerChecks(W,j);default:return[]}}function Bw($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("\u2713 All checks passed!");else W.push("\u2717 Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
`).length},X,Y=new RegExp(V0.contractHandler);while((X=Y.exec($))!==null)if(X[1])Q(X[1],"handler",Z(X.index));let B=new RegExp(V0.typeofSpec);while((X=B.exec($))!==null)if(X[1])Q(X[1],"typeof",Z(X.index));let q=new RegExp(V0.namedImport);while((X=q.exec($))!==null){let J=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(J)for(let b of J)Q(b,"import",Z(X.index))}let H=new RegExp(V0.defaultImport);while((X=H.exec($))!==null)if(X[1])Q(X[1],"import",Z(X.index));let V=new RegExp(V0.specAssignment);while((X=V.exec($))!==null)if(X[1])Q(X[1],"unknown",Z(X.index));return j}var l8=["**/*.ts(x)"];async function _W($,W,j={}){let{fs:A}=W,Q=j.includePatterns??l8,Z=j.excludePatterns??[...new Set([...S$,...Y$])],X=[];for(let Y of Q){let B=await A.glob({pattern:Y,ignore:Z});for(let q of B)try{let H=await A.readFile(q),G=r8(H,q).filter((J)=>J.specKey===$);X.push(...G)}catch{}}return X}async function rw($,W={}){let{fs:j}=$,A=W.includePatterns??l8,Q=W.excludePatterns??[...new Set([...S$,...Y$])],Z=new Map;for(let X of A){let Y=await j.glob({pattern:X,ignore:Q});for(let B of Y)try{let q=await j.readFile(B),H=r8(q,B);for(let V of H){let G=Z.get(V.specKey)??[];G.push(V),Z.set(V.specKey,G)}}catch{}}return Z}function h7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o8($,W,j){let A=h7(W),Q=[];if($==="operation")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")Q.push({path:`${j}/components/${A}.tsx`,type:"component"}),Q.push({path:`${j}/components/${A}.test.tsx`,type:"test"});if($==="form")Q.push({path:`${j}/forms/${A}.form.tsx`,type:"form"}),Q.push({path:`${j}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});return Q}import{Node as c,Project as g7,SyntaxKind as f7}from"ts-morph";function i8($){let W=[],A=new g7({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Q=(B)=>{if(!c.isObjectLiteralExpression(B))return;let q=B.getProperty("implementations");if(q&&c.isPropertyAssignment(q)){let H=q.getInitializer();if(H&&c.isArrayLiteralExpression(H)){for(let V of H.getElements())if(c.isObjectLiteralExpression(V)){let G,J,b,w=V.getProperty("path");if(w&&c.isPropertyAssignment(w)){let S=w.getInitializer();if(c.isStringLiteral(S))G=S.getLiteralText()}let L=V.getProperty("type");if(L&&c.isPropertyAssignment(L)){let S=L.getInitializer();if(c.isStringLiteral(S))J=S.getLiteralText()}let z=V.getProperty("description");if(z&&c.isPropertyAssignment(z)){let S=z.getInitializer();if(c.isStringLiteral(S))b=S.getLiteralText()}if(G&&J)W.push({path:G,type:J,description:b})}}}},Z=A.getDescendantsOfKind(f7.CallExpression);for(let B of Z){let q=B.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(q)){let H=B.getArguments();if(H.length>0&&c.isObjectLiteralExpression(H[0]))return Q(H[0]),W}}let X=A.getVariableStatements();for(let B of X)if(B.isExported())for(let q of B.getDeclarations()){let H=q.getInitializer();if(H&&c.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Q(H),W}}let Y=A.getExportAssignment((B)=>!B.isExportEquals());if(Y){let B=Y.getExpression();if(c.isObjectLiteralExpression(B))Q(B);else if(c.isAsExpression(B)&&c.isObjectLiteralExpression(B.getExpression()))Q(B.getExpression())}return W}function p8($){if($.length===0)return"missing";let W=$.filter((Q)=>Q.exists),j=$.filter((Q)=>Q.type!=="test");if(W.filter((Q)=>Q.type!=="test").length===0)return"missing";if($.every((Q)=>Q.exists))return"implemented";return"partial"}function tw($){let W=$.filter((Q)=>Q.status==="implemented").length,j=$.filter((Q)=>Q.status==="partial").length,A=$.filter((Q)=>Q.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:A,coverage:$.length>0?Math.round(W/$.length*100):100}}var n7={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function t8($){return u7("sha256").update($).digest("hex")}async function c7($,W,j,A={},Q){let Z={...n7,...A},X=Z.computeHashes?t8($.sourceBlock||""):void 0,Y=$.key??d7.basename($.filePath).replace(/\.[jt]s$/,""),B=$.version??"1.0.0",{fs:q}=W,H=[],V=new Set,G=async(b,w,L,z)=>{if(V.has(b))return;V.add(b);let S=await q.exists(b),U=void 0,O=void 0;if(S&&Z.computeHashes)try{U=await q.readFile(b),O=t8(U)}catch{}H.push({path:b,type:w,source:L,exists:S,implementationSourceContent:U,implementationSourceHash:O,description:z})};if(Z.includeExplicit&&$.sourceBlock){if(Q)Q.suffixText="Discover explicit implementations";let b=i8($.sourceBlock);for(let w of b)await G(w.path,w.type,"explicit",w.description)}if(Z.includeDiscovered){if(Q)Q.suffixText="Discover implementations";let b=await _W(Y,W,Z);for(let w of b){if(w.filePath===$.filePath)continue;await G(w.filePath,w.inferredType,"discovered")}}if(Z.includeConvention){if(Q)Q.suffixText="Discover implementations based on conventions";let b=Z.outputDir??j.outputDir??"./src",w=o8($.specType,Y,b);for(let{path:L,type:z}of w)await G(L,z,"convention")}if(Q)Q.suffixText="Determine implementation status";let J=p8(H);return{specKey:Y,specVersion:B,specPath:$.filePath,specType:$.specType,implementations:H,status:J,specHash:X}}async function a8($,W,j,A={},Q){let Z=[];for(let X of $){if(Q)Q.text=`Resolving implementation... (${Z.length}/${$.length})`;try{let Y=await c7(X,W,j,A,Q);Z.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return Z}async function o1($,W,j){let{fs:A}=$,Q=[],Z=await m(A),X=j.implementation??{},Y=W.filter((q)=>q.specType==="operation"),B=await a8(Y,{fs:A},Z,{computeHashes:X.useCache??!0});for(let q of B){if(X.requireImplemented&&q.status==="missing")Q.push({ruleId:"impl-missing",severity:"error",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});else if(q.status==="missing")Q.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});if(!X.allowPartial&&q.status==="partial"){let V=q.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Q.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${q.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status,missingFiles:V}})}let H=q.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Q.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${q.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,missingTests:H.map((V)=>V.path)}})}return Q}import{isFeatureFile as o7,scanAllSpecsFromSource as i7,scanFeatureSource as p7}from"@contractspec/module.workspace";function r7($,W){return`${$}.v${W}`}function i1($,W,j,A,Q,Z={}){let{treatMissingAsError:X=!0}=Z;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],B=[],q=[];for(let H of A){let V=r7(H.key,H.version);if(Q.has(V))Y.push(H);else if(B.push(H),X)q.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:B.length===0,foundTests:Y,missingTests:B,errors:q,specFile:$}}function s8($,W){return`${$}.v${W}`}function e8($,W){let j=new Map,A=new Map,Q=[],Z=[];for(let X of $){if(!X.key||!X.version)continue;let Y=s8(X.key,X.version);if(!X.testTarget){Z.push(Y);continue}let{type:B,key:q,version:H}=X.testTarget,V=H??X.version,G=s8(q,V),J=l7(W,B);if(!J||!J.has(G)){Q.push(Y);continue}if(A.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:A,orphanedTests:Q,testsWithoutTarget:Z}}function l7($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function t($,W){return`${$}.v${W}`}function t7(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function p1($,W){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[W]}async function zW($,W={}){let{fs:j,logger:A}=$;A.info("Starting integrity analysis...",{options:W});let Q=await N$(j,{config:W.config,cwd:W.cwd,pattern:W.pattern}),Z=t7(),X=[],Y=[];for(let K of Q){if((await j.stat(K)).isDirectory)continue;let I=await j.readFile(K);if(o7(K)){let M=p7(I,K);X.push(M)}else{let M=i7(I,K);for(let E of M)if(E.specType!=="unknown"&&E.specType!=="feature"){let C=p1(Z,E.specType);if(C&&E.key&&E.version!==void 0){let R=t(E.key,E.version);C.set(R,{key:E.key,version:E.version,file:E.filePath,type:E.specType,stability:E.stability,testTarget:E.testTarget,testCoverage:E.testCoverage})}}}}let B=W.featureKey?X.filter((K)=>K.key===W.featureKey):X,q=new Set;for(let K of B){for(let _ of K.operations){let I=t(_.key,_.version);if(q.add(`operation:${I}`),!Z.operations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_})}for(let _ of K.events){let I=t(_.key,_.version);if(q.add(`event:${I}`),!Z.events.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"event",ref:_})}for(let _ of K.presentations){let I=t(_.key,_.version);if(q.add(`presentation:${I}`),!Z.presentations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_})}for(let _ of K.experiments){let I=t(_.key,_.version);if(q.add(`experiment:${I}`),!Z.experiments.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"experiment",ref:_})}for(let _ of K.capabilities.provides){let I=t(_.key,_.version);if(q.add(`capability:${I}`),!Z.capabilities.has(I))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"capability",ref:_})}for(let _ of K.capabilities.requires){let I=t(_.key,_.version);q.add(`capability:${I}`)}for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=t(_.pres.key,_.pres.version);if(!Z.operations.has(I))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${_.op.key}.v${_.op.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op});if(!Z.presentations.has(M))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${_.pres.key}.v${_.pres.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_.pres})}if(K.presentationsTargets)for(let _ of K.presentationsTargets){let I=t(_.key,_.version);if(!Z.presentations.has(I))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:{key:_.key,version:_.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let K of V){let _=p1(Z,K);if(!_)continue;for(let[I,M]of _)if(!q.has(`${K}:${I}`))H.push(M),Y.push({severity:"warning",type:"orphaned",message:`${K} ${M.key}.v${M.version} is not linked to any feature`,file:M.file,specKey:M.key,specType:M.type})}let G=[];for(let[,K]of Z.testSpecs)G.push({filePath:K.file,specType:"test-spec",key:K.key,version:K.version,testTarget:K.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let J=e8(G,Z);for(let K of B)for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=J.targetToTests.get(I),E=!1,C=!1;if(M)for(let R of M){let v=Z.testSpecs.get(R);if(v?.testCoverage){if(v.testCoverage.hasSuccess)E=!0;if(v.testCoverage.hasError)C=!0}}if(!M||!E||!C){let R=[];if(!E)R.push("success scenario");if(!C)R.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${_.op.key}.v${_.op.version} linked to presentation requires tests covering: ${R.join(", ")}`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op})}}let b={},w=0;for(let K of V){let _=p1(Z,K);if(!_)continue;let I=_.size,M=0,E=0,C=W.requireTestsFor?.includes(K);for(let[R,v]of _){if(q.has(`${K}:${R}`))M++;if(C){let x=t(v.key,v.version),L$=J.targetToTests.has(x),v0=`${v.key}.test`,zA=Z.testSpecs.has(t(v0,v.version));if(!L$&&!zA)E++,w++,Y.push({severity:"warning",type:"missing-test",message:`${K} ${v.key}.v${v.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:v.file,specKey:v.key,specType:v.type})}}b[K]={total:I,covered:M,orphaned:I-M,missingTest:C?E:0}}let L=Object.values(b).reduce((K,_)=>K+_.total,0),z=Object.values(b).reduce((K,_)=>K+_.covered,0),S={total:L,linkedToFeature:z,orphaned:L-z,missingTest:w,byType:b},O=!Y.some((K)=>K.severity==="error");return A.info("Integrity analysis complete",{features:X.length,totalSpecs:L,orphaned:H.length,issues:Y.length,healthy:O}),{inventory:Z,features:B,coverage:S,issues:Y,orphanedSpecs:H,healthy:O}}function _K($){let W=[];for(let j of Object.values($))for(let A of j.values())W.push(A);return W}function zK($,W){return $.filter((j)=>j.type===W)}function UK($,W){return $.filter((j)=>j.severity===W)}i();async function t1($,W){let j=[],A=await m($.fs),Q=await zW($,{config:A,pattern:W.pattern,all:!0});for(let Z of Q.issues)j.push({ruleId:`integrity-${Z.type}`,severity:Z.severity==="error"?"error":"warning",message:Z.message,category:"integrity",file:Z.file,context:{specKey:Z.specKey,specType:Z.specType,featureKey:Z.featureKey,ref:Z.ref}});return j}async function a1($,W){let j=[],A=await VW($,{});for(let[Q,Z]of A.inventory.features){if(!Z.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Q}' missing 'owners' field`,category:"layers",file:Z.filePath,context:{key:Q}});if(Z.operations.length===0&&Z.events.length===0&&Z.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Q}' has no operations, events, or presentations`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let[Q,Z]of A.inventory.examples){if(!Z.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Q}' missing 'packageName' in entrypoints`,category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.surfaces.templates&&!Z.surfaces.sandbox.enabled&&!Z.surfaces.studio.enabled&&!Z.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Q}' has no enabled surfaces`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let Q of A.inventory.workspaceConfigs.values())if(!Q.valid)for(let Z of Q.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${Z}`,category:"layers",file:Q.file});return j}i();import{ContractsrcSchema as s7,DEFAULT_CONTRACTSRC as UW}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as a7}from"@contractspec/module.workspace";async function $$($,W={}){let{fs:j,scan:A=a7}=$,Q=await N$(j,W),Z=[],X=Array.isArray(W.type)?W.type:[W.type];for(let Y of Q){if(j0(Y,W.config))continue;if(A0(Y))continue;try{let B=await j.readFile(Y),q=A(B,Y);if(q.specType==="unknown")continue;if(W.type&&!X.includes(q.specType))continue;Z.push(q)}catch{}}return Z}function DK($){let W=new Map;for(let j of $){let A=W.get(j.specType)??[];A.push(j),W.set(j.specType,A)}return W}var e7=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,$X=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,WX=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,jX=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,AX=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,QX=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,ZX=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function LW($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function XX($,W){let j=$.replaceAll("\\","/"),A=new Set(["contracts","features",...LW(W?.conventions?.operations),...LW(W?.conventions?.events),...LW(W?.conventions?.presentations),...LW(W?.conventions?.forms)]);return j.split("/").some((Q)=>A.has(Q))}function YX($,W,j){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||AX.test(A)||jX.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(W.has(A))return!1;if(XX(A,j))return!1;return e7.test(A)}function $4($){return $.replaceAll("\\","/").match(QX)?.[1]??null}function BX($){let W=$.split(`
|
|
1611
|
-
`).map((j)=>j.trim()).filter((j)=>j.length>0&&!j.startsWith("//")&&!j.startsWith("/*")&&!j.startsWith("*")&&!j.startsWith("*/"));return W.length>0&&W.every((j)=>j.startsWith("import ")||j.startsWith("export *")||j.startsWith("export {")||j.startsWith("export type {")||j==="'use client';"||j==='"use client";'||j==="'use server';"||j==='"use server";')}function qX($){if(!$)return UW;let W=s7.safeParse($),j=W.success?W.data:{};return{...UW,...j,conventions:{...UW.conventions,...j.conventions??{}},ci:{...UW.ci,...j.ci??{}}}}async function s1($,W){let{fs:j,logger:A}=$,Q=[],Z=W.config?qX(W.config):await m(j),X=await $$({fs:j},{config:Z}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),B=new Set(X.map((H)=>$4(H.filePath)).filter((H)=>Boolean(H))),q=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of q){if(!YX(H,Y,Z))continue;try{let V=await j.readFile(H);if(BX(V))continue;let G=$4(H);if(!(G!==null&&ZX.test(G)&&B.has(G))&&!WX.test(V))continue;if($X.test(V))continue;Q.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:H})}catch(V){A.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Q}import{validateSpecStructure as HX}from"@contractspec/module.workspace";async function e1($){let W=[];for(let j of $){let A=HX(j);for(let Q of A.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Q,category:"structure",file:j.filePath});for(let Q of A.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Q,category:"structure",file:j.filePath})}return W}async function $j($){let W=[],j=new Map,A=new Map;for(let Q of $){if(!Q.key||!Q.version)continue;if(Q.specType==="test-spec"){let Z=`${Q.key}.v${Q.version}`;j.set(Z,{key:Q.key,version:Q.version,file:Q.filePath,type:"test-spec"})}if(Q.testRefs&&Q.testRefs.length>0){if(!A.has(Q.filePath))A.set(Q.filePath,[]);A.get(Q.filePath)?.push({key:Q.key,version:Q.version,testRefs:Q.testRefs})}}for(let[Q,Z]of A)for(let X of Z){if(!X.testRefs)continue;let Y=i1(Q,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let B of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:B,category:"test-refs",file:Q,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}i();async function Wj($,W){let{fs:j}=$,A=[],Q=await m(j);for(let Z of W){if(Z.specType!=="operation")continue;let X=await KW(Z,{fs:j},Q,{checkTests:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:Z.filePath})}return A}function l($,W,j){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},Q=W.filter((Y)=>Y.severity==="error").length,Z=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:A[$],errors:Q,warnings:Z,notes:X,passed:Q===0,durationMs:j}}async function W4($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),A=j.match(/^ref: (.+)$/m);if(A){let Z=A[1]?.replace("refs/heads/",""),X=`.git/${A[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:Z};return{branch:Z}}return{commitSha:j.trim()}}catch{return{}}}function j4($){let W=$.config?.ci?.checks,j=W&&W.length>0?[...W]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)j.push("handlers");if($.checkTests)j.push("tests");if($.implementation)j.push("implementation");if($.checkDrift)j.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return j.filter((A)=>!$.skip?.includes(A));return j}async function Y_($,W={}){let j=Date.now(),{fs:A,logger:Q}=$,Z=[],X=[],Y=j4(W);Q.info("Starting CI checks...",{checks:Y});let B=await m(A),q=await QW($,{config:B,pattern:W.pattern});if(Y.includes("structure")){let L=Date.now(),z=await e1(q);Z.push(...z),X.push(l("structure",z,Date.now()-L))}if(Y.includes("integrity")){let L=Date.now(),z=await t1($,W);Z.push(...z),X.push(l("integrity",z,Date.now()-L))}if(Y.includes("deps")){let L=Date.now(),z=await C1($,W);Z.push(...z),X.push(l("deps",z,Date.now()-L))}if(Y.includes("doctor")){let L=Date.now(),z=await u1($,W);Z.push(...z),X.push(l("doctor",z,Date.now()-L))}if(Y.includes("docs")){let L=Date.now(),z=await D1($,W);Z.push(...z),X.push(l("docs",z,Date.now()-L))}if(Y.includes("policy")){let L=Date.now(),z=await s1($,W);Z.push(...z),X.push(l("policy",z,Date.now()-L))}if(Y.includes("handlers")||W.checkHandlers){let L=Date.now(),z=await l1($,q);Z.push(...z),X.push(l("handlers",z,Date.now()-L))}if(Y.includes("tests")||W.checkTests){let L=Date.now(),z=await Wj($,q);Z.push(...z),X.push(l("tests",z,Date.now()-L))}if(Y.includes("test-refs")){let L=Date.now(),z=await $j(q);Z.push(...z),X.push(l("test-refs",z,Date.now()-L))}if(Y.includes("coverage")){let L=Date.now(),z=await R1($,q,W);Z.push(...z),X.push(l("coverage",z,Date.now()-L))}if(Y.includes("implementation")){let L=Date.now(),z=await o1($,q,W);Z.push(...z),X.push(l("implementation",z,Date.now()-L))}if(Y.includes("layers")){let L=Date.now(),z=await a1($,W);Z.push(...z),X.push(l("layers",z,Date.now()-L))}if(Y.includes("drift")){let L=Date.now(),z=await r1($,W);Z.push(...z),X.push(l("drift",z,Date.now()-L))}let H=Z.filter((L)=>L.severity==="error").length,V=Z.filter((L)=>L.severity==="warning").length,G=Z.filter((L)=>L.severity==="note").length,J=W.failOnWarnings?H===0&&V===0:H===0,b=await W4(A),w={success:J,totalErrors:H,totalWarnings:V,totalNotes:G,issues:Z,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...b};return Q.info("CI checks complete",{success:J,errors:H,warnings:V,durationMs:w.durationMs}),w}var q_=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],H_={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function w_($,W={}){let{fs:j,logger:A}=$,Q=(W.outputDir??"./src").replace(/\\/g,"/"),Z=["generated/**","dist/**",".turbo/**"],X=[`${Q}/handlers/**/*.handler.ts`,`${Q}/handlers/**/*.handler.test.ts`,`${Q}/components/**/*.tsx`,`${Q}/components/**/*.test.tsx`,`${Q}/forms/**/*.form.tsx`,`${Q}/forms/**/*.form.test.tsx`,`${Q}/**/*.runner.ts`,`${Q}/**/*.renderer.tsx`],Y=W.generatedOnly?[...Z,...X]:[...Z,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],B=await j.glob({patterns:Y,ignore:["node_modules/**"]}),q=[],H=[];for(let V of B)try{let G=await j.stat(V),J=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&J<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)A.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),A.info("clean.removed",{path:V,size:G.size});q.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:q,skipped:H}}i();var C4={};h(C4,{writeReviewPacket:()=>_j,writeDecisionEnvelope:()=>z0,withBranch:()=>x$,verifyConnectMutation:()=>w2,resolveWorkspace:()=>d,resolveStoragePaths:()=>A$,replayConnectDecision:()=>pX,persistLatestArtifacts:()=>wj,persistDecisionArtifacts:()=>_0,normalizeEvalInput:()=>fX,matchConfiguredPath:()=>G0,loadStoredDecision:()=>U0,listStoredReviewPackets:()=>zj,listConnectReviewPackets:()=>tX,isReviewCommand:()=>jj,isDeniedCommand:()=>Aj,isAllowedCommand:()=>OW,initConnectWorkspace:()=>rX,inferSurfaces:()=>w0,evaluateConnectDecision:()=>hX,ensureStorage:()=>K0,defaultActor:()=>b0,decisionArtifactRefs:()=>r$,createConnectControlPlaneRuntime:()=>X2,connectVerdictToPolicy:()=>n$,configuredThreshold:()=>D$,compileConnectPlanPacket:()=>Uj,buildConnectContextPack:()=>bj,assessConnectPolicy:()=>J0,assertConnectEnabled:()=>a,artifactRef:()=>V$,appendAuditRecord:()=>Kj,analyzeConnectImpact:()=>y$,CONTROL_PLANE_TRACE_GET_REF:()=>SW,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>IW,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Yj,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Xj,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Zj,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>T$,AGENT_APPROVALS_REF:()=>MW,ACP_TERMINAL_EXEC_REF:()=>bX,ACP_FS_ACCESS_REF:()=>JX});import VX from"micromatch";function a($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function G0($,W,j){if(!j||j.length===0)return!1;let A=W.replaceAll("\\","/");return VX.isMatch(A,j,{contains:!0})}function D$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function OW($,W){return Qj($.config.connect?.commands?.allow,W)}function jj($,W){return Qj($.config.connect?.commands?.review,W)}function Aj($,W){return Qj($.config.connect?.commands?.deny,W)}function Qj($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function Q4($,W){if(W.length===0)return{state:"none"};for(let A of W)if(Aj($,A))return{commandMatch:A,state:"deny"};for(let A of W)if(jj($,A))return{commandMatch:A,state:"review"};if(W.every((A)=>OW($,A)))return{state:"allow"};let j=W.find(GX);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((A)=>!OW($,A)),state:"unknown"}}function GX($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return A4(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return A4(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function A4($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var Zj={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Xj={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Yj={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},SW={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},IW={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},T$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},JX={key:"acp.fs.access",version:"1.0.0",kind:"command"},bX={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},MW={key:"agent.approvals",version:"1.0.0",kind:"command"};function J0($,W){let j=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.immutablePaths)),A=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.protectedPaths)),Q=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:Z,state:X}=Q4($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,B=W.impactAnalysis.driftFiles.length>0,q=wX({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:B,generatedPath:Boolean(Q),immutable:Boolean(j),protectedPath:Boolean(A),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=KX({breakingChange:W.impactAnalysis.breakingChange,commandMatch:Z,commandState:X,contractDrift:B,protectedPath:A,unknownPaths:W.impactAnalysis.unknownPaths}),V=n$(q);return{commandMatch:Z,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Q,immutablePath:j,protectedPath:A,requiredApprovals:V.requiresApproval?[{capability:T$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:q}}function n$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function wX($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(D$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(D$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(D$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(D$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(D$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(_X)[0]??"permit"}function KX($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function _X($,W){return Z4($)-Z4(W)}function Z4($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as PX}from"crypto";var H4={};h(H4,{formatPrComment:()=>X4,formatMinimalComment:()=>Bj,formatJson:()=>B4,formatCheckRun:()=>Y4,detectImpact:()=>F$,ImpactDetectionOverviewDocBlock:()=>IX});function X4($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)j.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else j.push("\u2705 **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| \u2796 Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let A=$.deltas.filter((Z)=>Z.severity==="breaking"),Q=$.deltas.filter((Z)=>Z.severity==="non_breaking");if(A.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let Z of A)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}if(Q.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let Z of Q)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let A of $.addedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let A of $.removedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### \u26A0\uFE0F Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let A of W.drift.files)j.push(`- \`${A}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### \u2705 No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
|
|
1612
|
-
|
|
1892
|
+
- This workspace was initialized with the \`${m}\` setup preset.
|
|
1893
|
+
`}function hw($){let b=$.projectName??"this project";return`# ContractSpec Usage Guide
|
|
1894
|
+
|
|
1895
|
+
Scope: \`${$.isMonorepo&&$.scope==="package"&&$.packageName?`${$.packageName} package`:b}\`
|
|
1896
|
+
|
|
1897
|
+
This workspace uses ContractSpec to keep contracts, generated artifacts, and AI guidance aligned.
|
|
1898
|
+
|
|
1899
|
+
## Start Here
|
|
1900
|
+
|
|
1901
|
+
1. Run \`contractspec onboard\` to generate a track-aware onboarding guide for this repo.
|
|
1902
|
+
2. Run \`contractspec validate\` after changing contracts or generated outputs.
|
|
1903
|
+
3. Run \`contractspec doctor\` if local setup or tooling looks unhealthy.
|
|
1904
|
+
|
|
1905
|
+
## Recommended Commands
|
|
1906
|
+
|
|
1907
|
+
- \`contractspec onboard\` - generate repo-local onboarding guidance and next steps
|
|
1908
|
+
- \`contractspec create\` - scaffold a new contract or package target
|
|
1909
|
+
- \`contractspec generate\` - refresh derived docs and artifacts
|
|
1910
|
+
- \`contractspec validate\` - validate contracts, package scaffolds, and integrity
|
|
1911
|
+
- \`contractspec connect adoption resolve --family <family> --stdin\` - reuse existing ContractSpec or workspace surfaces before building new ones
|
|
1912
|
+
|
|
1913
|
+
## Builder / Connect
|
|
1914
|
+
|
|
1915
|
+
- Use \`contractspec init --preset connect\` when you want local Connect artifacts and reuse guidance in the repo.
|
|
1916
|
+
- Use \`contractspec init --preset builder-managed\`, \`builder-local\`, or \`builder-hybrid\` when you want Builder control-plane defaults.
|
|
1917
|
+
|
|
1918
|
+
## Notes
|
|
1919
|
+
|
|
1920
|
+
- \`AGENTS.md\` is for AI-agent operating guidance.
|
|
1921
|
+
- \`USAGE.md\` is for human implementation flow and repo-local onboarding notes.
|
|
1922
|
+
`}function O9($){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 V9($){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)+`
|
|
1923
|
+
`}async function Jm($,b){let A=[];return A.push(await J9($,b)),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}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 J9($,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 K9($,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 _9($,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 U9($,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 z9($,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 L9($,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 R9($,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 C9}from"child_process";import{promisify as I9}from"util";var P$=I9(C9);async function Km($,b){let A=[];return A.push(await E9(b)),A.push(await M9(b)),A.push(await x9($,b)),A.push(await T9($,b)),A.push(await D9($,b)),A}async function E9($){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 M9($){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 x9($,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 T9($,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 D9($,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 N9,isFeatureFile as F9,scanAllSpecsFromSource as v9,scanExampleSource as g9,scanFeatureSource as k9}from"@contractspec/module.workspace";function P9(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function PA($,b={}){let{fs:A,logger:m}=$,n=P9(),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(F9(y)){let S=k9(B,y);n.features.set(S.key,S);continue}if(N9(y)){let S=g9(B,y);n.examples.set(S.key,S);continue}if(y.includes(".app-config.")||y.includes(".blueprint.")){let S=v9(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 $O($){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(r9(n.stats.features)),A.push(f9(n.stats.examples)),A.push(h9(n.inventory.features,m,b)),A.push(c9(n.inventory.examples)),A.push(d9(n.inventory.workspaceConfigs)),A}function r9($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function f9($){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 h9($,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 c9($){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 d9($){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 u9($,b)),A.push(await o9($,b)),A.push(await i9($,b)),A}async function u9($,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 o9($,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 i9($,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 l9=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],uw=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function t9($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((b,[A,m])=>{if(typeof m==="string")b[A]=m;return b},{})}function p9($){return Object.entries($).some(([b,A])=>{return b.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(A)})}async function a9($,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=t9(y.scripts),S=await $.glob({patterns:l9,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:p9(B),testFileCount:S.length,tier:cw(j,A)})}catch{continue}}return n}function e9($){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 s9($){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 a9($,b,A),n=[];for(let w of m){if(w.tier==="critical")n.push(...e9(w));n.push(...s9(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 $S=["src/contracts","contracts","src/specs","specs"];async function Rm($,b){let A=[];return A.push(bS(b)),A.push(await AS($,b)),A.push(await mS($,b)),A.push(await nS($,b)),A.push(await wS($,b)),A.push(...await tw($,b)),A}function bS($){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 AS($,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 mS($,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 $S){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 nS($,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 wS($,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 jS={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$}},yS={confirm:async()=>!1,input:async()=>""};async function ew($,b,A=yS,m=jS){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 BS(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(`\u2713 ${U.message}`),H.status="pass",H.message=`Fixed: ${U.message}`,H.fix=void 0;else W.warn(`\u2717 ${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 BS($,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 EO($){let b=[];if(b.push(""),b.push("=== Health Check Summary ==="),b.push(""),$.healthy)b.push("\u2713 All checks passed!");else b.push("\u2717 Some issues found");return b.push(""),b.push(` Passed: ${$.passed}`),b.push(` Warnings: ${$.warnings}`),b.push(` Failures: ${$.failures}`),b.push(` Skipped: ${$.skipped}`),b.join(`
|
|
1924
|
+
`)}function MO($){let A=`${$.status==="pass"?"\u2713":$.status==="warn"?"\u26A0":$.status==="fail"?"\u2717":"\u25CB"} ${$.name}: ${$.message}`;if($.details)A+=`
|
|
1925
|
+
${$.details}`;if($.fix)A+=`
|
|
1926
|
+
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 LS,rm as RS}from"fs/promises";import{tmpdir as CS}from"os";import Rb from"path";import{DEFAULT_CONTRACTSRC as qS}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as OS}from"@contractspec/module.workspace";import VS from"path";import{packageDocBlocks as SS}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as QS,convertSpecToDocBlock as ZS,extractModuleDocData as GS,loadSpecFromSource as XS,scanAllSpecsFromSource as YS,scanSpecSource as HS}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=YS(S,B);if(Q.length>0)j.push(...Q);else{let Z=HS(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 XS(B);if(!S?.length){n.warn(`Could not parse spec from ${B}`);continue}for(let Q of S){let Z=ZS(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 rO($,b){return(await Aj($,b)).map(({entry:m})=>m.block)}function fO($,b){return SS(QS({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=GS(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. -->
|
|
1927
|
+
|
|
1928
|
+
${$.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??KS(b,n)});if(w.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let j=VS.join(_S(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=JS(S);if(!Q||Q.materialization==="none"||Q.materialization==="docs")continue;let Z=await $b(S.filePath,$,W??qS,{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 JS($){return OS($.specType)}function KS($,b){if(b.config&&!b.specPattern)return;if(b.scanAllSpecs)return b.specPattern;return $?`${Mm($)}/**/*.ts`:void 0}function _S($,b){let A=(b?.connect?.policy?.generatedPaths??[]).map(zS).filter(Boolean);if(A.length>0)return A[0];if(b?.outputDir&&b.outputDir!=="./src")return Mm(b.outputDir);return $}function US($){return Mm($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function zS($){let b=US($);return b.endsWith("/docs")?b.replace(/\/docs$/,""):b}function Mm($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function cA($,b,A,m={}){let n=await LS(Rb.join(CS(),"contractspec-drift-"));try{await mj($,b,n,m.rootPath,m.generation);let W=[],w=await import("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 RS(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 IS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function ES($){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=IS(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=`${ES(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 FS}from"crypto";import vS 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},MS={".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 xS($){let b=$.toLowerCase();for(let[A,m]of Object.entries(MS))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:xS(b)})},W=(Z)=>{return $.substring(0,Z).split(`
|
|
1929
|
+
`).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 ZV($,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 TS($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function wj($,b,A){let m=TS(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 DS,SyntaxKind as NS}from"ts-morph";function jj($){let b=[],m=new DS({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(NS.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 qV($){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 gS={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function Bj($){return FS("sha256").update($).digest("hex")}async function kS($,b,A,m={},n){let W={...gS,...m},w=W.computeHashes?Bj($.sourceBlock||""):void 0,j=$.key??vS.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 kS(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 fS,scanAllSpecsFromSource as hS,scanFeatureSource as cS}from"@contractspec/module.workspace";function PS($,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=PS(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=rS(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 rS($,b){switch(b){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function b$($,b){return`${$}.v${b}`}function dS(){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=dS(),w=[],j=[];for(let H of n){if((await A.stat(H)).isDirectory)continue;let U=await A.readFile(H);if(fS(H)){let z=cS(U,H);w.push(z)}else{let z=hS(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 kV($){let b=[];for(let A of Object.values($))for(let m of A.values())b.push(m);return b}function PV($,b){return $.filter((A)=>A.type===b)}function rV($,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 oS,DEFAULT_CONTRACTSRC as iA}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as uS}from"@contractspec/module.workspace";async function j$($,b={}){let{fs:A,scan:m=uS}=$,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 pV($){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 iS=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,lS=/@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?)?['"]/,tS=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,pS=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,aS=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,eS=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,sS=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function lA($){if(!$)return[];return $.split(/[|/]/).map((b)=>b.trim()).filter(Boolean)}function $Q($,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 bQ($,b,A){let m=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(m))return!1;if(m.includes("/node_modules/")||m.includes("/dist/")||aS.test(m)||pS.test(m)||m.endsWith(".d.ts")||m.endsWith(".test.ts")||m.endsWith(".spec.ts"))return!1;if(b.has(m))return!1;if($Q(m,A))return!1;return iS.test(m)}function Gj($){return $.replaceAll("\\","/").match(eS)?.[1]??null}function AQ($){let b=$.split(`
|
|
1930
|
+
`).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 mQ($){if(!$)return iA;let b=oS.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?mQ(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(!bQ(S,j,W))continue;try{let Q=await A.readFile(S);if(AQ(Q))continue;let Z=Gj(S);if(!(Z!==null&&sS.test(Z)&&y.has(Z))&&!tS.test(Q))continue;if(lS.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 nQ}from"@contractspec/module.workspace";async function Pm($){let b=[];for(let A of $){let m=nQ(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 IJ($,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 MJ=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],xJ={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 vJ($,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:()=>Q4,resolveWorkspace:()=>o,resolveStoragePaths:()=>Q$,replayConnectDecision:()=>cQ,persistLatestArtifacts:()=>$n,persistDecisionArtifacts:()=>Nb,normalizeEvalInput:()=>NQ,matchConfiguredPath:()=>Ib,loadStoredDecision:()=>vb,listStoredReviewPackets:()=>mn,listConnectReviewPackets:()=>dQ,isReviewCommand:()=>hm,isDeniedCommand:()=>cm,isAllowedCommand:()=>tA,initConnectWorkspace:()=>PQ,inferSurfaces:()=>xb,evaluateConnectDecision:()=>TQ,ensureStorage:()=>Db,defaultActor:()=>Mb,decisionArtifactRefs:()=>nb,createConnectControlPlaneRuntime:()=>$4,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:()=>yQ,ACP_FS_ACCESS_REF:()=>jQ});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(wQ);if(A)return{commandMatch:A,state:"destructive"};return{commandMatch:b.find((m)=>!tA($,m)),state:"unknown"}}function wQ($){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"},jQ={key:"acp.fs.access",version:"1.0.0",kind:"command"},yQ={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=BQ({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=SQ({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 BQ($){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(QQ)[0]??"permit"}function SQ($){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 QQ($,b){return Oj($)-Oj(b)}function Oj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as MQ}from"crypto";var Uj={};P(Uj,{formatPrComment:()=>Vj,formatMinimalComment:()=>lm,formatJson:()=>Kj,formatCheckRun:()=>Jj,detectImpact:()=>V$,ImpactDetectionOverviewDocBlock:()=>qQ});function Vj($,b={template:"detailed"}){let A=[];if(A.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),A.push(""),$.hasBreaking)A.push("\u274C **Breaking changes detected**");else if($.hasNonBreaking)A.push("\u26A0\uFE0F **Contract changed (non-breaking)**");else A.push("\u2705 **No contract impact**");if(A.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(A.push("### Summary"),A.push(""),A.push("| Type | Count |"),A.push("|------|-------|"),$.summary.breaking>0)A.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)A.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)A.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)A.push(`| \u2795 Added | ${$.summary.added} |`);if($.summary.removed>0)A.push(`| \u2796 Removed | ${$.summary.removed} |`);A.push("")}if(b.template==="detailed"&&$.deltas.length>0){A.push("### Changes"),A.push("");let 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("### \u26A0\uFE0F 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("### \u2705 No Drift Detected"),A.push("");return A.push("---"),A.push(`*Generated by ContractSpec at ${$.timestamp}*`),A.join(`
|
|
1931
|
+
`)}function lm($){if($.hasBreaking)return`\u274C **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`\u26A0\uFE0F **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"\u2705 **No contract impact**"}function 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 ZQ,computeIoDiff as GQ,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 XQ(A,j,W),B=_j(y),S;if(b.baseline){let G=await YQ(A,m,j,b.baseline,W);S=_j(G)}else S={version:"1.0.0",generatedAt:"",specs:[],hash:""};let Q=HQ(S.specs,B.specs),Z=ZQ(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 XQ($,b,A){let m=[];for(let n of b){let W=await $.readFile(n);m.push({path:n,content:W})}return m}async function YQ($,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 HQ($,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=GQ(j.io,w.io);A.push(...y)}}return A}var qQ={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1613
1932
|
# Contract Impact Detection
|
|
1614
1933
|
|
|
1615
1934
|
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
@@ -1655,49 +1974,49 @@ The system consists of three layers:
|
|
|
1655
1974
|
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1656
1975
|
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1657
1976
|
3. **Integrations**: CLI command + GitHub Action
|
|
1658
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as
|
|
1659
|
-
`;await $.writeFile(
|
|
1660
|
-
`)}async function
|
|
1661
|
-
`);if(
|
|
1662
|
-
`)?
|
|
1977
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as Lj,readFileSync as Rj}from"fs";import{basename as OQ,join as tm,resolve as VQ}from"path";import{ContractsrcSchema as JQ,DEFAULT_CONTRACTSRC as KQ}from"@contractspec/lib.contracts-spec/workspace-config";function o($={}){let b=VQ($.cwd??process.cwd()),A=$.workspaceRoot??M(b),m=$.packageRoot??r(b),n=$.config??_Q(A,m),W=UQ(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 _Q($,b){let A={...KQ};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=JQ.safeParse(m);if(!n.success)return $;return{...$,...n.data}}catch{return $}}function UQ($,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 OQ(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)=>zQ($.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 LQ($,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 zQ($,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:IQ(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 LQ($,b,A){let m=RQ($.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 RQ($,b,A){let m=(b.config.connect?.policy?.generatedPaths??[]).map(EQ).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=CQ($,n,y);W.set(`${B}::${y}`,{comparisonRoot:B,filterPrefix:y})}}return[...W.values()]}function CQ($,b,A){if(b&&A.startsWith(b))return b;return $.basename(A)==="docs"?m$($.dirname(A)):A}function IQ($,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 EQ($){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 xQ($,A.workspaceRoot,b),W=await h$($,{baseline:b.baseline,touchedPaths:n,workspace:A}),w=A.config.connect?.canonPacks??[];return{id:`connect.ctx_${MQ()}`,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 xQ($,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"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)}
|
|
1978
|
+
`;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)}
|
|
1979
|
+
`)}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 TQ($,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=DQ(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 DQ($,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 NQ($){return $}import{DEFAULT_CONTRACTSRC as kQ}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=FQ(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 FQ($,b){let A=vQ(b),m=gQ(),n=$.replace(/\r\n/g,`
|
|
1980
|
+
`);if(m.test(n))return n.replace(m,A);if(n.trim().length===0)return A;return`${n.endsWith(`
|
|
1981
|
+
`)?n:`${n}
|
|
1663
1982
|
`}
|
|
1664
|
-
${
|
|
1983
|
+
${A}`}function vQ($){return`# contractspec:init:gitignore:start
|
|
1665
1984
|
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1666
|
-
${
|
|
1985
|
+
${Dj($).join(`
|
|
1667
1986
|
`)}
|
|
1668
1987
|
# contractspec:init:gitignore:end
|
|
1669
|
-
`}function
|
|
1670
|
-
`).trimEnd()}function L4($){return[...new Set($.map((W)=>W.trim()).filter(Boolean))]}async function rX($,W={}){let j=d(W),A=W.scope==="package"?j.packageRoot:j.workspaceRoot,Q=$.join(A,".contractsrc.json"),Z={connect:{...cX.connect,enabled:!0}},X="created";if(await $.exists(Q)){let q=r(await $.readFile(Q)),H=p(q??{},Z);if(q?.connect&&typeof q.connect==="object")H.connect.enabled=!0;await $.writeFile(Q,F(H)),X="merged"}else await $.writeFile(Q,F(Z));let Y=A$(d({...W,workspaceRoot:A,packageRoot:A}));await K0($,Y);let B=await EW($,{behavior:W.gitignoreBehavior,interactive:W.interactive??!1,patterns:[Y0.connect,Y0.verificationCache],prompts:W.prompts,root:j.workspaceRoot});return{configPath:Q,targetRoot:A,action:X,gitignore:B}}import{randomUUID as NW}from"crypto";async function Uj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let{commands:A,touchedPaths:Q}=lX(W.candidate),Z=await bj($,{...W,paths:Q}),X=b0(W.taskId,W.actor),Y=oX(W.candidate.steps,W.candidate),B=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),q=J0(j,{commands:A,impactAnalysis:B,touchedPaths:Q}),H={id:`connect.plan_${NW()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:Z.impactedContracts,affectedSurfaces:Z.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:q.requiredApprovals,riskScore:iX(Q.length,A.length),verificationStatus:q.verificationStatus,controlPlane:{intentSubmit:Zj,planCompile:Xj,planVerify:Yj,traceId:X.traceId},acpActions:[...Q.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:Z,planPacket:H}}function lX($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let Q of A.paths??[])W.add(Q);for(let Q of A.commands??[])j.add(Q)}return{commands:[...j],touchedPaths:[...W]}}function oX($,W){if(!$||$.length===0)return[{id:`step_${NW()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${NW()}`,summary:j}:{id:`step_${NW()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function iX($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function pX($,W,j){let A=d(W);a(A);let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X={decisionId:Z.envelope?.runtimeLink?.decisionId,traceId:Z.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,B=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:Z.historyDir,contextPack:Z.contextPack,planPacket:Z.planPacket,patchVerdict:Z.patchVerdict,reviewPacket:Z.reviewPacket,trace:Y??void 0,replay:B??void 0,source:Y?"local+control-plane":"local"}}async function tX($,W={}){let j=d(W);return a(j),zj($.fs,A$(j))}import{buildChannelPlanTrace as aX,compileChannelPlan as sX,finalizeChannelPlan as eX,replayExecutionTrace as $2,resolveChannelExecutionActor as W2}from"@contractspec/integration.runtime/channel";import{createHash as j2}from"crypto";var L0="connect.local",A2="connect.runtime-link.v1",Q2="connect.adapter.v1",Z2="connect-control-plane-bridge";function X2($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:A,patchVerdict:Q,planPacket:Z,workspace:X})=>{let Y=new Date(j),B=JSON.stringify({connectDecisionId:W,objective:Z.objective,taskId:Z.taskId,tool:A.tool,verdict:Q.verdict}),q={workspaceId:X.repoId,providerKey:L0,externalEventId:W,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Q.controlPlane.traceId,thread:{externalThreadId:`connect:${Z.taskId}`,externalUserId:Z.actor.id},message:{text:H2(Z.objective,A)},metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`}),rawPayload:B},H=await $.store.claimEventReceipt({workspaceId:q.workspaceId,providerKey:q.providerKey,externalEventId:q.externalEventId,eventType:q.eventType,signatureValid:!0,payloadHash:V2(B),traceId:q.traceId});if(H.duplicate)return Y2($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:q.workspaceId,providerKey:q.providerKey,externalThreadId:q.thread.externalThreadId,externalUserId:q.thread.externalUserId,occurredAt:Y}),G=W2(q,{actorId:Z.actor.id,actorType:Z.actor.type,capabilityGrants:q2(Q.verdict),capabilitySource:"connect",sessionId:Z.actor.sessionId}),J=sX({event:q,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),b=eX({plan:J,decision:B2(Q),approvalTimeoutMs:900000,now:Y}),w=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:b.policy?.verdict??"blocked",riskTier:b.policy?.riskTier??"blocked",confidence:b.policy?.confidence??0.5,modelName:Z2,promptVersion:A2,policyVersion:Q2,toolTrace:aX(b),actionPlan:b,requiresApproval:b.approval.required,approvalStatus:b.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:b.approval.required?"pending":"processed",decisionId:w.id,receiptId:H.receiptId,traceId:b.traceId,workspaceId:X.repoId,providerKey:L0,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`,metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,tool:A.tool})}),{approvalStatus:w.approvalStatus,decisionId:w.id,planId:b.id,providerKey:L0,receiptId:H.receiptId,threadId:V.id,traceId:b.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>O4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await O4($.traceService,W);return j?$2(j):null}}}async function Y2($,W,j){let Q=(await $.listDecisions({externalEventId:j,limit:1,providerKey:L0,workspaceId:W}))[0];return Q?{approvalStatus:Q.approvalStatus,decisionId:Q.id,planId:Q.actionPlan.id,providerKey:L0,receiptId:Q.receiptId,threadId:Q.threadId,traceId:Q.actionPlan.traceId,workspaceId:W}:null}async function O4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function B2($){let W=n$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((j)=>`${j.status}:${j.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:W.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:W.controlPlaneVerdict}}function q2($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function H2($,W){return`${$} [${W.tool}]`}function V2($){return j2("sha256").update($).digest("hex")}function S4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as b2}from"crypto";function I4($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as G2}from"crypto";function M4($,W,j){let A=$?`Immutable path: ${$}`:W?`Protected path: ${W}`:j?`Generated path: ${j}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":W||j?"warn":"pass",detail:A}}function E4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:A}}function N4($,W,j){return{id:"impact-analysis",status:$?"fail":W||j?"warn":"pass",detail:$?"Breaking change detected.":W?"Generated-path drift detected.":j?"Impact could not be resolved.":"Impact resolved."}}function R4($,W,j,A,Q,Z){let X=Z.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${Z.runtimeLink.decisionId}`:Z.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${Z.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${G2()}`,sourceDecisionId:W,objective:A.objective,reason:Z.reason,summary:{paths:Q,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:Z.artifactRefs.contextPack},{type:"plan-packet",ref:Z.artifactRefs.planPacket},{type:"patch-verdict",ref:Z.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:T$.key,reason:Z.reason}],controlPlane:{traceQuery:SW,policyExplain:IW,approvalStatus:Z.runtimeLink?.approvalStatus,decisionId:Z.runtimeLink?.decisionId,traceId:Z.runtimeLink?.traceId??j.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Lj($,W,j,A,Q,Z,X,Y,B){let q=n$(X);return{decisionId:$,summary:A.objective,action:W.tool==="acp.fs.access"?{actionType:W.operation==="write"?"write_file":"edit_file",tool:W.tool,target:W.path}:{actionType:"run_command",tool:W.tool,cwd:W.cwd},impacted:Q,checks:Z,verdict:X,controlPlane:{verdict:q.controlPlaneVerdict,requiresApproval:q.requiresApproval,approvalStatus:B?.approvalStatus,decisionId:B?.decisionId,traceId:B?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${T$.key}@${T$.version}`,`${MW.key}@${MW.version}`]:void 0,remediation:J2(X),reviewPacketRef:Y,replay:{traceQuery:SW,policyExplain:IW}}}function J2($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function w2($,W,j={}){let A=d(W);a(A),A=x$(A,await $.git.currentBranch());let Q=`connect.dec_${b2()}`,Z=(j.now??(()=>new Date))().toISOString(),X=A$(A);await K0($.fs,X);let{contextPack:Y,planPacket:B}=await Uj($,{...W,candidate:K2(W)}),q=_2(W),H=await y$($,{baseline:W.baseline,touchedPaths:q,workspace:A}),V=await z2(j,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),G=V.some((M)=>M.id.startsWith("smoke:")&&M.status==="fail"),J=J0(A,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:q}),b=[M4(J.immutablePath,J.protectedPath,J.generatedPath),E4(J.commandState,J.commandMatch),N4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],w=r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0}),L=H.pathImpacts.length>0?H.pathImpacts.map((M)=>({file:M.path,contracts:M.contracts,policies:M.policies,surfaces:M.surfaces})):q.map((M)=>({file:M,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),z=Lj(Q,W,Y,B,L,b,J.verdict,void 0),S=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Q,createdAt:Z,input:W,patchVerdict:z,planPacket:B,workspace:A}):null,U=S?{...B,controlPlane:{...B.controlPlane,decisionId:S.decisionId,traceId:S.traceId??B.controlPlane.traceId}}:B,O=J.verdict==="require_review"?R4(A,Q,Y,U,q,{artifactRefs:w,reason:J.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:S}):void 0,K=Lj(Q,W,Y,U,L,b,J.verdict,O?V$($.fs,A,$.fs.join(X.reviewPacketsDir,`${O.id}.json`)):void 0,S);if(await wj($.fs,X,{contextPack:Y,planPacket:U,patchVerdict:K}),O)await _j($.fs,X,O);let _=await _0($.fs,X,Q,{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O}),I={artifacts:r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(O)}),connectDecisionId:Q,createdAt:Z,runtimeLink:S??void 0,taskId:W.taskId,verdict:J.verdict};return await z0($.fs,X,Q,I),await Kj($.fs,X,I4({contextPack:Y,createdAt:Z,envelope:I,reviewPacket:O,verifyInput:W,workspace:A})),{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O,historyDir:_}}function K2($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function _2($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function z2($,W,j){if(!$.runCommand)return[];let A=[];for(let Q of W){let Z=await $.runCommand(Q,{cwd:j});A.push({id:`smoke:${Q}`,status:Z.exitCode===0?"pass":"fail",detail:Z.exitCode===0?`Passed: ${Q}`:`Failed (${Z.exitCode}): ${Q}`})}return A}DW();var Ij={};h(Ij,{generateWorkflowSpec:()=>Y8,generateWorkflowRunnerTemplate:()=>jW,generateWorkflowDevkitWorkflowTemplate:()=>a0,generateWorkflowDevkitStreamRouteTemplate:()=>$W,generateWorkflowDevkitStartRouteTemplate:()=>s0,generateWorkflowDevkitGenericTemplate:()=>WW,generateWorkflowDevkitFollowUpRouteTemplate:()=>e0,generateTestTemplate:()=>s5,generateTelemetrySpec:()=>X8,generatePresentationSpec:()=>Z8,generateOperationSpec:()=>Q8,generateMigrationSpec:()=>A8,generateKnowledgeSpaceSpec:()=>W8,generateIntegrationSpec:()=>$8,generateHandlerTemplate:()=>t5,generateFormSpec:()=>p5,generateFeatureSpec:()=>i5,generateExperimentSpec:()=>o5,generateEventSpec:()=>l5,generateDataViewSpec:()=>r5,generateDataViewRendererTemplate:()=>p0,generateComponentTemplate:()=>a5,generateAppBlueprintSpec:()=>c5});DW();class T4{ai;templates=Ij;constructor($){this.ai=new CW($)}}function HU($){return new T4($)}import{scanSpecSource as C2}from"@contractspec/module.workspace";function F4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function KU($,W,j={}){let{fs:A,logger:Q}=W,Z=await A.exists($);if(!Z&&!j.force)return{specPath:$,specInfo:F4($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let X=F4($),Y;if(Z)try{let q=await A.readFile($);X=C2(q,$),Y=X.key}catch{}let B=[];if(j.clean&&Y)try{let q=await _W(Y,{fs:A});for(let H of q)try{await A.remove(H.filePath),B.push(H.filePath),Q.info(`Removed artifact: ${H.filePath}`)}catch{Q.warn(`Could not remove artifact: ${H.filePath}`)}}catch{Q.warn("Could not discover implementations for cleanup")}if(Z)await A.remove($),Q.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:X,deleted:!0,cleanedFiles:B,errors:[]}}import{computeSemanticDiff as D2}from"@contractspec/module.workspace";async function UU($,W,j,A={}){let{fs:Q,git:Z}=j;if(!await Q.exists($))throw Error(`Spec file not found: ${$}`);let Y=await Q.readFile($),B,q;if(A.baseline)B=await Z.showFile(A.baseline,$),q=`${A.baseline}:${$}`;else{if(!await Q.exists(W))throw Error(`Spec file not found: ${W}`);B=await Q.readFile(W),q=W}let H=D2(Y,$,B,q,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:q,differences:H}}i();import{openApiForRegistry as T2}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Mj}from"@contractspec/lib.contracts-spec/operations";async function F2($,W){let{fs:j,logger:A}=W,{registryPath:Q,outputPath:Z="./openapi.json"}=$;A.info("Loading registry...",{registryPath:Q});let X=await x2(Q,j);A.info("Generating OpenAPI document...");let Y=T2(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),B=JSON.stringify(Y,null,2)+`
|
|
1671
|
-
`,
|
|
1988
|
+
`}function gQ(){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,`
|
|
1989
|
+
`).trimEnd()}function Dj($){return[...new Set($.map((b)=>b.trim()).filter(Boolean))]}async function PQ($,b={}){let A=o(b),m=b.scope==="package"?A.packageRoot:A.workspaceRoot,n=$.join(m,".contractsrc.json"),W={connect:{...kQ.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}=rQ(b.candidate),W=await Tb($,{...b,paths:n}),w=Mb(b.taskId,b.actor),j=fQ(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:hQ(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 rQ($){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 fQ($,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 hQ($,b){return Math.min(1,$*0.1+b*0.15+0.1)}async function cQ($,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 dQ($,b={}){let A=o(b);return A$(A),mn($.fs,Q$(A))}import{buildChannelPlanTrace as uQ,compileChannelPlan as oQ,finalizeChannelPlan as iQ,replayExecutionTrace as lQ,resolveChannelExecutionActor as tQ}from"@contractspec/integration.runtime/channel";import{createHash as pQ}from"crypto";var kb="connect.local",aQ="connect.runtime-link.v1",eQ="connect.adapter.v1",sQ="connect-control-plane-bridge";function $4($){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:n4(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 b4($.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=tQ(B,{actorId:W.actor.id,actorType:W.actor.type,capabilityGrants:m4(n.verdict),capabilitySource:"connect",sessionId:W.actor.sessionId}),G=oQ({event:B,receiptId:S.receiptId,threadId:Q.id,actor:Z,now:j}),X=iQ({plan:G,decision:A4(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:sQ,promptVersion:aQ,policyVersion:eQ,toolTrace:uQ(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?lQ(A):null}}}async function b4($,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 A4($){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 m4($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function n4($,b){return`${$} [${b.tool}]`}function W4($){return pQ("sha256").update($).digest("hex")}function Fj($){return Object.fromEntries(Object.entries($).filter((b)=>Boolean(b[1])))}import{randomUUID as S4}from"crypto";async function vj($,b){if(!b.config?.connect?.adoption?.enabled)return{};let A=w4(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"?j4(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 w4($){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 j4($){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 y4}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_${y4()}`,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:B4(w),reviewPacketRef:j,replay:{traceQuery:pA,policyExplain:aA}}}function B4($){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 Q4($,b,A={}){let m=o(b);A$(m),m=f$(m,await $.git.currentBranch());let n=`connect.dec_${S4()}`,W=(A.now??(()=>new Date))().toISOString(),w=Q$(m);await Db($.fs,w);let{contextPack:j,planPacket:y}=await gb($,{...b,candidate:X4(b)}),B=Y4(b),S=await h$($,{baseline:b.baseline,touchedPaths:B,workspace:m}),Q=await H4(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=Z4(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 Z4($,b){if(b==="rewrite"&&$.verdict==="require_review"&&!$.immutablePath&&!$.protectedPath&&$.commandState!=="review"&&$.commandState!=="destructive")return b;return G4($.verdict,b)}function G4($,b){if(!b)return $;return hj($)<=hj(b)?$:b}function hj($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}function X4($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function Y4($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function H4($,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 N_($){return new uj($)}import{scanSpecSource as R4}from"@contractspec/module.workspace";function oj($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function r_($,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=R4(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 C4}from"@contractspec/module.workspace";async function c_($,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=C4(j,$,y,B,{breakingOnly:m.breakingOnly});return{spec1:$,spec2:B,differences:S}}s();import{openApiForRegistry as I4}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Bn}from"@contractspec/lib.contracts-spec/operations";async function E4($,b){let{fs:A,logger:m}=b,{registryPath:n,outputPath:W="./openapi.json"}=$;m.info("Loading registry...",{registryPath:n});let w=await M4(n,A);m.info("Generating OpenAPI document...");let j=I4(w,{title:$.title,version:$.version,description:$.description,servers:$.servers}),y=JSON.stringify(j,null,2)+`
|
|
1990
|
+
`,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 M4($,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 x4,parseOpenApi as T4}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Sn,dirname as ij,join as Wb}from"path";function D4($,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 T4(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=x4(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=D4(_,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=`/**
|
|
1672
1991
|
* Auto-generated registry file.
|
|
1673
1992
|
*/
|
|
1674
|
-
`;
|
|
1675
|
-
`}),
|
|
1676
|
-
`;let
|
|
1993
|
+
`;_.forEach((x)=>{let h=`./${Sn(x.file,".ts")}`;L+=`import { ${x.name} } from '${h}';
|
|
1994
|
+
`}),L+=`
|
|
1995
|
+
`;let I=!1;if(q)L+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1677
1996
|
|
|
1678
|
-
`,
|
|
1679
|
-
`,
|
|
1680
|
-
`}),
|
|
1997
|
+
`,L+=`export const operationRegistry = new OperationSpecRegistry();
|
|
1998
|
+
`,_.forEach((x)=>{L+=`operationRegistry.register(${x.name});
|
|
1999
|
+
`}),I=!0;else if(U)L+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
1681
2000
|
|
|
1682
|
-
`,
|
|
1683
|
-
`,
|
|
1684
|
-
`}),
|
|
2001
|
+
`,L+=`export const eventRegistry = new EventRegistry();
|
|
2002
|
+
`,_.forEach((x)=>{L+=`eventRegistry.register(${x.name});
|
|
2003
|
+
`}),I=!0;else if(z)L+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
1685
2004
|
|
|
1686
|
-
`,
|
|
1687
|
-
`,
|
|
1688
|
-
`}),
|
|
2005
|
+
`,L+=`export const modelRegistry = new ModelRegistry();
|
|
2006
|
+
`,_.forEach((x)=>{L+=`modelRegistry.register(${x.name});
|
|
2007
|
+
`}),I=!0;if(I){let x=Wb(J,"registry.ts");await m.writeFile(x,L),n.info(`Created/Updated registry: ${x}`)}let C=`/**
|
|
1689
2008
|
* Auto-generated barrel file.
|
|
1690
2009
|
*/
|
|
1691
2010
|
|
|
1692
|
-
`;if(
|
|
1693
|
-
`}),C
|
|
1694
|
-
`;let
|
|
1695
|
-
{ key: '${
|
|
2011
|
+
`;if(_.forEach((x)=>{let h=`./${Sn(x.file,".ts")}`;C+=`export * from '${h}';
|
|
2012
|
+
`}),I)C+=`export * from './registry';
|
|
2013
|
+
`;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 N4,parseOpenApi as F4}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as v4,join as g4}from"path";async function AU($,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 F4(X,{fetch:globalThis.fetch,readFile:(O)=>m.readFile(O)});n.info(`Parsed ${Y.operations.length} operations from ${G.name}`);let V=N4(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=g4(S,O.fileName);if(!await m.exists(K)){if(!B){let _=v4(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 k4}from"@contractspec/lib.contracts-transformers/openapi";async function WU($,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 k4(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 YU($,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:()=>f4,getArrayNameForSpecType:()=>tj,detectFeatureContext:()=>P4,computeAddSpecEdit:()=>r4});function P4($,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 r4($,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=`
|
|
2014
|
+
{ 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 f4($,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:()=>h4,FixService:()=>sj,FIX_STRATEGY_STABILITY:()=>db,FIX_STRATEGY_LABELS:()=>l4,CiOutputSchema:()=>W6});function h4($,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}\`:
|
|
1696
2015
|
|
|
1697
2016
|
> ${$.message}
|
|
1698
2017
|
|
|
1699
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);
|
|
1700
|
-
`)}function
|
|
2018
|
+
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 t4 from"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(`,
|
|
2019
|
+
`)}function rb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"Spec",m=R$($,{kind:"'api'"});return`/**
|
|
1701
2020
|
* Capability: ${$.key}
|
|
1702
2021
|
*
|
|
1703
2022
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1708,9 +2027,9 @@ Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",labe
|
|
|
1708
2027
|
|
|
1709
2028
|
import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
1710
2029
|
|
|
1711
|
-
export const ${
|
|
2030
|
+
export const ${A} = defineCapability({
|
|
1712
2031
|
meta: {
|
|
1713
|
-
${
|
|
2032
|
+
${m}
|
|
1714
2033
|
},
|
|
1715
2034
|
|
|
1716
2035
|
provides: [
|
|
@@ -1734,7 +2053,7 @@ export const ${j} = defineCapability({
|
|
|
1734
2053
|
// }
|
|
1735
2054
|
],
|
|
1736
2055
|
});
|
|
1737
|
-
`}function
|
|
2056
|
+
`}function fb($){let b=$.key.split(".").pop()||"Unknown",A=L$(b)+"EventSpec",m=A.replace("Spec","Payload"),n=R$($);return`/**
|
|
1738
2057
|
* Event: ${$.key}
|
|
1739
2058
|
*
|
|
1740
2059
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1747,8 +2066,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
1747
2066
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1748
2067
|
|
|
1749
2068
|
// TODO: Define event payload schema
|
|
1750
|
-
export const ${
|
|
1751
|
-
name: '${
|
|
2069
|
+
export const ${m} = new SchemaModel({
|
|
2070
|
+
name: '${m}',
|
|
1752
2071
|
description: 'Payload for ${$.key} event',
|
|
1753
2072
|
fields: {
|
|
1754
2073
|
// Add your payload fields here
|
|
@@ -1758,12 +2077,12 @@ export const ${A} = new SchemaModel({
|
|
|
1758
2077
|
},
|
|
1759
2078
|
});
|
|
1760
2079
|
|
|
1761
|
-
export const ${
|
|
2080
|
+
export const ${A} = defineEvent({
|
|
1762
2081
|
meta: {
|
|
1763
|
-
${
|
|
2082
|
+
${n}
|
|
1764
2083
|
},
|
|
1765
2084
|
|
|
1766
|
-
payload: ${
|
|
2085
|
+
payload: ${m},
|
|
1767
2086
|
|
|
1768
2087
|
// TODO: Specify PII fields if any
|
|
1769
2088
|
// piiFields: ['user.email'],
|
|
@@ -1774,7 +2093,7 @@ export const ${j} = defineEvent({
|
|
|
1774
2093
|
// policy: 'archive',
|
|
1775
2094
|
// },
|
|
1776
2095
|
});
|
|
1777
|
-
`}function
|
|
2096
|
+
`}function c4($){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=c4($.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`/**
|
|
1778
2097
|
* Operation: ${$.key}
|
|
1779
2098
|
*
|
|
1780
2099
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1783,12 +2102,12 @@ export const ${j} = defineEvent({
|
|
|
1783
2102
|
* Referenced by feature: ${$.featureKey||"unknown"}
|
|
1784
2103
|
*/
|
|
1785
2104
|
|
|
1786
|
-
import { ${
|
|
2105
|
+
import { ${w} } from '@contractspec/lib.contracts-spec';
|
|
1787
2106
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1788
2107
|
|
|
1789
2108
|
// TODO: Define input schema
|
|
1790
|
-
export const ${
|
|
1791
|
-
name: '${
|
|
2109
|
+
export const ${m} = new SchemaModel({
|
|
2110
|
+
name: '${m}',
|
|
1792
2111
|
description: 'Input for ${$.key}',
|
|
1793
2112
|
fields: {
|
|
1794
2113
|
// Add your input fields here
|
|
@@ -1797,8 +2116,8 @@ export const ${A} = new SchemaModel({
|
|
|
1797
2116
|
});
|
|
1798
2117
|
|
|
1799
2118
|
// TODO: Define output schema
|
|
1800
|
-
export const ${
|
|
1801
|
-
name: '${
|
|
2119
|
+
export const ${n} = new SchemaModel({
|
|
2120
|
+
name: '${n}',
|
|
1802
2121
|
description: 'Output for ${$.key}',
|
|
1803
2122
|
fields: {
|
|
1804
2123
|
// Add your output fields here
|
|
@@ -1806,14 +2125,14 @@ export const ${Q} = new SchemaModel({
|
|
|
1806
2125
|
},
|
|
1807
2126
|
});
|
|
1808
2127
|
|
|
1809
|
-
export const ${
|
|
2128
|
+
export const ${A} = ${w}({
|
|
1810
2129
|
meta: {
|
|
1811
|
-
${
|
|
2130
|
+
${B}
|
|
1812
2131
|
},
|
|
1813
2132
|
|
|
1814
2133
|
io: {
|
|
1815
|
-
input: ${
|
|
1816
|
-
output: ${
|
|
2134
|
+
input: ${m},
|
|
2135
|
+
output: ${n},
|
|
1817
2136
|
errors: {
|
|
1818
2137
|
// TODO: Define possible errors
|
|
1819
2138
|
// EXAMPLE_ERROR: {
|
|
@@ -1835,7 +2154,7 @@ export const ${j} = ${X}({
|
|
|
1835
2154
|
},
|
|
1836
2155
|
|
|
1837
2156
|
transport: {
|
|
1838
|
-
rest: { method: '${
|
|
2157
|
+
rest: { method: '${W==="command"?"POST":"GET"}' },
|
|
1839
2158
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
1840
2159
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
1841
2160
|
},
|
|
@@ -1852,7 +2171,7 @@ export const ${j} = ${X}({
|
|
|
1852
2171
|
examples: [],
|
|
1853
2172
|
},
|
|
1854
2173
|
});
|
|
1855
|
-
`}function
|
|
2174
|
+
`}function d4($){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=d4($.key),n=R$($);return`/**
|
|
1856
2175
|
* Presentation: ${$.key}
|
|
1857
2176
|
*
|
|
1858
2177
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1863,12 +2182,12 @@ export const ${j} = ${X}({
|
|
|
1863
2182
|
|
|
1864
2183
|
import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
1865
2184
|
|
|
1866
|
-
export const ${
|
|
2185
|
+
export const ${A} = definePresentation({
|
|
1867
2186
|
meta: {
|
|
1868
|
-
${
|
|
2187
|
+
${n}
|
|
1869
2188
|
},
|
|
1870
2189
|
|
|
1871
|
-
kind: '${
|
|
2190
|
+
kind: '${m}',
|
|
1872
2191
|
|
|
1873
2192
|
// TODO: Define content structure
|
|
1874
2193
|
content: {
|
|
@@ -1892,7 +2211,7 @@ export const ${j} = definePresentation({
|
|
|
1892
2211
|
// focusable: true,
|
|
1893
2212
|
// },
|
|
1894
2213
|
});
|
|
1895
|
-
`}import X$ from"path";function TW($,W){if(W.outputDir)return Nj(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=o2($.featureFile);if(j)return Nj(j,$.ref.key,$.specType)}return Nj(X$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function o2($){let W=X$.dirname($),j=X$.parse($).root,A=0;while(W!==j&&A<50){if(X$.basename(W)==="src")return W;W=X$.dirname(W),A++}W=X$.dirname($),A=0;while(W!==j&&A<50)W=X$.dirname(W),A++;let Q=$.lastIndexOf(`${X$.sep}src${X$.sep}`);if(Q!==-1)return $.substring(0,Q+5);return null}function Nj($,W,j){let A=W.replace(/\./g,"-").toLowerCase(),Q=i2(j),Z=p2(j);return X$.join($,Z,`${A}${Q}`)}function i2($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function p2($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var t2={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},N0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function FW($,W,j){let{fs:A,logger:Q}=j,{ref:Z,specType:X,featureKey:Y}=$;try{let B={key:Z.key,version:Z.version,specType:X,stability:N0["implement-ai"],featureKey:Y},q=B;if(W.aiConfig)try{q=await s2(B,W,Q)}catch(J){Q.warn("AI enrichment failed, falling back to skeleton",{error:J instanceof Error?J.message:String(J)})}else Q.info("No AI config provided, using skeleton with experimental stability");let H=WY(q);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=TW($,W),G=[];if(!W.dryRun){let J=a2.dirname(V);await A.mkdir(J),await A.writeFile(V,H),G.push({path:V,action:"created"})}else G.push({path:V,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:G}}catch(B){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:B instanceof Error?B.message:String(B)}}}async function s2($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Q}=await Promise.resolve().then(() => (DW(),D4)),Z=e2(W),X=new Q(Z),Y=$.specType==="operation"?"command":$.specType,B=`${P4($.specType)} for ${$.key}`;if($.specType==="operation"){let q=await X.generateOperationSpec(B,Y);return{...$,description:q.description,enrichment:{goal:q.goal,context:q.context,owners:q.owners,tags:q.tags}}}if($.specType==="event"){let q=await X.generateEventSpec(B);return{...$,description:q.description,enrichment:{goal:`Emit ${$.key} event`,context:q.description,owners:["@team"],tags:q.tags}}}}catch(Q){j.warn("AIGenerator call failed, falling back to heuristics",{error:Q instanceof Error?Q.message:String(Q)})}let A=$Y($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function e2($){let W=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[W?.provider??"openai"]??"openai",aiModel:W?.model??"gpt-4-turbo",customApiKey:W?.apiKey??"",customEndpoint:W?.endpoint??""}}function $Y($,W){let j=$.split("."),A=j[0]||"unknown",Q=j.slice(1).join(" ").replace(/_/g," "),Z=[A],X=Q.toLowerCase().split(" "),B=["auth","user","admin","api","data","search","create","update","delete"].filter((q)=>X.some((H)=>H.includes(q)));return{description:`${P4(W)} for ${A} ${Q}`,goal:`Enable ${Q} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...Z,...B]}}function WY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}function P4($){return $.charAt(0).toUpperCase()+$.slice(1)}import jY from"path";async function xW($,W,j){let{fs:A}=j,{ref:Q,specType:Z,featureKey:X}=$;try{let Y={key:Q.key,version:Q.version,specType:Z,stability:N0["implement-skeleton"],description:`Skeleton spec for ${Q.key}`,featureKey:X},B=AY(Y);if(!B)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${Z}`};let q=TW($,W),H=[];if(!W.dryRun){let V=jY.dirname(q);await A.mkdir(V),await A.writeFile(q,B),H.push({path:q,action:"created"})}else H.push({path:q,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function AY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}async function yW($,W,j){let{fs:A}=j,{ref:Q,featureFile:Z,specType:X}=$;try{let Y=await A.readFile(Z),B=Y,q=QY(Y,Q,X);if(q===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Q.key}.v${Q.version} in ${Z}`};let H=[];if(!W.dryRun)await A.writeFile(Z,q),H.push({path:Z,action:"modified",previousContent:B});else H.push({path:Z,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function QY($,W,j){if(!ZY(j))return $;let Q=k4(W.key),Z=k4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Q}['"],\\s*version:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${Z}['"],\\s*key:\\s*['"]${Q}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let B of X)Y=Y.replace(B,"");return Y=XY(Y),Y}function ZY($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function k4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XY($){return $.replace(/,(\s*)\]/g,"$1]")}class h4{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(W,j)=>yW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(W,j)=>xW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(W,j)=>FW(W,j,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let W=[];if($.type==="unresolved-ref")W.push("remove-reference"),W.push("implement-skeleton"),W.push("implement-ai");else if($.type==="broken-link")W.push("remove-reference"),W.push("implement-skeleton");return W}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,W){let j=this.strategies.get(W.strategy);if(!j)return{success:!1,strategy:W.strategy,issue:$,filesChanged:[],error:`Strategy ${W.strategy} not found`};return this.adapters.logger.info(`Applying fix ${W.strategy} for ${$.ref.key}`,{dryRun:W.dryRun}),j.fix($,W)}async batchFix($){let W=[],j=0,A=0;for(let Q of $.issues)try{let Z=await this.fixIssue(Q,$.options);if(W.push(Z),Z.success)j++;else A++}catch(Z){A++,W.push({success:!1,strategy:$.options.strategy,issue:Q,filesChanged:[],error:Z instanceof Error?Z.message:String(Z)})}return{total:$.issues.length,succeeded:j,failed:A,results:W}}async scanAndGetFixables($={}){return(await zW(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((j)=>this.getToFix(j)).filter((j)=>j!==null)}getToFix($){let W=this.getStrategiesForIssue($);if(W.length===0)return null;let j=this.parseFixableIssue($);if(!j)return null;return{...j,availableStrategies:W,strategies:[]}}resolveStrategy($,W){let{forceStrategy:j,preferAi:A,select:Q}=W;if(j)return Promise.resolve(j);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof Q==="function")return Q($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((W)=>{return this.getToFix(W)}).filter((W)=>W!==null)}}import{z as o$}from"zod";var YY=o$.union([o$.array(o$.unknown()),o$.object({issues:o$.array(o$.unknown())}).transform(($)=>$.issues)]);import{exec as BY}from"child_process";import{promisify as qY}from"util";var HY=qY(BY),f4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function cL($,W,j={}){if($.length===0)return;let A=j.cwd??process.cwd(),Q=f4[j.type??"biome"]??f4.biome,Z=50;for(let X=0;X<$.length;X+=Z){let B=$.slice(X,X+Z).map((q)=>`"${q}"`).join(" ");try{await HY(`${Q} ${B}`,{cwd:A})}catch(q){}}}import _$ from"path";async function iL($,W){let j=_$.join(W,"contracts"),A=_$.join(W,"generated"),Q=_$.join(A,"docs"),Z=await $.fs.exists(j),X=await $.fs.exists(A);if(!Z)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await $$($,{pattern:"contracts/**/*.ts"}),B=[];if(X)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts"),w=_$.join(Q,`${b}.md`);if(!await $.fs.exists(w))B.push(b)}else if(Y.length>0)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts");B.push(b)}let q=_$.join(j,"index.ts"),H=_$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(q),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:B,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var c4={};h(c4,{runHook:()=>u4,getAvailableHooks:()=>d4});import{exec as VY}from"child_process";import{promisify as GY}from"util";var JY=GY(VY);async function u4($,W){let{fs:j,logger:A}=$,{hookName:Q,dryRun:Z=!1}=W,X=D(W.workspaceRoot);A.info(`Running hook: ${Q}`,{workspaceRoot:X,dryRun:Z});let Y=await n4(j,X);if(!Y)return{hookName:Q,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let B=Y[Q];if(!B||B.length===0)return{hookName:Q,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Q}`};A.info(`Found ${B.length} command(s) for ${Q}`);let q=[],H=!0;for(let G of B){if(Z){A.info(`[DRY RUN] Would execute: ${G}`),q.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${G}`);try{let{stdout:J,stderr:b}=await JY(G,{cwd:X,timeout:300000});q.push({command:G,success:!0,exitCode:0,stdout:J,stderr:b}),A.info(`\u2713 ${G}`)}catch(J){H=!1;let b=J;q.push({command:G,success:!1,exitCode:b.code??1,stdout:b.stdout??"",stderr:b.stderr??b.message??String(J)}),A.error(`\u2717 ${G}`,{exitCode:b.code,stderr:b.stderr});break}}let V=q.filter((G)=>G.success).length;return{hookName:Q,success:H,commandResults:q,totalCommands:B.length,successfulCommands:V,summary:H?`\u2713 All ${B.length} command(s) passed`:`\u2717 ${V}/${B.length} command(s) passed`}}async function d4($,W){let j=await n4($.fs,W);return j?Object.keys(j):[]}async function n4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let A=await $.readFile(j);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as bY,extractFromProject as wY}from"@contractspec/lib.source-extractors";import{generateOperations as KY,generateRegistry as _Y,generateSchemas as zY}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as UY}from"@contractspec/lib.source-extractors/extractors";import{dirname as LY,join as Rj}from"path";async function OY($,W,j,A){let{fs:Q,logger:Z}=j,X=A??process.cwd();UY(),Z.info(`Scanning source code in ${X}...`);let Y={readFile:(O)=>Q.readFile(O),glob:(O,K)=>Q.glob({pattern:O,cwd:K?.cwd}),exists:(O)=>Q.exists(O)},B=await bY(X,{readFile:(O)=>Q.readFile(O),glob:(O)=>Q.glob({pattern:O})});if(B.frameworks.length===0)return Z.warn("No supported frameworks detected"),{success:!1,report:SY(),errors:["No supported frameworks detected in project"]};Z.info(`Detected frameworks: ${B.frameworks.map((O)=>O.name).join(", ")}`);let{extractorRegistry:q}=await import("@contractspec/lib.source-extractors");for(let O of q.getAll())if("setFs"in O&&typeof O.setFs==="function")O.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await wY(B,H);if(!V.success||!V.ir)return{success:!1,report:IY(V.errors??[]),errors:V.errors?.map((O)=>O.message)};let G=V.ir;if(Z.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:MY(G)};let J=W.outputDir??Rj($.outputDir,"generated"),b={outputDir:J,defaultAuth:"user"},w=KY(G,b),L=zY(G,b),z=_Y(w),S=[...w,...L,z];if(!W.dryRun)for(let O of S){let K=Rj(J,O.path),_=LY(K);if(!await Q.exists(_))await Q.mkdir(_);await Q.writeFile(K,O.content),Z.info(`Created: ${K}`)}else for(let O of S)Z.info(`[DRY RUN] Would create: ${Rj(J,O.path)}`);let U={files:S,operationsGenerated:w.length,schemasGenerated:L.length,warnings:[]};return{success:!0,ir:G,generation:U,report:EY(G,U,W)}}function SY(){return`# Import Report
|
|
2214
|
+
`}import G$ from"path";function n0($,b){if(b.outputDir)return Qn(b.outputDir,$.ref.key,$.specType);if($.featureFile){let A=u4($.featureFile);if(A)return Qn(A,$.ref.key,$.specType)}return Qn(G$.join(b.workspaceRoot,"specs"),$.ref.key,$.specType)}function u4($){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=o4(A),W=i4(A);return G$.join($,W,`${m}${n}`)}function o4($){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 i4($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var l4={"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 p4(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=s4(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=t4.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 p4($,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=a4(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=e4($.key,$.specType);return{...$,description:m.description,enrichment:{goal:m.goal,context:m.context,owners:["@team"],tags:m.tags}}}function a4($){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 e4($,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 s4($){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 $6 from"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=b6(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=$6.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 b6($){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=A6(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 A6($,b,A){if(!m6(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=n6(j),j}function m6($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function ej($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n6($){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 w6}from"child_process";import{promisify as j6}from"util";var y6=j6(w6),by={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function Xz($,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 y6(`${n} ${y}`,{cwd:m})}catch(B){}}}import C$ from"path";async function Oz($,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 B6}from"child_process";import{promisify as S6}from"util";var Q6=S6(B6);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 Q6(Z,{cwd:w,timeout:300000});B.push({command:Z,success:!0,exitCode:0,stdout:G,stderr:X}),m.info(`\u2713 ${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(`\u2717 ${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?`\u2713 All ${y.length} command(s) passed`:`\u2717 ${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 Z6,extractFromProject as G6}from"@contractspec/lib.source-extractors";import{generateOperations as X6,generateRegistry as Y6,generateSchemas as H6}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as q6}from"@contractspec/lib.source-extractors/extractors";import{dirname as O6,join as Zn}from"path";async function V6($,b,A,m){let{fs:n,logger:W}=A,w=m??process.cwd();q6(),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 Z6(w,{readFile:(_)=>n.readFile(_),glob:(_)=>n.glob({pattern:_})});if(y.frameworks.length===0)return W.warn("No supported frameworks detected"),{success:!1,report:J6(),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 G6(y,S);if(!Q.success||!Q.ir)return{success:!1,report:K6(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:_6(Z)};let G=b.outputDir??Zn($.outputDir,"generated"),X={outputDir:G,defaultAuth:"user"},Y=X6(Z,X),V=H6(Z,X),O=Y6(Y),K=[...Y,...V,O];if(!b.dryRun)for(let _ of K){let H=Zn(G,_.path),q=O6(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:U6(Z,J,b)}}function J6(){return`# Import Report
|
|
1896
2215
|
|
|
1897
2216
|
## \u274C No Supported Frameworks Detected
|
|
1898
2217
|
|
|
@@ -1909,13 +2228,13 @@ No supported frameworks were detected in the project.
|
|
|
1909
2228
|
- Next.js API Routes
|
|
1910
2229
|
|
|
1911
2230
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
1912
|
-
`}function
|
|
2231
|
+
`}function K6($){return`# Import Report
|
|
1913
2232
|
|
|
1914
2233
|
## \u274C Extraction Failed
|
|
1915
2234
|
|
|
1916
|
-
${$.map((
|
|
2235
|
+
${$.map((b)=>`- ${b.message}`).join(`
|
|
1917
2236
|
`)}
|
|
1918
|
-
`}function
|
|
2237
|
+
`}function _6($){return`# Import Analysis Report
|
|
1919
2238
|
|
|
1920
2239
|
## Summary
|
|
1921
2240
|
|
|
@@ -1935,19 +2254,19 @@ ${$.map((W)=>`- ${W.message}`).join(`
|
|
|
1935
2254
|
|
|
1936
2255
|
## Detected Frameworks
|
|
1937
2256
|
|
|
1938
|
-
${$.project.frameworks.map((
|
|
2257
|
+
${$.project.frameworks.map((b)=>`- ${b.name} (${b.confidence})`).join(`
|
|
1939
2258
|
`)}
|
|
1940
2259
|
|
|
1941
2260
|
## Endpoints
|
|
1942
2261
|
|
|
1943
|
-
${$.endpoints.map((
|
|
2262
|
+
${$.endpoints.map((b)=>`- \`${b.method} ${b.path}\` - ${b.confidence.level}`).join(`
|
|
1944
2263
|
`)}
|
|
1945
2264
|
|
|
1946
2265
|
## Ambiguities (Require Review)
|
|
1947
2266
|
|
|
1948
|
-
${$.ambiguities.length>0?$.ambiguities.map((
|
|
2267
|
+
${$.ambiguities.length>0?$.ambiguities.map((b)=>`- ${b.description}`).join(`
|
|
1949
2268
|
`):"None"}
|
|
1950
|
-
`}function
|
|
2269
|
+
`}function U6($,b,A){return`# Import Report${A.dryRun?" (Dry Run)":""}
|
|
1951
2270
|
|
|
1952
2271
|
## \u2705 Import Successful
|
|
1953
2272
|
|
|
@@ -1959,9 +2278,9 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1959
2278
|
|
|
1960
2279
|
### Generation Summary
|
|
1961
2280
|
|
|
1962
|
-
- **Operations Generated**: ${
|
|
1963
|
-
- **Schemas Generated**: ${
|
|
1964
|
-
- **Total Files**: ${
|
|
2281
|
+
- **Operations Generated**: ${b.operationsGenerated}
|
|
2282
|
+
- **Schemas Generated**: ${b.schemasGenerated}
|
|
2283
|
+
- **Total Files**: ${b.files.length}
|
|
1965
2284
|
|
|
1966
2285
|
### Confidence Breakdown
|
|
1967
2286
|
|
|
@@ -1973,41 +2292,42 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1973
2292
|
|
|
1974
2293
|
### Next Steps
|
|
1975
2294
|
|
|
1976
|
-
1. Review generated contracts in \`${
|
|
2295
|
+
1. Review generated contracts in \`${A.outputDir??"generated/"}\`
|
|
1977
2296
|
2. Fill in TODO placeholders with business context
|
|
1978
2297
|
3. Run \`contractspec validate\` to verify contracts
|
|
1979
2298
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
1980
|
-
`}function
|
|
1981
|
-
`)}function
|
|
1982
|
-
`)}async function
|
|
1983
|
-
`)}function
|
|
1984
|
-
`)}function
|
|
1985
|
-
`)}function
|
|
1986
|
-
`);
|
|
1987
|
-
`)}function
|
|
1988
|
-
`)}async function
|
|
2299
|
+
`}function z6($,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"?"\u274C":w.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";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(`
|
|
2300
|
+
`)}function L6($,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(` \u2022 ${m.name}`);if(A.push(""),b)A.push("\u2705 Verification"),A.push(` Valid: ${b.summary.validEndpoints}`),A.push(` Warnings: ${b.summary.warningEndpoints}`),A.push(` Errors: ${b.summary.errorEndpoints}`),A.push("");return A.join(`
|
|
2301
|
+
`)}async function R6($,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=C6(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 C6($,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 fz($,b="feature-map",A={}){switch(b){case"feature-map":return Yn($,A);case"orphans":return I6($,A);case"dependencies":return E6($,A);case"full":return M6($,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(`
|
|
2302
|
+
`)}function I6($,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(`
|
|
2303
|
+
`)}function E6($,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(`
|
|
2304
|
+
`)}function M6($,b){let A=Yn($,b);if($.orphanedSpecs.length===0)return A;let m=A.split(`
|
|
2305
|
+
`);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(`
|
|
2306
|
+
`)}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 x6,specToMarkdown as I$}from"@contractspec/module.workspace";function cz($,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 dz($,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(`- \u274C **${w.category}**: ${w.message}`);A.push("")}if(n.length>0){A.push("## Warnings"),A.push("");for(let w of n)A.push(`- \u26A0\uFE0F **${w.category}**: ${w.message}`);A.push("")}if(W.length>0){A.push("## Info"),A.push("");for(let w of W)A.push(`- \u2139\uFE0F **${w.category}**: ${w.message}`);A.push("")}return A.join(`
|
|
2307
|
+
`)}async function lz($,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 x6(w.filePath)).find((y)=>y.meta.key===W.name)??null};if($.operations?.length){A.push(`
|
|
1989
2308
|
## Operations (${$.operations.length})
|
|
1990
|
-
`);for(let
|
|
2309
|
+
`);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})
|
|
1991
2310
|
|
|
1992
|
-
*Spec not found*`);
|
|
2311
|
+
*Spec not found*`);A.push("---")}}if($.events?.length){A.push(`
|
|
1993
2312
|
## Events (${$.events.length})
|
|
1994
|
-
`);for(let
|
|
2313
|
+
`);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})
|
|
1995
2314
|
|
|
1996
|
-
*Spec not found*`);
|
|
2315
|
+
*Spec not found*`);A.push("---")}}if($.presentations?.length){A.push(`
|
|
1997
2316
|
## Presentations (${$.presentations.length})
|
|
1998
|
-
`);for(let
|
|
1999
|
-
|
|
2000
|
-
*Spec not found*`);
|
|
2001
|
-
`)}function
|
|
2002
|
-
`)}function
|
|
2003
|
-
`)}function
|
|
2004
|
-
`)}
|
|
2005
|
-
`).
|
|
2006
|
-
${
|
|
2007
|
-
${
|
|
2008
|
-
${
|
|
2009
|
-
|
|
2010
|
-
`).trimEnd()}function eY(){return new RegExp(`${e4($9)}[\\s\\S]*?${e4(W9)}(?:\\r?\\n)?`)}function e4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{generateArtifactsForAudience as $3,generateBiomePreset as W3}from"@contractspec/biome-config";async function kj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"biome.jsonc"),Z=$.join(A,".contractspec","biome"),X=$.join(Z,"plugins"),Y=$.join(Z,"ai"),B=$3("consumer");try{let q=await $.exists(Q);if(q&&W.interactive){if(!await j.confirm(`${Q} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Q,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Q,W3("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(B.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),B.aiRules),{target:"biome-config",filePath:Q,action:q?"merged":"created",message:q?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(q){return{target:"biome-config",filePath:Q,action:"error",message:q instanceof Error?q.message:"Unknown error"}}}async function hj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".contractsrc.json");try{let Z=await $.exists(Q),X=u$(W);if(Z){let Y=await $.readFile(Q),B=r(Y);if(!B)return{target:"cli-config",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Q,action:"skipped",message:"User skipped merge"}}let q=p(B,X);if((W.preset==="connect"||W.preset?.startsWith("builder-"))&&typeof X==="object"&&X!==null){let H={};if("connect"in X)H.connect=X.connect;if("builder"in X)H.builder=X.builder;await $.writeFile(Q,F(y1(q,H)))}else await $.writeFile(Q,F(q));return{target:"cli-config",filePath:Q,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Q,F(X)),{target:"cli-config",filePath:Q,action:"created",message:"Created CLI configuration"}}catch(Z){return{target:"cli-config",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function gj($,W,j){let A=$.join(W.workspaceRoot,".cursor","rules"),Q=$.join(A,"contractspec.mdc");try{let Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=C8(W);if(X)if(W.interactive){if(!await j.confirm(`${Q} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Q,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Q,action:"skipped",message:"File already exists"};return await $.writeFile(Q,Y),{target:"cursor-rules",filePath:Q,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(Z){return{target:"cursor-rules",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function fj($,W,j){let A=qW();try{let Q=await $.exists(A),Z=R8();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Q){let B=await $.readFile(A),q=r(B);if(!q)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let H=p(q,Z);return await $.writeFile(A,F(H)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(A,F(Z)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(Q){return{target:"mcp-claude",filePath:A,action:"error",message:Q instanceof Error?Q.message:"Unknown error"}}}async function uj($,W,j){let A=$.join(W.workspaceRoot,".cursor"),Q=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=q0();if(X){let B=await $.readFile(Q),q=r(B);if(!q)return{target:"mcp-cursor",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Q,action:"skipped",message:"User skipped merge"}}let H=p(q,Y);return await $.writeFile(Q,F(H)),{target:"mcp-cursor",filePath:Q,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Q,F(Y)),{target:"mcp-cursor",filePath:Q,action:"created",message:"Created Cursor MCP configuration"}}catch(Z){return{target:"mcp-cursor",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function dj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".vscode"),Z=$.join(Q,"settings.json");try{if(!await $.exists(Q))await $.mkdir(Q);let Y=await $.exists(Z),B=BW(W);if(Y){let q=await $.readFile(Z),H=r(q);if(!H)return{target:"vscode-settings",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:Z,action:"skipped",message:"User skipped merge"}}let V=p(H,B);if((W.preset==="builder-managed"||W.preset==="builder-hybrid")&&"contractspec.api.baseUrl"in B)V["contractspec.api.baseUrl"]=B["contractspec.api.baseUrl"];return await $.writeFile(Z,F(V)),{target:"vscode-settings",filePath:Z,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(Z,F(B)),{target:"vscode-settings",filePath:Z,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:Z,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var j3={confirm:async($,W)=>W??!0,select:async($,W)=>{return W.find((j)=>j.selected)?.value??W[0]?.value??""},multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function PS($,W,j=j3){let A=[],Q=W.targets.length>0?W.targets:X0,Z=W.workspaceRoot,X=D(Z),Y=W.packageRoot??f(Z),B=W.isMonorepo??e$(X),q=W.packageName??(B?I$(Y):void 0),H=await A9($,[Y,X]),V=W.preset??B0(H);if(W.interactive&&!W.preset)V=await j.select("Select initialization preset:",U8.map((R)=>({value:R,label:L8[R],description:O8[R],selected:R===V})));let G=W.scope??"workspace",J=Y!==X;if(B&&W.interactive&&J)G=await j.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${q??Y})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${X})`,description:"Create config files at the workspace root"}]);let b=B&&G==="package"?Y:X,w=await A9($,[b]),L={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:B,scope:G,packageName:q,preset:V,builderApiBaseUrl:W.builderApiBaseUrl??w?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:W.builderControlPlaneTokenEnvVar??w?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:W.builderLocalRuntimeId??w?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:W.builderLocalGrantedTo??w?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:W.builderLocalProviderIds??w?.builder?.localRuntime?.providerIds,connectStudioEndpoint:W.connectStudioEndpoint??w?.connect?.studio?.endpoint,connectStudioQueue:W.connectStudioQueue??w?.connect?.studio?.queue},z=S8(V,Q);if(W.interactive)z=await j.multiSelect("Select components to configure:",X0.map((R)=>({value:R,label:z8[R],selected:z.includes(R)})));let S=L.projectName;if(W.interactive&&!S){let R=G==="package"&&q?q:b.split("/").pop()??"my-project";S=await j.input("Project name:",R)}let U=L.builderApiBaseUrl;if(W.interactive&&(V==="builder-managed"||V==="builder-hybrid"))U=await j.input("Builder API base URL:",U??"https://api.contractspec.io");let{builderLocalRuntimeId:O,builderLocalGrantedTo:K}=L;if(W.interactive&&(V==="builder-local"||V==="builder-hybrid"))O=await j.input("Default local runtime target id:",O??"rt_local_daemon"),K=await j.input("Default local runtime grant target:",K??"local:operator");let _={...L,projectName:S,targets:z,builderApiBaseUrl:U,builderLocalRuntimeId:O,builderLocalGrantedTo:K};for(let R of z){let v=await A3($,R,_,j);A.push(v)}let I=await EW($,{behavior:_.gitignoreBehavior,interactive:_.interactive,patterns:N8({preset:V}),prompts:j,root:X});if(_.gitignoreBehavior!=="skip"||I.action!=="skipped")A.push(I);let M=A.filter((R)=>R.action!=="error").length,E=A.filter((R)=>R.action==="error").length,C=B?` (${G} level)`:"";return{success:E===0,preset:V,files:A,summary:`Setup complete${C}: ${M} configured, ${E} failed.`,nextSteps:E8(_)}}async function A3($,W,j,A){switch(W){case"agents-md":return Pj($,j,A);case"cli-config":return hj($,j,A);case"biome-config":return kj($,j,A);case"vscode-settings":return dj($,j,A);case"mcp-cursor":return uj($,j,A);case"mcp-claude":return fj($,j,A);case"cursor-rules":return gj($,j,A);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}async function A9($,W){for(let j of W){let A=$.join(j,".contractsrc.json");if(!await $.exists(A))continue;let Q=r(await $.readFile(A));if(Q)return Q}return null}import{validateBlueprint as Q3}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as Z3}from"path";async function iS($,W){let{fs:j}=W,A=Z3(process.cwd(),$);if(!await j.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let Q=await Q$(A),Z=X3(Q.exports),X=Q3(Z);return{spec:Z,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Q){return{valid:!1,errors:[Q instanceof Error?Q.message:String(Q)]}}}function X3($){let W=Object.values($).filter(Y3);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function Y3($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as B3,dirname as nj,join as R0}from"path";async function sS($,W,j,A,Q){let{fs:Z}=Q,X=A.implementationPath;if(!X){let H=nj($),V=B3($,".ts"),G=[R0(H,V.replace(".contracts",".handler")+".ts"),R0(H,V.replace(".presentation","")+".tsx"),R0(H,V.replace(".form",".form")+".tsx"),R0(nj(H),"handlers",V.replace(".contracts",".handler")+".ts"),R0(nj(H),"components",V.replace(".presentation","")+".tsx")];for(let J of G)if(await Z.exists(J)){X=J;break}}if(!X||!await Z.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await Z.readFile(X),q=await new g0(j).validate(W,Y);return{success:q.success,errors:q.errors||[],warnings:q.warnings||[],suggestions:q.suggestions||[],report:q.code}}import{validateBuilderBlueprint as q3,validateBuilderReadinessReport as H3,validateBuilderWorkspace as V3,validateBuilderWorkspaceSnapshot as G3}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as J3,validateExternalPatchProposal as b3,validateProviderRoutingPolicy as w3,validateRuntimeTarget as K3}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as _3,validateLayoutSlots as z3}from"@contractspec/lib.surface-runtime/spec";async function QI($,W){if(!I3($.specType))return{valid:!0,errors:[],warnings:[]};let j=y3($.filePath),A=[`${j}/package.json`,`${j}/README.md`,`${j}/src/index.ts`,$.filePath],Q=[];for(let Y of A)if(!await W.exists(Y))Q.push(`Missing package scaffold file: ${Y}`);if(Q.length>0)return{valid:!1,errors:Q,warnings:[]};let Z;try{Z=(await Q$($.filePath)).exports}catch(Y){return{valid:!1,errors:[Y instanceof Error?Y.message:String(Y)],warnings:[]}}let X=$.specType==="module-bundle"?U3(Z):$.specType==="builder-spec"?L3(Z):O3(Z);return{valid:Q.length===0&&X.errors.length===0,errors:[...Q,...X.errors],warnings:X.warnings.map((Y)=>`[${$.filePath}] ${Y}`)}}function U3($){let W=[],j=[],A=S3($,M3);if(A.length===0)return j.push(cj("module-bundle","bundle")),{errors:W,warnings:j};for(let Q of A){let Z=Object.values(Q.value.surfaces);for(let X of Z){try{z3(X)}catch(Y){W.push(`[${Q.exportName}] ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of _3(X).warnings)j.push(`[${Q.exportName}] ${Y}`)}}return{errors:W,warnings:j}}function L3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(E3(Z)){A+=1,W.push(...PW(Q,V3(Z)));continue}if(N3(Z)){A+=1,W.push(...PW(Q,q3(Z)));continue}if(R3(Z)){A+=1,W.push(...PW(Q,H3(Z)));continue}if(C3(Z))A+=1,W.push(...PW(Q,G3(Z)))}if(A===0)j.push(cj("builder-spec","builder"));return{errors:W,warnings:j}}function O3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(D3(Z)){A+=1,W.push(...kW(Q,K3(Z)));continue}if(T3(Z)){A+=1,W.push(...kW(Q,w3(Z)));continue}if(F3(Z)){A+=1,W.push(...kW(Q,J3(Z)));continue}if(x3(Z))A+=1,W.push(...kW(Q,b3(Z)))}if(A===0)j.push(cj("provider-spec","provider"));return{errors:W,warnings:j}}function S3($,W){return Object.entries($).filter(([j,A])=>j!=="__esModule"&&W(A)).map(([j,A])=>({exportName:j,value:A}))}function PW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function kW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function I3($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function M3($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function E3($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function N3($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function R3($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function C3($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function D3($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function T3($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function F3($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function x3($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function y3($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function cj($,W){return`No recognized ${W} exports were found for ${$} deep validation.`}import{validateSpecStructure as v3}from"@contractspec/module.workspace";function Q9($,W={}){let j=[],A=[],Q;if(!W.skipStructure)Q=v3($),j.push(...Q.errors),A.push(...Q.warnings);return{valid:j.length===0,structureResult:Q,errors:j,warnings:A,code:$.sourceBlock}}async function BI($,W={}){return $.map((j)=>({spec:j,...Q9(j,W)}))}async function m$($,W,j={}){let{fs:A}=W;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let Z=await A.readFile($),X=[],Y=[],B=void 0;if(!j.skipStructure){let q=await $$(W,{pattern:$});for(let H of q){let V=Q9(H,j);B=V.structureResult,X.push(...V.errors),Y.push(...V.warnings)}}return{valid:X.length===0,structureResult:B,errors:X,warnings:Y,code:Z}}async function qI($,W,j={}){let A=new Map;for(let Q of $){let Z=await m$(Q,W,j);A.set(Q,Z)}return A}import{validateConfig as m3}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as lj}from"fs/promises";import{resolve as hW}from"path";async function wI($,W,j,A){let{fs:Q}=A,Z=hW(process.cwd(),W);if(!await Q.exists(Z))return{valid:!1,errors:[`Tenant config file not found: ${Z}`]};try{let X=await P3(Z),Y=await k3(j.connections,Q),B=await h3(j.translationCatalog,Q),q=await g3(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(B)H.translationCatalogs={blueprint:[B],platform:[]};if(q)H.integrationSpecs=q;let V=m3($,X,H);return{config:X,report:V,valid:V.valid,errors:V.errors.map((G)=>`[${G.code}] ${G.path}: ${G.message}`)}}catch(X){return{valid:!1,errors:[X instanceof Error?X.message:String(X)]}}}async function P3($){if($.endsWith(".json")){let A=await lj($,"utf-8"),Q=JSON.parse(A);if(!Z9(Q))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Q}let W=await Q$($),j=Object.values(W.exports).filter(Z9);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function Z9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function q9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function k3($,W){let j=q9($);if(!j.length)return[];let A=[];for(let Q of j){let Z=hW(process.cwd(),Q);if(!await W.exists(Z)){console.warn(`Warning: Connection file not found: ${Z}`);continue}if(Z.endsWith(".json")){let Y=await lj(Z,"utf-8"),B=JSON.parse(Y);A.push(...rj(B));continue}let X=await Q$(Z);A.push(...rj(X.exports))}return A}function rj($){if(Array.isArray($)){let W=$.filter(X9);if(W.length)return W}if(X9($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((A)=>rj(A));if(j.length)return j}return[]}function X9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function h3($,W){if(!$)return;let j=hW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let Z=await lj(j,"utf-8"),X=JSON.parse(Z);if(Y9(X))return B9(X);return}let A=await Q$(j),Q=Object.values(A.exports).filter(Y9);if(Q.length===0)return;return B9(Q[0])}function Y9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function B9($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function g3($){let W=q9($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),A=new j;for(let Q of W){let{modulePath:Z,exportName:X}=f3(Q);if(!Z)continue;let Y=hW(process.cwd(),Z);try{let B=await Q$(Y),q=u3(B.exports,X);if(q)await q(A)}catch(B){console.warn(`Failed to load registrar from ${Y}: ${B}`)}}return A}function f3($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),A=W?.trim()??null,Q=j?.trim();return{modulePath:A,exportName:Q}}function u3($,W){if(W){let j=$[W];if(typeof j==="function")return j;return}if(typeof $.default==="function")return $.default;for(let j of Object.values($))if(typeof j==="function")return j;return}async function NI($,W,j={},A){let{fs:Q,logger:Z}=$,X=await Q.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],B=[],q=A?.validate??((V)=>m$(V,{fs:Q,logger:Z})),H=A?.build??((V,G)=>f$(V,{fs:Q,logger:Z},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let J={specPath:V,outputDir:G};if(j.validate)try{J.validation=await q(V)}catch(b){J.error={phase:"validate",message:b instanceof Error?b.message:String(b)},B.push(J);continue}if(!j.dryRun)try{J.build=await H(V,G)}catch(b){J.error={phase:"build",message:b instanceof Error?b.message:String(b)},B.push(J);continue}else Z.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});B.push(J)}return{specs:X,runs:B}}import{generateText as d3}from"ai";var n3=`
|
|
2317
|
+
`);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})
|
|
2318
|
+
|
|
2319
|
+
*Spec not found*`);A.push("---")}}return A.join(`
|
|
2320
|
+
`)}function T6($,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(`
|
|
2321
|
+
`)}function D6($){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(`
|
|
2322
|
+
`)}function tz($,b,A="generic-mcp"){switch(b){case"guide":return T6($,A);case"rules":return D6($);case"prompt":return I$($,"prompt");case"context":return I$($,"context");case"full":default:return I$($,"full")}}import{readFile as N6}from"fs/promises";import{createRequire as F6}from"module";import{dirname as v6,resolve as jy}from"path";import{pathToFileURL as g6}from"url";import wy from"vm";import Hn from"typescript";async function n$($,b={}){let A=jy(process.cwd(),$),m=b.runtime??r6();try{let n=m==="bun"?await k6(A):await P6(A);return{modulePath:A,exports:n}}catch(n){throw Error(By(A,n))}}async function nL($,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 k6($){return await import(g6($).href)}async function P6($){return await f6($)??{}}function r6(){return typeof globalThis.Bun<"u"?"bun":"node"}var WL={formatModuleLoadError:By,resolveAuthoredModuleValue:Sy};async function f6($){let b=await N6($,"utf-8"),A=Hn.transpileModule(b,{compilerOptions:{module:Hn.ModuleKind.CommonJS,target:Hn.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),m={},n={exports:m},W=F6($),w=wy.createContext({module:n,exports:m,require:W,__dirname:v6($),__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:()=>e6,buildOnboardingPlan:()=>a6,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:h6($),humanGuide:d6($)}}function h6($){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(...c6(A.track,A.reason));return b.join(`
|
|
2323
|
+
`)}function c6($,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 d6($){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(...u6(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(`
|
|
2324
|
+
`)}function u6($,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 o6}from"@contractspec/lib.surface-runtime/runtime/build-context";import{resolveBundle as i6}from"@contractspec/lib.surface-runtime/runtime/resolve-bundle";import{defineModuleBundle as l6}from"@contractspec/lib.surface-runtime/spec/define-module-bundle";async function Qy($,b,A,m){let n=o6({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 i6(l6(t6(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 p6($,b.flatMap((A)=>A.track.connectSurfaces))}function t6($){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 p6($,b){return[...new Set([...$,...b])].sort()}async function a6($,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=s6(["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 e6($,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 s6($){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)"}],$7=[...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:$7}function _n($){return $.filter((b)=>!b.dev)}function Un($){return $.filter((b)=>b.dev)}import{exec as b7}from"child_process";import{promisify as A7}from"util";var m7=A7(b7),n7={confirm:async()=>!0,select:async($,b)=>b[0]?.value??""};async function IL($,b,A=n7){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 m7(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 EL($,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 ML($){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(` \u2022 ${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(` \u2022 ${W.name} - ${W.description}`)}return A.join(`
|
|
2325
|
+
`)}import{RegeneratorService as W7}from"@contractspec/lib.contracts-spec/regenerator";function gL($){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 PL($,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 rL($,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 fL($,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 w7{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=j7(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}
|
|
2326
|
+
${b.note}
|
|
2327
|
+
${A}
|
|
2328
|
+
${b.endMarker}
|
|
2329
|
+
`}function Ln($){return $.replace(/\r\n/g,`
|
|
2330
|
+
`).trimEnd()}function j7($){return new RegExp(`${Vy($.startMarker)}[\\s\\S]*?${Vy($.endMarker)}(?:\\r?\\n)?`)}function Vy($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var y7="<!-- contractspec:init:agents:start -->",B7="<!-- contractspec:init:agents:end -->",S7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Jy={endMarker:B7,note:S7,startMarker:y7};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 Q7,generateBiomePreset as Z7}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=Q7("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,Z7("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 G7="<!-- contractspec:init:usage:start -->",X7="<!-- contractspec:init:usage:end -->",Y7="<!-- This section is managed by `contractspec init` and `contractspec onboard`. Content outside these markers is user-owned and preserved. -->",Ky={endMarker:X7,note:Y7,startMarker:G7};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 H7={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 IR($,b,A=H7){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 q7($,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 q7($,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 O7}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as V7}from"path";async function cR($,b){let{fs:A}=b,m=V7(process.cwd(),$);if(!await A.exists(m))return{valid:!1,errors:[`Blueprint file not found: ${m}`]};try{let n=await n$(m),W=J7(n.exports),w=O7(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 J7($){let b=Object.values($).filter(K7);if(b.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return b[0]}function K7($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as _7,dirname as Nn,join as ob}from"path";async function iR($,b,A,m,n){let{fs:W}=n,w=m.implementationPath;if(!w){let S=Nn($),Q=_7($,".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 U7,validateBuilderReadinessReport as z7,validateBuilderWorkspace as L7,validateBuilderWorkspaceSnapshot as R7}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as C7,validateExternalPatchProposal as I7,validateProviderRoutingPolicy as E7,validateRuntimeTarget as M7}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as x7,validateLayoutSlots as T7}from"@contractspec/lib.surface-runtime/spec";async function sR($,b){if(!g7($.specType))return{valid:!0,errors:[],warnings:[]};let A=i7($.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"?D7(W):$.specType==="builder-spec"?N7(W):F7(W);return{valid:n.length===0&&w.errors.length===0,errors:[...n,...w.errors],warnings:w.warnings.map((j)=>`[${$.filePath}] ${j}`)}}function D7($){let b=[],A=[],m=v7($,k7);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{T7(w)}catch(j){b.push(`[${n.exportName}] ${j instanceof Error?j.message:String(j)}`)}for(let j of x7(w).warnings)A.push(`[${n.exportName}] ${j}`)}}return{errors:b,warnings:A}}function N7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(P7(W)){m+=1,b.push(...Z0(n,L7(W)));continue}if(r7(W)){m+=1,b.push(...Z0(n,U7(W)));continue}if(f7(W)){m+=1,b.push(...Z0(n,z7(W)));continue}if(h7(W))m+=1,b.push(...Z0(n,R7(W)))}if(m===0)A.push(Fn("builder-spec","builder"));return{errors:b,warnings:A}}function F7($){let b=[],A=[],m=0;for(let[n,W]of Object.entries($)){if(n==="__esModule")continue;if(c7(W)){m+=1,b.push(...G0(n,M7(W)));continue}if(d7(W)){m+=1,b.push(...G0(n,E7(W)));continue}if(u7(W)){m+=1,b.push(...G0(n,C7(W)));continue}if(o7(W))m+=1,b.push(...G0(n,I7(W)))}if(m===0)A.push(Fn("provider-spec","provider"));return{errors:b,warnings:A}}function v7($,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 g7($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function k7($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function P7($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function r7($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function f7($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function h7($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function c7($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function d7($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function u7($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function o7($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function i7($){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 l7}from"@contractspec/lib.contracts-spec/app-config/validation";import{validateFeatureSpec as t7}from"@contractspec/lib.contracts-spec/features";import{validateThemeSpec as p7}from"@contractspec/lib.contracts-spec/themes";import{validateSpecStructure as a7}from"@contractspec/module.workspace";async function zy($,b={}){let A=[],m=[],n;if(!b.skipStructure){n=a7($),A.push(...n.errors),m.push(...n.warnings);let W=await e7($);A.push(...W.errors),m.push(...W.warnings)}return{valid:A.length===0,structureResult:n,errors:A,warnings:m,code:$.sourceBlock}}async function jC($,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 yC($,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 e7($){if($.specType!=="app-config"&&$.specType!=="feature"&&$.specType!=="theme")return{errors:[],warnings:[]};try{let b=await n$($.filePath);if($.specType==="app-config"){let n=s7(b.exports,$),W=l7(n);return{errors:W.errors.map((w)=>Uy(w)),warnings:[...W.warnings,...W.info].map((w)=>Uy(w))}}if($.specType==="feature"){let n=$Z(b.exports,$),W=t7(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=bZ(b.exports,$),m=p7(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 s7($,b){return vn($,b.exportName,AZ)}function $Z($,b){return vn($,b.exportName,mZ)}function bZ($,b){return vn($,b.exportName,nZ)}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 AZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&typeof $.meta?.appId==="string"}function mZ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}function nZ($){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 XC($,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 wZ(W),j=await jZ(A.connections,n),y=await yZ(A.translationCatalog,n),B=await BZ(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 wZ($){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 jZ($,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 yZ($,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 BZ($){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}=SZ(n);if(!W)continue;let j=Y0(process.cwd(),W);try{let y=await n$(j),B=QZ(y.exports,w);if(B)await B(m)}catch(y){console.warn(`Failed to load registrar from ${j}: ${y}`)}}return m}function SZ($){if(!$)return{modulePath:null};let[b,A]=$.split("#"),m=b?.trim()??null,n=A?.trim();return{modulePath:m,exportName:n}}function QZ($,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 LC($,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 ZZ}from"ai";var GZ=`
|
|
2011
2331
|
You are an expert software test engineer specializing in ContractSpec.
|
|
2012
2332
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
2013
2333
|
|
|
@@ -2025,7 +2345,7 @@ Generate scenarios covering:
|
|
|
2025
2345
|
- Happy path (valid input, successful execution)
|
|
2026
2346
|
- Edge cases (boundary values, optional fields)
|
|
2027
2347
|
- Error cases (invalid input, business rule violations)
|
|
2028
|
-
`.trim();class
|
|
2348
|
+
`.trim();class XZ{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=`
|
|
2029
2349
|
Generate a TestSpec for the following Operation:
|
|
2030
2350
|
|
|
2031
2351
|
\`\`\`json
|
|
@@ -2034,23 +2354,23 @@ ${JSON.stringify($,null,2)}
|
|
|
2034
2354
|
|
|
2035
2355
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
2036
2356
|
Do not include markdown formatting or explanations, just the JSON.
|
|
2037
|
-
`.trim();try{let{text:
|
|
2038
|
-
`)}function
|
|
2039
|
-
`)}function
|
|
2040
|
-
`);for(let
|
|
2041
|
-
`)}function
|
|
2357
|
+
`.trim();try{let{text:n,usage:W}=await ZZ({model:A,system:GZ,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 DC($,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 NC($,b,A){let{logger:m}=A,n;if(b.registry)n=await HZ(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 FC($,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(YZ(A))b.push(A);return b}function YZ($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function HZ($){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 qZ,Node as jb,Project as OZ,QuoteKind as VZ,SyntaxKind as JZ}from"ts-morph";function KZ($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function cC($,b,A={}){let{fs:m,logger:n}=b;if(!await m.exists($))return{specPath:$,specInfo:KZ($),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=_Z(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 _Z($,b){let m=new OZ({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:qZ.TwoSpaces,quoteKind:VZ.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),n=zZ(m);if(!n)return $;for(let W of b)UZ(n,W);return m.getFullText()}function UZ($,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(JZ.ObjectLiteralExpression);if(!Q)return;m=Q}let n=A[A.length-1];if(!n)return;let W=LZ(b.value),w=m.getProperty(n);if(w&&jb.isPropertyAssignment(w)){w.setInitializer(W);return}m.addPropertyAssignment({name:n,initializer:W})}function zZ($){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 LZ($){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 NZ,DEFAULT_CONTRACTSRC as FZ}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)=>`- ${RZ(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(`
|
|
2358
|
+
`)}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(`
|
|
2359
|
+
`)}function gy($){let b=[`### ${$.summary}`,...rn($,["customer"])];if($.migrationInstructions.length===0)return b.push("- No manual migration steps recorded."),b.join(`
|
|
2360
|
+
`);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(`
|
|
2361
|
+
`)}function fn($){return["# Patch Notes","",...$.releases.map(Fy)].join(`
|
|
2042
2362
|
|
|
2043
|
-
`)}function
|
|
2363
|
+
`)}function hn($){return["# Customer Upgrade Guide","",...$.releases.flatMap((b)=>[vy(b),"",gy(b)])].join(`
|
|
2044
2364
|
|
|
2045
|
-
`)}function
|
|
2365
|
+
`)}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(`
|
|
2046
2366
|
`)).join(`
|
|
2047
|
-
`)}function
|
|
2048
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",
|
|
2049
|
-
`)}import{compareVersions as
|
|
2050
|
-
`),
|
|
2051
|
-
`),!0}async function
|
|
2052
|
-
`),!0}async function
|
|
2053
|
-
`),
|
|
2367
|
+
`)}function yb($,b){let A=b.targetPackages.map((m)=>`${m.name}: ${m.currentVersion??"unknown"} -> ${m.targetVersion??"latest"}`).join(`
|
|
2368
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",A||"- No package version targets were inferred.","","Required steps:",ky(b)].join(`
|
|
2369
|
+
`)}function RZ($){return $.charAt(0).toUpperCase()+$.slice(1)}import{compareVersions as ry,countUpgradePlanStepLevels as CZ,createAgentPromptBundles as IZ,dedupeUpgradePlanSteps as EZ,sortReleaseManifest as Py}from"@contractspec/lib.contracts-spec";function MZ($,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=MZ($,b),W=xZ(n,b),w=EZ(n.flatMap((S)=>S.upgradeSteps)),j=CZ(w),y={generatedAt:new Date().toISOString(),targetPackages:W,releases:n,steps:w,autofixCount:j.auto,manualCount:j.manual,assistedCount:j.assisted,agentPrompts:[]},B=IZ(y,A,m);return{...y,agentPrompts:B}}function xZ($,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 TZ(A,n),y=await DZ(A,n,W),B=j.length>0||y.length>0;return{packageManager:w,packages:j,configUpgrades:y,hasUpgrades:B}}async function TZ($,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 DZ($,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)+`
|
|
2370
|
+
`),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 vZ="**/*.{ts,tsx,js,jsx,mjs,cjs}",oy=FZ.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 kZ(A,m,n),w=await gZ(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=PZ(B,j.packages,j.configUpgrades);return{packageManager:j.packageManager,manifestPath:w.path,plan:S,humanChecklist:rZ(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 fZ(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 gZ($,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 kZ($,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=NZ.safeParse(n);if(W.success)return{...oy,...W.data.upgrade}}catch{continue}}return oy}function PZ($,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 rZ($){return $.steps.map((b)=>`${b.title}: ${b.summary}`)}async function fZ($,b,A){switch(A.kind){case"package-json":return hZ($,b,A);case"contractsrc":return cZ($,b,A);case"import-rewrite":return dZ($,b,A);case"codemod":return!1}}async function hZ($,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)+`
|
|
2371
|
+
`),!0}async function cZ($,b,A){let m=$.join(b,".contractsrc.json"),n=await $.exists(m)?JSON.parse(await $.readFile(m)):{};if(!A.configPath)return!1;return uZ(n,A.configPath,A.value),await $.writeFile(m,JSON.stringify(n,null,2)+`
|
|
2372
|
+
`),!0}async function dZ($,b,A){if(!A.from||!A.to)return!1;let m=await $.glob({pattern:A.path??vZ,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 uZ($,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 oZ,readFileSync as iZ,renameSync as lZ,statSync as tZ,writeFileSync as pZ}from"fs";import{dirname as aZ,join as eZ}from"path";var sZ=".contractspec/verification-cache.json",ty=1;class py{filePath;cache;isDirty=!1;constructor($,b){let A=b??process.cwd();this.filePath=$??eZ(A,sZ),this.cache=new Map,this.loadSync()}loadSync(){try{if(!dn(this.filePath))return;let $=iZ(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 $=aZ(this.filePath);if(!dn($))oZ($,{recursive:!0});let b={version:ty,entries:Object.fromEntries(this.cache.entries())},A=`${this.filePath}.tmp`;pZ(A,JSON.stringify(b,null,2),"utf-8"),lZ(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))$=tZ(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function BI($,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 QI(){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 GI($){return new ey($)}import{createHash as $G}from"crypto";var sy={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function $1($){return $G("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 bG($){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 AG($,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=AG($.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=bG(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 _I($,b){return new A1($,b)}import{generateVerificationPrompt as mG}from"@contractspec/lib.contracts-spec/llm";function nG($){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(`
|
|
2373
|
+
`),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(/^[-*\u2022]\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
|
|
2054
2374
|
{
|
|
2055
2375
|
"passed": true,
|
|
2056
2376
|
"score": 50,
|
|
@@ -2067,23 +2387,23 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
2067
2387
|
],
|
|
2068
2388
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
2069
2389
|
}
|
|
2070
|
-
\`\`\``;try{let
|
|
2390
|
+
\`\`\``;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
|
|
2071
2391
|
{
|
|
2072
2392
|
"passed": false,
|
|
2073
2393
|
"score": 0,
|
|
2074
2394
|
"issues": [
|
|
2075
|
-
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${
|
|
2395
|
+
{ "severity": "error", "category": "semantic", "message": "AI verification failed: ${A instanceof Error?A.message:"Unknown error"}" }
|
|
2076
2396
|
],
|
|
2077
2397
|
"summary": "AI verification encountered an error"
|
|
2078
2398
|
}
|
|
2079
|
-
\`\`\``}}async function
|
|
2399
|
+
\`\`\``}}async function tb($,b={}){let{spec:A,implementationCode:m,implementationPath:n}=$,W=Date.now(),w=mG(A,m),j=await m1(w.taskPrompt,b),y=nG(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.
|
|
2080
2400
|
|
|
2081
2401
|
## Spec Schema Fields
|
|
2082
2402
|
${$}
|
|
2083
2403
|
|
|
2084
2404
|
## Implementation Code
|
|
2085
2405
|
\`\`\`typescript
|
|
2086
|
-
${
|
|
2406
|
+
${b}
|
|
2087
2407
|
\`\`\`
|
|
2088
2408
|
|
|
2089
2409
|
## Task
|
|
@@ -2123,42 +2443,43 @@ Match types:
|
|
|
2123
2443
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
2124
2444
|
- "mismatch": Different meaning despite similar naming
|
|
2125
2445
|
- "missing": Spec field not found in implementation
|
|
2126
|
-
`}function
|
|
2127
|
-
`)}function
|
|
2128
|
-
`),
|
|
2129
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,
|
|
2130
|
-
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function
|
|
2131
|
-
`)}function
|
|
2132
|
-
`)}function
|
|
2133
|
-
`),
|
|
2134
|
-
`).trim()||void 0,
|
|
2135
|
-
${
|
|
2446
|
+
`}function wG($){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(`
|
|
2447
|
+
`)}function jG($){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=wG(A),W=WG(n,m),w=await m1(W,b);return jG(w)}async function yG($,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 BG}from"@contractspec/lib.contracts-spec/operations";function SG($,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 QG($,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 ZG($,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 GG($,b){let A=b.sideEffects?.emits??[],m=[];for(let n of A){let W=BG(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 XG($,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(SG(A,X));for(let X of b.acceptance?.examples??[])W.push(QG(A,X));for(let[X,Y]of Object.entries(b.io.errors??{}))W.push(ZG(A,X,Y));W.push(...GG(A,b));let w=XG(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 YG}from"@contractspec/lib.contracts-spec/operations";function HG($){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 qG($){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 OG($,b){if(qG(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 VG($,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 JG($){let b=/:\s*any\b|as\s+any\b|<any>/,A=$.split(`
|
|
2448
|
+
`),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 KG($,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 _G($,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(YG(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 UG($,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 zG($,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=[HG(A),OG(A,m),VG(A,b),JG(A),KG(A,b),_G(A,b),UG(A,b),zG(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 LG={verbose:!1},RG=["structure","behavior","ai_review"];class K0{config;constructor($={}){this.config={...LG,...$}}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 RG){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?"\u2713 Passed":"\u2717 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?"\u2713 Passed":"\u2717 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"?"\u274C":W.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";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(`
|
|
2449
|
+
`)}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?"\u2713 Verification passed":"\u2717 Verification failed"),A.push(`Score: ${n}/100`),A.push("");for(let y of $){let B=y.passed?"\u2713":"\u2717";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(`
|
|
2450
|
+
`)}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 CG($){return new K0($)}var IG=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:()=>FG,initReleaseArtifacts:()=>_1,getHighestBumpType:()=>on,getBumpTypeFromCommit:()=>un,generateChangelogs:()=>H1,formatKeepAChangelog:()=>ab,formatConventionalChangelog:()=>j1,formatChangelogJson:()=>_0,filterCommitsByScope:()=>vG,filterBumpableCommits:()=>gG,commitsToChangeEntries:()=>ln,commitToChangeEntry:()=>B1,checkReleaseArtifacts:()=>z1,buildReleaseArtifacts:()=>U1,applyVersionBump:()=>Y1,analyzeVersionsFromCommits:()=>Bb,analyzeVersions:()=>AA,DEFAULT_COMMIT_TYPE_MAP:()=>U0});import{basename as EG,dirname as MG}from"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("### \u26A0\uFE0F 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(`
|
|
2451
|
+
`)}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(`
|
|
2452
|
+
`)}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:TG(A,n)}}function xG($){let b=$.split("/"),A=b.lastIndexOf("packages");if(A>=0&&A+2<b.length)return b.slice(0,A+3).join("/");return MG($)}var w1={major:3,minor:2,patch:1};function TG($,b){let A=new Map;for(let m of $){let n=xG(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:EG(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"},DG=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,NG=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function z0($){let b=$.split(`
|
|
2453
|
+
`),A=b[0]?.trim();if(!A)return null;let m=A.match(DG);if(!m)return null;let[,n,W,w,j]=m;if(!n||!j)return null;let y=b.slice(1).join(`
|
|
2454
|
+
`).trim()||void 0,B=y?.match(NG),S=B?.[1];return{type:n.toLowerCase(),scope:W?.toLowerCase(),breaking:!!w||!!B,description:j.trim(),body:y,breakingDescription:S,raw:$}}function FG($){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 vG($,b){return $.filter((A)=>A.scope?.toLowerCase()===b.toLowerCase())}function gG($,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 kG,load as PG}from"js-yaml";var rG=".changeset/*.md",fG=".changeset/*.release.yaml",hG=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,cG=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function dG($,b){return(await $.glob({pattern:rG,cwd:b,absolute:!0})).filter((m)=>$.basename(m)!=="README.md")}async function eb($,b){let A=await dG($,b),m=[];for(let n of A){let W=await $.readFile(n);m.push(uG($.basename(n),W))}return m}async function sb($,b,A){let m=await $.glob({pattern:fG,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=PG(await $.readFile(j)),S=oG(B,y,n.get(y)??[]);W.set(y,S)}catch(B){w.push(iG(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`---
|
|
2455
|
+
${b.map((m)=>`"${m.name}": ${m.releaseType}`).join(`
|
|
2136
2456
|
`)}
|
|
2137
2457
|
---
|
|
2138
2458
|
|
|
2139
2459
|
${$}
|
|
2140
|
-
`}function
|
|
2141
|
-
`)
|
|
2142
|
-
`)}function
|
|
2143
|
-
|
|
2460
|
+
`}function C0($){return kG(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(`
|
|
2461
|
+
`)}function uG($,b){let A=$.replace(/\.md$/,""),m=b.match(hG);if(!m)return{slug:A,summary:b.trim(),packages:[]};let n=m[1]??"",W=(m[2]??"").trim(),w=[];for(let j of n.split(`
|
|
2462
|
+
`)){let y=j.trim().match(cG);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 oG($,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 iG($,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 lG}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=tG(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=lG(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=aG(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 $2($,{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:eG(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=sG(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 tG($,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=pG($,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 pG($,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 aG($,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 eG($){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(`
|
|
2463
|
+
`)}function sG($){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 $2($,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=`${b2()}.md`,G=A.join(Q,Z),X=`---
|
|
2464
|
+
"${B}": ${W}
|
|
2144
2465
|
---
|
|
2145
2466
|
|
|
2146
|
-
${
|
|
2147
|
-
`;if(!Y)await j.writeFile(J,b),A.info("Generated changeset",{filePath:J});else A.info("Would generate changeset",{filePath:J,content:b})}catch(B){A.error("Failed to generate changeset",{error:B instanceof Error?B.message:String(B)})}}function Tq(){let $=["neat","calm","wild","soft","bold","fair","cool"],W=["fox","cat","dog","bat","ant","elk","owl"],j=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],Q=W[Math.floor(Math.random()*W.length)],Z=j[Math.floor(Math.random()*j.length)],X=Math.floor(Math.random()*1000);return`${A}-${Q}-${Z}-${X}`}var e9="generated/releases",tW=yq.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function $A($,W={}){let{fs:j,git:A,logger:Q}=$,Z=D(W.workspaceRoot),X=await A5(j,Z),Y=W.baseline?await A.diffFiles(W.baseline):[],B=W.packages&&W.packages.length>0?W.packages:c9(Y,X),q=W.baseline?await pW($,{baseline:W.baseline,workspaceRoot:Z}):null,H=W.baseline?await F$($,{baseline:W.baseline,workspaceRoot:Z}):null,V=(H?.summary.breaking??0)>0?"major":q?.suggestedBumpType??vq(B),G=W.releaseType??V,J=W.summary??`Describe the ${G} release for ${B[0]??"the workspace"}`,b=W.slug??Pq(J),w=B.map((K)=>({name:K,releaseType:G,version:X.find((_)=>_.name===K)?.version})),L={schemaVersion:"1",slug:b,summary:J,isBreaking:G==="major"||(H?.summary.breaking??0)>0,packages:w,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:J},{kind:"customer",summary:J}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},z=j.join(Z,".changeset",`${b}.md`),S=j.join(Z,".changeset",`${b}.release.yaml`);if(!W.force){if(await j.exists(z))throw Error(`Changeset already exists: ${z}`);if(await j.exists(S))throw Error(`Release capsule already exists: ${S}`)}let U=r9(J,w),O=l9(L);if(!W.dryRun)await j.writeFile(z,U),await j.writeFile(S,O);return Q.info("Initialized release artifacts",{slug:b,workspaceRoot:Z}),{slug:b,changesetPath:z,capsulePath:S,changesetContent:U,capsuleContent:O,packages:w,releaseType:G,isBreaking:L.isBreaking}}async function WA($,W={}){let{fs:j,logger:A}=$,Q=D(W.workspaceRoot),Z=await AA(j,Q),X=j.join(Q,W.outputDir??e9),Y=await W5(j,Q),B=await j5(j,Q,Y),q=await A5(j,Q),H=await Promise.all(Array.from(B.entries()).map(async([U,O])=>{let K=j.join(Q,".changeset",`${U}.release.yaml`),_=await j.stat(K);return{slug:U,version:mq(O,q),summary:O.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:O.isBreaking,packages:O.packages.map((I)=>({...I,version:q.find((M)=>M.name===I.name)?.version??I.version})),affectedRuntimes:[...O.affectedRuntimes],affectedFrameworks:[...O.affectedFrameworks],audiences:[...O.audiences],deprecations:[...O.deprecations],migrationInstructions:[...O.migrationInstructions],upgradeSteps:[...O.upgradeSteps],validation:O.validation}})),V=Fq.parse({generatedAt:new Date().toISOString(),releases:H}),G=W.agentTargets??Z.agentTargets??["codex"],J=D0(V,[],G,p$),b=j.join(X,"manifest.json"),w=j.join(X,"upgrade-manifest.json"),L=j.join(X,"patch-notes.md"),z=j.join(X,"customer-guide.md"),S=Object.fromEntries(J.agentPrompts.map((U)=>[U.agent,j.join(X,"prompts",`${U.agent}.md`)]));if(!W.dryRun){await j.writeFile(b,JSON.stringify(V,null,2)),await j.writeFile(w,JSON.stringify(V,null,2)),await j.writeFile(L,ij(V)),await j.writeFile(z,pj(V));for(let U of J.agentPrompts)await j.writeFile(S[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:X,releasesBuilt:V.releases.length}),{outputDir:X,manifestPath:b,upgradeManifestPath:w,patchNotesPath:L,customerGuidePath:z,promptPaths:S,manifest:V,upgradePlan:J,releasesBuilt:V.releases.length}}async function jA($,W={}){let{fs:j}=$,A=D(W.workspaceRoot),Q=await AA(j,A),Z=j.join(A,W.outputDir??e9),X=[],Y=[],B=[],q=await W5(j,A),H=await j5(j,A,q),V=q.length>0,G=!V&&H.size>0;t$(X,V||G,"changesets",V?`Found ${q.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let J of q)if(!H.has(J.slug)&&Q.requireReleaseCapsule)B.push(`Missing release capsule for changeset ${J.slug}.`);for(let[J,b]of H){if(b.isBreaking&&b.migrationInstructions.length===0)B.push(`Breaking release ${J} is missing migration instructions.`);if(b.validation.commands.length===0)B.push(`Release capsule ${J} is missing validation commands.`);if(b.validation.evidence.length===0)B.push(`Release capsule ${J} is missing validation evidence.`)}if(W.baseline){try{let J=await F$($,{baseline:W.baseline,workspaceRoot:A});if(t$(X,!0,"impact",`Impact status: ${J.status}`),J.summary.breaking>0&&!Array.from(H.values()).some((b)=>b.isBreaking))B.push("Breaking impact detected without a breaking release capsule.")}catch(J){t$(X,!1,"impact",aW(J)),B.push(`Impact detection failed: ${aW(J)}`)}try{let J=await y0($,{baseline:W.baseline,workspaceRoot:A});t$(X,!0,"versioning",`${J.specsNeedingBump} spec(s) need version review.`)}catch(J){t$(X,!1,"versioning",aW(J)),B.push(`Version analysis failed: ${aW(J)}`)}}if(W.strict)for(let J of Q.publishArtifacts??[]){let b=j.join(Z,J);if(!await j.exists(b))B.push(`Missing generated release artifact: ${b}`)}if(t$(X,B.length===0,"capsules",B.length===0?"All release capsules are complete.":B[0]??""),!V&&!G)Y.push("No pending release changesets were found.");return{success:B.length===0,errors:B,warnings:Y,checks:X}}async function AA($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return tW;try{let A=JSON.parse(await $.readFile(j)),Q=xq.safeParse(A);return Q.success?{...tW,...Q.data.release}:tW}catch{return tW}}function vq($){return $.length>0?"minor":"patch"}function mq($,W){return $.packages.map((A)=>W.find((Q)=>Q.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function Pq($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function t$($,W,j,A){$.push({name:j,ok:W,message:A})}function aW($){return $ instanceof Error?$.message:String($)}var wA={};h(wA,{silentLogger:()=>YA,runWorkflow:()=>BA,loadWorkflows:()=>X5,loadVibeConfig:()=>eW,installPack:()=>bA,getWorkflow:()=>HA,exportContext:()=>XA,consoleLogger:()=>Z5,builtinWorkflows:()=>$1,DEFAULT_VIBE_CONFIG:()=>sW});import{existsSync as kq}from"fs";import{readFile as hq}from"fs/promises";import{join as Q5}from"path";import gq from"js-yaml";var sW={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function eW($){let W=$??process.cwd(),j=D(W)??W,A=[Q5(j,".contractspec","vibe","config.json"),Q5(j,".contractspec","vibe","config.yaml"),Q5(j,".contractspec","vibe","config.yml")],Q={};for(let Z of A)if(kq(Z))try{let X=await hq(Z,"utf-8");if(Z.endsWith(".json"))Q=JSON.parse(X);else Q=gq.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${Z}`,X)}return{...sW,...Q}}import{existsSync as fq}from"fs";import{copyFile as uq,mkdir as ZA,readFile as dq,writeFile as nq}from"fs/promises";import{dirname as cq,join as a$}from"path";import{glob as rq}from"glob";var lq=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function XA($){let W=$??process.cwd(),j=D(W)??W,A=await eW(W),Q=a$(j,".contractspec","context"),Z=a$(Q,"files"),X=[...lq],Y=a$(j,".gitignore");if(fq(Y)){let w=(await dq(Y,"utf-8")).split(`
|
|
2148
|
-
`).map((
|
|
2467
|
+
${w}
|
|
2468
|
+
`;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 b2(){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 A2=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??j2(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??y2(Q)),_=(Y?await A.exists(Y):!1)||(V?await A.exists(V):!1),H=await n2(W,m2({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(w2(n));return await A.writeFile(W,y),await A.writeFile(w,B),{source:j,changesetPath:W,capsulePath:w,changesetContent:y,capsuleContent:B}}function m2($){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??B2(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 n2($,b,A,m){if(!$)return b;try{let n=await $.generateStructured({schema:A2,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 w2($){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 j2($,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 y2($){return $.length>0?"minor":"patch"}function J1($){return $.trim().startsWith("Describe the ")}function B2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}import{GeneratedReleaseManifestSchema as S2}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as Q2,DEFAULT_CONTRACTSRC as Z2}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";var K1="generated/releases",E0=Z2.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??G2(y),Z=b.releaseType??Q,G=b.summary??`Describe the ${Z} release for ${y[0]??"the workspace"}`,X=b.slug??Y2(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:X2(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=S2.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=Q2.safeParse(m);return n.success?{...E0,...n.data.release}:E0}catch{return E0}}function G2($){return $.length>0?"minor":"patch"}function X2($,b){return $.packages.map((m)=>b.find((n)=>n.name===m.name)?.version??m.version).find((m)=>typeof m==="string")??"0.0.0"}function Y2($){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 H2}from"fs";import{readFile as q2}from"fs/promises";import{join as pn}from"path";import O2 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(H2(W))try{let w=await q2(W,"utf-8");if(W.endsWith(".json"))n=JSON.parse(w);else n=O2.load(w);break}catch(w){console.warn(`Warning: Failed to parse ${W}`,w)}return{...x0,...n}}import{existsSync as V2}from"fs";import{copyFile as J2,mkdir as C1,readFile as K2,writeFile as _2}from"fs/promises";import{dirname as U2,join as Qb}from"path";import{glob as z2}from"glob";var L2=["**/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=[...L2],j=Qb(A,".gitignore");if(V2(j)){let Y=(await K2(j,"utf-8")).split(`
|
|
2469
|
+
`).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 z2(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(U2(V),{recursive:!0}),await J2(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 _2(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.
|
|
2149
2470
|
Please review them and move selected files to contracts/ directory.
|
|
2150
|
-
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"
|
|
2151
|
-
Running Workflow: ${$.name}`),$.description)
|
|
2152
|
-
`);let
|
|
2153
|
-
\uD83D\uDC49 Step: ${
|
|
2471
|
+
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 R2}from"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(`
|
|
2472
|
+
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.
|
|
2473
|
+
`);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(`
|
|
2474
|
+
\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(" \u2192 Skipped by user."),W.steps.push(j);continue}}}if(!b.dryRun)try{if(w.execute)await w.execute(b);else if(w.command)await C2(w.command,b.root);j.status="pass",W.stepsExecuted.push(w.id),W.steps.push(j),m.log(" \u2713 Completed")}catch(y){let B=y instanceof Error?y.message:String(y);return m.error(` \u274C 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 C2($,b){let A=$.split(" "),m=A[0],n=A.slice(1);if(!m)throw Error("Invalid command");return new Promise((W,w)=>{let j=R2(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 I2}from"fs";import{readdir as E2,readFile as M2}from"fs/promises";import{join as x1}from"path";import x2 from"js-yaml";async function en($){let b=[...D0],A=$??process.cwd(),m=M(A)??A,n=x1(m,".contractspec","vibe","workflows");if(I2(n))try{let W=await E2(n);for(let w of W)if(w.endsWith(".json")||w.endsWith(".yaml")||w.endsWith(".yml")){let j=await M2(x1(n,w),"utf-8");try{let y;if(w.endsWith(".json"))y=JSON.parse(j);else y=x2.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"fs";import{copyFile as D1,mkdir as N1,readdir as F1,stat as T2}from"fs/promises";import{join as E$,resolve as D2}from"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=D2(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 T2(Z)).isFile())await D1(Z,G),w++}}return{success:!0,workflowsInstalled:W,templatesInstalled:w}}import{loadSpecFromSource as N2}from"@contractspec/module.workspace";var k1=["product","eng","qa"];function F2($){return k1.includes($)}async function yM($,b){if(!F2(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 v2($,{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 g2(w,b.audience,$);W.push({filePath:w,content:j})}return{views:W,totalSpecs:m,changedFilesCount:n,status:"success"}}async function v2($,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 g2($,b,A){if(!await A.fs.exists($))throw Error(`File not found: ${$}`);let m=await N2($);if(m.length===0)return`No specs found in ${$} (Parse result empty)`;return m.map((n)=>k2(n,b)).join(`
|
|
2154
2475
|
|
|
2155
2476
|
---
|
|
2156
2477
|
|
|
2157
|
-
`)}function
|
|
2158
|
-
`)}function
|
|
2478
|
+
`)}function k2($,b){let A=[];switch(b){case"product":P2($,A);break;case"eng":r2($,A);break;case"qa":f2($,A);break}return A.join(`
|
|
2479
|
+
`)}function P2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Product (User Flow & Capabilities)"),b.push(""),$.meta.goal)b.push(`### Goal
|
|
2159
2480
|
${$.meta.goal}
|
|
2160
|
-
`);if($.meta.context)
|
|
2481
|
+
`);if($.meta.context)b.push(`### Context
|
|
2161
2482
|
${$.meta.context}
|
|
2162
|
-
`);if($.specType==="feature"){if($.operations?.length)
|
|
2163
|
-
`);if($.testRefs?.length)
|
|
2164
|
-
`)}export{
|
|
2483
|
+
`);if($.specType==="feature"){if($.operations?.length)b.push("### Capabilities (Operations)"),$.operations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("");if($.presentations?.length)b.push("### User Interfaces (Presentations)"),$.presentations.forEach((A)=>b.push(`- **${A.name}**`)),b.push("")}else if($.specType==="operation"){if(b.push("### Behavior"),$.hasPolicy)b.push("- \u2705 Enforces Business Policies");if($.hasIo)b.push("- \u2705 Validates Inputs/Outputs");if($.emittedEvents?.length)b.push("### Triggers"),$.emittedEvents.forEach((A)=>b.push(`- **${A.name}** (Event)`))}else b.push(`Type: ${$.specType}`)}function r2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: Engineering (API, Schemas, Constraints)"),b.push(""),b.push(`- **Type**: \`${$.specType}\``),b.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)b.push(`- **Stability**: \`${$.meta.stability}\``);if(b.push(""),$.specType==="operation"){if(b.push("### Contract Details"),b.push(`- **I/O Schema**: ${$.hasIo?"\u2705 Defined":"\u274C Missing"}`),b.push(`- **Policy Config**: ${$.hasPolicy?"\u2705 Defined":"\u274C None"}`),b.push(""),$.emittedEvents?.length)b.push("### Emitted Events"),$.emittedEvents.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}else if($.specType==="feature"){if($.operations?.length)b.push("### Operations"),$.operations.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("");if($.events?.length)b.push("### Events"),$.events.forEach((A)=>b.push(`- \`${A.name}\``)),b.push("")}if($.sourceBlock)b.push("### Source Signature"),b.push("```typescript"),b.push($.sourceBlock),b.push("```")}function f2($,b){if(b.push(`# ${$.meta.key}`),b.push("**View**: QA (Scenarios, Test Coverage)"),b.push(""),$.meta.goal)b.push(`**Goal**: ${$.meta.goal}
|
|
2484
|
+
`);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 ZM($,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 YM($,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 HM($,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 qM($,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 OM($){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(`
|
|
2485
|
+
`)}export{ZM as watchSpecs,g1 as vibe,R1 as versioning,yG as verifyWithAIEnhanced,tb as verifyWithAI,pb as verifyStructure,IG as verifyService,n1 as verifySemanticFields,R6 as verifyImportedContracts,cz as verifyImplementationAgainstParsedSpec,J0 as verifyBehavior,XC as validateTenantConfig,yC as validateSpecs,d$ as validateSpec,zy as validateScannedSpec,sR as validatePackageScaffold,iR as validateImplementationWithAgent,dA as validateImplementationFiles,jC as validateDiscoveredSpecs,cR as validateBlueprint,F2 as validateAudience,WU as validateAgainstOpenApiService,Ew as utils,ly as upgrade,cC as updateSpec,TS as toKebabCase,Kw as templates,AU as syncWithOpenApiService,LC as syncSpecs,bG as stringToCacheKey,Tn as setupUsageMd,sA as setupGitignore,Rn as setupAgentsMd,fL as searchRegistry,p as safeParseJson,DC as runTests,NC as runTestSpecs,IR as runSetup,IL as runQuickstart,ew as runDoctor,IJ as runCIChecks,Fw as resolveSetupTargets,U$ as resolveSetupPreset,zn as resolveRegistryUrl,kS as resolveImplementations,wm as resolveDefaultBuildTargets,Sy as resolveAuthoredModuleValue,Sj as resolveAllImplementations,ub as renderManagedMarkdownBlock,IW as prompts,HW as parseGitModules,jj as parseExplicitImplementations,vY as operationRegistry,Hy as onboarding,Ln as normalizeMarkdownContent,Sx as module,qM as mergeMonorepoConfigs,Q0 as mergeManagedMarkdown,FQ as mergeGitignoreContent,g as loadWorkspaceConfig,fO as loadPackageAuthoredDocBlocks,yy as loadAuthoredModuleValue,nL as loadAuthoredModuleIfExists,y0 as loadAuthoredModuleExports,n$ as loadAuthoredModule,rO as loadAuthoredDocBlocksFromSourceFiles,FC as listTests,v2 as listSpecsForView,j$ as listSpecs,rL as listFromRegistry,bm as listAgentTypes,Gb as isMonorepo,EL as isContractSpecInstalled,vq as isConnectPreset,Fq as isBuilderPreset,zb as inferSetupPresetFromConfig,xS as inferImplementationType,V6 as importFromSourceService,lj as importFromOpenApiService,Uj as impact,Wy as hooks,pV as groupSpecsByType,UB as getWorkspacePackages,OW as getWorkspaceInfo,LX as getRunCommand,_n as getProductionDependencies,T$ as getPackageName,LB as getMetaRepoInfo,VW as getInstallCommand,qV as getImplementationSummary,Oq as getGraphStats,YM as getExtendedWorkspaceInfo,RX as getExecCommand,Un as getDevDependencies,Kn as getDependencies,wj as getConventionPaths,Hq as getContractNode,gA as getClaudeDesktopConfigPath,Om as getBuilderRuntimeModeForPreset,vw as getBuilderBootstrapPresetForSetupPreset,Rw as getApiKey,kV as getAllSpecs,$O 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,yM as generateViews,g2 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,fz as generateMermaidDiagram,z6 as generateMarkdownReport,Gw as generateKnowledgeSpaceSpec,uW as generateJobSpec,Zw as generateIntegrationSpec,aW as generateHarnessSuiteSpec,pW as generateHarnessScenarioSpec,yw as generateHandlerTemplate,T6 as generateGuideFromParsedSpec,jw as generateFormSpec,ww as generateFeatureSpec,lz as generateFeatureContextMarkdown,Ww as generateExperimentSpec,iW as generateExampleSpec,nw as generateEventSpec,bj as generateDocsFromSpecs,mw as generateDataViewSpec,_A as generateDataViewRendererTemplate,D6 as generateCursorRulesFromParsedSpec,rw as generateCursorRules,Lb as generateCursorMcpConfig,bb as generateContractsrcConfig,Bw as generateComponentTemplate,L6 as generateCliReport,Pw as generateClaudeMcpConfig,fW as generateCapabilitySpec,mj as generateArtifacts,Aw as generateAppBlueprintSpec,fw as generateAgentsGuide,lW as generateAgentSpec,xW as formatters,OM as formatWorkspaceInfo,dz as formatVerificationReport,ML as formatQuickstartPreview,By as formatModuleLoadError,N as formatJson,Xz as formatFiles,EO as formatDoctorSummary,MO as formatCheckResult,$y as fix,M as findWorkspaceRoot,r as findPackageRoot,qW as findMetaRepoRoot,HM as findAllConfigFiles,PV as filterIssuesByType,rV as filterIssuesBySeverity,pj as features,nj as extractSpecReferences,YU as extractContracts,tz as exportSpecForLLM,E4 as exportOpenApi,qq as exportGraphAsDot,Uw as ensurePackageScaffold,xA as discoverSpecs,g$ as discoverSpecFiles,PA as discoverLayers,uA as discoverImplementationsForSpec,ZV as discoverAllImplementations,yj as determineStatus,RB as detectRepositoryType,o$ as detectPackageManager,r_ as deleteSpec,$$ as deepMergePreserve,Vm as deepMergeOverwrite,HA as cursorCLIAdapter,GI as createWorkspaceStateCacheStorage,tB as createWorkspaceRegistry,CG as createVerifyService,_I as createVerificationCacheService,N_ as createSpecCreator,gw as createSetupNextSteps,kw as createSetupGitignorePatterns,gL as createRegeneratorService,V0 as createQuickAIReview,zw as createPackageTargetSpecSource,QW as createNoopLoggerAdapter,ZW as createNodeWatcherAdapter,BW as createNodeGitAdapter,jW as createNodeFsAdapter,mW as createNodeAiAdapter,XX as createNodeAdapters,QI as createInMemoryCacheStorage,BI as createFileSystemCacheStorage,P9 as createEmptyLayerInventory,SW as createConsoleLoggerAdapter,JX as createBunFsAdapter,q9 as createBuilderWorkspaceId,C5 as createAgentGuideService,cj as connect,$1 as computeContentHash,c_ as compareSpecs,vJ as cleanArtifacts,XA as claudeCodeAdapter,b1 as cacheKeyToString,$b as buildSpec,DA as analyzeWorkspaceDocBlocks,oA as analyzeIntegrity,Oz as analyzeGap,Mw as analyzeDeps,I5 as agentGuideService,$m as agentAdapters,s0 as adoption,PL as addToRegistry,WL as __moduleLoaderInternals,ey as WorkspaceStateCacheStorage,K0 as VerifyService,A1 as VerificationCacheService,k1 as VALID_AUDIENCES,XZ 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,w7 as RuleSyncService,S0 as RegistryClient,eB as PrActionService,jA as OpenAICodexAgent,qy as MINIMAL_DEPENDENCIES,ay as InMemoryCacheStorage,qA as GenericMCPAdapter,py as FileSystemCacheStorage,$7 as FULL_DEPENDENCIES,pB 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,G7 as CONTRACTSPEC_USAGE_BLOCK_START,X7 as CONTRACTSPEC_USAGE_BLOCK_END,y7 as CONTRACTSPEC_AGENTS_BLOCK_START,B7 as CONTRACTSPEC_AGENTS_BLOCK_END,xJ 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,MJ as ALL_CI_CHECK_CATEGORIES,pw as ALL_CHECK_CATEGORIES,A0 as AIGenerator};
|