@contractspec/bundle.workspace 4.3.0 → 4.4.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/contracts/operations/init.operation.d.ts +1 -1
- package/dist/index.js +771 -526
- package/dist/node/index.js +771 -526
- package/dist/services/build.d.ts +36 -1
- package/dist/services/connect/init.d.ts +2 -6
- package/dist/services/connect/types.d.ts +10 -0
- package/dist/services/contractsrc-schema-ref.d.ts +4 -0
- package/dist/services/deps.d.ts +2 -0
- package/dist/services/discover.d.ts +15 -0
- package/dist/services/discover.test.d.ts +1 -0
- package/dist/services/generate-artifacts.d.ts +4 -0
- package/dist/services/index.d.ts +3 -0
- package/dist/services/integrity.d.ts +2 -0
- package/dist/services/module-loader.d.ts +25 -0
- package/dist/services/module-loader.test.d.ts +1 -0
- package/dist/services/package-scaffold.d.ts +22 -0
- package/dist/services/setup/config-generators.d.ts +1 -1
- package/dist/services/setup/gitignore.d.ts +10 -0
- package/dist/services/setup/gitignore.test.d.ts +1 -0
- package/dist/services/setup/index.d.ts +2 -0
- package/dist/services/setup/presets.d.ts +16 -0
- package/dist/services/setup/targets/cli-config.test.d.ts +1 -0
- package/dist/services/setup/types.d.ts +36 -2
- package/dist/services/update.test.d.ts +1 -0
- package/dist/services/validate/index.d.ts +1 -0
- package/dist/services/validate/module-loader-usage.test.d.ts +1 -0
- package/dist/services/validate/package-scaffold-validator.d.ts +8 -0
- package/dist/services/validate/package-scaffold-validator.test.d.ts +1 -0
- package/dist/services/validate/spec-validator.d.ts +6 -1
- package/dist/services/vibe/definitions.test.d.ts +1 -0
- package/dist/templates/data-view-renderer.template.d.ts +6 -0
- package/dist/templates/feature.template.d.ts +7 -6
- package/dist/templates/form.template.d.ts +16 -0
- package/dist/templates/form.template.test.d.ts +1 -0
- package/dist/templates/index.d.ts +3 -0
- package/dist/templates/workflow-devkit.template.d.ts +11 -0
- package/dist/utils/index.d.ts +0 -1
- package/package.json +8 -8
- package/dist/utils/module-loader.d.ts +0 -1
package/dist/node/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)){if(!Y)continue;let[q,
|
|
3
|
-
`).filter(Boolean)}catch{return[]}}}}function
|
|
4
|
-
`).map((X)=>X.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let j=
|
|
1
|
+
import{createRequire as SA}from"node:module";var UA=Object.defineProperty;var LA=($)=>$;function OA($,W){this[$]=LA.bind(null,W)}var h=($,W)=>{for(var j in W)UA($,j,{get:W[j],enumerable:!0,configurable:!0,set:OA.bind(W,j)})};var B5=($,W)=>()=>($&&(W=$($=0)),W);var O$=SA(import.meta.url);import{ContractsrcSchema as cZ,DEFAULT_CONTRACTSRC as AW}from"@contractspec/lib.contracts-spec/workspace-config";async function m($,W){let j=$.join(W??".",".contractsrc.json");if(!await $.exists(j))return AW;try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=cZ.safeParse(Z);return{...AW,...X.data,conventions:{...AW.conventions,...X.data?.conventions||{}}}}catch{return AW}}function J8($){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 i=()=>{};var D4={};h(D4,{AIGenerator:()=>CW});import{createProvider as L2}from"@contractspec/lib.ai-providers";import{buildComponentPrompt as O2,buildEventSpecPrompt as S2,buildFormPrompt as I2,buildHandlerPrompt as M2,buildOperationSpecPrompt as E2,buildPresentationSpecPrompt as N2,buildTestPrompt as R2,getCodeGenSystemPrompt as O0,getSystemPrompt as Oj}from"@contractspec/module.workspace";import{generateObject as Sj,generateText as RW,streamText as C2}from"ai";import*as N from"zod";class CW{config;constructor($){this.config=$}getModel(){let $=this.config.aiProvider,W=this.config.customApiKey||J8(this.config.aiProvider),j={provider:$==="custom"?"openai":$,model:this.config.aiModel,apiKey:W,baseUrl:this.config.customEndpoint||void 0};return L2(j).getModel()}async generateOperationSpec($,W){let j=this.getModel(),A=N.object({name:N.string().describe('Dot notation name like "domain.operation"'),version:N.number().int().positive().default(1),description:N.string().describe("Clear, concise summary"),goal:N.string().describe("Business purpose"),context:N.string().describe("Background and constraints"),stability:N.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:N.array(N.string()).describe("Team/person owners with @ prefix"),tags:N.array(N.string()).describe("Categorization tags"),auth:N.enum(["anonymous","user","admin"]).describe("Required auth level"),inputShape:N.string().describe("Description of input structure"),outputShape:N.string().describe("Description of output structure"),flags:N.array(N.string()).describe("Feature flags").default([]),possibleEvents:N.array(N.string()).describe("Events this may emit").default([]),analytics:N.array(N.string()).describe("Analytics events to track").default([])}),Q=E2($,W);return(await Sj({model:j,schema:A,prompt:Q,system:Oj()})).object}async generateEventSpec($){let W=this.getModel(),j=N.object({name:N.string().describe('Dot notation name like "domain.event_name"'),version:N.number().int().positive().default(1),description:N.string().describe("When this event is emitted"),stability:N.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:N.array(N.string()).default([]),tags:N.array(N.string()).default([]),payloadShape:N.string().describe("Description of event payload"),piiFields:N.array(N.string()).describe("PII field paths").default([])}),A=S2($);return(await Sj({model:W,schema:j,prompt:A,system:Oj()})).object}async generatePresentationSpec($,W){let j=this.getModel(),A=N.object({name:N.string(),version:N.number().int().positive().default(1),description:N.string(),stability:N.enum(["experimental","beta","stable","deprecated"]).default("beta"),owners:N.array(N.string()).default([]),tags:N.array(N.string()).default([]),componentKey:N.string().optional(),propsShape:N.string().optional(),content:N.string().optional(),mimeType:N.string().optional(),dataShape:N.string().optional()}),Q=N2($,W);return(await Sj({model:j,schema:A,prompt:Q,system:Oj()})).object}async generateHandler($){let W=this.getModel();return(await RW({model:W,prompt:M2($),system:O0()})).text}async generateComponent($){let W=this.getModel();return(await RW({model:W,prompt:O2($),system:O0()})).text}async generateForm($){let W=this.getModel();return(await RW({model:W,prompt:I2($),system:O0()})).text}async generateTests($,W,j){let A=this.getModel();return(await RW({model:A,prompt:R2($,W,j),system:O0()})).text}async streamCodeGeneration($,W){let j=this.getModel(),A=await C2({model:j,prompt:$,system:O0()}),Q="";for await(let Z of A.textStream)Q+=Z,W(Z);return Q}}var DW=B5(()=>{i()});import*as XR from"@contractspec/module.workspace";import{anthropic as IA}from"@ai-sdk/anthropic";import{openai as q5}from"@ai-sdk/openai";import{DEFAULT_MODELS as H5}from"@contractspec/lib.ai-providers/models";import{generateObject as MA,generateText as EA,streamText as NA}from"ai";import{ollama as RA}from"ollama-ai-provider";function V5($){return{async validateProvider(W){try{let{aiProvider:j}=W;if(j==="ollama")return{success:!0};if(j==="claude"&&!process.env.ANTHROPIC_API_KEY)return{success:!1,error:"ANTHROPIC_API_KEY environment variable not set"};if(j==="openai"&&!process.env.OPENAI_API_KEY)return{success:!1,error:"OPENAI_API_KEY environment variable not set"};return{success:!0}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}},async generateText(W){let j=W1($);return{text:(await EA({model:j,prompt:W.prompt,system:W.systemPrompt})).text}},async generateStructured(W){let A={model:W1($),schema:W.schema,prompt:W.prompt,system:W.systemPrompt};return{object:(await MA(A)).object}},async streamText(W,j){let A=W1($),Q=await NA({model:A,prompt:W.prompt,system:W.systemPrompt}),Z="";for await(let X of Q.textStream)Z+=X,j(X);return Z}}}function W1($){let{aiProvider:W,aiModel:j,customEndpoint:A}=$;switch(W){case"claude":{let Q=j??H5.anthropic;return IA(Q)}case"openai":{let Q=j??H5.openai;return q5(Q)}case"ollama":return RA(j??"codellama");case"custom":{if(!A)throw Error("Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var");return q5(j??"default")}default:throw Error(`Unknown AI provider: ${W}`)}}import{DEFAULT_CONTRACTSRC as nA}from"@contractspec/lib.contracts-spec/workspace-config";import{access as CA,stat as DA,mkdir as G5,readFile as TA,rm as FA,writeFile as xA}from"node:fs/promises";import{basename as yA,dirname as J5,isAbsolute as vA,join as mA,relative as PA,resolve as b5}from"node:path";import{glob as kA}from"glob";var Y$=["**/*.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"],S$=["**/.git/**","**/node_modules/**","**/dist/**","**/build/**","**/.turbo/**","**/.next/**","**/coverage/**","**/*.d.ts","**/importer/**","**/exporter/**","**/docs/presentations.ts"];function w5($){let W=$??process.cwd();return{async exists(A){try{return await CA(j(A)),!0}catch{return!1}},async readFile(A){return TA(j(A),"utf-8")},async writeFile(A,Q){let Z=j(A),X=J5(Z);await G5(X,{recursive:!0}),await xA(Z,Q,"utf-8")},async remove(A){await FA(j(A),{recursive:!0,force:!0})},async stat(A){let Q=await DA(j(A));return{size:Q.size,isFile:Q.isFile(),isDirectory:Q.isDirectory(),mtime:Q.mtime}},async mkdir(A){await G5(j(A),{recursive:!0})},async glob(A){let Q=A.patterns??(A.pattern?[A.pattern]:Y$),Z=A.ignore??S$,X=A.cwd??W,Y=A.absolute??!0;return(await kA(Q,{cwd:X,ignore:Z,absolute:Y})).sort((q,H)=>q.localeCompare(H))},resolve(...A){let[Q,...Z]=A;if(!Q)return W;return b5(W,Q,...Z)},dirname(A){return J5(A)},basename(A){return yA(A)},join(...A){return mA(...A)},relative(A,Q){return PA(A,Q)}};function j(A){return vA(A)?A:b5(W,A)}}import{execFileSync as s$}from"node:child_process";import{access as hA}from"node:fs/promises";import{resolve as K5}from"node:path";function _5($){let W=$??process.cwd();return{async currentBranch(){try{let j=s$("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();return j.length>0?j:void 0}catch{return}},async showFile(j,A){try{return s$("git",["show",`${j}:${A}`],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}catch(Q){throw Error(`Could not load ${A} at ref ${j}: ${Q instanceof Error?Q.message:String(Q)}`)}},async clean(j){let A=[];if(j?.force)A.push("-f");if(j?.directories)A.push("-d");if(j?.ignored)A.push("-x");if(j?.dryRun)A.push("--dry-run");s$("git",["clean",...A],{cwd:W,stdio:"inherit"})},async isGitRepo(j){let A=j?K5(W,j):W;try{return await hA(K5(A,".git")),!0}catch{return!1}},async log(j){let A=j??"HEAD~10",Q="--format=%H|||%s|||%an|||%aI";try{let Z=s$("git",["log",`${A}..HEAD`,"--format=%H|||%s|||%an|||%aI"],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}),X=[];for(let Y of Z.trim().split(`
|
|
2
|
+
`)){if(!Y)continue;let[B,q,H,V]=Y.split("|||");if(B&&q)X.push({hash:B,message:q,author:H,date:V})}return X}catch{return[]}},async diffFiles(j,A){try{let Q=A&&A.length>0?["--",...A]:[];return s$("git",["diff","--name-only",`${j}...HEAD`,...Q],{cwd:W,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim().split(`
|
|
3
|
+
`).filter(Boolean)}catch{return[]}}}}function z5(){return{debug($,W){if(process.env.DEBUG)console.debug(`[DEBUG] ${$}`,W??"")},info($,W){console.info(`[INFO] ${$}`,W??"")},warn($,W){console.warn(`[WARN] ${$}`,W??"")},error($,W){console.error(`[ERROR] ${$}`,W??"")},createProgress(){return gA()}}}function U5(){let $=()=>{};return{debug:$,info:$,warn:$,error:$,createProgress:fA}}function gA(){return{start($){console.warn(`⏳ ${$}`)},update($){let W=$.current!==void 0&&$.total!==void 0?` (${$.current}/${$.total})`:"";console.warn(` ${$.message}${W}`)},succeed($){console.warn(`✅ ${$??"Done"}`)},fail($){console.error(`❌ ${$??"Failed"}`)},warn($){console.warn(`⚠️ ${$??"Warning"}`)},stop(){}}}function fA(){let $=()=>{};return{start:$,update:$,succeed:$,fail:$,warn:$,stop:$}}import uA from"chokidar";var dA=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**","**/build/**","**/coverage/**","**/*.d.ts"];function L5($){let W=$??process.cwd();return{watch(j){let A=[],Q,Z=uA.watch(j.pattern,{cwd:W,ignored:j.ignore??dA,persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:250,pollInterval:50}}),X=(Y)=>{if(j.debounceMs&&j.debounceMs>0)clearTimeout(Q),Q=setTimeout(()=>{A.forEach((B)=>B(Y))},j.debounceMs);else A.forEach((B)=>B(Y))};return Z.on("add",(Y)=>{X({type:"add",path:Y})}),Z.on("change",(Y)=>{X({type:"change",path:Y})}),Z.on("unlink",(Y)=>{X({type:"unlink",path:Y})}),{on(Y){A.push(Y)},async close(){clearTimeout(Q),await Z.close()}}}}}function kH($={}){let{cwd:W,config:j,silent:A}=$,Q=j??nA;return{fs:w5(W),git:_5(W),watcher:L5(W),ai:V5(Q),logger:A?U5():z5()}}import{stat as cA,mkdir as rA}from"node:fs/promises";import{basename as lA,dirname as oA,isAbsolute as iA,join as pA,relative as tA,resolve as O5}from"node:path";import{glob as aA}from"glob";function nH($){let W=$??process.cwd();return{async exists(A){let Q=Bun.file(j(A));try{return await Q.exists(),!0}catch{return!1}},async readFile(A){return Bun.file(j(A)).text()},async writeFile(A,Q){let Z=j(A);await Bun.write(Z,Q)},async remove(A){await Bun.file(j(A)).delete()},async stat(A){let Q=await cA(j(A));return{size:Q.size,isFile:Q.isFile(),isDirectory:Q.isDirectory(),mtime:Q.mtime}},async mkdir(A){await rA(j(A),{recursive:!0})},async glob(A){let Q=A.patterns??(A.pattern?[A.pattern]:Y$),Z=A.ignore??S$,X=A.cwd??W,Y=A.absolute??!0;return await aA(Q,{cwd:X,ignore:Z,absolute:Y})},resolve(...A){let[Q,...Z]=A;if(!Q)return W;return O5(W,Q,...Z)},dirname(A){return oA(A)},basename(A){return lA(A)},join(...A){return pA(...A)},relative(A,Q){return tA(A,Q)}};function j(A){return iA(A)?A:O5(W,A)}}import{existsSync as g,readFileSync as G$}from"node:fs";import{tmpdir as sA}from"node:os";import{dirname as j1,isAbsolute as eA,join as k,relative as $Q,resolve as P$}from"node:path";var S5={"bun.lockb":"bun","bun.lock":"bun","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm"},I5=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json"];function WQ($,W){let j=$Q(W,$);return j===""||!j.startsWith("..")&&!eA(j)}function A1($){let W=P$($),j=P$(sA());return WQ(W,j)?j:void 0}function f($=process.cwd()){let W=P$($),j=A1($);while(!0){if(g(k(W,"package.json")))return W;let A=j1(W);if(A===W||W===j)break;W=A}return $}function D($=process.cwd()){let W=P$($),j=null,A=A1($);while(!0){for(let X of I5)if(g(k(W,X)))return W;let Q=k(W,"package.json");if(g(Q)){j=W;try{if(JSON.parse(G$(Q,"utf-8")).workspaces)return W}catch{}}for(let X of Object.keys(S5))if(g(k(W,X)))return W;let Z=j1(W);if(Z===W||W===A)break;W=Z}return j??$}function k$($=process.cwd()){let W=["bun","pnpm","yarn","npm"];for(let A of W){let Q=Object.entries(S5).filter(([,Z])=>Z===A);for(let[Z]of Q)if(g(k($,Z)))return A}let j=k($,"package.json");if(g(j))try{let A=JSON.parse(G$(j,"utf-8"));if(A.packageManager){let Q=A.packageManager.match(/^(bun|pnpm|yarn|npm)@/);if(Q)return Q[1]}}catch{}if(process.env.BUN_INSTALL||typeof globalThis.Bun<"u")return"bun";return"npm"}function e$($=process.cwd()){for(let j of I5)if(g(k($,j)))return!0;let W=k($,"package.json");if(g(W))try{if(JSON.parse(G$(W,"utf-8")).workspaces)return!0}catch{}return!1}function jQ($){let W=k($,"pnpm-workspace.yaml");if(g(W))try{let Q=G$(W,"utf-8").match(/packages:\s*\n((?:\s+-\s+['"]?[^\n]+['"]?\n?)+)/);if(Q?.[1])return Q[1].split(`
|
|
4
|
+
`).map((X)=>X.replace(/^\s+-\s+['"]?|['"]?\s*$/g,"")).filter(Boolean)}catch{}let j=k($,"package.json");if(g(j))try{let A=JSON.parse(G$(j,"utf-8"));if(Array.isArray(A.workspaces))return A.workspaces;if(A.workspaces?.packages&&Array.isArray(A.workspaces.packages))return A.workspaces.packages}catch{}return}function I$($){let W=k($,"package.json");if(g(W))try{return JSON.parse(G$(W,"utf-8")).name}catch{}return}function M5($){let W=k($,".gitmodules");if(!g(W))return[];try{let j=G$(W,"utf-8"),A=[],Q=/\[submodule\s+"([^"]+)"\]\s*\n\s*path\s*=\s*(\S+)\s*\n\s*url\s*=\s*(\S+)/g,Z;while((Z=Q.exec(j))!==null){let[,X,Y,B]=Z;if(X&&Y&&B){let q=k($,Y),H=g(k(q,"package.json"))&&AQ(q);A.push({name:X,path:Y,url:B,absolutePath:q,hasWorkspaces:H})}}return A}catch{return[]}}function AQ($){let W=k($,"package.json");if(g(W))try{let j=JSON.parse(G$(W,"utf-8"));return Boolean(j.workspaces)}catch{}return g(k($,"pnpm-workspace.yaml"))}function E5($){let W=P$($),j=A1($);while(!0){if(g(k(W,".gitmodules")))return W;let A=j1(W);if(A===W||W===j)break;W=A}return}function QQ($){let W=E5($);if(!W)return;let j=M5(W);if(j.length===0)return;let A=P$($),Q=j.find((Z)=>A.startsWith(Z.absolutePath));return{root:W,submodules:j,activeSubmodule:Q}}function ZQ($,W){let j=E5($);if(j){if(M5(j).length>0)return"meta-repo"}if(W)return"monorepo";return"classic"}function N5($=process.cwd()){let W=f($),j=D($),A=k$(j),Q=e$(j),Z=Q?jQ(j):void 0,X=I$(W),Y=ZQ($,Q),B=Y==="meta-repo"?QQ($):void 0;return{packageManager:A,workspaceRoot:j,packageRoot:W,isMonorepo:Q,packages:Z,packageName:X,repositoryType:Y,metaRepo:B}}function iH($,W){switch($){case"bun":return`bun run ${W}`;case"pnpm":return`pnpm run ${W}`;case"yarn":return`yarn ${W}`;case"npm":return`npm run ${W}`}}function pH($,W){switch($){case"bun":return`bunx ${W}`;case"pnpm":return`pnpm exec ${W}`;case"yarn":return`yarn ${W}`;case"npm":return`npx ${W}`}}function R5($,W=!1){let j=W?$==="npm"?"--save-dev":"-D":"";switch($){case"bun":return`bun add ${j}`.trim();case"pnpm":return`pnpm add ${j}`.trim();case"yarn":return`yarn add ${j}`.trim();case"npm":return`npm install ${j}`.trim()}}import{anthropic as C5}from"@ai-sdk/anthropic";import{generateText as D5}from"ai";class m0{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 W=C5("claude-3-7-sonnet-20250219"),j=this.buildSystemPrompt($),A=this.buildUserPrompt($),Q=await D5({model:W,prompt:A,system:j,temperature:0.2});return{success:!0,code:this.extractCode(Q.text),metadata:{model:"claude-3-7-sonnet",agentMode:"claude-code",usage:Q.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["ANTHROPIC_API_KEY not set"]};try{let W=C5("claude-3-7-sonnet-20250219"),j=`
|
|
5
5
|
You are an expert code reviewer. Carefully analyze this implementation against its specification.
|
|
6
6
|
|
|
7
7
|
SPECIFICATION:
|
|
@@ -30,7 +30,7 @@ Provide a structured validation report:
|
|
|
30
30
|
- Are there any missing edge cases?
|
|
31
31
|
|
|
32
32
|
Be thorough and precise. Use a critical but constructive tone.
|
|
33
|
-
`,
|
|
33
|
+
`,A=await D5({model:W,prompt:j,system:"You are a senior software engineer performing a critical code review.",temperature:0.3}),Q=this.detectIssues(A.text);return{success:!Q,code:A.text,errors:Q?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),suggestions:this.extractSuggestions(A.text),metadata:{agentMode:"claude-code",validationType:"comprehensive"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript developer specializing in contract-driven development.
|
|
34
34
|
|
|
35
35
|
Your code is:
|
|
36
36
|
- Type-safe with comprehensive TypeScript types
|
|
@@ -73,10 +73,10 @@ Spec:
|
|
|
73
73
|
${$.specCode}
|
|
74
74
|
|
|
75
75
|
Code:
|
|
76
|
-
${$.existingCode}`};return W[$.type]||W.generate}extractCode($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W&&W[1])return W[1];return $}detectIssues($){let W=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],j=$.toLowerCase();return W.some((
|
|
77
|
-
`);for(let
|
|
78
|
-
`);for(let
|
|
79
|
-
`);for(let
|
|
76
|
+
${$.existingCode}`};return W[$.type]||W.generate}extractCode($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W&&W[1])return W[1];return $}detectIssues($){let W=["missing","incorrect","bug","error","violation","does not","fails to","not implemented","critical"],j=$.toLowerCase();return W.some((A)=>j.includes(A))}extractErrors($){let W=[],j=$.split(`
|
|
77
|
+
`);for(let A of j){let Q=A.toLowerCase();if(Q.includes("error")||Q.includes("bug")||Q.includes("incorrect")||Q.includes("missing"))W.push(A.trim())}return W.length>0?W:["Code review identified issues"]}extractWarnings($){let W=[],j=$.split(`
|
|
78
|
+
`);for(let A of j){let Q=A.toLowerCase();if(Q.includes("warning")||Q.includes("should")||Q.includes("consider"))W.push(A.trim())}return W}extractSuggestions($){let W=[],j=$.split(`
|
|
79
|
+
`);for(let A of j){let Q=A.toLowerCase();if(Q.includes("suggest")||Q.includes("recommend")||Q.includes("could")||Q.includes("improvement"))W.push(A.trim())}return W}}import{spawn as XQ}from"child_process";import{existsSync as T5}from"fs";import{mkdir as F5,readFile as YQ,rm as BQ,writeFile as Z$}from"fs/promises";import{homedir as Q1,tmpdir as x5}from"os";import{join as u}from"path";class P0{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 W=u(x5(),`cursor-agent-${Date.now()}`);await F5(W,{recursive:!0});let j=await this.executeWithBestMethod($,W);return await this.cleanupWorkDir(W),j}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){try{let W=u(x5(),`cursor-validate-${Date.now()}`);await F5(W,{recursive:!0}),await this.setupValidationWorkspace($,W);let j=await this.executeWithBestMethod({...$,type:"validate"},W);return await this.cleanupWorkDir(W),j}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}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(Q1(),".cursor","cursor"),u(Q1(),"AppData","Local","Programs","cursor","Cursor.exe"),u(Q1(),"AppData","Local","Programs","windsurf","Windsurf.exe"),"cursor","windsurf"];for(let W of $)if(W.includes("cursor")||W.includes("Cursor")||W.includes("windsurf")||W.includes("Windsurf"))try{if(T5(W)){this.cursorPath=W;break}}catch{continue}}async executeWithBestMethod($,W){let j=[{name:"cursor-cli",fn:()=>this.useCursorCLI($,W)},{name:"file-based",fn:()=>this.useFileBasedApproach($,W)}];for(let A of j)try{let Q=await A.fn();if(Q.success)return Q}catch(Q){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($,W){if(!this.cursorPath)throw Error("Cursor executable not found");let j=u(W,"spec.ts"),A=u(W,"output.ts"),Q=u(W,"INSTRUCTIONS.md");if(await Z$(j,$.specCode),await Z$(Q,this.buildDetailedPrompt($)),$.existingCode)await Z$(u(W,"existing.ts"),$.existingCode);return new Promise((Z,X)=>{let Y=["--wait","--new-window",W],B=XQ(this.cursorPath,Y,{cwd:W,stdio:"pipe",detached:!1}),q="",H="";B.stdout?.on("data",(V)=>{q+=V.toString()}),B.stderr?.on("data",(V)=>{H+=V.toString()}),B.on("error",(V)=>{X(V)}),B.on("close",async(V)=>{if(T5(A))try{let G=await YQ(A,"utf-8");Z({success:!0,code:G,metadata:{agentMode:"cursor",method:"cli",exitCode:V}})}catch(G){X(Error("Failed to read generated output"))}else X(Error(`Cursor CLI exited with code ${V}. No output generated.`))}),setTimeout(()=>{B.kill(),X(Error("Cursor CLI timeout"))},60000)})}async useFileBasedApproach($,W){let j=u(W,"SPECIFICATION.ts"),A=u(W,"INSTRUCTIONS.md"),Q=u(W,"template.ts");return await Z$(j,$.specCode),await Z$(A,this.buildDetailedPrompt($)),await Z$(Q,this.generateTemplate($)),await Z$(u(W,"README.md"),`# Cursor Agent Workspace
|
|
80
80
|
|
|
81
81
|
This workspace was prepared for Cursor AI code generation.
|
|
82
82
|
|
|
@@ -92,7 +92,7 @@ This workspace was prepared for Cursor AI code generation.
|
|
|
92
92
|
4. Save the result as output.ts
|
|
93
93
|
|
|
94
94
|
Workspace path: ${W}
|
|
95
|
-
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${W}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:W}}}async setupValidationWorkspace($,W){await
|
|
95
|
+
`),{success:!1,warnings:["Cursor agent created workspace but cannot auto-execute.",`Workspace prepared at: ${W}`,"Open this folder in Cursor IDE to complete code generation."],code:this.generateTemplate($),metadata:{agentMode:"cursor",method:"file-based",workDir:W}}}async setupValidationWorkspace($,W){await Z$(u(W,"specification.ts"),$.specCode),await Z$(u(W,"implementation.ts"),$.existingCode||"// No implementation"),await Z$(u(W,"VALIDATION_INSTRUCTIONS.md"),this.buildValidationPrompt($))}async prepareFilesForAPI($,W){let j=[{path:"spec.ts",content:$.specCode}];if($.existingCode)j.push({path:"existing.ts",content:$.existingCode});return j}buildDetailedPrompt($){let W=`# AI Code Generation Task - Cursor Agent
|
|
96
96
|
|
|
97
97
|
**Task Type:** ${$.type}
|
|
98
98
|
**Generated:** ${new Date().toISOString()}
|
|
@@ -103,7 +103,7 @@ Workspace path: ${W}
|
|
|
103
103
|
${$.specCode}
|
|
104
104
|
\`\`\`
|
|
105
105
|
|
|
106
|
-
`,
|
|
106
|
+
`,A={generate:`## Task: Generate Implementation
|
|
107
107
|
|
|
108
108
|
### Requirements:
|
|
109
109
|
1. **Type Safety**: Use strict TypeScript with comprehensive types
|
|
@@ -196,7 +196,7 @@ ${$.existingCode||""}
|
|
|
196
196
|
- Enhance error messages
|
|
197
197
|
|
|
198
198
|
### Output Format:
|
|
199
|
-
Refactored code that maintains functionality while improving quality.`};return W+j+(
|
|
199
|
+
Refactored code that maintains functionality while improving quality.`};return W+j+(A[$.type]||A.generate)}buildValidationPrompt($){return`# Implementation Validation Report
|
|
200
200
|
|
|
201
201
|
## Specification
|
|
202
202
|
\`\`\`typescript
|
|
@@ -254,7 +254,7 @@ export function implementation() {
|
|
|
254
254
|
// Implementation goes here
|
|
255
255
|
throw new Error('Not implemented');
|
|
256
256
|
}
|
|
257
|
-
`}async cleanupWorkDir($){try{await
|
|
257
|
+
`}async cleanupWorkDir($){try{await BQ($,{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 y5}from"@ai-sdk/openai";import{generateText as v5}from"ai";class k0{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 j=this.isComplexTask($)?"o1":"gpt-5.4",A=y5(j),Q=this.buildSystemPrompt($),Z=this.buildUserPrompt($),X=await v5({model:A,prompt:Z,system:Q,temperature:0.2});return{success:!0,code:this.extractCode(X.text),metadata:{model:j,agentMode:"openai-codex",usage:X.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){if(!this.apiKey)return{success:!1,errors:["OPENAI_API_KEY not set"]};try{let W=y5("gpt-5.4"),j=`
|
|
258
258
|
Review this code implementation against its specification.
|
|
259
259
|
|
|
260
260
|
SPECIFICATION:
|
|
@@ -274,7 +274,7 @@ Provide a detailed validation report including:
|
|
|
274
274
|
4. Recommendations for improvement
|
|
275
275
|
|
|
276
276
|
Format as a structured report.
|
|
277
|
-
`,
|
|
277
|
+
`,A=await v5({model:W,prompt:j,system:"You are a senior software engineer performing thorough code review.",temperature:0.3}),Q=this.detectIssues(A.text);return{success:!Q,code:A.text,errors:Q?this.extractErrors(A.text):[],warnings:this.extractWarnings(A.text),metadata:{agentMode:"openai-codex",validationType:"ai-review"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}isComplexTask($){let W=["algorithm","optimization","complex logic","state management","concurrent","distributed"],j=($.specCode+($.existingCode||"")).toLowerCase();return W.some((A)=>j.includes(A))}buildSystemPrompt($){if($.type==="test")return`You are an expert TypeScript/JavaScript developer.
|
|
278
278
|
|
|
279
279
|
Generate production-quality code that is:
|
|
280
280
|
- Type-safe and well-typed
|
|
@@ -311,9 +311,9 @@ Generate complete Vitest test suite.`;case"refactor":return`Refactor this code w
|
|
|
311
311
|
${$.existingCode}
|
|
312
312
|
|
|
313
313
|
Spec:
|
|
314
|
-
${$.specCode}`;default:return $.specCode}}extractCode($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return W&&W[1]?W[1]:$}detectIssues($){let W=["issue","problem","bug","error","incorrect","missing","fails","violation"],j=$.toLowerCase();return W.some((
|
|
315
|
-
`);for(let
|
|
316
|
-
`);for(let
|
|
314
|
+
${$.specCode}`;default:return $.specCode}}extractCode($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);return W&&W[1]?W[1]:$}detectIssues($){let W=["issue","problem","bug","error","incorrect","missing","fails","violation"],j=$.toLowerCase();return W.some((A)=>j.includes(A))}extractErrors($){let W=[],j=$.split(`
|
|
315
|
+
`);for(let A of j)if(A.toLowerCase().includes("error")||A.toLowerCase().includes("bug")||A.toLowerCase().includes("fails"))W.push(A.trim());return W}extractWarnings($){let W=[],j=$.split(`
|
|
316
|
+
`);for(let A of j)if(A.toLowerCase().includes("warning")||A.toLowerCase().includes("should")||A.toLowerCase().includes("consider"))W.push(A.trim());return W}}import M$ from"chalk";import VQ from"ora";import{generateText as m5}from"ai";var H1={};h(H1,{getCodeGenSystemPrompt:()=>q1,buildTestPrompt:()=>B1,buildHandlerPrompt:()=>Z1,buildFormPrompt:()=>Y1,buildComponentPrompt:()=>X1});function Z1($){return`You are a senior TypeScript developer implementing a handler for a contract specification.
|
|
317
317
|
|
|
318
318
|
Here is the contract spec:
|
|
319
319
|
|
|
@@ -332,7 +332,7 @@ Generate a complete handler implementation that:
|
|
|
332
332
|
|
|
333
333
|
The handler should be production-ready with proper error handling, logging points, and clear structure.
|
|
334
334
|
|
|
335
|
-
Return only the TypeScript code for the handler function.`}function
|
|
335
|
+
Return only the TypeScript code for the handler function.`}function X1($){return`You are a senior React developer creating a component for a presentation specification.
|
|
336
336
|
|
|
337
337
|
Here is the presentation spec:
|
|
338
338
|
|
|
@@ -351,7 +351,7 @@ Generate a complete React component that:
|
|
|
351
351
|
|
|
352
352
|
The component should follow Atomic Design principles and be reusable.
|
|
353
353
|
|
|
354
|
-
Return only the TypeScript/TSX code for the component.`}function
|
|
354
|
+
Return only the TypeScript/TSX code for the component.`}function Y1($){return`You are a senior React developer creating a form component from a form specification.
|
|
355
355
|
|
|
356
356
|
Here is the form spec:
|
|
357
357
|
|
|
@@ -371,7 +371,7 @@ Generate a complete form component using react-hook-form that:
|
|
|
371
371
|
|
|
372
372
|
The form should provide excellent UX with real-time validation and helpful feedback.
|
|
373
373
|
|
|
374
|
-
Return only the TypeScript/TSX code for the form component.`}function
|
|
374
|
+
Return only the TypeScript/TSX code for the form component.`}function B1($,W,j){return`You are a senior developer writing comprehensive tests.
|
|
375
375
|
|
|
376
376
|
Spec:
|
|
377
377
|
\`\`\`typescript
|
|
@@ -398,7 +398,7 @@ ${j==="handler"?`
|
|
|
398
398
|
|
|
399
399
|
Use clear test descriptions and follow AAA pattern (Arrange, Act, Assert).
|
|
400
400
|
|
|
401
|
-
Return only the TypeScript test code.`}function
|
|
401
|
+
Return only the TypeScript test code.`}function q1(){return`You are an expert TypeScript developer with deep knowledge of:
|
|
402
402
|
- Type-safe API design
|
|
403
403
|
- React and modern hooks
|
|
404
404
|
- Test-driven development
|
|
@@ -412,7 +412,7 @@ Generate production-ready code that is:
|
|
|
412
412
|
- Defensive and error-safe
|
|
413
413
|
- Easy to maintain and extend
|
|
414
414
|
|
|
415
|
-
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as
|
|
415
|
+
Always prioritize code quality, safety, and user experience.`}import{getAIProvider as qQ}from"@contractspec/lib.ai-providers";function V1($){let W={aiProvider:$.aiProvider,aiModel:$.aiModel||void 0,customEndpoint:$.customEndpoint||void 0};return qQ(W)}class h0{config;name="simple";constructor($){this.config=$}canHandle($){return!0}async generate($){try{let W=V1(this.config),j=this.buildPrompt($),A=await m5({model:W,prompt:j,system:q1()});return{success:!0,code:A.text,metadata:{model:this.config.aiModel,provider:this.config.aiProvider,tokens:A.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){try{let W=V1(this.config),j=`
|
|
416
416
|
Review the following implementation against its specification.
|
|
417
417
|
|
|
418
418
|
Specification:
|
|
@@ -426,15 +426,15 @@ Provide a detailed validation report:
|
|
|
426
426
|
2. Are there any missing features?
|
|
427
427
|
3. Are there any bugs or issues?
|
|
428
428
|
4. Suggestions for improvement
|
|
429
|
-
`,
|
|
430
|
-
${$.specCode}`;case"test":return
|
|
431
|
-
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as
|
|
429
|
+
`,A=await m5({model:W,prompt:j,system:"You are a code review expert. Provide thorough, constructive feedback."}),Q=A.text.toLowerCase().includes("error")||A.text.toLowerCase().includes("missing")||A.text.toLowerCase().includes("incorrect");return{success:!Q,code:A.text,warnings:Q?["Implementation may not match specification"]:[],metadata:{validationType:"simple-llm"}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}buildPrompt($){switch($.type){case"generate":if($.specCode.includes(".operation.")||$.specCode.includes("kind:"))return Z1($.specCode);else if($.specCode.includes(".presentation."))return X1($.specCode);else if($.specCode.includes(".form."))return Y1($.specCode);return`Generate implementation for:
|
|
430
|
+
${$.specCode}`;case"test":return B1($.specCode,$.existingCode||"","handler");case"validate":return`Validate this implementation:
|
|
431
|
+
${$.existingCode}`;default:return $.specCode}}}import{createUnifiedAgent as HQ}from"@contractspec/lib.ai-agent/agent/unified-agent";class G1{name;agent;constructor($,W,j={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=HQ(j,W)}canHandle($){return!0}async generate($){try{let W=this.buildPrompt($),j=await this.agent.run(W);return{success:!0,code:j.text,metadata:{finishReason:j.finishReason,usage:j.usage}}}catch(W){return{success:!1,errors:[W instanceof Error?W.message:String(W)]}}}async validate($){return this.generate($)}buildPrompt($){let W="";if($.specCode)W+=`Specification:
|
|
432
432
|
${$.specCode}
|
|
433
433
|
|
|
434
434
|
`;if($.existingCode)W+=`Existing Code:
|
|
435
435
|
${$.existingCode}
|
|
436
436
|
|
|
437
|
-
`;switch($.type){case"generate":W+="Generate implementation code based on the specification above.";break;case"validate":W+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":W+="Refactor the existing code to better match the specification and improve quality.";break;case"test":W+="Generate tests for the existing code based on the specification.";break}return W}}class
|
|
437
|
+
`;switch($.type){case"generate":W+="Generate implementation code based on the specification above.";break;case"validate":W+="Validate if the existing code implements the specification correctly. Report any issues.";break;case"refactor":W+="Refactor the existing code to better match the specification and improve quality.";break;case"test":W+="Generate tests for the existing code based on the specification.";break}return W}}class g0{config;agents;defaultAgent;constructor($){this.config=$;this.agents=new Map;let W=new h0($),j=new P0,A=new m0,Q=new k0;this.agents.set("simple",W),this.agents.set("cursor",j),this.agents.set("claude-code",A),this.agents.set("openai-codex",Q),this.defaultAgent=W,this.agents.set("opencode-sdk",new G1("opencode-sdk",{backend:"opencode-sdk"}))}async executeTask($){let W=this.getAgentMode(),j=this.agents.get(W);if(!j)return console.log(M$.yellow(`⚠️ Agent '${W}' not found, using simple agent`)),this.defaultAgent.generate($);if(!j.canHandle($))return console.log(M$.yellow(`⚠️ Agent '${W}' cannot handle this task, falling back to simple agent`)),this.defaultAgent.generate($);let A=VQ(`Executing with ${W} agent...`).start();try{let Q=$.type==="validate"?await j.validate($):await j.generate($);if(Q.success)return A.succeed(M$.green(`${W} agent completed successfully`)),Q;A.warn(M$.yellow(`${W} agent failed, trying fallback...`));let Z=this.getFallbackMode(W);if(Z&&Z!==W){let X=this.agents.get(Z);if(X&&X.canHandle($))return $.type==="validate"?await X.validate($):await X.generate($)}return A.info(M$.gray("Using simple agent as ultimate fallback")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}catch(Q){return A.fail(M$.red("Agent execution failed")),console.log(M$.gray("Falling back to simple agent...")),$.type==="validate"?await this.defaultAgent.validate($):await this.defaultAgent.generate($)}}async generate($,W){return this.executeTask({type:"generate",specCode:$,targetPath:W})}async generateTests($,W){return this.executeTask({type:"test",specCode:$,existingCode:W})}async validate($,W){return this.executeTask({type:"validate",specCode:$,existingCode:W})}async refactor($,W){return this.executeTask({type:"refactor",specCode:$,existingCode:W})}async getAvailableAgents(){let $=[];for(let[W,j]of this.agents){let A={type:"generate",specCode:"test"},Q=j.canHandle(A);$.push({mode:W,available:Q,reason:Q?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 P5={};h(P5,{specCreation:()=>J1,codeGeneration:()=>H1});var J1={};h(J1,{getSystemPrompt:()=>wQ,buildPresentationSpecPrompt:()=>bQ,buildOperationSpecPrompt:()=>GQ,buildEventSpecPrompt:()=>JQ,addExampleContext:()=>KQ});function GQ($,W){return`You are a senior software architect creating a contract specification for an operation.
|
|
438
438
|
|
|
439
439
|
The operation is a ${W} (${W==="command"?"changes state, has side effects":"read-only, idempotent"}).
|
|
440
440
|
|
|
@@ -452,7 +452,7 @@ Create a complete contract specification following these guidelines:
|
|
|
452
452
|
8. **Feature Flags**: Any flags that gate this operation
|
|
453
453
|
9. **Side Effects**: What events might be emitted, analytics to track
|
|
454
454
|
|
|
455
|
-
Respond with a structured spec.`}function
|
|
455
|
+
Respond with a structured spec.`}function JQ($){return`You are a senior software architect creating an event specification.
|
|
456
456
|
|
|
457
457
|
User description: ${$}
|
|
458
458
|
|
|
@@ -466,7 +466,7 @@ Create a complete event specification following these guidelines:
|
|
|
466
466
|
|
|
467
467
|
Events represent things that have already happened and should use past tense.
|
|
468
468
|
|
|
469
|
-
Respond with a structured spec.`}function
|
|
469
|
+
Respond with a structured spec.`}function bQ($,W){return`You are a senior software architect creating a presentation specification.
|
|
470
470
|
|
|
471
471
|
This is a ${W} presentation - ${{web_component:"a React component with props schema",markdown:"markdown/MDX documentation or guide",data:"structured data export (JSON/XML)"}[W]}.
|
|
472
472
|
|
|
@@ -484,7 +484,7 @@ Create a complete presentation specification following these guidelines:
|
|
|
484
484
|
- Target audience`:`- MIME type (e.g., application/json)
|
|
485
485
|
- Data structure description`}
|
|
486
486
|
|
|
487
|
-
Respond with a structured spec.`}function
|
|
487
|
+
Respond with a structured spec.`}function wQ(){return`You are an expert software architect specializing in API design and contract-driven development.
|
|
488
488
|
|
|
489
489
|
You create clear, well-documented specifications that serve as the single source of truth for operations, events, and presentations.
|
|
490
490
|
|
|
@@ -494,7 +494,7 @@ Your specs are:
|
|
|
494
494
|
- Business-oriented (capturing the "why" not just "what")
|
|
495
495
|
- Designed for both humans and AI agents to understand
|
|
496
496
|
|
|
497
|
-
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function
|
|
497
|
+
Always use proper dot notation for names and ensure all metadata is meaningful and accurate.`}function KQ($,W){if(W.length===0)return $;return`${$}
|
|
498
498
|
|
|
499
499
|
Here are some good examples for reference:
|
|
500
500
|
|
|
@@ -502,271 +502,103 @@ ${W.join(`
|
|
|
502
502
|
|
|
503
503
|
`)}
|
|
504
504
|
|
|
505
|
-
Follow this structure and quality level.`}var
|
|
506
|
-
`)}function
|
|
505
|
+
Follow this structure and quality level.`}var g5={};h(g5,{sarifToJson:()=>SQ,formatAsTextLines:()=>h5,formatAsText:()=>IQ,formatAsSarif:()=>UQ,formatAsJson:()=>_Q});function _Q($,W={}){let{pretty:j=!0,driftResult:A}=W,Q=$.issues.map((H)=>({name:H.ruleId,status:H.severity==="error"?"fail":H.severity==="warning"?"warn":"pass",category:H.category,message:H.message,file:H.file,line:H.line,details:H.context})),Z=$.categories.filter((H)=>H.passed).length,X=$.totalErrors,Y=$.totalWarnings,B=$.totalNotes,q={schemaVersion:"1.0",success:$.success,checks:Q,categories:$.categories.map((H)=>({category:H.category,label:H.label,passed:H.passed,errors:H.errors,warnings:H.warnings,notes:H.notes,durationMs:H.durationMs})),drift:{status:A?.hasDrift?"detected":"none",files:A?.files??[]},summary:{pass:Z,fail:X,warn:Y,note:B,total:Z+X+Y+B,totalErrors:$.totalErrors,totalWarnings:$.totalWarnings,totalNotes:$.totalNotes,durationMs:$.durationMs,timestamp:$.timestamp},details:{commit:$.commitSha,branch:$.branch}};return j?JSON.stringify(q,null,2):JSON.stringify(q)}var zQ={"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 UQ($,W={}){let{toolName:j="ContractSpec",toolVersion:A="1.0.0",toolUri:Q="https://contractspec.io",repositoryUri:Z,workingDirectory:X}=W,Y=new Map,B=new Map,q=$.issues.filter((J)=>J.file);for(let J of q)if(!Y.has(J.ruleId)){let b=zQ[J.ruleId]??{name:J.ruleId,description:`Rule: ${J.ruleId}`},w={id:J.ruleId,name:b.name,shortDescription:{text:b.description},defaultConfiguration:{level:k5(J.severity)}};if(b.helpUri)w.helpUri=b.helpUri;B.set(J.ruleId,Y.size),Y.set(J.ruleId,w)}let H=q.map((J)=>{let b={ruleId:J.ruleId,ruleIndex:B.get(J.ruleId)??0,level:k5(J.severity),message:{text:J.message}},w={physicalLocation:{artifactLocation:{uri:LQ(J.file),uriBaseId:"%SRCROOT%"}}};if(J.line!==void 0)w.physicalLocation.region={startLine:J.line,startColumn:J.column??1,endLine:J.endLine??J.line,endColumn:J.endColumn};return b.locations=[w],b.partialFingerprints={primaryLocationLineHash:OQ(J)},b}),V=[];if(Z)V.push({repositoryUri:Z,revisionId:$.commitSha,branch:$.branch});let G={tool:{driver:{name:j,version:A,informationUri:Q,rules:Array.from(Y.values())}},results:H,invocations:[{executionSuccessful:$.success,endTimeUtc:$.timestamp,...X&&{workingDirectory:{uri:X}}}]};if(V.length>0)G.versionControlProvenance=V;return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[G]}}function k5($){switch($){case"error":return"error";case"warning":return"warning";case"note":return"note";default:return"warning"}}function LQ($){return $.replace(/^\.\//,"").replace(/\\/g,"/")}function OQ($){let W=[$.ruleId,$.file??"",$.message];return Buffer.from(W.join("|")).toString("base64").slice(0,16)}function SQ($){return JSON.stringify($,null,2)}function h5($,W={}){let j=[],{verbose:A=!1,showTiming:Q=!0,groupByFile:Z=!1}=W;if(j.push({text:"",style:"normal"}),j.push({text:"\uD83D\uDCCB ContractSpec CI Check Results",style:"bold"}),j.push({text:"",style:"normal"}),$.commitSha||$.branch){let Y=[$.branch?`branch: ${$.branch}`:null,$.commitSha?`commit: ${$.commitSha.slice(0,7)}`:null].filter(Boolean).join(", ");j.push({text:`Git: ${Y}`,style:"muted"})}j.push({text:"",style:"normal"}),j.push({text:"Check Results:",style:"bold"});for(let Y of $.categories){let B=Y.passed?"✓":"✗",q=Y.passed?"success":"error",H=MQ(Y),V=Q?` (${Y.durationMs}ms)`:"";j.push({text:` ${B} ${Y.label}: ${H}${V}`,style:q})}if($.issues.length>0)if(j.push({text:"",style:"normal"}),j.push({text:"Issues:",style:"bold"}),Z){let Y=EQ($.issues);for(let[B,q]of Y){j.push({text:"",style:"normal"}),j.push({text:` ${B||"(no file)"}`,style:"bold",indent:1});for(let H of q)j.push(...f0(H,A,2))}}else{let Y=$.issues.filter((H)=>H.severity==="error"),B=$.issues.filter((H)=>H.severity==="warning"),q=$.issues.filter((H)=>H.severity==="note");if(Y.length>0){j.push({text:"",style:"normal"}),j.push({text:" Errors:",style:"error",indent:1});for(let H of Y)j.push(...f0(H,A,2))}if(B.length>0){j.push({text:"",style:"normal"}),j.push({text:" Warnings:",style:"warning",indent:1});for(let H of B)j.push(...f0(H,A,2))}if(q.length>0&&A){j.push({text:"",style:"normal"}),j.push({text:" Notes:",style:"muted",indent:1});for(let H of q)j.push(...f0(H,A,2))}}j.push({text:"",style:"normal"}),j.push({text:"─".repeat(50),style:"muted"});let X=[$.totalErrors>0?`${$.totalErrors} error(s)`:null,$.totalWarnings>0?`${$.totalWarnings} warning(s)`:null,$.totalNotes>0&&A?`${$.totalNotes} note(s)`:null].filter(Boolean);if(X.length>0)j.push({text:`Found: ${X.join(", ")}`,style:$.success?"warning":"error"});if(Q)j.push({text:`Duration: ${$.durationMs}ms`,style:"muted"});if(j.push({text:"",style:"normal"}),$.success)j.push({text:"✅ All CI checks passed!",style:"success"});else j.push({text:"❌ CI checks failed",style:"error"});return j.push({text:"",style:"normal"}),j}function IQ($,W={}){return h5($,W).map((A)=>" ".repeat(A.indent??0)+A.text).join(`
|
|
506
|
+
`)}function MQ($){let W=[];if($.errors>0)W.push(`${$.errors} error(s)`);if($.warnings>0)W.push(`${$.warnings} warning(s)`);if(W.length===0)return"passed";return W.join(", ")}function f0($,W,j){let A=[],Q=$.severity==="error"?"✗":$.severity==="warning"?"⚠":"○",Z=$.severity==="error"?"error":$.severity==="warning"?"warning":"muted",X=`${Q} ${$.message}`;if($.file){let Y=$.line?`:${$.line}`:"";X+=` (${$.file}${Y})`}if(A.push({text:X,style:Z,indent:j}),W&&$.context){let Y=JSON.stringify($.context);if(Y!=="{}")A.push({text:`Context: ${Y}`,style:"muted",indent:j+1})}return A}function EQ($){let W=new Map;for(let j of $){let A=j.file??"";if(!W.has(A))W.set(A,[]);let Q=W.get(A);if(Q)Q.push(j)}return new Map([...W.entries()].sort(([j],[A])=>j.localeCompare(A)))}import{OperationSpecRegistry as NQ}from"@contractspec/lib.contracts-spec/operations";import{registerReportContracts as RQ}from"@contractspec/lib.contracts-spec/operations/report";function CQ(){let $=new NQ;return RQ($),$}var ZG=CQ();class DQ{buildReportData($){let W=$.existingReportData||{};if(W.contracts=$.contractsJson,W.whatChanged={summary:"Drift check completed.",detailsPath:"",...W.whatChanged},W.risk={status:"unknown",breaking:0,nonBreaking:0,...W.risk},W.validation={status:"skipped",outputPath:"",...W.validation},W.drift={status:$.driftStatus,files:$.driftFiles},!W.nextSteps)W.nextSteps=[];if($.driftStatus==="fail")W.nextSteps.push("Run the generate command locally and commit drift fixes.");return W}finalizeResults($,W){let j=$.drift?.status==="fail",A=!1;if(j&&W==="fail")A=!0;return{driftDetected:j,shouldFail:A}}}function TQ($){if(!$)return"—";let W=new Date($),A=new Date().getTime()-W.getTime(),Q=Math.floor(A/86400000);if(Q<1)return"today";if(Q===1)return"yesterday";return`${Q} days ago`}class FQ{collectChanges($,W,j){if($){let A=$.endsWith("/")?$:`${$}/`;return j.filter((Q)=>Q.startsWith(A))}if(W){let A=new RegExp("^"+W.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$");return j.filter((Q)=>A.test(Q))}return j}detectDrift($){let W=$.map((j)=>j.slice(3)).filter((j)=>j&&j.trim().length>0).filter((j)=>j!==".contractspec-ci"&&!j.startsWith(".contractspec-ci/"));return{files:W,status:W.length>0?"fail":"pass"}}deriveImpactStatus($){let W=$?.summary||{},j=W.breaking||0,A=W.nonBreaking||0,Q=W.total;if(Q===void 0)Q=j+A;let Z=$?.breaking||!1,X="unknown";if($){if(Z||j>0)X="breaking",Z=!0;else if(A>0)X="non-breaking";else if(Q===0)X="no-impact"}return{status:X,breaking:Z,breakingCount:j,nonBreakingCount:A,total:Q||0}}buildReportData($){let W=$.contractChanges.length===0?"No contract files changed.":`${$.contractChanges.length} contract file(s) changed.`,j=this.deriveImpactStatus($.impactJson),A={contracts:$.contractsJson,whatChanged:{summary:W,detailsPath:".contractspec-ci/product-view.md"},risk:{status:j.status,breaking:j.breakingCount,nonBreaking:j.nonBreakingCount},validation:{status:$.validationStatus,outputPath:".contractspec-ci/validation.txt"},drift:{status:$.driftStatus,files:$.driftFiles},nextSteps:[]};if(A.validation?.status==="fail")A.nextSteps?.push("Fix validation errors and rerun the workflow.");if(A.risk?.status==="breaking")A.nextSteps?.push("Review breaking changes and plan a migration.");if(A.risk?.status==="unknown")A.nextSteps?.push("Re-run impact detection or check contractspec impact output.");if(A.drift?.status==="fail")A.nextSteps?.push("Run the generate command locally and commit drift fixes.");let Q=this.finalizeResults(A,$.failOn);if(Q.shouldFail)A.nextSteps?.unshift(`CI failed: ${Q.failReasons.join(", ")} (fail_on=${$.failOn}).`);return A}finalizeResults($,W){let j=$.risk?.status==="breaking"||($.risk?.breaking||0)>0,A=$.drift?.status==="fail",Q=$.validation?.status==="fail",Z=$.risk?.status==="unknown",X=[],Y=!1;if(W!=="never"){if(W==="breaking"){if(j)X.push("breaking changes detected");if(Z)X.push("impact status unknown")}else if(W==="drift"){if(A)X.push("drift detected");if(Z)X.push("impact status unknown")}else if(W==="any"){if(j)X.push("breaking changes detected");if(A)X.push("drift detected");if(Q)X.push("validation failed");if(Z)X.push("impact status unknown")}else X.push(`invalid fail_on value (${W})`);if(X.length>0)Y=!0}return{driftDetected:A,breakingChangeDetected:j,validationFailed:Q,shouldFail:Y,failReasons:X}}generateReportMarkdown($,W){let j=(B,q=60000)=>{if(B.length<=q)return B;return`${B.slice(0,q)}
|
|
507
507
|
|
|
508
|
-
*(output truncated)*`},
|
|
509
|
-
`)},
|
|
508
|
+
*(output truncated)*`},A=(B)=>{if(!B||B.length===0)return"- None";return B.slice(0,20).map((q)=>`- ${q}`).join(`
|
|
509
|
+
`)},Q=j($.whatChanged?.detailsPath?W($.whatChanged.detailsPath):""),Z=j($.validation?.outputPath?W($.validation.outputPath):""),X=$.drift?.files??[],Y=[];if(Y.push("## ContractSpec Report"),Y.push(""),$.contracts&&$.contracts.length>0){Y.push("### Overall verification status"),Y.push(""),Y.push("| Contract / Endpoint / Event | Time since verified | Drift debt | Surfaces covered | Last verified commit |"),Y.push("| --- | --- | --- | --- | --- |");for(let B of $.contracts){let q=B.lastVerifiedSha??"—",H=TQ(B.lastVerifiedDate),V=B.surfaces.join(", ");Y.push(`| ${B.name} | ${H} | ${B.driftMismatches} | ${V} | ${q} |`)}Y.push("")}if(Y.push("### 1) What changed"),$.whatChanged?.summary)Y.push($.whatChanged.summary);else Y.push("No contract changes detected.");if(Q.trim().length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Contract view (product)</summary>"),Y.push(""),Y.push(Q),Y.push(""),Y.push("</details>");if(Y.push(""),Y.push("### 2) Risk classification"),$.risk?.status){let B=[`Status: ${$.risk.status}`,$.risk.breaking!==void 0?`Breaking: ${$.risk.breaking}`:null,$.risk.nonBreaking!==void 0?`Non-breaking: ${$.risk.nonBreaking}`:null].filter(Boolean);Y.push(B.join(" | "))}else Y.push("Impact analysis unavailable.");if(Y.push(""),Y.push("### 3) Validation results"),$.validation?.status){if(Y.push(`Status: ${$.validation.status}`),Z.trim().length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Validation output</summary>"),Y.push(""),Y.push(Z),Y.push(""),Y.push("</details>")}else Y.push("Validation step not run.");if(Y.push(""),Y.push("### 4) Drift results"),$.drift?.status){if(Y.push(`Status: ${$.drift.status}`),X.length>0)Y.push(""),Y.push("<details>"),Y.push("<summary>Drifted files</summary>"),Y.push(""),Y.push(A(X)),Y.push(""),Y.push("</details>")}else Y.push("Drift check not run.");if(Y.push(""),Y.push("### 5) Next steps"),$.nextSteps&&$.nextSteps.length>0)Y.push(A($.nextSteps));else Y.push("- No action required.");return`${Y.join(`
|
|
510
510
|
`)}
|
|
511
|
-
`}}import{AGENT_SYSTEM_PROMPTS as
|
|
511
|
+
`}}import{AGENT_SYSTEM_PROMPTS as xQ}from"@contractspec/lib.contracts-spec/llm";class u0{agentType="claude-code";formatPlan($){let W=[];if(W.push(`# Implement: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Context"),W.push(""),W.push(`**Goal:** ${$.context.goal}`),W.push(""),W.push(`**Description:** ${$.context.description}`),W.push(""),$.context.background)W.push("**Background:**"),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files to Create/Modify"),W.push("");for(let j of $.fileStructure){let A=j.type==="create"?"\uD83D\uDCDD":"✏️";W.push(`${A} \`${j.path}\``),W.push(` ${j.purpose}`),W.push("")}}W.push("## Implementation Steps"),W.push("");for(let j of $.steps){W.push(`### ${j.order}. ${j.title}`),W.push(""),W.push(j.description),W.push(""),W.push("**Acceptance Criteria:**");for(let A of j.acceptanceCriteria)W.push(`- [ ] ${A}`);W.push("")}if($.constraints.policy.length>0||$.constraints.security.length>0||$.constraints.pii.length>0){if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("### Policy");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("### Security");for(let j of $.constraints.security)W.push(`- ⚠️ ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("### PII Handling"),W.push("The following fields contain personally identifiable information:");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}}W.push("## Verification Checklist"),W.push(""),W.push("Before submitting, verify:");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),W.push("## Instructions"),W.push(""),W.push("1. Implement each step in order"),W.push("2. Use TypeScript with strict typing (no `any`)"),W.push("3. Include JSDoc comments for public APIs"),W.push("4. Handle all error cases defined in the spec"),W.push("5. Emit events as specified"),W.push("6. Mark checklist items as you complete them"),W.push(""),{agent:"claude-code",systemPrompt:xQ["claude-code"],taskPrompt:W.join(`
|
|
512
512
|
`)}}generateConfig($){let W=[];return W.push("# ContractSpec Implementation Context"),W.push(""),W.push("This codebase uses ContractSpec for spec-first development."),W.push(""),W.push("## Spec Details"),W.push(""),W.push(`- **Name:** ${$.meta.key}`),W.push(`- **Version:** ${$.meta.version}`),W.push(`- **Kind:** ${$.meta.kind}`),W.push(`- **Stability:** ${$.meta.stability}`),W.push(""),W.push("## Implementation Requirements"),W.push(""),W.push("1. Match input/output types exactly"),W.push("2. Handle all defined error cases"),W.push("3. Emit events as specified"),W.push("4. Respect policy constraints"),W.push(""),W.join(`
|
|
513
|
-
`)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};let j=[],
|
|
514
|
-
`)}}generateConfig($){let W=$.meta,j=[];if(j.push("---"),j.push(`description: Implementation rules for ${W.key}.v${W.version}`),j.push(`globs: ["**/${W.key.replace(/\./g,"/")}/**"]`),j.push("alwaysApply: false"),j.push("---"),j.push(""),j.push(`# ${W.key} Implementation Rules`),j.push(""),j.push(`This ${W.kind} operation must follow the ContractSpec specification.`),j.push(""),j.push("## Goal"),j.push(""),j.push(W.goal),j.push(""),j.push("## Requirements"),j.push(""),j.push("1. Input/output types MUST match the spec schema exactly"),j.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)j.push("3. Events MUST be emitted as specified");if(j.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)j.push(`5. Idempotency: ${$.policy.idempotent}`);if(j.push(""),$.io.errors&&Object.keys($.io.errors).length>0){j.push("## Error Cases"),j.push("");for(let[Q
|
|
515
|
-
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};return{code:$}}}var
|
|
513
|
+
`)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};let j=[],A=[/error:\s*(.+)/gi,/failed:\s*(.+)/gi,/cannot\s+(.+)/gi];for(let Q of A){let Z=$.matchAll(Q);for(let X of Z)if(X[1])j.push(X[1])}if(j.length>0)return{errors:j};return{code:$}}}var d0=new u0;import{AGENT_SYSTEM_PROMPTS as yQ}from"@contractspec/lib.contracts-spec/llm";class n0{agentType="cursor-cli";formatPlan($){let W=[];if(W.push(`# ${$.target.key}.v${$.target.version}`),W.push(""),W.push(`> ${$.context.goal}`),W.push(""),$.fileStructure.length>0){W.push("## Files"),W.push("");for(let A of $.fileStructure)W.push(`- ${A.type}: \`${A.path}\` - ${A.purpose}`);W.push("")}W.push("## Spec"),W.push(""),W.push($.specMarkdown),W.push(""),W.push("## Steps"),W.push("");for(let A of $.steps)W.push(`${A.order}. **${A.title}**: ${A.description}`);W.push("");let j=[...$.constraints.policy,...$.constraints.security.map((A)=>`⚠️ ${A}`)];if(j.length>0){W.push("## Constraints"),W.push("");for(let A of j)W.push(`- ${A}`);W.push("")}if($.constraints.pii.length>0)W.push("## PII Fields"),W.push(""),W.push(`Handle carefully: ${$.constraints.pii.map((A)=>`\`${A}\``).join(", ")}`),W.push("");return{agent:"cursor-cli",systemPrompt:yQ["cursor-cli"],taskPrompt:W.join(`
|
|
514
|
+
`)}}generateConfig($){let W=$.meta,j=[];if(j.push("---"),j.push(`description: Implementation rules for ${W.key}.v${W.version}`),j.push(`globs: ["**/${W.key.replace(/\./g,"/")}/**"]`),j.push("alwaysApply: false"),j.push("---"),j.push(""),j.push(`# ${W.key} Implementation Rules`),j.push(""),j.push(`This ${W.kind} operation must follow the ContractSpec specification.`),j.push(""),j.push("## Goal"),j.push(""),j.push(W.goal),j.push(""),j.push("## Requirements"),j.push(""),j.push("1. Input/output types MUST match the spec schema exactly"),j.push("2. All error cases MUST be handled"),$.sideEffects?.emits?.length)j.push("3. Events MUST be emitted as specified");if(j.push(`4. Auth level: ${$.policy.auth}`),$.policy.idempotent!==void 0)j.push(`5. Idempotency: ${$.policy.idempotent}`);if(j.push(""),$.io.errors&&Object.keys($.io.errors).length>0){j.push("## Error Cases"),j.push("");for(let[A,Q]of Object.entries($.io.errors))j.push(`- \`${A}\` (HTTP ${Q.http??400}): ${Q.when}`);j.push("")}if($.sideEffects?.emits?.length){j.push("## Events to Emit"),j.push("");for(let A of $.sideEffects.emits)if("ref"in A)j.push(`- \`${A.ref.key}.v${A.ref.version}\`: ${A.when}`);else j.push(`- \`${A.key}.v${A.version}\`: ${A.when}`);j.push("")}if($.policy.pii?.length){j.push("## PII Handling"),j.push(""),j.push("These fields contain PII and must be handled with care:");for(let A of $.policy.pii)j.push(`- \`${A}\``);j.push("")}if($.acceptance?.scenarios?.length){j.push("## Acceptance Scenarios"),j.push("");for(let A of $.acceptance.scenarios)j.push(`### ${A.key}`),j.push(`- Given: ${A.given.join("; ")}`),j.push(`- When: ${A.when.join("; ")}`),j.push(`- Then: ${A.then.join("; ")}`),j.push("")}return j.join(`
|
|
515
|
+
`)}getCursorRulesPath($){return`.cursor/rules/${$.meta.key.replace(/\./g,"-")}.mdc`}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};return{code:$}}}var c0=new n0;import{AGENT_SYSTEM_PROMPTS as vQ}from"@contractspec/lib.contracts-spec/llm";class r0{agentType="generic-mcp";formatPlan($){let W=[];if(W.push(`# Implementation Task: ${$.target.key}.v${$.target.version}`),W.push(""),W.push("## Task"),W.push(""),W.push(`Implement the ${$.target.type} \`${$.target.key}\` version ${$.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(""),W.push($.context.background),W.push("");if(W.push("## Specification"),W.push(""),W.push($.specMarkdown),W.push(""),$.fileStructure.length>0){W.push("## Files"),W.push(""),W.push("| Path | Action | Purpose |"),W.push("|------|--------|---------|");for(let j of $.fileStructure)W.push(`| \`${j.path}\` | ${j.type} | ${j.purpose} |`);W.push("")}W.push("## Implementation Steps"),W.push("");for(let j of $.steps)if(W.push(`### Step ${j.order}: ${j.title}`),W.push(""),W.push(j.description),W.push(""),j.acceptanceCriteria.length>0){W.push("**Acceptance Criteria:**"),W.push("");for(let A of j.acceptanceCriteria)W.push(`- ${A}`);W.push("")}if(W.push("## Constraints"),W.push(""),$.constraints.policy.length>0){W.push("**Policy:**");for(let j of $.constraints.policy)W.push(`- ${j}`);W.push("")}if($.constraints.security.length>0){W.push("**Security:**");for(let j of $.constraints.security)W.push(`- ${j}`);W.push("")}if($.constraints.pii.length>0){W.push("**PII Fields (handle with care):**");for(let j of $.constraints.pii)W.push(`- \`${j}\``);W.push("")}W.push("## Verification"),W.push(""),W.push("After implementation, verify:"),W.push("");for(let j of $.verificationChecklist)W.push(`- [ ] ${j}`);return W.push(""),{agent:"generic-mcp",systemPrompt:vQ["generic-mcp"],taskPrompt:W.join(`
|
|
516
516
|
`)}}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 W=$.meta,j=[];return j.push(`# ${W.key} v${W.version}`),j.push(""),j.push(`**Type:** ${W.kind}`),j.push(`**Stability:** ${W.stability}`),j.push(""),j.push("## Goal"),j.push(""),j.push(W.goal),j.push(""),j.push("## Description"),j.push(""),j.push(W.description),j.push(""),j.join(`
|
|
517
|
-
`)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};try{let j=JSON.parse($);if(typeof j.code==="string")return{code:j.code};if(typeof j.errors==="object")return{errors:Array.isArray(j.errors)?j.errors:[String(j.errors)]}}catch{}return{code:$}}}var D0=new R0;var dW={"claude-code":E0,"cursor-cli":N0,"generic-mcp":D0};function l$($){let W=dW[$];if(!W)throw Error(`Unknown agent type: ${$}`);return W}function nW(){return Object.keys(dW)}import{featureToMarkdown as cW,generateImplementationPlan as A5,operationSpecToAgentPrompt as v7,operationSpecToFullMarkdown as y7}from"@contractspec/lib.contracts-spec/llm";var P7={defaultAgent:"generic-mcp",verbose:!1};class F0{config;constructor($={}){this.config={...P7,...$}}generateGuide($,W={}){let j=W.agent??this.config.defaultAgent,Q=l$(j),Z=A5($,{projectRoot:this.config.projectRoot,existingFiles:W.targetPath?[W.targetPath]:void 0}),B=Q.formatPlan(Z),X=y7($);return{plan:Z,prompt:B,markdown:X}}generateFeatureGuide($,W,j={}){let Q=j.agent??this.config.defaultAgent,Z=l$(Q),B=$.operations?.[0],X=B?W.specs?.get(B.key,B.version):void 0,Y;if(X)Y=A5(X,{projectRoot:this.config.projectRoot}),Y.target={type:"feature",key:$.meta.key,version:"1.0.0"},Y.context.goal=$.meta.description??Y.context.goal;else Y={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:cW($,W),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(Y.specMarkdown=cW($,W,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)Y.steps=$.operations.map((H,V)=>({order:V+1,title:`Implement ${H.key}`,description:`Implement operation ${H.key}.v${H.version}`,acceptanceCriteria:[`Operation ${H.key} works as specified`]}));let q=Z.formatPlan(Y),A=cW($,W);return{plan:Y,prompt:q,markdown:A}}generateAgentConfig($,W){return l$(W??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,W,j="implement",Q){return v7($,{taskType:j,existingCode:Q})}listAgentTypes(){return nW()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function m7($){return new F0($)}var k7=new F0;import{generateComponentTemplate as g7,generateHandlerTemplate as h7,generateTestTemplate as f7,inferSpecTypeFromFilePath as u7,scanSpecSource as d7}from"@contractspec/module.workspace";async function x0($,W,j,Q={}){let{fs:Z,logger:B,workspace:X}=W,Y=X?.scanSpecSource??d7,q=X?.inferSpecTypeFromFilePath??u7,A=X?.generateHandlerTemplate??h7,H=X?.generateComponentTemplate??g7,V=X?.generateTestTemplate??f7,{targets:G=c7($,q),outputDir:z=j.outputDir,overwrite:J=!1,dryRun:K=!1}=Q,_=await Z.readFile($),w=Y(_,$),b=q($);B.info(`Building from spec: ${$}`,{specType:b});let L=[];for(let I of G)try{let U=await n7(I,$,_,w,b,{fs:Z,logger:B},z,J,K,{genHandler:A,genComponent:H,genTest:V});L.push(U)}catch(U){L.push({target:I,outputPath:"",success:!1,error:U instanceof Error?U.message:String(U),skipped:!1})}return{specPath:$,specInfo:w,results:L}}async function n7($,W,j,Q,Z,B,X,Y,q,A){let{fs:H,logger:V}=B,{genHandler:G,genComponent:z,genTest:J}=A,K,_;switch($){case"handler":{if(Z!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${Z})`};let L=Q.kind==="command"||Q.kind==="query"?Q.kind:"command";K=G(Q.key??"unknown",L),_=lW(W,X,"handlers",Q.key??"unknown",".handler.ts",B.fs);break}case"component":{if(Z!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${Z})`};K=z(Q.key??"unknown",Q.description??""),_=lW(W,X,"components",Q.key??"unknown",".tsx",B.fs);break}case"test":{let L=Z==="operation"?"handler":"component";K=J(Q.key??"unknown",L),_=lW(W,X,"__tests__",Q.key??"unknown",".test.ts",B.fs);break}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}if(await H.exists(_)&&!Y)return{target:$,outputPath:_,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(q)return V.info(`[dry-run] Would write: ${_}`),{target:$,outputPath:_,success:!0};let b=H.dirname(_);return await H.mkdir(b),await H.writeFile(_,K),V.info(`Generated: ${_}`),{target:$,outputPath:_,success:!0}}function c7($,W){switch(W($)){case"operation":return["handler"];case"presentation":return["component"];default:return[]}}function lW($,W,j,Q,Z,B){let X=l7(Q.split(".").pop()??"unknown"),Y;if(W.startsWith("."))Y=B.resolve(B.dirname($),"..",W,j);else Y=B.resolve(W,j);return B.join(Y,`${X}${Z}`)}function l7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}import{scanSpecSource as e7}from"@contractspec/module.workspace";import $8 from"micromatch";var z5={};P(z5,{validators:()=>s7,urlSchema:()=>t7,loadTypeScriptModule:()=>r$,isValidVersion:()=>i7,isValidIdentifier:()=>V5,isValidDotName:()=>G5,isTestFile:()=>oW,isLibraryDefinitionFile:()=>pW,emailSchema:()=>a7});import rW from"micromatch";function oW($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return rW.isMatch($,j)}function pW($){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(rW.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 rW.isMatch($,j)}import{readFile as r7}from"node:fs/promises";import{createRequire as o7}from"node:module";import{dirname as p7}from"node:path";import H5 from"node:vm";import iW from"typescript";async function r$($){let W=await r7($,"utf-8"),j=iW.transpileModule(W,{compilerOptions:{module:iW.ModuleKind.CommonJS,target:iW.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),Q={},Z={exports:Q},B=o7($),X=H5.createContext({module:Z,exports:Q,require:B,__dirname:p7($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new H5.Script(j.outputText,{filename:$}).runInContext(X),Z.exports}import*as Z$ from"zod";function V5($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function G5($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function i7($){return Number.isInteger($)&&$>0}var a7=Z$.string().email(),t7=Z$.string().url(),s7={specName:Z$.string().refine(G5,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:Z$.number().int().positive(),identifier:Z$.string().refine(V5,{message:"Must be a valid TypeScript identifier"}),owner:Z$.string().startsWith("@"),tag:Z$.string().min(1)};async function h($,W={}){let{fs:j,scan:Q=e7}=$,Z=W.pattern,B=await j.glob({cwd:W.cwd,pattern:Z}),X=[],Y=Array.isArray(W.type)?W.type:[W.type];for(let q of B){if(q.includes("node_modules")||q.includes("/dist/"))continue;if(W.config?.excludePackages&&$8.isMatch(q,W.config.excludePackages,{contains:!0}))continue;if(oW(q,W.config))continue;if(pW(q))continue;try{let A=await j.readFile(q),H=Q(A,q);if(H.specType==="unknown")continue;if(W.type&&!Y.includes(H.specType))continue;X.push(H)}catch{}}return X}function xH($){let W=new Map;for(let j of $){let Q=W.get(j.specType)??[];Q.push(j),W.set(j.specType,Q)}return W}function A$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function T0($){let W=JSON.parse($),j=new Map,Q=0,Z=0,B=0,X=0,Y=0,q=0,A=0,H=0;for(let[G,z]of Object.entries(W)){let J=W8(G,z);j.set(G,J),Q+=J.statements.total,Z+=J.statements.covered,B+=J.branches.total,X+=J.branches.covered,Y+=J.functions.total,q+=J.functions.covered,A+=J.lines.total,H+=J.lines.covered}let V={statements:{covered:Z,total:Q,pct:A$(Z,Q)},branches:{covered:X,total:B,pct:A$(X,B)},functions:{covered:q,total:Y,pct:A$(q,Y)},lines:{covered:H,total:A,pct:A$(H,A)}};return{files:j,total:V}}function W8($,W){let j=Object.keys(W.statementMap).length,Q=Object.values(W.s).filter((H)=>H>0).length,Z=Object.keys(W.fnMap).length,B=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 q=new Set,A=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(q.add(G),(W.s[H]??0)>0)A.add(G);return{path:$,statements:{covered:Q,total:j,pct:A$(Q,j)},branches:{covered:Y,total:X,pct:A$(Y,X)},functions:{covered:B,total:Z,pct:A$(B,Z)},lines:{covered:A.size,total:q.size,pct:A$(A.size,q.size)}}}function aW($){switch($){case"istanbul":return{parse:T0};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 tW($,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 sW($,W,j,Q){let Z=[];if(j.statements!==void 0&&Q.statements.pct<j.statements)Z.push({metric:"statements",required:j.statements,actual:Q.statements.pct,message:`Statement coverage ${Q.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&Q.branches.pct<j.branches)Z.push({metric:"branches",required:j.branches,actual:Q.branches.pct,message:`Branch coverage ${Q.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&Q.functions.pct<j.functions)Z.push({metric:"functions",required:j.functions,actual:Q.functions.pct,message:`Function coverage ${Q.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&Q.lines.pct<j.lines)Z.push({metric:"lines",required:j.lines,actual:Q.lines.pct,message:`Line coverage ${Q.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Z.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:Q,passed:Z.length===0,failures:Z}}async function eW($,W,j){let{fs:Q,logger:Z}=$,B=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],q,A;for(let z of Y)if(await Q.exists(z)){q=await Q.readFile(z),A=z;break}if(!q)return Z.info("No coverage report found, skipping coverage checks"),B;let H=tW(A??"coverage.json"),G=aW(H).parse(q);for(let z of W){if(z.specType!=="test-spec"||!z.key||!z.version||!z.sourceBlock)continue;let J=z.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!J||!J[1])continue;let K=J[1],_={},w=K.match(/statements\s*:\s*(\d+)/);if(w&&w[1])_.statements=parseInt(w[1],10);let b=K.match(/branches\s*:\s*(\d+)/);if(b&&b[1])_.branches=parseInt(b[1],10);let L=K.match(/functions\s*:\s*(\d+)/);if(L&&L[1])_.functions=parseInt(L[1],10);let I=K.match(/lines\s*:\s*(\d+)/);if(I&&I[1])_.lines=parseInt(I[1],10);if(Object.keys(_).length===0)continue;let U=sW(z.key,z.version,_,G.total);for(let O of U.failures)B.push({ruleId:"coverage-below-threshold",severity:"error",message:O.message,category:"coverage",file:z.filePath,context:{specKey:z.key,specVersion:z.version,metric:O.metric,required:O.required,actual:O.actual}})}return B}import{addContractNode as j8,buildReverseEdges as Q8,createContractGraph as Z8,detectCycles as B8,findMissingDependencies as X8,parseImportedSpecNames as Y8,toDot as q8}from"@contractspec/module.workspace";async function J5($,W={}){let{fs:j}=$,Q=await j.glob({pattern:W.pattern}),Z=Z8();for(let Y of Q){let q=await j.readFile(Y),A=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=Y8(q,Y);j8(Z,H,A,V)}Q8(Z);let B=B8(Z),X=X8(Z);return{graph:Z,total:Z.size,cycles:B,missing:X}}function tH($,W){return $.get(W)}function sH($){return q8($)}function eH($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),Q=W.filter((X)=>X.dependencies.length===0),Z=W.filter((X)=>X.dependents.length>0),B=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:Q.length,used:Z.length,unused:B.length}}async function $1($,W){let j=[],Q=await J5($,{pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" → ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let B of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${B}`,category:"deps",context:{contract:Z.contract,missing:B}});return j}import{analyzePackageDocBlocks as A8}from"@contractspec/module.workspace";var H8=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function V8($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:H8}),Q=new Map;for(let X of j){let Y=$.dirname(X),q=$.join(Y,"src");if(!await $.exists(q))continue;try{let A=JSON.parse(await $.readFile(X));Q.set(Y,{packageName:A.name??$.relative(W,Y),packageRoot:Y,srcRoot:q})}catch{continue}}let Z=$.join(W,"package.json"),B=$.join(W,"src");if(await $.exists(Z)&&await $.exists(B))try{let X=JSON.parse(await $.readFile(Z));Q.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:B})}catch{}return[...Q.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function v0($,W){let j=[],Q=await V8($,W);for(let Z of Q){let B=A8({packageName:Z.packageName,srcRoot:Z.srcRoot});for(let X of B.diagnostics)j.push({...X,packageName:Z.packageName,packageRoot:Z.packageRoot,srcRoot:Z.srcRoot})}return j}async function W1($,W){let j=W.workspaceRoot??process.cwd();return(await v0($.fs,j)).map((Z)=>({ruleId:Z.ruleId,severity:Z.severity==="warning"?"warning":"error",message:Z.message,category:"docs",file:Z.file,line:Z.line,column:Z.column,context:{packageName:Z.packageName,packageRoot:Z.packageRoot,...Z.context}}))}async function j1($,W,j){let Q=[],Z=await G8($,W);if(Q.push(Z),Z.status==="pass")Q.push(await z8($,W,j));return Q}async function G8($,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 Z=await $.readFile(j),B=JSON.parse(Z),X=B.aiProvider??"claude",Y=B.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 z8($,W,j){let Q=$.join(W.workspaceRoot,".contractsrc.json");try{let Z=await $.readFile(Q),X=JSON.parse(Z).aiProvider??"claude",q={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!q)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[q])return{category:"ai",name:"API Key",status:"pass",message:`${q} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${q} not set`,details:`Set ${q} in your environment to use AI features`,fix:j?{description:`Set ${q} 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(`${q}=`))return{success:!1,message:`${q} already in .env, update manually`};G+=`
|
|
518
|
-
`}return G+=`${q}=${H}
|
|
519
|
-
`,await $.writeFile(V,G),{success:!0,message:`Added ${q} to .env (restart required)`}}catch(G){return{success:!1,message:`Failed: ${G instanceof Error?G.message:String(G)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as J8}from"node:child_process";import{promisify as K8}from"node:util";var y0=K8(J8);async function Q1($,W){let j=[];return j.push(await U8(W)),j.push(await _8(W)),j.push(await L8($,W)),j}async function U8($){try{return await y0("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 y0("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(W){return{success:!1,message:`Failed to install: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function _8($){try{let{stdout:W}=await y0("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${W.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function L8($,W){let j=$.join(W.workspaceRoot,"package.json");try{if(!await $.exists(j))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot){let Y=$.join(W.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(Y))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let Z=await $.readFile(j),B=JSON.parse(Z);if(B.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||B.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 y0("npm install -D @contractspec/app.cli-contractspec",{cwd:W.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(Y){return{success:!1,message:`Failed to install: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}function x$($){let W=$.isMonorepo&&$.scope==="package";return{$schema:"https://api.contractspec.io/schemas/contractsrc.json",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",features:"contracts/features"},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"]},...W&&$.packageName?{package:$.packageName}:{}}}function K5(){return{"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.enabled":!0,"contractspec.validation.validateOnSave":!0,"contractspec.validation.validateOnOpen":!0,"contractspec.codeLens.enabled":!0,"contractspec.diagnostics.showWarnings":!0,"contractspec.diagnostics.showHints":!0,"contractspec.integrity.enabled":!0,"contractspec.integrity.checkOnSave":!0}}function o$(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function U5(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function _5($){let W=$.projectName??"this project",Q=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
520
|
-
|
|
521
|
-
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
522
|
-
|
|
523
|
-
## Spec-First Principle
|
|
524
|
-
|
|
525
|
-
- **Always update contracts first** before changing implementation code.
|
|
526
|
-
- Contracts are the source of truth for operations, events, and presentations.
|
|
527
|
-
- Implementation code should be generated or derived from contracts.
|
|
528
|
-
${$.isMonorepo?`
|
|
529
|
-
## Monorepo Structure
|
|
530
|
-
|
|
531
|
-
This is a monorepo. Contracts may exist at:
|
|
532
|
-
- Package level: \`packages/*/src/contracts/\`
|
|
533
|
-
- Workspace level: \`src/contracts/\`
|
|
534
|
-
|
|
535
|
-
Check the appropriate level based on the feature scope.
|
|
536
|
-
`:""}
|
|
537
|
-
## Contract Locations
|
|
538
|
-
|
|
539
|
-
Contracts are located in:
|
|
540
|
-
- \`${Q}/operations/\` - Command and query specs
|
|
541
|
-
- \`${Q}/events/\` - Event specs
|
|
542
|
-
- \`${Q}/presentations/\` - UI presentation specs
|
|
543
|
-
- \`${Q}/features/\` - Feature module specs
|
|
544
|
-
|
|
545
|
-
## When Making Changes
|
|
546
|
-
|
|
547
|
-
1. **Before coding**: Check if a contract exists for the feature.
|
|
548
|
-
2. **If contract exists**: Update the contract first, then regenerate code.
|
|
549
|
-
3. **If no contract**: Create a new contract using \`contractspec create\`.
|
|
550
|
-
4. **After changes**: Validate with \`contractspec validate\`.
|
|
551
|
-
|
|
552
|
-
## Key Commands
|
|
553
|
-
|
|
554
|
-
- \`contractspec create\` - Scaffold new specs
|
|
555
|
-
- \`contractspec validate\` - Validate specs
|
|
556
|
-
- \`contractspec build\` - Generate implementation code
|
|
557
|
-
- \`contractspec integrity\` - Check contract health
|
|
558
|
-
|
|
559
|
-
## Contract Structure
|
|
560
|
-
|
|
561
|
-
Operations follow this pattern:
|
|
562
|
-
\`\`\`typescript
|
|
563
|
-
defineCommand({
|
|
564
|
-
meta: { name: 'service.action', version: '1.0.0', ... },
|
|
565
|
-
io: { input: InputSchema, output: OutputSchema },
|
|
566
|
-
policy: { auth: 'user', ... },
|
|
567
|
-
handler: async (args, ctx) => { ... }
|
|
568
|
-
});
|
|
569
|
-
\`\`\`
|
|
570
|
-
|
|
571
|
-
## Rules for ${W}
|
|
572
|
-
|
|
573
|
-
- All API endpoints must have a corresponding operation contract.
|
|
574
|
-
- Events must be declared in contracts before being emitted.
|
|
575
|
-
- UI components should reference presentation contracts.
|
|
576
|
-
- Feature flags should be defined in feature modules.
|
|
577
|
-
`}function L5($){let W=$.projectName??"this project",j=$.isMonorepo&&$.scope==="package",Q=j&&$.packageName?`${$.packageName} package`:W,Z="src/contracts",B=$.isMonorepo?j?`
|
|
578
|
-
## Monorepo Scope
|
|
579
|
-
|
|
580
|
-
This guide is scoped to the current package.
|
|
581
|
-
- Prefer package-local contracts under \`src/contracts/\`
|
|
582
|
-
- Check workspace-level rules only when a change crosses package boundaries.
|
|
583
|
-
`:`
|
|
584
|
-
## Monorepo Scope
|
|
585
|
-
|
|
586
|
-
This guide is scoped to the workspace root.
|
|
587
|
-
- Shared contracts may live in multiple packages under \`packages/*/src/contracts/\`
|
|
588
|
-
- Prefer the nearest package guide when working inside a specific package.
|
|
589
|
-
`:"";return`# ContractSpec AI Guide
|
|
590
|
-
|
|
591
|
-
Scope: \`${Q}\`
|
|
592
|
-
|
|
593
|
-
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
594
|
-
|
|
595
|
-
## Core Rules
|
|
596
|
-
|
|
597
|
-
- Update contracts before implementation code.
|
|
598
|
-
- Validate contracts after changes with \`contractspec validate\`.
|
|
599
|
-
- Regenerate derived artifacts before considering the work complete.
|
|
600
|
-
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
601
|
-
${B}
|
|
602
|
-
## Contract Locations
|
|
603
|
-
|
|
604
|
-
- \`src/contracts/operations/\` - command and query specs
|
|
605
|
-
- \`src/contracts/events/\` - domain and integration events
|
|
606
|
-
- \`src/contracts/presentations/\` - UI presentation contracts
|
|
607
|
-
- \`src/contracts/features/\` - feature module contracts
|
|
608
|
-
|
|
609
|
-
## Recommended Workflow
|
|
610
|
-
|
|
611
|
-
1. Check whether a contract already exists for the change.
|
|
612
|
-
2. Update or create the contract first.
|
|
613
|
-
3. Run validation and generation commands.
|
|
614
|
-
4. Review downstream code and tests affected by the contract update.
|
|
615
|
-
|
|
616
|
-
## Key Commands
|
|
617
|
-
|
|
618
|
-
- \`contractspec create\` - scaffold a new contract
|
|
619
|
-
- \`contractspec validate\` - validate contract integrity
|
|
620
|
-
- \`contractspec build\` - generate implementation artifacts
|
|
621
|
-
- \`contractspec doctor\` - verify workspace configuration
|
|
622
|
-
|
|
623
|
-
## Working Agreement
|
|
624
|
-
|
|
625
|
-
- Keep changes spec-first, deterministic, and reviewable.
|
|
626
|
-
- Do not change generated outputs without updating their source contract.
|
|
627
|
-
- When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
|
|
628
|
-
`}function P0(){let $=process.platform,W=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${W}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??W}/Claude/claude_desktop_config.json`;default:return`${W}/.config/claude/claude_desktop_config.json`}}function r($,W){let j={...$};for(let Q of Object.keys(W)){let Z=$[Q],B=W[Q];if(Z===void 0)j[Q]=B;else if(m0(Z)&&m0(B))j[Q]=r(Z,B)}return j}function I8($,W){let j={...$};for(let Q of Object.keys(W)){let Z=$[Q],B=W[Q];if(B===void 0)continue;if(m0(Z)&&m0(B))j[Q]=I8(Z,B);else j[Q]=B}return j}function m0($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function j$($){try{return JSON.parse($)}catch{return null}}function D($){return JSON.stringify($,null,2)+`
|
|
629
|
-
`}async function Z1($,W){let j=[];return j.push(await O8($,W)),j.push(await b8($,W)),j.push(await w8($,W)),j.push(await C8($,W)),j.push(await S8($,W)),j}async function O8($,W){let j=$.join(W.workspaceRoot,".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 Z=x$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,D(Z)),{success:!0,message:"Created .contractsrc.json"}}catch(Z){return{success:!1,message:`Failed to create: ${Z instanceof Error?Z.message:String(Z)}`}}}}}}async function b8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j);return JSON.parse(Z),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Z){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Z instanceof Error?Z.message:String(Z),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=x$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,D(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function w8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z),X=[];if(!B.outputDir)X.push("outputDir");if(!B.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=x$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let q of X)if(Y[q]!==void 0)B[q]=Y[q];return await $.writeFile(j,D(B)),{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 C8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z);if(B.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:B.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 B.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,D(B)),{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 S8($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Z=await $.readFile(j),B=JSON.parse(Z);if(B.hooks){let q=B.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(q).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 B.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,D(B)),{success:!0,message:"Added hooks configuration"}}catch(q){return{success:!1,message:`Failed: ${q instanceof Error?q.message:String(q)}`}}}}};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"}}}import{exec as E8}from"node:child_process";import{promisify as M8}from"node:util";var O$=M8(E8);async function B1($,W){let j=[];return j.push(await N8(W)),j.push(await R8(W)),j.push(await D8($,W)),j.push(await F8($,W)),j.push(await x8($,W)),j}async function N8($){try{let{stdout:W}=await O$("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 R8($){try{let{stdout:W}=await O$("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 D8($,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"}],Q=null;for(let{file:Z,name:B}of j){let X=$.join(W.workspaceRoot,Z);if(await $.exists(X)){Q=B;break}}if(!Q){let Z=$.join(W.workspaceRoot,".."),B=$.join(W.workspaceRoot,"../.."),X=[Z,B];for(let Y of X){for(let{file:q,name:A}of j){let H=$.join(Y,q);if(await $.exists(H)){Q=A;break}}if(Q)break}}if(!Q)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 O$(`${Q} --version`,{cwd:W.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${Q}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${Q} detected but not available`,details:`Install ${Q} or use a different package manager`}}}async function F8($,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 O$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await O$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}}}async function x8($,W){let j=$.join(W.workspaceRoot,"package.json");try{let Q=await $.readFile(j),Z=JSON.parse(Q),B={...Z.dependencies,...Z.devDependencies};if("@contractspec/lib.contracts-spec"in B)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${B["@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 O$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await O$("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 X1($,W){let j=await v0($,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((Q)=>({category:"docs",name:`Same-File DocBlocks (${Q.packageName})`,status:Q.severity==="warning"?"warn":"fail",message:Q.message,details:$.relative(W.workspaceRoot,Q.file),context:{ruleId:Q.ruleId,file:Q.file,line:Q.line,column:Q.column,packageName:Q.packageName}}))}import{isExampleFile as T8,isFeatureFile as v8,scanAllSpecsFromSource as y8,scanExampleSource as P8,scanFeatureSource as m8}from"@contractspec/module.workspace";function k8(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function k0($,W={}){let{fs:j,logger:Q}=$,Z=k8(),B=W.pattern??"**/*.{ts,tsx}";Q.info("Scanning for contract layer files...");let X=await j.glob({pattern:B});for(let q of X){if(q.includes("node_modules")||q.includes("/dist/"))continue;try{let A=await j.readFile(q);if(v8(q)){let H=m8(A,q);Z.features.set(H.key,H);continue}if(T8(q)){let H=P8(A,q);Z.examples.set(H.key,H);continue}if(q.includes(".app-config.")||q.includes(".blueprint.")){let H=y8(A,q);for(let V of H)if(V.specType==="app-config"&&V.key)Z.appConfigs.set(V.key,V)}}catch{}}try{let q=await j.glob({pattern:"**/.contractsrc.json"});for(let A of q){if(A.includes("node_modules"))continue;try{let H=await j.readFile(A),V=JSON.parse(H);Z.workspaceConfigs.set(A,{file:A,config:V,valid:!0,errors:[]})}catch(H){Z.workspaceConfigs.set(A,{file:A,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Z.features.size,examples:Z.examples.size,appConfigs:Z.appConfigs.size,workspaceConfigs:Z.workspaceConfigs.size,total:Z.features.size+Z.examples.size+Z.appConfigs.size+Z.workspaceConfigs.size};return Q.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Z,stats:Y}}function wV($){let W=[];for(let[j,Q]of $.features)W.push({key:j,file:Q.filePath,type:"feature"});for(let[j,Q]of $.examples)W.push({key:j,version:Q.version,file:Q.filePath,type:"example"});for(let[j,Q]of $.appConfigs)W.push({key:j,version:Q.version,file:Q.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function g0($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function Y1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function h0($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let Q=await $.readFile(j),Z=JSON.parse(Q);return{version:typeof Z.version==="number"&&Number.isFinite(Z.version)?Z.version:1,criticalPackages:Y1(Z.criticalPackages).map(g0),criticalFeatureKeys:Y1(Z.criticalFeatureKeys),smokePackages:Y1(Z.smokePackages)}}catch{return}}function I5($,W){let j=g0($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function O5($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function T$($){return g0(`${g0($)}/config/stability-policy.json`)}async function q1($,W){let j=[],Q=await h0($,W.workspaceRoot),Z=await k0({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(g8(Z.stats.features)),j.push(h8(Z.stats.examples)),j.push(f8(Z.inventory.features,Q,W)),j.push(u8(Z.inventory.examples)),j.push(d8(Z.inventory.workspaceConfigs)),j}function g8($){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 h8($){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 f8($,W,j){let Q=[],Z=[];for(let[B,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(O5(B,W))Z.push(B);else Q.push(B);if(Z.length===0&&Q.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?T$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Z.length>0?"fail":"warn",message:Z.length>0?`${Z.length} critical feature(s) missing owners`:`${Q.length} feature(s) missing owners`,details:Z.length>0?`Critical features: ${Z.join(", ")}`:`Features: ${Q.slice(0,3).join(", ")}${Q.length>3?"...":""}`,context:{policyPath:W?T$(j.workspaceRoot):void 0,criticalMissingFeatures:Z,missingFeatures:Q}}}function u8($){let W=[];for(let[j,Q]of $)if(!Q.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 d8($){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 A1($,W){let j=[];return j.push(await n8($,W)),j.push(await c8($,W)),j.push(await l8($,W)),j}async function n8($,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 Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);let B=o$();return await $.writeFile(j,D(B)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Z){return{success:!1,message:`Failed: ${Z instanceof Error?Z.message:String(Z)}`}}}}}}async function c8($,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 Z=await $.readFile(j),B=JSON.parse(Z);if(B.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=o$(),q=r(B,Y);return await $.writeFile(j,D(q)),{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 l8($,W){let j=P0();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Z=await $.readFile(j);if(JSON.parse(Z).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 r8=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],b5=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function o8($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,Q])=>{if(typeof Q==="string")W[j]=Q;return W},{})}function p8($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function i8($,W,j){let Q=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:b5}),Z=[];for(let B of Q){let X=$.dirname(B),Y=$.relative(W,X);try{let q=JSON.parse(await $.readFile(B)),A=o8(q.scripts),H=await $.glob({patterns:r8,cwd:X,ignore:b5});Z.push({packageName:q.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof A.build==="string",hasTypecheckScript:typeof A.typecheck==="string",hasLintScript:typeof A.lint==="string"||typeof A["lint:check"]==="string",hasTestScript:typeof A.test==="string",usesPassWithNoTests:p8(A),testFileCount:H.length,tier:I5(Y,j)})}catch{continue}}return Z}function a8($){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 t8($){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 w5($,W,j){let Q=await i8($,W,j),Z=[];for(let X of Q){if(X.tier==="critical")Z.push(...a8(X));Z.push(...t8(X))}let B=Q.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:Z,criticalPackages:B}}function S5($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function C5($,W,j,Q){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:Q,context:{findings:[]}};let Z=W.filter((B)=>{return B.tier==="critical"||j.has(B.code)});return{category:"workspace",name:$,status:Z.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:S5(W),context:{findings:W}}}async function E5($,W){let j=await h0($,W.workspaceRoot);if(!j)return[];let Q=await w5($,W.workspaceRoot,j),Z=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"]),B=Q.findings.filter((q)=>Z.has(q.code)),X=Q.findings.filter((q)=>q.code==="tests-without-test-script"),Y=Q.findings.filter((q)=>q.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:B.length>0?"fail":"pass",message:B.length>0?`${B.length} critical package gate failure(s)`:`All ${Q.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:B.length>0?S5(B):W.verbose?`Policy: ${T$(W.workspaceRoot)}`:void 0,context:{policyPath:T$(W.workspaceRoot),criticalPackages:Q.criticalPackages,findings:B}},C5("Package Test Scripts",X,new Set,"All tested packages expose a test script"),C5("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var s8=["src/contracts","contracts","src/specs","specs"];async function H1($,W){let j=[];return j.push(e8(W)),j.push(await $9($,W)),j.push(await W9($,W)),j.push(await j9($,W)),j.push(await Z9($,W)),j.push(...await E5($,W)),j}function e8($){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 $9($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let Q of j){let Z=$.join(Q,"package.json");if(await $.exists(Z))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.isMonorepo?`Found at: ${Q}`: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 W9($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],Q=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of s8){let q=$.join(X,Y);if(await $.exists(q)){let A=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${A} 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 Z=W.isMonorepo?"src/contracts":"src/contracts",B=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Z}/${B} to organize your specs`,fix:{description:`Create ${Z}/ directory${B}`,apply:async()=>{try{let X=$.join(Q,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Z}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function j9($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],Q=W.isMonorepo?W.packageRoot:W.workspaceRoot,Z=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:Q});if(Z.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Z.length} contract file(s)${X}`,details:W.verbose?Z.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 Q9($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let Q=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(Q))return{path:Q,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 Z9($,W){try{let j=await Q9($,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 Q=await $.readFile(j.path),Z=JSON.parse(Q),B=Z.outputDir??"./src",X=$.join(j.root,B),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${B}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let A=B==="./src"||B==="src",H=Array.isArray(Z.packages)&&Z.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&A&&(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: ${B}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${B} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${B}`}}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 M5=["cli","config","mcp","deps","docs","workspace","ai","layers"],N5={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var B9={checks:{runCliChecks:Q1,runConfigChecks:Z1,runMcpChecks:A1,runDepsChecks:B1,runDocChecks:X1,runWorkspaceChecks:H1,runAiChecks:j1,runLayerChecks:q1},workspace:{findWorkspaceRoot:R,findPackageRoot:k,isMonorepo:c$,getPackageName:L$}},X9={confirm:async()=>!1,input:async()=>""};async function R5($,W,j=X9,Q=B9){let{fs:Z,logger:B}=$,X=W.categories??M5,{checks:Y,workspace:q}=Q,A=q.findWorkspaceRoot(W.workspaceRoot),H=q.findPackageRoot(W.workspaceRoot),V=q.isMonorepo(A),G=V?q.getPackageName(H):void 0,z={workspaceRoot:A,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let L=G?` (package: ${G})`:"";B.info(`Detected monorepo${L}`)}let J=[];for(let L of X){if(W.skipAi&&L==="ai")continue;B.info(`Checking ${N5[L]}...`);let I=await Y9(L,Z,z,j,Y);for(let U of I){if(U.fix&&(U.status==="fail"||U.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${U.name}"? ${U.fix.description}`)){B.info(`Applying fix: ${U.fix.description}`);let C=await U.fix.apply();if(C.success)B.info(`✓ ${C.message}`),U.status="pass",U.message=`Fixed: ${C.message}`,U.fix=void 0;else B.warn(`✗ ${C.message}`)}}J.push(U)}}let K=J.filter((L)=>L.status==="pass").length,_=J.filter((L)=>L.status==="warn").length,w=J.filter((L)=>L.status==="fail").length,b=J.filter((L)=>L.status==="skip").length;return{checks:J,passed:K,warnings:_,failures:w,skipped:b,healthy:w===0}}async function Y9($,W,j,Q,Z){switch($){case"cli":return Z.runCliChecks(W,j);case"config":return Z.runConfigChecks(W,j);case"mcp":return Z.runMcpChecks(W,j);case"deps":return Z.runDepsChecks(W,j);case"docs":return Z.runDocChecks(W,j);case"workspace":return Z.runWorkspaceChecks(W,j);case"ai":return Z.runAiChecks(W,j,Q);case"layers":return Z.runLayerChecks(W,j);default:return[]}}function tV($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("✓ All checks passed!");else W.push("✗ Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
|
|
630
|
-
`)}function sV($){let j=`${$.status==="pass"?"✓":$.status==="warn"?"⚠":$.status==="fail"?"✗":"○"} ${$.name}: ${$.message}`;if($.details)j+=`
|
|
631
|
-
${$.details}`;if($.fix)j+=`
|
|
632
|
-
Fix available: ${$.fix.description}`;return j}async function V1($,W){let j=[],Q=W.workspaceRoot??process.cwd(),Z=await R5($,{workspaceRoot:Q,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let B of Z.checks)if(B.status==="fail")j.push({ruleId:`doctor-${B.category}-${B.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${B.name}: ${B.message}`,category:"doctor",context:{details:B.details,...B.context??{}}});else if(B.status==="warn")j.push({ruleId:`doctor-${B.category}-${B.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${B.name}: ${B.message}`,category:"doctor",context:{details:B.details,...B.context??{}}});return j}B$();import{mkdtemp as _9,rm as L9}from"node:fs/promises";import{tmpdir as I9}from"node:os";import p$ from"path";import U9 from"path";import{packageDocBlocks as A9}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as H9,convertSpecToDocBlock as V9,extractModuleDocData as G9,loadSpecFromSource as z9,scanAllSpecsFromSource as J9,scanSpecSource as K9}from"@contractspec/module.workspace";import z1 from"path";import{dirname as F5,sep as u0}from"path";class G1{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let W of $){let j;if(W.specType==="app-config")j="app-config";else if(W.specType==="example")j="example";else if(W.specType==="feature")j="feature";if(j&&W.key){let Q=F5(W.filePath);this.modules.push({type:j,key:W.key,dirPath:Q})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let W=F5($),j=this.modules.filter((Q)=>{let Z=Q.dirPath.endsWith(u0)?Q.dirPath:Q.dirPath+u0;return(W.endsWith(u0)?W:W+u0).startsWith(Z)||W===Q.dirPath});if(j.length===0)return;return j.sort((Q,Z)=>{let B={"app-config":3,example:2,feature:1},X=B[Q.type],Y=B[Z.type];if(X!==Y)return Y-X;return Z.dirPath.length-Q.dirPath.length}),j[0]}}async function T5($,W,j){let{fs:Q,logger:Z}=j,B=[];if(Z.info(`Generating docs for ${$.length} files...`),W.outputDir)await Q.mkdir(W.outputDir);let X=new G1(j),Y=[];for(let A of $)try{let H=await Q.readFile(A),V=J9(H,A);if(V.length>0)Y.push(...V);else{let G=K9(H,A);if(G.specType!=="unknown")Y.push(G)}}catch(H){}X.initialize(Y);let q=await v5($,j);for(let A of q)if(B.push(A.entry.block),Z.debug(`Loaded authored doc ${A.entry.id}`),W.outputDir)await x5(A.entry.block,A.filePath,W.outputDir,X,Q);for(let A of $)try{let H=await z9(A);if(!H?.length){Z.warn(`Could not parse spec from ${A}`);continue}for(let V of H){let G=V9(V,{rootPath:W.rootPath});if(B.push(G),Z.debug(`Generated doc for ${G.id}`),!W.outputDir)continue;await x5(G,A,W.outputDir,X,Q)}}catch(H){Z.error(`Error processing ${A}: ${H instanceof Error?H.message:String(H)}`)}if(W.outputDir)Z.info(`Wrote ${B.length} doc files to ${W.outputDir}`);return{blocks:B,count:B.length}}async function HG($,W){return(await v5($,W)).map(({entry:Q})=>Q.block)}function VG($,W){return A9(H9({packageName:$,srcRoot:W}))}async function v5($,W){let j=[...new Set($)].sort((Z,B)=>Z.localeCompare(B)),Q=[];for(let Z of j){let B=await W.fs.readFile(Z),X=Z.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),Y=G9(B,Z,X);for(let q of Y.entries)Q.push({entry:q,filePath:Z})}return Q}async function x5($,W,j,Q,Z){let B=Q.resolve(W),X=B?z1.join(j,B.key):z1.join(j,"_common");await Z.mkdir(X);let Y=z1.join(X,`${$.id}.md`),q=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
633
|
-
|
|
634
|
-
${$.body}`;await Z.writeFile(Y,q)}async function y5($,W,j,Q,Z={}){let B=await $.fs.exists(W),X=Z.scanAllSpecs?Z.specPattern:Z.specPattern??(B?"contracts/**/*.ts":"**/*.ts"),Y=await h($,{cwd:Z.specSearchRoot,pattern:X});if(Y.length===0)return{specsCount:0,docsCount:0};let q=Y.map((V)=>V.filePath),A=U9.join(j,"docs"),H=await T5(q,{outputDir:A,format:"markdown",rootPath:Q},$);return{specsCount:Y.length,docsCount:H.count}}async function d0($,W,j,Q={}){let Z=await _9(p$.join(I9(),"contractspec-drift-"));try{await y5($,W,Z,Q.rootPath,Q.generation);let B=[],X=await import("node:fs/promises");async function Y(G){let z=await X.readdir(G,{withFileTypes:!0}),J=[];for(let K of z){let _=p$.resolve(G,K.name);if(K.isDirectory())J.push(...await Y(_));else J.push(_)}return J}let q=async(G)=>{if(!await X.stat(G).catch(()=>!1))return[];return(await Y(G)).map((J)=>p$.relative(G,J)).sort()},A=await q(Z),H=await q(j),V=new Set([...A,...H]);for(let G of V){if(!H.includes(G)){B.push(G);continue}if(!A.includes(G)){B.push(G);continue}let z=await X.readFile(p$.join(Z,G)),J=await X.readFile(p$.join(j,G));if(!z.equals(J))B.push(G)}return{hasDrift:B.length>0,files:B}}finally{await L9(Z,{recursive:!0,force:!0})}}async function J1($,W){let{fs:j,logger:Q}=$,Z=[],B=await a(j);if(!B.outputDir)return Q.info("No outputDir configured, skipping drift checks"),Z;let X="./contracts",Y=B.outputDir;if(!await j.exists(Y))return Q.info("Generated directory does not exist, skipping drift checks"),Z;try{let q=await d0($,X,Y);if(q.hasDrift)for(let A of q.files)Z.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${A}`,category:"drift",file:`${Y}/${A}`,context:{file:A}})}catch(q){Q.warn("Drift detection failed",{error:q instanceof Error?q.message:String(q)})}return Z}B$();function O9($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function b9($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}async function n0($,W,j,Q={}){let{fs:Z}=W,B=[],X=[],Y=$.key??Z.basename($.filePath).replace(/\.[jt]s$/,""),q=Q.outputDir??j.outputDir??"./src",A=O9(Y),H={};if($.specType==="operation")H.handlerPath=Z.join(q,"handlers",`${A}.handler.ts`),H.handlerTestPath=Z.join(q,"handlers",`${A}.handler.test.ts`);if($.specType==="presentation")H.componentPath=Z.join(q,"components",`${A}.tsx`),H.componentTestPath=Z.join(q,"components",`${A}.test.tsx`);if($.specType==="form")H.formPath=Z.join(q,"forms",`${A}.form.tsx`),H.formTestPath=Z.join(q,"forms",`${A}.form.test.tsx`);if(Q.checkHandlers&&H.handlerPath)if(!await Z.exists(H.handlerPath))B.push(`Missing handler file: ${H.handlerPath}`);else{let G=await Z.readFile(H.handlerPath),z=`${b9(Y.split(".").pop()??Y)}Spec`,J=/ContractHandler<\s*typeof\s+\w+\s*>/.test(G),K=new RegExp(`typeof\\s+${z}\\b`).test(G);if(!J)X.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${H.handlerPath}`);else if(!K)X.push(`Handler ContractHandler typing does not reference expected spec var (${z}): ${H.handlerPath}`)}if(Q.checkTests){let V=[H.handlerTestPath,H.componentTestPath,H.formTestPath].filter((G)=>typeof G==="string");for(let G of V)if(!await Z.exists(G))B.push(`Missing test file: ${G}`)}return{valid:B.length===0,errors:B,warnings:X,expected:H}}async function K1($,W){let{fs:j}=$,Q=[],Z=await a(j);for(let B of W){if(B.specType!=="operation")continue;let X=await n0(B,{fs:j},Z,{checkHandlers:!0,outputDir:Z.outputDir});for(let Y of X.errors)Q.push({ruleId:"handler-missing",severity:"warning",message:Y,category:"handlers",file:B.filePath});for(let Y of X.warnings)Q.push({ruleId:"handler-warning",severity:"warning",message:Y,category:"handlers",file:B.filePath})}return Q}B$();import{createHash as N9}from"crypto";import R9 from"path";var i$={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},w9={".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 C9($){let W=$.toLowerCase();for(let[j,Q]of Object.entries(w9))if(W.endsWith(j))return Q;if(W.includes("/handlers/"))return"handler";if(W.includes("/services/"))return"service";if(W.includes("/components/"))return"component";if(W.includes("/forms/"))return"form";if(W.includes("/hooks/"))return"hook";if(W.includes("/__tests__/"))return"test";return"other"}function P5($,W){let j=[],Q=new Set,Z=(G,z,J)=>{let K=`${G}:${z}`;if(Q.has(K))return;Q.add(K),j.push({filePath:W,specKey:G,referenceType:z,lineNumber:J,inferredType:C9(W)})},B=(G)=>{return $.substring(0,G).split(`
|
|
635
|
-
`).length},X,Y=new RegExp(i$.contractHandler);while((X=Y.exec($))!==null)if(X[1])Z(X[1],"handler",B(X.index));let q=new RegExp(i$.typeofSpec);while((X=q.exec($))!==null)if(X[1])Z(X[1],"typeof",B(X.index));let A=new RegExp(i$.namedImport);while((X=A.exec($))!==null){let z=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(z)for(let J of z)Z(J,"import",B(X.index))}let H=new RegExp(i$.defaultImport);while((X=H.exec($))!==null)if(X[1])Z(X[1],"import",B(X.index));let V=new RegExp(i$.specAssignment);while((X=V.exec($))!==null)if(X[1])Z(X[1],"unknown",B(X.index));return j}var m5=["**/*.ts(x)"];async function c0($,W,j={}){let{fs:Q}=W,Z=j.includePatterns??m5,B=j.excludePatterns??[...new Set([..._$,...U$])],X=[];for(let Y of Z){let q=await Q.glob({pattern:Y,ignore:B});for(let A of q)try{let H=await Q.readFile(A),G=P5(H,A).filter((z)=>z.specKey===$);X.push(...G)}catch{}}return X}async function vG($,W={}){let{fs:j}=$,Q=W.includePatterns??m5,Z=W.excludePatterns??[...new Set([..._$,...U$])],B=new Map;for(let X of Q){let Y=await j.glob({pattern:X,ignore:Z});for(let q of Y)try{let A=await j.readFile(q),H=P5(A,q);for(let V of H){let G=B.get(V.specKey)??[];G.push(V),B.set(V.specKey,G)}}catch{}}return B}function S9($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function k5($,W,j){let Q=S9(W),Z=[];if($==="operation")Z.push({path:`${j}/handlers/${Q}.handler.ts`,type:"handler"}),Z.push({path:`${j}/handlers/${Q}.handler.test.ts`,type:"test"});if($==="presentation")Z.push({path:`${j}/components/${Q}.tsx`,type:"component"}),Z.push({path:`${j}/components/${Q}.test.tsx`,type:"test"});if($==="form")Z.push({path:`${j}/forms/${Q}.form.tsx`,type:"form"}),Z.push({path:`${j}/forms/${Q}.form.test.tsx`,type:"test"});if($==="event")Z.push({path:`${j}/handlers/${Q}.handler.ts`,type:"handler"}),Z.push({path:`${j}/handlers/${Q}.handler.test.ts`,type:"test"});return Z}import{Node as d,Project as E9,SyntaxKind as M9}from"ts-morph";function g5($){let W=[],Q=new E9({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Z=(q)=>{if(!d.isObjectLiteralExpression(q))return;let A=q.getProperty("implementations");if(A&&d.isPropertyAssignment(A)){let H=A.getInitializer();if(H&&d.isArrayLiteralExpression(H)){for(let V of H.getElements())if(d.isObjectLiteralExpression(V)){let G,z,J,K=V.getProperty("path");if(K&&d.isPropertyAssignment(K)){let b=K.getInitializer();if(d.isStringLiteral(b))G=b.getLiteralText()}let _=V.getProperty("type");if(_&&d.isPropertyAssignment(_)){let b=_.getInitializer();if(d.isStringLiteral(b))z=b.getLiteralText()}let w=V.getProperty("description");if(w&&d.isPropertyAssignment(w)){let b=w.getInitializer();if(d.isStringLiteral(b))J=b.getLiteralText()}if(G&&z)W.push({path:G,type:z,description:J})}}}},B=Q.getDescendantsOfKind(M9.CallExpression);for(let q of B){let A=q.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(A)){let H=q.getArguments();if(H.length>0&&d.isObjectLiteralExpression(H[0]))return Z(H[0]),W}}let X=Q.getVariableStatements();for(let q of X)if(q.isExported())for(let A of q.getDeclarations()){let H=A.getInitializer();if(H&&d.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Z(H),W}}let Y=Q.getExportAssignment((q)=>!q.isExportEquals());if(Y){let q=Y.getExpression();if(d.isObjectLiteralExpression(q))Z(q);else if(d.isAsExpression(q)&&d.isObjectLiteralExpression(q.getExpression()))Z(q.getExpression())}return W}function h5($){if($.length===0)return"missing";let W=$.filter((Z)=>Z.exists),j=$.filter((Z)=>Z.type!=="test");if(W.filter((Z)=>Z.type!=="test").length===0)return"missing";if($.every((Z)=>Z.exists))return"implemented";return"partial"}function gG($){let W=$.filter((Z)=>Z.status==="implemented").length,j=$.filter((Z)=>Z.status==="partial").length,Q=$.filter((Z)=>Z.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:Q,coverage:$.length>0?Math.round(W/$.length*100):100}}var D9={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function f5($){return N9("sha256").update($).digest("hex")}async function F9($,W,j,Q={},Z){let B={...D9,...Q},X=B.computeHashes?f5($.sourceBlock||""):void 0,Y=$.key??R9.basename($.filePath).replace(/\.[jt]s$/,""),q=$.version??"1.0.0",{fs:A}=W,H=[],V=new Set,G=async(J,K,_,w)=>{if(V.has(J))return;V.add(J);let b=await A.exists(J),L=void 0,I=void 0;if(b&&B.computeHashes)try{L=await A.readFile(J),I=f5(L)}catch{}H.push({path:J,type:K,source:_,exists:b,implementationSourceContent:L,implementationSourceHash:I,description:w})};if(B.includeExplicit&&$.sourceBlock){if(Z)Z.suffixText="Discover explicit implementations";let J=g5($.sourceBlock);for(let K of J)await G(K.path,K.type,"explicit",K.description)}if(B.includeDiscovered){if(Z)Z.suffixText="Discover implementations";let J=await c0(Y,W,B);for(let K of J){if(K.filePath===$.filePath)continue;await G(K.filePath,K.inferredType,"discovered")}}if(B.includeConvention){if(Z)Z.suffixText="Discover implementations based on conventions";let J=B.outputDir??j.outputDir??"./src",K=k5($.specType,Y,J);for(let{path:_,type:w}of K)await G(_,w,"convention")}if(Z)Z.suffixText="Determine implementation status";let z=h5(H);return{specKey:Y,specVersion:q,specPath:$.filePath,specType:$.specType,implementations:H,status:z,specHash:X}}async function u5($,W,j,Q={},Z){let B=[];for(let X of $){if(Z)Z.text=`Resolving implementation... (${B.length}/${$.length})`;try{let Y=await F9(X,W,j,Q,Z);B.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return B}async function U1($,W,j){let{fs:Q}=$,Z=[],B=await a(Q),X=j.implementation??{},Y=W.filter((A)=>A.specType==="operation"),q=await u5(Y,{fs:Q},B,{computeHashes:X.useCache??!0});for(let A of q){if(X.requireImplemented&&A.status==="missing")Z.push({ruleId:"impl-missing",severity:"error",message:`Spec ${A.specKey} has no implementation`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,specVersion:A.specVersion,status:A.status}});else if(A.status==="missing")Z.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${A.specKey} has no implementation`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,specVersion:A.specVersion,status:A.status}});if(!X.allowPartial&&A.status==="partial"){let V=A.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Z.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${A.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,specVersion:A.specVersion,status:A.status,missingFiles:V}})}let H=A.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Z.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${A.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:A.specPath,context:{specKey:A.specKey,missingTests:H.map((V)=>V.path)}})}return Z}import{isFeatureFile as v9,scanAllSpecsFromSource as y9,scanFeatureSource as P9}from"@contractspec/module.workspace";function x9($,W){return`${$}.v${W}`}function _1($,W,j,Q,Z,B={}){let{treatMissingAsError:X=!0}=B;if(!Q||Q.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],q=[],A=[];for(let H of Q){let V=x9(H.key,H.version);if(Z.has(V))Y.push(H);else if(q.push(H),X)A.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:q.length===0,foundTests:Y,missingTests:q,errors:A,specFile:$}}function d5($,W){return`${$}.v${W}`}function n5($,W){let j=new Map,Q=new Map,Z=[],B=[];for(let X of $){if(!X.key||!X.version)continue;let Y=d5(X.key,X.version);if(!X.testTarget){B.push(Y);continue}let{type:q,key:A,version:H}=X.testTarget,V=H??X.version,G=d5(A,V),z=T9(W,q);if(!z||!z.has(G)){Z.push(Y);continue}if(Q.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:Q,orphanedTests:Z,testsWithoutTarget:B}}function T9($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function o($,W){return`${$}.v${W}`}function m9(){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 L1($,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 l0($,W={}){let{fs:j,logger:Q}=$;Q.info("Starting integrity analysis...",{options:W});let Z=await j.glob({pattern:W.pattern,cwd:W.cwd}),B=m9(),X=[],Y=[];for(let U of Z){if((await j.stat(U)).isDirectory)continue;let C=await j.readFile(U);if(v9(U)){let S=P9(C,U);X.push(S)}else{let S=y9(C,U);for(let M of S)if(M.specType!=="unknown"&&M.specType!=="feature"){let u=L1(B,M.specType);if(u&&M.key&&M.version!==void 0){let l=o(M.key,M.version);u.set(l,{key:M.key,version:M.version,file:M.filePath,type:M.specType,stability:M.stability,testTarget:M.testTarget,testCoverage:M.testCoverage})}}}}let q=W.featureKey?X.filter((U)=>U.key===W.featureKey):X,A=new Set;for(let U of q){for(let O of U.operations){let C=o(O.key,O.version);if(A.add(`operation:${C}`),!B.operations.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"operation",ref:O})}for(let O of U.events){let C=o(O.key,O.version);if(A.add(`event:${C}`),!B.events.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"event",ref:O})}for(let O of U.presentations){let C=o(O.key,O.version);if(A.add(`presentation:${C}`),!B.presentations.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"presentation",ref:O})}for(let O of U.experiments){let C=o(O.key,O.version);if(A.add(`experiment:${C}`),!B.experiments.has(C))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"experiment",ref:O})}for(let O of U.capabilities.provides){let C=o(O.key,O.version);if(A.add(`capability:${C}`),!B.capabilities.has(C))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"capability",ref:O})}for(let O of U.capabilities.requires){let C=o(O.key,O.version);A.add(`capability:${C}`)}for(let O of U.opToPresentationLinks){let C=o(O.op.key,O.op.version),S=o(O.pres.key,O.pres.version);if(!B.operations.has(C))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${O.op.key}.v${O.op.version} not found`,file:U.filePath,featureKey:U.key,specType:"operation",ref:O.op});if(!B.presentations.has(S))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${O.pres.key}.v${O.pres.version} not found`,file:U.filePath,featureKey:U.key,specType:"presentation",ref:O.pres})}if(U.presentationsTargets)for(let O of U.presentationsTargets){let C=o(O.key,O.version);if(!B.presentations.has(C))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${O.key}.v${O.version} not found`,file:U.filePath,featureKey:U.key,specType:"presentation",ref:{key:O.key,version:O.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let U of V){let O=L1(B,U);if(!O)continue;for(let[C,S]of O)if(!A.has(`${U}:${C}`))H.push(S),Y.push({severity:"warning",type:"orphaned",message:`${U} ${S.key}.v${S.version} is not linked to any feature`,file:S.file,specKey:S.key,specType:S.type})}let G=[];for(let[,U]of B.testSpecs)G.push({filePath:U.file,specType:"test-spec",key:U.key,version:U.version,testTarget:U.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let z=n5(G,B);for(let U of q)for(let O of U.opToPresentationLinks){let C=o(O.op.key,O.op.version),S=z.targetToTests.get(C),M=!1,u=!1;if(S)for(let l of S){let y=B.testSpecs.get(l);if(y?.testCoverage){if(y.testCoverage.hasSuccess)M=!0;if(y.testCoverage.hasError)u=!0}}if(!S||!M||!u){let l=[];if(!M)l.push("success scenario");if(!u)l.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${O.op.key}.v${O.op.version} linked to presentation requires tests covering: ${l.join(", ")}`,file:U.filePath,featureKey:U.key,specType:"operation",ref:O.op})}}let J={},K=0;for(let U of V){let O=L1(B,U);if(!O)continue;let C=O.size,S=0,M=0,u=W.requireTestsFor?.includes(U);for(let[l,y]of O){if(A.has(`${U}:${l}`))S++;if(u){let F=o(y.key,y.version),d$=z.targetToTests.has(F),K6=`${y.key}.test`,U6=B.testSpecs.has(o(K6,y.version));if(!d$&&!U6)M++,K++,Y.push({severity:"warning",type:"missing-test",message:`${U} ${y.key}.v${y.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:y.file,specKey:y.key,specType:y.type})}}J[U]={total:C,covered:S,orphaned:C-S,missingTest:u?M:0}}let _=Object.values(J).reduce((U,O)=>U+O.total,0),w=Object.values(J).reduce((U,O)=>U+O.covered,0),b={total:_,linkedToFeature:w,orphaned:_-w,missingTest:K,byType:J},I=!Y.some((U)=>U.severity==="error");return Q.info("Integrity analysis complete",{features:X.length,totalSpecs:_,orphaned:H.length,issues:Y.length,healthy:I}),{inventory:B,features:q,coverage:b,issues:Y,orphanedSpecs:H,healthy:I}}function Zz($){let W=[];for(let j of Object.values($))for(let Q of j.values())W.push(Q);return W}function Bz($,W){return $.filter((j)=>j.type===W)}function Xz($,W){return $.filter((j)=>j.severity===W)}async function I1($,W){let j=[],Q=await l0($,{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 O1($,W){let j=[],Q=await k0($,{});for(let[Z,B]of Q.inventory.features){if(!B.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:B.filePath,context:{key:Z}});if(!B.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Z}' missing 'owners' field`,category:"layers",file:B.filePath,context:{key:Z}});if(B.operations.length===0&&B.events.length===0&&B.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Z}' has no operations, events, or presentations`,category:"layers",file:B.filePath,context:{key:Z}})}for(let[Z,B]of Q.inventory.examples){if(!B.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Z}' missing 'packageName' in entrypoints`,category:"layers",file:B.filePath,context:{key:Z}});if(!B.surfaces.templates&&!B.surfaces.sandbox.enabled&&!B.surfaces.studio.enabled&&!B.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Z}' has no enabled surfaces`,category:"layers",file:B.filePath,context:{key:Z}})}for(let Z of Q.inventory.workspaceConfigs.values())if(!Z.valid)for(let B of Z.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${B}`,category:"layers",file:Z.file});return j}B$();import{ContractsrcSchema as k9,DEFAULT_CONTRACTSRC as r0}from"@contractspec/lib.contracts-spec/workspace-config";var g9=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,h9=/@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?)?['"]/,f9=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,u9=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,d9=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,n9=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,c9=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function o0($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function l9($,W){let j=$.replaceAll("\\","/"),Q=new Set(["contracts","features",...o0(W?.conventions?.operations),...o0(W?.conventions?.events),...o0(W?.conventions?.presentations),...o0(W?.conventions?.forms)]);return j.split("/").some((Z)=>Q.has(Z))}function r9($,W,j){let Q=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(Q))return!1;if(Q.includes("/node_modules/")||Q.includes("/dist/")||d9.test(Q)||u9.test(Q)||Q.endsWith(".d.ts")||Q.endsWith(".test.ts")||Q.endsWith(".spec.ts"))return!1;if(W.has(Q))return!1;if(l9(Q,j))return!1;return g9.test(Q)}function c5($){return $.replaceAll("\\","/").match(n9)?.[1]??null}function o9($){let W=$.split(`
|
|
636
|
-
`).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 p9($){if(!$)return r0;let W=k9.safeParse($),j=W.success?W.data:{};return{...r0,...j,conventions:{...r0.conventions,...j.conventions??{}},ci:{...r0.ci,...j.ci??{}}}}async function b1($,W){let{fs:j,logger:Q}=$,Z=[],B=W.config?p9(W.config):await a(j),X=await h({fs:j},{config:B}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),q=new Set(X.map((H)=>c5(H.filePath)).filter((H)=>Boolean(H))),A=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of A){if(!r9(H,Y,B))continue;try{let V=await j.readFile(H);if(o9(V))continue;let G=c5(H);if(!(G!==null&&c9.test(G)&&q.has(G))&&!f9.test(V))continue;if(h9.test(V))continue;Z.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){Q.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Z}import{validateSpecStructure as i9}from"@contractspec/module.workspace";async function w1($){let W=[];for(let j of $){let Q=i9(j);for(let Z of Q.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Z,category:"structure",file:j.filePath});for(let Z of Q.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Z,category:"structure",file:j.filePath})}return W}async function C1($){let W=[],j=new Map,Q=new Map;for(let Z of $){if(!Z.key||!Z.version)continue;if(Z.specType==="test-spec"){let B=`${Z.key}.v${Z.version}`;j.set(B,{key:Z.key,version:Z.version,file:Z.filePath,type:"test-spec"})}if(Z.testRefs&&Z.testRefs.length>0){if(!Q.has(Z.filePath))Q.set(Z.filePath,[]);Q.get(Z.filePath)?.push({key:Z.key,version:Z.version,testRefs:Z.testRefs})}}for(let[Z,B]of Q)for(let X of B){if(!X.testRefs)continue;let Y=_1(Z,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let q of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:q,category:"test-refs",file:Z,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}B$();async function S1($,W){let{fs:j}=$,Q=[],Z=await a(j);for(let B of W){if(B.specType!=="operation")continue;let X=await n0(B,{fs:j},Z,{checkTests:!0,outputDir:Z.outputDir});for(let Y of X.errors)Q.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:B.filePath});for(let Y of X.warnings)Q.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:B.filePath})}return Q}function c($,W,j){let Q={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"},Z=W.filter((Y)=>Y.severity==="error").length,B=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:Q[$],errors:Z,warnings:B,notes:X,passed:Z===0,durationMs:j}}async function l5($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),Q=j.match(/^ref: (.+)$/m);if(Q){let B=Q[1]?.replace("refs/heads/",""),X=`.git/${Q[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:B};return{branch:B}}return{commitSha:j.trim()}}catch{return{}}}function r5($){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((Q)=>!$.skip?.includes(Q));return j}async function uz($,W={}){let j=Date.now(),{fs:Q,logger:Z}=$,B=[],X=[],Y=r5(W);Z.info("Starting CI checks...",{checks:Y});let q=await h($,{pattern:W.pattern,type:["feature","test-spec"]});if(Y.includes("structure")){let K=Date.now(),_=await w1(q);B.push(..._),X.push(c("structure",_,Date.now()-K))}if(Y.includes("integrity")){let K=Date.now(),_=await I1($,W);B.push(..._),X.push(c("integrity",_,Date.now()-K))}if(Y.includes("deps")){let K=Date.now(),_=await $1($,W);B.push(..._),X.push(c("deps",_,Date.now()-K))}if(Y.includes("doctor")){let K=Date.now(),_=await V1($,W);B.push(..._),X.push(c("doctor",_,Date.now()-K))}if(Y.includes("docs")){let K=Date.now(),_=await W1($,W);B.push(..._),X.push(c("docs",_,Date.now()-K))}if(Y.includes("policy")){let K=Date.now(),_=await b1($,W);B.push(..._),X.push(c("policy",_,Date.now()-K))}if(Y.includes("handlers")||W.checkHandlers){let K=Date.now(),_=await K1($,q);B.push(..._),X.push(c("handlers",_,Date.now()-K))}if(Y.includes("tests")||W.checkTests){let K=Date.now(),_=await S1($,q);B.push(..._),X.push(c("tests",_,Date.now()-K))}if(Y.includes("test-refs")){let K=Date.now(),_=await C1(q);B.push(..._),X.push(c("test-refs",_,Date.now()-K))}if(Y.includes("coverage")){let K=Date.now(),_=await eW($,q,W);B.push(..._),X.push(c("coverage",_,Date.now()-K))}if(Y.includes("implementation")){let K=Date.now(),_=await U1($,q,W);B.push(..._),X.push(c("implementation",_,Date.now()-K))}if(Y.includes("layers")){let K=Date.now(),_=await O1($,W);B.push(..._),X.push(c("layers",_,Date.now()-K))}if(Y.includes("drift")){let K=Date.now(),_=await J1($,W);B.push(..._),X.push(c("drift",_,Date.now()-K))}let A=B.filter((K)=>K.severity==="error").length,H=B.filter((K)=>K.severity==="warning").length,V=B.filter((K)=>K.severity==="note").length,G=W.failOnWarnings?A===0&&H===0:A===0,z=await l5(Q),J={success:G,totalErrors:A,totalWarnings:H,totalNotes:V,issues:B,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...z};return Z.info("CI checks complete",{success:G,errors:A,warnings:H,durationMs:J.durationMs}),J}var nz=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],cz={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 iz($,W={}){let{fs:j,logger:Q}=$,Z=(W.outputDir??"./src").replace(/\\/g,"/"),B=["generated/**","dist/**",".turbo/**"],X=[`${Z}/handlers/**/*.handler.ts`,`${Z}/handlers/**/*.handler.test.ts`,`${Z}/components/**/*.tsx`,`${Z}/components/**/*.test.tsx`,`${Z}/forms/**/*.form.tsx`,`${Z}/forms/**/*.form.test.tsx`,`${Z}/**/*.runner.ts`,`${Z}/**/*.renderer.tsx`],Y=W.generatedOnly?[...B,...X]:[...B,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],q=await j.glob({patterns:Y,ignore:["node_modules/**"]}),A=[],H=[];for(let V of q)try{let G=await j.stat(V),z=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&z<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)Q.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),Q.info("clean.removed",{path:V,size:G.size});A.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:A,skipped:H}}B$();var K4={};P(K4,{writeReviewPacket:()=>f1,writeDecisionEnvelope:()=>j0,withBranch:()=>S$,verifyConnectMutation:()=>tZ,resolveWorkspace:()=>f,resolveStoragePaths:()=>$$,replayConnectDecision:()=>xZ,persistLatestArtifacts:()=>g1,persistDecisionArtifacts:()=>W0,normalizeEvalInput:()=>EZ,matchConfiguredPath:()=>a$,loadStoredDecision:()=>Q0,listStoredReviewPackets:()=>u1,listConnectReviewPackets:()=>TZ,isReviewCommand:()=>E1,isDeniedCommand:()=>M1,isAllowedCommand:()=>p0,initConnectWorkspace:()=>NZ,inferSurfaces:()=>e$,evaluateConnectDecision:()=>CZ,ensureStorage:()=>$0,defaultActor:()=>s$,decisionArtifactRefs:()=>P$,createConnectControlPlaneRuntime:()=>dZ,connectVerdictToPolicy:()=>v$,configuredThreshold:()=>b$,compileConnectPlanPacket:()=>d1,buildConnectContextPack:()=>k1,assessConnectPolicy:()=>t$,assertConnectEnabled:()=>p,artifactRef:()=>X$,appendAuditRecord:()=>h1,analyzeConnectImpact:()=>E$,CONTROL_PLANE_TRACE_GET_REF:()=>i0,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>a0,CONTROL_PLANE_PLAN_VERIFY_REF:()=>F1,CONTROL_PLANE_PLAN_COMPILE_REF:()=>D1,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>R1,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>w$,AGENT_APPROVALS_REF:()=>t0,ACP_TERMINAL_EXEC_REF:()=>e9,ACP_FS_ACCESS_REF:()=>s9});import a9 from"micromatch";function p($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function a$($,W,j){if(!j||j.length===0)return!1;let Q=W.replaceAll("\\","/");return a9.isMatch(Q,j,{contains:!0})}function b$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function p0($,W){return N1($.config.connect?.commands?.allow,W)}function E1($,W){return N1($.config.connect?.commands?.review,W)}function M1($,W){return N1($.config.connect?.commands?.deny,W)}function N1($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function p5($,W){if(W.length===0)return{state:"none"};for(let Q of W)if(M1($,Q))return{commandMatch:Q,state:"deny"};for(let Q of W)if(E1($,Q))return{commandMatch:Q,state:"review"};if(W.every((Q)=>p0($,Q)))return{state:"allow"};let j=W.find(t9);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((Q)=>!p0($,Q)),state:"unknown"}}function t9($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return o5(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return o5(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function o5($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var R1={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},D1={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},F1={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},i0={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},a0={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},w$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},s9={key:"acp.fs.access",version:"1.0.0",kind:"command"},e9={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},t0={key:"agent.approvals",version:"1.0.0",kind:"command"};function t$($,W){let j=W.touchedPaths.find((G)=>a$($,G,$.config.connect?.policy?.immutablePaths)),Q=W.touchedPaths.find((G)=>a$($,G,$.config.connect?.policy?.protectedPaths)),Z=W.touchedPaths.find((G)=>a$($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:B,state:X}=p5($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,q=W.impactAnalysis.driftFiles.length>0,A=$Z({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:q,generatedPath:Boolean(Z),immutable:Boolean(j),protectedPath:Boolean(Q),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=WZ({breakingChange:W.impactAnalysis.breakingChange,commandMatch:B,commandState:X,contractDrift:q,protectedPath:Q,unknownPaths:W.impactAnalysis.unknownPaths}),V=v$(A);return{commandMatch:B,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Z,immutablePath:j,protectedPath:Q,requiredApprovals:V.requiresApproval?[{capability:w$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:A}}function v$($){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 $Z($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(b$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(b$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(b$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(b$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(b$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(jZ)[0]??"permit"}function WZ($){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 jZ($,W){return i5($)-i5(W)}function i5($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as bZ}from"crypto";var $4={};P($4,{formatPrComment:()=>a5,formatMinimalComment:()=>x1,formatJson:()=>s5,formatCheckRun:()=>t5,detectImpact:()=>C$,ImpactDetectionOverviewDocBlock:()=>qZ});function a5($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)j.push("⚠️ **Contract changed (non-breaking)**");else j.push("✅ **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| ➖ Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let Q=$.deltas.filter((B)=>B.severity==="breaking"),Z=$.deltas.filter((B)=>B.severity==="non_breaking");if(Q.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let B of Q)j.push(`- **${B.specKey}**: ${B.description}`);j.push("")}if(Z.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let B of Z)j.push(`- **${B.specKey}**: ${B.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let Q of $.addedSpecs)j.push(`- \`${Q.key}\` v${Q.version} (${Q.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let Q of $.removedSpecs)j.push(`- \`${Q.key}\` v${Q.version} (${Q.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### ⚠️ Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let Q of W.drift.files)j.push(`- \`${Q}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### ✅ No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
|
|
637
|
-
`)}function x1($){if($.hasBreaking)return`❌ **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`⚠️ **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"✅ **No contract impact**"}function t5($,W,j={}){let Q=j.key??"ContractSpec Impact",Z=j.failOnBreaking??!0,B,X;if($.hasBreaking)B=Z?"failure":"neutral",X=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)B="success",X=`Non-breaking changes (${$.summary.nonBreaking})`;else B="success",X="No contract impact";let Y=x1($);return{name:Q,headSha:W,conclusion:B,title:X,summary:Y,annotations:$.deltas.filter((q)=>q.severity==="breaking").slice(0,50).map((q)=>({path:q.path,startLine:1,endLine:1,annotationLevel:"failure",message:q.description,title:`Breaking: ${q.rule}`}))}}function s5($){let W={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((j)=>({type:j.rule,path:j.specKey,summary:j.description,severity:j.severity==="breaking"?"breaking":j.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(W,null,2)}import{classifyImpact as QZ,computeIoDiff as ZZ,generateSnapshot as e5}from"@contractspec/module.workspace";async function C$($,W={}){let{fs:j,git:Q,logger:Z}=$,B=W.workspaceRoot??process.cwd();Z.info("Starting impact detection...",{baseline:W.baseline});let Y=(await j.glob({pattern:W.pattern??"**/*.{operation,event}.ts",cwd:B})).filter((z)=>!z.includes(".test.")&&!z.includes(".spec.")&&!z.includes("node_modules"));Z.debug(`Found ${Y.length} spec files`);let q=await BZ(j,Y,B),A=e5(q),H;if(W.baseline){let z=await XZ(j,Q,Y,W.baseline,B);H=e5(z)}else H={version:"1.0.0",generatedAt:"",specs:[],hash:""};let V=YZ(H.specs,A.specs),G=QZ(H.specs,A.specs,V);return Z.info("Impact detection complete",{status:G.status,breaking:G.summary.breaking,nonBreaking:G.summary.nonBreaking}),{...G,workspaceRoot:B,specsAnalyzed:Y.length,baseRef:W.baseline}}async function BZ($,W,j){let Q=[];for(let Z of W){let B=await $.readFile(Z);Q.push({path:Z,content:B})}return Q}async function XZ($,W,j,Q,Z){let B=[];for(let X of j)try{let Y=await W.showFile(Q,X);B.push({path:X,content:Y})}catch{}return B}function YZ($,W){let j=[],Q=new Map($.map((B)=>[`${B.key}@${B.version}`,B])),Z=new Map(W.map((B)=>[`${B.key}@${B.version}`,B]));for(let[B,X]of Z){let Y=Q.get(B);if(Y&&X.type==="operation"&&Y.type==="operation"){let q=ZZ(Y.io,X.io);j.push(...q)}}return j}var qZ={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
638
|
-
# Contract Impact Detection
|
|
639
|
-
|
|
640
|
-
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
641
|
-
|
|
642
|
-
## Features
|
|
643
|
-
|
|
644
|
-
- **Snapshot Generation**: Creates canonical, deterministic representations of contracts
|
|
645
|
-
- **Deep Diff Engine**: Field-level comparison of input/output schemas
|
|
646
|
-
- **Breaking Change Classification**: Automatic classification using 16 rules
|
|
647
|
-
- **Multiple Output Formats**: JSON, Markdown, Text, GitHub Check Run
|
|
648
|
-
- **GitHub Integration**: PR comments and check runs
|
|
649
|
-
- **CLI Tool**: \`contractspec impact\` command
|
|
650
|
-
|
|
651
|
-
## Quick Start
|
|
652
|
-
|
|
653
|
-
### CLI Usage
|
|
654
|
-
|
|
655
|
-
\`\`\`bash
|
|
656
|
-
# Basic usage
|
|
657
|
-
contractspec impact
|
|
658
|
-
|
|
659
|
-
# Compare against specific baseline
|
|
660
|
-
contractspec impact --baseline origin/main
|
|
661
|
-
|
|
662
|
-
# Get JSON output
|
|
663
|
-
contractspec impact --format json
|
|
664
|
-
\`\`\`
|
|
665
|
-
|
|
666
|
-
### GitHub Action
|
|
667
|
-
|
|
668
|
-
\`\`\`yaml
|
|
669
|
-
- uses: lssm-tech/contractspec-action@v1
|
|
670
|
-
with:
|
|
671
|
-
mode: impact
|
|
672
|
-
pr-comment: true
|
|
673
|
-
fail-on-breaking: true
|
|
674
|
-
\`\`\`
|
|
675
|
-
|
|
676
|
-
## Architecture
|
|
677
|
-
|
|
678
|
-
The system consists of three layers:
|
|
679
|
-
|
|
680
|
-
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
681
|
-
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
682
|
-
3. **Integrations**: CLI command + GitHub Action
|
|
683
|
-
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as j4,readFileSync as Q4}from"node:fs";import{basename as AZ,join as T1,resolve as HZ}from"node:path";import{ContractsrcSchema as VZ,DEFAULT_CONTRACTSRC as GZ}from"@contractspec/lib.contracts-spec/workspace-config";function f($={}){let W=HZ($.cwd??process.cwd()),j=$.workspaceRoot??R(W),Q=$.packageRoot??k(W),Z=$.config??zZ(j,Q),B=JZ(Q,j);return{cwd:W,workspaceRoot:j,packageRoot:Q,config:Z,repoId:B,branch:"unknown"}}function S$($,W){return{...$,branch:W&&W.length>0?W:"unknown"}}function s$($,W){return W??{id:`cli:${$}`,type:"human"}}function e$($){let W=new Set;for(let j of $){if(j.includes("/cli-")||j.includes("/apps/cli-"))W.add("cli");if(j.includes("/contracts-spec/")||j.includes("/specs/"))W.add("contract");if(j.includes("/runtime/"))W.add("runtime");if(j.includes("/harness"))W.add("harness");if(j.includes("/ai-agent/"))W.add("agent");if(j.includes("/knowledge/"))W.add("knowledge");if(j.includes("/mcp/"))W.add("mcp")}if(W.size===0)W.add("runtime");return W.add("audit"),[...W].sort()}function zZ($,W){let j={...GZ};if($!==W)j=W4(j,T1($,".contractsrc.json"));return W4(j,T1(W,".contractsrc.json"))}function W4($,W){if(!j4(W))return $;try{let j=Q4(W,"utf-8"),Q=JSON.parse(j),Z=VZ.safeParse(Q);if(!Z.success)return $;return{...$,...Z.data}}catch{return $}}function JZ($,W){let j=T1($,"package.json");if(j4(j))try{let Q=JSON.parse(Q4(j,"utf-8"));if(Q.name)return Q.name}catch{}return AZ(W)}async function E$($,W){let j=await h({fs:$.fs},{config:W.workspace.config}),Q=new Map(j.filter((q)=>typeof q.key==="string").map((q)=>[q.key,q])),Z=W.touchedPaths.map((q)=>KZ($.fs,W.workspace,q,j,Q)),B=W.baseline!=null?await C$({...$,logger:$.logger??B4},{baseline:W.baseline,workspaceRoot:W.workspace.workspaceRoot}):void 0,X=await UZ($,W.workspace,W.touchedPaths),Y=m1([...Z.flatMap((q)=>q.contracts),...(B?.deltas??[]).map((q)=>({key:q.specKey,version:q.specVersion,kind:q.specType==="event"?"event":"command"}))]);return{breakingChange:B?.hasBreaking===!0,driftFiles:X,impactResult:B,impactedContracts:Y,pathImpacts:Z,unknownPaths:Z.filter((q)=>q.contracts.length===0).map((q)=>q.path)}}function KZ($,W,j,Q,Z){let B=$.resolve(W.workspaceRoot,j),X=P1(j),Y=Q.map((J)=>{let K=i($.relative(W.workspaceRoot,J.filePath));return{score:IZ(j,X,K,J.key),spec:J}}).filter((J)=>J.score>=45).sort((J,K)=>K.score-J.score).slice(0,3),q=Q.find((J)=>J.filePath===B),A=q?[{score:100,spec:q}]:Y,H=A.filter((J)=>typeof J.spec.key==="string").map((J)=>y1(J.spec.key,J.spec.version,J.spec.kind)),V=A.flatMap((J)=>[...J.spec.emittedEvents??[],...J.spec.policyRefs??[],...J.spec.testRefs??[]].map((K)=>Z.get(K.key)).filter(Boolean).map((K)=>y1(K.key,K.version,K.kind))),G=m1([...H,...V]),z=m1([{key:"connect.policy",version:"1.0.0",kind:"policy"},...A.flatMap((J)=>J.spec.policyRefs??[]).map((J)=>y1(J.key,J.version,"policy"))]);return{confidence:A[0]?.score===100?"exact":(A[0]?.score??0)>=70?"high":A.length>0?"medium":"none",contracts:G,path:j,policies:z,reasons:A.map((J)=>`${J.spec.key??J.spec.filePath} matched with score ${J.score}`),surfaces:e$([j])}}async function UZ($,W,j){let Q=_Z($.fs,W,j),Z=await Promise.all(Q.map(async(B)=>{let X=$.fs.resolve(W.packageRoot,B.comparisonRoot),Y=await d0({...$,logger:$.logger??B4},W.workspaceRoot,X,{generation:{scanAllSpecs:!0,specSearchRoot:W.workspaceRoot},rootPath:W.workspaceRoot}),q=B.filterPrefix&&B.filterPrefix!==B.comparisonRoot?i($.fs.relative(B.comparisonRoot,B.filterPrefix)):void 0;return Y.files.filter((A)=>q?i(A)===q||i(A).startsWith(`${q}/`):!0).map((A)=>i($.fs.join(B.comparisonRoot,A)))}));return[...new Set(Z.flat())].sort()}function _Z($,W,j){let Q=(W.config.connect?.policy?.generatedPaths??[]).map(OZ).filter(Boolean),Z=W.config.outputDir&&W.config.outputDir!=="./src"?i(W.config.outputDir):void 0,B=new Map;for(let X of j){let Y=i(X);if(Z&&Y.startsWith(Z))B.set(Z,{comparisonRoot:Z});for(let q of Q)if(Y.startsWith(q)){let A=LZ($,Z,q);B.set(`${A}::${q}`,{comparisonRoot:A,filterPrefix:q})}}return[...B.values()]}function LZ($,W,j){if(W&&j.startsWith(W))return W;return $.basename(j)==="docs"?i($.dirname(j)):j}function IZ($,W,j,Q){if(i($)===i(j))return 100;let Z=P1(j),B=P1(Q??""),X=Z4($)===Z4(j)?40:0,Y=v1($.split("/"),j.split("/"),5),q=v1(W,Z,5),A=v1(W,B,4);return X+Y+q+A}function v1($,W,j){let Q=new Set(W);return $.filter((Z)=>Q.has(Z)).length*j}function P1($){return i($).split(/[\/._-]+/).filter(Boolean)}function Z4($){return i($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function OZ($){return i($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function i($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function y1($,W,j){return{key:$,version:String(W??"1.0.0"),kind:j==="query"||j==="event"||j==="policy"||j==="capability"?j:"command"}}function m1($){return[...new Map($.map((W)=>[`${W.key}@${W.version}`,W])).values()]}var B4={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function k1($,W){let j=f(W);p(j),j=S$(j,await $.git.currentBranch());let Q=s$(W.taskId,W.actor),Z=await wZ($,j.workspaceRoot,W),B=await E$($,{baseline:W.baseline,touchedPaths:Z,workspace:j}),X=j.config.connect?.canonPacks??[];return{id:`connect.ctx_${bZ()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:Q,knowledge:X.map((Y)=>({spaceKey:Y.ref,category:"canonical",trustLevel:Y.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:B.impactedContracts,affectedSurfaces:B.pathImpacts.length>0?[...new Set(B.pathImpacts.flatMap((Y)=>Y.surfaces))].sort():e$(Z),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...X.map((Y)=>({key:Y.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...X.map((Y)=>({kind:"canon-pack",ref:Y.ref}))],acceptanceChecks:j.config.connect?.policy?.smokeChecks??[]}}async function wZ($,W,j){let Q=j.paths??[];if(Q.length>0)return Q.map((B)=>X4($.fs,W,B));if(!j.baseline)return[];return(await $.git.diffFiles(j.baseline)).map((B)=>X4($.fs,W,B))}function X4($,W,j){let Q=$.resolve(W,j);return $.relative(W,Q).replaceAll("\\","/")}import{resolve as M$}from"node:path";function $$($){let W=$.config.connect?.storage,j=M$($.packageRoot,W?.root??".contractspec/connect");return{root:j,contextPack:M$($.packageRoot,W?.contextPack??".contractspec/connect/context-pack.json"),planPacket:M$($.packageRoot,W?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:M$($.packageRoot,W?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:M$($.packageRoot,W?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:M$($.packageRoot,W?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:M$(j,"decisions")}}async function $0($,W){await $.mkdir(W.root),await $.mkdir(W.reviewPacketsDir),await $.mkdir(W.decisionsDir)}async function g1($,W,j){if(j.contextPack)await e($,W.contextPack,j.contextPack);if(j.planPacket)await e($,W.planPacket,j.planPacket);if(j.patchVerdict)await e($,W.patchVerdict,j.patchVerdict)}async function W0($,W,j,Q){let Z=$.join(W.decisionsDir,j);if(await $.mkdir(Z),Q.contextPack)await e($,$.join(Z,"context-pack.json"),Q.contextPack);if(Q.planPacket)await e($,$.join(Z,"plan-packet.json"),Q.planPacket);if(Q.patchVerdict)await e($,$.join(Z,"patch-verdict.json"),Q.patchVerdict);if(Q.reviewPacket)await e($,$.join(Z,"review-packet.json"),Q.reviewPacket);if(Q.evaluationResult!==void 0)await e($,$.join(Z,"evaluation-result.json"),Q.evaluationResult);if(Q.replayBundle!==void 0)await e($,$.join(Z,"replay-bundle.json"),Q.replayBundle);return Z}async function j0($,W,j,Q){let Z=$.join(W.decisionsDir,j,"decision-envelope.json");return await e($,Z,Q),Z}async function h1($,W,j){let Q=await Y4($,W.auditFile)??"",Z=`${JSON.stringify(j)}
|
|
684
|
-
`;await $.writeFile(W.auditFile,`${Q}${Z}`)}async function f1($,W,j){let Q=$.join(W.reviewPacketsDir,`${j.id}.json`);return await e($,Q,j),Q}async function Q0($,W,j){let Q=$.join(W.decisionsDir,j);return{historyDir:Q,contextPack:await y$($,$.join(Q,"context-pack.json")),planPacket:await y$($,$.join(Q,"plan-packet.json")),patchVerdict:await y$($,$.join(Q,"patch-verdict.json")),reviewPacket:await y$($,$.join(Q,"review-packet.json")),envelope:await y$($,$.join(Q,"decision-envelope.json"))}}async function u1($,W){let j=await $.glob({pattern:"*.json",cwd:W.reviewPacketsDir,absolute:!0}),Q=[];for(let Z of j){let B=await y$($,Z);if(B)Q.push({filePath:Z,packet:B})}return Q.sort((Z,B)=>Z.packet.id.localeCompare(B.packet.id))}function X$($,W,j){return $.relative(W.packageRoot,$.resolve(j)).replaceAll("\\","/")}function P$($,W,j,Q,Z){let B=$.join(j.decisionsDir,Q);return{contextPack:X$($,W,$.join(B,"context-pack.json")),planPacket:X$($,W,$.join(B,"plan-packet.json")),patchVerdict:X$($,W,$.join(B,"patch-verdict.json")),reviewPacket:Z.reviewPacket?X$($,W,$.join(B,"review-packet.json")):void 0,evaluationResult:Z.evaluationResult?X$($,W,$.join(B,"evaluation-result.json")):void 0,replayBundle:Z.replayBundle?X$($,W,$.join(B,"replay-bundle.json")):void 0}}async function e($,W,j){await $.writeFile(W,`${JSON.stringify(j,null,2)}
|
|
685
|
-
`)}async function y$($,W){let j=await Y4($,W);if(!j)return;try{return JSON.parse(j)}catch{return}}async function Y4($,W){if(!await $.exists(W))return;try{return await $.readFile(W)}catch{return}}async function CZ($,W,j){let Q=f(W);if(p(Q),!W.scenarioKey&&!W.suiteKey||W.scenarioKey&&W.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let Z=$$(Q),B=await Q0($.fs,Z,W.decisionId),X=SZ(Q,B),Y=W.scenarioKey?await j.runScenarioEvaluation({scenarioKey:W.scenarioKey,version:W.version,context:X}):await j.runSuiteEvaluation({suiteKey:W.suiteKey??"",version:W.version,context:X}),q=await W0($.fs,Z,W.decisionId,{evaluationResult:Y}),A=await $.fs.exists($.fs.join(q,"replay-bundle.json")),H={artifacts:P$($.fs,Q,Z,W.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:A,reviewPacket:Boolean(B.reviewPacket)}),connectDecisionId:W.decisionId,createdAt:B.envelope?.createdAt??new Date().toISOString(),runtimeLink:B.envelope?.runtimeLink,taskId:B.contextPack?.taskId??W.decisionId,verdict:B.patchVerdict?.verdict??"permit"};return await j0($.fs,Z,W.decisionId,H),{historyDir:q,evaluation:Y,context:X}}function SZ($,W){return{traceId:W.envelope?.runtimeLink?.traceId??W.patchVerdict?.controlPlane.traceId??W.contextPack?.actor.traceId,actorId:W.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:W.envelope?.runtimeLink?.decisionId,controlPlanePlanId:W.envelope?.runtimeLink?.planId??W.planPacket?.id,metadata:{approvalStatus:W.envelope?.runtimeLink?.approvalStatus,decisionId:W.patchVerdict?.decisionId,taskId:W.contextPack?.taskId,branch:W.contextPack?.branch??$.branch}}}function EZ($){return $}import{DEFAULT_CONTRACTSRC as MZ}from"@contractspec/lib.contracts-spec/workspace-config";async function NZ($,W={}){let j=f(W),Q=W.scope==="package"?j.packageRoot:j.workspaceRoot,Z=$.join(Q,".contractsrc.json"),B={connect:{...MZ.connect,enabled:!0}},X="created";if(await $.exists(Z)){let q=j$(await $.readFile(Z)),A=r(q??{},B);if(q?.connect&&typeof q.connect==="object")A.connect.enabled=!0;await $.writeFile(Z,D(A)),X="merged"}else await $.writeFile(Z,D(B));let Y=$$(f({...W,workspaceRoot:Q,packageRoot:Q}));return await $0($,Y),{configPath:Z,targetRoot:Q,action:X}}import{randomUUID as s0}from"crypto";async function d1($,W){let j=f(W);p(j),j=S$(j,await $.git.currentBranch());let{commands:Q,touchedPaths:Z}=RZ(W.candidate),B=await k1($,{...W,paths:Z}),X=s$(W.taskId,W.actor),Y=DZ(W.candidate.steps,W.candidate),q=await E$($,{baseline:W.baseline,touchedPaths:Z,workspace:j}),A=t$(j,{commands:Q,impactAnalysis:q,touchedPaths:Z}),H={id:`connect.plan_${s0()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:B.impactedContracts,affectedSurfaces:B.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:A.requiredApprovals,riskScore:FZ(Z.length,Q.length),verificationStatus:A.verificationStatus,controlPlane:{intentSubmit:R1,planCompile:D1,planVerify:F1,traceId:X.traceId},acpActions:[...Z.length>0?["acp.fs.access"]:[],...Q.length>0?["acp.terminal.exec"]:[]]};return{contextPack:B,planPacket:H}}function RZ($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let Q of $.steps??[]){if(typeof Q==="string")continue;for(let Z of Q.paths??[])W.add(Z);for(let Z of Q.commands??[])j.add(Z)}return{commands:[...j],touchedPaths:[...W]}}function DZ($,W){if(!$||$.length===0)return[{id:`step_${s0()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${s0()}`,summary:j}:{id:`step_${s0()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function FZ($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function xZ($,W,j){let Q=f(W);p(Q);let Z=$$(Q),B=await Q0($.fs,Z,W.decisionId),X={decisionId:B.envelope?.runtimeLink?.decisionId,traceId:B.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,q=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:B.historyDir,contextPack:B.contextPack,planPacket:B.planPacket,patchVerdict:B.patchVerdict,reviewPacket:B.reviewPacket,trace:Y??void 0,replay:q??void 0,source:Y?"local+control-plane":"local"}}async function TZ($,W={}){let j=f(W);return p(j),u1($.fs,$$(j))}import{buildChannelPlanTrace as vZ,compileChannelPlan as yZ,finalizeChannelPlan as PZ,replayExecutionTrace as mZ,resolveChannelExecutionActor as kZ}from"@contractspec/integration.runtime/channel";import{createHash as gZ}from"crypto";var Z0="connect.local",hZ="connect.runtime-link.v1",fZ="connect.adapter.v1",uZ="connect-control-plane-bridge";function dZ($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:Q,patchVerdict:Z,planPacket:B,workspace:X})=>{let Y=new Date(j),q=JSON.stringify({connectDecisionId:W,objective:B.objective,taskId:B.taskId,tool:Q.tool,verdict:Z.verdict}),A={workspaceId:X.repoId,providerKey:Z0,externalEventId:W,eventType:Q.tool==="acp.fs.access"?`connect.fs.${Q.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Z.controlPlane.traceId,thread:{externalThreadId:`connect:${B.taskId}`,externalUserId:B.actor.id},message:{text:rZ(B.objective,Q)},metadata:A4({connectDecisionId:W,connectVerdict:Z.verdict,sessionId:B.actor.sessionId,workflowId:`connect:${B.taskId}`}),rawPayload:q},H=await $.store.claimEventReceipt({workspaceId:A.workspaceId,providerKey:A.providerKey,externalEventId:A.externalEventId,eventType:A.eventType,signatureValid:!0,payloadHash:oZ(q),traceId:A.traceId});if(H.duplicate)return nZ($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:A.workspaceId,providerKey:A.providerKey,externalThreadId:A.thread.externalThreadId,externalUserId:A.thread.externalUserId,occurredAt:Y}),G=kZ(A,{actorId:B.actor.id,actorType:B.actor.type,capabilityGrants:lZ(Z.verdict),capabilitySource:"connect",sessionId:B.actor.sessionId}),z=yZ({event:A,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),J=PZ({plan:z,decision:cZ(Z),approvalTimeoutMs:900000,now:Y}),K=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:J.policy?.verdict??"blocked",riskTier:J.policy?.riskTier??"blocked",confidence:J.policy?.confidence??0.5,modelName:uZ,promptVersion:hZ,policyVersion:fZ,toolTrace:vZ(J),actionPlan:J,requiresApproval:J.approval.required,approvalStatus:J.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:J.approval.required?"pending":"processed",decisionId:K.id,receiptId:H.receiptId,traceId:J.traceId,workspaceId:X.repoId,providerKey:Z0,sessionId:B.actor.sessionId,workflowId:`connect:${B.taskId}`,metadata:A4({connectDecisionId:W,connectVerdict:Z.verdict,tool:Q.tool})}),{approvalStatus:K.approvalStatus,decisionId:K.id,planId:J.id,providerKey:Z0,receiptId:H.receiptId,threadId:V.id,traceId:J.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>q4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await q4($.traceService,W);return j?mZ(j):null}}}async function nZ($,W,j){let Z=(await $.listDecisions({externalEventId:j,limit:1,providerKey:Z0,workspaceId:W}))[0];return Z?{approvalStatus:Z.approvalStatus,decisionId:Z.id,planId:Z.actionPlan.id,providerKey:Z0,receiptId:Z.receiptId,threadId:Z.threadId,traceId:Z.actionPlan.traceId,workspaceId:W}:null}async function q4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function cZ($){let W=v$($.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 lZ($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function rZ($,W){return`${$} [${W.tool}]`}function oZ($){return gZ("sha256").update($).digest("hex")}function A4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as aZ}from"crypto";function H4($){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 pZ}from"crypto";function V4($,W,j){let Q=$?`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:Q}}function G4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",Q=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:Q}}function z4($,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 J4($,W,j,Q,Z,B){let X=B.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${B.runtimeLink.decisionId}`:B.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${B.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${pZ()}`,sourceDecisionId:W,objective:Q.objective,reason:B.reason,summary:{paths:Z,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:Q.requiredChecks},evidence:[{type:"context-pack",ref:B.artifactRefs.contextPack},{type:"plan-packet",ref:B.artifactRefs.planPacket},{type:"patch-verdict",ref:B.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:w$.key,reason:B.reason}],controlPlane:{traceQuery:i0,policyExplain:a0,approvalStatus:B.runtimeLink?.approvalStatus,decisionId:B.runtimeLink?.decisionId,traceId:B.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 n1($,W,j,Q,Z,B,X,Y,q){let A=v$(X);return{decisionId:$,summary:Q.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:Z,checks:B,verdict:X,controlPlane:{verdict:A.controlPlaneVerdict,requiresApproval:A.requiresApproval,approvalStatus:q?.approvalStatus,decisionId:q?.decisionId,traceId:q?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${w$.key}@${w$.version}`,`${t0.key}@${t0.version}`]:void 0,remediation:iZ(X),reviewPacketRef:Y,replay:{traceQuery:i0,policyExplain:a0}}}function iZ($){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 tZ($,W,j={}){let Q=f(W);p(Q),Q=S$(Q,await $.git.currentBranch());let Z=`connect.dec_${aZ()}`,B=(j.now??(()=>new Date))().toISOString(),X=$$(Q);await $0($.fs,X);let{contextPack:Y,planPacket:q}=await d1($,{...W,candidate:sZ(W)}),A=eZ(W),H=await E$($,{baseline:W.baseline,touchedPaths:A,workspace:Q}),V=await $B(j,Q.config.connect?.policy?.smokeChecks??[],Q.workspaceRoot),G=V.some((S)=>S.id.startsWith("smoke:")&&S.status==="fail"),z=t$(Q,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:A}),J=[V4(z.immutablePath,z.protectedPath,z.generatedPath),G4(z.commandState,z.commandMatch),z4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],K=P$($.fs,Q,X,Z,{contextPack:!0,patchVerdict:!0,planPacket:!0}),_=H.pathImpacts.length>0?H.pathImpacts.map((S)=>({file:S.path,contracts:S.contracts,policies:S.policies,surfaces:S.surfaces})):A.map((S)=>({file:S,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),w=n1(Z,W,Y,q,_,J,z.verdict,void 0),b=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Z,createdAt:B,input:W,patchVerdict:w,planPacket:q,workspace:Q}):null,L=b?{...q,controlPlane:{...q.controlPlane,decisionId:b.decisionId,traceId:b.traceId??q.controlPlane.traceId}}:q,I=z.verdict==="require_review"?J4(Q,Z,Y,L,A,{artifactRefs:K,reason:z.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:b}):void 0,U=n1(Z,W,Y,L,_,J,z.verdict,I?X$($.fs,Q,$.fs.join(X.reviewPacketsDir,`${I.id}.json`)):void 0,b);if(await g1($.fs,X,{contextPack:Y,planPacket:L,patchVerdict:U}),I)await f1($.fs,X,I);let O=await W0($.fs,X,Z,{contextPack:Y,planPacket:L,patchVerdict:U,reviewPacket:I}),C={artifacts:P$($.fs,Q,X,Z,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(I)}),connectDecisionId:Z,createdAt:B,runtimeLink:b??void 0,taskId:W.taskId,verdict:z.verdict};return await j0($.fs,X,Z,C),await h1($.fs,X,H4({contextPack:Y,createdAt:B,envelope:C,reviewPacket:I,verifyInput:W,workspace:Q})),{contextPack:Y,planPacket:L,patchVerdict:U,reviewPacket:I,historyDir:O}}function sZ($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function eZ($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function $B($,W,j){if(!$.runCommand)return[];let Q=[];for(let Z of W){let B=await $.runCommand(Z,{cwd:j});Q.push({id:`smoke:${Z}`,status:B.exitCode===0?"pass":"fail",detail:B.exitCode===0?`Passed: ${Z}`:`Failed (${B.exitCode}): ${Z}`})}return Q}WW();var o1={};P(o1,{generateWorkflowSpec:()=>m4,generateWorkflowRunnerTemplate:()=>k4,generateTestTemplate:()=>N4,generateTelemetrySpec:()=>P4,generatePresentationSpec:()=>y4,generateOperationSpec:()=>v4,generateMigrationSpec:()=>T4,generateKnowledgeSpaceSpec:()=>F4,generateIntegrationSpec:()=>D4,generateHandlerTemplate:()=>E4,generateFeatureSpec:()=>S4,generateExperimentSpec:()=>C4,generateEventSpec:()=>w4,generateDataViewSpec:()=>b4,generateComponentTemplate:()=>M4,generateAppBlueprintSpec:()=>O4});var g4={};P(g4,{generateWorkflowSpec:()=>m4,generateWorkflowRunnerTemplate:()=>k4,generateTestTemplate:()=>N4,generateTelemetrySpec:()=>P4,generatePresentationSpec:()=>y4,generateOperationSpec:()=>v4,generateMigrationSpec:()=>T4,generateKnowledgeSpaceSpec:()=>F4,generateIntegrationSpec:()=>D4,generateHandlerTemplate:()=>E4,generateFeatureSpec:()=>S4,generateExperimentSpec:()=>C4,generateEventSpec:()=>w4,generateDataViewSpec:()=>b4,generateComponentTemplate:()=>M4,generateAppBlueprintSpec:()=>O4});function O4($){let W=LB($.name.split(".").pop()??"App")+"AppConfig",j=HB($),Q=VB($),Z=_4("dataViews",$.dataViews),B=_4("workflows",$.workflows),X=GB($),Y=zB($),q=JB($),A=KB($),H=UB($),V=_B($),G=$.notes?` notes: '${N($.notes)}',
|
|
517
|
+
`)}parseOutput($){let W=$.match(/```(?:typescript|ts|tsx|javascript|js|python|go|rust)?\n([\s\S]*?)\n```/);if(W?.[1])return{code:W[1]};try{let j=JSON.parse($);if(typeof j.code==="string")return{code:j.code};if(typeof j.errors==="object")return{errors:Array.isArray(j.errors)?j.errors:[String(j.errors)]}}catch{}return{code:$}}}var l0=new r0;var b1={"claude-code":d0,"cursor-cli":c0,"generic-mcp":l0};function $0($){let W=b1[$];if(!W)throw Error(`Unknown agent type: ${$}`);return W}function w1(){return Object.keys(b1)}import{featureToMarkdown as K1,generateImplementationPlan as f5,operationSpecToAgentPrompt as mQ,operationSpecToFullMarkdown as PQ}from"@contractspec/lib.contracts-spec/llm";var kQ={defaultAgent:"generic-mcp",verbose:!1};class o0{config;constructor($={}){this.config={...kQ,...$}}generateGuide($,W={}){let j=W.agent??this.config.defaultAgent,A=$0(j),Q=f5($,{projectRoot:this.config.projectRoot,existingFiles:W.targetPath?[W.targetPath]:void 0}),Z=A.formatPlan(Q),X=PQ($);return{plan:Q,prompt:Z,markdown:X}}generateFeatureGuide($,W,j={}){let A=j.agent??this.config.defaultAgent,Q=$0(A),Z=$.operations?.[0],X=Z?W.specs?.get(Z.key,Z.version):void 0,Y;if(X)Y=f5(X,{projectRoot:this.config.projectRoot}),Y.target={type:"feature",key:$.meta.key,version:"1.0.0"},Y.context.goal=$.meta.description??Y.context.goal;else Y={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:K1($,W),fileStructure:[],steps:[{order:1,title:"Implement Feature",description:`Implement the ${$.meta.key} feature`,acceptanceCriteria:[]}],constraints:{policy:[],security:[],pii:[]},verificationChecklist:[]};if(Y.specMarkdown=K1($,W,{format:"full",includeRelatedSpecs:!0,includeRelatedEvents:!0,includeRelatedPresentations:!0}),$.operations?.length)Y.steps=$.operations.map((H,V)=>({order:V+1,title:`Implement ${H.key}`,description:`Implement operation ${H.key}.v${H.version}`,acceptanceCriteria:[`Operation ${H.key} works as specified`]}));let B=Q.formatPlan(Y),q=K1($,W);return{plan:Y,prompt:B,markdown:q}}generateAgentConfig($,W){return $0(W??this.config.defaultAgent).generateConfig?.($)}exportForAgent($,W,j="implement",A){return mQ($,{taskType:j,existingCode:A})}listAgentTypes(){return w1()}getDefaultAgent(){return this.config.defaultAgent}configure($){this.config={...this.config,...$}}}function hQ($){return new o0($)}var gQ=new o0;import{detectAuthoringTarget as RZ,generateComponentTemplate as CZ,generateHandlerTemplate as DZ,generateTestTemplate as TZ,getAuthoringTargetDefinition as FZ,inferSpecTypeFromFilePath as xZ,scanSpecSource as yZ}from"@contractspec/module.workspace";var B8={};h(B8,{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});function c5($){let W=iQ($.name.split(".").pop()??"App")+"AppConfig",j=fQ($),A=uQ($),Q=u5("dataViews",$.dataViews),Z=u5("workflows",$.workflows),X=dQ($),Y=nQ($),B=cQ($),q=rQ($),H=lQ($),V=oQ($),G=$.notes?` notes: '${T($.notes)}',
|
|
686
518
|
`:"";return`import type { AppBlueprintSpec } from '@contractspec/lib.contracts-spec/app-config';
|
|
687
519
|
|
|
688
520
|
export const ${W}: AppBlueprintSpec = {
|
|
689
521
|
meta: {
|
|
690
|
-
key: '${
|
|
522
|
+
key: '${T($.name)}',
|
|
691
523
|
version: ${$.version},
|
|
692
|
-
title: '${
|
|
693
|
-
description: '${
|
|
694
|
-
domain: '${
|
|
695
|
-
owners: [${$.owners.map((
|
|
696
|
-
tags: [${$.tags.map((
|
|
524
|
+
title: '${T($.title)}',
|
|
525
|
+
description: '${T($.description)}',
|
|
526
|
+
domain: '${T($.domain)}',
|
|
527
|
+
owners: [${$.owners.map((J)=>`'${T(J)}'`).join(", ")}],
|
|
528
|
+
tags: [${$.tags.map((J)=>`'${T(J)}'`).join(", ")}],
|
|
697
529
|
stability: '${$.stability}',
|
|
698
|
-
appId: '${
|
|
530
|
+
appId: '${T($.appId)}',
|
|
699
531
|
},
|
|
700
|
-
${j}${
|
|
701
|
-
`}function
|
|
702
|
-
`:"",j=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((
|
|
532
|
+
${j}${A}${Q}${Z}${X}${Y}${B}${q}${H}${V}${G}};
|
|
533
|
+
`}function fQ($){if($.capabilitiesEnabled.length===0&&$.capabilitiesDisabled.length===0)return"";let W=$.capabilitiesEnabled.length>0?` enabled: [${$.capabilitiesEnabled.map((A)=>d5(A)).join(", ")}],
|
|
534
|
+
`:"",j=$.capabilitiesDisabled.length>0?` disabled: [${$.capabilitiesDisabled.map((A)=>d5(A)).join(", ")}],
|
|
703
535
|
`:"";return` capabilities: {
|
|
704
536
|
${W}${j} },
|
|
705
|
-
`}function
|
|
706
|
-
`:"",j=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((
|
|
537
|
+
`}function uQ($){if($.featureIncludes.length===0&&$.featureExcludes.length===0)return"";let W=$.featureIncludes.length>0?` include: [${$.featureIncludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
538
|
+
`:"",j=$.featureExcludes.length>0?` exclude: [${$.featureExcludes.map((A)=>`{ key: '${T(A)}' }`).join(", ")}],
|
|
707
539
|
`:"";return` features: {
|
|
708
540
|
${W}${j} },
|
|
709
|
-
`}function
|
|
710
|
-
name: '${
|
|
711
|
-
${
|
|
541
|
+
`}function u5($,W){if(W.length===0)return"";let j=W.map((A)=>` ${A.slot}: {
|
|
542
|
+
name: '${T(A.name)}',
|
|
543
|
+
${A.version!==void 0?`version: '${A.version}',`:""}
|
|
712
544
|
}`).join(`,
|
|
713
545
|
`);return` ${$}: {
|
|
714
546
|
${j}
|
|
715
547
|
},
|
|
716
|
-
`}function
|
|
548
|
+
`}function dQ($){if($.policyRefs.length===0)return"";return` policies: [
|
|
717
549
|
${$.policyRefs.map((j)=>` {
|
|
718
|
-
name: '${
|
|
550
|
+
name: '${T(j.name)}'${j.version!==void 0?`,
|
|
719
551
|
version: '${j.version}'`:""}
|
|
720
552
|
}`).join(`,
|
|
721
553
|
`)}
|
|
722
554
|
],
|
|
723
|
-
`}function
|
|
724
|
-
`,j=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((
|
|
555
|
+
`}function nQ($){if(!$.theme)return"";let W=` primary: { name: '${T($.theme.name)}', version: '${$.theme.version}' },
|
|
556
|
+
`,j=$.themeFallbacks.length>0?` fallbacks: [${$.themeFallbacks.map((A)=>`{ name: '${T(A.name)}', version: '${A.version}' }`).join(", ")}],
|
|
725
557
|
`:"";return` theme: {
|
|
726
558
|
${W}${j} },
|
|
727
|
-
`}function
|
|
559
|
+
`}function cQ($){if(!$.telemetry)return"";return` telemetry: {
|
|
728
560
|
spec: {
|
|
729
|
-
name: '${
|
|
561
|
+
name: '${T($.telemetry.name)}'${$.telemetry.version!==void 0?`
|
|
730
562
|
version: '${$.telemetry.version}'`:""}
|
|
731
563
|
},
|
|
732
564
|
},
|
|
733
|
-
`}function
|
|
734
|
-
`:"",j=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((
|
|
565
|
+
`}function rQ($){if($.activeExperiments.length===0&&$.pausedExperiments.length===0)return"";let W=$.activeExperiments.length>0?` active: [${$.activeExperiments.map((A)=>n5(A)).join(", ")}],
|
|
566
|
+
`:"",j=$.pausedExperiments.length>0?` paused: [${$.pausedExperiments.map((A)=>n5(A)).join(", ")}],
|
|
735
567
|
`:"";return` experiments: {
|
|
736
568
|
${W}${j} },
|
|
737
|
-
`}function
|
|
569
|
+
`}function lQ($){if($.featureFlags.length===0)return"";return` featureFlags: [
|
|
738
570
|
${$.featureFlags.map((j)=>` {
|
|
739
|
-
key: '${
|
|
571
|
+
key: '${T(j.key)}',
|
|
740
572
|
enabled: ${j.enabled},
|
|
741
|
-
${j.variant?`variant: '${
|
|
742
|
-
${j.description?`description: '${
|
|
573
|
+
${j.variant?`variant: '${T(j.variant)}',`:""}
|
|
574
|
+
${j.description?`description: '${T(j.description)}',`:""}
|
|
743
575
|
}`).join(`,
|
|
744
576
|
`)}
|
|
745
577
|
],
|
|
746
|
-
`}function
|
|
747
|
-
${$.routes.map((j)=>{return` { ${[`path: '${
|
|
578
|
+
`}function oQ($){if($.routes.length===0)return"";return` routes: [
|
|
579
|
+
${$.routes.map((j)=>{return` { ${[`path: '${T(j.path)}'`,j.label?`label: '${T(j.label)}'`:null,j.dataView?`dataView: '${T(j.dataView)}'`:null,j.workflow?`workflow: '${T(j.workflow)}'`:null,j.guardName?`guard: { name: '${T(j.guardName)}'${j.guardVersion!==void 0?`, version: '${j.guardVersion}'`:""} }`:null,j.featureFlag?`featureFlag: '${T(j.featureFlag)}'`:null,j.experimentName?`experiment: { name: '${T(j.experimentName)}'${j.experimentVersion!==void 0?`, version: '${j.experimentVersion}'`:""} }`:null].filter(Boolean).join(", ")} }`}).join(`,
|
|
748
580
|
`)}
|
|
749
581
|
],
|
|
750
|
-
`}function
|
|
751
|
-
key: '${
|
|
752
|
-
label: '${
|
|
753
|
-
dataPath: '${
|
|
754
|
-
${
|
|
755
|
-
${
|
|
756
|
-
${
|
|
582
|
+
`}function d5($){return`{ key: '${T($)}' }`}function n5($){let W=$.version!==void 0?`, version: '${$.version}'`:"";return`{ name: '${T($.name)}'${W} }`}function iQ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function T($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function r5($){let W=pQ($.name.split(".").pop()??"DataView")+"DataView",j=$.fields.map((Z)=>` {
|
|
583
|
+
key: '${Z.key}',
|
|
584
|
+
label: '${i0(Z.label)}',
|
|
585
|
+
dataPath: '${Z.dataPath}',
|
|
586
|
+
${Z.format?`format: '${Z.format}',`:""}
|
|
587
|
+
${Z.sortable?"sortable: true,":""}
|
|
588
|
+
${Z.filterable?"filterable: true,":""}
|
|
757
589
|
}`).join(`,
|
|
758
|
-
`),
|
|
590
|
+
`),A=$.secondaryFields?.length?`secondaryFields: [${$.secondaryFields.map((Z)=>`'${Z}'`).join(", ")}],`:"",Q=$.itemOperation?`item: { name: '${$.itemOperation.name}', version: ${$.itemOperation.version} },`:"";return`import type { DataViewSpec } from '@contractspec/lib.contracts-spec/data-views';
|
|
759
591
|
|
|
760
592
|
export const ${W}: DataViewSpec = {
|
|
761
593
|
meta: {
|
|
762
594
|
key: '${$.name}',
|
|
763
595
|
version: ${$.version},
|
|
764
596
|
entity: '${$.entity}',
|
|
765
|
-
title: '${
|
|
766
|
-
description: '${
|
|
767
|
-
domain: '${
|
|
768
|
-
owners: [${$.owners.map((
|
|
769
|
-
tags: [${$.tags.map((
|
|
597
|
+
title: '${i0($.title)}',
|
|
598
|
+
description: '${i0($.description||"Describe the purpose of this data view.")}',
|
|
599
|
+
domain: '${i0($.domain||$.entity)}',
|
|
600
|
+
owners: [${$.owners.map((Z)=>`'${Z}'`).join(", ")}],
|
|
601
|
+
tags: [${$.tags.map((Z)=>`'${Z}'`).join(", ")}],
|
|
770
602
|
stability: '${$.stability}',
|
|
771
603
|
},
|
|
772
604
|
source: {
|
|
@@ -774,7 +606,7 @@ export const ${W}: DataViewSpec = {
|
|
|
774
606
|
name: '${$.primaryOperation.name}',
|
|
775
607
|
version: ${$.primaryOperation.version},
|
|
776
608
|
},
|
|
777
|
-
${
|
|
609
|
+
${Q}
|
|
778
610
|
refreshEvents: [
|
|
779
611
|
// { name: 'entity.updated', version: '1.0.0' },
|
|
780
612
|
],
|
|
@@ -785,7 +617,7 @@ export const ${W}: DataViewSpec = {
|
|
|
785
617
|
${j}
|
|
786
618
|
],
|
|
787
619
|
${$.primaryField?`primaryField: '${$.primaryField}',`:""}
|
|
788
|
-
${
|
|
620
|
+
${A}
|
|
789
621
|
filters: [
|
|
790
622
|
// Example filter:
|
|
791
623
|
// { key: 'search', label: 'Search', field: 'fullName', type: 'search' },
|
|
@@ -800,12 +632,51 @@ ${j}
|
|
|
800
632
|
// error: { name: 'app.data.error', version: '1.0.0' },
|
|
801
633
|
},
|
|
802
634
|
};
|
|
803
|
-
`}function
|
|
635
|
+
`}function pQ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function i0($){return $.replace(/'/g,"\\'")}function p0({exportName:$,specImportPath:W,rendererName:j,viewKind:A}){return`'use client';
|
|
636
|
+
|
|
637
|
+
import * as React from 'react';
|
|
638
|
+
import { DataViewRenderer } from '@contractspec/lib.design-system';
|
|
639
|
+
import { ${$} } from '${W}';
|
|
640
|
+
|
|
641
|
+
export interface ${j}Props {
|
|
642
|
+
items?: Record<string, unknown>[];
|
|
643
|
+
item?: Record<string, unknown> | null;
|
|
644
|
+
className?: string;
|
|
645
|
+
renderActions?: (item: Record<string, unknown>) => React.ReactNode;
|
|
646
|
+
onSelect?: (item: Record<string, unknown>) => void;
|
|
647
|
+
onRowClick?: (item: Record<string, unknown>) => void;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* Auto-generated renderer for the "${A}" data view.
|
|
652
|
+
* Customize as needed for app-specific behaviour.
|
|
653
|
+
*/
|
|
654
|
+
export function ${j}({
|
|
655
|
+
items = [],
|
|
656
|
+
item = null,
|
|
657
|
+
className,
|
|
658
|
+
renderActions,
|
|
659
|
+
onSelect,
|
|
660
|
+
onRowClick,
|
|
661
|
+
}: ${j}Props) {
|
|
662
|
+
return (
|
|
663
|
+
<DataViewRenderer
|
|
664
|
+
spec={${$}}
|
|
665
|
+
items={items}
|
|
666
|
+
item={item}
|
|
667
|
+
className={className}
|
|
668
|
+
renderActions={renderActions}
|
|
669
|
+
onSelect={onSelect}
|
|
670
|
+
onRowClick={onRowClick}
|
|
671
|
+
/>
|
|
672
|
+
);
|
|
673
|
+
}
|
|
674
|
+
`}function l5($){let{name:W,version:j,description:A,stability:Q,owners:Z,tags:X,piiFields:Y}=$,B=tQ(W.replace(/\./g,"_"))+"V"+j,q=B+"Payload";return`import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
804
675
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
805
676
|
|
|
806
677
|
// TODO: Define event payload schema
|
|
807
|
-
export const ${
|
|
808
|
-
name: '${
|
|
678
|
+
export const ${q} = new SchemaModel({
|
|
679
|
+
name: '${q}',
|
|
809
680
|
description: 'Payload for ${W}',
|
|
810
681
|
fields: {
|
|
811
682
|
// Add your payload fields here
|
|
@@ -813,80 +684,80 @@ export const ${A} = new SchemaModel({
|
|
|
813
684
|
},
|
|
814
685
|
});
|
|
815
686
|
|
|
816
|
-
export const ${
|
|
687
|
+
export const ${B} = defineEvent({
|
|
817
688
|
name: '${W}',
|
|
818
689
|
name: '${W}',
|
|
819
690
|
version: '${j}',
|
|
820
|
-
description: '${
|
|
821
|
-
description: '${
|
|
822
|
-
stability: '${
|
|
823
|
-
owners: [${
|
|
691
|
+
description: '${A}',
|
|
692
|
+
description: '${A}',
|
|
693
|
+
stability: '${Q}',
|
|
694
|
+
owners: [${Z.map((H)=>`'${H}'`).join(", ")}],
|
|
824
695
|
tags: [${X.map((H)=>`'${H}'`).join(", ")}],
|
|
825
696
|
${Y.length>0?`pii: [${Y.map((H)=>`'${H}'`).join(", ")}],`:"// pii: [],"}
|
|
826
|
-
payload: ${
|
|
697
|
+
payload: ${q},
|
|
827
698
|
});
|
|
828
|
-
`}function
|
|
829
|
-
${
|
|
699
|
+
`}function tQ($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function o5($){let W=sQ($.name.split(".").pop()??"Experiment")+"Experiment",j=$.variants.map((Z)=>{let X=Z.overrides?.length?` overrides: [
|
|
700
|
+
${Z.overrides.map((Y)=>` {
|
|
830
701
|
type: '${Y.type}',
|
|
831
|
-
target: '${
|
|
702
|
+
target: '${P(Y.target)}',
|
|
832
703
|
${typeof Y.version==="string"?`version: ${Y.version},`:""}
|
|
833
704
|
}`).join(`,
|
|
834
705
|
`)}
|
|
835
706
|
],`:"";return` {
|
|
836
|
-
id: '${
|
|
837
|
-
name: '${
|
|
838
|
-
${
|
|
839
|
-
${typeof
|
|
707
|
+
id: '${P(Z.id)}',
|
|
708
|
+
name: '${P(Z.name)}',
|
|
709
|
+
${Z.description?`description: '${P(Z.description)}',`:""}
|
|
710
|
+
${typeof Z.weight==="number"?`weight: ${Z.weight},`:""}
|
|
840
711
|
${X}
|
|
841
712
|
}`}).join(`,
|
|
842
|
-
`),
|
|
843
|
-
${$.successMetrics.map((
|
|
844
|
-
name: '${
|
|
845
|
-
telemetryEvent: { name: '${
|
|
846
|
-
aggregation: '${
|
|
847
|
-
${typeof
|
|
713
|
+
`),A=aQ($.allocation),Q=$.successMetrics?.length?` successMetrics: [
|
|
714
|
+
${$.successMetrics.map((Z)=>` {
|
|
715
|
+
name: '${P(Z.name)}',
|
|
716
|
+
telemetryEvent: { name: '${P(Z.eventName)}', version: ${typeof Z.eventVersion==="string"?`'${Z.eventVersion}'`:Z.eventVersion} },
|
|
717
|
+
aggregation: '${Z.aggregation}',
|
|
718
|
+
${typeof Z.target==="number"?`target: ${Z.target},`:""}
|
|
848
719
|
}`).join(`,
|
|
849
720
|
`)}
|
|
850
721
|
],`:"";return`import type { ExperimentSpec } from '@contractspec/lib.contracts-spec/experiments';
|
|
851
722
|
|
|
852
723
|
export const ${W}: ExperimentSpec = {
|
|
853
724
|
meta: {
|
|
854
|
-
key: '${
|
|
725
|
+
key: '${P($.name)}',
|
|
855
726
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
856
|
-
title: '${
|
|
857
|
-
description: '${
|
|
858
|
-
domain: '${
|
|
859
|
-
owners: [${$.owners.map((
|
|
860
|
-
tags: [${$.tags.map((
|
|
727
|
+
title: '${P($.name)} experiment',
|
|
728
|
+
description: '${P($.description||"Describe the experiment goal.")}',
|
|
729
|
+
domain: '${P($.domain)}',
|
|
730
|
+
owners: [${$.owners.map((Z)=>`'${P(Z)}'`).join(", ")}],
|
|
731
|
+
tags: [${$.tags.map((Z)=>`'${P(Z)}'`).join(", ")}],
|
|
861
732
|
stability: '${$.stability}',
|
|
862
733
|
},
|
|
863
|
-
controlVariant: '${
|
|
734
|
+
controlVariant: '${P($.controlVariant)}',
|
|
864
735
|
variants: [
|
|
865
736
|
${j}
|
|
866
737
|
],
|
|
867
|
-
allocation: ${
|
|
868
|
-
${
|
|
738
|
+
allocation: ${A},
|
|
739
|
+
${Q}
|
|
869
740
|
};
|
|
870
|
-
`}function
|
|
741
|
+
`}function aQ($){switch($.type){case"random":return`{
|
|
871
742
|
type: 'random',
|
|
872
|
-
${$.salt?`salt: '${
|
|
743
|
+
${$.salt?`salt: '${P($.salt)}',`:""}
|
|
873
744
|
}`;case"sticky":return`{
|
|
874
745
|
type: 'sticky',
|
|
875
746
|
attribute: '${$.attribute}',
|
|
876
|
-
${$.salt?`salt: '${
|
|
747
|
+
${$.salt?`salt: '${P($.salt)}',`:""}
|
|
877
748
|
}`;case"targeted":return`{
|
|
878
749
|
type: 'targeted',
|
|
879
750
|
rules: [
|
|
880
751
|
${$.rules.map((W)=>` {
|
|
881
|
-
variantId: '${
|
|
752
|
+
variantId: '${P(W.variantId)}',
|
|
882
753
|
${typeof W.percentage==="number"?`percentage: ${W.percentage},`:""}
|
|
883
|
-
${W.policy?`policy: { name: '${
|
|
884
|
-
${W.expression?`expression: '${
|
|
754
|
+
${W.policy?`policy: { name: '${P(W.policy.name)}'${W.policy.version!==void 0?`, version: ${typeof W.policy.version==="string"?`'${W.policy.version}'`:W.policy.version}`:""} },`:""}
|
|
755
|
+
${W.expression?`expression: '${P(W.expression)}',`:""}
|
|
885
756
|
}`).join(`,
|
|
886
757
|
`)}
|
|
887
758
|
],
|
|
888
759
|
fallback: '${$.fallback??"control"}',
|
|
889
|
-
}`;default:return
|
|
760
|
+
}`;default:return eQ($)}}function sQ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function P($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function eQ($){throw Error(`Unsupported allocation type ${$}`)}function $Z($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function i5($){let W=(j)=>j.map((A)=>` { key: '${A.key}', version: '${A.version}' },`).join(`
|
|
890
761
|
`);return`/**
|
|
891
762
|
* ${$.title} Feature
|
|
892
763
|
*
|
|
@@ -895,13 +766,17 @@ ${$.rules.map((W)=>` {
|
|
|
895
766
|
|
|
896
767
|
import { defineFeature } from '@contractspec/lib.contracts-spec';
|
|
897
768
|
|
|
898
|
-
export const ${
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
769
|
+
export const ${$Z($.key)}Feature = defineFeature({
|
|
770
|
+
meta: {
|
|
771
|
+
key: '${$.key}',
|
|
772
|
+
version: '${$.version}',
|
|
773
|
+
title: '${$.title}',
|
|
774
|
+
description: '${$.description||"TODO: Add description"}',
|
|
775
|
+
domain: '${$.domain}',
|
|
776
|
+
owners: [${$.owners.map((j)=>`'${j}'`).join(", ")}],
|
|
777
|
+
tags: [${$.tags.map((j)=>`'${j}'`).join(", ")}],
|
|
778
|
+
stability: '${$.stability||"beta"}',
|
|
779
|
+
},
|
|
905
780
|
|
|
906
781
|
operations: [
|
|
907
782
|
${W($.operations)||" // Add operations here"}
|
|
@@ -918,19 +793,70 @@ ${W($.presentations)||" // Add presentations here"}
|
|
|
918
793
|
experiments: [
|
|
919
794
|
${W($.experiments)||" // Add experiments here"}
|
|
920
795
|
],
|
|
796
|
+
});
|
|
797
|
+
`}function WZ($){return $.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function p5($){let W=WZ($.key),j=`${W}FormModel`,A=`${W}Form`;return`/**
|
|
798
|
+
* ${$.title} Form
|
|
799
|
+
*
|
|
800
|
+
* Auto-generated form spec.
|
|
801
|
+
*/
|
|
921
802
|
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
803
|
+
import { defineFormSpec } from '@contractspec/lib.contracts-spec/forms';
|
|
804
|
+
import { ScalarTypeEnum, defineSchemaModel } from '@contractspec/lib.schema';
|
|
805
|
+
|
|
806
|
+
const ${j} = defineSchemaModel({
|
|
807
|
+
name: '${j}',
|
|
808
|
+
description: '${$.description||"TODO: Add form model description"}',
|
|
809
|
+
fields: {
|
|
810
|
+
${$.primaryFieldKey}: {
|
|
811
|
+
type: ScalarTypeEnum.String_unsecure(),
|
|
812
|
+
isOptional: false,
|
|
813
|
+
},
|
|
814
|
+
},
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
export const ${A} = defineFormSpec({
|
|
818
|
+
meta: {
|
|
819
|
+
key: '${$.key}',
|
|
820
|
+
version: '${$.version}',
|
|
821
|
+
title: '${$.title}',
|
|
822
|
+
description: '${$.description||"TODO: Add description"}',
|
|
823
|
+
domain: '${$.domain}',
|
|
824
|
+
owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
|
|
825
|
+
tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
|
|
826
|
+
stability: '${$.stability||"beta"}',
|
|
827
|
+
},
|
|
828
|
+
model: ${j},
|
|
829
|
+
fields: [
|
|
830
|
+
{
|
|
831
|
+
kind: 'text',
|
|
832
|
+
name: '${$.primaryFieldKey}',
|
|
833
|
+
labelI18n: '${$.primaryFieldLabel}',
|
|
834
|
+
placeholderI18n: '${$.primaryFieldPlaceholder||"TODO.placeholder"}',
|
|
835
|
+
required: true,
|
|
836
|
+
},
|
|
837
|
+
],
|
|
838
|
+
actions: [
|
|
839
|
+
{
|
|
840
|
+
key: '${$.actionKey}',
|
|
841
|
+
labelI18n: '${$.actionLabel}',
|
|
842
|
+
},
|
|
843
|
+
],
|
|
844
|
+
policy: {
|
|
845
|
+
flags: [],
|
|
846
|
+
pii: [],
|
|
847
|
+
},
|
|
848
|
+
renderHints: {
|
|
849
|
+
ui: 'custom',
|
|
850
|
+
form: 'react-hook-form',
|
|
925
851
|
},
|
|
926
852
|
});
|
|
927
|
-
`}function
|
|
928
|
-
import { ${
|
|
853
|
+
`}function t5($,W){let j=jZ($.split(".").pop()||"unknown")+"Handler",A=t0($.split(".").pop()||"Unknown")+"Spec";return`import type { ContractHandler } from '@contractspec/lib.contracts-spec';
|
|
854
|
+
import { ${A} } from '../contracts/${e5($)}.contracts';
|
|
929
855
|
|
|
930
856
|
/**
|
|
931
857
|
* Handler for ${$}
|
|
932
858
|
*/
|
|
933
|
-
export const ${j}: ContractHandler<typeof ${
|
|
859
|
+
export const ${j}: ContractHandler<typeof ${A}> = async (
|
|
934
860
|
input,
|
|
935
861
|
context
|
|
936
862
|
) => {
|
|
@@ -950,7 +876,7 @@ export const ${j}: ContractHandler<typeof ${Q}> = async (
|
|
|
950
876
|
throw error;
|
|
951
877
|
}
|
|
952
878
|
};
|
|
953
|
-
`}function
|
|
879
|
+
`}function a5($,W){let j=t0($);return`import React from 'react';
|
|
954
880
|
|
|
955
881
|
interface ${j}Props {
|
|
956
882
|
// TODO: Define props based on presentation spec
|
|
@@ -967,10 +893,10 @@ export const ${j}: React.FC<${j}Props> = (props) => {
|
|
|
967
893
|
</div>
|
|
968
894
|
);
|
|
969
895
|
};
|
|
970
|
-
`}function
|
|
971
|
-
import { ${
|
|
896
|
+
`}function s5($,W){let j=W==="handler"?"../handlers":"../components",A=t0($);return`import { describe, it, expect } from 'bun:test';
|
|
897
|
+
import { ${A} } from '${j}/${e5($)}';
|
|
972
898
|
|
|
973
|
-
describe('${
|
|
899
|
+
describe('${A}', () => {
|
|
974
900
|
it('should ${W==="handler"?"handle valid input":"render correctly"}', async () => {
|
|
975
901
|
// TODO: Implement test
|
|
976
902
|
expect(true).toBe(true);
|
|
@@ -986,12 +912,12 @@ describe('${Q}', () => {
|
|
|
986
912
|
// TODO: Test accessibility
|
|
987
913
|
});`}
|
|
988
914
|
});
|
|
989
|
-
`}function
|
|
915
|
+
`}function jZ($){let W=t0($);return W.charAt(0).toLowerCase()+W.slice(1)}function t0($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function e5($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function $8($){let W=VZ($.name.split(".").pop()??"Integration"),j=`${W}IntegrationSpec`,A=`register${W}Integration`,Q=$.supportedModes.length?$.supportedModes:["managed"],Z=Q.map((w)=>`'${w}'`).join(", "),X=$.capabilitiesProvided.map((w)=>` { key: '${w.key}', version: '${w.version}' }`).join(`,
|
|
990
916
|
`),Y=$.capabilitiesRequired.length>0?` requires: [
|
|
991
|
-
${$.capabilitiesRequired.map((
|
|
917
|
+
${$.capabilitiesRequired.map((w)=>{let L=w.version!==void 0?`, version: '${w.version}'`:"",z=w.optional?", optional: true":"",S=w.reason?`, reason: '${e(w.reason)}'`:"";return` { key: '${w.key}'${L}${z}${S} }`}).join(`,
|
|
992
918
|
`)}
|
|
993
|
-
],`:"",
|
|
994
|
-
`:"",
|
|
919
|
+
],`:"",B=AZ($.configFields),q=ZZ($.configFields),H=QZ($.secretFields),V=XZ($.secretFields),G=$.docsUrl?` docsUrl: '${e($.docsUrl)}',
|
|
920
|
+
`:"",J=YZ($.rateLimitRpm,$.rateLimitRph),b=BZ(Q,$.byokSetupInstructions,$.byokRequiredScopes);return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
995
921
|
import type { IntegrationSpec } from '@contractspec/lib.contracts-integrations';
|
|
996
922
|
import type { IntegrationSpecRegistry } from '@contractspec/lib.contracts-integrations';
|
|
997
923
|
|
|
@@ -1000,15 +926,15 @@ export const ${j}: IntegrationSpec = {
|
|
|
1000
926
|
key: '${$.name}',
|
|
1001
927
|
version: ${typeof $.version==="string"?`'${$.version}'`:$.version},
|
|
1002
928
|
category: '${$.category}',
|
|
1003
|
-
displayName: '${
|
|
1004
|
-
title: '${
|
|
1005
|
-
description: '${
|
|
1006
|
-
domain: '${
|
|
1007
|
-
owners: [${$.owners.map((
|
|
1008
|
-
tags: [${$.tags.map((
|
|
1009
|
-
stability: StabilityEnum.${
|
|
929
|
+
displayName: '${e($.displayName)}',
|
|
930
|
+
title: '${e($.title)}',
|
|
931
|
+
description: '${e($.description)}',
|
|
932
|
+
domain: '${e($.domain)}',
|
|
933
|
+
owners: [${$.owners.map((w)=>`'${e(w)}'`).join(", ")}],
|
|
934
|
+
tags: [${$.tags.map((w)=>`'${e(w)}'`).join(", ")}],
|
|
935
|
+
stability: StabilityEnum.${HZ($.stability)},
|
|
1010
936
|
},
|
|
1011
|
-
supportedModes: [${
|
|
937
|
+
supportedModes: [${Z}],
|
|
1012
938
|
capabilities: {
|
|
1013
939
|
provides: [
|
|
1014
940
|
${X}
|
|
@@ -1016,57 +942,57 @@ ${X}
|
|
|
1016
942
|
${Y.length>0?`${Y}
|
|
1017
943
|
`:""} },
|
|
1018
944
|
configSchema: {
|
|
1019
|
-
${
|
|
1020
|
-
example: ${
|
|
945
|
+
${B}
|
|
946
|
+
example: ${q},
|
|
1021
947
|
},
|
|
1022
948
|
secretSchema: {
|
|
1023
949
|
${H}
|
|
1024
950
|
example: ${V},
|
|
1025
951
|
},
|
|
1026
|
-
${G}${
|
|
952
|
+
${G}${J}${b} healthCheck: {
|
|
1027
953
|
method: '${$.healthCheckMethod}',
|
|
1028
954
|
timeoutMs: ${$.healthCheckTimeoutMs},
|
|
1029
955
|
},
|
|
1030
956
|
};
|
|
1031
957
|
|
|
1032
|
-
export function ${
|
|
958
|
+
export function ${A}(
|
|
1033
959
|
registry: IntegrationSpecRegistry
|
|
1034
960
|
): IntegrationSpecRegistry {
|
|
1035
961
|
return registry.register(${j});
|
|
1036
962
|
}
|
|
1037
|
-
`}function
|
|
1038
|
-
`:"",
|
|
963
|
+
`}function AZ($){let W=$.filter((Q)=>Q.required),j=W.length>0?` required: [${W.map((Q)=>`'${Q.key}'`).join(", ")}],
|
|
964
|
+
`:"",A=$.length?$.map((Q)=>{let Z=Q.description?`, description: '${e(Q.description)}'`:"";return` ${Q.key}: { type: '${qZ(Q.type)}'${Z} }`}).join(`,
|
|
1039
965
|
`):"";return` schema: {
|
|
1040
966
|
type: 'object',
|
|
1041
967
|
${j} properties: {
|
|
1042
|
-
${
|
|
968
|
+
${A||" "}
|
|
1043
969
|
},
|
|
1044
970
|
},
|
|
1045
|
-
`}function
|
|
1046
|
-
`:"",
|
|
971
|
+
`}function QZ($){let W=$.filter((Q)=>Q.required),j=W.length>0?` required: [${W.map((Q)=>`'${Q.key}'`).join(", ")}],
|
|
972
|
+
`:"",A=$.length?$.map((Q)=>{let Z=Q.description?`, description: '${e(Q.description)}'`:"";return` ${Q.key}: { type: 'string'${Z} }`}).join(`,
|
|
1047
973
|
`):"";return` schema: {
|
|
1048
974
|
type: 'object',
|
|
1049
975
|
${j} properties: {
|
|
1050
|
-
${
|
|
976
|
+
${A||" "}
|
|
1051
977
|
},
|
|
1052
978
|
},
|
|
1053
|
-
`}function
|
|
979
|
+
`}function ZZ($){if($.length===0)return"{}";return`{
|
|
1054
980
|
${$.map((j)=>{switch(j.type){case"number":return` ${j.key}: 0`;case"boolean":return` ${j.key}: true`;case"string":default:return` ${j.key}: '${j.key.toUpperCase()}_VALUE'`}}).join(`,
|
|
1055
981
|
`)}
|
|
1056
|
-
}`}function
|
|
982
|
+
}`}function XZ($){if($.length===0)return"{}";return`{
|
|
1057
983
|
${$.map((j)=>` ${j.key}: '${j.key.toUpperCase()}_SECRET'`).join(`,
|
|
1058
984
|
`)}
|
|
1059
|
-
}`}function
|
|
985
|
+
}`}function YZ($,W){if($==null&&W==null)return"";let j=[];if($!=null)j.push(` rpm: ${$}`);if(W!=null)j.push(` rph: ${W}`);return` constraints: {
|
|
1060
986
|
rateLimit: {
|
|
1061
987
|
${j.join(`,
|
|
1062
988
|
`)}
|
|
1063
989
|
},
|
|
1064
990
|
},
|
|
1065
|
-
`}function
|
|
1066
|
-
`:"",
|
|
1067
|
-
`:"";if(!Q
|
|
1068
|
-
${
|
|
1069
|
-
`}function
|
|
991
|
+
`}function BZ($,W,j){if(!$.includes("byok"))return"";let A=W?` setupInstructions: '${e(W)}',
|
|
992
|
+
`:"",Q=j&&j.length?` requiredScopes: [${j.map((Z)=>`'${e(Z)}'`).join(", ")}],
|
|
993
|
+
`:"";if(!A&&!Q)return"";return` byokSetup: {
|
|
994
|
+
${A}${Q} },
|
|
995
|
+
`}function qZ($){switch($){case"number":return"number";case"boolean":return"boolean";case"string":default:return"string"}}function HZ($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function VZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function e($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function W8($){let W=KZ($.name.split(".").pop()??"KnowledgeSpace"),j=`${W}KnowledgeSpace`,A=`register${W}KnowledgeSpace`,Q=GZ($),Z=JZ($),X=bZ($),Y=$.policyName&&!$.policyVersion?" // defaults to latest version":"";return`import { StabilityEnum } from '@contractspec/lib.contracts-spec/ownership';
|
|
1070
996
|
import type { KnowledgeSpaceSpec } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1071
997
|
import type { KnowledgeSpaceRegistry } from '@contractspec/lib.contracts-spec/knowledge/spec';
|
|
1072
998
|
|
|
@@ -1075,74 +1001,74 @@ export const ${j}: KnowledgeSpaceSpec = {
|
|
|
1075
1001
|
key: '${$.name}',
|
|
1076
1002
|
version: ${$.version},
|
|
1077
1003
|
category: '${$.category}',
|
|
1078
|
-
displayName: '${
|
|
1079
|
-
title: '${
|
|
1080
|
-
description: '${
|
|
1081
|
-
domain: '${
|
|
1082
|
-
owners: [${$.owners.map((
|
|
1083
|
-
tags: [${$.tags.map((
|
|
1084
|
-
stability: StabilityEnum.${
|
|
1004
|
+
displayName: '${B$($.displayName)}',
|
|
1005
|
+
title: '${B$($.title)}',
|
|
1006
|
+
description: '${B$($.description)}',
|
|
1007
|
+
domain: '${B$($.domain)}',
|
|
1008
|
+
owners: [${$.owners.map((B)=>`'${B$(B)}'`).join(", ")}],
|
|
1009
|
+
tags: [${$.tags.map((B)=>`'${B$(B)}'`).join(", ")}],
|
|
1010
|
+
stability: StabilityEnum.${wZ($.stability)},
|
|
1085
1011
|
},
|
|
1086
|
-
retention: ${
|
|
1012
|
+
retention: ${Q},
|
|
1087
1013
|
access: {
|
|
1088
|
-
${
|
|
1014
|
+
${Z}${$.policyName?` policy: { name: '${$.policyName}',${$.policyVersion?` version: ${$.policyVersion}`:""} },${Y}
|
|
1089
1015
|
`:""} },
|
|
1090
|
-
${X} description: '${
|
|
1016
|
+
${X} description: '${B$($.description||$.displayName)}',
|
|
1091
1017
|
};
|
|
1092
1018
|
|
|
1093
|
-
export function ${
|
|
1019
|
+
export function ${A}(
|
|
1094
1020
|
registry: KnowledgeSpaceRegistry
|
|
1095
1021
|
): KnowledgeSpaceRegistry {
|
|
1096
1022
|
return registry.register(${j});
|
|
1097
1023
|
}
|
|
1098
|
-
`}function
|
|
1024
|
+
`}function GZ($){let W=$.retention.ttlDays===null?"null":typeof $.retention.ttlDays==="number"?String($.retention.ttlDays):"null",j=typeof $.retention.archiveAfterDays==="number"?`, archiveAfterDays: ${$.retention.archiveAfterDays}`:"";return`{ ttlDays: ${W}${j} }`}function JZ($){let W=` trustLevel: '${$.trustLevel}',
|
|
1099
1025
|
`,j=` automationWritable: ${$.automationWritable},
|
|
1100
|
-
`;return`${W}${j}`}function
|
|
1026
|
+
`;return`${W}${j}`}function bZ($){let W=[];if($.embeddingModel)W.push(` embeddingModel: '${B$($.embeddingModel)}'`);if(typeof $.chunkSize==="number")W.push(` chunkSize: ${$.chunkSize}`);if($.vectorDbIntegration)W.push(` vectorDbIntegration: '${B$($.vectorDbIntegration)}'`);if(W.length===0)return"";return` indexing: {
|
|
1101
1027
|
${W.join(`,
|
|
1102
1028
|
`)}
|
|
1103
1029
|
},
|
|
1104
|
-
`}function
|
|
1030
|
+
`}function wZ($){switch($){case"beta":return"Beta";case"stable":return"Stable";case"deprecated":return"Deprecated";case"experimental":default:return"Experimental"}}function KZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function B$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function A8($){let j=`${_Z($.name.split(".").pop()??"Migration")}Migration`,A=$.dependencies.length>0?`dependencies: [${$.dependencies.map((Q)=>`'${Q}'`).join(", ")}],`:"";return`import type { MigrationSpec } from '@contractspec/lib.contracts-spec/migrations';
|
|
1105
1031
|
|
|
1106
1032
|
export const ${j}: MigrationSpec = {
|
|
1107
1033
|
meta: {
|
|
1108
1034
|
key: '${$.name}',
|
|
1109
1035
|
version: ${$.version},
|
|
1110
|
-
title: '${
|
|
1111
|
-
description: '${
|
|
1112
|
-
domain: '${
|
|
1113
|
-
owners: [${$.owners.map((
|
|
1114
|
-
tags: [${$.tags.map((
|
|
1036
|
+
title: '${E$($.title)}',
|
|
1037
|
+
description: '${E$($.description??"")}',
|
|
1038
|
+
domain: '${E$($.domain)}',
|
|
1039
|
+
owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
|
|
1040
|
+
tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
|
|
1115
1041
|
stability: '${$.stability}',
|
|
1116
1042
|
},
|
|
1117
1043
|
plan: {
|
|
1118
1044
|
up: [
|
|
1119
|
-
${
|
|
1045
|
+
${j8($.up)}
|
|
1120
1046
|
],${$.down&&$.down.length?`
|
|
1121
1047
|
down: [
|
|
1122
|
-
${
|
|
1048
|
+
${j8($.down)}
|
|
1123
1049
|
],`:""}
|
|
1124
1050
|
},
|
|
1125
|
-
${
|
|
1051
|
+
${A}
|
|
1126
1052
|
};
|
|
1127
|
-
`}function
|
|
1053
|
+
`}function j8($){return $.map((W)=>{let j=W.description?`description: '${E$(W.description)}',`:"";switch(W.kind){case"schema":return` {
|
|
1128
1054
|
kind: 'schema',
|
|
1129
1055
|
${j}
|
|
1130
|
-
sql: \`${
|
|
1056
|
+
sql: \`${E$(W.sql??"")}\`,
|
|
1131
1057
|
}`;case"data":return` {
|
|
1132
1058
|
kind: 'data',
|
|
1133
1059
|
${j}
|
|
1134
|
-
script: \`${
|
|
1060
|
+
script: \`${E$(W.script??"")}\`,
|
|
1135
1061
|
}`;case"validation":default:return` {
|
|
1136
1062
|
kind: 'validation',
|
|
1137
1063
|
${j}
|
|
1138
|
-
assertion: \`${
|
|
1064
|
+
assertion: \`${E$(W.assertion??"")}\`,
|
|
1139
1065
|
}`}}).join(`,
|
|
1140
|
-
`)}function
|
|
1066
|
+
`)}function _Z($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function E$($){return $.replace(/`/g,"\\`").replace(/'/g,"\\'")}function Q8($){let{name:W,version:j,kind:A,description:Q,goal:Z,context:X,stability:Y,owners:B,tags:q,auth:H,flags:V}=$,G=zZ(W.split(".").pop()||"Unknown")+"Spec",J=G.replace("Spec","Input"),b=G.replace("Spec","Output");return`import { define${_1(A)} } from '@contractspec/lib.contracts-spec';
|
|
1141
1067
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1142
1068
|
|
|
1143
1069
|
// TODO: Define input schema
|
|
1144
|
-
export const ${
|
|
1145
|
-
name: '${
|
|
1070
|
+
export const ${J} = new SchemaModel({
|
|
1071
|
+
name: '${J}',
|
|
1146
1072
|
description: 'Input for ${W}',
|
|
1147
1073
|
fields: {
|
|
1148
1074
|
// Add your fields here
|
|
@@ -1151,8 +1077,8 @@ export const ${z} = new SchemaModel({
|
|
|
1151
1077
|
});
|
|
1152
1078
|
|
|
1153
1079
|
// TODO: Define output schema
|
|
1154
|
-
export const ${
|
|
1155
|
-
name: '${
|
|
1080
|
+
export const ${b} = new SchemaModel({
|
|
1081
|
+
name: '${b}',
|
|
1156
1082
|
description: 'Output for ${W}',
|
|
1157
1083
|
fields: {
|
|
1158
1084
|
// Add your fields here
|
|
@@ -1160,23 +1086,23 @@ export const ${J} = new SchemaModel({
|
|
|
1160
1086
|
},
|
|
1161
1087
|
});
|
|
1162
1088
|
|
|
1163
|
-
export const ${G} = define${
|
|
1089
|
+
export const ${G} = define${_1(A)}({
|
|
1164
1090
|
meta: {
|
|
1165
1091
|
key: '${W}',
|
|
1166
1092
|
key: '${W}',
|
|
1167
1093
|
version: '${j}',
|
|
1168
1094
|
stability: '${Y}',
|
|
1169
1095
|
stability: '${Y}',
|
|
1170
|
-
owners: [${
|
|
1171
|
-
tags: [${
|
|
1172
|
-
description: '${
|
|
1173
|
-
goal: '${
|
|
1096
|
+
owners: [${B.map((w)=>`'${w}'`).join(", ")}],
|
|
1097
|
+
tags: [${q.map((w)=>`'${w}'`).join(", ")}],
|
|
1098
|
+
description: '${Q}',
|
|
1099
|
+
goal: '${Z}',
|
|
1174
1100
|
context: '${X}',
|
|
1175
1101
|
},
|
|
1176
1102
|
|
|
1177
1103
|
io: {
|
|
1178
|
-
input: ${
|
|
1179
|
-
output: ${
|
|
1104
|
+
input: ${J},
|
|
1105
|
+
output: ${b},
|
|
1180
1106
|
errors: {
|
|
1181
1107
|
// Define possible errors
|
|
1182
1108
|
// EXAMPLE_ERROR: {
|
|
@@ -1189,7 +1115,7 @@ export const ${G} = define${r1(Q)}({
|
|
|
1189
1115
|
|
|
1190
1116
|
policy: {
|
|
1191
1117
|
auth: '${H}',
|
|
1192
|
-
${V.length>0?`flags: [${V.map((
|
|
1118
|
+
${V.length>0?`flags: [${V.map((w)=>`'${w}'`).join(", ")}],`:"// flags: [],"}
|
|
1193
1119
|
},
|
|
1194
1120
|
|
|
1195
1121
|
sideEffects: {
|
|
@@ -1203,7 +1129,7 @@ export const ${G} = define${r1(Q)}({
|
|
|
1203
1129
|
},
|
|
1204
1130
|
|
|
1205
1131
|
transport: {
|
|
1206
|
-
rest: { method: '${
|
|
1132
|
+
rest: { method: '${A==="command"?"POST":"GET"}' },
|
|
1207
1133
|
gql: { field: '${W.replace(/\./g,"_")}' },
|
|
1208
1134
|
mcp: { toolName: '${W.replace(/\./g,"_")}-v${String(j).replace(/\./g,"_")}' },
|
|
1209
1135
|
},
|
|
@@ -1226,12 +1152,12 @@ export const ${G} = define${r1(Q)}({
|
|
|
1226
1152
|
],
|
|
1227
1153
|
},
|
|
1228
1154
|
});
|
|
1229
|
-
`}function
|
|
1155
|
+
`}function _1($){return $.charAt(0).toUpperCase()+$.slice(1)}function zZ($){return $.split(/[-_.]/).map(_1).join("")}function Z8($){let{name:W,version:j,description:A,stability:Q,owners:Z,tags:X,presentationKind:Y}=$,B=UZ(W.replace(/\./g,"_"))+"Presentation",q="";switch(Y){case"web_component":q=` content: {
|
|
1230
1156
|
kind: 'web_component',
|
|
1231
1157
|
framework: 'react',
|
|
1232
1158
|
componentKey: '${W.replace(/\./g,"_")}',
|
|
1233
1159
|
props: new SchemaModel({
|
|
1234
|
-
name: '${
|
|
1160
|
+
name: '${B}Props',
|
|
1235
1161
|
description: 'Props for ${W}',
|
|
1236
1162
|
fields: {
|
|
1237
1163
|
// TODO: Define component props
|
|
@@ -1240,19 +1166,19 @@ export const ${G} = define${r1(Q)}({
|
|
|
1240
1166
|
analytics: [
|
|
1241
1167
|
// TODO: Define analytics events
|
|
1242
1168
|
],
|
|
1243
|
-
},`;break;case"markdown":
|
|
1169
|
+
},`;break;case"markdown":q=` content: {
|
|
1244
1170
|
kind: 'markdown',
|
|
1245
1171
|
content: \`
|
|
1246
|
-
# ${
|
|
1172
|
+
# ${A}
|
|
1247
1173
|
|
|
1248
1174
|
TODO: Add markdown content here
|
|
1249
1175
|
\`,
|
|
1250
1176
|
// Or use resourceUri: 'feature://${W}/guide.md'
|
|
1251
|
-
},`;break;case"data":
|
|
1177
|
+
},`;break;case"data":q=` content: {
|
|
1252
1178
|
kind: 'data',
|
|
1253
1179
|
mimeType: 'application/json',
|
|
1254
1180
|
model: new SchemaModel({
|
|
1255
|
-
name: '${
|
|
1181
|
+
name: '${B}Data',
|
|
1256
1182
|
description: 'Data structure for ${W}',
|
|
1257
1183
|
fields: {
|
|
1258
1184
|
// TODO: Define data structure
|
|
@@ -1261,14 +1187,14 @@ TODO: Add markdown content here
|
|
|
1261
1187
|
},`;break}return`import type { PresentationSpec } from '@contractspec/lib.contracts-spec/presentations';
|
|
1262
1188
|
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';
|
|
1263
1189
|
|
|
1264
|
-
export const ${
|
|
1190
|
+
export const ${B}: PresentationSpec = {
|
|
1265
1191
|
meta: {
|
|
1266
1192
|
key: '${W}',
|
|
1267
1193
|
version: ${j},
|
|
1268
|
-
stability: '${
|
|
1269
|
-
owners: [${
|
|
1194
|
+
stability: '${Q}',
|
|
1195
|
+
owners: [${Z.map((H)=>`'${H}'`).join(", ")}],
|
|
1270
1196
|
tags: [${X.map((H)=>`'${H}'`).join(", ")}],
|
|
1271
|
-
description: '${
|
|
1197
|
+
description: '${A}',
|
|
1272
1198
|
},
|
|
1273
1199
|
|
|
1274
1200
|
policy: {
|
|
@@ -1276,52 +1202,52 @@ export const ${q}: PresentationSpec = {
|
|
|
1276
1202
|
// pii: [],
|
|
1277
1203
|
},
|
|
1278
1204
|
|
|
1279
|
-
${
|
|
1205
|
+
${q}
|
|
1280
1206
|
};
|
|
1281
|
-
`}function
|
|
1282
|
-
${$.providers.map((
|
|
1283
|
-
type: '${
|
|
1284
|
-
config: ${
|
|
1207
|
+
`}function UZ($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function X8($){let W=LZ($.name.split(".").pop()??"Telemetry")+"Telemetry",j=$.providers?.length?`providers: [
|
|
1208
|
+
${$.providers.map((Q)=>` {
|
|
1209
|
+
type: '${Q.type}',
|
|
1210
|
+
config: ${OZ(Q.config)},
|
|
1285
1211
|
}`).join(`,
|
|
1286
1212
|
`)}
|
|
1287
|
-
],`:"",
|
|
1213
|
+
],`:"",A=$.events.map((Q)=>{let Z=Q.properties.map((Y)=>` '${Y.name}': {
|
|
1288
1214
|
type: '${Y.type}',
|
|
1289
1215
|
${Y.required?"required: true,":""}
|
|
1290
1216
|
${Y.pii?"pii: true,":""}
|
|
1291
1217
|
${Y.redact?"redact: true,":""}
|
|
1292
1218
|
${Y.description?`description: '${n(Y.description)}',`:""}
|
|
1293
1219
|
}`).join(`,
|
|
1294
|
-
`),X=
|
|
1220
|
+
`),X=Q.anomalyRules?.length?` anomalyDetection: {
|
|
1295
1221
|
enabled: true,
|
|
1296
|
-
${typeof
|
|
1222
|
+
${typeof Q.anomalyMinimumSample==="number"?`minimumSample: ${Q.anomalyMinimumSample},`:""}
|
|
1297
1223
|
thresholds: [
|
|
1298
|
-
${
|
|
1224
|
+
${Q.anomalyRules.map((Y)=>` {
|
|
1299
1225
|
metric: '${n(Y.metric)}',
|
|
1300
1226
|
${typeof Y.min==="number"?`min: ${Y.min},`:""}
|
|
1301
1227
|
${typeof Y.max==="number"?`max: ${Y.max},`:""}
|
|
1302
1228
|
}`).join(`,
|
|
1303
1229
|
`)}
|
|
1304
1230
|
],
|
|
1305
|
-
actions: [${(
|
|
1306
|
-
},`:
|
|
1231
|
+
actions: [${(Q.anomalyActions??[]).map((Y)=>`'${Y}'`).join(", ")}],
|
|
1232
|
+
},`:Q.anomalyEnabled?` anomalyDetection: {
|
|
1307
1233
|
enabled: true,
|
|
1308
|
-
${typeof
|
|
1234
|
+
${typeof Q.anomalyMinimumSample==="number"?`minimumSample: ${Q.anomalyMinimumSample},`:""}
|
|
1309
1235
|
},`:"";return` {
|
|
1310
|
-
name: '${n(
|
|
1311
|
-
version: ${
|
|
1236
|
+
name: '${n(Q.name)}',
|
|
1237
|
+
version: ${Q.version},
|
|
1312
1238
|
semantics: {
|
|
1313
|
-
what: '${n(
|
|
1314
|
-
${
|
|
1315
|
-
${
|
|
1239
|
+
what: '${n(Q.what)}',
|
|
1240
|
+
${Q.who?`who: '${n(Q.who)}',`:""}
|
|
1241
|
+
${Q.why?`why: '${n(Q.why)}',`:""}
|
|
1316
1242
|
},
|
|
1317
|
-
privacy: '${
|
|
1243
|
+
privacy: '${Q.privacy}',
|
|
1318
1244
|
properties: {
|
|
1319
|
-
${
|
|
1245
|
+
${Z}
|
|
1320
1246
|
},
|
|
1321
|
-
${typeof
|
|
1322
|
-
${typeof
|
|
1247
|
+
${typeof Q.retentionDays==="number"?`retention: { days: ${Q.retentionDays}, ${Q.retentionPolicy?`policy: '${Q.retentionPolicy}'`:""} },`:""}
|
|
1248
|
+
${typeof Q.samplingRate==="number"?`sampling: { rate: ${Q.samplingRate}${Q.samplingConditions?`, conditions: ['${n(Q.samplingConditions)}']`:""} },`:""}
|
|
1323
1249
|
${X}
|
|
1324
|
-
${
|
|
1250
|
+
${Q.tags?.length?`tags: [${Q.tags.map((Y)=>`'${n(Y)}'`).join(", ")}],`:""}
|
|
1325
1251
|
}`}).join(`,
|
|
1326
1252
|
`);return`import type { TelemetrySpec } from '@contractspec/lib.contracts-spec/telemetry';
|
|
1327
1253
|
|
|
@@ -1332,8 +1258,8 @@ export const ${W}: TelemetrySpec = {
|
|
|
1332
1258
|
title: '${n($.name)} telemetry',
|
|
1333
1259
|
description: '${n($.description||"Describe the purpose of this telemetry spec.")}',
|
|
1334
1260
|
domain: '${n($.domain)}',
|
|
1335
|
-
owners: [${$.owners.map((
|
|
1336
|
-
tags: [${$.tags.map((
|
|
1261
|
+
owners: [${$.owners.map((Q)=>`'${n(Q)}'`).join(", ")}],
|
|
1262
|
+
tags: [${$.tags.map((Q)=>`'${n(Q)}'`).join(", ")}],
|
|
1337
1263
|
stability: '${$.stability}',
|
|
1338
1264
|
},
|
|
1339
1265
|
config: {
|
|
@@ -1343,14 +1269,14 @@ export const ${W}: TelemetrySpec = {
|
|
|
1343
1269
|
${j}
|
|
1344
1270
|
},
|
|
1345
1271
|
events: [
|
|
1346
|
-
${
|
|
1272
|
+
${A}
|
|
1347
1273
|
],
|
|
1348
1274
|
};
|
|
1349
|
-
`}function
|
|
1350
|
-
`),
|
|
1351
|
-
from: '${
|
|
1352
|
-
to: '${
|
|
1353
|
-
${
|
|
1275
|
+
`}function LZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function n($){return $.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function OZ($){let W=$.trim();if(!W)return"{}";if(W.startsWith("{")&&W.endsWith("}")||W.startsWith("[")&&W.endsWith("]"))return W;return`'${n(W)}'`}function Y8($){let W=IZ($.name.split(".").pop()??"Workflow")+"Workflow",j=$.steps.map((Q)=>SZ(Q)).join(`,
|
|
1276
|
+
`),A=$.transitions.map((Q)=>` {
|
|
1277
|
+
from: '${Q.from}',
|
|
1278
|
+
to: '${Q.to}',
|
|
1279
|
+
${Q.condition?` condition: '${h$(Q.condition)}',`:""}
|
|
1354
1280
|
}`).join(`,
|
|
1355
1281
|
`);return`import type { WorkflowSpec } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1356
1282
|
|
|
@@ -1366,12 +1292,12 @@ export const ${W}: WorkflowSpec = {
|
|
|
1366
1292
|
meta: {
|
|
1367
1293
|
key: '${$.name}',
|
|
1368
1294
|
version: ${$.version},
|
|
1369
|
-
title: '${
|
|
1370
|
-
description: '${
|
|
1371
|
-
domain: '${
|
|
1295
|
+
title: '${h$($.title)}',
|
|
1296
|
+
description: '${h$($.description)}',
|
|
1297
|
+
domain: '${h$($.domain)}',
|
|
1372
1298
|
stability: '${$.stability}',
|
|
1373
|
-
owners: [${$.owners.map((
|
|
1374
|
-
tags: [${$.tags.map((
|
|
1299
|
+
owners: [${$.owners.map((Q)=>`'${Q}'`).join(", ")}],
|
|
1300
|
+
tags: [${$.tags.map((Q)=>`'${Q}'`).join(", ")}],
|
|
1375
1301
|
},
|
|
1376
1302
|
definition: {
|
|
1377
1303
|
${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
@@ -1379,21 +1305,73 @@ ${$.entryStepId?` entryStepId: '${$.entryStepId}',
|
|
|
1379
1305
|
${j}
|
|
1380
1306
|
],
|
|
1381
1307
|
transitions: [
|
|
1382
|
-
${
|
|
1308
|
+
${A}
|
|
1383
1309
|
],
|
|
1384
1310
|
},
|
|
1385
1311
|
${$.policyFlags.length>0?`policy: {
|
|
1386
|
-
flags: [${$.policyFlags.map((
|
|
1312
|
+
flags: [${$.policyFlags.map((Q)=>`'${Q}'`).join(", ")}],
|
|
1387
1313
|
},`:"// policy: { flags: [] },"}
|
|
1388
1314
|
};
|
|
1389
|
-
`}function
|
|
1390
|
-
`)}function
|
|
1315
|
+
`}function SZ($){let W=[" {",` id: '${$.id}',`,` type: '${$.type}',`,` label: '${h$($.label)}',`];if($.description)W.push(` description: '${h$($.description)}',`);let j=[];if($.operation)j.push(`operation: { name: '${$.operation.name}', version: ${$.operation.version} }`);if($.form)j.push(`form: { key: '${$.form.key}', version: ${$.form.version} }`);if(j.length)W.push(` action: { ${j.join(", ")} },`);return W.push(" }"),W.join(`
|
|
1316
|
+
`)}function IZ($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function h$($){return $.replace(/'/g,"\\'")}function a0({exportName:$,specImportPath:W,workflowFunctionName:j}){return`import { createHook, createWebhook, sleep } from 'workflow';
|
|
1317
|
+
import { runWorkflowSpecWithWorkflowDevkit } from '@contractspec/integration.workflow-devkit';
|
|
1318
|
+
import { ${$} } from '${W}';
|
|
1319
|
+
|
|
1320
|
+
export async function ${j}(input = {}, bridge = {}) {
|
|
1321
|
+
"use workflow";
|
|
1322
|
+
|
|
1323
|
+
// Keep the workflow function deterministic.
|
|
1324
|
+
// Any Node.js or side-effectful logic should live in "use step" helpers that
|
|
1325
|
+
// your bridge calls, not in this orchestrator itself.
|
|
1326
|
+
return runWorkflowSpecWithWorkflowDevkit({
|
|
1327
|
+
spec: ${$},
|
|
1328
|
+
initialData: input,
|
|
1329
|
+
bridge,
|
|
1330
|
+
primitives: {
|
|
1331
|
+
sleep,
|
|
1332
|
+
createHook,
|
|
1333
|
+
createWebhook,
|
|
1334
|
+
},
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
`}function s0($,W){return`import { createWorkflowDevkitStartRoute } from '@contractspec/integration.workflow-devkit';
|
|
1338
|
+
import { ${W} } from '${$}';
|
|
1339
|
+
|
|
1340
|
+
export const POST = createWorkflowDevkitStartRoute({
|
|
1341
|
+
workflow: ${W},
|
|
1342
|
+
async buildArgs(body) {
|
|
1343
|
+
return [body];
|
|
1344
|
+
},
|
|
1345
|
+
});
|
|
1346
|
+
`}function e0(){return`import { createWorkflowDevkitFollowUpRoute } from '@contractspec/integration.workflow-devkit';
|
|
1347
|
+
|
|
1348
|
+
export const POST = createWorkflowDevkitFollowUpRoute({
|
|
1349
|
+
resolveToken({ runId }) {
|
|
1350
|
+
return \`workflow-session:\${runId}\`;
|
|
1351
|
+
},
|
|
1352
|
+
});
|
|
1353
|
+
`}function $W(){return`import { createWorkflowDevkitStreamRoute } from '@contractspec/integration.workflow-devkit';
|
|
1354
|
+
|
|
1355
|
+
export const GET = createWorkflowDevkitStreamRoute();
|
|
1356
|
+
`}function WW($,W){return`import { ${W} } from '${$}';
|
|
1357
|
+
|
|
1358
|
+
export const workflowDevkitBootstrap = {
|
|
1359
|
+
workflow: ${W},
|
|
1360
|
+
createBridge() {
|
|
1361
|
+
return {
|
|
1362
|
+
executeAutomationStep: async () => {
|
|
1363
|
+
throw new Error('Provide executeAutomationStep in your generic host bridge.');
|
|
1364
|
+
},
|
|
1365
|
+
};
|
|
1366
|
+
},
|
|
1367
|
+
};
|
|
1368
|
+
`}function jW({exportName:$,specImportPath:W,runnerName:j,workflowName:A}){return`import { InMemoryStateStore } from '@contractspec/lib.contracts-spec/workflow/adapters';
|
|
1391
1369
|
import { WorkflowRunner } from '@contractspec/lib.contracts-spec/workflow/runner';
|
|
1392
1370
|
import { WorkflowRegistry } from '@contractspec/lib.contracts-spec/workflow/spec';
|
|
1393
1371
|
import { ${$} } from '${W}';
|
|
1394
1372
|
|
|
1395
1373
|
/**
|
|
1396
|
-
* Runner wiring for ${
|
|
1374
|
+
* Runner wiring for ${A}.
|
|
1397
1375
|
*
|
|
1398
1376
|
* TODO:
|
|
1399
1377
|
* - Replace the in-memory state store with a persistent adapter if needed.
|
|
@@ -1427,37 +1405,298 @@ export const ${j} = new WorkflowRunner({
|
|
|
1427
1405
|
// console.log(event, payload);
|
|
1428
1406
|
},
|
|
1429
1407
|
});
|
|
1430
|
-
`}
|
|
1431
|
-
|
|
1408
|
+
`}import{getAuthoringTargetDefinition as MZ}from"@contractspec/module.workspace";var q8={"module-bundle":"AI-native module bundle scaffold","builder-spec":"Builder contract scaffold","provider-spec":"Provider contract scaffold"};async function H8($,W){let j=EZ($,W.specPath),A=NZ($,W.target,j),Q=$.join(j,"package.json"),Z=$.join(j,"README.md"),X=$.join(j,"src"),Y=$.join(X,"index.ts"),B=z1($.relative(X,W.specPath)).replace(/\.[^.]+$/,"");await $.mkdir(X);let q=[[Q,JSON.stringify({name:A,version:"0.1.0",description:q8[W.target],type:"module",exports:{".":"./src/index.ts"}},null,2)+`
|
|
1409
|
+
`],[Z,`# ${A}
|
|
1410
|
+
|
|
1411
|
+
${q8[W.target]}.
|
|
1412
|
+
`],[Y,`export * from "./${B.startsWith(".")?B:`./${B}`}";
|
|
1413
|
+
`],[W.specPath,W.specCode]],H={packageRoot:j,files:q.map(([V])=>V),created:[],skipped:[]};for(let[V,G]of q){if(await $.exists(V)&&!W.overwrite){H.skipped.push(V);continue}await $.writeFile(V,G),H.created.push(V)}return H}function V8($){switch($.target){case"module-bundle":return`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec";
|
|
1414
|
+
|
|
1415
|
+
export const ${$.exportName} = defineModuleBundle({
|
|
1416
|
+
meta: {
|
|
1417
|
+
key: "${$.key}",
|
|
1418
|
+
version: "1.0.0",
|
|
1419
|
+
title: "${$.title}",
|
|
1420
|
+
description: "${$.description}",
|
|
1421
|
+
},
|
|
1422
|
+
routes: [
|
|
1423
|
+
{
|
|
1424
|
+
routeId: "default",
|
|
1425
|
+
path: "/",
|
|
1426
|
+
defaultSurface: "main",
|
|
1427
|
+
},
|
|
1428
|
+
],
|
|
1429
|
+
surfaces: {
|
|
1430
|
+
main: {
|
|
1431
|
+
surfaceId: "main",
|
|
1432
|
+
kind: "workbench",
|
|
1433
|
+
title: "${$.title}",
|
|
1434
|
+
slots: [],
|
|
1435
|
+
layouts: [],
|
|
1436
|
+
data: [],
|
|
1437
|
+
verification: {
|
|
1438
|
+
level: "basic",
|
|
1439
|
+
},
|
|
1440
|
+
},
|
|
1441
|
+
},
|
|
1442
|
+
});
|
|
1443
|
+
`;case"builder-spec":return`import type { BuilderWorkspace } from "@contractspec/lib.builder-spec";
|
|
1444
|
+
|
|
1445
|
+
export const ${$.exportName}: BuilderWorkspace = {
|
|
1446
|
+
id: "${$.key}",
|
|
1447
|
+
tenantId: "default",
|
|
1448
|
+
name: "${$.title}",
|
|
1449
|
+
status: "draft",
|
|
1450
|
+
appClass: "custom",
|
|
1451
|
+
defaultRuntimeMode: "managed",
|
|
1452
|
+
mobileParityRequired: false,
|
|
1453
|
+
ownerIds: [],
|
|
1454
|
+
defaultLocale: "en",
|
|
1455
|
+
defaultChannelPolicy: {},
|
|
1456
|
+
createdAt: new Date().toISOString(),
|
|
1457
|
+
updatedAt: new Date().toISOString(),
|
|
1458
|
+
};
|
|
1459
|
+
`;case"provider-spec":return`import type { ProviderCapabilityProfile } from "@contractspec/lib.provider-spec";
|
|
1460
|
+
|
|
1461
|
+
export const ${$.exportName}: ProviderCapabilityProfile = {
|
|
1462
|
+
providerId: "${$.key}",
|
|
1463
|
+
supportsRepoScopedPatch: true,
|
|
1464
|
+
supportsStructuredDiff: true,
|
|
1465
|
+
supportsLongContext: true,
|
|
1466
|
+
supportsFunctionCalling: true,
|
|
1467
|
+
supportsSTT: false,
|
|
1468
|
+
supportsVision: false,
|
|
1469
|
+
supportsStreaming: true,
|
|
1470
|
+
supportsLocalExecution: false,
|
|
1471
|
+
supportedArtifactTypes: ["patch"],
|
|
1472
|
+
knownConstraints: [],
|
|
1473
|
+
};
|
|
1474
|
+
`}}function EZ($,W){let j=z1(W),A="/src/",Q=j.lastIndexOf("/src/");if(Q===-1)return $.dirname(W);return j.slice(0,Q)}function NZ($,W,j){let A=MZ(W),Q=z1($.basename(j));return`${A.defaultPackagePrefix??(W==="module-bundle"?"@contractspec/bundle.":"@contractspec/lib.")}${Q}`}function z1($){return $.replaceAll("\\","/").replace(/\/$/,"")}async function f$($,W,j,A={}){let{fs:Q,logger:Z,workspace:X}=W,Y=X?.scanSpecSource??yZ,B=X?.inferSpecTypeFromFilePath??xZ,q=X?.generateHandlerTemplate??DZ,H=X?.generateComponentTemplate??CZ,V=X?.generateTestTemplate??TZ,{targets:G=void 0,outputDir:J=j.outputDir,overwrite:b=!1,dryRun:w=!1,includeTests:L=!1,runtimeGeneration:z}=A,S=await Q.readFile($),U=Y(S,$),O=RZ(S,$),K=O==="unknown"?B($):O,_=G??L1(K,{includeTests:L});Z.info(`Building from spec: ${$}`,{targetId:K});let I=[],M={};for(let E of _)try{let C=await vZ(E,$,S,U,K,{fs:Q,logger:Z},J,b,w,z,M,{genHandler:q,genComponent:H,genTest:V});if(I.push(C),C.success&&C.generatedCode)M[E]=C.generatedCode}catch(C){I.push({target:E,outputPath:"",success:!1,error:C instanceof Error?C.message:String(C),skipped:!1})}return{specPath:$,specInfo:U,targetId:K,results:I}}async function vZ($,W,j,A,Q,Z,X,Y,B,q,H,V){let{fs:G,logger:J}=Z,{genHandler:b,genComponent:w,genTest:L}=V,z,S,U=[];switch($){case"handler":{if(Q!=="operation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Handler generation only supported for operation specs (got ${Q})`};let _=A.kind==="command"||A.kind==="query"?A.kind:"command",I=b(o(j,A,W),_);S=g$(W,X,"handlers",o(j,A,W),".handler.ts",Z.fs),z=await q?.generateArtifact?.({kind:"handler",specCode:j,outputPath:S,fallbackCode:I})??I;break}case"component":{if(Q!=="presentation")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Component generation only supported for presentation specs (got ${Q})`};let _=w(o(j,A,W),A.description??"");S=g$(W,X,"components",o(j,A,W),".tsx",Z.fs),z=await q?.generateArtifact?.({kind:"component",specCode:j,outputPath:S,fallbackCode:_})??_;break}case"test":{let _=Q==="operation"?"handler":"component",I=Q==="operation"?H.handler??"":Q==="presentation"?H.component??"":Q==="form"?H.form??"":"",M=L(o(j,A,W),_);S=g$(W,X,"__tests__",o(j,A,W),".test.ts",Z.fs),z=await q?.generateTest?.({kind:_,specCode:j,outputPath:S,existingCode:I,fallbackCode:M})??M;break}case"form":{if(Q!=="form")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Form generation only supported for form specs (got ${Q})`};let _=`import * as React from "react";
|
|
1475
|
+
|
|
1476
|
+
export interface ${q$(o(j,A,W))}Props {
|
|
1477
|
+
className?: string;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
export function ${q$(o(j,A,W))}Form({
|
|
1481
|
+
className,
|
|
1482
|
+
}: ${q$(o(j,A,W))}Props) {
|
|
1483
|
+
return <form className={className}>TODO: implement ${o(j,A,W)}</form>;
|
|
1484
|
+
}
|
|
1485
|
+
`;S=g$(W,X,"forms",o(j,A,W),".form.tsx",Z.fs),z=await q?.generateArtifact?.({kind:"form",specCode:j,outputPath:S,fallbackCode:_})??_;break}case"workflow-runner":{if(Q!=="workflow")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Workflow runners only supported for workflow specs (got ${Q})`};let _=o(j,A,W),I=hZ(j)??`${q$(_)}Workflow`,M=`${q$(_)}Runner`,E=O1(_);if(S=g$(W,X,"workflows",_,".runner.ts",Z.fs),z=jW({exportName:I,specImportPath:U1(Z.fs,S,W),runnerName:M,workflowName:_}),uZ(j)){let C=`${q$(_)}WorkflowDevkit`,R=W0(Z.fs,S,`${E}.workflow-devkit.ts`),v=W0(Z.fs,S,`${E}.workflow-devkit.start.route.ts`),x=W0(Z.fs,S,`${E}.workflow-devkit.follow-up.route.ts`),L$=W0(Z.fs,S,`${E}.workflow-devkit.stream.route.ts`),v0=W0(Z.fs,S,`${E}.workflow-devkit.generic.ts`);U=[{path:R,code:a0({exportName:I,specImportPath:U1(Z.fs,R,W),workflowFunctionName:C})},{path:v,code:s0(G8(Z.fs,v,R),C)},{path:x,code:e0()},{path:L$,code:$W()},{path:v0,code:WW(G8(Z.fs,v0,R),C)}]}break}case"data-view-renderer":{if(Q!=="data-view")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Data view renderers only supported for data-view specs (got ${Q})`};let _=o(j,A,W),I=gZ(j)??`${q$(_)}DataView`,M=`${q$(_)}Renderer`;S=g$(W,X,"data-views",_,".renderer.tsx",Z.fs),z=p0({exportName:I,specImportPath:U1(Z.fs,S,W),rendererName:M,viewKind:fZ(j)??"table"});break}case"package-scaffold":{if(Q!=="module-bundle"&&Q!=="builder-spec"&&Q!=="provider-spec")return{target:$,outputPath:"",success:!1,skipped:!0,error:`Package scaffold generation only supported for package targets (got ${Q})`};if(B){let M=PZ(W);return J.info(`[dry-run] Would scaffold package: ${M}`),{target:$,outputPath:M,success:!0}}let _=j.trim().length>0?j:V8({target:Q,key:A.key??Z.fs.basename(W),title:A.key??Z.fs.basename(W),description:A.description??FZ(Q).title,exportName:q$(A.key??Z.fs.basename(W))});return S=(await H8(Z.fs,{target:Q,specPath:W,specCode:_,overwrite:Y})).packageRoot,J.info(`Generated package scaffold: ${S}`),{target:$,outputPath:S,success:!0}}default:return{target:$,outputPath:"",success:!1,error:`Unknown target: ${$}`}}let O=[{path:S,code:z},...U],K=Y?void 0:await mZ(O,G);if(K)return{target:$,outputPath:K,success:!1,skipped:!0,error:"File already exists (use overwrite option)"};if(B){for(let _ of O)J.info(`[dry-run] Would write: ${_.path}`);return{target:$,outputPath:S,success:!0,generatedCode:O[0]?.code}}for(let _ of O)await G.mkdir(G.dirname(_.path)),await G.writeFile(_.path,dZ(_.code)),J.info(`Generated: ${_.path}`);return{target:$,outputPath:S,success:!0}}function L1($,W){switch($){case"operation":return W.includeTests?["handler","test"]:["handler"];case"presentation":return W.includeTests?["component","test"]:["component"];case"form":return W.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 g$($,W,j,A,Q,Z){let X=O1(A.split(".").pop()??"unknown"),Y;if(W.startsWith("."))Y=Z.resolve(Z.dirname($),"..",W,j);else Y=Z.resolve(W,j);return Z.join(Y,`${X}${Q}`)}async function mZ($,W){for(let j of $)if(await W.exists(j.path))return j.path;return}function O1($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function q$($){return O1($).split("-").filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function S1($){return $.replace(/\.[^.]+$/,"")}function PZ($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function U1($,W,j){let A=S1($.relative($.dirname(W),j));return A.startsWith(".")?A:`./${A}`}function G8($,W,j){let A=S1($.relative($.dirname(W),j));return A.startsWith(".")?A:`./${A}`}function W0($,W,j){return $.join($.dirname(W),j)}function o($,W,j){return kZ($,"name")??W.key??S1(nZ(j))}function kZ($,W){let j=new RegExp(`${W}\\s*:\\s*['"]([^'"]+)['"]`);return $.match(j)?.[1]??null}function hZ($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*WorkflowSpec/)?.[1]??null}function gZ($){return $.match(/export\\s+const\\s+(\\w+)\\s*:\\s*DataViewSpec/)?.[1]??null}function fZ($){return $.match(/view\\s*:\\s*{[\\s\\S]*?kind:\\s*['"]([^'"]+)['"]/)?.[1]??null}function uZ($){return/workflowDevkit\s*:/.test($)||/['"]workflow-devkit['"]\s*:\s*true/.test($)}function dZ($){return $.endsWith(`
|
|
1486
|
+
`)?$:`${$}
|
|
1487
|
+
`}function nZ($){return $.replaceAll("\\","/").split("/").pop()??$}i();import{scanAllSpecsFromSource as pZ,scanSpecSource as tZ}from"@contractspec/module.workspace";import aZ from"micromatch";var K8={};h(K8,{validators:()=>iZ,urlSchema:()=>oZ,isValidVersion:()=>rZ,isValidIdentifier:()=>b8,isValidDotName:()=>w8,isTestFile:()=>j0,isLibraryDefinitionFile:()=>A0,emailSchema:()=>lZ});import I1 from"micromatch";function j0($,W){let j=W?.testing?.testMatch??["**/*.{test,spec}.{ts,js}"];return I1.isMatch($,j)}function A0($){let W=["**/libs/contracts/src/app-config/app-config.capability.ts","**/libs/contracts/src/app-config/app-config.contracts.ts","**/libs/contracts/src/app-config/app-config.feature.ts","**/libs/contracts/src/app-config/lifecycle-contracts.ts","**/libs/contracts/src/app-config/events.ts","**/libs/contracts-spec/src/app-config/app-config.capability.ts","**/libs/contracts-spec/src/app-config/app-config.contracts.ts","**/libs/contracts-spec/src/app-config/app-config.feature.ts","**/libs/contracts-spec/src/app-config/lifecycle-contracts.ts","**/libs/contracts-spec/src/app-config/events.ts"];if(I1.isMatch($,W))return!1;let j=["**/libs/contracts/src/*.ts","**/libs/contracts-spec/src/*.ts","**/libs/contracts/src/operations/*.ts","**/libs/contracts/src/presentations/*.ts","**/libs/contracts/src/contract-registry/*.ts","**/libs/contracts/src/model-registry/*.ts","**/libs/contracts/src/registry-utils/*.ts","**/libs/contracts-spec/src/operations/*.ts","**/libs/contracts-spec/src/presentations/*.ts","**/libs/contracts-spec/src/contract-registry/*.ts","**/libs/contracts-spec/src/model-registry/*.ts","**/libs/contracts-spec/src/registry-utils/*.ts","**/libs/contracts-transformers/src/**","**/libs/schema/src/**"];return I1.isMatch($,j)}import*as H$ from"zod";function b8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test($)}function w8($){return/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test($)}function rZ($){return Number.isInteger($)&&$>0}var lZ=H$.string().email(),oZ=H$.string().url(),iZ={specName:H$.string().refine(w8,{message:'Must be valid dot notation (e.g., "domain.operation")'}),version:H$.number().int().positive(),identifier:H$.string().refine(b8,{message:"Must be a valid TypeScript identifier"}),owner:H$.string().startsWith("@"),tag:H$.string().min(1)};function Q0($){return($??"").split("|").map((W)=>W.trim().replace(/^\.?\//,"")).filter(Boolean)}function sZ($){let W=$?.packages&&$.packages.length>0?$.packages:["**"],j=[...Q0($?.conventions.models),...Q0($?.conventions.operations),...Q0($?.conventions.events),...Q0($?.conventions.presentations),...Q0($?.conventions.forms)];return[...new Set(W.flatMap((A)=>{let Q=A==="**"?"":`${A}/`,Z=Y$.map((Y)=>`${Q}${Y}`),X=j.map((Y)=>`${Q}${Y}/**/*.ts`);return[...Z,...X]}))]}function eZ($,W,j){if($.specType==="unknown")return!1;if(W.type&&!j.includes($.specType))return!1;return!0}function $6($,W){let j=$.filePath.localeCompare(W.filePath);if(j!==0)return j;let A=($.declarationLine??Number.MAX_SAFE_INTEGER)-(W.declarationLine??Number.MAX_SAFE_INTEGER);if(A!==0)return A;return($.discoveryId??$.key??"").localeCompare(W.discoveryId??W.key??"")}async function N$($,W={}){if(W.paths&&W.paths.length>0)return[...new Set(W.paths)].sort((j,A)=>j.localeCompare(A));if(W.pattern)return $.glob({cwd:W.cwd,pattern:W.pattern});return $.glob({cwd:W.cwd,patterns:sZ(W.config)})}async function QW($,W={}){let j=await N$($.fs,W),A=W.type?Array.isArray(W.type)?W.type:[W.type]:[],Q=[];for(let Z of j){if(W.config?.excludePackages&&aZ.isMatch(Z,W.config.excludePackages,{contains:!0}))continue;if(Z.includes("node_modules")||Z.includes("/dist/")||j0(Z,W.config)||A0(Z))continue;try{let X=await $.fs.readFile(Z),Y=pZ(X,Z),B=Y.length>0?Y:[tZ(X,Z)];for(let q of B)if(eZ(q,W,A))Q.push(q)}catch{}}return Q.sort($6)}function J$($,W){if(W===0)return 100;return Math.round($/W*100*100)/100}function ZW($){let W=JSON.parse($),j=new Map,A=0,Q=0,Z=0,X=0,Y=0,B=0,q=0,H=0;for(let[G,J]of Object.entries(W)){let b=W6(G,J);j.set(G,b),A+=b.statements.total,Q+=b.statements.covered,Z+=b.branches.total,X+=b.branches.covered,Y+=b.functions.total,B+=b.functions.covered,q+=b.lines.total,H+=b.lines.covered}let V={statements:{covered:Q,total:A,pct:J$(Q,A)},branches:{covered:X,total:Z,pct:J$(X,Z)},functions:{covered:B,total:Y,pct:J$(B,Y)},lines:{covered:H,total:q,pct:J$(H,q)}};return{files:j,total:V}}function W6($,W){let j=Object.keys(W.statementMap).length,A=Object.values(W.s).filter((H)=>H>0).length,Q=Object.keys(W.fnMap).length,Z=Object.values(W.f).filter((H)=>H>0).length,X=0,Y=0;for(let H of Object.values(W.b))X+=H.length,Y+=H.filter((V)=>V>0).length;let B=new Set,q=new Set;for(let[H,V]of Object.entries(W.statementMap))for(let G=V.start.line;G<=V.end.line;G++)if(B.add(G),(W.s[H]??0)>0)q.add(G);return{path:$,statements:{covered:A,total:j,pct:J$(A,j)},branches:{covered:Y,total:X,pct:J$(Y,X)},functions:{covered:Z,total:Q,pct:J$(Z,Q)},lines:{covered:q.size,total:B.size,pct:J$(q.size,B.size)}}}function M1($){switch($){case"istanbul":return{parse:ZW};case"lcov":throw Error("LCOV format not yet supported");case"cobertura":throw Error("Cobertura format not yet supported");default:throw Error(`Unknown coverage format: ${$}`)}}function E1($,W){if($.endsWith(".json")||$.includes("coverage-final.json"))return"istanbul";if($.endsWith(".lcov")||$.includes("lcov.info"))return"lcov";if($.endsWith(".xml")&&W?.includes("cobertura"))return"cobertura";return"istanbul"}function N1($,W,j,A){let Q=[];if(j.statements!==void 0&&A.statements.pct<j.statements)Q.push({metric:"statements",required:j.statements,actual:A.statements.pct,message:`Statement coverage ${A.statements.pct}% is below required ${j.statements}%`});if(j.branches!==void 0&&A.branches.pct<j.branches)Q.push({metric:"branches",required:j.branches,actual:A.branches.pct,message:`Branch coverage ${A.branches.pct}% is below required ${j.branches}%`});if(j.functions!==void 0&&A.functions.pct<j.functions)Q.push({metric:"functions",required:j.functions,actual:A.functions.pct,message:`Function coverage ${A.functions.pct}% is below required ${j.functions}%`});if(j.lines!==void 0&&A.lines.pct<j.lines)Q.push({metric:"lines",required:j.lines,actual:A.lines.pct,message:`Line coverage ${A.lines.pct}% is below required ${j.lines}%`});if(j.mutations!==void 0)Q.push({metric:"mutations",required:j.mutations,actual:0,message:`Mutation coverage required (${j.mutations}%) but mutation testing is not yet supported`});return{specKey:$,specVersion:W,requirement:j,actual:A,passed:Q.length===0,failures:Q}}async function R1($,W,j){let{fs:A,logger:Q}=$,Z=[],X=j.workspaceRoot?`${j.workspaceRoot}/coverage`:"./coverage",Y=[`${X}/coverage-final.json`,`${X}/coverage.json`,`${X}/coverage-summary.json`],B,q;for(let J of Y)if(await A.exists(J)){B=await A.readFile(J),q=J;break}if(!B)return Q.info("No coverage report found, skipping coverage checks"),Z;let H=E1(q??"coverage.json"),G=M1(H).parse(B);for(let J of W){if(J.specType!=="test-spec"||!J.key||!J.version||!J.sourceBlock)continue;let b=J.sourceBlock.match(/coverage\s*:\s*\{([^}]+)\}/);if(!b||!b[1])continue;let w=b[1],L={},z=w.match(/statements\s*:\s*(\d+)/);if(z&&z[1])L.statements=parseInt(z[1],10);let S=w.match(/branches\s*:\s*(\d+)/);if(S&&S[1])L.branches=parseInt(S[1],10);let U=w.match(/functions\s*:\s*(\d+)/);if(U&&U[1])L.functions=parseInt(U[1],10);let O=w.match(/lines\s*:\s*(\d+)/);if(O&&O[1])L.lines=parseInt(O[1],10);if(Object.keys(L).length===0)continue;let K=N1(J.key,J.version,L,G.total);for(let _ of K.failures)Z.push({ruleId:"coverage-below-threshold",severity:"error",message:_.message,category:"coverage",file:J.filePath,context:{specKey:J.key,specVersion:J.version,metric:_.metric,required:_.required,actual:_.actual}})}return Z}import{addContractNode as j6,buildReverseEdges as A6,createContractGraph as Q6,detectCycles as Z6,findMissingDependencies as X6,parseImportedSpecNames as Y6,toDot as B6}from"@contractspec/module.workspace";async function _8($,W={}){let{fs:j}=$,A=await N$(j,{config:W.config,pattern:W.pattern}),Q=Q6();for(let Y of A){let B=await j.readFile(Y),q=j.relative(".",Y),H=j.basename(Y).replace(/\.[jt]s$/,"").replace(/\.(contracts|contract|command|query|operation|operations|event|presentation|workflow|data-view|migration|telemetry|experiment|app-config|integration|knowledge)$/,"")||"unknown",V=Y6(B,Y);j6(Q,H,q,V)}A6(Q);let Z=Z6(Q),X=X6(Q);return{graph:Q,total:Q.size,cycles:Z,missing:X}}function aJ($,W){return $.get(W)}function sJ($){return B6($)}function eJ($){let W=Array.from($.values()),j=W.filter((X)=>X.dependencies.length>0),A=W.filter((X)=>X.dependencies.length===0),Q=W.filter((X)=>X.dependents.length>0),Z=W.filter((X)=>X.dependents.length===0);return{total:$.size,withDeps:j.length,withoutDeps:A.length,used:Q.length,unused:Z.length}}i();async function C1($,W){let j=[],A=await m($.fs),Q=await _8($,{config:A,pattern:W.pattern});for(let Z of Q.cycles)j.push({ruleId:"deps-circular",severity:"error",message:`Circular dependency detected: ${Z.join(" → ")}`,category:"deps",context:{cycle:Z}});for(let Z of Q.missing)for(let X of Z.missing)j.push({ruleId:"deps-missing",severity:"error",message:`Missing dependency: ${Z.contract} requires ${X}`,category:"deps",context:{contract:Z.contract,missing:X}});return j}import{analyzePackageDocBlocks as q6}from"@contractspec/module.workspace";var H6=["**/node_modules/**","**/dist/**","**/.turbo/**","**/.next/**"];async function V6($,W){let j=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:H6}),A=new Map;for(let X of j){let Y=$.dirname(X),B=$.join(Y,"src");if(!await $.exists(B))continue;try{let q=JSON.parse(await $.readFile(X));A.set(Y,{packageName:q.name??$.relative(W,Y),packageRoot:Y,srcRoot:B})}catch{continue}}let Q=$.join(W,"package.json"),Z=$.join(W,"src");if(await $.exists(Q)&&await $.exists(Z))try{let X=JSON.parse(await $.readFile(Q));A.set(W,{packageName:X.name??W,packageRoot:W,srcRoot:Z})}catch{}return[...A.values()].sort((X,Y)=>X.packageRoot.localeCompare(Y.packageRoot))}async function XW($,W){let j=[],A=await V6($,W);for(let Q of A){let Z=q6({packageName:Q.packageName,srcRoot:Q.srcRoot});for(let X of Z.diagnostics)j.push({...X,packageName:Q.packageName,packageRoot:Q.packageRoot,srcRoot:Q.srcRoot})}return j}async function D1($,W){let j=W.workspaceRoot??process.cwd();return(await XW($.fs,j)).map((Q)=>({ruleId:Q.ruleId,severity:Q.severity==="warning"?"warning":"error",message:Q.message,category:"docs",file:Q.file,line:Q.line,column:Q.column,context:{packageName:Q.packageName,packageRoot:Q.packageRoot,...Q.context}}))}async function T1($,W,j){let A=[],Q=await G6($,W);if(A.push(Q),Q.status==="pass")A.push(await J6($,W,j));return A}async function G6($,W){let j=$.join(W.workspaceRoot,".contractsrc.json");try{if(!await $.exists(j))return{category:"ai",name:"AI Provider",status:"skip",message:"No config file found"};let Q=await $.readFile(j),Z=JSON.parse(Q),X=Z.aiProvider??"claude",Y=Z.aiModel??"default";return{category:"ai",name:"AI Provider",status:"pass",message:`Provider: ${X}, Model: ${Y}`}}catch{return{category:"ai",name:"AI Provider",status:"skip",message:"Could not read AI config"}}}async function J6($,W,j){let A=$.join(W.workspaceRoot,".contractsrc.json");try{let Q=await $.readFile(A),X=JSON.parse(Q).aiProvider??"claude",B={claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",ollama:"",custom:"CONTRACTSPEC_LLM_API_KEY"}[X];if(!B)return{category:"ai",name:"API Key",status:"pass",message:`${X} does not require an API key`};if(!!process.env[B])return{category:"ai",name:"API Key",status:"pass",message:`${B} is set`};return{category:"ai",name:"API Key",status:"warn",message:`${B} not set`,details:`Set ${B} in your environment to use AI features`,fix:j?{description:`Set ${B} environment variable`,apply:async()=>{let H=await j.input(`Enter your ${X} API key:`,{password:!0});if(!H)return{success:!1,message:"No API key provided"};let V=$.join(W.workspaceRoot,".env");try{let G="";if(await $.exists(V)){if(G=await $.readFile(V),G.includes(`${B}=`))return{success:!1,message:`${B} already in .env, update manually`};G+=`
|
|
1488
|
+
`}return G+=`${B}=${H}
|
|
1489
|
+
`,await $.writeFile(V,G),{success:!0,message:`Added ${B} to .env (restart required)`}}catch(G){return{success:!1,message:`Failed: ${G instanceof Error?G.message:String(G)}`}}}}:void 0}}catch{return{category:"ai",name:"API Key",status:"skip",message:"Could not check API key"}}}import{exec as b6}from"node:child_process";import{promisify as w6}from"node:util";var YW=w6(b6);async function F1($,W){let j=[];return j.push(await K6(W)),j.push(await _6(W)),j.push(await z6($,W)),j}async function K6($){try{return await YW("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 YW("npm install -g @contractspec/app.cli-contractspec",{cwd:$.workspaceRoot,timeout:60000}),{success:!0,message:"CLI installed globally"}}catch(W){return{success:!1,message:`Failed to install: ${W instanceof Error?W.message:String(W)}`}}}}}}}async function _6($){try{let{stdout:W}=await YW("bunx contractspec --version",{cwd:$.workspaceRoot,timeout:1e4});return{category:"cli",name:"CLI Version",status:"pass",message:`CLI version: ${W.trim()}`}}catch{return{category:"cli",name:"CLI Version",status:"skip",message:"Could not determine CLI version"}}}async function z6($,W){let j=$.join(W.workspaceRoot,"package.json");try{if(!await $.exists(j))return{category:"cli",name:"Local Installation",status:"skip",message:"No package.json found"};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot){let Y=$.join(W.workspaceRoot,"packages/apps/cli-contractspec");if(await $.exists(Y))return{category:"cli",name:"Local Installation",status:"pass",message:"CLI is part of the workspace (source)"}}let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.dependencies?.["@contractspec/app.cli-contractspec"]!==void 0||Z.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 YW("npm install -D @contractspec/app.cli-contractspec",{cwd:W.workspaceRoot,timeout:60000}),{success:!0,message:"CLI added as dev dependency"}}catch(Y){return{success:!1,message:`Failed to install: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"cli",name:"Local Installation",status:"skip",message:"Could not check local installation"}}}i();import{DEFAULT_CONTRACTSRC as x1}from"@contractspec/lib.contracts-spec/workspace-config";import{join as U6,relative as L6}from"node:path";var O6="contractspec",S6="contractsrc.schema.json";function I6($){let W=$.replaceAll("\\","/");return W.startsWith(".")?W:`./${W}`}function Z0($){return I6(L6($.configRoot,U6($.workspaceRoot,"node_modules",O6,S6)))}var X0=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md"],z8={"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)"},U8=["core","connect","builder-managed","builder-local","builder-hybrid"],L8={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)"},O8={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.","builder-hybrid":"Core workspace setup plus Builder config for hybrid runtime with API and local defaults."};var Y0={connect:"**/.contractspec/connect/",verificationCache:"**/.contractspec/verification-cache.json"};function B0($){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 b$($){return $.preset??"core"}function S8($,W){if(W.length>0)return W;switch($){case"core":case"connect":case"builder-managed":case"builder-local":case"builder-hybrid":default:return X0}}function I8($){switch($){case"builder-local":return"local";case"builder-hybrid":return"hybrid";case"builder-managed":return"managed";default:return}}function M8($){switch($){case"builder-local":return"local_daemon_mvp";case"builder-hybrid":return"hybrid_mvp";case"builder-managed":return"managed_mvp";default:return}}function Kb($){return $.startsWith("builder-")}function _b($){return $==="connect"}function E8($){let W=b$($),j=M6($.projectName);switch(W){case"connect":return["contractspec validate","contractspec connect review list --json"];case"builder-managed":return[`contractspec builder init --workspace-id ${j} --preset managed-mvp`,`contractspec builder status --workspace-id ${j}`];case"builder-local":return[`contractspec builder init --workspace-id ${j} --preset local-daemon-mvp`,`contractspec builder local register --workspace-id ${j} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"builder-hybrid":return[`contractspec builder init --workspace-id ${j} --preset hybrid-mvp`,`contractspec builder local register --workspace-id ${j} --runtime-id ${$.builderLocalRuntimeId??"rt_local_daemon"} --granted-to ${$.builderLocalGrantedTo??"local:operator"}`];case"core":default:return["contractspec validate","contractspec doctor"]}}function M6($){return`ws-${($??"demo").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"demo"}`}function N8($){let W=b$($),j=[Y0.verificationCache];if(W==="connect")j.unshift(Y0.connect);return j}function u$($){let W=$.isMonorepo&&$.scope==="package",j=W&&$.packageRoot?$.packageRoot:$.workspaceRoot,A=E6($),Q=N6($);return{$schema:Z0({configRoot:j,workspaceRoot:$.workspaceRoot}),aiProvider:"claude",aiModel:"claude-sonnet-4-6",agentMode:"claude-code",outputDir:"./src",conventions:{operations:"contracts/operations",events:"contracts/events",presentations:"contracts/presentations",forms:"contracts/forms"},defaultOwners:$.defaultOwners??["@team"],defaultTags:[],formatter:{type:"biome"},ci:{checks:["structure","integrity","deps","doctor","docs","policy"],failOnWarnings:!1,uploadSarif:!0},versioning:{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},hooks:{"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},...A?{connect:A}:{},...Q?{builder:Q}:{},...W&&$.packageName?{package:$.packageName}:{}}}function BW($){let W=b$($),j={"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(W==="builder-managed"||W==="builder-hybrid")j["contractspec.api.baseUrl"]=$.builderApiBaseUrl??"https://api.contractspec.io";return j}function q0(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function R8(){return{mcpServers:{"contractspec-local":{command:"bunx",args:["contractspec-mcp"]}}}}function C8($){let W=$.projectName??"this project",A=$.isMonorepo&&$.scope==="package"&&$.packageRoot?`${$.packageRoot.split("/").slice(-2).join("/")}/src/contracts`:"src/contracts";return`# ContractSpec Development Rules
|
|
1490
|
+
|
|
1491
|
+
This project uses ContractSpec for spec-first development. Follow these guidelines when working with AI agents.
|
|
1492
|
+
|
|
1493
|
+
## Spec-First Principle
|
|
1494
|
+
|
|
1495
|
+
- **Always update contracts first** before changing implementation code.
|
|
1496
|
+
- Contracts are the source of truth for operations, events, and presentations.
|
|
1497
|
+
- Implementation code should be generated or derived from contracts.
|
|
1498
|
+
${$.isMonorepo?`
|
|
1499
|
+
## Monorepo Structure
|
|
1500
|
+
|
|
1501
|
+
This is a monorepo. Contracts may exist at:
|
|
1502
|
+
- Package level: \`packages/*/src/contracts/\`
|
|
1503
|
+
- Workspace level: \`src/contracts/\`
|
|
1504
|
+
|
|
1505
|
+
Check the appropriate level based on the feature scope.
|
|
1506
|
+
`:""}
|
|
1507
|
+
## Contract Locations
|
|
1508
|
+
|
|
1509
|
+
Contracts are located in:
|
|
1510
|
+
- \`${A}/operations/\` - Command and query specs
|
|
1511
|
+
- \`${A}/events/\` - Event specs
|
|
1512
|
+
- \`${A}/presentations/\` - UI presentation specs
|
|
1513
|
+
- \`${A}/features/\` - Feature module specs
|
|
1514
|
+
|
|
1515
|
+
## When Making Changes
|
|
1516
|
+
|
|
1517
|
+
1. **Before coding**: Check if a contract exists for the feature.
|
|
1518
|
+
2. **If contract exists**: Update the contract first, then regenerate code.
|
|
1519
|
+
3. **If no contract**: Create a new contract using \`contractspec create\`.
|
|
1520
|
+
4. **After changes**: Validate with \`contractspec validate\`.
|
|
1521
|
+
|
|
1522
|
+
## Key Commands
|
|
1523
|
+
|
|
1524
|
+
- \`contractspec create\` - Scaffold new specs
|
|
1525
|
+
- \`contractspec validate\` - Validate specs
|
|
1526
|
+
- \`contractspec build\` - Generate implementation code
|
|
1527
|
+
- \`contractspec integrity\` - Check contract health
|
|
1528
|
+
|
|
1529
|
+
## Contract Structure
|
|
1530
|
+
|
|
1531
|
+
Operations follow this pattern:
|
|
1532
|
+
\`\`\`typescript
|
|
1533
|
+
defineCommand({
|
|
1534
|
+
meta: { name: 'service.action', version: '1.0.0', ... },
|
|
1535
|
+
io: { input: InputSchema, output: OutputSchema },
|
|
1536
|
+
policy: { auth: 'user', ... },
|
|
1537
|
+
handler: async (args, ctx) => { ... }
|
|
1538
|
+
});
|
|
1539
|
+
\`\`\`
|
|
1540
|
+
|
|
1541
|
+
## Rules for ${W}
|
|
1542
|
+
|
|
1543
|
+
- All API endpoints must have a corresponding operation contract.
|
|
1544
|
+
- Events must be declared in contracts before being emitted.
|
|
1545
|
+
- UI components should reference presentation contracts.
|
|
1546
|
+
- Feature flags should be defined in feature modules.
|
|
1547
|
+
`}function D8($){let W=$.projectName??"this project",j=$.isMonorepo&&$.scope==="package",A=b$($),Q=j&&$.packageName?`${$.packageName} package`:W,Z="src/contracts",X=$.isMonorepo?j?`
|
|
1548
|
+
## Monorepo Scope
|
|
1549
|
+
|
|
1550
|
+
This guide is scoped to the current package.
|
|
1551
|
+
- Prefer package-local contracts under \`src/contracts/\`
|
|
1552
|
+
- Check workspace-level rules only when a change crosses package boundaries.
|
|
1553
|
+
`:`
|
|
1554
|
+
## Monorepo Scope
|
|
1555
|
+
|
|
1556
|
+
This guide is scoped to the workspace root.
|
|
1557
|
+
- Shared contracts may live in multiple packages under \`packages/*/src/contracts/\`
|
|
1558
|
+
- Prefer the nearest package guide when working inside a specific package.
|
|
1559
|
+
`:"";return`# ContractSpec AI Guide
|
|
1560
|
+
|
|
1561
|
+
Scope: \`${Q}\`
|
|
1562
|
+
|
|
1563
|
+
This project uses ContractSpec for spec-first development. Treat contracts as the source of truth for implementation changes.
|
|
1564
|
+
|
|
1565
|
+
## Core Rules
|
|
1566
|
+
|
|
1567
|
+
- Update contracts before implementation code.
|
|
1568
|
+
- Validate contracts after changes with \`contractspec validate\`.
|
|
1569
|
+
- Regenerate derived artifacts before considering the work complete.
|
|
1570
|
+
- Prefer existing package-local guides and READMEs when working in a nested package.
|
|
1571
|
+
${X}
|
|
1572
|
+
## Contract Locations
|
|
1573
|
+
|
|
1574
|
+
- \`src/contracts/operations/\` - command and query specs
|
|
1575
|
+
- \`src/contracts/events/\` - domain and integration events
|
|
1576
|
+
- \`src/contracts/presentations/\` - UI presentation contracts
|
|
1577
|
+
- \`src/contracts/features/\` - feature module contracts
|
|
1578
|
+
|
|
1579
|
+
## Recommended Workflow
|
|
1580
|
+
|
|
1581
|
+
1. Check whether a contract already exists for the change.
|
|
1582
|
+
2. Update or create the contract first.
|
|
1583
|
+
3. Run validation and generation commands.
|
|
1584
|
+
4. Review downstream code and tests affected by the contract update.
|
|
1585
|
+
|
|
1586
|
+
## Key Commands
|
|
1587
|
+
|
|
1588
|
+
- \`contractspec create\` - scaffold a new contract
|
|
1589
|
+
- \`contractspec validate\` - validate contract integrity
|
|
1590
|
+
- \`contractspec build\` - generate implementation artifacts
|
|
1591
|
+
- \`contractspec doctor\` - verify workspace configuration
|
|
1592
|
+
|
|
1593
|
+
## Working Agreement
|
|
1594
|
+
|
|
1595
|
+
- Keep changes spec-first, deterministic, and reviewable.
|
|
1596
|
+
- Do not change generated outputs without updating their source contract.
|
|
1597
|
+
- When touching nested packages, prefer the nearest \`AGENTS.md\` and \`README.md\` as the local source of truth.
|
|
1598
|
+
|
|
1599
|
+
## Initialization Preset
|
|
1600
|
+
|
|
1601
|
+
- This workspace was initialized with the \`${A}\` setup preset.
|
|
1602
|
+
`}function E6($){if(b$($)!=="connect")return;return{...x1.connect,enabled:!0,adapters:{cursor:{enabled:!0,mode:"plugin"},codex:{enabled:!0,mode:"wrapper"},"claude-code":{enabled:!0,mode:"rule"}},studio:$.connectStudioEndpoint?{enabled:!0,mode:"review-bridge",endpoint:$.connectStudioEndpoint,queue:$.connectStudioQueue??"connect-default"}:x1.connect?.studio}}function N6($){let W=I8(b$($)),j=M8(b$($));if(!W||!j)return;let A=W==="managed"||W==="hybrid",Q=W==="local"||W==="hybrid";return{...x1.builder,enabled:!0,runtimeMode:W,bootstrapPreset:j,api:A?{baseUrl:$.builderApiBaseUrl??"https://api.contractspec.io",controlPlaneTokenEnvVar:$.builderControlPlaneTokenEnvVar??"CONTROL_PLANE_API_TOKEN"}:void 0,localRuntime:Q?{runtimeId:$.builderLocalRuntimeId??"rt_local_daemon",grantedTo:$.builderLocalGrantedTo??"local:operator",providerIds:$.builderLocalProviderIds??["provider.codex","provider.local.model"]}:void 0}}function qW(){let $=process.platform,W=process.env.HOME??process.env.USERPROFILE??"";switch($){case"darwin":return`${W}/Library/Application Support/Claude/claude_desktop_config.json`;case"win32":return`${process.env.APPDATA??W}/Claude/claude_desktop_config.json`;default:return`${W}/.config/claude/claude_desktop_config.json`}}function p($,W){let j={...$};for(let A of Object.keys(W)){let Q=$[A],Z=W[A];if(Q===void 0)j[A]=Z;else if(HW(Q)&&HW(Z))j[A]=p(Q,Z)}return j}function y1($,W){let j={...$};for(let A of Object.keys(W)){let Q=$[A],Z=W[A];if(Z===void 0)continue;if(HW(Q)&&HW(Z))j[A]=y1(Q,Z);else j[A]=Z}return j}function HW($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&Object.getPrototypeOf($)===Object.prototype}function r($){try{return JSON.parse($)}catch{return null}}function F($){return JSON.stringify($,null,2)+`
|
|
1603
|
+
`}async function v1($,W){let j=[];return j.push(await R6($,W)),j.push(await C6($,W)),j.push(await D6($,W)),j.push(await T6($,W)),j.push(await F6($,W)),j.push(await x6($,W)),j.push(await y6($,W)),j}async function R$($,W){if(W.packageRoot&&W.packageRoot!==W.workspaceRoot&&await $.exists($.join(W.packageRoot,".contractsrc.json")))return W.packageRoot;return W.workspaceRoot}async function R6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(await $.exists(j))return{category:"config",name:"Config File Exists",status:"pass",message:".contractsrc.json found"};return{category:"config",name:"Config File Exists",status:"fail",message:".contractsrc.json not found",fix:{description:"Create .contractsrc.json with defaults",apply:async()=>{try{let Q=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(Q)),{success:!0,message:"Created .contractsrc.json"}}catch(Q){return{success:!1,message:`Failed to create: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function C6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Valid JSON",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j);return JSON.parse(Q),{category:"config",name:"Config Valid JSON",status:"pass",message:".contractsrc.json is valid JSON"}}catch(Q){return{category:"config",name:"Config Valid JSON",status:"fail",message:".contractsrc.json is not valid JSON",details:Q instanceof Error?Q.message:String(Q),fix:{description:"Replace with valid default config",apply:async()=>{try{let X=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});return await $.writeFile(j,F(X)),{success:!0,message:"Replaced with valid config"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}}async function D6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Config Fields",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q),X=[];if(!Z.outputDir)X.push("outputDir");if(!Z.conventions)X.push("conventions");if(X.length===0)return{category:"config",name:"Config Fields",status:"pass",message:"All recommended fields present"};return{category:"config",name:"Config Fields",status:"warn",message:`Missing recommended fields: ${X.join(", ")}`,fix:{description:"Add missing fields with defaults",apply:async()=>{try{let Y=u$({workspaceRoot:W.workspaceRoot,interactive:!1,targets:[]});for(let B of X)if(Y[B]!==void 0)Z[B]=Y[B];return await $.writeFile(j,F(Z)),{success:!0,message:"Added missing fields"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"config",name:"Config Fields",status:"skip",message:"Could not parse config"}}}async function T6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Versioning Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.versioning)return{category:"config",name:"Versioning Config",status:"pass",message:Z.versioning.integrateWithChangesets===!0?"Versioning configured with Changesets integration":"Versioning configured"};return{category:"config",name:"Versioning Config",status:"warn",message:"Versioning configuration not found",details:"Consider adding versioning config for automated version bumps and changelog generation",fix:{description:"Add versioning configuration with defaults",apply:async()=>{try{return Z.versioning={autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0},await $.writeFile(j,F(Z)),{success:!0,message:"Added versioning configuration"}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"config",name:"Versioning Config",status:"skip",message:"Could not parse config"}}}async function F6($,W){let j=$.join(await R$($,W),".contractsrc.json");if(!await $.exists(j))return{category:"config",name:"Hooks Config",status:"skip",message:"Config file does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.hooks){let B=Z.hooks;return{category:"config",name:"Hooks Config",status:"pass",message:`${Object.keys(B).length} git hook(s) configured`}}let X=$.join(W.workspaceRoot,".husky");if(await $.exists(X))return{category:"config",name:"Hooks Config",status:"warn",message:"Husky detected but no hooks configured in .contractsrc.json",details:"Add hooks config to run contractspec checks from git hooks",fix:{description:"Add pre-commit hooks configuration",apply:async()=>{try{return Z.hooks={"pre-commit":["contractspec validate **/*.operation.ts","contractspec integrity check"]},await $.writeFile(j,F(Z)),{success:!0,message:"Added hooks configuration"}}catch(B){return{success:!1,message:`Failed: ${B instanceof Error?B.message:String(B)}`}}}}};return{category:"config",name:"Hooks Config",status:"pass",message:"No hooks configured (optional)"}}catch{return{category:"config",name:"Hooks Config",status:"skip",message:"Could not parse config"}}}async function x6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q==="core")return{category:"config",name:"Setup Preset",status:"pass",message:"Core setup inferred from workspace config"};if(Q==="connect"){let Y=[A.connect?.storage?.root?null:"storage.root",A.connect?.storage?.contextPack?null:"storage.contextPack",A.connect?.storage?.planPacket?null:"storage.planPacket",A.connect?.storage?.patchVerdict?null:"storage.patchVerdict"].filter((H)=>H!==null),B=A.connect?.studio?.enabled&&A.connect?.studio?.mode==="review-bridge"&&!A.connect?.studio?.endpoint;if(Y.length===0&&!B)return{category:"config",name:"Setup Preset",status:"pass",message:"Connect setup inferred and artifact storage is configured"};return{category:"config",name:"Setup Preset",status:"fail",message:`Connect preset is incomplete: ${[...Y,...B?["connect.studio.endpoint"]:[]].join(", ")}`}}let Z=[],X=A.builder?.api?.controlPlaneTokenEnvVar;if((Q==="builder-managed"||Q==="builder-hybrid")&&!A.builder?.api?.baseUrl)Z.push("builder.api.baseUrl");if((Q==="builder-managed"||Q==="builder-hybrid")&&!X)Z.push("builder.api.controlPlaneTokenEnvVar");if((Q==="builder-managed"||Q==="builder-hybrid")&&X&&!process.env[X])Z.push(`env:${X}`);if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.runtimeId)Z.push("builder.localRuntime.runtimeId");if((Q==="builder-local"||Q==="builder-hybrid")&&!A.builder?.localRuntime?.grantedTo)Z.push("builder.localRuntime.grantedTo");return{category:"config",name:"Setup Preset",status:Z.length===0?"pass":"warn",message:Z.length===0?`Builder preset inferred (${Q}) and required config is present`:`Builder preset inferred (${Q}) but setup is missing ${Z.join(", ")}`}}async function y6($,W){let j=await R$($,W),A=await m($,j),Q=B0(A);if(Q!=="builder-managed"&&Q!=="builder-hybrid")return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder managed/hybrid preset is not enabled"};let Z=$.join(j,".vscode","settings.json"),X=A.builder?.api?.baseUrl;if(!X)return{category:"config",name:"VS Code API Mirror",status:"skip",message:"Builder API base URL is not configured"};let Y=await $.readFile(Z).catch(()=>""),B=Y?r(Y):void 0;if(B?.["contractspec.api.baseUrl"]===X)return{category:"config",name:"VS Code API Mirror",status:"pass",message:"VS Code API base URL matches Builder configuration"};return{category:"config",name:"VS Code API Mirror",status:"warn",message:"VS Code settings do not mirror builder.api.baseUrl",fix:{description:"Write the expected ContractSpec API base URL into .vscode/settings.json",apply:async()=>{try{let H=$.join(j,".vscode");if(!await $.exists(H))await $.mkdir(H);let V={...B??{},...BW({workspaceRoot:W.workspaceRoot,packageRoot:W.packageRoot,isMonorepo:W.isMonorepo,packageName:W.packageName,interactive:!1,preset:Q,targets:[],builderApiBaseUrl:X})};return await $.writeFile(Z,F(V)),{success:!0,message:"Updated VS Code settings mirror"}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}}}import{exec as v6}from"node:child_process";import{promisify as m6}from"node:util";var C$=m6(v6);async function m1($,W){let j=[];return j.push(await P6(W)),j.push(await k6(W)),j.push(await h6($,W)),j.push(await g6($,W)),j.push(await f6($,W)),j}async function P6($){try{let{stdout:W}=await C$("node --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Node.js",status:"pass",message:`Node.js ${W.trim()} available`}}catch{return{category:"deps",name:"Node.js",status:"fail",message:"Node.js not found",details:"Install Node.js from https://nodejs.org"}}}async function k6($){try{let{stdout:W}=await C$("bun --version",{cwd:$.workspaceRoot,timeout:5000});return{category:"deps",name:"Bun Runtime",status:"pass",message:`Bun ${W.trim()} available`}}catch{return{category:"deps",name:"Bun Runtime",status:"warn",message:"Bun not found (optional but recommended)",details:"Install Bun from https://bun.sh for faster execution"}}}async function h6($,W){let j=[{file:"bun.lockb",name:"bun"},{file:"pnpm-lock.yaml",name:"pnpm"},{file:"yarn.lock",name:"yarn"},{file:"package-lock.json",name:"npm"}],A=null;for(let{file:Q,name:Z}of j){let X=$.join(W.workspaceRoot,Q);if(await $.exists(X)){A=Z;break}}if(!A){let Q=$.join(W.workspaceRoot,".."),Z=$.join(W.workspaceRoot,"../.."),X=[Q,Z];for(let Y of X){for(let{file:B,name:q}of j){let H=$.join(Y,B);if(await $.exists(H)){A=q;break}}if(A)break}}if(!A)return{category:"deps",name:"Package Manager",status:"warn",message:"No lock file found",details:"Run npm install, yarn, pnpm install, or bun install"};try{return await C$(`${A} --version`,{cwd:W.workspaceRoot,timeout:5000}),{category:"deps",name:"Package Manager",status:"pass",message:`Using ${A}`}}catch{return{category:"deps",name:"Package Manager",status:"fail",message:`${A} detected but not available`,details:`Install ${A} or use a different package manager`}}}async function g6($,W){let j=$.join(W.workspaceRoot,"node_modules");if(await $.exists(j))return{category:"deps",name:"Dependencies Installed",status:"pass",message:"node_modules directory exists"};return{category:"deps",name:"Dependencies Installed",status:"fail",message:"node_modules not found",details:"Run your package manager install command",fix:{description:"Install dependencies",apply:async()=>{try{try{return await C$("bun install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function f6($,W){let j=$.join(W.workspaceRoot,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A),Z={...Q.dependencies,...Q.devDependencies};if("@contractspec/lib.contracts-spec"in Z)return{category:"deps",name:"ContractSpec Library",status:"pass",message:`@contractspec/lib.contracts-spec installed (${Z["@contractspec/lib.contracts-spec"]})`};if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"deps",name:"ContractSpec Library",status:"pass",message:"Monorepo root detected (library check skipped)",details:"Run doctor in specific packages to verify dependencies"};return{category:"deps",name:"ContractSpec Library",status:"fail",message:"@contractspec/lib.contracts-spec not installed",details:'Run "contractspec quickstart" to install required packages',fix:{description:"Install @contractspec/lib.contracts-spec and dependencies",apply:async()=>{try{try{return await C$("bun add @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with bun"}}catch{return await C$("npm install @contractspec/lib.contracts-spec zod",{cwd:W.workspaceRoot,timeout:120000}),{success:!0,message:"Installed with npm"}}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}catch{return{category:"deps",name:"ContractSpec Library",status:"skip",message:"Could not read package.json"}}}async function P1($,W){let j=await XW($,W.workspaceRoot);if(j.length===0)return[{category:"docs",name:"Same-File DocBlocks",status:"pass",message:"All analyzed packages follow the same-file DocBlock rules."}];return j.map((A)=>({category:"docs",name:`Same-File DocBlocks (${A.packageName})`,status:A.severity==="warning"?"warn":"fail",message:A.message,details:$.relative(W.workspaceRoot,A.file),context:{ruleId:A.ruleId,file:A.file,line:A.line,column:A.column,packageName:A.packageName}}))}import{isExampleFile as u6,isFeatureFile as d6,scanAllSpecsFromSource as n6,scanExampleSource as c6,scanFeatureSource as r6}from"@contractspec/module.workspace";function l6(){return{features:new Map,examples:new Map,appConfigs:new Map,workspaceConfigs:new Map}}async function VW($,W={}){let{fs:j,logger:A}=$,Q=l6(),Z=W.pattern??"**/*.{ts,tsx}";A.info("Scanning for contract layer files...");let X=await j.glob({pattern:Z});for(let B of X){if(B.includes("node_modules")||B.includes("/dist/"))continue;try{let q=await j.readFile(B);if(d6(B)){let H=r6(q,B);Q.features.set(H.key,H);continue}if(u6(B)){let H=c6(q,B);Q.examples.set(H.key,H);continue}if(B.includes(".app-config.")||B.includes(".blueprint.")){let H=n6(q,B);for(let V of H)if(V.specType==="app-config"&&V.key)Q.appConfigs.set(V.key,V)}}catch{}}try{let B=await j.glob({pattern:"**/.contractsrc.json"});for(let q of B){if(q.includes("node_modules"))continue;try{let H=await j.readFile(q),V=JSON.parse(H);Q.workspaceConfigs.set(q,{file:q,config:V,valid:!0,errors:[]})}catch(H){Q.workspaceConfigs.set(q,{file:q,config:{},valid:!1,errors:[H instanceof Error?H.message:"Parse error"]})}}}catch{}let Y={features:Q.features.size,examples:Q.examples.size,appConfigs:Q.appConfigs.size,workspaceConfigs:Q.workspaceConfigs.size,total:Q.features.size+Q.examples.size+Q.appConfigs.size+Q.workspaceConfigs.size};return A.info(`Discovered ${Y.features} features, ${Y.examples} examples, ${Y.appConfigs} app configs, ${Y.workspaceConfigs} workspace configs`),{inventory:Q,stats:Y}}function mb($){let W=[];for(let[j,A]of $.features)W.push({key:j,file:A.filePath,type:"feature"});for(let[j,A]of $.examples)W.push({key:j,version:A.version,file:A.filePath,type:"example"});for(let[j,A]of $.appConfigs)W.push({key:j,version:A.version,file:A.filePath,type:"app-config"});for(let[,j]of $.workspaceConfigs)W.push({key:j.file,file:j.file,type:"workspace-config"});return W}function GW($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}function k1($){if(!Array.isArray($))return[];return $.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean)}async function JW($,W){let j=$.join(W,"config/stability-policy.json");if(!await $.exists(j))return;try{let A=await $.readFile(j),Q=JSON.parse(A);return{version:typeof Q.version==="number"&&Number.isFinite(Q.version)?Q.version:1,criticalPackages:k1(Q.criticalPackages).map(GW),criticalFeatureKeys:k1(Q.criticalFeatureKeys),smokePackages:k1(Q.smokePackages)}}catch{return}}function T8($,W){let j=GW($);if(W?.criticalPackages.includes(j))return"critical";return"non-critical"}function F8($,W){return Boolean($&&W?.criticalFeatureKeys.includes($))}function d$($){return GW(`${GW($)}/config/stability-policy.json`)}async function h1($,W){let j=[],A=await JW($,W.workspaceRoot),Q=await VW({fs:$,logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},createProgress:()=>({start:()=>{},update:()=>{},succeed:()=>{},fail:()=>{},warn:()=>{},stop:()=>{},finish:()=>{}})}},{});return j.push(o6(Q.stats.features)),j.push(i6(Q.stats.examples)),j.push(p6(Q.inventory.features,A,W)),j.push(t6(Q.inventory.examples)),j.push(a6(Q.inventory.workspaceConfigs)),j}function o6($){if($>0)return{category:"layers",name:"Features Defined",status:"pass",message:`Found ${$} feature module(s)`};return{category:"layers",name:"Features Defined",status:"warn",message:"No feature modules found",details:"Create a .feature.ts file to organize your specs into features"}}function i6($){if($>0)return{category:"layers",name:"Examples Defined",status:"pass",message:`Found ${$} example(s)`};return{category:"layers",name:"Examples Defined",status:"skip",message:"No examples found (optional)",details:"Create an example.ts file to package reusable templates"}}function p6($,W,j){let A=[],Q=[];for(let[Z,X]of $)if(!(Boolean(X.owners?.length)||/owners\s*:\s*(?!\[\s*\])/.test(X.sourceBlock??"")))if(F8(Z,W))Q.push(Z);else A.push(Z);if(Q.length===0&&A.length===0)return{category:"layers",name:"Feature Owners",status:$.size>0?"pass":"skip",message:$.size>0?"All features have owners defined":"No features to check",context:$.size>0?{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:[],missingFeatures:[]}:void 0};return{category:"layers",name:"Feature Owners",status:Q.length>0?"fail":"warn",message:Q.length>0?`${Q.length} critical feature(s) missing owners`:`${A.length} feature(s) missing owners`,details:Q.length>0?`Critical features: ${Q.join(", ")}`:`Features: ${A.slice(0,3).join(", ")}${A.length>3?"...":""}`,context:{policyPath:W?d$(j.workspaceRoot):void 0,criticalMissingFeatures:Q,missingFeatures:A}}}function t6($){let W=[];for(let[j,A]of $)if(!A.entrypoints.packageName)W.push(j);if(W.length===0)return{category:"layers",name:"Example Entrypoints",status:$.size>0?"pass":"skip",message:$.size>0?"All examples have valid entrypoints":"No examples to check"};return{category:"layers",name:"Example Entrypoints",status:"fail",message:`${W.length} example(s) missing packageName`,details:`Examples: ${W.join(", ")}`}}function a6($){let W=[];for(let[,j]of $)if(!j.valid)W.push(j.file);if($.size===0)return{category:"layers",name:"Workspace Configs",status:"skip",message:"No .contractsrc.json files found"};if(W.length===0)return{category:"layers",name:"Workspace Configs",status:"pass",message:`All ${$.size} workspace config(s) are valid`};return{category:"layers",name:"Workspace Configs",status:"fail",message:`${W.length} workspace config(s) invalid`,details:`Files: ${W.join(", ")}`}}async function g1($,W){let j=[];return j.push(await s6($,W)),j.push(await e6($,W)),j.push(await $7($,W)),j}async function s6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(await $.exists(j))return{category:"mcp",name:"Cursor MCP Config",status:"pass",message:".cursor/mcp.json found"};return{category:"mcp",name:"Cursor MCP Config",status:"warn",message:".cursor/mcp.json not found",details:"MCP integration with Cursor will not work",fix:{description:"Create .cursor/mcp.json",apply:async()=>{try{let Q=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Q))await $.mkdir(Q);let Z=q0();return await $.writeFile(j,F(Z)),{success:!0,message:"Created .cursor/mcp.json"}}catch(Q){return{success:!1,message:`Failed: ${Q instanceof Error?Q.message:String(Q)}`}}}}}}async function e6($,W){let j=$.join(W.workspaceRoot,".cursor","mcp.json");if(!await $.exists(j))return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Cursor MCP config does not exist"};try{let Q=await $.readFile(j),Z=JSON.parse(Q);if(Z.mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"MCP Server Registered",status:"pass",message:"ContractSpec MCP server is registered"};return{category:"mcp",name:"MCP Server Registered",status:"fail",message:"ContractSpec MCP server not registered",fix:{description:"Register ContractSpec MCP server",apply:async()=>{try{let Y=q0(),B=p(Z,Y);return await $.writeFile(j,F(B)),{success:!0,message:"Registered MCP server"}}catch(Y){return{success:!1,message:`Failed: ${Y instanceof Error?Y.message:String(Y)}`}}}}}}catch{return{category:"mcp",name:"MCP Server Registered",status:"skip",message:"Could not parse Cursor MCP config"}}}async function $7($,W){let j=qW();try{if(!await $.exists(j))return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Claude Desktop config not found (optional)"};let Q=await $.readFile(j);if(JSON.parse(Q).mcpServers?.["contractspec-local"]!==void 0)return{category:"mcp",name:"Claude Desktop MCP",status:"pass",message:"ContractSpec registered in Claude Desktop"};return{category:"mcp",name:"Claude Desktop MCP",status:"warn",message:"ContractSpec not registered in Claude Desktop",details:"Optional: Run setup to configure Claude Desktop"}}catch{return{category:"mcp",name:"Claude Desktop MCP",status:"skip",message:"Could not check Claude Desktop config"}}}var W7=["**/*.{test,spec}.{ts,tsx,js,jsx,mts,cts}"],x8=["**/node_modules/**","**/dist/**","**/.next/**","**/.turbo/**","**/coverage/**"];function j7($){if(!$||typeof $!=="object")return{};return Object.entries($).reduce((W,[j,A])=>{if(typeof A==="string")W[j]=A;return W},{})}function A7($){return Object.entries($).some(([W,j])=>{return W.startsWith("test")&&/pass[- ]with[- ]no[- ]tests/i.test(j)})}async function Q7($,W,j){let A=await $.glob({pattern:"packages/**/package.json",cwd:W,ignore:x8}),Q=[];for(let Z of A){let X=$.dirname(Z),Y=$.relative(W,X);try{let B=JSON.parse(await $.readFile(Z)),q=j7(B.scripts),H=await $.glob({patterns:W7,cwd:X,ignore:x8});Q.push({packageName:B.name??Y,packagePath:Y.replace(/\\/g,"/"),hasBuildScript:typeof q.build==="string",hasTypecheckScript:typeof q.typecheck==="string",hasLintScript:typeof q.lint==="string"||typeof q["lint:check"]==="string",hasTestScript:typeof q.test==="string",usesPassWithNoTests:A7(q),testFileCount:H.length,tier:T8(Y,j)})}catch{continue}}return Q}function Z7($){let W=[];if(!$.hasBuildScript)W.push({code:"critical-missing-build-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing build script"});if(!$.hasTypecheckScript)W.push({code:"critical-missing-typecheck-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing typecheck script"});if(!$.hasLintScript)W.push({code:"critical-missing-lint-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing lint or lint:check script"});if(!$.hasTestScript)W.push({code:"critical-missing-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Missing test script"});if($.testFileCount===0)W.push({code:"critical-missing-test-files",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"No real test files found"});if($.usesPassWithNoTests)W.push({code:"critical-pass-with-no-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Uses pass-with-no-tests in a critical package"});return W}function X7($){let W=[];if($.testFileCount>0&&!$.hasTestScript)W.push({code:"tests-without-test-script",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has test files on disk but no test script"});if($.hasBuildScript&&$.testFileCount===0&&!$.hasTestScript)W.push({code:"build-without-tests",tier:$.tier,packageName:$.packageName,packagePath:$.packagePath,message:"Has a build script but no test script or test files"});return W}async function y8($,W,j){let A=await Q7($,W,j),Q=[];for(let X of A){if(X.tier==="critical")Q.push(...Z7(X));Q.push(...X7(X))}let Z=A.filter((X)=>X.tier==="critical").map((X)=>({packageName:X.packageName,packagePath:X.packagePath,hasBuildScript:X.hasBuildScript,hasTypecheckScript:X.hasTypecheckScript,hasLintScript:X.hasLintScript,hasTestScript:X.hasTestScript,usesPassWithNoTests:X.usesPassWithNoTests,testFileCount:X.testFileCount}));return{findings:Q,criticalPackages:Z}}function m8($){return $.slice(0,5).map((W)=>`${W.packagePath}: ${W.message}`).join("; ")}function v8($,W,j,A){if(W.length===0)return{category:"workspace",name:$,status:"pass",message:A,context:{findings:[]}};let Q=W.filter((Z)=>{return Z.tier==="critical"||j.has(Z.code)});return{category:"workspace",name:$,status:Q.length>0?"fail":"warn",message:`${W.length} package issue(s) found`,details:m8(W),context:{findings:W}}}async function P8($,W){let j=await JW($,W.workspaceRoot);if(!j)return[];let A=await y8($,W.workspaceRoot,j),Q=new Set(["critical-missing-build-script","critical-missing-typecheck-script","critical-missing-lint-script","critical-missing-test-script","critical-missing-test-files","critical-pass-with-no-tests"]),Z=A.findings.filter((B)=>Q.has(B.code)),X=A.findings.filter((B)=>B.code==="tests-without-test-script"),Y=A.findings.filter((B)=>B.code==="build-without-tests");return[{category:"workspace",name:"Critical Package Gates",status:Z.length>0?"fail":"pass",message:Z.length>0?`${Z.length} critical package gate failure(s)`:`All ${A.criticalPackages.length} critical packages meet build, lint, typecheck, and test requirements`,details:Z.length>0?m8(Z):W.verbose?`Policy: ${d$(W.workspaceRoot)}`:void 0,context:{policyPath:d$(W.workspaceRoot),criticalPackages:A.criticalPackages,findings:Z}},v8("Package Test Scripts",X,new Set,"All tested packages expose a test script"),v8("Buildable Packages Without Tests",Y,new Set,"All buildable packages have tests or explicit test scripts")]}var Y7=["src/contracts","contracts","src/specs","specs"];async function f1($,W){let j=[];return j.push(B7(W)),j.push(await q7($,W)),j.push(await H7($,W)),j.push(await V7($,W)),j.push(await J7($,W)),j.push(...await P8($,W)),j}function B7($){if($.isMonorepo){let W=$.packageName?` in package "${$.packageName}"`:"",j=$.packageRoot!==$.workspaceRoot?` (package root: ${$.packageRoot})`:"";return{category:"workspace",name:"Monorepo Detection",status:"pass",message:`Monorepo detected${W}`,details:$.verbose?`Workspace root: ${$.workspaceRoot}${j}`:void 0}}return{category:"workspace",name:"Monorepo Detection",status:"pass",message:"Single project (not a monorepo)"}}async function q7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot];for(let A of j){let Q=$.join(A,"package.json");if(await $.exists(Q))return{category:"workspace",name:"Valid Workspace",status:"pass",message:"package.json found",details:W.verbose&&W.isMonorepo?`Found at: ${A}`:void 0}}return{category:"workspace",name:"Valid Workspace",status:"fail",message:"No package.json found",details:"This does not appear to be a Node.js/TypeScript project"}}async function H7($,W){let j=W.isMonorepo?[W.packageRoot,W.workspaceRoot]:[W.workspaceRoot],A=W.isMonorepo?W.packageRoot:W.workspaceRoot;for(let X of j)for(let Y of Y7){let B=$.join(X,Y);if(await $.exists(B)){let q=X===W.packageRoot?"package":"workspace";return{category:"workspace",name:"Contracts Directory",status:"pass",message:`Contracts directory found: ${Y}`,details:W.isMonorepo?`Found at ${q} level`:void 0}}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contracts Directory",status:"pass",message:"Monorepo root detected (contracts expected in packages)"};let Q=W.isMonorepo?"src/contracts":"src/contracts",Z=W.isMonorepo?` in package "${W.packageName??W.packageRoot}"`:"";return{category:"workspace",name:"Contracts Directory",status:"warn",message:"No contracts directory found",details:`Create ${Q}/${Z} to organize your specs`,fix:{description:`Create ${Q}/ directory${Z}`,apply:async()=>{try{let X=$.join(A,"src","contracts");return await $.mkdir(X),{success:!0,message:`Created ${Q}/`}}catch(X){return{success:!1,message:`Failed: ${X instanceof Error?X.message:String(X)}`}}}}}}async function V7($,W){try{let j=["**/*.operation.ts","**/*.event.ts","**/*.presentation.ts","**/*.feature.ts"],A=W.isMonorepo?W.packageRoot:W.workspaceRoot,Q=await $.glob({patterns:j,ignore:["node_modules/**","dist/**"],cwd:A});if(Q.length>0){let X=W.isMonorepo?" (in current package)":"";return{category:"workspace",name:"Contract Files",status:"pass",message:`Found ${Q.length} contract file(s)${X}`,details:W.verbose?Q.slice(0,5).join(", "):void 0}}if(W.isMonorepo&&W.packageRoot===W.workspaceRoot)return{category:"workspace",name:"Contract Files",status:"pass",message:"No contract files in root (expected in packages)"};return{category:"workspace",name:"Contract Files",status:"warn",message:W.isMonorepo?`No contract files found in package "${W.packageName??"current"}"`:"No contract files found",details:'Create specs using "contractspec create" or VS Code command'}}catch{return{category:"workspace",name:"Contract Files",status:"skip",message:"Could not search for contract files"}}}async function G7($,W){if(W.isMonorepo&&W.packageRoot!==W.workspaceRoot){let A=$.join(W.packageRoot,".contractsrc.json");if(await $.exists(A))return{path:A,root:W.packageRoot,level:"package"}}let j=$.join(W.workspaceRoot,".contractsrc.json");if(await $.exists(j))return{path:j,root:W.workspaceRoot,level:"workspace"};return null}async function J7($,W){try{let j=await G7($,W);if(!j)return{category:"workspace",name:"Output Directory",status:"skip",message:W.isMonorepo?"No config file found at package or workspace level":"No config file to check output directory"};let A=await $.readFile(j.path),Q=JSON.parse(A),Z=Q.outputDir??"./src",X=$.join(j.root,Z),Y=W.isMonorepo?` (${j.level} level)`:"";if(await $.exists(X))return{category:"workspace",name:"Output Directory",status:"pass",message:`Output directory exists: ${Z}${Y}`,details:W.verbose?`Resolved to: ${X}`:void 0};let q=Z==="./src"||Z==="src",H=Array.isArray(Q.packages)&&Q.packages.length>0;if(W.isMonorepo&&W.packageRoot===W.workspaceRoot&&q&&(H||j.level==="workspace"))return{category:"workspace",name:"Output Directory",status:"pass",message:"Monorepo root detected (using package directories)",details:W.verbose?`Resolved default output to packages via ${j.path}`:void 0};return{category:"workspace",name:"Output Directory",status:"warn",message:`Output directory not found: ${Z}${Y}`,details:W.verbose?`Expected at: ${X}`:void 0,fix:{description:`Create ${Z} directory`,apply:async()=>{try{return await $.mkdir(X),{success:!0,message:`Created ${Z}`}}catch(V){return{success:!1,message:`Failed: ${V instanceof Error?V.message:String(V)}`}}}}}}catch{return{category:"workspace",name:"Output Directory",status:"skip",message:"Could not check output directory"}}}var k8=["cli","config","mcp","deps","docs","workspace","ai","layers"],h8={cli:"CLI Installation",config:"Configuration Files",mcp:"MCP Server",deps:"Dependencies",docs:"DocBlock Ownership",workspace:"Workspace Structure",ai:"AI Provider",layers:"Contract Layers"};var b7={checks:{runCliChecks:F1,runConfigChecks:v1,runMcpChecks:g1,runDepsChecks:m1,runDocChecks:P1,runWorkspaceChecks:f1,runAiChecks:T1,runLayerChecks:h1},workspace:{findWorkspaceRoot:D,findPackageRoot:f,isMonorepo:e$,getPackageName:I$}},w7={confirm:async()=>!1,input:async()=>""};async function g8($,W,j=w7,A=b7){let{fs:Q,logger:Z}=$,X=W.categories??k8,{checks:Y,workspace:B}=A,q=B.findWorkspaceRoot(W.workspaceRoot),H=B.findPackageRoot(W.workspaceRoot),V=B.isMonorepo(q),G=V?B.getPackageName(H):void 0,J={workspaceRoot:q,packageRoot:H,isMonorepo:V,packageName:G,verbose:W.verbose??!1};if(V){let U=G?` (package: ${G})`:"";Z.info(`Detected monorepo${U}`)}let b=[];for(let U of X){if(W.skipAi&&U==="ai")continue;Z.info(`Checking ${h8[U]}...`);let O=await K7(U,Q,J,j,Y);for(let K of O){if(K.fix&&(K.status==="fail"||K.status==="warn")){if(W.autoFix?!0:await j.confirm(`Fix "${K.name}"? ${K.fix.description}`)){Z.info(`Applying fix: ${K.fix.description}`);let I=await K.fix.apply();if(I.success)Z.info(`✓ ${I.message}`),K.status="pass",K.message=`Fixed: ${I.message}`,K.fix=void 0;else Z.warn(`✗ ${I.message}`)}}b.push(K)}}let w=b.filter((U)=>U.status==="pass").length,L=b.filter((U)=>U.status==="warn").length,z=b.filter((U)=>U.status==="fail").length,S=b.filter((U)=>U.status==="skip").length;return{checks:b,passed:w,warnings:L,failures:z,skipped:S,healthy:z===0}}async function K7($,W,j,A,Q){switch($){case"cli":return Q.runCliChecks(W,j);case"config":return Q.runConfigChecks(W,j);case"mcp":return Q.runMcpChecks(W,j);case"deps":return Q.runDepsChecks(W,j);case"docs":return Q.runDocChecks(W,j);case"workspace":return Q.runWorkspaceChecks(W,j);case"ai":return Q.runAiChecks(W,j,A);case"layers":return Q.runLayerChecks(W,j);default:return[]}}function Hw($){let W=[];if(W.push(""),W.push("=== Health Check Summary ==="),W.push(""),$.healthy)W.push("✓ All checks passed!");else W.push("✗ Some issues found");return W.push(""),W.push(` Passed: ${$.passed}`),W.push(` Warnings: ${$.warnings}`),W.push(` Failures: ${$.failures}`),W.push(` Skipped: ${$.skipped}`),W.join(`
|
|
1604
|
+
`)}function Vw($){let j=`${$.status==="pass"?"✓":$.status==="warn"?"⚠":$.status==="fail"?"✗":"○"} ${$.name}: ${$.message}`;if($.details)j+=`
|
|
1605
|
+
${$.details}`;if($.fix)j+=`
|
|
1606
|
+
Fix available: ${$.fix.description}`;return j}async function u1($,W){let j=[],A=W.workspaceRoot??process.cwd(),Q=await g8($,{workspaceRoot:A,skipAi:!0,categories:["cli","config","deps","workspace","layers"]});for(let Z of Q.checks)if(Z.status==="fail")j.push({ruleId:`doctor-${Z.category}-${Z.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"error",message:`${Z.name}: ${Z.message}`,category:"doctor",context:{details:Z.details,...Z.context??{}}});else if(Z.status==="warn")j.push({ruleId:`doctor-${Z.category}-${Z.name.toLowerCase().replace(/\s+/g,"-")}`,severity:"warning",message:`${Z.name}: ${Z.message}`,category:"doctor",context:{details:Z.details,...Z.context??{}}});return j}i();import{mkdtemp as x7,rm as y7}from"node:fs/promises";import{tmpdir as v7}from"node:os";import H0 from"path";import{DEFAULT_CONTRACTSRC as M7}from"@contractspec/lib.contracts-spec/workspace-config";import{findAuthoringTargetDefinition as E7}from"@contractspec/module.workspace";import N7 from"path";import{packageDocBlocks as _7}from"@contractspec/lib.contracts-spec/docs";import{buildPackageDocManifest as z7,convertSpecToDocBlock as U7,extractModuleDocData as L7,loadSpecFromSource as O7,scanAllSpecsFromSource as S7,scanSpecSource as I7}from"@contractspec/module.workspace";import n1 from"path";import{dirname as f8,sep as bW}from"path";class d1{adapters;modules=[];initialized=!1;constructor($){this.adapters=$}initialize($){this.modules=[];for(let W of $){let j;if(W.specType==="app-config")j="app-config";else if(W.specType==="example")j="example";else if(W.specType==="feature")j="feature";if(j&&W.key){let A=f8(W.filePath);this.modules.push({type:j,key:W.key,dirPath:A})}}this.initialized=!0}resolve($){if(!this.initialized)throw Error("ModuleResolver must be initialized before use");let W=f8($),j=this.modules.filter((A)=>{let Q=A.dirPath.endsWith(bW)?A.dirPath:A.dirPath+bW;return(W.endsWith(bW)?W:W+bW).startsWith(Q)||W===A.dirPath});if(j.length===0)return;return j.sort((A,Q)=>{let Z={"app-config":3,example:2,feature:1},X=Z[A.type],Y=Z[Q.type];if(X!==Y)return Y-X;return Q.dirPath.length-A.dirPath.length}),j[0]}}async function d8($,W,j){let{fs:A,logger:Q}=j,Z=[];if(Q.info(`Generating docs for ${$.length} files...`),W.outputDir)await A.mkdir(W.outputDir);let X=new d1(j),Y=[];for(let q of $)try{let H=await A.readFile(q),V=S7(H,q);if(V.length>0)Y.push(...V);else{let G=I7(H,q);if(G.specType!=="unknown")Y.push(G)}}catch(H){}X.initialize(Y);let B=await n8($,j);for(let q of B)if(Z.push(q.entry.block),Q.debug(`Loaded authored doc ${q.entry.id}`),W.outputDir)await u8(q.entry.block,q.filePath,W.outputDir,X,A);for(let q of $)try{let H=await O7(q);if(!H?.length){Q.warn(`Could not parse spec from ${q}`);continue}for(let V of H){let G=U7(V,{rootPath:W.rootPath});if(Z.push(G),Q.debug(`Generated doc for ${G.id}`),!W.outputDir)continue;await u8(G,q,W.outputDir,X,A)}}catch(H){Q.error(`Error processing ${q}: ${H instanceof Error?H.message:String(H)}`)}if(W.outputDir)Q.info(`Wrote ${Z.length} doc files to ${W.outputDir}`);return{blocks:Z,count:Z.length}}async function Ow($,W){return(await n8($,W)).map(({entry:A})=>A.block)}function Sw($,W){return _7(z7({packageName:$,srcRoot:W}))}async function n8($,W){let j=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z)),A=[];for(let Q of j){let Z=await W.fs.readFile(Q),X=Q.replace(/\\/g,"/").replace(/\.[cm]?[jt]sx?$/,""),Y=L7(Z,Q,X);for(let B of Y.entries)A.push({entry:B,filePath:Q})}return A}async function u8($,W,j,A,Q){let Z=A.resolve(W),X=Z?n1.join(j,Z.key):n1.join(j,"_common");await Q.mkdir(X);let Y=n1.join(X,`${$.id}.md`),B=`<!-- @generated - This file was generated by ContractSpec. Do not edit manually. -->
|
|
1607
|
+
|
|
1608
|
+
${$.body}`;await Q.writeFile(Y,B)}async function c8($,W,j,A,Q={}){let Z=Q.config,X=await QW($,{cwd:Q.specSearchRoot,config:Z,pattern:Q.specPattern??C7(W,Q)});if(X.length===0)return{specsCount:0,docsCount:0,materializedCount:0};let Y=N7.join(D7(j,Z),"docs"),B=await d8(X.map((H)=>H.filePath),{outputDir:Y,format:"markdown",rootPath:A},$),q=0;for(let H of X){let V=R7(H);if(!V||V.materialization==="none"||V.materialization==="docs")continue;let G=await f$(H.filePath,$,Z??M7,{targets:L1(H.specType,{includeTests:Boolean(Q.includeRuntimeTests)}),outputDir:Z?.outputDir??"./src",overwrite:!1});q+=G.results.filter((J)=>J.success).length}return{specsCount:X.length,docsCount:B.count,materializedCount:q}}function R7($){return E7($.specType)}function C7($,W){if(W.config&&!W.specPattern)return;if(W.scanAllSpecs)return W.specPattern;return $?`${c1($)}/**/*.ts`:void 0}function D7($,W){let j=(W?.connect?.policy?.generatedPaths??[]).map(F7).filter(Boolean);if(j.length>0)return j[0];if(W?.outputDir&&W.outputDir!=="./src")return c1(W.outputDir);return $}function T7($){return c1($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function F7($){let W=T7($);return W.endsWith("/docs")?W.replace(/\/docs$/,""):W}function c1($){return $.replaceAll("\\","/").replace(/^\.\//,"")}async function wW($,W,j,A={}){let Q=await x7(H0.join(v7(),"contractspec-drift-"));try{await c8($,W,Q,A.rootPath,A.generation);let Z=[],X=await import("node:fs/promises");async function Y(G){let J=await X.readdir(G,{withFileTypes:!0}),b=[];for(let w of J){let L=H0.resolve(G,w.name);if(w.isDirectory())b.push(...await Y(L));else b.push(L)}return b}let B=async(G)=>{if(!await X.stat(G).catch(()=>!1))return[];return(await Y(G)).map((b)=>H0.relative(G,b)).sort()},q=await B(Q),H=await B(j),V=new Set([...q,...H]);for(let G of V){if(!H.includes(G)){Z.push(G);continue}if(!q.includes(G)){Z.push(G);continue}let J=await X.readFile(H0.join(Q,G)),b=await X.readFile(H0.join(j,G));if(!J.equals(b))Z.push(G)}return{hasDrift:Z.length>0,files:Z}}finally{await y7(Q,{recursive:!0,force:!0})}}async function r1($,W){let{fs:j,logger:A}=$,Q=[],Z=await m(j);if(!Z.outputDir)return A.info("No outputDir configured, skipping drift checks"),Q;let X="./contracts",Y=Z.outputDir;if(!await j.exists(Y))return A.info("Generated directory does not exist, skipping drift checks"),Q;try{let B=await wW($,X,Y);if(B.hasDrift)for(let q of B.files)Q.push({ruleId:"drift-detected",severity:"error",message:`Drift detected: generated file is out of sync with spec: ${q}`,category:"drift",file:`${Y}/${q}`,context:{file:q}})}catch(B){A.warn("Drift detection failed",{error:B instanceof Error?B.message:String(B)})}return Q}i();function m7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function P7($){return $.split(/[-_.]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}async function KW($,W,j,A={}){let{fs:Q}=W,Z=[],X=[],Y=$.key??Q.basename($.filePath).replace(/\.[jt]s$/,""),B=A.outputDir??j.outputDir??"./src",q=m7(Y),H={};if($.specType==="operation")H.handlerPath=Q.join(B,"handlers",`${q}.handler.ts`),H.handlerTestPath=Q.join(B,"handlers",`${q}.handler.test.ts`);if($.specType==="presentation")H.componentPath=Q.join(B,"components",`${q}.tsx`),H.componentTestPath=Q.join(B,"components",`${q}.test.tsx`);if($.specType==="form")H.formPath=Q.join(B,"forms",`${q}.form.tsx`),H.formTestPath=Q.join(B,"forms",`${q}.form.test.tsx`);if(A.checkHandlers&&H.handlerPath)if(!await Q.exists(H.handlerPath))Z.push(`Missing handler file: ${H.handlerPath}`);else{let G=await Q.readFile(H.handlerPath),J=`${P7(Y.split(".").pop()??Y)}Spec`,b=/ContractHandler<\s*typeof\s+\w+\s*>/.test(G),w=new RegExp(`typeof\\s+${J}\\b`).test(G);if(!b)X.push(`Handler does not appear to type itself as ContractHandler<typeof Spec>: ${H.handlerPath}`);else if(!w)X.push(`Handler ContractHandler typing does not reference expected spec var (${J}): ${H.handlerPath}`)}if(A.checkTests){let V=[H.handlerTestPath,H.componentTestPath,H.formTestPath].filter((G)=>typeof G==="string");for(let G of V)if(!await Q.exists(G))Z.push(`Missing test file: ${G}`)}return{valid:Z.length===0,errors:Z,warnings:X,expected:H}}async function l1($,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,{checkHandlers:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"handler-missing",severity:"warning",message:Y,category:"handlers",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"handler-warning",severity:"warning",message:Y,category:"handlers",file:Z.filePath})}return A}i();import{createHash as d7}from"crypto";import n7 from"path";var V0={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},k7={".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 h7($){let W=$.toLowerCase();for(let[j,A]of Object.entries(k7))if(W.endsWith(j))return A;if(W.includes("/handlers/"))return"handler";if(W.includes("/services/"))return"service";if(W.includes("/components/"))return"component";if(W.includes("/forms/"))return"form";if(W.includes("/hooks/"))return"hook";if(W.includes("/__tests__/"))return"test";return"other"}function r8($,W){let j=[],A=new Set,Q=(G,J,b)=>{let w=`${G}:${J}`;if(A.has(w))return;A.add(w),j.push({filePath:W,specKey:G,referenceType:J,lineNumber:b,inferredType:h7(W)})},Z=(G)=>{return $.substring(0,G).split(`
|
|
1609
|
+
`).length},X,Y=new RegExp(V0.contractHandler);while((X=Y.exec($))!==null)if(X[1])Q(X[1],"handler",Z(X.index));let B=new RegExp(V0.typeofSpec);while((X=B.exec($))!==null)if(X[1])Q(X[1],"typeof",Z(X.index));let q=new RegExp(V0.namedImport);while((X=q.exec($))!==null){let J=X[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(J)for(let b of J)Q(b,"import",Z(X.index))}let H=new RegExp(V0.defaultImport);while((X=H.exec($))!==null)if(X[1])Q(X[1],"import",Z(X.index));let V=new RegExp(V0.specAssignment);while((X=V.exec($))!==null)if(X[1])Q(X[1],"unknown",Z(X.index));return j}var l8=["**/*.ts(x)"];async function _W($,W,j={}){let{fs:A}=W,Q=j.includePatterns??l8,Z=j.excludePatterns??[...new Set([...S$,...Y$])],X=[];for(let Y of Q){let B=await A.glob({pattern:Y,ignore:Z});for(let q of B)try{let H=await A.readFile(q),G=r8(H,q).filter((J)=>J.specKey===$);X.push(...G)}catch{}}return X}async function ow($,W={}){let{fs:j}=$,A=W.includePatterns??l8,Q=W.excludePatterns??[...new Set([...S$,...Y$])],Z=new Map;for(let X of A){let Y=await j.glob({pattern:X,ignore:Q});for(let B of Y)try{let q=await j.readFile(B),H=r8(q,B);for(let V of H){let G=Z.get(V.specKey)??[];G.push(V),Z.set(V.specKey,G)}}catch{}}return Z}function g7($){return $.replace(/\./g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function o8($,W,j){let A=g7(W),Q=[];if($==="operation")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});if($==="presentation")Q.push({path:`${j}/components/${A}.tsx`,type:"component"}),Q.push({path:`${j}/components/${A}.test.tsx`,type:"test"});if($==="form")Q.push({path:`${j}/forms/${A}.form.tsx`,type:"form"}),Q.push({path:`${j}/forms/${A}.form.test.tsx`,type:"test"});if($==="event")Q.push({path:`${j}/handlers/${A}.handler.ts`,type:"handler"}),Q.push({path:`${j}/handlers/${A}.handler.test.ts`,type:"test"});return Q}import{Node as c,Project as f7,SyntaxKind as u7}from"ts-morph";function i8($){let W=[],A=new f7({useInMemoryFileSystem:!0}).createSourceFile("spec.ts",$),Q=(B)=>{if(!c.isObjectLiteralExpression(B))return;let q=B.getProperty("implementations");if(q&&c.isPropertyAssignment(q)){let H=q.getInitializer();if(H&&c.isArrayLiteralExpression(H)){for(let V of H.getElements())if(c.isObjectLiteralExpression(V)){let G,J,b,w=V.getProperty("path");if(w&&c.isPropertyAssignment(w)){let S=w.getInitializer();if(c.isStringLiteral(S))G=S.getLiteralText()}let L=V.getProperty("type");if(L&&c.isPropertyAssignment(L)){let S=L.getInitializer();if(c.isStringLiteral(S))J=S.getLiteralText()}let z=V.getProperty("description");if(z&&c.isPropertyAssignment(z)){let S=z.getInitializer();if(c.isStringLiteral(S))b=S.getLiteralText()}if(G&&J)W.push({path:G,type:J,description:b})}}}},Z=A.getDescendantsOfKind(u7.CallExpression);for(let B of Z){let q=B.getExpression().getText();if(["defineCommand","defineQuery","defineEvent","defineFeature"].includes(q)){let H=B.getArguments();if(H.length>0&&c.isObjectLiteralExpression(H[0]))return Q(H[0]),W}}let X=A.getVariableStatements();for(let B of X)if(B.isExported())for(let q of B.getDeclarations()){let H=q.getInitializer();if(H&&c.isObjectLiteralExpression(H)){if(H.getProperty("implementations"))return Q(H),W}}let Y=A.getExportAssignment((B)=>!B.isExportEquals());if(Y){let B=Y.getExpression();if(c.isObjectLiteralExpression(B))Q(B);else if(c.isAsExpression(B)&&c.isObjectLiteralExpression(B.getExpression()))Q(B.getExpression())}return W}function p8($){if($.length===0)return"missing";let W=$.filter((Q)=>Q.exists),j=$.filter((Q)=>Q.type!=="test");if(W.filter((Q)=>Q.type!=="test").length===0)return"missing";if($.every((Q)=>Q.exists))return"implemented";return"partial"}function sw($){let W=$.filter((Q)=>Q.status==="implemented").length,j=$.filter((Q)=>Q.status==="partial").length,A=$.filter((Q)=>Q.status==="missing").length;return{total:$.length,implemented:W,partial:j,missing:A,coverage:$.length>0?Math.round(W/$.length*100):100}}var c7={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function t8($){return d7("sha256").update($).digest("hex")}async function r7($,W,j,A={},Q){let Z={...c7,...A},X=Z.computeHashes?t8($.sourceBlock||""):void 0,Y=$.key??n7.basename($.filePath).replace(/\.[jt]s$/,""),B=$.version??"1.0.0",{fs:q}=W,H=[],V=new Set,G=async(b,w,L,z)=>{if(V.has(b))return;V.add(b);let S=await q.exists(b),U=void 0,O=void 0;if(S&&Z.computeHashes)try{U=await q.readFile(b),O=t8(U)}catch{}H.push({path:b,type:w,source:L,exists:S,implementationSourceContent:U,implementationSourceHash:O,description:z})};if(Z.includeExplicit&&$.sourceBlock){if(Q)Q.suffixText="Discover explicit implementations";let b=i8($.sourceBlock);for(let w of b)await G(w.path,w.type,"explicit",w.description)}if(Z.includeDiscovered){if(Q)Q.suffixText="Discover implementations";let b=await _W(Y,W,Z);for(let w of b){if(w.filePath===$.filePath)continue;await G(w.filePath,w.inferredType,"discovered")}}if(Z.includeConvention){if(Q)Q.suffixText="Discover implementations based on conventions";let b=Z.outputDir??j.outputDir??"./src",w=o8($.specType,Y,b);for(let{path:L,type:z}of w)await G(L,z,"convention")}if(Q)Q.suffixText="Determine implementation status";let J=p8(H);return{specKey:Y,specVersion:B,specPath:$.filePath,specType:$.specType,implementations:H,status:J,specHash:X}}async function a8($,W,j,A={},Q){let Z=[];for(let X of $){if(Q)Q.text=`Resolving implementation... (${Z.length}/${$.length})`;try{let Y=await r7(X,W,j,A,Q);Z.push(Y)}catch(Y){console.error(`Failed to resolve implementations for ${X}:`,Y)}}return Z}async function o1($,W,j){let{fs:A}=$,Q=[],Z=await m(A),X=j.implementation??{},Y=W.filter((q)=>q.specType==="operation"),B=await a8(Y,{fs:A},Z,{computeHashes:X.useCache??!0});for(let q of B){if(X.requireImplemented&&q.status==="missing")Q.push({ruleId:"impl-missing",severity:"error",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});else if(q.status==="missing")Q.push({ruleId:"impl-missing",severity:"warning",message:`Spec ${q.specKey} has no implementation`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status}});if(!X.allowPartial&&q.status==="partial"){let V=q.implementations.filter((G)=>!G.exists&&G.type!=="test").map((G)=>G.path);Q.push({ruleId:"impl-partial",severity:"warning",message:`Spec ${q.specKey} has partial implementation: missing ${V.join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,specVersion:q.specVersion,status:q.status,missingFiles:V}})}let H=q.implementations.filter((V)=>!V.exists&&V.type==="test");if(H.length>0)Q.push({ruleId:"impl-missing-tests",severity:"note",message:`Spec ${q.specKey} missing test files: ${H.map((V)=>V.path).join(", ")}`,category:"implementation",file:q.specPath,context:{specKey:q.specKey,missingTests:H.map((V)=>V.path)}})}return Q}import{isFeatureFile as i7,scanAllSpecsFromSource as p7,scanFeatureSource as t7}from"@contractspec/module.workspace";function l7($,W){return`${$}.v${W}`}function i1($,W,j,A,Q,Z={}){let{treatMissingAsError:X=!0}=Z;if(!A||A.length===0)return{valid:!0,foundTests:[],missingTests:[],errors:[],specFile:$};let Y=[],B=[],q=[];for(let H of A){let V=l7(H.key,H.version);if(Q.has(V))Y.push(H);else if(B.push(H),X)q.push(`Spec ${W}.v${j} references test ${H.key}.v${H.version} which does not exist`)}return{valid:B.length===0,foundTests:Y,missingTests:B,errors:q,specFile:$}}function s8($,W){return`${$}.v${W}`}function e8($,W){let j=new Map,A=new Map,Q=[],Z=[];for(let X of $){if(!X.key||!X.version)continue;let Y=s8(X.key,X.version);if(!X.testTarget){Z.push(Y);continue}let{type:B,key:q,version:H}=X.testTarget,V=H??X.version,G=s8(q,V),J=o7(W,B);if(!J||!J.has(G)){Q.push(Y);continue}if(A.set(Y,G),!j.has(G))j.set(G,new Set);j.get(G)?.add(Y)}return{targetToTests:j,testToTarget:A,orphanedTests:Q,testsWithoutTarget:Z}}function o7($,W){switch(W){case"operation":return $.operations;case"workflow":return $.workflows;default:return}}function t($,W){return`${$}.v${W}`}function a7(){return{operations:new Map,events:new Map,presentations:new Map,capabilities:new Map,workflows:new Map,dataViews:new Map,forms:new Map,migrations:new Map,experiments:new Map,integrations:new Map,knowledge:new Map,telemetry:new Map,appConfigs:new Map,policies:new Map,testSpecs:new Map}}function p1($,W){return{operation:$.operations,event:$.events,presentation:$.presentations,capability:$.capabilities,workflow:$.workflows,"data-view":$.dataViews,form:$.forms,migration:$.migrations,experiment:$.experiments,integration:$.integrations,knowledge:$.knowledge,telemetry:$.telemetry,"app-config":$.appConfigs,policy:$.policies,"test-spec":$.testSpecs}[W]}async function zW($,W={}){let{fs:j,logger:A}=$;A.info("Starting integrity analysis...",{options:W});let Q=await N$(j,{config:W.config,cwd:W.cwd,pattern:W.pattern}),Z=a7(),X=[],Y=[];for(let K of Q){if((await j.stat(K)).isDirectory)continue;let I=await j.readFile(K);if(i7(K)){let M=t7(I,K);X.push(M)}else{let M=p7(I,K);for(let E of M)if(E.specType!=="unknown"&&E.specType!=="feature"){let C=p1(Z,E.specType);if(C&&E.key&&E.version!==void 0){let R=t(E.key,E.version);C.set(R,{key:E.key,version:E.version,file:E.filePath,type:E.specType,stability:E.stability,testTarget:E.testTarget,testCoverage:E.testCoverage})}}}}let B=W.featureKey?X.filter((K)=>K.key===W.featureKey):X,q=new Set;for(let K of B){for(let _ of K.operations){let I=t(_.key,_.version);if(q.add(`operation:${I}`),!Z.operations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Operation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_})}for(let _ of K.events){let I=t(_.key,_.version);if(q.add(`event:${I}`),!Z.events.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Event ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"event",ref:_})}for(let _ of K.presentations){let I=t(_.key,_.version);if(q.add(`presentation:${I}`),!Z.presentations.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_})}for(let _ of K.experiments){let I=t(_.key,_.version);if(q.add(`experiment:${I}`),!Z.experiments.has(I))Y.push({severity:"error",type:"unresolved-ref",message:`Experiment ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"experiment",ref:_})}for(let _ of K.capabilities.provides){let I=t(_.key,_.version);if(q.add(`capability:${I}`),!Z.capabilities.has(I))Y.push({severity:"warning",type:"unresolved-ref",message:`Provided capability ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"capability",ref:_})}for(let _ of K.capabilities.requires){let I=t(_.key,_.version);q.add(`capability:${I}`)}for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=t(_.pres.key,_.pres.version);if(!Z.operations.has(I))Y.push({severity:"error",type:"broken-link",message:`Linked operation ${_.op.key}.v${_.op.version} not found`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op});if(!Z.presentations.has(M))Y.push({severity:"error",type:"broken-link",message:`Linked presentation ${_.pres.key}.v${_.pres.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:_.pres})}if(K.presentationsTargets)for(let _ of K.presentationsTargets){let I=t(_.key,_.version);if(!Z.presentations.has(I))Y.push({severity:"error",type:"broken-link",message:`Targeted presentation ${_.key}.v${_.version} not found`,file:K.filePath,featureKey:K.key,specType:"presentation",ref:{key:_.key,version:_.version}})}}let H=[],V=["operation","event","presentation","experiment"];for(let K of V){let _=p1(Z,K);if(!_)continue;for(let[I,M]of _)if(!q.has(`${K}:${I}`))H.push(M),Y.push({severity:"warning",type:"orphaned",message:`${K} ${M.key}.v${M.version} is not linked to any feature`,file:M.file,specKey:M.key,specType:M.type})}let G=[];for(let[,K]of Z.testSpecs)G.push({filePath:K.file,specType:"test-spec",key:K.key,version:K.version,testTarget:K.testTarget,hasMeta:!0,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1});let J=e8(G,Z);for(let K of B)for(let _ of K.opToPresentationLinks){let I=t(_.op.key,_.op.version),M=J.targetToTests.get(I),E=!1,C=!1;if(M)for(let R of M){let v=Z.testSpecs.get(R);if(v?.testCoverage){if(v.testCoverage.hasSuccess)E=!0;if(v.testCoverage.hasError)C=!0}}if(!M||!E||!C){let R=[];if(!E)R.push("success scenario");if(!C)R.push("error scenario");Y.push({severity:"error",type:"missing-test-coverage",message:`Operation ${_.op.key}.v${_.op.version} linked to presentation requires tests covering: ${R.join(", ")}`,file:K.filePath,featureKey:K.key,specType:"operation",ref:_.op})}}let b={},w=0;for(let K of V){let _=p1(Z,K);if(!_)continue;let I=_.size,M=0,E=0,C=W.requireTestsFor?.includes(K);for(let[R,v]of _){if(q.has(`${K}:${R}`))M++;if(C){let x=t(v.key,v.version),L$=J.targetToTests.has(x),v0=`${v.key}.test`,zA=Z.testSpecs.has(t(v0,v.version));if(!L$&&!zA)E++,w++,Y.push({severity:"warning",type:"missing-test",message:`${K} ${v.key}.v${v.version} is missing a test spec (no TestSpec.target or naming convention match)`,file:v.file,specKey:v.key,specType:v.type})}}b[K]={total:I,covered:M,orphaned:I-M,missingTest:C?E:0}}let L=Object.values(b).reduce((K,_)=>K+_.total,0),z=Object.values(b).reduce((K,_)=>K+_.covered,0),S={total:L,linkedToFeature:z,orphaned:L-z,missingTest:w,byType:b},O=!Y.some((K)=>K.severity==="error");return A.info("Integrity analysis complete",{features:X.length,totalSpecs:L,orphaned:H.length,issues:Y.length,healthy:O}),{inventory:Z,features:B,coverage:S,issues:Y,orphanedSpecs:H,healthy:O}}function UK($){let W=[];for(let j of Object.values($))for(let A of j.values())W.push(A);return W}function LK($,W){return $.filter((j)=>j.type===W)}function OK($,W){return $.filter((j)=>j.severity===W)}i();async function t1($,W){let j=[],A=await m($.fs),Q=await zW($,{config:A,pattern:W.pattern,all:!0});for(let Z of Q.issues)j.push({ruleId:`integrity-${Z.type}`,severity:Z.severity==="error"?"error":"warning",message:Z.message,category:"integrity",file:Z.file,context:{specKey:Z.specKey,specType:Z.specType,featureKey:Z.featureKey,ref:Z.ref}});return j}async function a1($,W){let j=[],A=await VW($,{});for(let[Q,Z]of A.inventory.features){if(!Z.key)j.push({ruleId:"layer-feature-missing-key",severity:"error",message:"Feature missing required 'key' field",category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.owners?.length)j.push({ruleId:"layer-feature-missing-owners",severity:"warning",message:`Feature '${Q}' missing 'owners' field`,category:"layers",file:Z.filePath,context:{key:Q}});if(Z.operations.length===0&&Z.events.length===0&&Z.presentations.length===0)j.push({ruleId:"layer-feature-empty",severity:"warning",message:`Feature '${Q}' has no operations, events, or presentations`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let[Q,Z]of A.inventory.examples){if(!Z.entrypoints.packageName)j.push({ruleId:"layer-example-missing-package",severity:"error",message:`Example '${Q}' missing 'packageName' in entrypoints`,category:"layers",file:Z.filePath,context:{key:Q}});if(!Z.surfaces.templates&&!Z.surfaces.sandbox.enabled&&!Z.surfaces.studio.enabled&&!Z.surfaces.mcp.enabled)j.push({ruleId:"layer-example-no-surfaces",severity:"warning",message:`Example '${Q}' has no enabled surfaces`,category:"layers",file:Z.filePath,context:{key:Q}})}for(let Q of A.inventory.workspaceConfigs.values())if(!Q.valid)for(let Z of Q.errors)j.push({ruleId:"layer-workspace-config-invalid",severity:"error",message:`Invalid workspace config: ${Z}`,category:"layers",file:Q.file});return j}i();import{ContractsrcSchema as e7,DEFAULT_CONTRACTSRC as UW}from"@contractspec/lib.contracts-spec/workspace-config";import{scanSpecSource as s7}from"@contractspec/module.workspace";async function $$($,W={}){let{fs:j,scan:A=s7}=$,Q=await N$(j,W),Z=[],X=Array.isArray(W.type)?W.type:[W.type];for(let Y of Q){if(j0(Y,W.config))continue;if(A0(Y))continue;try{let B=await j.readFile(Y),q=A(B,Y);if(q.specType==="unknown")continue;if(W.type&&!X.includes(q.specType))continue;Z.push(q)}catch{}}return Z}function FK($){let W=new Map;for(let j of $){let A=W.get(j.specType)??[];A.push(j),W.set(j.specType,A)}return W}var $X=/(^|\/)(handlers?|routes?|controllers?|api)(\/|$)|\.(handler|handlers|route|routes|controller)\.(ts|tsx)$/i,WX=/@contractspec\/lib\.contracts(?:-spec|-integrations)?|define(Command|Query|Event|Feature|Presentation|Capability|Form|DataView|Integration)|OperationSpecRegistry|ContractHandler|installOp|contracts\b|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,jX=/@contractspec\/(?:lib\.contracts(?:-spec|-integrations)?|module\.ai-chat|bundle\.library\/application\/mcp|example\.)|['"][^'"]+\.(operation|event|presentation|feature|capability|form|test-spec)(?:\.[tj]sx?)?['"]/,AX=/(^|\/)(index|types)\.ts$|\.types\.ts$|\.storage\.ts$|(?:^|\/)[^/]*\.(resolver|scheduler)\.ts$|(?:^|\/)[^/]*(factory|resources|mock-data)\.ts$/i,QX=/(^|\/)(__fixtures__|fixtures)(\/|$)/i,ZX=/^(.*\/packages\/(?:apps|apps-registry|bundles|examples|integrations|libs|modules|tools)\/[^/]+)(?:\/|$)/i,XX=/\/packages\/(?:apps|apps-registry|bundles|modules)\//i;function LW($){if(!$)return[];return $.split(/[|/]/).map((W)=>W.trim()).filter(Boolean)}function YX($,W){let j=$.replaceAll("\\","/"),A=new Set(["contracts","features",...LW(W?.conventions?.operations),...LW(W?.conventions?.events),...LW(W?.conventions?.presentations),...LW(W?.conventions?.forms)]);return j.split("/").some((Q)=>A.has(Q))}function BX($,W,j){let A=$.replaceAll("\\","/");if(!/\.(ts|tsx)$/.test(A))return!1;if(A.includes("/node_modules/")||A.includes("/dist/")||QX.test(A)||AX.test(A)||A.endsWith(".d.ts")||A.endsWith(".test.ts")||A.endsWith(".spec.ts"))return!1;if(W.has(A))return!1;if(YX(A,j))return!1;return $X.test(A)}function $4($){return $.replaceAll("\\","/").match(ZX)?.[1]??null}function qX($){let W=$.split(`
|
|
1610
|
+
`).map((j)=>j.trim()).filter((j)=>j.length>0&&!j.startsWith("//")&&!j.startsWith("/*")&&!j.startsWith("*")&&!j.startsWith("*/"));return W.length>0&&W.every((j)=>j.startsWith("import ")||j.startsWith("export *")||j.startsWith("export {")||j.startsWith("export type {")||j==="'use client';"||j==='"use client";'||j==="'use server';"||j==='"use server";')}function HX($){if(!$)return UW;let W=e7.safeParse($),j=W.success?W.data:{};return{...UW,...j,conventions:{...UW.conventions,...j.conventions??{}},ci:{...UW.ci,...j.ci??{}}}}async function s1($,W){let{fs:j,logger:A}=$,Q=[],Z=W.config?HX(W.config):await m(j),X=await $$({fs:j},{config:Z}),Y=new Set(X.map((H)=>H.filePath.replaceAll("\\","/"))),B=new Set(X.map((H)=>$4(H.filePath)).filter((H)=>Boolean(H))),q=await j.glob({pattern:"**/*.{ts,tsx}"});for(let H of q){if(!BX(H,Y,Z))continue;try{let V=await j.readFile(H);if(qX(V))continue;let G=$4(H);if(!(G!==null&&XX.test(G)&&B.has(G))&&!jX.test(V))continue;if(WX.test(V))continue;Q.push({ruleId:"policy-contract-first",severity:"error",message:"Implementation entrypoints in handlers/routes/api must import or reference a ContractSpec contract before shipping behavior.",category:"policy",file:H})}catch(V){A.warn("Policy scan failed for file",{file:H,error:V instanceof Error?V.message:String(V)})}}return Q}import{validateSpecStructure as VX}from"@contractspec/module.workspace";async function e1($){let W=[];for(let j of $){let A=VX(j);for(let Q of A.errors)W.push({ruleId:"spec-structure-error",severity:"error",message:Q,category:"structure",file:j.filePath});for(let Q of A.warnings)W.push({ruleId:"spec-structure-warning",severity:"warning",message:Q,category:"structure",file:j.filePath})}return W}async function $j($){let W=[],j=new Map,A=new Map;for(let Q of $){if(!Q.key||!Q.version)continue;if(Q.specType==="test-spec"){let Z=`${Q.key}.v${Q.version}`;j.set(Z,{key:Q.key,version:Q.version,file:Q.filePath,type:"test-spec"})}if(Q.testRefs&&Q.testRefs.length>0){if(!A.has(Q.filePath))A.set(Q.filePath,[]);A.get(Q.filePath)?.push({key:Q.key,version:Q.version,testRefs:Q.testRefs})}}for(let[Q,Z]of A)for(let X of Z){if(!X.testRefs)continue;let Y=i1(Q,X.key,X.version,X.testRefs,j,{treatMissingAsError:!0});for(let B of Y.errors)W.push({ruleId:"test-ref-missing",severity:"error",message:B,category:"test-refs",file:Q,context:{specKey:X.key,specVersion:X.version,missingTests:Y.missingTests}})}return W}i();async function Wj($,W){let{fs:j}=$,A=[],Q=await m(j);for(let Z of W){if(Z.specType!=="operation")continue;let X=await KW(Z,{fs:j},Q,{checkTests:!0,outputDir:Q.outputDir});for(let Y of X.errors)A.push({ruleId:"test-missing",severity:"warning",message:Y,category:"tests",file:Z.filePath});for(let Y of X.warnings)A.push({ruleId:"test-warning",severity:"warning",message:Y,category:"tests",file:Z.filePath})}return A}function l($,W,j){let A={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Verification",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"},Q=W.filter((Y)=>Y.severity==="error").length,Z=W.filter((Y)=>Y.severity==="warning").length,X=W.filter((Y)=>Y.severity==="note").length;return{category:$,label:A[$],errors:Q,warnings:Z,notes:X,passed:Q===0,durationMs:j}}async function W4($){try{if(!await $.exists(".git/HEAD"))return{};let j=await $.readFile(".git/HEAD"),A=j.match(/^ref: (.+)$/m);if(A){let Z=A[1]?.replace("refs/heads/",""),X=`.git/${A[1]}`;if(await $.exists(X))return{commitSha:(await $.readFile(X)).trim(),branch:Z};return{branch:Z}}return{commitSha:j.trim()}}catch{return{}}}function j4($){let W=$.config?.ci?.checks,j=W&&W.length>0?[...W]:["structure","integrity","deps","doctor","docs"];if($.checkHandlers)j.push("handlers");if($.checkTests)j.push("tests");if($.implementation)j.push("implementation");if($.checkDrift)j.push("drift");if($.checks&&$.checks.length>0)return $.checks;if($.skip&&$.skip.length>0)return j.filter((A)=>!$.skip?.includes(A));return j}async function q_($,W={}){let j=Date.now(),{fs:A,logger:Q}=$,Z=[],X=[],Y=j4(W);Q.info("Starting CI checks...",{checks:Y});let B=await m(A),q=await QW($,{config:B,pattern:W.pattern});if(Y.includes("structure")){let L=Date.now(),z=await e1(q);Z.push(...z),X.push(l("structure",z,Date.now()-L))}if(Y.includes("integrity")){let L=Date.now(),z=await t1($,W);Z.push(...z),X.push(l("integrity",z,Date.now()-L))}if(Y.includes("deps")){let L=Date.now(),z=await C1($,W);Z.push(...z),X.push(l("deps",z,Date.now()-L))}if(Y.includes("doctor")){let L=Date.now(),z=await u1($,W);Z.push(...z),X.push(l("doctor",z,Date.now()-L))}if(Y.includes("docs")){let L=Date.now(),z=await D1($,W);Z.push(...z),X.push(l("docs",z,Date.now()-L))}if(Y.includes("policy")){let L=Date.now(),z=await s1($,W);Z.push(...z),X.push(l("policy",z,Date.now()-L))}if(Y.includes("handlers")||W.checkHandlers){let L=Date.now(),z=await l1($,q);Z.push(...z),X.push(l("handlers",z,Date.now()-L))}if(Y.includes("tests")||W.checkTests){let L=Date.now(),z=await Wj($,q);Z.push(...z),X.push(l("tests",z,Date.now()-L))}if(Y.includes("test-refs")){let L=Date.now(),z=await $j(q);Z.push(...z),X.push(l("test-refs",z,Date.now()-L))}if(Y.includes("coverage")){let L=Date.now(),z=await R1($,q,W);Z.push(...z),X.push(l("coverage",z,Date.now()-L))}if(Y.includes("implementation")){let L=Date.now(),z=await o1($,q,W);Z.push(...z),X.push(l("implementation",z,Date.now()-L))}if(Y.includes("layers")){let L=Date.now(),z=await a1($,W);Z.push(...z),X.push(l("layers",z,Date.now()-L))}if(Y.includes("drift")){let L=Date.now(),z=await r1($,W);Z.push(...z),X.push(l("drift",z,Date.now()-L))}let H=Z.filter((L)=>L.severity==="error").length,V=Z.filter((L)=>L.severity==="warning").length,G=Z.filter((L)=>L.severity==="note").length,J=W.failOnWarnings?H===0&&V===0:H===0,b=await W4(A),w={success:J,totalErrors:H,totalWarnings:V,totalNotes:G,issues:Z,categories:X,durationMs:Date.now()-j,timestamp:new Date().toISOString(),...b};return Q.info("CI checks complete",{success:J,errors:H,warnings:V,durationMs:w.durationMs}),w}var V_=["structure","integrity","deps","doctor","docs","policy","handlers","tests","test-refs","coverage","implementation","layers","drift"],G_={structure:"Spec Structure Validation",integrity:"Contract Integrity Analysis",deps:"Dependency Analysis",doctor:"Installation Health",docs:"DocBlock Ownership",policy:"Contract Policy Enforcement",handlers:"Handler Implementation",tests:"Test Coverage","test-refs":"Test Reference Validation",coverage:"Coverage Goal Enforcement",implementation:"Implementation Verification",layers:"Contract Layers Validation",drift:"Drift Detection"};async function __($,W={}){let{fs:j,logger:A}=$,Q=(W.outputDir??"./src").replace(/\\/g,"/"),Z=["generated/**","dist/**",".turbo/**"],X=[`${Q}/handlers/**/*.handler.ts`,`${Q}/handlers/**/*.handler.test.ts`,`${Q}/components/**/*.tsx`,`${Q}/components/**/*.test.tsx`,`${Q}/forms/**/*.form.tsx`,`${Q}/forms/**/*.form.test.tsx`,`${Q}/**/*.runner.ts`,`${Q}/**/*.renderer.tsx`],Y=W.generatedOnly?[...Z,...X]:[...Z,"**/*.generated.ts","**/*.generated.js","**/*.generated.d.ts",...X],B=await j.glob({patterns:Y,ignore:["node_modules/**"]}),q=[],H=[];for(let V of B)try{let G=await j.stat(V),J=(Date.now()-G.mtime.getTime())/86400000;if(typeof W.olderThanDays==="number"&&J<W.olderThanDays){H.push({path:V,reason:`younger_than_${W.olderThanDays}_days`});continue}if(W.dryRun)A.info("[dry-run] clean would remove",{path:V,size:G.size});else await j.remove(V),A.info("clean.removed",{path:V,size:G.size});q.push({path:V,size:G.size})}catch(G){H.push({path:V,reason:G instanceof Error?G.message:String(G)})}return{removed:q,skipped:H}}i();var C4={};h(C4,{writeReviewPacket:()=>_j,writeDecisionEnvelope:()=>z0,withBranch:()=>x$,verifyConnectMutation:()=>K2,resolveWorkspace:()=>d,resolveStoragePaths:()=>A$,replayConnectDecision:()=>tX,persistLatestArtifacts:()=>wj,persistDecisionArtifacts:()=>_0,normalizeEvalInput:()=>uX,matchConfiguredPath:()=>G0,loadStoredDecision:()=>U0,listStoredReviewPackets:()=>zj,listConnectReviewPackets:()=>aX,isReviewCommand:()=>jj,isDeniedCommand:()=>Aj,isAllowedCommand:()=>OW,initConnectWorkspace:()=>lX,inferSurfaces:()=>w0,evaluateConnectDecision:()=>gX,ensureStorage:()=>K0,defaultActor:()=>b0,decisionArtifactRefs:()=>r$,createConnectControlPlaneRuntime:()=>Y2,connectVerdictToPolicy:()=>n$,configuredThreshold:()=>D$,compileConnectPlanPacket:()=>Uj,buildConnectContextPack:()=>bj,assessConnectPolicy:()=>J0,assertConnectEnabled:()=>a,artifactRef:()=>V$,appendAuditRecord:()=>Kj,analyzeConnectImpact:()=>y$,CONTROL_PLANE_TRACE_GET_REF:()=>SW,CONTROL_PLANE_POLICY_EXPLAIN_REF:()=>IW,CONTROL_PLANE_PLAN_VERIFY_REF:()=>Yj,CONTROL_PLANE_PLAN_COMPILE_REF:()=>Xj,CONTROL_PLANE_INTENT_SUBMIT_REF:()=>Zj,CONTROL_PLANE_EXECUTION_APPROVE_REF:()=>T$,AGENT_APPROVALS_REF:()=>MW,ACP_TERMINAL_EXEC_REF:()=>wX,ACP_FS_ACCESS_REF:()=>bX});import GX from"micromatch";function a($){if(!$.config.connect?.enabled)throw Error("ContractSpec Connect is not enabled. Configure .contractsrc.json > connect.enabled = true.")}function G0($,W,j){if(!j||j.length===0)return!1;let A=W.replaceAll("\\","/");return GX.isMatch(A,j,{contains:!0})}function D$($,W,j){return $.config.connect?.policy?.reviewThresholds?.[W]??j}function OW($,W){return Qj($.config.connect?.commands?.allow,W)}function jj($,W){return Qj($.config.connect?.commands?.review,W)}function Aj($,W){return Qj($.config.connect?.commands?.deny,W)}function Qj($,W){if(!$||$.length===0)return!1;return $.some((j)=>W===j||W.startsWith(`${j} `))}function Q4($,W){if(W.length===0)return{state:"none"};for(let A of W)if(Aj($,A))return{commandMatch:A,state:"deny"};for(let A of W)if(jj($,A))return{commandMatch:A,state:"review"};if(W.every((A)=>OW($,A)))return{state:"allow"};let j=W.find(JX);if(j)return{commandMatch:j,state:"destructive"};return{commandMatch:W.find((A)=>!OW($,A)),state:"unknown"}}function JX($){let W=$.trim().toLowerCase();if(W.startsWith("rm "))return A4(W,["-r","-f"])||W.includes("--recursive")&&W.includes("--force");if(W.startsWith("git reset "))return W.includes("--hard");if(W.startsWith("git clean "))return A4(W,["-f","-d"]);if(W.startsWith("git push "))return W.includes("--force")||/\s-f(\s|$)/.test(W);return!1}function A4($,W){return W.every((j)=>$.includes(j)||$.includes(j.replace("-","")))}var Zj={key:"controlPlane.intent.submit",version:"1.0.0",kind:"command"},Xj={key:"controlPlane.plan.compile",version:"1.0.0",kind:"command"},Yj={key:"controlPlane.plan.verify",version:"1.0.0",kind:"command"},SW={key:"controlPlane.trace.get",version:"1.0.0",kind:"query"},IW={key:"controlPlane.policy.explain",version:"1.0.0",kind:"query"},T$={key:"controlPlane.execution.approve",version:"1.0.0",kind:"command"},bX={key:"acp.fs.access",version:"1.0.0",kind:"command"},wX={key:"acp.terminal.exec",version:"1.0.0",kind:"command"},MW={key:"agent.approvals",version:"1.0.0",kind:"command"};function J0($,W){let j=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.immutablePaths)),A=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.protectedPaths)),Q=W.touchedPaths.find((G)=>G0($,G,$.config.connect?.policy?.generatedPaths)),{commandMatch:Z,state:X}=Q4($,W.commands??[]),Y=W.impactAnalysis.unknownPaths.length>0,B=W.impactAnalysis.driftFiles.length>0,q=KX({breakingChange:W.impactAnalysis.breakingChange,destructiveCommand:X==="destructive",commandState:X,contractDrift:B,generatedPath:Boolean(Q),immutable:Boolean(j),protectedPath:Boolean(A),smokeFailed:W.smokeFailed===!0,unknownImpact:Y,workspace:$}),H=_X({breakingChange:W.impactAnalysis.breakingChange,commandMatch:Z,commandState:X,contractDrift:B,protectedPath:A,unknownPaths:W.impactAnalysis.unknownPaths}),V=n$(q);return{commandMatch:Z,commandState:X,controlPlaneVerdict:V.controlPlaneVerdict,generatedPath:Q,immutablePath:j,protectedPath:A,requiredApprovals:V.requiresApproval?[{capability:T$.key,reason:H??"Connect policy requires human review before continuing."}]:[],requiresApproval:V.requiresApproval,reviewReason:H,verificationStatus:V.verificationStatus,verdict:q}}function n$($){switch($){case"rewrite":return{controlPlaneVerdict:"assist",requiresApproval:!1,verificationStatus:"revise"};case"require_review":return{controlPlaneVerdict:"assist",requiresApproval:!0,verificationStatus:"review"};case"deny":return{controlPlaneVerdict:"blocked",requiresApproval:!1,verificationStatus:"denied"};case"permit":default:return{controlPlaneVerdict:"autonomous",requiresApproval:!1,verificationStatus:"approved"}}}function KX($){if($.immutable||$.commandState==="deny")return"deny";let W=[];if($.protectedPath)W.push(D$($.workspace,"protectedPathWrite","require_review"));if($.breakingChange)W.push(D$($.workspace,"breakingChange","require_review"));if($.contractDrift)W.push(D$($.workspace,"contractDrift","require_review"));if($.unknownImpact)W.push(D$($.workspace,"unknownImpact","require_review"));if($.commandState==="review")W.push("require_review");if($.destructiveCommand)W.push(D$($.workspace,"destructiveCommand","deny"));if($.generatedPath||$.smokeFailed)W.push("rewrite");return W.sort(zX)[0]??"permit"}function _X($){if($.protectedPath)return`Protected path ${$.protectedPath} requires human review.`;if($.breakingChange)return"Breaking contract impact requires human review.";if($.contractDrift)return"Generated-path drift requires human review before continuing.";if($.commandState==="review"&&$.commandMatch)return`Command "${$.commandMatch}" requires human review.`;if($.commandState==="destructive"&&$.commandMatch)return`Destructive command "${$.commandMatch}" requires human review.`;if($.unknownPaths.length>0)return`Impact could not be resolved for ${$.unknownPaths[0]}.`;return}function zX($,W){return Z4($)-Z4(W)}function Z4($){return{deny:0,require_review:1,rewrite:2,permit:3}[$]}import{randomUUID as kX}from"crypto";var H4={};h(H4,{formatPrComment:()=>X4,formatMinimalComment:()=>Bj,formatJson:()=>B4,formatCheckRun:()=>Y4,detectImpact:()=>F$,ImpactDetectionOverviewDocBlock:()=>MX});function X4($,W={template:"detailed"}){let j=[];if(j.push("## \uD83D\uDCCB ContractSpec Impact Analysis"),j.push(""),$.hasBreaking)j.push("❌ **Breaking changes detected**");else if($.hasNonBreaking)j.push("⚠️ **Contract changed (non-breaking)**");else j.push("✅ **No contract impact**");if(j.push(""),$.summary.breaking>0||$.summary.nonBreaking>0||$.summary.info>0){if(j.push("### Summary"),j.push(""),j.push("| Type | Count |"),j.push("|------|-------|"),$.summary.breaking>0)j.push(`| \uD83D\uDD34 Breaking | ${$.summary.breaking} |`);if($.summary.nonBreaking>0)j.push(`| \uD83D\uDFE1 Non-breaking | ${$.summary.nonBreaking} |`);if($.summary.info>0)j.push(`| \uD83D\uDD35 Info | ${$.summary.info} |`);if($.summary.added>0)j.push(`| ➕ Added | ${$.summary.added} |`);if($.summary.removed>0)j.push(`| ➖ Removed | ${$.summary.removed} |`);j.push("")}if(W.template==="detailed"&&$.deltas.length>0){j.push("### Changes"),j.push("");let A=$.deltas.filter((Z)=>Z.severity==="breaking"),Q=$.deltas.filter((Z)=>Z.severity==="non_breaking");if(A.length>0){j.push("#### \uD83D\uDD34 Breaking Changes"),j.push("");for(let Z of A)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}if(Q.length>0){j.push("#### \uD83D\uDFE1 Non-breaking Changes"),j.push("");for(let Z of Q)j.push(`- **${Z.specKey}**: ${Z.description}`);j.push("")}}if($.addedSpecs.length>0){j.push("### Added Specs"),j.push("");for(let A of $.addedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if($.removedSpecs.length>0){j.push("### Removed Specs"),j.push("");for(let A of $.removedSpecs)j.push(`- \`${A.key}\` v${A.version} (${A.type})`);j.push("")}if(W.drift)if(W.drift.hasDrift){j.push("### ⚠️ Drift Detected"),j.push(""),j.push("The following generated files are out of sync with their specs:"),j.push("");for(let A of W.drift.files)j.push(`- \`${A}\``);j.push(""),j.push("Run `contractspec generate` to regenerate artifacts."),j.push("")}else j.push("### ✅ No Drift Detected"),j.push("");return j.push("---"),j.push(`*Generated by ContractSpec at ${$.timestamp}*`),j.join(`
|
|
1611
|
+
`)}function Bj($){if($.hasBreaking)return`❌ **Breaking changes detected** (${$.summary.breaking} breaking, ${$.summary.nonBreaking} non-breaking)`;if($.hasNonBreaking)return`⚠️ **Contract changed** (${$.summary.nonBreaking} non-breaking changes)`;return"✅ **No contract impact**"}function Y4($,W,j={}){let A=j.key??"ContractSpec Impact",Q=j.failOnBreaking??!0,Z,X;if($.hasBreaking)Z=Q?"failure":"neutral",X=`Breaking changes detected (${$.summary.breaking})`;else if($.hasNonBreaking)Z="success",X=`Non-breaking changes (${$.summary.nonBreaking})`;else Z="success",X="No contract impact";let Y=Bj($);return{name:A,headSha:W,conclusion:Z,title:X,summary:Y,annotations:$.deltas.filter((B)=>B.severity==="breaking").slice(0,50).map((B)=>({path:B.path,startLine:1,endLine:1,annotationLevel:"failure",message:B.description,title:`Breaking: ${B.rule}`}))}}function B4($){let W={schemaVersion:"1.0",breaking:$.hasBreaking,changes:$.deltas.map((j)=>({type:j.rule,path:j.specKey,summary:j.description,severity:j.severity==="breaking"?"breaking":j.severity==="non_breaking"?"medium":"low"})),summary:{breaking:$.summary.breaking,nonBreaking:$.summary.nonBreaking,total:$.deltas.length}};return JSON.stringify(W,null,2)}import{classifyImpact as UX,computeIoDiff as LX,generateSnapshot as q4}from"@contractspec/module.workspace";async function F$($,W={}){let{fs:j,git:A,logger:Q}=$,Z=W.workspaceRoot??process.cwd();Q.info("Starting impact detection...",{baseline:W.baseline});let Y=(await j.glob({pattern:W.pattern??"**/*.{operation,event}.ts",cwd:Z})).filter((J)=>!J.includes(".test.")&&!J.includes(".spec.")&&!J.includes("node_modules"));Q.debug(`Found ${Y.length} spec files`);let B=await OX(j,Y,Z),q=q4(B),H;if(W.baseline){let J=await SX(j,A,Y,W.baseline,Z);H=q4(J)}else H={version:"1.0.0",generatedAt:"",specs:[],hash:""};let V=IX(H.specs,q.specs),G=UX(H.specs,q.specs,V);return Q.info("Impact detection complete",{status:G.status,breaking:G.summary.breaking,nonBreaking:G.summary.nonBreaking}),{...G,workspaceRoot:Z,specsAnalyzed:Y.length,baseRef:W.baseline}}async function OX($,W,j){let A=[];for(let Q of W){let Z=await $.readFile(Q);A.push({path:Q,content:Z})}return A}async function SX($,W,j,A,Q){let Z=[];for(let X of j)try{let Y=await W.showFile(A,X);Z.push({path:X,content:Y})}catch{}return Z}function IX($,W){let j=[],A=new Map($.map((Z)=>[`${Z.key}@${Z.version}`,Z])),Q=new Map(W.map((Z)=>[`${Z.key}@${Z.version}`,Z]));for(let[Z,X]of Q){let Y=A.get(Z);if(Y&&X.type==="operation"&&Y.type==="operation"){let B=LX(Y.io,X.io);j.push(...B)}}return j}var MX={id:"feature.impact-detection.overview",title:"Contract Impact Detection",kind:"goal",visibility:"public",route:"/docs/features/impact-detection",body:`
|
|
1612
|
+
# Contract Impact Detection
|
|
1613
|
+
|
|
1614
|
+
Automated detection and classification of breaking changes in ContractSpec APIs.
|
|
1615
|
+
|
|
1616
|
+
## Features
|
|
1617
|
+
|
|
1618
|
+
- **Snapshot Generation**: Creates canonical, deterministic representations of contracts
|
|
1619
|
+
- **Deep Diff Engine**: Field-level comparison of input/output schemas
|
|
1620
|
+
- **Breaking Change Classification**: Automatic classification using 16 rules
|
|
1621
|
+
- **Multiple Output Formats**: JSON, Markdown, Text, GitHub Check Run
|
|
1622
|
+
- **GitHub Integration**: PR comments and check runs
|
|
1623
|
+
- **CLI Tool**: \`contractspec impact\` command
|
|
1624
|
+
|
|
1625
|
+
## Quick Start
|
|
1626
|
+
|
|
1627
|
+
### CLI Usage
|
|
1628
|
+
|
|
1629
|
+
\`\`\`bash
|
|
1630
|
+
# Basic usage
|
|
1631
|
+
contractspec impact
|
|
1632
|
+
|
|
1633
|
+
# Compare against specific baseline
|
|
1634
|
+
contractspec impact --baseline origin/main
|
|
1635
|
+
|
|
1636
|
+
# Get JSON output
|
|
1637
|
+
contractspec impact --format json
|
|
1638
|
+
\`\`\`
|
|
1639
|
+
|
|
1640
|
+
### GitHub Action
|
|
1641
|
+
|
|
1642
|
+
\`\`\`yaml
|
|
1643
|
+
- uses: lssm-tech/contractspec-action@v1
|
|
1644
|
+
with:
|
|
1645
|
+
mode: impact
|
|
1646
|
+
pr-comment: true
|
|
1647
|
+
fail-on-breaking: true
|
|
1648
|
+
\`\`\`
|
|
1649
|
+
|
|
1650
|
+
## Architecture
|
|
1651
|
+
|
|
1652
|
+
The system consists of three layers:
|
|
1653
|
+
|
|
1654
|
+
1. **Analysis Modules** (module package): Snapshot, Deep Diff, Classifier
|
|
1655
|
+
2. **Impact Service** (bundle package): Orchestration + Formatters
|
|
1656
|
+
3. **Integrations**: CLI command + GitHub Action
|
|
1657
|
+
`,tags:["impact-detection","breaking-changes","ci-cd"]};import{existsSync as G4,readFileSync as J4}from"node:fs";import{basename as EX,join as qj,resolve as NX}from"node:path";import{ContractsrcSchema as RX,DEFAULT_CONTRACTSRC as CX}from"@contractspec/lib.contracts-spec/workspace-config";function d($={}){let W=NX($.cwd??process.cwd()),j=$.workspaceRoot??D(W),A=$.packageRoot??f(W),Q=$.config??DX(j,A),Z=TX(A,j);return{cwd:W,workspaceRoot:j,packageRoot:A,config:Q,repoId:Z,branch:"unknown"}}function x$($,W){return{...$,branch:W&&W.length>0?W:"unknown"}}function b0($,W){return W??{id:`cli:${$}`,type:"human"}}function w0($){let W=new Set;for(let j of $){if(j.includes("/cli-")||j.includes("/apps/cli-"))W.add("cli");if(j.includes("/contracts-spec/")||j.includes("/specs/"))W.add("contract");if(j.includes("/runtime/"))W.add("runtime");if(j.includes("/harness"))W.add("harness");if(j.includes("/ai-agent/"))W.add("agent");if(j.includes("/knowledge/"))W.add("knowledge");if(j.includes("/mcp/"))W.add("mcp")}if(W.size===0)W.add("runtime");return W.add("audit"),[...W].sort()}function DX($,W){let j={...CX};if($!==W)j=V4(j,qj($,".contractsrc.json"));return V4(j,qj(W,".contractsrc.json"))}function V4($,W){if(!G4(W))return $;try{let j=J4(W,"utf-8"),A=JSON.parse(j),Q=RX.safeParse(A);if(!Q.success)return $;return{...$,...Q.data}}catch{return $}}function TX($,W){let j=qj($,"package.json");if(G4(j))try{let A=JSON.parse(J4(j,"utf-8"));if(A.name)return A.name}catch{}return EX(W)}async function y$($,W){let j=await $$({fs:$.fs},{config:W.workspace.config}),A=new Map(j.filter((B)=>typeof B.key==="string").map((B)=>[B.key,B])),Q=W.touchedPaths.map((B)=>FX($.fs,W.workspace,B,j,A)),Z=W.baseline!=null?await F$({...$,logger:$.logger??w4},{baseline:W.baseline,workspaceRoot:W.workspace.workspaceRoot}):void 0,X=await xX($,W.workspace,W.touchedPaths),Y=Jj([...Q.flatMap((B)=>B.contracts),...(Z?.deltas??[]).map((B)=>({key:B.specKey,version:B.specVersion,kind:B.specType==="event"?"event":"command"}))]);return{breakingChange:Z?.hasBreaking===!0,driftFiles:X,impactResult:Z,impactedContracts:Y,pathImpacts:Q,unknownPaths:Q.filter((B)=>B.contracts.length===0).map((B)=>B.path)}}function FX($,W,j,A,Q){let Z=$.resolve(W.workspaceRoot,j),X=Gj(j),Y=A.map((b)=>{let w=s($.relative(W.workspaceRoot,b.filePath));return{score:mX(j,X,w,b.key),spec:b}}).filter((b)=>b.score>=45).sort((b,w)=>w.score-b.score).slice(0,3),B=A.find((b)=>b.filePath===Z),q=B?[{score:100,spec:B}]:Y,H=q.filter((b)=>typeof b.spec.key==="string").map((b)=>Vj(b.spec.key,b.spec.version,b.spec.kind)),V=q.flatMap((b)=>[...b.spec.emittedEvents??[],...b.spec.policyRefs??[],...b.spec.testRefs??[]].map((w)=>Q.get(w.key)).filter(Boolean).map((w)=>Vj(w.key,w.version,w.kind))),G=Jj([...H,...V]),J=Jj([{key:"connect.policy",version:"1.0.0",kind:"policy"},...q.flatMap((b)=>b.spec.policyRefs??[]).map((b)=>Vj(b.key,b.version,"policy"))]);return{confidence:q[0]?.score===100?"exact":(q[0]?.score??0)>=70?"high":q.length>0?"medium":"none",contracts:G,path:j,policies:J,reasons:q.map((b)=>`${b.spec.key??b.spec.filePath} matched with score ${b.score}`),surfaces:w0([j])}}async function xX($,W,j){let A=yX($.fs,W,j),Q=await Promise.all(A.map(async(Z)=>{let X=$.fs.resolve(W.packageRoot,Z.comparisonRoot),Y=await wW({...$,logger:$.logger??w4},W.workspaceRoot,X,{generation:{scanAllSpecs:!0,specSearchRoot:W.workspaceRoot},rootPath:W.workspaceRoot}),B=Z.filterPrefix&&Z.filterPrefix!==Z.comparisonRoot?s($.fs.relative(Z.comparisonRoot,Z.filterPrefix)):void 0;return Y.files.filter((q)=>B?s(q)===B||s(q).startsWith(`${B}/`):!0).map((q)=>s($.fs.join(Z.comparisonRoot,q)))}));return[...new Set(Q.flat())].sort()}function yX($,W,j){let A=(W.config.connect?.policy?.generatedPaths??[]).map(PX).filter(Boolean),Q=W.config.outputDir&&W.config.outputDir!=="./src"?s(W.config.outputDir):void 0,Z=new Map;for(let X of j){let Y=s(X);if(Q&&Y.startsWith(Q))Z.set(Q,{comparisonRoot:Q});for(let B of A)if(Y.startsWith(B)){let q=vX($,Q,B);Z.set(`${q}::${B}`,{comparisonRoot:q,filterPrefix:B})}}return[...Z.values()]}function vX($,W,j){if(W&&j.startsWith(W))return W;return $.basename(j)==="docs"?s($.dirname(j)):j}function mX($,W,j,A){if(s($)===s(j))return 100;let Q=Gj(j),Z=Gj(A??""),X=b4($)===b4(j)?40:0,Y=Hj($.split("/"),j.split("/"),5),B=Hj(W,Q,5),q=Hj(W,Z,4);return X+Y+B+q}function Hj($,W,j){let A=new Set(W);return $.filter((Q)=>A.has(Q)).length*j}function Gj($){return s($).split(/[\/._-]+/).filter(Boolean)}function b4($){return s($).split("/").pop()?.replace(/\.[^.]+$/,"")??$}function PX($){return s($.split(/[\[*?{]/,1)[0]??"").replace(/\/$/,"")}function s($){return $.replaceAll("\\","/").replace(/^\.\//,"")}function Vj($,W,j){return{key:$,version:String(W??"1.0.0"),kind:j==="query"||j==="event"||j==="policy"||j==="capability"?j:"command"}}function Jj($){return[...new Map($.map((W)=>[`${W.key}@${W.version}`,W])).values()]}var w4={createProgress:()=>({fail:()=>{},start:()=>{},stop:()=>{},succeed:()=>{},update:()=>{},warn:()=>{}}),debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}};async function bj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let A=b0(W.taskId,W.actor),Q=await hX($,j.workspaceRoot,W),Z=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),X=j.config.connect?.canonPacks??[];return{id:`connect.ctx_${kX()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:A,knowledge:X.map((Y)=>({spaceKey:Y.ref,category:"canonical",trustLevel:Y.readOnly===!1?"medium":"high",source:"connect.canonPacks"})),impactedContracts:Z.impactedContracts,affectedSurfaces:Z.pathImpacts.length>0?[...new Set(Z.pathImpacts.flatMap((Y)=>Y.surfaces))].sort():w0(Q),policyBindings:[{key:"connect.policy",version:"1.0.0",source:"workspace-config",authority:"operational"},...X.map((Y)=>({key:Y.ref,version:"1.0.0",source:"canon-pack",authority:"canonical"}))],configRefs:[{kind:"contractsrc",ref:".contractsrc.json#connect"},...X.map((Y)=>({kind:"canon-pack",ref:Y.ref}))],acceptanceChecks:j.config.connect?.policy?.smokeChecks??[]}}async function hX($,W,j){let A=j.paths??[];if(A.length>0)return A.map((Z)=>K4($.fs,W,Z));if(!j.baseline)return[];return(await $.git.diffFiles(j.baseline)).map((Z)=>K4($.fs,W,Z))}function K4($,W,j){let A=$.resolve(W,j);return $.relative(W,A).replaceAll("\\","/")}import{resolve as v$}from"node:path";function A$($){let W=$.config.connect?.storage,j=v$($.packageRoot,W?.root??".contractspec/connect");return{root:j,contextPack:v$($.packageRoot,W?.contextPack??".contractspec/connect/context-pack.json"),planPacket:v$($.packageRoot,W?.planPacket??".contractspec/connect/plan-packet.json"),patchVerdict:v$($.packageRoot,W?.patchVerdict??".contractspec/connect/patch-verdict.json"),auditFile:v$($.packageRoot,W?.auditFile??".contractspec/connect/audit.ndjson"),reviewPacketsDir:v$($.packageRoot,W?.reviewPacketsDir??".contractspec/connect/review-packets"),decisionsDir:v$(j,"decisions")}}async function K0($,W){await $.mkdir(W.root),await $.mkdir(W.reviewPacketsDir),await $.mkdir(W.decisionsDir)}async function wj($,W,j){if(j.contextPack)await j$($,W.contextPack,j.contextPack);if(j.planPacket)await j$($,W.planPacket,j.planPacket);if(j.patchVerdict)await j$($,W.patchVerdict,j.patchVerdict)}async function _0($,W,j,A){let Q=$.join(W.decisionsDir,j);if(await $.mkdir(Q),A.contextPack)await j$($,$.join(Q,"context-pack.json"),A.contextPack);if(A.planPacket)await j$($,$.join(Q,"plan-packet.json"),A.planPacket);if(A.patchVerdict)await j$($,$.join(Q,"patch-verdict.json"),A.patchVerdict);if(A.reviewPacket)await j$($,$.join(Q,"review-packet.json"),A.reviewPacket);if(A.evaluationResult!==void 0)await j$($,$.join(Q,"evaluation-result.json"),A.evaluationResult);if(A.replayBundle!==void 0)await j$($,$.join(Q,"replay-bundle.json"),A.replayBundle);return Q}async function z0($,W,j,A){let Q=$.join(W.decisionsDir,j,"decision-envelope.json");return await j$($,Q,A),Q}async function Kj($,W,j){let A=await _4($,W.auditFile)??"",Q=`${JSON.stringify(j)}
|
|
1658
|
+
`;await $.writeFile(W.auditFile,`${A}${Q}`)}async function _j($,W,j){let A=$.join(W.reviewPacketsDir,`${j.id}.json`);return await j$($,A,j),A}async function U0($,W,j){let A=$.join(W.decisionsDir,j);return{historyDir:A,contextPack:await c$($,$.join(A,"context-pack.json")),planPacket:await c$($,$.join(A,"plan-packet.json")),patchVerdict:await c$($,$.join(A,"patch-verdict.json")),reviewPacket:await c$($,$.join(A,"review-packet.json")),envelope:await c$($,$.join(A,"decision-envelope.json"))}}async function zj($,W){let j=await $.glob({pattern:"*.json",cwd:W.reviewPacketsDir,absolute:!0}),A=[];for(let Q of j){let Z=await c$($,Q);if(Z)A.push({filePath:Q,packet:Z})}return A.sort((Q,Z)=>Q.packet.id.localeCompare(Z.packet.id))}function V$($,W,j){return $.relative(W.packageRoot,$.resolve(j)).replaceAll("\\","/")}function r$($,W,j,A,Q){let Z=$.join(j.decisionsDir,A);return{contextPack:V$($,W,$.join(Z,"context-pack.json")),planPacket:V$($,W,$.join(Z,"plan-packet.json")),patchVerdict:V$($,W,$.join(Z,"patch-verdict.json")),reviewPacket:Q.reviewPacket?V$($,W,$.join(Z,"review-packet.json")):void 0,evaluationResult:Q.evaluationResult?V$($,W,$.join(Z,"evaluation-result.json")):void 0,replayBundle:Q.replayBundle?V$($,W,$.join(Z,"replay-bundle.json")):void 0}}async function j$($,W,j){await $.writeFile(W,`${JSON.stringify(j,null,2)}
|
|
1659
|
+
`)}async function c$($,W){let j=await _4($,W);if(!j)return;try{return JSON.parse(j)}catch{return}}async function _4($,W){if(!await $.exists(W))return;try{return await $.readFile(W)}catch{return}}async function gX($,W,j){let A=d(W);if(a(A),!W.scenarioKey&&!W.suiteKey||W.scenarioKey&&W.suiteKey)throw Error("Provide exactly one of scenarioKey or suiteKey.");let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X=fX(A,Z),Y=W.scenarioKey?await j.runScenarioEvaluation({scenarioKey:W.scenarioKey,version:W.version,context:X}):await j.runSuiteEvaluation({suiteKey:W.suiteKey??"",version:W.version,context:X}),B=await _0($.fs,Q,W.decisionId,{evaluationResult:Y}),q=await $.fs.exists($.fs.join(B,"replay-bundle.json")),H={artifacts:r$($.fs,A,Q,W.decisionId,{contextPack:!0,evaluationResult:!0,patchVerdict:!0,planPacket:!0,replayBundle:q,reviewPacket:Boolean(Z.reviewPacket)}),connectDecisionId:W.decisionId,createdAt:Z.envelope?.createdAt??new Date().toISOString(),runtimeLink:Z.envelope?.runtimeLink,taskId:Z.contextPack?.taskId??W.decisionId,verdict:Z.patchVerdict?.verdict??"permit"};return await z0($.fs,Q,W.decisionId,H),{historyDir:B,evaluation:Y,context:X}}function fX($,W){return{traceId:W.envelope?.runtimeLink?.traceId??W.patchVerdict?.controlPlane.traceId??W.contextPack?.actor.traceId,actorId:W.contextPack?.actor.id,workspaceId:$.repoId,controlPlaneExecutionId:W.envelope?.runtimeLink?.decisionId,controlPlanePlanId:W.envelope?.runtimeLink?.planId??W.planPacket?.id,metadata:{approvalStatus:W.envelope?.runtimeLink?.approvalStatus,decisionId:W.patchVerdict?.decisionId,taskId:W.contextPack?.taskId,branch:W.contextPack?.branch??$.branch}}}function uX($){return $}import{DEFAULT_CONTRACTSRC as rX}from"@contractspec/lib.contracts-spec/workspace-config";async function EW($,W){let j=$.join(W.root,".gitignore"),A=W.behavior??"auto",Q=L4(W.patterns);if(Q.length===0||A==="skip")return{target:"gitignore",filePath:j,action:"skipped",message:A==="skip"?"Skipped ContractSpec gitignore updates":"No ContractSpec ignore patterns requested"};try{if(A==="auto"&&W.interactive&&W.prompts&&!await W.prompts.confirm(`Add recommended ContractSpec ignore rules to ${j}?`,!0))return{target:"gitignore",filePath:j,action:"skipped",message:"User skipped ContractSpec gitignore update"};let Z=await $.exists(j),X=Z?await $.readFile(j):"",Y=dX(X,Q);if(U4(X)===U4(Y))return{target:"gitignore",filePath:j,action:"skipped",message:"ContractSpec ignore rules already up to date"};return await $.writeFile(j,Y),{target:"gitignore",filePath:j,action:Z?"merged":"created",message:Z?"Updated ContractSpec-managed .gitignore rules":"Created .gitignore with ContractSpec-managed rules"}}catch(Z){return{target:"gitignore",filePath:j,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}function dX($,W){let j=nX(W),A=cX(),Q=$.replace(/\r\n/g,`
|
|
1660
|
+
`);if(A.test(Q))return Q.replace(A,j);if(Q.trim().length===0)return j;return`${Q.endsWith(`
|
|
1661
|
+
`)?Q:`${Q}
|
|
1662
|
+
`}
|
|
1663
|
+
${j}`}function nX($){return`# contractspec:init:gitignore:start
|
|
1664
|
+
# Managed by \`contractspec init\` and \`contractspec connect init\`.
|
|
1665
|
+
${L4($).join(`
|
|
1666
|
+
`)}
|
|
1667
|
+
# contractspec:init:gitignore:end
|
|
1668
|
+
`}function cX(){return new RegExp(`${z4("# contractspec:init:gitignore:start")}[\\s\\S]*?${z4("# contractspec:init:gitignore:end")}(?:\\r?\\n)?`)}function z4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U4($){return $.replace(/\r\n/g,`
|
|
1669
|
+
`).trimEnd()}function L4($){return[...new Set($.map((W)=>W.trim()).filter(Boolean))]}async function lX($,W={}){let j=d(W),A=W.scope==="package"?j.packageRoot:j.workspaceRoot,Q=$.join(A,".contractsrc.json"),Z={connect:{...rX.connect,enabled:!0}},X="created";if(await $.exists(Q)){let q=r(await $.readFile(Q)),H=p(q??{},Z);if(q?.connect&&typeof q.connect==="object")H.connect.enabled=!0;await $.writeFile(Q,F(H)),X="merged"}else await $.writeFile(Q,F(Z));let Y=A$(d({...W,workspaceRoot:A,packageRoot:A}));await K0($,Y);let B=await EW($,{behavior:W.gitignoreBehavior,interactive:W.interactive??!1,patterns:[Y0.connect,Y0.verificationCache],prompts:W.prompts,root:j.workspaceRoot});return{configPath:Q,targetRoot:A,action:X,gitignore:B}}import{randomUUID as NW}from"crypto";async function Uj($,W){let j=d(W);a(j),j=x$(j,await $.git.currentBranch());let{commands:A,touchedPaths:Q}=oX(W.candidate),Z=await bj($,{...W,paths:Q}),X=b0(W.taskId,W.actor),Y=iX(W.candidate.steps,W.candidate),B=await y$($,{baseline:W.baseline,touchedPaths:Q,workspace:j}),q=J0(j,{commands:A,impactAnalysis:B,touchedPaths:Q}),H={id:`connect.plan_${NW()}`,taskId:W.taskId,repoId:j.repoId,branch:j.branch,actor:X,objective:W.candidate.objective,steps:Y,impactedContracts:Z.impactedContracts,affectedSurfaces:Z.affectedSurfaces,requiredChecks:j.config.connect?.policy?.smokeChecks??[],requiredApprovals:q.requiredApprovals,riskScore:pX(Q.length,A.length),verificationStatus:q.verificationStatus,controlPlane:{intentSubmit:Zj,planCompile:Xj,planVerify:Yj,traceId:X.traceId},acpActions:[...Q.length>0?["acp.fs.access"]:[],...A.length>0?["acp.terminal.exec"]:[]]};return{contextPack:Z,planPacket:H}}function oX($){let W=new Set($.touchedPaths??[]),j=new Set($.commands??[]);for(let A of $.steps??[]){if(typeof A==="string")continue;for(let Q of A.paths??[])W.add(Q);for(let Q of A.commands??[])j.add(Q)}return{commands:[...j],touchedPaths:[...W]}}function iX($,W){if(!$||$.length===0)return[{id:`step_${NW()}`,summary:W.objective,paths:W.touchedPaths,commands:W.commands}];return $.map((j)=>typeof j==="string"?{id:`step_${NW()}`,summary:j}:{id:`step_${NW()}`,summary:j.summary,paths:j.paths,commands:j.commands,contractRefs:j.contractRefs})}function pX($,W){return Math.min(1,$*0.1+W*0.15+0.1)}async function tX($,W,j){let A=d(W);a(A);let Q=A$(A),Z=await U0($.fs,Q,W.decisionId),X={decisionId:Z.envelope?.runtimeLink?.decisionId,traceId:Z.envelope?.runtimeLink?.traceId},Y=j&&(X.decisionId||X.traceId)?await j.getExecutionTrace(X):null,B=j&&Y?await j.replayExecutionTrace(X):null;return{decisionId:W.decisionId,historyDir:Z.historyDir,contextPack:Z.contextPack,planPacket:Z.planPacket,patchVerdict:Z.patchVerdict,reviewPacket:Z.reviewPacket,trace:Y??void 0,replay:B??void 0,source:Y?"local+control-plane":"local"}}async function aX($,W={}){let j=d(W);return a(j),zj($.fs,A$(j))}import{buildChannelPlanTrace as sX,compileChannelPlan as eX,finalizeChannelPlan as $2,replayExecutionTrace as W2,resolveChannelExecutionActor as j2}from"@contractspec/integration.runtime/channel";import{createHash as A2}from"crypto";var L0="connect.local",Q2="connect.runtime-link.v1",Z2="connect.adapter.v1",X2="connect-control-plane-bridge";function Y2($){return{linkDecision:async({connectDecisionId:W,createdAt:j,input:A,patchVerdict:Q,planPacket:Z,workspace:X})=>{let Y=new Date(j),B=JSON.stringify({connectDecisionId:W,objective:Z.objective,taskId:Z.taskId,tool:A.tool,verdict:Q.verdict}),q={workspaceId:X.repoId,providerKey:L0,externalEventId:W,eventType:A.tool==="acp.fs.access"?`connect.fs.${A.operation}`:"connect.terminal.exec",occurredAt:Y,signatureValid:!0,traceId:Q.controlPlane.traceId,thread:{externalThreadId:`connect:${Z.taskId}`,externalUserId:Z.actor.id},message:{text:V2(Z.objective,A)},metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`}),rawPayload:B},H=await $.store.claimEventReceipt({workspaceId:q.workspaceId,providerKey:q.providerKey,externalEventId:q.externalEventId,eventType:q.eventType,signatureValid:!0,payloadHash:G2(B),traceId:q.traceId});if(H.duplicate)return B2($.store,X.repoId,W);let V=await $.store.upsertThread({workspaceId:q.workspaceId,providerKey:q.providerKey,externalThreadId:q.thread.externalThreadId,externalUserId:q.thread.externalUserId,occurredAt:Y}),G=j2(q,{actorId:Z.actor.id,actorType:Z.actor.type,capabilityGrants:H2(Q.verdict),capabilitySource:"connect",sessionId:Z.actor.sessionId}),J=eX({event:q,receiptId:H.receiptId,threadId:V.id,actor:G,now:Y}),b=$2({plan:J,decision:q2(Q),approvalTimeoutMs:900000,now:Y}),w=await $.store.saveDecision({receiptId:H.receiptId,threadId:V.id,policyMode:b.policy?.verdict??"blocked",riskTier:b.policy?.riskTier??"blocked",confidence:b.policy?.confidence??0.5,modelName:X2,promptVersion:Q2,policyVersion:Z2,toolTrace:sX(b),actionPlan:b,requiresApproval:b.approval.required,approvalStatus:b.approval.required?"pending":"not_required"});return await $.store.appendTraceEvent({stage:"decision",status:b.approval.required?"pending":"processed",decisionId:w.id,receiptId:H.receiptId,traceId:b.traceId,workspaceId:X.repoId,providerKey:L0,sessionId:Z.actor.sessionId,workflowId:`connect:${Z.taskId}`,metadata:S4({connectDecisionId:W,connectVerdict:Q.verdict,tool:A.tool})}),{approvalStatus:w.approvalStatus,decisionId:w.id,planId:b.id,providerKey:L0,receiptId:H.receiptId,threadId:V.id,traceId:b.traceId,workspaceId:X.repoId}},getExecutionTrace:(W)=>O4($.traceService,W),replayExecutionTrace:async(W)=>{if(W.decisionId)return $.traceService.replayExecutionTrace(W.decisionId);let j=await O4($.traceService,W);return j?W2(j):null}}}async function B2($,W,j){let Q=(await $.listDecisions({externalEventId:j,limit:1,providerKey:L0,workspaceId:W}))[0];return Q?{approvalStatus:Q.approvalStatus,decisionId:Q.id,planId:Q.actionPlan.id,providerKey:L0,receiptId:Q.receiptId,threadId:Q.threadId,traceId:Q.actionPlan.traceId,workspaceId:W}:null}async function O4($,W){if(W.decisionId)return $.getExecutionTrace(W.decisionId);if(!W.traceId)return null;return(await $.listExecutionTraces({limit:1,traceId:W.traceId}))[0]??null}function q2($){let W=n$($.verdict);return{confidence:$.verdict==="deny"?0.98:0.82,policyRef:void 0,reasons:$.checks.map((j)=>`${j.status}:${j.detail}`),responseText:$.summary??"Connect decision recorded.",requiresApproval:W.requiresApproval,riskTier:$.verdict==="permit"?"low":$.verdict==="rewrite"?"medium":$.verdict==="require_review"?"high":"blocked",verdict:W.controlPlaneVerdict}}function H2($){return $==="require_review"?["control-plane.approval.request"]:["control-plane.channel-runtime.reply.autonomous"]}function V2($,W){return`${$} [${W.tool}]`}function G2($){return A2("sha256").update($).digest("hex")}function S4($){return Object.fromEntries(Object.entries($).filter((W)=>Boolean(W[1])))}import{randomUUID as w2}from"crypto";function I4($){return{timestamp:$.createdAt,eventType:"connect.verify",decisionId:$.envelope.connectDecisionId,runtimeDecisionId:$.envelope.runtimeLink?.decisionId,taskId:$.verifyInput.taskId,verdict:$.envelope.verdict,tool:$.verifyInput.tool,traceId:$.envelope.runtimeLink?.traceId??$.contextPack.actor.traceId,actor:$.contextPack.actor,adapter:{channel:"cli",source:"connect",tool:$.verifyInput.tool},repoId:$.workspace.repoId,refs:{...$.envelope.artifacts,reviewPacket:$.reviewPacket!=null?$.envelope.artifacts.reviewPacket:void 0}}}import{randomUUID as J2}from"crypto";function M4($,W,j){let A=$?`Immutable path: ${$}`:W?`Protected path: ${W}`:j?`Generated path: ${j}`:"No protected path boundaries triggered.";return{id:"path-boundary",status:$?"fail":W||j?"warn":"pass",detail:A}}function E4($,W){let j=$==="deny"||$==="destructive"?"fail":$==="review"||$==="unknown"?"warn":"pass",A=W?`Command policy: ${$} (${W})`:`Command policy: ${$}`;return{id:"command-policy",status:j,detail:A}}function N4($,W,j){return{id:"impact-analysis",status:$?"fail":W||j?"warn":"pass",detail:$?"Breaking change detected.":W?"Generated-path drift detected.":j?"Impact could not be resolved.":"Impact resolved."}}function R4($,W,j,A,Q,Z){let X=Z.runtimeLink?.decisionId?`controlPlane.trace.get?decisionId=${Z.runtimeLink.decisionId}`:Z.runtimeLink?.traceId?`controlPlane.trace.get?traceId=${Z.runtimeLink.traceId}`:`controlPlane.trace.get?connectDecisionId=${W}`;return{id:`review_${J2()}`,sourceDecisionId:W,objective:A.objective,reason:Z.reason,summary:{paths:Q,impactedContracts:j.impactedContracts,affectedSurfaces:j.affectedSurfaces,requiredChecks:A.requiredChecks},evidence:[{type:"context-pack",ref:Z.artifactRefs.contextPack},{type:"plan-packet",ref:Z.artifactRefs.planPacket},{type:"patch-verdict",ref:Z.artifactRefs.patchVerdict},{type:"control-plane-trace",ref:X}],requiredApprovals:[{capability:T$.key,reason:Z.reason}],controlPlane:{traceQuery:SW,policyExplain:IW,approvalStatus:Z.runtimeLink?.approvalStatus,decisionId:Z.runtimeLink?.decisionId,traceId:Z.runtimeLink?.traceId??j.actor.traceId},studio:$.config.connect?.studio?.enabled?{enabled:!0,mode:$.config.connect.studio.mode,queue:$.config.connect.studio.queue}:{enabled:!1,mode:"off"}}}function Lj($,W,j,A,Q,Z,X,Y,B){let q=n$(X);return{decisionId:$,summary:A.objective,action:W.tool==="acp.fs.access"?{actionType:W.operation==="write"?"write_file":"edit_file",tool:W.tool,target:W.path}:{actionType:"run_command",tool:W.tool,cwd:W.cwd},impacted:Q,checks:Z,verdict:X,controlPlane:{verdict:q.controlPlaneVerdict,requiresApproval:q.requiresApproval,approvalStatus:B?.approvalStatus,decisionId:B?.decisionId,traceId:B?.traceId??j.actor.traceId},approvalOperationRefs:X==="require_review"?[`${T$.key}@${T$.version}`,`${MW.key}@${MW.version}`]:void 0,remediation:b2(X),reviewPacketRef:Y,replay:{traceQuery:SW,policyExplain:IW}}}function b2($){return $==="rewrite"?["Regenerate derived files instead of editing them directly."]:$==="require_review"?["Request human review for the flagged change set."]:$==="deny"?["Remove immutable or denied mutations before retrying."]:void 0}async function K2($,W,j={}){let A=d(W);a(A),A=x$(A,await $.git.currentBranch());let Q=`connect.dec_${w2()}`,Z=(j.now??(()=>new Date))().toISOString(),X=A$(A);await K0($.fs,X);let{contextPack:Y,planPacket:B}=await Uj($,{...W,candidate:_2(W)}),q=z2(W),H=await y$($,{baseline:W.baseline,touchedPaths:q,workspace:A}),V=await U2(j,A.config.connect?.policy?.smokeChecks??[],A.workspaceRoot),G=V.some((M)=>M.id.startsWith("smoke:")&&M.status==="fail"),J=J0(A,{commands:W.tool==="acp.terminal.exec"?[W.command]:[],impactAnalysis:H,smokeFailed:G,touchedPaths:q}),b=[M4(J.immutablePath,J.protectedPath,J.generatedPath),E4(J.commandState,J.commandMatch),N4(H.breakingChange,H.driftFiles.length>0,H.unknownPaths.length>0),...V],w=r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0}),L=H.pathImpacts.length>0?H.pathImpacts.map((M)=>({file:M.path,contracts:M.contracts,policies:M.policies,surfaces:M.surfaces})):q.map((M)=>({file:M,contracts:Y.impactedContracts,policies:[{key:"connect.policy",version:"1.0.0",kind:"policy"}],surfaces:Y.affectedSurfaces})),z=Lj(Q,W,Y,B,L,b,J.verdict,void 0),S=j.controlPlane?await j.controlPlane.linkDecision({connectDecisionId:Q,createdAt:Z,input:W,patchVerdict:z,planPacket:B,workspace:A}):null,U=S?{...B,controlPlane:{...B.controlPlane,decisionId:S.decisionId,traceId:S.traceId??B.controlPlane.traceId}}:B,O=J.verdict==="require_review"?R4(A,Q,Y,U,q,{artifactRefs:w,reason:J.reviewReason??"Connect policy requires human review before continuing.",runtimeLink:S}):void 0,K=Lj(Q,W,Y,U,L,b,J.verdict,O?V$($.fs,A,$.fs.join(X.reviewPacketsDir,`${O.id}.json`)):void 0,S);if(await wj($.fs,X,{contextPack:Y,planPacket:U,patchVerdict:K}),O)await _j($.fs,X,O);let _=await _0($.fs,X,Q,{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O}),I={artifacts:r$($.fs,A,X,Q,{contextPack:!0,patchVerdict:!0,planPacket:!0,reviewPacket:Boolean(O)}),connectDecisionId:Q,createdAt:Z,runtimeLink:S??void 0,taskId:W.taskId,verdict:J.verdict};return await z0($.fs,X,Q,I),await Kj($.fs,X,I4({contextPack:Y,createdAt:Z,envelope:I,reviewPacket:O,verifyInput:W,workspace:A})),{contextPack:Y,planPacket:U,patchVerdict:K,reviewPacket:O,historyDir:_}}function _2($){if($.tool==="acp.fs.access")return{objective:`${$.operation} ${$.path}`,touchedPaths:[$.path]};return{objective:`Run ${$.command}`,touchedPaths:$.touchedPaths,commands:[$.command]}}function z2($){return $.tool==="acp.fs.access"?[$.path]:$.touchedPaths??[]}async function U2($,W,j){if(!$.runCommand)return[];let A=[];for(let Q of W){let Z=await $.runCommand(Q,{cwd:j});A.push({id:`smoke:${Q}`,status:Z.exitCode===0?"pass":"fail",detail:Z.exitCode===0?`Passed: ${Q}`:`Failed (${Z.exitCode}): ${Q}`})}return A}DW();var Ij={};h(Ij,{generateWorkflowSpec:()=>Y8,generateWorkflowRunnerTemplate:()=>jW,generateWorkflowDevkitWorkflowTemplate:()=>a0,generateWorkflowDevkitStreamRouteTemplate:()=>$W,generateWorkflowDevkitStartRouteTemplate:()=>s0,generateWorkflowDevkitGenericTemplate:()=>WW,generateWorkflowDevkitFollowUpRouteTemplate:()=>e0,generateTestTemplate:()=>s5,generateTelemetrySpec:()=>X8,generatePresentationSpec:()=>Z8,generateOperationSpec:()=>Q8,generateMigrationSpec:()=>A8,generateKnowledgeSpaceSpec:()=>W8,generateIntegrationSpec:()=>$8,generateHandlerTemplate:()=>t5,generateFormSpec:()=>p5,generateFeatureSpec:()=>i5,generateExperimentSpec:()=>o5,generateEventSpec:()=>l5,generateDataViewSpec:()=>r5,generateDataViewRendererTemplate:()=>p0,generateComponentTemplate:()=>a5,generateAppBlueprintSpec:()=>c5});DW();class T4{ai;templates=Ij;constructor($){this.ai=new CW($)}}function GU($){return new T4($)}import{scanSpecSource as D2}from"@contractspec/module.workspace";function F4($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function zU($,W,j={}){let{fs:A,logger:Q}=W,Z=await A.exists($);if(!Z&&!j.force)return{specPath:$,specInfo:F4($),deleted:!1,cleanedFiles:[],errors:[`Spec file not found: ${$}`]};let X=F4($),Y;if(Z)try{let q=await A.readFile($);X=D2(q,$),Y=X.key}catch{}let B=[];if(j.clean&&Y)try{let q=await _W(Y,{fs:A});for(let H of q)try{await A.remove(H.filePath),B.push(H.filePath),Q.info(`Removed artifact: ${H.filePath}`)}catch{Q.warn(`Could not remove artifact: ${H.filePath}`)}}catch{Q.warn("Could not discover implementations for cleanup")}if(Z)await A.remove($),Q.info(`Deleted spec: ${$}`);return{specPath:$,specInfo:X,deleted:!0,cleanedFiles:B,errors:[]}}import{computeSemanticDiff as T2}from"@contractspec/module.workspace";async function OU($,W,j,A={}){let{fs:Q,git:Z}=j;if(!await Q.exists($))throw Error(`Spec file not found: ${$}`);let Y=await Q.readFile($),B,q;if(A.baseline)B=await Z.showFile(A.baseline,$),q=`${A.baseline}:${$}`;else{if(!await Q.exists(W))throw Error(`Spec file not found: ${W}`);B=await Q.readFile(W),q=W}let H=T2(Y,$,B,q,{breakingOnly:A.breakingOnly});return{spec1:$,spec2:q,differences:H}}i();import{openApiForRegistry as F2}from"@contractspec/lib.contracts-spec/openapi";import{OperationSpecRegistry as Mj}from"@contractspec/lib.contracts-spec/operations";async function x2($,W){let{fs:j,logger:A}=W,{registryPath:Q,outputPath:Z="./openapi.json"}=$;A.info("Loading registry...",{registryPath:Q});let X=await y2(Q,j);A.info("Generating OpenAPI document...");let Y=F2(X,{title:$.title,version:$.version,description:$.description,servers:$.servers}),B=JSON.stringify(Y,null,2)+`
|
|
1670
|
+
`,q=j.resolve(Z);return await j.mkdir(j.dirname(q)),await j.writeFile(q,B),A.info(`OpenAPI document written to ${q}`),{document:Y,outputPath:q,json:B}}async function y2($,W){let A=await import(W.resolve($));if(A instanceof Mj)return A;if(A.registry instanceof Mj)return A.registry;let Q=typeof A.createRegistry==="function"?A.createRegistry:typeof A.default==="function"?A.default:void 0;if(Q){let Z=await Q();if(Z instanceof Mj)return Z}throw Error(`Registry module ${$} must export a OperationSpecRegistry instance or a factory function returning one.`)}import{importFromOpenApi as v2,parseOpenApi as m2}from"@contractspec/lib.contracts-transformers/openapi";import{basename as Ej,dirname as x4,join as l$}from"path";function P2($,W,j){if(W.outputDir)return W.outputDir;let{outputDir:A,conventions:Q}=j;switch($){case"operation":return l$(A,Q.operations.split("|")[0]??"operations");case"event":return l$(A,Q.events);case"model":return l$(A,"models");default:return A}}async function y4($,W,j){let{fs:A,logger:Q}=j,{source:Z,prefix:X,tags:Y,exclude:B,defaultStability:q,defaultOwners:H,defaultAuth:V,dryRun:G=!1}=W;Q.info(`Importing from OpenAPI: ${Z}`);let J=await m2(Z,{fetch:globalThis.fetch,readFile:(U)=>A.readFile(U)});if(J.warnings.length>0)for(let U of J.warnings)Q.warn(`Parse warning: ${U}`);Q.info(`Parsed ${J.operations.length} operations from ${J.info.title} v${J.info.version}`);let b=v2(J,$,{prefix:X,tags:Y,exclude:B,defaultStability:q,defaultOwners:H,defaultAuth:V});Q.info(`Import result: ${b.summary.imported} imported, ${b.summary.skipped} skipped, ${b.summary.errors} errors`);let w=[],L=[],z=[],S=new Map;for(let U of b.operationSpecs){let O="operation",K=null;if(U.code.includes("defineEvent("))O="event",K=U.code.match(/export const (\w+)\s*=\s*defineEvent/);else if((U.code.includes("defineSchemaModel(")||U.code.includes("new EnumType(")||U.code.includes("ScalarTypeEnum.")||U.code.includes("new ZodSchemaType(")||U.code.includes("z.enum(")||U.code.includes("new JsonSchemaType(")||U.code.includes("new GraphQLSchemaType("))&&!U.code.includes("defineCommand(")&&!U.code.includes("defineQuery("))O="model";else O="operation",K=U.code.match(/export const (\w+)\s*=\s*define(?:Command|Query)/);let _=P2(O,W,$),I=l$(_,U.fileName);if(!K&&O==="model"){if(U.code.includes("new ZodSchemaType("))K=U.code.match(/export const (\w+)\s*=\s*new ZodSchemaType\(/);else if(U.code.includes("new JsonSchemaType("))K=U.code.match(/export const (\w+)\s*=\s*new JsonSchemaType\(/);else if(U.code.includes("new GraphQLSchemaType("))K=U.code.match(/export const (\w+)\s*=\s*new GraphQLSchemaType\(/);if(!K)K=U.code.match(/export const (\w+)\s*=/)}if(G)Q.info(`[DRY RUN] Would create: ${I}`);else{let M=x4(I);if(!await A.exists(M))await A.mkdir(M);await A.writeFile(I,U.code),Q.info(`Created: ${I}`)}if(w.push({path:I,operationId:U.source.sourceId,specName:U.fileName.replace(".ts","")}),K){let M=x4(I),E=S.get(M)||[];E.push({file:Ej(I),name:K[1],type:O}),S.set(M,E)}}if(!G&&w.length>0)for(let[U,O]of S.entries()){if(O.length===0)continue;let K=O.map((x)=>x.type),_=K.every((x)=>x==="operation"),I=K.every((x)=>x==="event"),M=K.every((x)=>x==="model"),E=`/**
|
|
1432
1671
|
* Auto-generated registry file.
|
|
1433
1672
|
*/
|
|
1434
|
-
`;
|
|
1435
|
-
`}),
|
|
1436
|
-
`;let
|
|
1673
|
+
`;O.forEach((x)=>{let L$=`./${Ej(x.file,".ts")}`;E+=`import { ${x.name} } from '${L$}';
|
|
1674
|
+
`}),E+=`
|
|
1675
|
+
`;let C=!1;if(_)E+=`import { OperationSpecRegistry } from '@contractspec/lib.contracts-spec';
|
|
1437
1676
|
|
|
1438
|
-
`,
|
|
1439
|
-
`,
|
|
1440
|
-
`}),
|
|
1677
|
+
`,E+=`export const operationRegistry = new OperationSpecRegistry();
|
|
1678
|
+
`,O.forEach((x)=>{E+=`operationRegistry.register(${x.name});
|
|
1679
|
+
`}),C=!0;else if(I)E+=`import { EventRegistry } from '@contractspec/lib.contracts-spec';
|
|
1441
1680
|
|
|
1442
|
-
`,
|
|
1443
|
-
`,
|
|
1444
|
-
`}),
|
|
1681
|
+
`,E+=`export const eventRegistry = new EventRegistry();
|
|
1682
|
+
`,O.forEach((x)=>{E+=`eventRegistry.register(${x.name});
|
|
1683
|
+
`}),C=!0;else if(M)E+=`import { ModelRegistry } from '@contractspec/lib.contracts-spec/model-registry';
|
|
1445
1684
|
|
|
1446
|
-
`,
|
|
1447
|
-
`,
|
|
1448
|
-
`}),
|
|
1685
|
+
`,E+=`export const modelRegistry = new ModelRegistry();
|
|
1686
|
+
`,O.forEach((x)=>{E+=`modelRegistry.register(${x.name});
|
|
1687
|
+
`}),C=!0;if(C){let x=l$(U,"registry.ts");await A.writeFile(x,E),Q.info(`Created/Updated registry: ${x}`)}let R=`/**
|
|
1449
1688
|
* Auto-generated barrel file.
|
|
1450
1689
|
*/
|
|
1451
1690
|
|
|
1452
|
-
`;if(
|
|
1453
|
-
`}),
|
|
1454
|
-
`;let
|
|
1455
|
-
{ key: '${W.key}', version: ${X} },`;return{index:
|
|
1691
|
+
`;if(O.forEach((x)=>{let L$=`./${Ej(x.file,".ts")}`;R+=`export * from '${L$}';
|
|
1692
|
+
`}),C)R+=`export * from './registry';
|
|
1693
|
+
`;let v=l$(U,"index.ts");await A.writeFile(v,R),Q.info(`Created/Updated index: ${v}`)}for(let U of b.skipped)L.push({operationId:U.sourceId,reason:U.reason}),Q.debug(`Skipped: ${U.sourceId} - ${U.reason}`);for(let U of b.errors)z.push({operationId:U.sourceId,error:U.error}),Q.error(`Error: ${U.sourceId} - ${U.error}`);return{imported:b.summary.imported,skipped:b.summary.skipped,errors:b.summary.errors,files:w,skippedOperations:L,errorMessages:z}}import{importFromOpenApi as k2,parseOpenApi as h2}from"@contractspec/lib.contracts-transformers/openapi";import{dirname as g2,join as f2}from"path";async function vU($,W,j){let{fs:A,logger:Q}=j,{sources:Z,sourceName:X,interactive:Y,force:B,dryRun:q}=$,{outputDir:H}=W,V=Z??W.openapi?.sources??[];if(X){if(V=V.filter((J)=>J.name===X),V.length===0)throw Error(`Source not found: ${X}`)}if(V.length===0)return Q.warn("No OpenAPI sources configured. Add sources to .contractsrc.json"),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let G={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let J of V){Q.info(`Syncing with source: ${J.name}`);let b=J.url??J.file;if(!b){Q.warn(`Source ${J.name} has no url or file configured`);continue}let w=await h2(b,{fetch:globalThis.fetch,readFile:(z)=>A.readFile(z)});Q.info(`Parsed ${w.operations.length} operations from ${J.name}`);let L=k2(w,W,{prefix:J.prefix,tags:J.tags,exclude:J.exclude,defaultStability:J.defaultStability,defaultAuth:J.defaultAuth});for(let z of L.operationSpecs){let S=f2(H,z.fileName);if(!await A.exists(S)){if(!q){let O=g2(S);await A.mkdir(O),await A.writeFile(S,z.code)}G.added++,G.changes.push({operationId:z.source.sourceId,action:"added",path:S}),Q.info(`Added: ${z.source.sourceId}`)}else if(await A.readFile(S)===z.code)G.unchanged++,G.changes.push({operationId:z.source.sourceId,action:"unchanged",path:S});else if(B==="openapi"){if(!q)await A.writeFile(S,z.code);G.updated++,G.changes.push({operationId:z.source.sourceId,action:"updated",path:S}),Q.info(`Updated: ${z.source.sourceId}`)}else if(B==="contractspec")G.unchanged++,G.changes.push({operationId:z.source.sourceId,action:"unchanged",path:S}),Q.info(`Kept: ${z.source.sourceId}`);else if(Y)G.conflicts++,G.changes.push({operationId:z.source.sourceId,action:"conflict",path:S}),Q.warn(`Conflict: ${z.source.sourceId} - needs resolution`);else G.conflicts++,G.changes.push({operationId:z.source.sourceId,action:"conflict",path:S}),Q.warn(`Conflict: ${z.source.sourceId}`)}}return Q.info(`Sync complete: ${G.added} added, ${G.updated} updated, ${G.unchanged} unchanged, ${G.conflicts} conflicts`),G}import{parseOpenApi as u2}from"@contractspec/lib.contracts-transformers/openapi";async function kU($,W){let{fs:j,logger:A}=W,{specPath:Q,openApiSource:Z,ignoreDescriptions:X,ignoreTags:Y,ignoreTransport:B}=$;A.info(`Validating specs against OpenAPI: ${Z}`);let q=await u2(Z,{fetch:globalThis.fetch,readFile:(z)=>j.readFile(z)});A.info(`Parsed ${q.operations.length} operations from ${q.info.title}`);let H=new Map;for(let z of q.operations)H.set(z.operationId,z);let V=[],G=0,J=0,b=await j.stat(Q),w=[];if(b.isDirectory){let z=await j.glob({pattern:"**/*.ts",cwd:Q,ignore:["node_modules/**","dist/**","*.test.ts","*.spec.ts"],absolute:!0});w.push(...z)}else w.push(Q);A.info(`Found ${w.length} spec files to validate`);for(let z of w)try{let S=await j.readFile(z),U=S.match(/operationId:\s*['"]([^'"]+)['"]/)||S.match(/name:\s*['"]([^'"]+)['"]/)||S.match(/export\s+const\s+(\w+)Spec\s*=/);if(!U||!U[1]){A.debug(`Could not extract operationId from ${z}`);continue}let O=U[1];G++;let K;if(K=H.get(O),!K){let M=O.replace(/([A-Z])/g,"_$1").toLowerCase();K=H.get(M)}if(!K){for(let[M,E]of H)if(M.toLowerCase().includes(O.toLowerCase())||O.toLowerCase().includes(M.toLowerCase())){K=E;break}}if(!K){V.push({specPath:z,valid:!1,diffs:[{path:"",type:"removed",description:`No matching operation found in OpenAPI for spec: ${O}`}]}),J++;continue}let _=[];if(K.deprecated&&!S.includes("deprecated"))_.push({path:"meta.stability",type:"modified",description:"OpenAPI operation is deprecated but spec does not indicate deprecation"});if(!B){let M=S.match(/path:\s*['"]([^'"]+)['"]/);if(M&&M[1]!==K.path)_.push({path:"transport.rest.path",type:"modified",description:`Path mismatch: spec has "${M[1]}", OpenAPI has "${K.path}"`})}if(!B){let M=S.match(/method:\s*['"]([^'"]+)['"]/);if(M?.[1]&&M[1].toLowerCase()!==K.method.toLowerCase())_.push({path:"transport.rest.method",type:"modified",description:`Method mismatch: spec has "${M[1]}", OpenAPI has "${K.method.toUpperCase()}"`})}let I=_.length===0;if(!I)J++;V.push({specPath:z,operationId:K.operationId,valid:I,diffs:_})}catch(S){A.error(`Error validating ${z}: ${S}`),V.push({specPath:z,valid:!1,diffs:[{path:"",type:"modified",description:`Error: ${S instanceof Error?S.message:String(S)}`}]}),J++}let L=J===0;return A.info(`Validation ${L?"passed":"failed"}: ${G} specs checked, ${J} with differences`),{valid:L,specsValidated:G,specsWithDiffs:J,results:V}}async function oU($,W,j){let{fs:A,logger:Q}=$,{source:Z,outputDir:X}=W,Y=A.resolve(j??process.cwd(),Z);if(!await A.exists(Y))throw Error(`Source file not found: ${Y}`);let q={...await m(A,j),outputDir:X};return Q.info(`Extracting contracts from ${Y} to ${X}`),y4(q,{source:Y,outputDir:X,dryRun:!1},$)}var m4={};h(m4,{validateFeatureRefs:()=>c2,getArrayNameForSpecType:()=>v4,detectFeatureContext:()=>d2,computeAddSpecEdit:()=>n2});function d2($,W){let j=[{type:"operations",regex:/operations\s*:\s*\[/g,specType:"operation"},{type:"events",regex:/events\s*:\s*\[/g,specType:"event"},{type:"presentations",regex:/presentations\s*:\s*\[/g,specType:"presentation"}],A=null;for(let{type:V,regex:G,specType:J}of j){let b;G.lastIndex=0;while((b=G.exec($))!==null)if(!A||b.index>A.index)A={type:V,specType:J,index:b.index}}if(!A)return null;let Q=$.slice(A.index)+W,Z=A.type;new RegExp(`${Z}\\s*:\\s*\\[`).exec(Q);let Y=$.slice(A.index),B=0,q=!1,H="";for(let V=0;V<Y.length;V++){let G=Y[V],J=V>0?Y[V-1]:"";if((G==='"'||G==="'"||G==="`")&&J!=="\\"){if(!q)q=!0,H=G;else if(G===H)q=!1;continue}if(q)continue;if(G==="[")B++;else if(G==="]"){if(B--,B===0)return null}}if(B>0)return{type:A.type,specType:A.specType};return null}function n2($,W){let j=v4(W.type),Q=new RegExp(`${j}\\s*:\\s*\\[`,"g").exec($);if(Q){let Z=Q.index+Q[0].length,X=typeof W.version==="string"?`'${W.version}'`:W.version,Y=`
|
|
1694
|
+
{ key: '${W.key}', version: ${X} },`;return{index:Z,text:Y}}return null}function v4($){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 c2($,W){let j=[],A=(Q,Z,X)=>{for(let Y of Q){let B=`${Y.key}.v${Y.version}`;if(!Z.has(B))j.push({key:Y.key,version:Y.version,type:X,message:`${X} ${Y.key}.v${Y.version} not found`})}};return A($.operations,W.operations,"Operation"),A($.events,W.events,"Event"),A($.presentations,W.presentations,"Presentation"),A($.experiments,W.experiments,"Experiment"),j}var g4={};h(g4,{removeReferenceStrategy:()=>yW,implementSkeletonStrategy:()=>xW,implementAiStrategy:()=>FW,generateFixLinks:()=>r2,FixService:()=>h4,FIX_STRATEGY_STABILITY:()=>N0,FIX_STRATEGY_LABELS:()=>a2,CiOutputSchema:()=>BY});function r2($,W){let j=[];if(!$.ref||!$.file)return j;if(W.includeCli)j.push({type:"cli",label:"Fix with CLI",value:`contractspec fix --target "${$.file}"`});if(W.includeVscode){let A=$.file.startsWith("/")?$.file:`/${$.file}`,Q=$.ref,Z=Q.line||1,X=Q.column||1;j.push({type:"vscode",label:"Open in VS Code",value:`vscode://file${A}:${Z}:${X}`})}if(W.includeGithubIssue&&W.repository){let A=encodeURIComponent(`Fix Integrity Issue: ${$.message}`),Q=encodeURIComponent(`Found integrity issue in \`${$.file}\`:
|
|
1456
1695
|
|
|
1457
1696
|
> ${$.message}
|
|
1458
1697
|
|
|
1459
|
-
Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${W.repository}/issues/new?title=${
|
|
1460
|
-
`)}function
|
|
1698
|
+
Reference: \`${$.ref.key}.v${$.ref.version}\``);j.push({type:"github-issue",label:"Create Issue",value:`https://github.com/${W.repository}/issues/new?title=${A}&body=${Q}`})}return j}import s2 from"node:path";function w$($){return $.split(/[-_.]/).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join("")}function K$($,W){let j=$.enrichment?.owners?.length?$.enrichment.owners.map((X)=>`'${X}'`).join(", "):"'@team'",A=$.enrichment?.tags?.length?$.enrichment.tags.map((X)=>`'${X}'`).join(", "):"",Q=$.description||`TODO: Add description for ${$.key}`,Z=[`key: '${$.key}'`,`version: '${$.version}'`,`stability: '${$.stability}'`];if(W)Object.entries(W).forEach(([X,Y])=>{if(Y!==void 0)Z.push(`${X}: ${Y}`)});return Z.push(`owners: [${j}]`),Z.push(`tags: [${A}]`),Z.push(`description: '${Q}'`),Z.join(`,
|
|
1699
|
+
`)}function S0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"Spec",A=K$($,{kind:"'api'"});return`/**
|
|
1461
1700
|
* Capability: ${$.key}
|
|
1462
1701
|
*
|
|
1463
1702
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1470,7 +1709,7 @@ import { defineCapability } from '@contractspec/lib.contracts-spec';
|
|
|
1470
1709
|
|
|
1471
1710
|
export const ${j} = defineCapability({
|
|
1472
1711
|
meta: {
|
|
1473
|
-
${
|
|
1712
|
+
${A}
|
|
1474
1713
|
},
|
|
1475
1714
|
|
|
1476
1715
|
provides: [
|
|
@@ -1494,7 +1733,7 @@ export const ${j} = defineCapability({
|
|
|
1494
1733
|
// }
|
|
1495
1734
|
],
|
|
1496
1735
|
});
|
|
1497
|
-
`}function
|
|
1736
|
+
`}function I0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"EventSpec",A=j.replace("Spec","Payload"),Q=K$($);return`/**
|
|
1498
1737
|
* Event: ${$.key}
|
|
1499
1738
|
*
|
|
1500
1739
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1507,8 +1746,8 @@ import { defineEvent } from '@contractspec/lib.contracts-spec';
|
|
|
1507
1746
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1508
1747
|
|
|
1509
1748
|
// TODO: Define event payload schema
|
|
1510
|
-
export const ${
|
|
1511
|
-
name: '${
|
|
1749
|
+
export const ${A} = new SchemaModel({
|
|
1750
|
+
name: '${A}',
|
|
1512
1751
|
description: 'Payload for ${$.key} event',
|
|
1513
1752
|
fields: {
|
|
1514
1753
|
// Add your payload fields here
|
|
@@ -1520,10 +1759,10 @@ export const ${Q} = new SchemaModel({
|
|
|
1520
1759
|
|
|
1521
1760
|
export const ${j} = defineEvent({
|
|
1522
1761
|
meta: {
|
|
1523
|
-
${
|
|
1762
|
+
${Q}
|
|
1524
1763
|
},
|
|
1525
1764
|
|
|
1526
|
-
payload: ${
|
|
1765
|
+
payload: ${A},
|
|
1527
1766
|
|
|
1528
1767
|
// TODO: Specify PII fields if any
|
|
1529
1768
|
// piiFields: ['user.email'],
|
|
@@ -1534,7 +1773,7 @@ export const ${j} = defineEvent({
|
|
|
1534
1773
|
// policy: 'archive',
|
|
1535
1774
|
// },
|
|
1536
1775
|
});
|
|
1537
|
-
`}function
|
|
1776
|
+
`}function l2($){let W=$.toLowerCase(),j=["get","list","search","find","fetch","read","query","browse","view","show","navigate"];for(let A of j)if(W.includes(A))return"query";return"command"}function M0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"Spec",A=j.replace("Spec","Input"),Q=j.replace("Spec","Output"),Z=l2($.key),X=Z==="query"?"defineQuery":"defineCommand",Y=$.enrichment?.goal||"TODO: Define the business goal",B=$.enrichment?.context||"TODO: Provide context",q=K$($,{goal:`'${Y}'`,context:`'${B}'`});return`/**
|
|
1538
1777
|
* Operation: ${$.key}
|
|
1539
1778
|
*
|
|
1540
1779
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1547,8 +1786,8 @@ import { ${X} } from '@contractspec/lib.contracts-spec';
|
|
|
1547
1786
|
import { ScalarTypeEnum, SchemaModel } from '@contractspec/lib.schema';
|
|
1548
1787
|
|
|
1549
1788
|
// TODO: Define input schema
|
|
1550
|
-
export const ${
|
|
1551
|
-
name: '${
|
|
1789
|
+
export const ${A} = new SchemaModel({
|
|
1790
|
+
name: '${A}',
|
|
1552
1791
|
description: 'Input for ${$.key}',
|
|
1553
1792
|
fields: {
|
|
1554
1793
|
// Add your input fields here
|
|
@@ -1557,8 +1796,8 @@ export const ${Q} = new SchemaModel({
|
|
|
1557
1796
|
});
|
|
1558
1797
|
|
|
1559
1798
|
// TODO: Define output schema
|
|
1560
|
-
export const ${
|
|
1561
|
-
name: '${
|
|
1799
|
+
export const ${Q} = new SchemaModel({
|
|
1800
|
+
name: '${Q}',
|
|
1562
1801
|
description: 'Output for ${$.key}',
|
|
1563
1802
|
fields: {
|
|
1564
1803
|
// Add your output fields here
|
|
@@ -1568,12 +1807,12 @@ export const ${Z} = new SchemaModel({
|
|
|
1568
1807
|
|
|
1569
1808
|
export const ${j} = ${X}({
|
|
1570
1809
|
meta: {
|
|
1571
|
-
${
|
|
1810
|
+
${q}
|
|
1572
1811
|
},
|
|
1573
1812
|
|
|
1574
1813
|
io: {
|
|
1575
|
-
input: ${
|
|
1576
|
-
output: ${
|
|
1814
|
+
input: ${A},
|
|
1815
|
+
output: ${Q},
|
|
1577
1816
|
errors: {
|
|
1578
1817
|
// TODO: Define possible errors
|
|
1579
1818
|
// EXAMPLE_ERROR: {
|
|
@@ -1595,7 +1834,7 @@ export const ${j} = ${X}({
|
|
|
1595
1834
|
},
|
|
1596
1835
|
|
|
1597
1836
|
transport: {
|
|
1598
|
-
rest: { method: '${
|
|
1837
|
+
rest: { method: '${Z==="command"?"POST":"GET"}' },
|
|
1599
1838
|
gql: { field: '${$.key.replace(/\./g,"_")}' },
|
|
1600
1839
|
mcp: { toolName: '${$.key.replace(/\./g,"_")}-v${String($.version).replace(/\./g,"_")}' },
|
|
1601
1840
|
},
|
|
@@ -1612,7 +1851,7 @@ export const ${j} = ${X}({
|
|
|
1612
1851
|
examples: [],
|
|
1613
1852
|
},
|
|
1614
1853
|
});
|
|
1615
|
-
`}function
|
|
1854
|
+
`}function o2($){let W=$.toLowerCase();if(W.includes("doc")||W.includes("guide")||W.includes("readme"))return"markdown";if(W.includes("data")||W.includes("api")||W.includes("export"))return"data";return"web_component"}function E0($){let W=$.key.split(".").pop()||"Unknown",j=w$(W)+"PresentationSpec",A=o2($.key),Q=K$($);return`/**
|
|
1616
1855
|
* Presentation: ${$.key}
|
|
1617
1856
|
*
|
|
1618
1857
|
* Skeleton spec generated by ContractSpec fix command.
|
|
@@ -1625,10 +1864,10 @@ import { definePresentation } from '@contractspec/lib.contracts-spec';
|
|
|
1625
1864
|
|
|
1626
1865
|
export const ${j} = definePresentation({
|
|
1627
1866
|
meta: {
|
|
1628
|
-
${
|
|
1867
|
+
${Q}
|
|
1629
1868
|
},
|
|
1630
1869
|
|
|
1631
|
-
kind: '${
|
|
1870
|
+
kind: '${A}',
|
|
1632
1871
|
|
|
1633
1872
|
// TODO: Define content structure
|
|
1634
1873
|
content: {
|
|
@@ -1652,7 +1891,7 @@ export const ${j} = definePresentation({
|
|
|
1652
1891
|
// focusable: true,
|
|
1653
1892
|
// },
|
|
1654
1893
|
});
|
|
1655
|
-
`}import Q$ from"node:path";function ZW($,W){if(W.outputDir)return a1(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=GX($.featureFile);if(j)return a1(j,$.ref.key,$.specType)}return a1(Q$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function GX($){let W=Q$.dirname($),j=Q$.parse($).root,Q=0;while(W!==j&&Q<50){if(Q$.basename(W)==="src")return W;W=Q$.dirname(W),Q++}W=Q$.dirname($),Q=0;while(W!==j&&Q<50)W=Q$.dirname(W),Q++;let Z=$.lastIndexOf(`${Q$.sep}src${Q$.sep}`);if(Z!==-1)return $.substring(0,Z+5);return null}function a1($,W,j){let Q=W.replace(/\./g,"-").toLowerCase(),Z=zX(j),B=JX(j);return Q$.join($,B,`${Q}${Z}`)}function zX($){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 JX($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var KX={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},H0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function BW($,W,j){let{fs:Q,logger:Z}=j,{ref:B,specType:X,featureKey:Y}=$;try{let q={key:B.key,version:B.version,specType:X,stability:H0["implement-ai"],featureKey:Y},A=q;if(W.aiConfig)try{A=await _X(q,W,Z)}catch(z){Z.warn("AI enrichment failed, falling back to skeleton",{error:z instanceof Error?z.message:String(z)})}else Z.info("No AI config provided, using skeleton with experimental stability");let H=OX(A);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=ZW($,W),G=[];if(!W.dryRun){let z=UX.dirname(V);await Q.mkdir(z),await Q.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(q){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:q instanceof Error?q.message:String(q)}}}async function _X($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Z}=await Promise.resolve().then(() => (WW(),U4)),B=LX(W),X=new Z(B),Y=$.specType==="operation"?"command":$.specType,q=`${l4($.specType)} for ${$.key}`;if($.specType==="operation"){let A=await X.generateOperationSpec(q,Y);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:A.owners,tags:A.tags}}}if($.specType==="event"){let A=await X.generateEventSpec(q);return{...$,description:A.description,enrichment:{goal:`Emit ${$.key} event`,context:A.description,owners:["@team"],tags:A.tags}}}}catch(Z){j.warn("AIGenerator call failed, falling back to heuristics",{error:Z instanceof Error?Z.message:String(Z)})}let Q=IX($.key,$.specType);return{...$,description:Q.description,enrichment:{goal:Q.goal,context:Q.context,owners:["@team"],tags:Q.tags}}}function LX($){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 IX($,W){let j=$.split("."),Q=j[0]||"unknown",Z=j.slice(1).join(" ").replace(/_/g," "),B=[Q],X=Z.toLowerCase().split(" "),q=["auth","user","admin","api","data","search","create","update","delete"].filter((A)=>X.some((H)=>H.includes(A)));return{description:`${l4(W)} for ${Q} ${Z}`,goal:`Enable ${Z} functionality in the ${Q} domain`,context:`Part of the ${Q} feature set. Generated by ContractSpec AI fix.`,tags:[...B,...q]}}function OX($){switch($.specType){case"operation":return q0($);case"event":return Y0($);case"presentation":return A0($);case"capability":return X0($);default:return}}function l4($){return $.charAt(0).toUpperCase()+$.slice(1)}import bX from"node:path";async function XW($,W,j){let{fs:Q}=j,{ref:Z,specType:B,featureKey:X}=$;try{let Y={key:Z.key,version:Z.version,specType:B,stability:H0["implement-skeleton"],description:`Skeleton spec for ${Z.key}`,featureKey:X},q=wX(Y);if(!q)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${B}`};let A=ZW($,W),H=[];if(!W.dryRun){let V=bX.dirname(A);await Q.mkdir(V),await Q.writeFile(A,q),H.push({path:A,action:"created"})}else H.push({path:A,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 wX($){switch($.specType){case"operation":return q0($);case"event":return Y0($);case"presentation":return A0($);case"capability":return X0($);default:return}}async function YW($,W,j){let{fs:Q}=j,{ref:Z,featureFile:B,specType:X}=$;try{let Y=await Q.readFile(B),q=Y,A=CX(Y,Z,X);if(A===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Z.key}.v${Z.version} in ${B}`};let H=[];if(!W.dryRun)await Q.writeFile(B,A),H.push({path:B,action:"modified",previousContent:q});else H.push({path:B,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 CX($,W,j){if(!SX(j))return $;let Z=r4(W.key),B=r4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Z}['"],\\s*version:\\s*['"]${B}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${B}['"],\\s*key:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let q of X)Y=Y.replace(q,"");return Y=EX(Y),Y}function SX($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function r4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function EX($){return $.replace(/,(\s*)\]/g,"$1]")}class o4{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)=>BW(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,Q=0;for(let Z of $.issues)try{let B=await this.fixIssue(Z,$.options);if(W.push(B),B.success)j++;else Q++}catch(B){Q++,W.push({success:!1,strategy:$.options.strategy,issue:Z,filesChanged:[],error:B instanceof Error?B.message:String(B)})}return{total:$.issues.length,succeeded:j,failed:Q,results:W}}async scanAndGetFixables($={}){return(await l0(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:Q,select:Z}=W;if(j)return Promise.resolve(j);if(Q&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof Z==="function")return Z($,$.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 g$}from"zod";var MX=g$.union([g$.array(g$.unknown()),g$.object({issues:g$.array(g$.unknown())}).transform(($)=>$.issues)]);import{exec as NX}from"node:child_process";import{promisify as RX}from"node:util";var DX=RX(NX),i4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function i_($,W,j={}){if($.length===0)return;let Q=j.cwd??process.cwd(),Z=i4[j.type??"biome"]??i4.biome,B=50;for(let X=0;X<$.length;X+=B){let q=$.slice(X,X+B).map((A)=>`"${A}"`).join(" ");try{await DX(`${Z} ${q}`,{cwd:Q})}catch(A){}}}import G$ from"path";async function e_($,W){let j=G$.join(W,"contracts"),Q=G$.join(W,"generated"),Z=G$.join(Q,"docs"),B=await $.fs.exists(j),X=await $.fs.exists(Q);if(!B)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await h($,{pattern:"contracts/**/*.ts"}),q=[];if(X)for(let z of Y){let J=z.key||G$.basename(z.filePath,".ts"),K=G$.join(Z,`${J}.md`);if(!await $.fs.exists(K))q.push(J)}else if(Y.length>0)for(let z of Y){let J=z.key||G$.basename(z.filePath,".ts");q.push(J)}let A=G$.join(j,"index.ts"),H=G$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(A),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:q,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var e4={};P(e4,{runHook:()=>a4,getAvailableHooks:()=>t4});import{exec as FX}from"node:child_process";import{promisify as xX}from"node:util";var TX=xX(FX);async function a4($,W){let{fs:j,logger:Q}=$,{hookName:Z,dryRun:B=!1}=W,X=R(W.workspaceRoot);Q.info(`Running hook: ${Z}`,{workspaceRoot:X,dryRun:B});let Y=await s4(j,X);if(!Y)return{hookName:Z,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let q=Y[Z];if(!q||q.length===0)return{hookName:Z,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Z}`};Q.info(`Found ${q.length} command(s) for ${Z}`);let A=[],H=!0;for(let G of q){if(B){Q.info(`[DRY RUN] Would execute: ${G}`),A.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}Q.info(`Executing: ${G}`);try{let{stdout:z,stderr:J}=await TX(G,{cwd:X,timeout:300000});A.push({command:G,success:!0,exitCode:0,stdout:z,stderr:J}),Q.info(`✓ ${G}`)}catch(z){H=!1;let J=z;A.push({command:G,success:!1,exitCode:J.code??1,stdout:J.stdout??"",stderr:J.stderr??J.message??String(z)}),Q.error(`✗ ${G}`,{exitCode:J.code,stderr:J.stderr});break}}let V=A.filter((G)=>G.success).length;return{hookName:Z,success:H,commandResults:A,totalCommands:q.length,successfulCommands:V,summary:H?`✓ All ${q.length} command(s) passed`:`✗ ${V}/${q.length} command(s) passed`}}async function t4($,W){let j=await s4($.fs,W);return j?Object.keys(j):[]}async function s4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let Q=await $.readFile(j);return JSON.parse(Q).hooks??null}catch{return null}}import{detectFramework as vX,extractFromProject as yX}from"@contractspec/lib.source-extractors";import{generateOperations as PX,generateRegistry as mX,generateSchemas as kX}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as gX}from"@contractspec/lib.source-extractors/extractors";import{dirname as hX,join as t1}from"path";async function fX($,W,j,Q){let{fs:Z,logger:B}=j,X=Q??process.cwd();gX(),B.info(`Scanning source code in ${X}...`);let Y={readFile:(I)=>Z.readFile(I),glob:(I,U)=>Z.glob({pattern:I,cwd:U?.cwd}),exists:(I)=>Z.exists(I)},q=await vX(X,{readFile:(I)=>Z.readFile(I),glob:(I)=>Z.glob({pattern:I})});if(q.frameworks.length===0)return B.warn("No supported frameworks detected"),{success:!1,report:uX(),errors:["No supported frameworks detected in project"]};B.info(`Detected frameworks: ${q.frameworks.map((I)=>I.name).join(", ")}`);let{extractorRegistry:A}=await import("@contractspec/lib.source-extractors");for(let I of A.getAll())if("setFs"in I&&typeof I.setFs==="function")I.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await yX(q,H);if(!V.success||!V.ir)return{success:!1,report:dX(V.errors??[]),errors:V.errors?.map((I)=>I.message)};let G=V.ir;if(B.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:nX(G)};let z=W.outputDir??t1($.outputDir,"generated"),J={outputDir:z,defaultAuth:"user"},K=PX(G,J),_=kX(G,J),w=mX(K),b=[...K,..._,w];if(!W.dryRun)for(let I of b){let U=t1(z,I.path),O=hX(U);if(!await Z.exists(O))await Z.mkdir(O);await Z.writeFile(U,I.content),B.info(`Created: ${U}`)}else for(let I of b)B.info(`[DRY RUN] Would create: ${t1(z,I.path)}`);let L={files:b,operationsGenerated:K.length,schemasGenerated:_.length,warnings:[]};return{success:!0,ir:G,generation:L,report:cX(G,L,W)}}function uX(){return`# Import Report
|
|
1894
|
+
`}import X$ from"node:path";function TW($,W){if(W.outputDir)return Nj(W.outputDir,$.ref.key,$.specType);if($.featureFile){let j=i2($.featureFile);if(j)return Nj(j,$.ref.key,$.specType)}return Nj(X$.join(W.workspaceRoot,"specs"),$.ref.key,$.specType)}function i2($){let W=X$.dirname($),j=X$.parse($).root,A=0;while(W!==j&&A<50){if(X$.basename(W)==="src")return W;W=X$.dirname(W),A++}W=X$.dirname($),A=0;while(W!==j&&A<50)W=X$.dirname(W),A++;let Q=$.lastIndexOf(`${X$.sep}src${X$.sep}`);if(Q!==-1)return $.substring(0,Q+5);return null}function Nj($,W,j){let A=W.replace(/\./g,"-").toLowerCase(),Q=p2(j),Z=t2(j);return X$.join($,Z,`${A}${Q}`)}function p2($){return{operation:".operation.ts",event:".event.ts",presentation:".presentation.ts",workflow:".workflow.ts","data-view":".data-view.ts",form:".form.ts",migration:".migration.ts",experiment:".experiment.ts",capability:".capability.ts"}[$]||".ts"}function t2($){return{operation:"operations",event:"events",presentation:"presentations",workflow:"workflows","data-view":"data-views",form:"forms",migration:"migrations",experiment:"experiments",capability:"capabilities"}[$]||"specs"}var a2={"remove-reference":"Remove broken reference from feature","implement-skeleton":"Create skeleton spec (in_creation)","implement-ai":"Create spec with AI assistance (experimental)"},N0={"implement-skeleton":"in_creation","implement-ai":"experimental"};async function FW($,W,j){let{fs:A,logger:Q}=j,{ref:Z,specType:X,featureKey:Y}=$;try{let B={key:Z.key,version:Z.version,specType:X,stability:N0["implement-ai"],featureKey:Y},q=B;if(W.aiConfig)try{q=await e2(B,W,Q)}catch(J){Q.warn("AI enrichment failed, falling back to skeleton",{error:J instanceof Error?J.message:String(J)})}else Q.info("No AI config provided, using skeleton with experimental stability");let H=jY(q);if(!H)return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:`Unsupported spec type: ${X}`};let V=TW($,W),G=[];if(!W.dryRun){let J=s2.dirname(V);await A.mkdir(J),await A.writeFile(V,H),G.push({path:V,action:"created"})}else G.push({path:V,action:"created"});return{success:!0,strategy:"implement-ai",issue:$,filesChanged:G}}catch(B){return{success:!1,strategy:"implement-ai",issue:$,filesChanged:[],error:B instanceof Error?B.message:String(B)}}}async function e2($,W,j){if(j.info("Generating AI content for spec",{key:$.key,type:$.specType}),W.aiConfig)try{let{AIGenerator:Q}=await Promise.resolve().then(() => (DW(),D4)),Z=$Y(W),X=new Q(Z),Y=$.specType==="operation"?"command":$.specType,B=`${P4($.specType)} for ${$.key}`;if($.specType==="operation"){let q=await X.generateOperationSpec(B,Y);return{...$,description:q.description,enrichment:{goal:q.goal,context:q.context,owners:q.owners,tags:q.tags}}}if($.specType==="event"){let q=await X.generateEventSpec(B);return{...$,description:q.description,enrichment:{goal:`Emit ${$.key} event`,context:q.description,owners:["@team"],tags:q.tags}}}}catch(Q){j.warn("AIGenerator call failed, falling back to heuristics",{error:Q instanceof Error?Q.message:String(Q)})}let A=WY($.key,$.specType);return{...$,description:A.description,enrichment:{goal:A.goal,context:A.context,owners:["@team"],tags:A.tags}}}function $Y($){let W=$.aiConfig;return{aiProvider:{claude:"anthropic",openai:"openai",ollama:"ollama",custom:"custom"}[W?.provider??"openai"]??"openai",aiModel:W?.model??"gpt-4-turbo",customApiKey:W?.apiKey??"",customEndpoint:W?.endpoint??""}}function WY($,W){let j=$.split("."),A=j[0]||"unknown",Q=j.slice(1).join(" ").replace(/_/g," "),Z=[A],X=Q.toLowerCase().split(" "),B=["auth","user","admin","api","data","search","create","update","delete"].filter((q)=>X.some((H)=>H.includes(q)));return{description:`${P4(W)} for ${A} ${Q}`,goal:`Enable ${Q} functionality in the ${A} domain`,context:`Part of the ${A} feature set. Generated by ContractSpec AI fix.`,tags:[...Z,...B]}}function jY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}function P4($){return $.charAt(0).toUpperCase()+$.slice(1)}import AY from"node:path";async function xW($,W,j){let{fs:A}=j,{ref:Q,specType:Z,featureKey:X}=$;try{let Y={key:Q.key,version:Q.version,specType:Z,stability:N0["implement-skeleton"],description:`Skeleton spec for ${Q.key}`,featureKey:X},B=QY(Y);if(!B)return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:`Unsupported spec type: ${Z}`};let q=TW($,W),H=[];if(!W.dryRun){let V=AY.dirname(q);await A.mkdir(V),await A.writeFile(q,B),H.push({path:q,action:"created"})}else H.push({path:q,action:"created"});return{success:!0,strategy:"implement-skeleton",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"implement-skeleton",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function QY($){switch($.specType){case"operation":return M0($);case"event":return I0($);case"presentation":return E0($);case"capability":return S0($);default:return}}async function yW($,W,j){let{fs:A}=j,{ref:Q,featureFile:Z,specType:X}=$;try{let Y=await A.readFile(Z),B=Y,q=ZY(Y,Q,X);if(q===Y)return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:`Could not find reference ${Q.key}.v${Q.version} in ${Z}`};let H=[];if(!W.dryRun)await A.writeFile(Z,q),H.push({path:Z,action:"modified",previousContent:B});else H.push({path:Z,action:"modified"});return{success:!0,strategy:"remove-reference",issue:$,filesChanged:H}}catch(Y){return{success:!1,strategy:"remove-reference",issue:$,filesChanged:[],error:Y instanceof Error?Y.message:String(Y)}}}function ZY($,W,j){if(!XY(j))return $;let Q=k4(W.key),Z=k4(W.version),X=[new RegExp(`\\{\\s*key:\\s*['"]${Q}['"],\\s*version:\\s*['"]${Z}['"]\\s*\\},?\\s*`,"g"),new RegExp(`\\{\\s*version:\\s*['"]${Z}['"],\\s*key:\\s*['"]${Q}['"]\\s*\\},?\\s*`,"g")],Y=$;for(let B of X)Y=Y.replace(B,"");return Y=YY(Y),Y}function XY($){return{operation:"operations",event:"events",presentation:"presentations",experiment:"experiments",capability:"capabilities",workflow:"workflows","data-view":"dataViews",form:"forms"}[$]}function k4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YY($){return $.replace(/,(\s*)\]/g,"$1]")}class h4{adapters;strategies;constructor($){this.adapters=$;this.strategies=new Map,this.registerStrategy({type:"remove-reference",fix:(W,j)=>yW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-skeleton",fix:(W,j)=>xW(W,j,{fs:this.adapters.fs})}),this.registerStrategy({type:"implement-ai",fix:(W,j)=>FW(W,j,this.adapters)})}registerStrategy($){this.strategies.set($.type,$)}getStrategiesForIssue($){let W=[];if($.type==="unresolved-ref")W.push("remove-reference"),W.push("implement-skeleton"),W.push("implement-ai");else if($.type==="broken-link")W.push("remove-reference"),W.push("implement-skeleton");return W}parseFixableIssue($){if(!$.ref||!$.featureKey||!$.specType)return;return{issue:$,ref:$.ref,specType:$.specType,featureFile:$.file,featureKey:$.featureKey}}async fixIssue($,W){let j=this.strategies.get(W.strategy);if(!j)return{success:!1,strategy:W.strategy,issue:$,filesChanged:[],error:`Strategy ${W.strategy} not found`};return this.adapters.logger.info(`Applying fix ${W.strategy} for ${$.ref.key}`,{dryRun:W.dryRun}),j.fix($,W)}async batchFix($){let W=[],j=0,A=0;for(let Q of $.issues)try{let Z=await this.fixIssue(Q,$.options);if(W.push(Z),Z.success)j++;else A++}catch(Z){A++,W.push({success:!1,strategy:$.options.strategy,issue:Q,filesChanged:[],error:Z instanceof Error?Z.message:String(Z)})}return{total:$.issues.length,succeeded:j,failed:A,results:W}}async scanAndGetFixables($={}){return(await zW(this.adapters,{pattern:$.pattern,cwd:$.cwd})).issues.map((j)=>this.getToFix(j)).filter((j)=>j!==null)}getToFix($){let W=this.getStrategiesForIssue($);if(W.length===0)return null;let j=this.parseFixableIssue($);if(!j)return null;return{...j,availableStrategies:W,strategies:[]}}resolveStrategy($,W){let{forceStrategy:j,preferAi:A,select:Q}=W;if(j)return Promise.resolve(j);if(A&&$.availableStrategies.includes("implement-ai"))return Promise.resolve("implement-ai");if($.availableStrategies.length===1)return Promise.resolve($.availableStrategies[0]);if($.availableStrategies.length>1){if(typeof Q==="function")return Q($,$.availableStrategies);return Promise.resolve($.availableStrategies[0])}return Promise.resolve(void 0)}async determineScanOptions($){try{if((await this.adapters.fs.stat($)).isDirectory)return{cwd:$};else return{pattern:$}}catch{return{pattern:$}}}parseIssuesFromCIResult($){if(!Array.isArray($))return[];return $.map((W)=>{return this.getToFix(W)}).filter((W)=>W!==null)}}import{z as o$}from"zod";var BY=o$.union([o$.array(o$.unknown()),o$.object({issues:o$.array(o$.unknown())}).transform(($)=>$.issues)]);import{exec as qY}from"node:child_process";import{promisify as HY}from"node:util";var VY=HY(qY),f4={biome:"bunx @biomejs/biome format --write",dprint:"bunx dprint fmt"};async function lL($,W,j={}){if($.length===0)return;let A=j.cwd??process.cwd(),Q=f4[j.type??"biome"]??f4.biome,Z=50;for(let X=0;X<$.length;X+=Z){let B=$.slice(X,X+Z).map((q)=>`"${q}"`).join(" ");try{await VY(`${Q} ${B}`,{cwd:A})}catch(q){}}}import _$ from"path";async function tL($,W){let j=_$.join(W,"contracts"),A=_$.join(W,"generated"),Q=_$.join(A,"docs"),Z=await $.fs.exists(j),X=await $.fs.exists(A);if(!Z)return{hasContracts:!1,hasGenerated:X,missingDocs:[],missingIndex:!1,missingRegistry:!1,totalSpecs:0};let Y=await $$($,{pattern:"contracts/**/*.ts"}),B=[];if(X)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts"),w=_$.join(Q,`${b}.md`);if(!await $.fs.exists(w))B.push(b)}else if(Y.length>0)for(let J of Y){let b=J.key||_$.basename(J.filePath,".ts");B.push(b)}let q=_$.join(j,"index.ts"),H=_$.join(j,"registry.ts"),V=Y.length>0&&!await $.fs.exists(q),G=Y.length>0&&!await $.fs.exists(H);return{hasContracts:!0,hasGenerated:X,missingDocs:B,missingIndex:V,missingRegistry:G,totalSpecs:Y.length}}var c4={};h(c4,{runHook:()=>u4,getAvailableHooks:()=>d4});import{exec as GY}from"node:child_process";import{promisify as JY}from"node:util";var bY=JY(GY);async function u4($,W){let{fs:j,logger:A}=$,{hookName:Q,dryRun:Z=!1}=W,X=D(W.workspaceRoot);A.info(`Running hook: ${Q}`,{workspaceRoot:X,dryRun:Z});let Y=await n4(j,X);if(!Y)return{hookName:Q,success:!1,commandResults:[],totalCommands:0,successfulCommands:0,summary:"No hooks configuration found in .contractsrc.json"};let B=Y[Q];if(!B||B.length===0)return{hookName:Q,success:!0,commandResults:[],totalCommands:0,successfulCommands:0,summary:`No commands configured for hook: ${Q}`};A.info(`Found ${B.length} command(s) for ${Q}`);let q=[],H=!0;for(let G of B){if(Z){A.info(`[DRY RUN] Would execute: ${G}`),q.push({command:G,success:!0,exitCode:0,stdout:"",stderr:""});continue}A.info(`Executing: ${G}`);try{let{stdout:J,stderr:b}=await bY(G,{cwd:X,timeout:300000});q.push({command:G,success:!0,exitCode:0,stdout:J,stderr:b}),A.info(`✓ ${G}`)}catch(J){H=!1;let b=J;q.push({command:G,success:!1,exitCode:b.code??1,stdout:b.stdout??"",stderr:b.stderr??b.message??String(J)}),A.error(`✗ ${G}`,{exitCode:b.code,stderr:b.stderr});break}}let V=q.filter((G)=>G.success).length;return{hookName:Q,success:H,commandResults:q,totalCommands:B.length,successfulCommands:V,summary:H?`✓ All ${B.length} command(s) passed`:`✗ ${V}/${B.length} command(s) passed`}}async function d4($,W){let j=await n4($.fs,W);return j?Object.keys(j):[]}async function n4($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return null;try{let A=await $.readFile(j);return JSON.parse(A).hooks??null}catch{return null}}import{detectFramework as wY,extractFromProject as KY}from"@contractspec/lib.source-extractors";import{generateOperations as _Y,generateRegistry as zY,generateSchemas as UY}from"@contractspec/lib.source-extractors/codegen";import{registerAllExtractors as LY}from"@contractspec/lib.source-extractors/extractors";import{dirname as OY,join as Rj}from"path";async function SY($,W,j,A){let{fs:Q,logger:Z}=j,X=A??process.cwd();LY(),Z.info(`Scanning source code in ${X}...`);let Y={readFile:(O)=>Q.readFile(O),glob:(O,K)=>Q.glob({pattern:O,cwd:K?.cwd}),exists:(O)=>Q.exists(O)},B=await wY(X,{readFile:(O)=>Q.readFile(O),glob:(O)=>Q.glob({pattern:O})});if(B.frameworks.length===0)return Z.warn("No supported frameworks detected"),{success:!1,report:IY(),errors:["No supported frameworks detected in project"]};Z.info(`Detected frameworks: ${B.frameworks.map((O)=>O.name).join(", ")}`);let{extractorRegistry:q}=await import("@contractspec/lib.source-extractors");for(let O of q.getAll())if("setFs"in O&&typeof O.setFs==="function")O.setFs(Y);let H={scope:W.scope,framework:W.framework},V=await KY(B,H);if(!V.success||!V.ir)return{success:!1,report:MY(V.errors??[]),errors:V.errors?.map((O)=>O.message)};let G=V.ir;if(Z.info(`Extracted ${G.endpoints.length} endpoints, ${G.schemas.length} schemas`),W.analyzeOnly)return{success:!0,ir:G,report:EY(G)};let J=W.outputDir??Rj($.outputDir,"generated"),b={outputDir:J,defaultAuth:"user"},w=_Y(G,b),L=UY(G,b),z=zY(w),S=[...w,...L,z];if(!W.dryRun)for(let O of S){let K=Rj(J,O.path),_=OY(K);if(!await Q.exists(_))await Q.mkdir(_);await Q.writeFile(K,O.content),Z.info(`Created: ${K}`)}else for(let O of S)Z.info(`[DRY RUN] Would create: ${Rj(J,O.path)}`);let U={files:S,operationsGenerated:w.length,schemasGenerated:L.length,warnings:[]};return{success:!0,ir:G,generation:U,report:NY(G,U,W)}}function IY(){return`# Import Report
|
|
1656
1895
|
|
|
1657
1896
|
## ❌ No Supported Frameworks Detected
|
|
1658
1897
|
|
|
@@ -1669,13 +1908,13 @@ No supported frameworks were detected in the project.
|
|
|
1669
1908
|
- Next.js API Routes
|
|
1670
1909
|
|
|
1671
1910
|
Please ensure your project uses one of these frameworks and has the appropriate dependencies installed.
|
|
1672
|
-
`}function
|
|
1911
|
+
`}function MY($){return`# Import Report
|
|
1673
1912
|
|
|
1674
1913
|
## ❌ Extraction Failed
|
|
1675
1914
|
|
|
1676
1915
|
${$.map((W)=>`- ${W.message}`).join(`
|
|
1677
1916
|
`)}
|
|
1678
|
-
`}function
|
|
1917
|
+
`}function EY($){return`# Import Analysis Report
|
|
1679
1918
|
|
|
1680
1919
|
## Summary
|
|
1681
1920
|
|
|
@@ -1707,7 +1946,7 @@ ${$.endpoints.map((W)=>`- \`${W.method} ${W.path}\` - ${W.confidence.level}`).jo
|
|
|
1707
1946
|
|
|
1708
1947
|
${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
1709
1948
|
`):"None"}
|
|
1710
|
-
`}function
|
|
1949
|
+
`}function NY($,W,j){return`# Import Report${j.dryRun?" (Dry Run)":""}
|
|
1711
1950
|
|
|
1712
1951
|
## ✅ Import Successful
|
|
1713
1952
|
|
|
@@ -1737,31 +1976,37 @@ ${$.ambiguities.length>0?$.ambiguities.map((W)=>`- ${W.description}`).join(`
|
|
|
1737
1976
|
2. Fill in TODO placeholders with business context
|
|
1738
1977
|
3. Run \`contractspec validate\` to verify contracts
|
|
1739
1978
|
4. Move stable contracts from \`generated/\` to \`curated/\`
|
|
1740
|
-
`}function
|
|
1741
|
-
`)}function
|
|
1742
|
-
`)}async function
|
|
1743
|
-
`)}function
|
|
1744
|
-
`)}function
|
|
1745
|
-
`)}function
|
|
1746
|
-
`);
|
|
1747
|
-
`)}function
|
|
1748
|
-
`)}async function
|
|
1979
|
+
`}function RY($,W,j={}){let A=[];if(A.push("# Import Report"),A.push(""),A.push(`**Generated**: ${new Date().toISOString()}`),A.push(""),A.push("## Summary"),A.push(""),A.push("| Metric | Count |"),A.push("|--------|-------|"),A.push(`| Files Scanned | ${$.stats.filesScanned} |`),A.push(`| Endpoints Found | ${$.stats.endpointsFound} |`),A.push(`| Schemas Found | ${$.stats.schemasFound} |`),A.push(`| Errors Found | ${$.stats.errorsFound} |`),A.push(`| Events Found | ${$.stats.eventsFound} |`),A.push(""),j.includeStats!==!1)A.push("### Confidence"),A.push(""),A.push("| Level | Count |"),A.push("|-------|-------|"),A.push(`| High | ${$.stats.highConfidence} |`),A.push(`| Medium | ${$.stats.mediumConfidence} |`),A.push(`| Low/Ambiguous | ${$.stats.lowConfidence} |`),A.push("");A.push("### Frameworks Detected"),A.push("");for(let Q of $.project.frameworks)A.push(`- **${Q.name}** (${Q.confidence})`);if(A.push(""),j.includeEndpoints!==!1&&$.endpoints.length>0){A.push("## Endpoints"),A.push(""),A.push("| Method | Path | Kind | Confidence |"),A.push("|--------|------|------|------------|");for(let Q of $.endpoints)A.push(`| ${Q.method} | \`${Q.path}\` | ${Q.kind} | ${Q.confidence.level} |`);A.push("")}if(j.includeSchemas!==!1&&$.schemas.length>0){A.push("## Schemas"),A.push(""),A.push("| Name | Type | Confidence |"),A.push("|------|------|------------|");for(let Q of $.schemas)A.push(`| ${Q.name} | ${Q.schemaType} | ${Q.confidence.level} |`);A.push("")}if(W&&j.includeIssues!==!1){A.push("## Verification"),A.push(""),A.push("| Status | Count |"),A.push("|--------|-------|"),A.push(`| Valid | ${W.summary.validEndpoints} |`),A.push(`| Warnings | ${W.summary.warningEndpoints} |`),A.push(`| Errors | ${W.summary.errorEndpoints} |`),A.push("");let Q=W.endpointResults.filter((Z)=>Z.issues.length>0);if(Q.length>0){A.push("### Issues"),A.push("");for(let Z of Q){A.push(`#### ${Z.endpoint.method} ${Z.endpoint.path}`);for(let X of Z.issues){let Y=X.severity==="error"?"❌":X.severity==="warning"?"⚠️":"ℹ️";if(A.push(`- ${Y} **${X.code}**: ${X.message}`),X.suggestion)A.push(` - *Suggestion*: ${X.suggestion}`)}A.push("")}}}if(j.includeAmbiguities!==!1&&$.ambiguities.length>0){A.push("## Ambiguities (Require Review)"),A.push("");for(let Q of $.ambiguities)if(A.push(`- **${Q.type}** (${Q.itemId}): ${Q.description}`),Q.suggestion)A.push(` - *Suggestion*: ${Q.suggestion}`);A.push("")}return A.push("## Next Steps"),A.push(""),A.push("1. Review generated contracts in the output directory"),A.push("2. Fill in TODO placeholders with business context"),A.push("3. Run `contractspec validate` to verify contracts"),A.push("4. Move stable contracts from `generated/` to `curated/`"),A.push(""),A.join(`
|
|
1980
|
+
`)}function CY($,W){let j=[];j.push(""),j.push("\uD83D\uDCCA Summary"),j.push(` Files scanned: ${$.stats.filesScanned}`),j.push(` Endpoints: ${$.stats.endpointsFound}`),j.push(` Schemas: ${$.stats.schemasFound}`),j.push(""),j.push("\uD83D\uDCC8 Confidence"),j.push(` High: ${$.stats.highConfidence}`),j.push(` Medium: ${$.stats.mediumConfidence}`),j.push(` Low: ${$.stats.lowConfidence}`),j.push(""),j.push("\uD83D\uDD27 Frameworks");for(let A of $.project.frameworks)j.push(` • ${A.name}`);if(j.push(""),W)j.push("✅ Verification"),j.push(` Valid: ${W.summary.validEndpoints}`),j.push(` Warnings: ${W.summary.warningEndpoints}`),j.push(` Errors: ${W.summary.errorEndpoints}`),j.push("");return j.join(`
|
|
1981
|
+
`)}async function DY($,W,j){let{logger:A}=j,Q=[],Z=[...$.ambiguities];A.info(`Verifying ${$.endpoints.length} endpoints...`);for(let Y of $.endpoints){let B=[];if(Y.confidence.level==="low"||Y.confidence.level==="ambiguous")B.push({code:"LOW_CONFIDENCE",message:`Endpoint has ${Y.confidence.level} confidence`,severity:"warning",suggestion:"Review source code and add explicit schema annotations"});if(!Y.input&&(Y.method==="POST"||Y.method==="PUT"||Y.method==="PATCH"))B.push({code:"MISSING_INPUT_SCHEMA",message:"Command endpoint missing input schema",severity:"warning",suggestion:"Add Zod schema or class-validator DTO"});if(!Y.output)B.push({code:"MISSING_OUTPUT_SCHEMA",message:"Endpoint missing output schema",severity:"info",suggestion:"Infer from return type or add explicit schema"});if(W.checkDuplicates){if($.endpoints.filter((V)=>V.id!==Y.id&&V.path===Y.path&&V.method===Y.method).length>0)B.push({code:"DUPLICATE_ENDPOINT",message:`Duplicate ${Y.method} ${Y.path} found`,severity:"error"})}if(W.checkConflicts){let H=TY(Y,$.endpoints);for(let V of H)B.push({code:"PATH_CONFLICT",message:`Path may conflict with ${V.method} ${V.path}`,severity:"warning"})}let q=B.some((H)=>H.severity==="error")?"error":B.some((H)=>H.severity==="warning")?"warning":"valid";Q.push({endpoint:Y,status:q,issues:B})}if(W.validateSchemas){for(let Y of $.schemas)if(!Y.fields||Y.fields.length===0)Z.push({type:"schema",itemId:Y.id,description:`Schema ${Y.name} has no extracted fields`,suggestion:"Review schema definition and add explicit field types",source:Y.source})}let X={totalEndpoints:Q.length,validEndpoints:Q.filter((Y)=>Y.status==="valid").length,warningEndpoints:Q.filter((Y)=>Y.status==="warning").length,errorEndpoints:Q.filter((Y)=>Y.status==="error").length,totalIssues:Q.reduce((Y,B)=>Y+B.issues.length,0)};return A.info(`Verification complete: ${X.validEndpoints} valid, ${X.warningEndpoints} warnings, ${X.errorEndpoints} errors`),{valid:X.errorEndpoints===0,endpointResults:Q,ambiguities:Z,summary:X}}function TY($,W){let j=[],A=$.path.split("/").filter(Boolean);for(let Q of W){if(Q.id===$.id)continue;if(Q.method!==$.method)continue;let Z=Q.path.split("/").filter(Boolean);if(Z.length!==A.length)continue;let X=!0;for(let Y=0;Y<A.length;Y++){let B=A[Y]??"",q=Z[Y]??"",H=B.startsWith(":")||B.startsWith("{"),V=q.startsWith(":")||q.startsWith("{");if(!H&&!V&&B!==q){X=!1;break}}if(X&&$.path!==Q.path)j.push(Q)}return j}function UO($,W="feature-map",j={}){switch(W){case"feature-map":return Tj($,j);case"orphans":return FY($,j);case"dependencies":return xY($,j);case"full":return yY($,j);default:return Tj($,j)}}function Tj($,W){let{direction:j="LR",showVersions:A=!0,maxNodes:Q=50}=W,Z=[`flowchart ${j}`],X=$.features;if(W.featureKeys&&W.featureKeys.length>0)X=X.filter((G)=>W.featureKeys?.includes(G.key));let Y=0,B=!1;if(X.length>0){Z.push(" subgraph features [Features]");for(let G of X){if(Y>=Q)break;let J=y(`F_${G.key}`),b=G.title??G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}let q=Cj(X,"operations",$.inventory);if(q.length>0&&Y<Q){Z.push(" subgraph ops [Operations]");for(let G of q){if(Y>=Q)break;let J=y(`O_${G.key}_v${G.version}`),b=A?`${G.key}.v${G.version}`:G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}let H=Cj(X,"events",$.inventory);if(H.length>0&&Y<Q){Z.push(" subgraph events [Events]");for(let G of H){if(Y>=Q)break;let J=y(`E_${G.key}_v${G.version}`),b=A?`${G.key}.v${G.version}`:G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}let V=Cj(X,"presentations",$.inventory);if(V.length>0&&Y<Q){Z.push(" subgraph presentations [Presentations]");for(let G of V){if(Y>=Q)break;let J=y(`P_${G.key}_v${G.version}`),b=A?`${G.key}.v${G.version}`:G.key;Z.push(` ${J}["${W$(b)}"]`),Y++}Z.push(" end")}for(let G of X){let J=y(`F_${G.key}`);for(let b of G.operations){let w=y(`O_${b.key}_v${b.version}`);Z.push(` ${J} --> ${w}`)}for(let b of G.events){let w=y(`E_${b.key}_v${b.version}`);Z.push(` ${J} -.-> ${w}`)}for(let b of G.presentations){let w=y(`P_${b.key}_v${b.version}`);Z.push(` ${J} --> ${w}`)}}if(B)Z.push(` note["... and more (truncated at ${Q} nodes)"]`);return Z.join(`
|
|
1982
|
+
`)}function FY($,W){let{direction:j="TB",showVersions:A=!0,maxNodes:Q=50}=W,Z=[`flowchart ${j}`],X=new Set,Y=new Set,B=new Set;for(let V of $.features){for(let G of V.operations)X.add(`${G.key}.v${G.version}`);for(let G of V.events)Y.add(`${G.key}.v${G.version}`);for(let G of V.presentations)B.add(`${G.key}.v${G.version}`)}let q=0;if($.features.length>0){Z.push(" subgraph features [Features]");for(let V of $.features){if(q>=Q)break;let G=y(`F_${V.key}`);Z.push(` ${G}["${W$(V.title??V.key)}"]`),q++}Z.push(" end")}if($.orphanedSpecs.length>0){Z.push(" subgraph orphaned [Orphaned Specs]");for(let V of $.orphanedSpecs){if(q>=Q)break;let G=y(`orphan_${V.type}_${V.key}_v${V.version}`),J=A?`${V.key}.v${V.version}`:V.key;Z.push(` ${G}["${W$(J)}"]`),q++}Z.push(" end")}let H=[];for(let V of X){let[G,J]=Dj(V);if(G&&J)H.push({type:"operation",key:G,version:J})}for(let V of Y){let[G,J]=Dj(V);if(G&&J)H.push({type:"event",key:G,version:J})}for(let V of B){let[G,J]=Dj(V);if(G&&J)H.push({type:"presentation",key:G,version:J})}if(H.length>0&&q<Q){Z.push(" subgraph linked [Linked Specs]");for(let V of H){if(q>=Q)break;let G=y(`${V.type}_${V.key}_v${V.version}`),J=A?`${V.key}.v${V.version}`:V.key;Z.push(` ${G}["${W$(J)}"]`),q++}Z.push(" end")}for(let V of $.features){let G=y(`F_${V.key}`);for(let J of V.operations){let b=y(`operation_${J.key}_v${J.version}`);Z.push(` ${G} --> ${b}`)}for(let J of V.events){let b=y(`event_${J.key}_v${J.version}`);Z.push(` ${G} -.-> ${b}`)}for(let J of V.presentations){let b=y(`presentation_${J.key}_v${J.version}`);Z.push(` ${G} --> ${b}`)}}return Z.join(`
|
|
1983
|
+
`)}function xY($,W){let{direction:j="TB",showVersions:A=!0,maxNodes:Q=50}=W,Z=[`flowchart ${j}`],X=0;for(let Y of $.features){if(X>=Q)break;let B=y(`F_${Y.key}`);Z.push(` ${B}["${W$(Y.title??Y.key)}"]`),X++;for(let q of Y.operations){if(X>=Q)break;let H=y(`O_${q.key}_v${q.version}`),V=A?`${q.key}.v${q.version}`:q.key;Z.push(` ${H}["${W$(V)}"]`),Z.push(` ${B} --> ${H}`),X++}for(let q of Y.events){if(X>=Q)break;let H=y(`E_${q.key}_v${q.version}`),V=A?`${q.key}.v${q.version}`:q.key;Z.push(` ${H}["${W$(V)}"]`),Z.push(` ${B} -.-> ${H}`),X++}for(let q of Y.presentations){if(X>=Q)break;let H=y(`P_${q.key}_v${q.version}`),V=A?`${q.key}.v${q.version}`:q.key;Z.push(` ${H}["${W$(V)}"]`),Z.push(` ${B} --> ${H}`),X++}for(let q of Y.opToPresentationLinks){let H=y(`O_${q.op.key}_v${q.op.version}`),V=y(`P_${q.pres.key}_v${q.pres.version}`);Z.push(` ${H} --> ${V}`)}}return Z.join(`
|
|
1984
|
+
`)}function yY($,W){let j=Tj($,W);if($.orphanedSpecs.length===0)return j;let A=j.split(`
|
|
1985
|
+
`);A.push(" subgraph orphaned [Orphaned Specs]");for(let Q of $.orphanedSpecs.slice(0,20)){let Z=y(`orphan_${Q.type}_${Q.key}_v${Q.version}`),X=`${Q.key}.v${Q.version}`;A.push(` ${Z}["${W$(X)}"]:::orphan`)}return A.push(" end"),A.push(" classDef orphan stroke-dasharray: 5 5"),A.join(`
|
|
1986
|
+
`)}function Cj($,W,j){let A=new Set,Q=[];for(let Z of $)for(let X of Z[W]){let Y=`${X.key}.v${X.version}`;if(!A.has(Y))A.add(Y),Q.push(X)}return Q}function Dj($){let W=$.match(/^(.+)\.v(\d+)$/);if(!W)return[void 0,void 0];return[W[1],W[2]]}function y($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function W$($){return $.replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")")}import{loadSpecFromSource as vY,specToMarkdown as z$}from"@contractspec/module.workspace";function OO($,W,j){let A=[];if(j.includes("structure")){if(!/export\s+(async\s+)?function|export\s+class|export\s+const/.test(W))A.push({severity:"warning",message:"No exports found in implementation",category:"structure"});if($.meta.key&&!W.includes($.meta.key))A.push({severity:"info",message:`Spec name "${$.meta.key}" not found in implementation`,category:"structure"})}if(j.includes("behavior")){if(!/try\s*{|catch\s*\(|throw\s+new/.test(W))A.push({severity:"warning",message:"No error handling patterns found",category:"behavior"});if($.specType==="operation"){if(!/async\s+|await\s+|Promise/.test(W))A.push({severity:"info",message:"No async patterns found (operations typically use async)",category:"behavior"})}if($.emittedEvents&&$.emittedEvents.length>0){if(!/emit|publish|dispatch|fire/i.test(W))A.push({severity:"warning",message:`Spec emits ${$.emittedEvents.length} event(s) but no event emission found`,category:"behavior"})}}return A}function SO($,W){let j=[];j.push(`# Verification Report: ${$.meta.key}`),j.push("");let A=W.filter((X)=>X.severity==="error"),Q=W.filter((X)=>X.severity==="warning"),Z=W.filter((X)=>X.severity==="info");if(j.push("## Summary"),j.push(""),j.push(`- Errors: ${A.length}`),j.push(`- Warnings: ${Q.length}`),j.push(`- Info: ${Z.length}`),j.push(""),A.length>0){j.push("## Errors"),j.push("");for(let X of A)j.push(`- ❌ **${X.category}**: ${X.message}`);j.push("")}if(Q.length>0){j.push("## Warnings"),j.push("");for(let X of Q)j.push(`- ⚠️ **${X.category}**: ${X.message}`);j.push("")}if(Z.length>0){j.push("## Info"),j.push("");for(let X of Z)j.push(`- ℹ️ **${X.category}**: ${X.message}`);j.push("")}return j.join(`
|
|
1987
|
+
`)}async function NO($,W){let j=[];j.push(z$($,"context"));let A=await $$(W),Q=async(Z)=>{let X=A.find((B)=>B.key===Z.name&&B.version===Z.version);if(!X)return null;return(await vY(X.filePath)).find((B)=>B.meta.key===Z.name)??null};if($.operations?.length){j.push(`
|
|
1749
1988
|
## Operations (${$.operations.length})
|
|
1750
|
-
`);for(let
|
|
1989
|
+
`);for(let Z of $.operations){let X=await Q(Z);if(X)j.push(z$(X,"full"));else j.push(`### ${Z.name} (v${Z.version})
|
|
1751
1990
|
|
|
1752
1991
|
*Spec not found*`);j.push("---")}}if($.events?.length){j.push(`
|
|
1753
1992
|
## Events (${$.events.length})
|
|
1754
|
-
`);for(let
|
|
1993
|
+
`);for(let Z of $.events){let X=await Q(Z);if(X)j.push(z$(X,"full"));else j.push(`### ${Z.name} (v${Z.version})
|
|
1755
1994
|
|
|
1756
1995
|
*Spec not found*`);j.push("---")}}if($.presentations?.length){j.push(`
|
|
1757
1996
|
## Presentations (${$.presentations.length})
|
|
1758
|
-
`);for(let
|
|
1997
|
+
`);for(let Z of $.presentations){let X=await Q(Z);if(X)j.push(z$(X,"full"));else j.push(`### ${Z.name} (v${Z.version})
|
|
1759
1998
|
|
|
1760
1999
|
*Spec not found*`);j.push("---")}}return j.join(`
|
|
1761
|
-
`)}function
|
|
1762
|
-
`)}function
|
|
1763
|
-
`)}function
|
|
1764
|
-
`)}import{RegeneratorService as XY}from"@contractspec/lib.contracts-spec/regenerator";function oL($){return new XY({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class qW{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let W=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,j;try{j=await fetch(W,{method:"GET",headers:{Accept:"application/json"}})}catch(Q){throw Error(`Registry request failed: ${W} (${Q instanceof Error?Q.message:String(Q)})`)}if(!j.ok){let Q=await j.text().catch(()=>"");throw Error(`Registry request failed: ${j.status} ${j.statusText} ${Q}`)}return await j.json()}}function Zj($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function iL($,W,j){let{logger:Q}=j,Z=Zj(W.registryUrl);Q.info(`Adding spec to registry: ${$}`,{registryUrl:Z}),await new qW({registryUrl:Z}).getJson(`/specs/add?path=${encodeURIComponent($)}`),Q.info("Spec added to registry successfully")}async function aL($,W){let{logger:j}=W,Q=Zj($.registryUrl);j.info("Listing specs from registry",{registryUrl:Q});let Z=new qW({registryUrl:Q}),B=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",X=await Z.getJson(`/specs${B}`);return j.info(`Found ${X.length} specs`),X}async function tL($,W,j){let{logger:Q}=j,Z=Zj(W.registryUrl);Q.info(`Searching registry: ${$}`,{registryUrl:Z});let X=await new qW({registryUrl:Z}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return Q.info(`Found ${X.length} results`),X}class YY{fs;logger;constructor($,W){this.fs=$;this.logger=W}async sync($){let{config:W,cwd:j}=$,Q=$.targets??W.targets??[];if(!W.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${Q.join(", ")}...`);try{let Z=this.fs.join(j,W.rulesDir??".rules");if(!await this.fs.exists(Z))return{success:!1,files:[],errors:[`Rules directory not found: ${Z}`]};let X=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${X}`);let Y=[];for(let q of Q){let A=this.getTargetFileName(q);if(A){let H=this.fs.join(j,A);Y.push(H)}}return{success:!0,files:Y,logs:[`Successfully synchronized rules to ${Y.length} targets.`]}}catch(Z){let B=Z instanceof Error?Z.message:String(Z);return this.logger.error(`Rule synchronization failed: ${B}`),{success:!1,files:[],errors:[B]}}}async generateConfig($){let{config:W}=$,j={rules:(W.rules??[]).map((Q)=>this.fs.join(W.rulesDir??".rules",Q)),targets:$.targets||W.targets};return JSON.stringify(j,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}}}async function Bj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,"AGENTS.md");try{let B=await $.exists(Z),X=L5(W);if(B)if(W.interactive){if(!await j.confirm(`${Z} exists. Overwrite with the latest ContractSpec guide?`))return{target:"agents-md",filePath:Z,action:"skipped",message:"User kept existing AGENTS guide"}}else return{target:"agents-md",filePath:Z,action:"skipped",message:"File already exists"};return await $.writeFile(Z,X),{target:"agents-md",filePath:Z,action:B?"merged":"created",message:B?"Updated AI agent guide":"Created AI agent guide"}}catch(B){return{target:"agents-md",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}import{generateArtifactsForAudience as qY,generateBiomePreset as AY}from"@contractspec/biome-config";async function Xj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,"biome.jsonc"),B=$.join(Q,".contractspec","biome"),X=$.join(B,"plugins"),Y=$.join(B,"ai"),q=qY("consumer");try{let A=await $.exists(Z);if(A&&W.interactive){if(!await j.confirm(`${Z} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Z,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Z,AY("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(q.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),q.aiRules),{target:"biome-config",filePath:Z,action:A?"merged":"created",message:A?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(A){return{target:"biome-config",filePath:Z,action:"error",message:A instanceof Error?A.message:"Unknown error"}}}async function Yj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,".contractsrc.json");try{let B=await $.exists(Z),X=x$(W);if(B){let Y=await $.readFile(Z),q=j$(Y);if(!q)return{target:"cli-config",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Z,action:"skipped",message:"User skipped merge"}}let A=r(q,X);return await $.writeFile(Z,D(A)),{target:"cli-config",filePath:Z,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Z,D(X)),{target:"cli-config",filePath:Z,action:"created",message:"Created CLI configuration"}}catch(B){return{target:"cli-config",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function qj($,W,j){let Q=$.join(W.workspaceRoot,".cursor","rules"),Z=$.join(Q,"contractspec.mdc");try{let B=$.join(W.workspaceRoot,".cursor");if(!await $.exists(B))await $.mkdir(B);if(!await $.exists(Q))await $.mkdir(Q);let X=await $.exists(Z),Y=_5(W);if(X)if(W.interactive){if(!await j.confirm(`${Z} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Z,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Z,action:"skipped",message:"File already exists"};return await $.writeFile(Z,Y),{target:"cursor-rules",filePath:Z,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(B){return{target:"cursor-rules",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function Aj($,W,j){let Q=P0();try{let Z=await $.exists(Q),B=U5();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${Q}?`))return{target:"mcp-claude",filePath:Q,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Z){let q=await $.readFile(Q),A=j$(q);if(!A)return{target:"mcp-claude",filePath:Q,action:"error",message:"Existing file is not valid JSON"};let H=r(A,B);return await $.writeFile(Q,D(H)),{target:"mcp-claude",filePath:Q,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=Q.substring(0,Q.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(Q,D(B)),{target:"mcp-claude",filePath:Q,action:"created",message:"Created Claude Desktop configuration"}}catch(Z){return{target:"mcp-claude",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function Hj($,W,j){let Q=$.join(W.workspaceRoot,".cursor"),Z=$.join(Q,"mcp.json");try{if(!await $.exists(Q))await $.mkdir(Q);let X=await $.exists(Z),Y=o$();if(X){let q=await $.readFile(Z),A=j$(q);if(!A)return{target:"mcp-cursor",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Z,action:"skipped",message:"User skipped merge"}}let H=r(A,Y);return await $.writeFile(Z,D(H)),{target:"mcp-cursor",filePath:Z,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Z,D(Y)),{target:"mcp-cursor",filePath:Z,action:"created",message:"Created Cursor MCP configuration"}}catch(B){return{target:"mcp-cursor",filePath:Z,action:"error",message:B instanceof Error?B.message:"Unknown error"}}}async function Vj($,W,j){let Q=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Z=$.join(Q,".vscode"),B=$.join(Z,"settings.json");try{if(!await $.exists(Z))await $.mkdir(Z);let Y=await $.exists(B),q=K5();if(Y){let A=await $.readFile(B),H=j$(A);if(!H)return{target:"vscode-settings",filePath:B,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${B} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:B,action:"skipped",message:"User skipped merge"}}let V=r(H,q);return await $.writeFile(B,D(V)),{target:"vscode-settings",filePath:B,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(B,D(q)),{target:"vscode-settings",filePath:B,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:B,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var Gj=["cli-config","biome-config","vscode-settings","mcp-cursor","mcp-claude","cursor-rules","agents-md"],jQ={"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)"};var HY={confirm:async()=>!0,multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function FI($,W,j=HY){let Q=[],Z=W.targets.length>0?W.targets:Gj,B=W.workspaceRoot,X=R(B),Y=W.packageRoot??k(B),q=W.isMonorepo??c$(X),A=W.packageName??(q?L$(Y):void 0),H=W.scope??"workspace",V=Y!==X;if(q&&W.interactive&&V)H=(await j.multiSelect("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${A??Y})`,selected:!0},{value:"workspace",label:`Workspace level (${X})`}]))[0]??"package";let G=Z;if(W.interactive)G=await j.multiSelect("Select components to configure:",Gj.map((b)=>({value:b,label:jQ[b],selected:Z.includes(b)})));let z=W.projectName;if(W.interactive&&!z){let b=H==="package"&&A?A:B.split("/").pop()??"my-project";z=await j.input("Project name:",b)}let J={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:q,scope:H,packageName:A,projectName:z,targets:G};for(let b of G){let L=await VY($,b,J,j);Q.push(L)}let K=Q.filter((b)=>b.action!=="error").length,_=Q.filter((b)=>b.action==="error").length,w=q?` (${H} level)`:"";return{success:_===0,files:Q,summary:`Setup complete${w}: ${K} configured, ${_} failed.`}}async function VY($,W,j,Q){switch(W){case"agents-md":return Bj($,j,Q);case"cli-config":return Yj($,j,Q);case"biome-config":return Xj($,j,Q);case"vscode-settings":return Vj($,j,Q);case"mcp-cursor":return Hj($,j,Q);case"mcp-claude":return Aj($,j,Q);case"cursor-rules":return qj($,j,Q);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}import{validateBlueprint as GY}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as zY}from"path";import{pathToFileURL as JY}from"url";async function fI($,W){let{fs:j}=W,Q=zY(process.cwd(),$);if(!await j.exists(Q))return{valid:!1,errors:[`Blueprint file not found: ${Q}`]};try{let Z=await KY(Q),B=UY(Z),X=GY(B);return{spec:B,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Z){return{valid:!1,errors:[Z instanceof Error?Z.message:String(Z)]}}}async function KY($){try{return await import(JY($).href)}catch(W){throw Error(`Failed to load module at ${$}: ${W}`)}}function UY($){let W=Object.values($).filter(_Y);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function _Y($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as LY,dirname as zj,join as V0}from"path";async function cI($,W,j,Q,Z){let{fs:B}=Z,X=Q.implementationPath;if(!X){let H=zj($),V=LY($,".ts"),G=[V0(H,V.replace(".contracts",".handler")+".ts"),V0(H,V.replace(".presentation","")+".tsx"),V0(H,V.replace(".form",".form")+".tsx"),V0(zj(H),"handlers",V.replace(".contracts",".handler")+".ts"),V0(zj(H),"components",V.replace(".presentation","")+".tsx")];for(let z of G)if(await B.exists(z)){X=z;break}}if(!X||!await B.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await B.readFile(X),A=await new w0(j).validate(W,Y);return{success:A.success,errors:A.errors||[],warnings:A.warnings||[],suggestions:A.suggestions||[],report:A.code}}import{validateSpecStructure as IY}from"@contractspec/module.workspace";async function R$($,W,j={}){let{fs:Q}=W;if(!await Q.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let B=await Q.readFile($),X=[],Y=[],q;if(!j.skipStructure){let A=await h(W,{pattern:$});for(let H of A)q=IY(H),X.push(...q.errors),Y.push(...q.warnings)}return{valid:X.length===0,structureResult:q,errors:X,warnings:Y,code:B}}async function pI($,W,j={}){let Q=new Map;for(let Z of $){let B=await R$(Z,W,j);Q.set(Z,B)}return Q}import{validateConfig as OY}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as Kj}from"fs/promises";import{resolve as AW}from"path";import{pathToFileURL as bY}from"url";async function $O($,W,j,Q){let{fs:Z}=Q,B=AW(process.cwd(),W);if(!await Z.exists(B))return{valid:!1,errors:[`Tenant config file not found: ${B}`]};try{let X=await wY(B),Y=await CY(j.connections,Z),q=await SY(j.translationCatalog,Z),A=await EY(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(q)H.translationCatalogs={blueprint:[q],platform:[]};if(A)H.integrationSpecs=A;let V=OY($,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 wY($){if($.endsWith(".json")){let Q=await Kj($,"utf-8"),Z=JSON.parse(Q);if(!QQ(Z))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Z}let W=await HW($),j=Object.values(W).filter(QQ);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function QQ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}async function HW($){try{return await import(bY($).href)}catch(W){throw Error(`Failed to load module at ${$}: ${W}`)}}function YQ($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function CY($,W){let j=YQ($);if(!j.length)return[];let Q=[];for(let Z of j){let B=AW(process.cwd(),Z);if(!await W.exists(B)){console.warn(`Warning: Connection file not found: ${B}`);continue}if(B.endsWith(".json")){let Y=await Kj(B,"utf-8"),q=JSON.parse(Y);Q.push(...Jj(q));continue}let X=await HW(B);Q.push(...Jj(X))}return Q}function Jj($){if(Array.isArray($)){let W=$.filter(ZQ);if(W.length)return W}if(ZQ($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((Q)=>Jj(Q));if(j.length)return j}return[]}function ZQ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function SY($,W){if(!$)return;let j=AW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let B=await Kj(j,"utf-8"),X=JSON.parse(B);if(BQ(X))return XQ(X);return}let Q=await HW(j),Z=Object.values(Q).filter(BQ);if(Z.length===0)return;return XQ(Z[0])}function BQ($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function XQ($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function EY($){let W=YQ($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),Q=new j;for(let Z of W){let{modulePath:B,exportName:X}=MY(Z);if(!B)continue;let Y=AW(process.cwd(),B);try{let q=await HW(Y),A=NY(q,X);if(A)await A(Q)}catch(q){console.warn(`Failed to load registrar from ${Y}: ${q}`)}}return Q}function MY($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),Q=W?.trim()??null,Z=j?.trim();return{modulePath:Q,exportName:Z}}function NY($,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 HO($,W,j={},Q){let{fs:Z,logger:B}=$,X=await Z.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],q=[],A=Q?.validate??((V)=>R$(V,{fs:Z,logger:B})),H=Q?.build??((V,G)=>x0(V,{fs:Z,logger:B},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let z={specPath:V,outputDir:G};if(j.validate)try{z.validation=await A(V)}catch(J){z.error={phase:"validate",message:J instanceof Error?J.message:String(J)},q.push(z);continue}if(!j.dryRun)try{z.build=await H(V,G)}catch(J){z.error={phase:"build",message:J instanceof Error?J.message:String(J)},q.push(z);continue}else B.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});q.push(z)}return{specs:X,runs:q}}import{generateText as RY}from"ai";var DY=`
|
|
2000
|
+
`)}function mY($,W){let j=[];if(j.push(`# Implementation Guide: ${$.meta.key}`),j.push(""),j.push(`**Target Agent**: ${W}`),j.push(`**Spec Type**: ${$.specType}${$.kind?` (${$.kind})`:""}`),j.push(""),$.meta.description)j.push("## Overview"),j.push(""),j.push($.meta.description),j.push("");if($.meta.goal)j.push("## Goal"),j.push(""),j.push($.meta.goal),j.push("");if($.meta.context)j.push("## Context"),j.push(""),j.push($.meta.context),j.push("");if(j.push("## Implementation Steps"),j.push(""),$.specType==="operation"){if(j.push(`1. Create the ${$.kind??"operation"} handler function`),$.hasIo)j.push("2. Implement input validation according to the schema"),j.push("3. Implement the core business logic"),j.push("4. Return output matching the expected schema");if($.hasPolicy)j.push("5. Enforce authorization and policies");if($.emittedEvents&&$.emittedEvents.length>0){j.push("6. Emit events on success:");for(let A of $.emittedEvents)j.push(` - \`${A.name}\` (v${A.version})`)}j.push("7. Add error handling for expected failure cases"),j.push("8. Write tests covering success and error scenarios")}else if($.specType==="feature"){if(j.push("1. Set up the feature module structure"),$.operations&&$.operations.length>0){j.push("2. Implement operations:");for(let A of $.operations)j.push(` - \`${A.name}\` (v${A.version})`)}if($.presentations&&$.presentations.length>0){j.push("3. Implement presentations:");for(let A of $.presentations)j.push(` - \`${A.name}\` (v${A.version})`)}j.push("4. Wire up feature exports"),j.push("5. Add integration tests")}else j.push("1. Review the spec requirements"),j.push("2. Implement the core logic"),j.push("3. Add tests"),j.push("4. Document the implementation");if(j.push(""),j.push("## Constraints"),j.push(""),j.push(`- Stability: ${$.meta.stability??"experimental"}`),$.meta.owners&&$.meta.owners.length>0)j.push(`- Owners: ${$.meta.owners.join(", ")}`);if($.meta.tags&&$.meta.tags.length>0)j.push(`- Tags: ${$.meta.tags.join(", ")}`);if(j.push(""),W==="cursor-cli")j.push("## Cursor Notes"),j.push(""),j.push("- Use Composer mode for multi-file changes"),j.push("- Reference this guide in your cursor rules"),j.push("- Break implementation into small, focused commits");else if(W==="claude-code")j.push("## Claude Code Notes"),j.push(""),j.push("- Use extended thinking for complex logic"),j.push("- Ask for clarification on ambiguous requirements"),j.push("- Provide step-by-step reasoning");else if(W==="generic-mcp")j.push("## General Notes"),j.push(""),j.push("- Use inline comments to guide generation"),j.push("- Review generated code carefully");return j.push(""),j.push("## Spec Definition"),j.push(""),j.push(z$($,"full")),j.join(`
|
|
2001
|
+
`)}function PY($){let W=[];if(W.push(`# ${$.meta.key}`),W.push(""),W.push(`Description: ${$.meta.description??"No description"}`),W.push(""),W.push("## Rules"),W.push(""),$.specType==="operation"){if(W.push(`- This is a ${$.kind??"operation"} spec`),$.hasIo)W.push("- Validate input and output against schemas");if($.hasPolicy)W.push("- Enforce authorization policies");if($.emittedEvents&&$.emittedEvents.length>0)W.push("- Emit documented events")}else if($.specType==="feature")W.push("- Implement all operations and presentations"),W.push("- Follow modular architecture");else W.push(`- Follow ${$.specType} patterns`);return W.push("- Follow project code quality standards"),W.push("- Write tests for new functionality"),W.join(`
|
|
2002
|
+
`)}function RO($,W,j="generic-mcp"){switch(W){case"guide":return mY($,j);case"rules":return PY($);case"prompt":return z$($,"prompt");case"context":return z$($,"context");case"full":default:return z$($,"full")}}import{readFile as kY}from"node:fs/promises";import{createRequire as hY}from"node:module";import{dirname as gY,resolve as l4}from"node:path";import{pathToFileURL as fY}from"node:url";import r4 from"node:vm";import Fj from"typescript";async function Q$($,W={}){let j=l4(process.cwd(),$),A=W.runtime??nY();try{let Q=A==="bun"?await uY(j):await dY(j);return{modulePath:j,exports:Q}}catch(Q){throw Error(i4(j,Q))}}async function PO($,W){let j=l4(process.cwd(),$);if(!await W.exists(j))return null;return Q$(j)}async function vW($,W={}){return(await Q$($,W)).exports}async function o4($,W){let j=await vW($);return p4(j,$,W)}function i4($,W){return`Failed to load authored module at ${$}: ${W instanceof Error?W.message:String(W)}`}async function p4($,W,j){if(j.isValue($))return $;for(let A of j.instanceKeys??[])if(j.isValue($[A]))return $[A];for(let A of j.factoryKeys??[]){let Q=$[A];if(typeof Q!=="function")continue;let Z=await Q();if(j.isValue(Z))return Z}throw Error(`${j.description} module ${W} must export a supported instance or factory.`)}async function uY($){return await import(fY($).href)}async function dY($){return await cY($)??{}}function nY(){return typeof globalThis.Bun<"u"?"bun":"node"}var kO={formatModuleLoadError:i4,resolveAuthoredModuleValue:p4};async function cY($){let W=await kY($,"utf-8"),j=Fj.transpileModule(W,{compilerOptions:{module:Fj.ModuleKind.CommonJS,target:Fj.ScriptTarget.ES2020,esModuleInterop:!0},fileName:$}),A={},Q={exports:A},Z=hY($),X=r4.createContext({module:Q,exports:A,require:Z,__dirname:gY($),__filename:$,process,console,Buffer,setTimeout,setImmediate,clearTimeout,clearImmediate});return new r4.Script(j.outputText,{filename:$}).runInContext(X),Q.exports}var t4=[{name:"@contractspec/lib.contracts-spec",description:"Core ContractSpec library for defining commands, queries, and events"},{name:"zod",description:"Schema validation library (peer dependency)"}],rY=[...t4,{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 xj($){return $==="minimal"?t4:rY}function yj($){return $.filter((W)=>!W.dev)}function vj($){return $.filter((W)=>W.dev)}import{exec as lY}from"node:child_process";import{promisify as oY}from"node:util";var iY=oY(lY),pY={confirm:async()=>!0,select:async($,W)=>W[0]?.value??""};async function cO($,W,j=pY){let A=xj(W.mode),Q=yj(A),Z=vj(A),X=[],Y=[],B=[],q=$.join(W.workspaceRoot,"package.json");if(!await $.exists(q))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 V=await $.readFile(q),G=JSON.parse(V),J=new Set([...Object.keys(G.dependencies??{}),...Object.keys(G.devDependencies??{})]),b=k$(W.workspaceRoot),w=Q.filter((U)=>{if(J.has(U.name)&&!W.force)return Y.push({name:U.name,action:"skipped",message:"Already installed",dev:!1}),!1;return!0}),L=Z.filter((U)=>{if(J.has(U.name)&&!W.force)return Y.push({name:U.name,action:"skipped",message:"Already installed",dev:!0}),!1;return!0});if(W.dryRun){let U=[...w,...L];return{success:!0,installed:U.map((O)=>({name:O.name,action:"installed",message:`Would install: ${O.description}`,dev:O.dev})),skipped:Y,errors:[],summary:`Dry run: would install ${U.length} package(s), skip ${Y.length}.`}}if(!W.skipPrompts&&(w.length>0||L.length>0)){let U=w.length+L.length;if(!await j.confirm(`Install ${U} package(s) using ${b}?`))return{success:!0,installed:[],skipped:[...Y,...w.map((K)=>({name:K.name,action:"skipped",message:"User cancelled"})),...L.map((K)=>({name:K.name,action:"skipped",message:"User cancelled",dev:!0}))],errors:[],summary:"Installation cancelled by user."}}if(w.length>0){let U=await a4(w,b,W.workspaceRoot,!1);for(let O of U)if(O.action==="installed")X.push(O);else B.push(O)}if(L.length>0){let U=await a4(L,b,W.workspaceRoot,!0);for(let O of U)if(O.action==="installed")X.push(O);else B.push(O)}let z=B.length===0,S=z?`Successfully installed ${X.length} package(s), skipped ${Y.length}.`:`Installed ${X.length}, skipped ${Y.length}, failed ${B.length}.`;return{success:z,installed:X,skipped:Y,errors:B,summary:S}}async function a4($,W,j,A){let Q=[],Z=$.map((X)=>X.version?`${X.name}@${X.version}`:X.name);try{let Y=`${R5(W,A)} ${Z.join(" ")}`;await iY(Y,{cwd:j,timeout:120000});for(let B of $)Q.push({name:B.name,action:"installed",message:B.description,dev:A})}catch(X){let Y=X instanceof Error?X.message:String(X);for(let B of $)Q.push({name:B.name,action:"error",message:`Failed to install: ${Y}`,dev:A})}return Q}async function rO($,W){let j=$.join(W,"package.json");try{let A=await $.readFile(j),Q=JSON.parse(A);return"@contractspec/lib.contracts-spec"in{...Q.dependencies,...Q.devDependencies}}catch{return!1}}function lO($){let W=xj($),j=[];j.push(`ContractSpec ${$} installation:`),j.push("");let A=yj(W);if(A.length>0){j.push("Dependencies:");for(let Z of A)j.push(` • ${Z.name} - ${Z.description}`)}let Q=vj(W);if(Q.length>0){j.push(""),j.push("Dev Dependencies:");for(let Z of Q)j.push(` • ${Z.name} - ${Z.description}`)}return j.join(`
|
|
2003
|
+
`)}import{RegeneratorService as tY}from"@contractspec/lib.contracts-spec/regenerator";function eO($){return new tY({contexts:$.contexts,adapters:$.adapters??{},rules:$.rules,sink:$.sink,pollIntervalMs:$.pollIntervalMs,batchDurationMs:$.batchDurationMs})}class mW{registryUrl;constructor($){this.registryUrl=$.registryUrl.replace(/\/+$/,"")}async getJson($){let W=`${this.registryUrl}${$.startsWith("/")?"":"/"}${$}`,j;try{j=await fetch(W,{method:"GET",headers:{Accept:"application/json"}})}catch(A){throw Error(`Registry request failed: ${W} (${A instanceof Error?A.message:String(A)})`)}if(!j.ok){let A=await j.text().catch(()=>"");throw Error(`Registry request failed: ${j.status} ${j.statusText} ${A}`)}return await j.json()}}function mj($){return $||process.env.CONTRACTSPEC_REGISTRY_URL||"http://localhost:8090"}async function WS($,W,j){let{logger:A}=j,Q=mj(W.registryUrl);A.info(`Adding spec to registry: ${$}`,{registryUrl:Q}),await new mW({registryUrl:Q}).getJson(`/specs/add?path=${encodeURIComponent($)}`),A.info("Spec added to registry successfully")}async function jS($,W){let{logger:j}=W,A=mj($.registryUrl);j.info("Listing specs from registry",{registryUrl:A});let Q=new mW({registryUrl:A}),Z=$.filter?`?filter=${encodeURIComponent($.filter)}`:"",X=await Q.getJson(`/specs${Z}`);return j.info(`Found ${X.length} specs`),X}async function AS($,W,j){let{logger:A}=j,Q=mj(W.registryUrl);A.info(`Searching registry: ${$}`,{registryUrl:Q});let X=await new mW({registryUrl:Q}).getJson(`/specs/search?q=${encodeURIComponent($)}`);return A.info(`Found ${X.length} results`),X}class aY{fs;logger;constructor($,W){this.fs=$;this.logger=W}async sync($){let{config:W,cwd:j}=$,A=$.targets??W.targets??[];if(!W.enabled&&!$.targets)return{success:!0,files:[],logs:["Rule synchronization is disabled."]};this.logger.info(`Synchronizing rules for targets: ${A.join(", ")}...`);try{let Q=this.fs.join(j,W.rulesDir??".rules");if(!await this.fs.exists(Q))return{success:!1,files:[],errors:[`Rules directory not found: ${Q}`]};let X=await this.generateConfig($);this.logger.debug(`Generated rulesync config: ${X}`);let Y=[];for(let B of A){let q=this.getTargetFileName(B);if(q){let H=this.fs.join(j,q);Y.push(H)}}return{success:!0,files:Y,logs:[`Successfully synchronized rules to ${Y.length} targets.`]}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return this.logger.error(`Rule synchronization failed: ${Z}`),{success:!1,files:[],errors:[Z]}}}async generateConfig($){let{config:W}=$,j={rules:(W.rules??[]).map((A)=>this.fs.join(W.rulesDir??".rules",A)),targets:$.targets||W.targets};return JSON.stringify(j,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}}}var $9="<!-- contractspec:init:agents:start -->",W9="<!-- contractspec:init:agents:end -->",sY="<!-- This section is managed by `contractspec init`. Content outside these markers is user-owned and preserved. -->";async function Pj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"AGENTS.md");try{let Z=await $.exists(Q),X=D8(W);if(Z){let Y=await $.readFile(Q);if(W.interactive){if(!await j.confirm(`${Q} exists. Add or update the ContractSpec-managed section while preserving existing content?`))return{target:"agents-md",filePath:Q,action:"skipped",message:"User skipped AGENTS guide merge"}}return await $.writeFile(Q,eY(Y,X)),{target:"agents-md",filePath:Q,action:"merged",message:"Added or updated the ContractSpec-managed AGENTS.md section"}}return await $.writeFile(Q,j9(X)),{target:"agents-md",filePath:Q,action:"created",message:"Created AI agent guide"}}catch(Z){return{target:"agents-md",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}function eY($,W){let j=j9(W),A=$3();if(A.test($))return $.replace(A,j);if(s4($)===s4(W))return j;return`${j}${$}`}function j9($){let W=$.replace(/\r\n/g,`
|
|
2004
|
+
`).trimEnd();return`${$9}
|
|
2005
|
+
${sY}
|
|
2006
|
+
${W}
|
|
2007
|
+
${W9}
|
|
2008
|
+
`}function s4($){return $.replace(/\r\n/g,`
|
|
2009
|
+
`).trimEnd()}function $3(){return new RegExp(`${e4($9)}[\\s\\S]*?${e4(W9)}(?:\\r?\\n)?`)}function e4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{generateArtifactsForAudience as W3,generateBiomePreset as j3}from"@contractspec/biome-config";async function kj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,"biome.jsonc"),Z=$.join(A,".contractspec","biome"),X=$.join(Z,"plugins"),Y=$.join(Z,"ai"),B=W3("consumer");try{let q=await $.exists(Q);if(q&&W.interactive){if(!await j.confirm(`${Q} exists. Overwrite it with ContractSpec's Biome preset?`))return{target:"biome-config",filePath:Q,action:"skipped",message:"User skipped Biome configuration"}}await $.mkdir(X),await $.mkdir(Y),await $.writeFile(Q,j3("consumer").replaceAll("../plugins/consumer-prefer-design-system.grit","./.contractspec/biome/plugins/consumer-prefer-design-system.grit"));for(let[H,V]of Object.entries(B.plugins))await $.writeFile($.join(X,H),V);return await $.writeFile($.join(Y,"consumer.md"),B.aiRules),{target:"biome-config",filePath:Q,action:q?"merged":"created",message:q?"Replaced existing Biome configuration and refreshed local plugins":"Created Biome configuration and local plugins"}}catch(q){return{target:"biome-config",filePath:Q,action:"error",message:q instanceof Error?q.message:"Unknown error"}}}async function hj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".contractsrc.json");try{let Z=await $.exists(Q),X=u$(W);if(Z){let Y=await $.readFile(Q),B=r(Y);if(!B)return{target:"cli-config",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Merge ContractSpec defaults?`))return{target:"cli-config",filePath:Q,action:"skipped",message:"User skipped merge"}}let q=p(B,X);if((W.preset==="connect"||W.preset?.startsWith("builder-"))&&typeof X==="object"&&X!==null){let H={};if("connect"in X)H.connect=X.connect;if("builder"in X)H.builder=X.builder;await $.writeFile(Q,F(y1(q,H)))}else await $.writeFile(Q,F(q));return{target:"cli-config",filePath:Q,action:"merged",message:"Merged with existing configuration"}}return await $.writeFile(Q,F(X)),{target:"cli-config",filePath:Q,action:"created",message:"Created CLI configuration"}}catch(Z){return{target:"cli-config",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function gj($,W,j){let A=$.join(W.workspaceRoot,".cursor","rules"),Q=$.join(A,"contractspec.mdc");try{let Z=$.join(W.workspaceRoot,".cursor");if(!await $.exists(Z))await $.mkdir(Z);if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=C8(W);if(X)if(W.interactive){if(!await j.confirm(`${Q} exists. Overwrite with latest rules?`))return{target:"cursor-rules",filePath:Q,action:"skipped",message:"User kept existing rules"}}else return{target:"cursor-rules",filePath:Q,action:"skipped",message:"File already exists"};return await $.writeFile(Q,Y),{target:"cursor-rules",filePath:Q,action:X?"merged":"created",message:X?"Updated Cursor rules":"Created Cursor rules"}}catch(Z){return{target:"cursor-rules",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function fj($,W,j){let A=qW();try{let Q=await $.exists(A),Z=R8();if(W.interactive){if(!await j.confirm(`Configure Claude Desktop at ${A}?`))return{target:"mcp-claude",filePath:A,action:"skipped",message:"User skipped Claude Desktop configuration"}}if(Q){let B=await $.readFile(A),q=r(B);if(!q)return{target:"mcp-claude",filePath:A,action:"error",message:"Existing file is not valid JSON"};let H=p(q,Z);return await $.writeFile(A,F(H)),{target:"mcp-claude",filePath:A,action:"merged",message:"Added ContractSpec to Claude Desktop"}}let X=A.substring(0,A.lastIndexOf("/"));if(!await $.exists(X))await $.mkdir(X);return await $.writeFile(A,F(Z)),{target:"mcp-claude",filePath:A,action:"created",message:"Created Claude Desktop configuration"}}catch(Q){return{target:"mcp-claude",filePath:A,action:"error",message:Q instanceof Error?Q.message:"Unknown error"}}}async function uj($,W,j){let A=$.join(W.workspaceRoot,".cursor"),Q=$.join(A,"mcp.json");try{if(!await $.exists(A))await $.mkdir(A);let X=await $.exists(Q),Y=q0();if(X){let B=await $.readFile(Q),q=r(B);if(!q)return{target:"mcp-cursor",filePath:Q,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Q} exists. Add ContractSpec MCP server?`))return{target:"mcp-cursor",filePath:Q,action:"skipped",message:"User skipped merge"}}let H=p(q,Y);return await $.writeFile(Q,F(H)),{target:"mcp-cursor",filePath:Q,action:"merged",message:"Added ContractSpec MCP server"}}return await $.writeFile(Q,F(Y)),{target:"mcp-cursor",filePath:Q,action:"created",message:"Created Cursor MCP configuration"}}catch(Z){return{target:"mcp-cursor",filePath:Q,action:"error",message:Z instanceof Error?Z.message:"Unknown error"}}}async function dj($,W,j){let A=W.isMonorepo&&W.scope==="package"?W.packageRoot??W.workspaceRoot:W.workspaceRoot,Q=$.join(A,".vscode"),Z=$.join(Q,"settings.json");try{if(!await $.exists(Q))await $.mkdir(Q);let Y=await $.exists(Z),B=BW(W);if(Y){let q=await $.readFile(Z),H=r(q);if(!H)return{target:"vscode-settings",filePath:Z,action:"error",message:"Existing file is not valid JSON"};if(W.interactive){if(!await j.confirm(`${Z} exists. Add ContractSpec settings?`))return{target:"vscode-settings",filePath:Z,action:"skipped",message:"User skipped merge"}}let V=p(H,B);if((W.preset==="builder-managed"||W.preset==="builder-hybrid")&&"contractspec.api.baseUrl"in B)V["contractspec.api.baseUrl"]=B["contractspec.api.baseUrl"];return await $.writeFile(Z,F(V)),{target:"vscode-settings",filePath:Z,action:"merged",message:"Added ContractSpec settings"}}return await $.writeFile(Z,F(B)),{target:"vscode-settings",filePath:Z,action:"created",message:"Created VS Code settings"}}catch(X){return{target:"vscode-settings",filePath:Z,action:"error",message:X instanceof Error?X.message:"Unknown error"}}}var A3={confirm:async($,W)=>W??!0,select:async($,W)=>{return W.find((j)=>j.selected)?.value??W[0]?.value??""},multiSelect:async($,W)=>W.filter((j)=>j.selected!==!1).map((j)=>j.value),input:async($,W)=>W??""};async function hS($,W,j=A3){let A=[],Q=W.targets.length>0?W.targets:X0,Z=W.workspaceRoot,X=D(Z),Y=W.packageRoot??f(Z),B=W.isMonorepo??e$(X),q=W.packageName??(B?I$(Y):void 0),H=await A9($,[Y,X]),V=W.preset??B0(H);if(W.interactive&&!W.preset)V=await j.select("Select initialization preset:",U8.map((R)=>({value:R,label:L8[R],description:O8[R],selected:R===V})));let G=W.scope??"workspace",J=Y!==X;if(B&&W.interactive&&J)G=await j.select("Monorepo detected. Configure at which level?",[{value:"package",label:`Package level (${q??Y})`,description:"Create config files in the current package",selected:!0},{value:"workspace",label:`Workspace level (${X})`,description:"Create config files at the workspace root"}]);let b=B&&G==="package"?Y:X,w=await A9($,[b]),L={...W,workspaceRoot:X,packageRoot:Y,isMonorepo:B,scope:G,packageName:q,preset:V,builderApiBaseUrl:W.builderApiBaseUrl??w?.builder?.api?.baseUrl,builderControlPlaneTokenEnvVar:W.builderControlPlaneTokenEnvVar??w?.builder?.api?.controlPlaneTokenEnvVar,builderLocalRuntimeId:W.builderLocalRuntimeId??w?.builder?.localRuntime?.runtimeId,builderLocalGrantedTo:W.builderLocalGrantedTo??w?.builder?.localRuntime?.grantedTo,builderLocalProviderIds:W.builderLocalProviderIds??w?.builder?.localRuntime?.providerIds,connectStudioEndpoint:W.connectStudioEndpoint??w?.connect?.studio?.endpoint,connectStudioQueue:W.connectStudioQueue??w?.connect?.studio?.queue},z=S8(V,Q);if(W.interactive)z=await j.multiSelect("Select components to configure:",X0.map((R)=>({value:R,label:z8[R],selected:z.includes(R)})));let S=L.projectName;if(W.interactive&&!S){let R=G==="package"&&q?q:b.split("/").pop()??"my-project";S=await j.input("Project name:",R)}let U=L.builderApiBaseUrl;if(W.interactive&&(V==="builder-managed"||V==="builder-hybrid"))U=await j.input("Builder API base URL:",U??"https://api.contractspec.io");let{builderLocalRuntimeId:O,builderLocalGrantedTo:K}=L;if(W.interactive&&(V==="builder-local"||V==="builder-hybrid"))O=await j.input("Default local runtime target id:",O??"rt_local_daemon"),K=await j.input("Default local runtime grant target:",K??"local:operator");let _={...L,projectName:S,targets:z,builderApiBaseUrl:U,builderLocalRuntimeId:O,builderLocalGrantedTo:K};for(let R of z){let v=await Q3($,R,_,j);A.push(v)}let I=await EW($,{behavior:_.gitignoreBehavior,interactive:_.interactive,patterns:N8({preset:V}),prompts:j,root:X});if(_.gitignoreBehavior!=="skip"||I.action!=="skipped")A.push(I);let M=A.filter((R)=>R.action!=="error").length,E=A.filter((R)=>R.action==="error").length,C=B?` (${G} level)`:"";return{success:E===0,preset:V,files:A,summary:`Setup complete${C}: ${M} configured, ${E} failed.`,nextSteps:E8(_)}}async function Q3($,W,j,A){switch(W){case"agents-md":return Pj($,j,A);case"cli-config":return hj($,j,A);case"biome-config":return kj($,j,A);case"vscode-settings":return dj($,j,A);case"mcp-cursor":return uj($,j,A);case"mcp-claude":return fj($,j,A);case"cursor-rules":return gj($,j,A);default:return{target:W,filePath:"",action:"error",message:`Unknown target: ${W}`}}}async function A9($,W){for(let j of W){let A=$.join(j,".contractsrc.json");if(!await $.exists(A))continue;let Q=r(await $.readFile(A));if(Q)return Q}return null}import{validateBlueprint as Z3}from"@contractspec/lib.contracts-spec/app-config/validation";import{resolve as X3}from"path";async function tS($,W){let{fs:j}=W,A=X3(process.cwd(),$);if(!await j.exists(A))return{valid:!1,errors:[`Blueprint file not found: ${A}`]};try{let Q=await Q$(A),Z=Y3(Q.exports),X=Z3(Z);return{spec:Z,report:X,valid:X.valid,errors:X.errors.map((Y)=>`[${Y.code}] ${Y.path}: ${Y.message}`)}}catch(Q){return{valid:!1,errors:[Q instanceof Error?Q.message:String(Q)]}}}function Y3($){let W=Object.values($).filter(B3);if(W.length===0)throw Error("Blueprint module does not export an AppBlueprintSpec.");return W[0]}function B3($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"}import{basename as q3,dirname as nj,join as R0}from"path";async function $I($,W,j,A,Q){let{fs:Z}=Q,X=A.implementationPath;if(!X){let H=nj($),V=q3($,".ts"),G=[R0(H,V.replace(".contracts",".handler")+".ts"),R0(H,V.replace(".presentation","")+".tsx"),R0(H,V.replace(".form",".form")+".tsx"),R0(nj(H),"handlers",V.replace(".contracts",".handler")+".ts"),R0(nj(H),"components",V.replace(".presentation","")+".tsx")];for(let J of G)if(await Z.exists(J)){X=J;break}}if(!X||!await Z.exists(X))return{success:!0,errors:[],warnings:["Implementation file not found. Specify with --implementation-path"],suggestions:[]};let Y=await Z.readFile(X),q=await new g0(j).validate(W,Y);return{success:q.success,errors:q.errors||[],warnings:q.warnings||[],suggestions:q.suggestions||[],report:q.code}}import{validateBuilderBlueprint as H3,validateBuilderReadinessReport as V3,validateBuilderWorkspace as G3,validateBuilderWorkspaceSnapshot as J3}from"@contractspec/lib.builder-spec";import{validateExternalExecutionReceipt as b3,validateExternalPatchProposal as w3,validateProviderRoutingPolicy as K3,validateRuntimeTarget as _3}from"@contractspec/lib.provider-spec";import{validateBundleNodeKinds as z3,validateLayoutSlots as U3}from"@contractspec/lib.surface-runtime/spec";async function XI($,W){if(!M3($.specType))return{valid:!0,errors:[],warnings:[]};let j=v3($.filePath),A=[`${j}/package.json`,`${j}/README.md`,`${j}/src/index.ts`,$.filePath],Q=[];for(let Y of A)if(!await W.exists(Y))Q.push(`Missing package scaffold file: ${Y}`);if(Q.length>0)return{valid:!1,errors:Q,warnings:[]};let Z;try{Z=(await Q$($.filePath)).exports}catch(Y){return{valid:!1,errors:[Y instanceof Error?Y.message:String(Y)],warnings:[]}}let X=$.specType==="module-bundle"?L3(Z):$.specType==="builder-spec"?O3(Z):S3(Z);return{valid:Q.length===0&&X.errors.length===0,errors:[...Q,...X.errors],warnings:X.warnings.map((Y)=>`[${$.filePath}] ${Y}`)}}function L3($){let W=[],j=[],A=I3($,E3);if(A.length===0)return j.push(cj("module-bundle","bundle")),{errors:W,warnings:j};for(let Q of A){let Z=Object.values(Q.value.surfaces);for(let X of Z){try{U3(X)}catch(Y){W.push(`[${Q.exportName}] ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of z3(X).warnings)j.push(`[${Q.exportName}] ${Y}`)}}return{errors:W,warnings:j}}function O3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(N3(Z)){A+=1,W.push(...PW(Q,G3(Z)));continue}if(R3(Z)){A+=1,W.push(...PW(Q,H3(Z)));continue}if(C3(Z)){A+=1,W.push(...PW(Q,V3(Z)));continue}if(D3(Z))A+=1,W.push(...PW(Q,J3(Z)))}if(A===0)j.push(cj("builder-spec","builder"));return{errors:W,warnings:j}}function S3($){let W=[],j=[],A=0;for(let[Q,Z]of Object.entries($)){if(Q==="__esModule")continue;if(T3(Z)){A+=1,W.push(...kW(Q,_3(Z)));continue}if(F3(Z)){A+=1,W.push(...kW(Q,K3(Z)));continue}if(x3(Z)){A+=1,W.push(...kW(Q,b3(Z)));continue}if(y3(Z))A+=1,W.push(...kW(Q,w3(Z)))}if(A===0)j.push(cj("provider-spec","provider"));return{errors:W,warnings:j}}function I3($,W){return Object.entries($).filter(([j,A])=>j!=="__esModule"&&W(A)).map(([j,A])=>({exportName:j,value:A}))}function PW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function kW($,W){return W.map((j)=>`[${$}] ${j.path}: ${j.message}`)}function M3($){return $==="module-bundle"||$==="builder-spec"||$==="provider-spec"}function E3($){return typeof $==="object"&&$!==null&&"meta"in $&&"routes"in $&&Array.isArray($.routes)&&"surfaces"in $&&typeof $.surfaces==="object"}function N3($){return typeof $==="object"&&$!==null&&"tenantId"in $&&"defaultLocale"in $&&Array.isArray($.ownerIds)}function R3($){return typeof $==="object"&&$!==null&&"appBrief"in $&&"coverageReport"in $&&Array.isArray($.runtimeProfiles)}function C3($){return typeof $==="object"&&$!==null&&"score"in $&&"recommendedNextAction"in $&&"evidenceBundleRef"in $}function D3($){return typeof $==="object"&&$!==null&&"workspace"in $&&"stableMemory"in $&&"workingMemory"in $}function T3($){return typeof $==="object"&&$!==null&&"displayName"in $&&"capabilityProfile"in $&&Array.isArray($.capabilityProfile.availableProviders)}function F3($){return typeof $==="object"&&$!==null&&"taskRules"in $&&"riskRules"in $&&"runtimeModeRules"in $}function x3($){return typeof $==="object"&&$!==null&&"runId"in $&&"providerId"in $&&"contextBundleId"in $}function y3($){return typeof $==="object"&&$!==null&&"diffHash"in $&&"changedAreas"in $&&"verificationRequirements"in $}function v3($){let W=$.replaceAll("\\","/"),j=W.lastIndexOf("/src/");return j===-1?W.replace(/\/[^/]+$/,""):W.slice(0,j)}function cj($,W){return`No recognized ${W} exports were found for ${$} deep validation.`}import{validateSpecStructure as m3}from"@contractspec/module.workspace";function Q9($,W={}){let j=[],A=[],Q;if(!W.skipStructure)Q=m3($),j.push(...Q.errors),A.push(...Q.warnings);return{valid:j.length===0,structureResult:Q,errors:j,warnings:A,code:$.sourceBlock}}async function HI($,W={}){return $.map((j)=>({spec:j,...Q9(j,W)}))}async function m$($,W,j={}){let{fs:A}=W;if(!await A.exists($))return{valid:!1,errors:[`Spec file not found: ${$}`],warnings:[],code:void 0};let Z=await A.readFile($),X=[],Y=[],B=void 0;if(!j.skipStructure){let q=await $$(W,{pattern:$});for(let H of q){let V=Q9(H,j);B=V.structureResult,X.push(...V.errors),Y.push(...V.warnings)}}return{valid:X.length===0,structureResult:B,errors:X,warnings:Y,code:Z}}async function VI($,W,j={}){let A=new Map;for(let Q of $){let Z=await m$(Q,W,j);A.set(Q,Z)}return A}import{validateConfig as P3}from"@contractspec/lib.contracts-spec/app-config/validation";import{readFile as lj}from"fs/promises";import{resolve as hW}from"path";async function _I($,W,j,A){let{fs:Q}=A,Z=hW(process.cwd(),W);if(!await Q.exists(Z))return{valid:!1,errors:[`Tenant config file not found: ${Z}`]};try{let X=await k3(Z),Y=await h3(j.connections,Q),B=await g3(j.translationCatalog,Q),q=await f3(j.integrationRegistrars),H={};if(Y.length>0)H.tenantConnections=Y;if(B)H.translationCatalogs={blueprint:[B],platform:[]};if(q)H.integrationSpecs=q;let V=P3($,X,H);return{config:X,report:V,valid:V.valid,errors:V.errors.map((G)=>`[${G.code}] ${G.path}: ${G.message}`)}}catch(X){return{valid:!1,errors:[X instanceof Error?X.message:String(X)]}}}async function k3($){if($.endsWith(".json")){let A=await lj($,"utf-8"),Q=JSON.parse(A);if(!Z9(Q))throw Error("Tenant config JSON does not match the expected structure (missing meta).");return Q}let W=await Q$($),j=Object.values(W.exports).filter(Z9);if(j.length===0)throw Error("Tenant config module does not export a TenantAppConfig.");return j[0]}function Z9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.tenantId==="string"}function q9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((j)=>j.trim()).filter(Boolean)}async function h3($,W){let j=q9($);if(!j.length)return[];let A=[];for(let Q of j){let Z=hW(process.cwd(),Q);if(!await W.exists(Z)){console.warn(`Warning: Connection file not found: ${Z}`);continue}if(Z.endsWith(".json")){let Y=await lj(Z,"utf-8"),B=JSON.parse(Y);A.push(...rj(B));continue}let X=await Q$(Z);A.push(...rj(X.exports))}return A}function rj($){if(Array.isArray($)){let W=$.filter(X9);if(W.length)return W}if(X9($))return[$];if($&&typeof $==="object"){let j=Object.values($).flatMap((A)=>rj(A));if(j.length)return j}return[]}function X9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.id==="string"&&typeof $.secretRef==="string"}async function g3($,W){if(!$)return;let j=hW(process.cwd(),$);if(!await W.exists(j))return;if(j.endsWith(".json")){let Z=await lj(j,"utf-8"),X=JSON.parse(Z);if(Y9(X))return B9(X);return}let A=await Q$(j),Q=Object.values(A.exports).filter(Y9);if(Q.length===0)return;return B9(Q[0])}function Y9($){return typeof $==="object"&&$!==null&&"meta"in $&&typeof $.meta?.key==="string"&&typeof $.meta?.version==="string"&&Array.isArray($.entries)}function B9($){let W=$.supportedLocales&&$.supportedLocales.length>0?$.supportedLocales:[$.defaultLocale];return{...$,supportedLocales:W}}async function f3($){let W=q9($);if(!W.length)return;let{IntegrationSpecRegistry:j}=await import("@contractspec/lib.contracts-integrations"),A=new j;for(let Q of W){let{modulePath:Z,exportName:X}=u3(Q);if(!Z)continue;let Y=hW(process.cwd(),Z);try{let B=await Q$(Y),q=d3(B.exports,X);if(q)await q(A)}catch(B){console.warn(`Failed to load registrar from ${Y}: ${B}`)}}return A}function u3($){if(!$)return{modulePath:null};let[W,j]=$.split("#"),A=W?.trim()??null,Q=j?.trim();return{modulePath:A,exportName:Q}}function d3($,W){if(W){let j=$[W];if(typeof j==="function")return j;return}if(typeof $.default==="function")return $.default;for(let j of Object.values($))if(typeof j==="function")return j;return}async function CI($,W,j={},A){let{fs:Q,logger:Z}=$,X=await Q.glob({pattern:j.pattern}),Y=j.outputDirs?.length?j.outputDirs:[void 0],B=[],q=A?.validate??((V)=>m$(V,{fs:Q,logger:Z})),H=A?.build??((V,G)=>f$(V,{fs:Q,logger:Z},G?{...W,outputDir:G}:W,{...j.buildOptions??{},outputDir:G}));for(let V of X)for(let G of Y){let J={specPath:V,outputDir:G};if(j.validate)try{J.validation=await q(V)}catch(b){J.error={phase:"validate",message:b instanceof Error?b.message:String(b)},B.push(J);continue}if(!j.dryRun)try{J.build=await H(V,G)}catch(b){J.error={phase:"build",message:b instanceof Error?b.message:String(b)},B.push(J);continue}else Z.info("[dry-run] syncSpecs skipped build",{specPath:V,outputDir:G});B.push(J)}return{specs:X,runs:B}}import{generateText as n3}from"ai";var c3=`
|
|
1765
2010
|
You are an expert software test engineer specializing in ContractSpec.
|
|
1766
2011
|
Your goal is to generate comprehensive test scenarios for a given ContractSpec Operation.
|
|
1767
2012
|
|
|
@@ -1779,7 +2024,7 @@ Generate scenarios covering:
|
|
|
1779
2024
|
- Happy path (valid input, successful execution)
|
|
1780
2025
|
- Edge cases (boundary values, optional fields)
|
|
1781
2026
|
- Error cases (invalid input, business rule violations)
|
|
1782
|
-
`.trim();class
|
|
2027
|
+
`.trim();class r3{logger;defaultModel;constructor($,W){this.logger=$;this.defaultModel=W}async generateTests($,W={}){let j=W.model??this.defaultModel;if(!j)throw Error("No AI model provided for test generation");this.logger.info(`Generating tests for operation ${$.meta.key}...`);let A=`
|
|
1783
2028
|
Generate a TestSpec for the following Operation:
|
|
1784
2029
|
|
|
1785
2030
|
\`\`\`json
|
|
@@ -1788,23 +2033,23 @@ ${JSON.stringify($,null,2)}
|
|
|
1788
2033
|
|
|
1789
2034
|
The output must be a valid JSON object conforming to the TestSpec interface.
|
|
1790
2035
|
Do not include markdown formatting or explanations, just the JSON.
|
|
1791
|
-
`.trim();try{let{text:
|
|
1792
|
-
`)}function
|
|
1793
|
-
`)}function
|
|
1794
|
-
`);for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`),W.push(...
|
|
1795
|
-
`)}function
|
|
2036
|
+
`.trim();try{let{text:Q,usage:Z}=await n3({model:j,system:c3,prompt:A});this.logUsage(Z);let X=this.parseResponse(Q);return this.enrichSpec(X,$)}catch(Q){throw this.logger.error("Failed to generate tests",{error:Q}),Q}}parseResponse($){try{let W=$.replace(/```json\n?|\n?```/g,"");return JSON.parse(W)}catch(W){throw Error("Failed to parse AI response as JSON")}}enrichSpec($,W){let j={key:`${W.meta.key}.test`,version:W.meta.version??"0.0.1",owners:W.meta.owners??[]},A={type:"operation",operation:{key:W.meta.key,version:W.meta.version}};return{meta:j,target:A,fixtures:$.fixtures??[],scenarios:$.scenarios??[],coverage:$.coverage}}logUsage($){let W=$;this.logger.debug(`AI Usage: ${W.promptTokens} prompt + ${W.completionTokens} completion = ${W.totalTokens} total tokens`)}}import{OperationSpecRegistry as H9}from"@contractspec/lib.contracts-spec";import{TestRunner as V9}from"@contractspec/lib.contracts-spec/tests";import{resolve as oj}from"path";async function PI($,W){let j=new V9({registry:W}),A=[],Q=0,Z=0;for(let X of $){let Y=await j.run(X);A.push(Y),Q+=Y.passed,Z+=Y.failed}return{results:A,passed:Q,failed:Z}}async function kI($,W,j){let{logger:A}=j,Q;if(W.registry)Q=await o3(oj(W.registry));else Q=new H9,A.warn("No registry module provided. Scenarios that execute operations without handlers will fail.");let Z=new V9({registry:Q}),X=[],Y=!0;for(let B of $)try{let q=oj(B),H=await vW(q),V=G9(H);if(V.length===0){A.warn(`No TestSpec exports found in ${B}`);continue}for(let G of V){A.info(`Running ${G.meta.key}...`);let J=await Z.run(G);if(X.push(J),J.failed>0)Y=!1,A.error(`${G.meta.key} failed (${J.failed}/${J.scenarios.length})`);else A.info(`${G.meta.key} passed (${J.passed}/${J.scenarios.length})`)}}catch(q){A.error(`Failed to load/run spec ${B}: ${q instanceof Error?q.message:String(q)}`),Y=!1}return{results:X,passed:Y}}async function hI($,W){let j=[];for(let A of $)try{let Q=oj(A),Z=await vW(Q),X=G9(Z);j.push(...X)}catch(Q){W.logger.warn(`Failed to load tests from ${A}: ${Q instanceof Error?Q.message:String(Q)}`)}return j}function G9($){let W=[];for(let j of Object.values($))if(l3(j))W.push(j);return W}function l3($){return typeof $==="object"&&$!==null&&Array.isArray($.scenarios)&&!!$.meta?.key}async function o3($){return o4($,{description:"OperationSpecRegistry",isValue:(W)=>W instanceof H9,instanceKeys:["registry"],factoryKeys:["createRegistry","default"]})}import{scanSpecSource as C0}from"@contractspec/module.workspace";import{IndentationText as i3,Node as i$,Project as p3,QuoteKind as t3,SyntaxKind as a3}from"ts-morph";function s3($){return{specType:"unknown",filePath:$,hasMeta:!1,hasIo:!1,hasPolicy:!1,hasPayload:!1,hasContent:!1,hasDefinition:!1}}async function lI($,W,j={}){let{fs:A,logger:Q}=W;if(!await A.exists($))return{specPath:$,specInfo:s3($),updated:!1,errors:[`Spec file not found: ${$}`],warnings:[]};let X=await A.readFile($),Y;if(j.content!==void 0)Y=j.content;else if(j.fields?.length)Y=e3(X,j.fields);else return{specPath:$,specInfo:C0(X,$),updated:!1,errors:["No update provided: supply `content` or `fields`"],warnings:[]};if(!j.skipValidation){await A.writeFile($,Y);let B=await m$($,W);if(B.errors.length>0)return await A.writeFile($,X),{specPath:$,specInfo:C0(Y,$),updated:!1,errors:B.errors,warnings:B.warnings};if(B.warnings.length>0&&!j.allowWarnings)return await A.writeFile($,X),{specPath:$,specInfo:C0(Y,$),updated:!1,errors:["Validation produced warnings (use allowWarnings to override)"],warnings:B.warnings};return Q.info(`Updated spec: ${$}`),{specPath:$,specInfo:C0(Y,$),updated:!0,errors:[],warnings:B.warnings}}return await A.writeFile($,Y),Q.info(`Updated spec (validation skipped): ${$}`),{specPath:$,specInfo:C0(Y,$),updated:!0,errors:[],warnings:[]}}function e3($,W){let A=new p3({useInMemoryFileSystem:!0,manipulationSettings:{indentationText:i3.TwoSpaces,quoteKind:t3.Double}}).createSourceFile("spec.ts",$,{overwrite:!0}),Q=WB(A);if(!Q)return $;for(let Z of W)$B(Q,Z);return A.getFullText()}function $B($,W){let j=W.key.split(".").map((Y)=>Y.trim()).filter(Boolean);if(j.length===0)return;let A=$;for(let Y of j.slice(0,-1)){if(!A.getProperty(Y))A.addPropertyAssignment({name:Y,initializer:"{}"});let q=A.getPropertyOrThrow(Y);if(!i$.isPropertyAssignment(q))return;let H=q.getInitializer();if(!H||!i$.isObjectLiteralExpression(H))q.setInitializer("{}");let V=q.getInitializerIfKind(a3.ObjectLiteralExpression);if(!V)return;A=V}let Q=j[j.length-1];if(!Q)return;let Z=jB(W.value),X=A.getProperty(Q);if(X&&i$.isPropertyAssignment(X)){X.setInitializer(Z);return}A.addPropertyAssignment({name:Q,initializer:Z})}function WB($){for(let W of $.getVariableDeclarations()){let j=W.getInitializer();if(!j)continue;if(i$.isObjectLiteralExpression(j))return j;if(i$.isCallExpression(j)){let A=j.getArguments()[0];if(A&&i$.isObjectLiteralExpression(A))return A}}return}function jB($){try{return JSON.stringify(JSON.parse($),null,2)}catch{if(/^(true|false|null|-?\d+(\.\d+)?)$/.test($))return $;return JSON.stringify($)}}var R9={};h(R9,{getPackageUpgradeCommand:()=>O9,getDefaultVersioningConfig:()=>fW,getDefaultHooksConfig:()=>uW,applyGuidedUpgrade:()=>N9,applyConfigUpgrades:()=>L9,analyzeUpgrades:()=>gW,analyzeGuidedUpgrade:()=>tj});import{GeneratedReleaseManifestSchema as M9}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as VB,DEFAULT_CONTRACTSRC as GB}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";function J9($){return $.packages.map((W)=>{let j=W.version?`@${W.version}`:"";return`- ${W.name}${j} (${W.releaseType})`})}function b9($){return $.map((W)=>` - ${W}`)}function w9($){let W=[`### ${$.summary}`,`- Slug: ${$.slug}`,`- Date: ${$.date}`,`- Breaking: ${$.isBreaking?"yes":"no"}`,...J9($)];if($.deprecations.length>0)W.push("- Deprecations:"),W.push(...$.deprecations.map((j)=>` - ${j}`));return W.join(`
|
|
2037
|
+
`)}function AB($){let W=[`### ${$.summary}`,...J9($)];for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`);return W.join(`
|
|
2038
|
+
`)}function K9($){let W=[`### ${$.summary}`];if($.migrationInstructions.length===0)return W.push("- No manual migration steps recorded."),W.join(`
|
|
2039
|
+
`);for(let j of $.migrationInstructions)W.push(`- ${j.title}: ${j.summary}`),W.push(...b9(j.steps));return W.join(`
|
|
2040
|
+
`)}function ij($){return["# Patch Notes","",...$.releases.map(w9)].join(`
|
|
1796
2041
|
|
|
1797
|
-
`)}function
|
|
2042
|
+
`)}function pj($){return["# Customer Upgrade Guide","",...$.releases.map(K9)].join(`
|
|
1798
2043
|
|
|
1799
|
-
`)}function
|
|
2044
|
+
`)}function _9($){if($.steps.length===0)return"- No release-managed upgrade steps were found.";return $.steps.map((W)=>[`- [${W.level}] ${W.title}: ${W.summary}`,...b9(W.instructions)].join(`
|
|
1800
2045
|
`)).join(`
|
|
1801
|
-
`)}function
|
|
1802
|
-
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",j||"- No package version targets were inferred.","","Required steps:",
|
|
1803
|
-
`)}import{compareVersions as
|
|
1804
|
-
`),
|
|
1805
|
-
`),!0}async function
|
|
1806
|
-
`),!0}async function
|
|
1807
|
-
`),
|
|
2046
|
+
`)}function p$($,W){let j=W.targetPackages.map((A)=>`${A.name}: ${A.currentVersion??"unknown"} -> ${A.targetVersion??"latest"}`).join(`
|
|
2047
|
+
`);return[`Apply the ContractSpec upgrade plan in this workspace using ${$}.`,"","Target packages:",j||"- No package version targets were inferred.","","Required steps:",_9(W)].join(`
|
|
2048
|
+
`)}import{compareVersions as U9,countUpgradePlanStepLevels as QB,createAgentPromptBundles as ZB,dedupeUpgradePlanSteps as XB,sortReleaseManifest as z9}from"@contractspec/lib.contracts-spec";function YB($,W){if(W.length===0)return z9($);let j=new Map(W.map((A)=>[A.name,A.currentVersion??"0.0.0"]));return z9({...$,releases:$.releases.filter((A)=>A.packages.some((Q)=>{let Z=j.get(Q.name);if(!Z||!Q.version)return!1;return U9(Q.version,Z)===1}))})}function D0($,W,j,A){let Q=YB($,W),Z=BB(Q,W),X=XB(Q.flatMap((H)=>H.upgradeSteps)),Y=QB(X),B={generatedAt:new Date().toISOString(),targetPackages:Z,releases:Q,steps:X,autofixCount:Y.auto,manualCount:Y.manual,assistedCount:Y.assisted,agentPrompts:[]},q=ZB(B,j,A);return{...B,agentPrompts:q}}function BB($,W){let j=new Map(W.map((Q)=>[Q.name,Q.currentVersion])),A=new Map;for(let Q of $)for(let Z of Q.packages){let X=j.get(Z.name),Y=A.get(Z.name);if(!Y){A.set(Z.name,{name:Z.name,currentVersion:X,targetVersion:Z.version});continue}if(Z.version&&Y.targetVersion&&U9(Z.version,Y.targetVersion)===1)Y.targetVersion=Z.version}return Array.from(A.values()).sort((Q,Z)=>Q.name.localeCompare(Z.name))}async function gW($,W){let{fs:j,logger:A}=$,Q=f(W.workspaceRoot),Z=D(W.workspaceRoot),X=k$(Z);A.info("Analyzing available upgrades...",{workspaceRoot:Z,packageRoot:Q,packageManager:X});let Y=await qB(j,Q),B=await HB(j,Q,Z),q=Y.length>0||B.length>0;return{packageManager:X,packages:Y,configUpgrades:B,hasUpgrades:q}}async function qB($,W){let j=$.join(W,"package.json");if(!await $.exists(j))return[];try{let A=await $.readFile(j),Q=JSON.parse(A),Z=Q.dependencies??{},X=Q.devDependencies??{},Y=[],B={...Z,...X};for(let[q,H]of Object.entries(B))if(q.startsWith("@contractspec/")||q==="contractspec"||q.startsWith("@lssm/"))Y.push({name:q,currentVersion:H,isDevDependency:!!X[q]});return Y}catch{return[]}}async function HB($,W,j){let A=$.join(W,".contractsrc.json"),Q=Z0({configRoot:W,workspaceRoot:j});if(!await $.exists(A))return[];try{let Z=await $.readFile(A),X=JSON.parse(Z),Y=[],B=X.$schema;if(!B||B!==Q)Y.push({key:"$schema",currentValue:B,suggestedValue:Q,isNew:!B});if(!X.versioning)Y.push({key:"versioning",currentValue:void 0,suggestedValue:fW(),isNew:!0});else if(X.versioning.integrateWithChangesets===void 0)Y.push({key:"versioning.integrateWithChangesets",currentValue:void 0,suggestedValue:!1,isNew:!0});if(!X.hooks)Y.push({key:"hooks",currentValue:void 0,suggestedValue:uW(),isNew:!0});if(!X.release)Y.push({key:"release",currentValue:void 0,suggestedValue:S9(),isNew:!0});if(!X.upgrade)Y.push({key:"upgrade",currentValue:void 0,suggestedValue:I9(),isNew:!0});return Y}catch{return[]}}async function L9($,W){let{fs:j,logger:A}=$,Q=f(W.workspaceRoot),Z=D(W.workspaceRoot),X=Z0({configRoot:Q,workspaceRoot:Z});if(W.dryRun)A.info("Dry run - no changes will be made");let Y=j.join(Q,".contractsrc.json");if(!await j.exists(Y))return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:"No .contractsrc.json found",summary:"No configuration file to upgrade"};try{let B=await j.readFile(Y),q=JSON.parse(B),H=0,V=q.$schema;if(!V||V!==X)q.$schema=X,H++;if(!q.versioning)q.versioning=fW(),H++;else{let G=q.versioning;if(G.integrateWithChangesets===void 0)G.integrateWithChangesets=!1,H++}if(!q.hooks)q.hooks=uW(),H++;if(!q.release)q.release=S9(),H++;if(!q.upgrade)q.upgrade=I9(),H++;if(H===0)return{success:!0,packagesUpgraded:0,configSectionsUpgraded:0,summary:"Configuration is already up to date"};if(!W.dryRun)await j.writeFile(Y,JSON.stringify(q,null,2)+`
|
|
2049
|
+
`),A.info("Configuration upgraded",{sectionsUpgraded:H});return{success:!0,packagesUpgraded:0,configSectionsUpgraded:H,summary:W.dryRun?`Would upgrade ${H} config section(s)`:`Upgraded ${H} config section(s)`}}catch(B){let q=B instanceof Error?B.message:String(B);return{success:!1,packagesUpgraded:0,configSectionsUpgraded:0,error:q,summary:`Failed to upgrade config: ${q}`}}}function O9($,W,j){let A=j?W.map((Q)=>`${Q.name}@latest`).join(" "):W.map((Q)=>Q.name).join(" ");switch($){case"bun":return`bun add ${A}`;case"pnpm":return`pnpm add ${A}`;case"yarn":return`yarn add ${A}`;default:return`npm install ${A}`}}function fW(){return{autoBump:!1,bumpStrategy:"impact",changelogTiers:["spec","library","monorepo"],format:"keep-a-changelog",commitChanges:!1,createTags:!1,integrateWithChangesets:!0}}function uW(){return{"pre-commit":["contractspec validate","contractspec integrity check"]}}function S9(){return{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:["manifest.json","patch-notes.md","customer-guide.md","upgrade-manifest.json"],agentTargets:["codex"]}}function I9(){return{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0}}var JB="**/*.{ts,tsx,js,jsx,mjs,cjs}",E9=GB.upgrade??{manifestPaths:["generated/releases/upgrade-manifest.json"],defaultAgentTarget:"codex",enableInteractiveGuidance:!0,applyCodemods:!0};async function tj($,W){let{fs:j}=$,A=f(W.workspaceRoot),Q=D(W.workspaceRoot),Z=await wB(j,A,Q),X=await bB(j,A,Q,W.manifestPaths??Z.manifestPaths),Y=await gW($,{workspaceRoot:A,dryRun:W.dryRun}),B=[W.agentTarget??Z.defaultAgentTarget??"codex"],q=D0(X.manifest,Y.packages.map((V)=>({name:V.name,currentVersion:V.currentVersion})),B,p$),H=KB(q,Y.packages,Y.configUpgrades);return{packageManager:Y.packageManager,manifestPath:X.path,plan:H,humanChecklist:_B(H)}}async function N9($,W){let{fs:j,logger:A}=$,Q=f(W.workspaceRoot),Z=await tj($,W),X=[];if(!W.dryRun){for(let B of Z.plan.steps){if(B.level!=="auto")continue;for(let q of B.autofixes??[])if(await zB(j,Q,q))X.push(q.id)}A.info("Applied guided upgrade autofixes",{count:X.length,workspaceRoot:Q})}let Y=Z.plan.steps.filter((B)=>B.level!=="auto");return{success:!0,packagesUpgraded:X.filter((B)=>B.startsWith("pkg:")).length,configSectionsUpgraded:X.filter((B)=>B.startsWith("config:")).length,summary:W.dryRun?`Would apply ${Z.plan.autofixCount} deterministic upgrade step(s)`:`Applied ${X.length} deterministic upgrade autofix(es)`,appliedAutofixes:X,remainingSteps:Y,humanChecklist:Z.humanChecklist,promptBundle:Z.plan.agentPrompts[0],plan:Z.plan,manifestPath:Z.manifestPath}}async function bB($,W,j,A){let Q=A??["generated/releases/upgrade-manifest.json"],Z=Array.from(new Set([W,j]));for(let X of Q){let Y=X.startsWith("/")?[X]:Z.map((B)=>$.join(B,X));for(let B of Y){if(!await $.exists(B))continue;let q=M9.parse(JSON.parse(await $.readFile(B)));return{path:B,manifest:q}}}return{manifest:M9.parse({generatedAt:new Date().toISOString(),releases:[]})}}async function wB($,W,j){for(let A of Array.from(new Set([$.join(W,".contractsrc.json"),$.join(j,".contractsrc.json")]))){if(!await $.exists(A))continue;try{let Q=JSON.parse(await $.readFile(A)),Z=VB.safeParse(Q);if(Z.success)return{...E9,...Z.data.upgrade}}catch{continue}}return E9}function KB($,W,j){let A=[];for(let H of W){let V=$.targetPackages.find((G)=>G.name===H.name);if(!V?.targetVersion||V.targetVersion===H.currentVersion)continue;A.push({id:`pkg:${H.name}`,kind:"package-json",title:`Update ${H.name}`,summary:`Update ${H.name} to ${V.targetVersion}`,packageName:H.name,dependencyType:H.isDevDependency?"devDependencies":"dependencies",from:H.currentVersion,to:V.targetVersion})}let Q=j.map((H)=>({id:`config:${H.key}`,kind:"contractsrc",title:`Update ${H.key}`,summary:`Update .contractsrc.json at ${H.key}`,configPath:H.key,value:H.suggestedValue})),Z=[];if(A.length>0)Z.push({id:"upgrade-contractspec-packages",title:"Update ContractSpec packages",summary:"Apply package version upgrades from the release manifest.",level:"auto",instructions:A.map((H)=>`${H.packageName}: ${H.from??"current"} -> ${H.to??"latest"}`),packages:A.map((H)=>H.packageName??""),autofixes:A});if(Q.length>0)Z.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:Q.map((H)=>`${H.configPath} -> updated`),autofixes:Q});let X=[...Z,...$.steps],Y=X.filter((H)=>H.level==="auto").length,B=X.filter((H)=>H.level==="assisted").length,q=X.filter((H)=>H.level==="manual").length;return{...$,steps:X,autofixCount:Y,assistedCount:B,manualCount:q,agentPrompts:D0({generatedAt:$.generatedAt,releases:$.releases},$.targetPackages.map((H)=>({name:H.name,currentVersion:H.currentVersion})),$.agentPrompts.map((H)=>H.agent),p$).agentPrompts}}function _B($){return $.steps.map((W)=>`${W.title}: ${W.summary}`)}async function zB($,W,j){switch(j.kind){case"package-json":return UB($,W,j);case"contractsrc":return LB($,W,j);case"import-rewrite":return OB($,W,j);case"codemod":return!1}}async function UB($,W,j){let A=$.join(W,"package.json");if(!await $.exists(A))return!1;let Q=JSON.parse(await $.readFile(A)),Z=j.dependencyType??"dependencies",X=Q[Z]??{};if(!j.packageName||!j.to||!X[j.packageName])return!1;return X[j.packageName]=j.to,Q[Z]=X,await $.writeFile(A,JSON.stringify(Q,null,2)+`
|
|
2050
|
+
`),!0}async function LB($,W,j){let A=$.join(W,".contractsrc.json"),Q=await $.exists(A)?JSON.parse(await $.readFile(A)):{};if(!j.configPath)return!1;return SB(Q,j.configPath,j.value),await $.writeFile(A,JSON.stringify(Q,null,2)+`
|
|
2051
|
+
`),!0}async function OB($,W,j){if(!j.from||!j.to)return!1;let A=await $.glob({pattern:j.path??JB,cwd:W,absolute:!0}),Q=!1;for(let Z of A){let X=await $.readFile(Z);if(!X.includes(j.from))continue;await $.writeFile(Z,X.split(j.from).join(j.to)),Q=!0}return Q}function SB($,W,j){let A=W.split("."),Q=$;for(let X of A.slice(0,-1)){let Y=Q[X];if(!Y||typeof Y!=="object"||Array.isArray(Y))Q[X]={};Q=Q[X]}let Z=A.at(-1);if(Z)Q[Z]=j}import{existsSync as aj,mkdirSync as IB,readFileSync as MB,renameSync as EB,statSync as NB,writeFileSync as RB}from"fs";import{dirname as CB,join as DB}from"path";var TB=".contractspec/verification-cache.json",C9=1;class D9{filePath;cache;isDirty=!1;constructor($,W){let j=W??process.cwd();this.filePath=$??DB(j,TB),this.cache=new Map,this.loadSync()}loadSync(){try{if(!aj(this.filePath))return;let $=MB(this.filePath,"utf-8"),W=JSON.parse($);if(W.version!==C9)return;for(let[j,A]of Object.entries(W.entries))this.cache.set(j,A)}catch{}}saveSync(){if(!this.isDirty)return;try{let $=CB(this.filePath);if(!aj($))IB($,{recursive:!0});let W={version:C9,entries:Object.fromEntries(this.cache.entries())},j=`${this.filePath}.tmp`;RB(j,JSON.stringify(W,null,2),"utf-8"),EB(j,this.filePath),this.isDirty=!1}catch{}}async get($){return this.cache.get($)??null}async set($,W){this.cache.set($,W),this.isDirty=!0,this.saveSync()}async delete($){let W=this.cache.delete($);if(W)this.isDirty=!0,this.saveSync();return W}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(aj(this.filePath))$=NB(this.filePath).size}catch{}return{entryCount:this.cache.size,memoryUsage:$}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}}function GM($,W){return new D9($,W)}class T9{cache=new Map;async get($){return this.cache.get($)??null}async set($,W){this.cache.set($,W)}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[W,j]of this.cache.entries())$+=W.length*2,$+=JSON.stringify(j).length*2;return{entryCount:this.cache.size,memoryUsage:$}}}function bM(){return new T9}class F9{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 W=this.getStorageKey($);return this.store.get(W)??null}async set($,W){let j=this.getStorageKey($);if(await this.store.update(j,W),!this.keyIndex.has($))this.keyIndex.add($),await this.saveKeyIndex()}async delete($){let W=this.getStorageKey($),j=this.keyIndex.has($);if(j)await this.store.update(W,void 0),this.keyIndex.delete($),await this.saveKeyIndex();return j}async has($){return this.keyIndex.has($)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let $ of this.keyIndex){let W=this.getStorageKey($);await this.store.update(W,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}}function KM($){return new F9($)}import{createHash as FB}from"crypto";var x9={maxEntries:1000,defaultTtlMs:86400000,structureTtlMs:604800000,behaviorTtlMs:86400000,aiTtlMs:86400000,transitiveInvalidation:!0};function y9($){return FB("sha256").update($).digest("hex")}function v9($){let W=[`spec:${$.specHash.substring(0,16)}`,`impl:${$.implHash.substring(0,16)}`,`tier:${$.tier}`];if($.aiModelVersion)W.push(`model:${$.aiModelVersion}`);return W.join("|")}function xB($){try{let W=$.split("|"),j=new Map;for(let X of W){let[Y,B]=X.split(":");if(Y&&B)j.set(Y,B)}let A=j.get("spec"),Q=j.get("impl"),Z=j.get("tier");if(!A||!Q||!Z)return null;return{specHash:A,implHash:Q,tier:Z,aiModelVersion:j.get("model")}}catch{return null}}function yB($,W){switch($){case"structure":return W.structureTtlMs;case"behavior":return W.behaviorTtlMs;case"ai_review":return W.aiTtlMs;default:return W.defaultTtlMs}}class m9{storage;config;stats;constructor($,W={}){this.storage=$,this.config={...x9,...W},this.stats={hits:0,misses:0}}createKey($,W,j,A){return{specHash:y9($),implHash:y9(W),tier:j,aiModelVersion:j==="ai_review"?A:void 0}}async lookup($){let W=v9($),j=await this.storage.get(W);if(!j)return this.stats.misses++,{hit:!1,reason:"not_found"};if(j.meta.expiresAt){let A=new Date(j.meta.expiresAt).getTime();if(Date.now()>A)return this.stats.misses++,await this.storage.delete(W),{hit:!1,reason:"expired"}}if(j.key.specHash!==$.specHash)return this.stats.misses++,{hit:!1,reason:"spec_changed"};if(j.key.implHash!==$.implHash)return this.stats.misses++,{hit:!1,reason:"impl_changed"};if($.tier==="ai_review"&&$.aiModelVersion&&j.key.aiModelVersion!==$.aiModelVersion)return this.stats.misses++,{hit:!1,reason:"model_changed"};return this.stats.hits++,{hit:!0,entry:j}}async store($,W,j={}){let A=v9($),Q=yB($.tier,this.config),Z={key:$,result:W,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Q).toISOString(),dependencies:j.dependencies??[],specName:j.specName,implPath:j.implPath}};await this.storage.set(A,Z),await this.pruneIfNeeded()}async invalidateForFile($){if(!this.config.transitiveInvalidation)return 0;let W=await this.storage.keys(),j=0;for(let A of W){let Q=await this.storage.get(A);if(!Q)continue;if(Q.meta.dependencies.includes($))await this.storage.delete(A),j++;if(Q.meta.specName===$||Q.meta.implPath===$)await this.storage.delete(A),j++}return j}async invalidateForSpec($){let W=await this.storage.keys(),j=0;for(let A of W){let Q=xB(A);if(Q&&Q.specHash.startsWith($.substring(0,16)))await this.storage.delete(A),j++}return j}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 W=[];for(let A of $){let Q=await this.storage.get(A);if(Q)W.push({key:A,createdAt:new Date(Q.meta.createdAt).getTime()})}W.sort((A,Q)=>A.createdAt-Q.createdAt);let j=W.length-this.config.maxEntries;for(let A=0;A<j;A++){let Q=W[A];if(Q)await this.storage.delete(Q.key)}}}function EM($,W){return new m9($,W)}import{generateVerificationPrompt as vB}from"@contractspec/lib.contracts-spec/llm";function mB($){let W=$.match(/```json\n?([\s\S]*?)\n?```/);if(W?.[1])try{let B=JSON.parse(W[1]);return{compliant:B.passed??!1,confidence:(B.score??0)/100,findings:(B.issues??[]).map((q)=>({category:String(q.category??"semantic"),severity:String(q.severity??"warning"),message:String(q.message??""),location:q.location?String(q.location):void 0,suggestion:q.suggestion?String(q.suggestion):void 0})),rawResponse:$}}catch{}let j=[],A=$.split(`
|
|
2052
|
+
`),Q="info";for(let B of A){let q=B.toLowerCase();if(q.includes("error")||q.includes("critical"))Q="error";else if(q.includes("warning")||q.includes("should"))Q="warning";else if(q.includes("info")||q.includes("note"))Q="info";let H=B.match(/^[-*•]\s*(.+)$/),V=B.match(/^\d+\.\s*(.+)$/);if(H||V){let G=H?.[1]??V?.[1]??"";if(G.length>10)j.push({category:"semantic",severity:Q,message:G})}}let Z=j.some((B)=>B.severity==="error"),X=!Z,Y=Z?0.3:j.length===0?0.9:0.7;return{compliant:X,confidence:Y,findings:j,rawResponse:$}}async function P9($,W){if(!W.aiApiKey)return`\`\`\`json
|
|
1808
2053
|
{
|
|
1809
2054
|
"passed": true,
|
|
1810
2055
|
"score": 50,
|
|
@@ -1821,7 +2066,7 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
1821
2066
|
],
|
|
1822
2067
|
"summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
|
|
1823
2068
|
}
|
|
1824
|
-
\`\`\``;try{let j=W.aiProvider??"anthropic";if(j==="anthropic"){let{anthropic:
|
|
2069
|
+
\`\`\``;try{let j=W.aiProvider??"anthropic";if(j==="anthropic"){let{anthropic:A}=await import("@ai-sdk/anthropic"),{generateText:Q}=await import("ai");return(await Q({model:A("claude-3-5-sonnet-20241022"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}else if(j==="openai"){let{openai:A}=await import("@ai-sdk/openai"),{generateText:Q}=await import("ai");return(await Q({model:A("gpt-4o"),prompt:$,system:"You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON."})).text}throw Error(`Unknown AI provider: ${j}`)}catch(j){return`\`\`\`json
|
|
1825
2070
|
{
|
|
1826
2071
|
"passed": false,
|
|
1827
2072
|
"score": 0,
|
|
@@ -1830,7 +2075,7 @@ Do not include markdown formatting or explanations, just the JSON.
|
|
|
1830
2075
|
],
|
|
1831
2076
|
"summary": "AI verification encountered an error"
|
|
1832
2077
|
}
|
|
1833
|
-
\`\`\``}}async function
|
|
2078
|
+
\`\`\``}}async function T0($,W={}){let{spec:j,implementationCode:A,implementationPath:Q}=$,Z=Date.now(),X=vB(j,A),Y=await P9(X.taskPrompt,W),B=mB(Y),q=B.findings.map((J)=>({severity:J.severity,category:"semantic",message:J.message,location:J.location?{file:J.location}:Q?{file:Q}:void 0,suggestion:J.suggestion})),H=Math.round(B.confidence*100),V=B.compliant,G=B.findings.filter((J)=>J.suggestion).map((J)=>J.suggestion);return{tier:"ai_review",passed:V,score:H,issues:q,suggestions:G,coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:V?1:0}},meta:{specName:j.meta.key,specVersion:j.meta.version,implementationPath:Q??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Z}}}function dW($){let{spec:W,implementationCode:j,implementationPath:A}=$,Q=Date.now(),Z=[];if(j.includes("console.log"))Z.push({severity:"warning",category:"semantic",message:"Console.log statements found - consider using proper logging",suggestion:"Use a structured logger instead of console.log"});if(j.includes("// TODO")||j.includes("// FIXME"))Z.push({severity:"info",category:"semantic",message:"TODO/FIXME comments found - implementation may be incomplete",suggestion:"Address TODO items before finalizing implementation"});if(W.policy.auth!=="anonymous"&&!j.includes("auth"))Z.push({severity:"warning",category:"semantic",message:`Spec requires ${W.policy.auth} auth but no auth check found`,suggestion:"Add authentication check at the handler entry point"});let X=Z.filter((B)=>B.severity==="error").length===0?80:40,Y=Z.filter((B)=>B.severity==="error").length===0;return{tier:"ai_review",passed:Y,score:X,issues:Z,suggestions:Z.filter((B)=>B.suggestion).map((B)=>B.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:Y?1:0}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Q}}}function PB($,W){return`You are analyzing a code implementation against its specification.
|
|
1834
2079
|
|
|
1835
2080
|
## Spec Schema Fields
|
|
1836
2081
|
${$}
|
|
@@ -1877,42 +2122,42 @@ Match types:
|
|
|
1877
2122
|
- "compatible": Semantically similar (e.g., "email" vs "emailAddress")
|
|
1878
2123
|
- "mismatch": Different meaning despite similar naming
|
|
1879
2124
|
- "missing": Spec field not found in implementation
|
|
1880
|
-
`}function
|
|
1881
|
-
`)}function
|
|
1882
|
-
`),
|
|
1883
|
-
`)}configure($){this.config={...this.config,...$}}generateSummary($,W){let j=[],
|
|
1884
|
-
`)}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
|
|
1885
|
-
`)}function
|
|
1886
|
-
`)}function
|
|
1887
|
-
`),j=W[0]?.trim();if(!j)return null;let
|
|
1888
|
-
`).trim()||void 0,
|
|
1889
|
-
${W.map((
|
|
2125
|
+
`}function kB($){let W=[],j=(A,Q)=>{try{let X=A?._def?.shape;if(X&&typeof X==="function"){let Y=X();for(let[B,q]of Object.entries(Y)){let V=q?._def?.typeName??"unknown";W.push(`- ${B}: ${String(V).replace("Zod","").toLowerCase()} (${Q})`)}}}catch{W.push(`- [unable to extract ${Q} fields]`)}};if($.io.input)j($.io.input,"input");if($.io.output&&!("resourceRef"in $.io.output))j($.io.output,"output");if(W.length===0)return"- [no schema fields could be extracted]";return W.join(`
|
|
2126
|
+
`)}function hB($){let W=$.match(/```json\n?([\s\S]*?)\n?```/);if(W?.[1])try{let j=JSON.parse(W[1]);return{fieldMappings:(j.fieldMappings??[]).map((A)=>({specField:String(A.specField??""),specType:String(A.specType??"unknown"),implementationField:A.implementationField?String(A.implementationField):void 0,implementationType:A.implementationType?String(A.implementationType):void 0,match:A.match??"missing",aiConfidence:typeof A.aiConfidence==="number"?A.aiConfidence:0.5,suggestion:A.suggestion?String(A.suggestion):void 0})),intentAlignment:{score:typeof j.intentAlignment?.score==="number"?j.intentAlignment.score:50,issues:Array.isArray(j.intentAlignment?.issues)?j.intentAlignment.issues:[],suggestions:Array.isArray(j.intentAlignment?.suggestions)?j.intentAlignment.suggestions:[]},semanticIssues:(j.semanticIssues??[]).map((A)=>({category:String(A.category??"semantic"),severity:A.severity??"warning",message:String(A.message??""),suggestion:A.suggestion?String(A.suggestion):void 0})),rawResponse:$}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:["Unable to parse AI response for semantic analysis"],suggestions:[]},semanticIssues:[],rawResponse:$}}async function k9($,W={}){let{spec:j,implementationCode:A}=$,Q=kB(j),Z=PB(Q,A),X=await P9(Z,W);return hB(X)}async function gB($,W={}){let{spec:j,implementationCode:A,implementationPath:Q}=$,Z=Date.now(),X=await T0($,W),Y;if(W.aiApiKey)try{Y=await k9($,W)}catch{}if(Y){let B=[];for(let G of Y.fieldMappings)if(G.match==="missing")B.push({severity:"error",category:"semantic",message:`Missing field: '${G.specField}' (${G.specType}) not found in implementation`,suggestion:G.suggestion??`Add field '${G.specField}' to implementation`});else if(G.match==="mismatch")B.push({severity:"warning",category:"semantic",message:`Field mismatch: '${G.specField}' has incorrect implementation as '${G.implementationField}'`,suggestion:G.suggestion});else if(G.match==="compatible"&&G.aiConfidence<0.8)B.push({severity:"info",category:"semantic",message:`Field naming: '${G.specField}' implemented as '${G.implementationField}' (compatible but not exact)`,suggestion:G.suggestion});for(let G of Y.intentAlignment.issues)B.push({severity:"warning",category:"semantic",message:G});for(let G of Y.semanticIssues)B.push({severity:G.severity,category:"semantic",message:G.message,suggestion:G.suggestion});X.issues=[...X.issues,...B];let q=Y.fieldMappings.length,H=Y.fieldMappings.filter((G)=>G.match==="exact"||G.match==="compatible").length;if(q>0){let G=Math.round(H/q*100);X.score=Math.round((X.score+G)/2),X.coverage.fields={total:q,implemented:H}}if(B.some((G)=>G.severity==="error"))X.passed=!1;X.suggestions=[...X.suggestions,...Y.intentAlignment.suggestions]}return X.meta={...X.meta,duration:Date.now()-Z},X}import{isEmitDeclRef as fB}from"@contractspec/lib.contracts-spec/operations";function uB($,W){let j=[...W.given,...W.when,...W.then].flatMap((q)=>q.toLowerCase().split(/\s+/).filter((H)=>H.length>3)),A=$.toLowerCase(),Q=j.filter((q)=>A.includes(q)),Z=j.length>0?Q.length/j.length:0,X=W.key.toLowerCase().replace(/\s+/g,""),Y=A.includes(X)||A.includes(`test('${W.key.toLowerCase()}'`)||A.includes(`it('${W.key.toLowerCase()}'`)||A.includes(`describe('${W.key.toLowerCase()}'`),B=Z>=0.3||Y;return{name:W.key,type:"scenario",passed:B,expected:`Given: ${W.given.join("; ")}; When: ${W.when.join("; ")}; Then: ${W.then.join("; ")}`,details:B?void 0:`Scenario keywords not found in implementation (${Math.round(Z*100)}% coverage)`}}function dB($,W){let j=JSON.stringify(W.input),A=JSON.stringify(W.output),Q=h9(W.input),Z=h9(W.output),X=$.toLowerCase(),Y=Q.filter((J)=>X.includes(J.toLowerCase())),B=Z.filter((J)=>X.includes(J.toLowerCase())),q=Q.length>0?Y.length/Q.length:1,H=Z.length>0?B.length/Z.length:1,V=(q+H)/2,G=V>=0.2;return{name:W.key,type:"example",passed:G,expected:`Input: ${j.slice(0,100)}...; Output: ${A.slice(0,100)}...`,details:G?void 0:`Example values not found in implementation (${Math.round(V*100)}% coverage)`}}function h9($){let W=[];function j(A){if(typeof A==="string"&&A.length>2)W.push(A);else if(Array.isArray(A))A.forEach(j);else if(A&&typeof A==="object")Object.values(A).forEach(j)}return j($),W}function nB($,W,j){let A=$.includes(W),Q=j.http?$.includes(String(j.http)):!0,Z=j.when.toLowerCase().split(/\s+/).filter((H)=>H.length>3),X=$.toLowerCase(),Y=Z.filter((H)=>X.includes(H)),B=Z.length>0?Y.length/Z.length:1,q=A&&(Q||B>=0.3);return{name:`Error: ${W}`,type:"error",passed:q,expected:`When: ${j.when}; Return: ${W} (HTTP ${j.http??400})`,details:q?void 0:!A?`Error code '${W}' not found in implementation`:"Error condition not properly implemented"}}function cB($,W){let j=W.sideEffects?.emits??[],A=[];for(let Q of j){let Z=fB(Q)?Q.ref.key:Q.key,X=Q.when,Y=X.toLowerCase().split(/\s+/).filter((G)=>G.length>3),B=$.toLowerCase(),q=B.includes(Z.toLowerCase()),H=Y.filter((G)=>B.includes(G)),V=Y.length>0?H.length/Y.length:1;A.push({name:`Event: ${Z}`,type:"scenario",passed:q&&V>=0.3,expected:`Emit ${Z} when: ${X}`,details:!q?`Event '${Z}' not found`:V<0.3?"Event condition not properly implemented":void 0})}return A}function rB($,W){if(W.policy.idempotent===void 0)return null;if(!W.policy.idempotent)return null;let j=["idempotency","idempotent","already exists","upsert","on conflict","if not exists","dedupe","duplicate"],A=$.toLowerCase(),Q=j.some((Z)=>A.includes(Z));return{name:"Idempotency",type:"scenario",passed:Q,expected:"Operation should be idempotent (safe to retry)",details:Q?void 0:"No idempotency pattern found for idempotent operation"}}function nW($){let{spec:W,implementationCode:j,implementationPath:A}=$,Q=Date.now(),Z=[];for(let b of W.acceptance?.scenarios??[])Z.push(uB(j,b));for(let b of W.acceptance?.examples??[])Z.push(dB(j,b));for(let[b,w]of Object.entries(W.io.errors??{}))Z.push(nB(j,b,w));Z.push(...cB(j,W));let X=rB(j,W);if(X)Z.push(X);let Y=Z.filter((b)=>!b.passed).map((b)=>({severity:b.type==="error"?"error":"warning",category:b.type==="scenario"?"scenario":b.type==="example"?"scenario":"error_handling",message:b.details??`${b.type} not covered: ${b.name}`,location:A?{file:A}:void 0,suggestion:b.expected?`Expected: ${b.expected}`:void 0})),B=Z.filter((b)=>b.type==="scenario"),q=Z.filter((b)=>b.type==="error"),H=Z.filter((b)=>b.passed).length,V=Z.length>0?Math.round(H/Z.length*100):100,G=Y.filter((b)=>b.severity==="error").length===0,J=Z.filter((b)=>!b.passed&&b.expected).map((b)=>`${b.name}: ${b.expected}`);return{tier:"behavior",passed:G,score:V,issues:Y,suggestions:J,coverage:{scenarios:{total:B.length,covered:B.filter((b)=>b.passed).length},errors:{total:q.length,handled:q.filter((b)=>b.passed).length},fields:{total:Z.length,implemented:H}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Q}}}import{isEmitDeclRef as lB}from"@contractspec/lib.contracts-spec/operations";function oB($){let W=/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:W,details:W?void 0:"No exported handler function found",suggestion:"Export a function that handles the operation: export async function handle(...) { }"}}function iB($){if(!$)return!1;let W=$.replace(/\\/g,"/");return W.includes("/packages/libs/contracts-spec/src/")||W.includes("/packages/libs/contracts-integrations/src/")||W.includes("/packages/libs/contracts-runtime-")}function pB($,W){if(iB(W))return{name:"contracts_import",passed:!0};let j=$.includes("from '@contractspec/lib.contracts-spec'")||$.includes('from "@contractspec/lib.contracts-spec"');return{name:"contracts_import",passed:j,details:j?void 0:"Missing import from @contractspec/lib.contracts-spec",suggestion:"Add: import { ... } from '@contractspec/lib.contracts-spec';"}}function tB($,W){if(!(W.io.input!==null||W.io.output!==null))return{name:"schema_import",passed:!0};let A=$.includes("from '@contractspec/lib.schema'")||$.includes('from "@contractspec/lib.schema"');return{name:"schema_import",passed:A,details:A?void 0:"Missing import from @contractspec/lib.schema",suggestion:"Add: import { ... } from '@contractspec/lib.schema';"}}function aB($){let W=/:\s*any\b|as\s+any\b|<any>/,j=$.split(`
|
|
2127
|
+
`),A=[];for(let Q=0;Q<j.length;Q++){let Z=j[Q]??"";if(Z.trim().startsWith("//")||Z.trim().startsWith("*"))continue;if(W.test(Z))A.push(Q+1)}return{name:"no_any_type",passed:A.length===0,details:A.length>0?`Found 'any' type on lines: ${A.slice(0,5).join(", ")}${A.length>5?"...":""}`:void 0,suggestion:"Replace any with proper types from the spec schema"}}function sB($,W){let j=W.io.errors;if(!j||Object.keys(j).length===0)return{name:"error_handling",passed:!0};let A=Object.keys(j),Q=[];for(let Z of A)if(!$.includes(Z))Q.push(Z);return{name:"error_handling",passed:Q.length===0,details:Q.length>0?`Missing error handling for: ${Q.join(", ")}`:void 0,suggestion:"Implement handlers for all error cases defined in the spec"}}function eB($,W){let j=W.sideEffects?.emits;if(!j||j.length===0)return{name:"event_emission",passed:!0};let A=$.includes("emit(")||$.includes(".emit(")||$.includes("publish(")||$.includes(".publish(")||$.includes("dispatchEvent")||$.includes("eventBus"),Q=j.map((X)=>{if(lB(X))return X.ref.key;return X.key}),Z=Q.filter((X)=>$.includes(X));return{name:"event_emission",passed:A&&Z.length>0,details:!A?"No event emission pattern found":Z.length===0?`Events not referenced: ${Q.join(", ")}`:void 0,suggestion:"Emit events as specified in sideEffects.emits"}}function $q($,W){if(!W.io.input)return{name:"input_validation",passed:!0};let j=$.includes(".parse(")||$.includes(".safeParse(")||$.includes("validate(")||$.includes(".validate(")||$.includes("schema.")||$.includes("zodSchema")||$.includes(".getZod()");return{name:"input_validation",passed:j,details:j?void 0:"No input validation pattern found",suggestion:"Validate input using the schema: schema.parse(input) or schema.safeParse(input)"}}function Wq($,W){let j=/export\s+(const\s+\w+\s*=\s*)?async/.test($)||/async\s+function/.test($);if(W.meta.kind!=="command")return{name:"async_patterns",passed:!0};return{name:"async_patterns",passed:j,details:j?void 0:"Handler should be async for command operations",suggestion:"Make the handler function async: export async function handle(...)"}}function F0($){let{spec:W,implementationCode:j,implementationPath:A}=$,Q=Date.now(),Z=[oB(j),pB(j,A),tB(j,W),aB(j),sB(j,W),eB(j,W),$q(j,W),Wq(j,W)],X=Z.filter((J)=>!J.passed).map((J)=>({severity:J.name==="no_any_type"?"warning":"error",category:J.name.includes("import")?"import":J.name.includes("export")?"export":"type",message:J.details??`Check failed: ${J.name}`,location:A?{file:A}:void 0,suggestion:J.suggestion})),Y=Z.filter((J)=>J.passed).length,B=Math.round(Y/Z.length*100),q=X.filter((J)=>J.severity==="error").length===0,H=Z.filter((J)=>!J.passed&&J.suggestion).map((J)=>J.suggestion),V=Object.keys(W.io.errors??{}).length,G=Z.find((J)=>J.name==="error_handling")?.passed?V:0;return{tier:"structure",passed:q,score:B,issues:X,suggestions:H,coverage:{scenarios:{total:0,covered:0},errors:{total:V,handled:G},fields:{total:Z.length,implemented:Y}},meta:{specName:W.meta.key,specVersion:W.meta.version,implementationPath:A??"unknown",verifiedAt:new Date().toISOString(),duration:Date.now()-Q}}}var jq={verbose:!1},Aq=["structure","behavior","ai_review"];class cW{config;constructor($={}){this.config={...jq,...$}}async verify($,W,j={}){let A=Date.now(),Q=new Map,Z=[],X={spec:$,implementationCode:W},Y=j.tiers??["structure","behavior"];for(let G of Aq){if(!Y.includes(G))continue;let J;switch(G){case"structure":J=F0(X);break;case"behavior":J=nW(X);break;case"ai_review":if(this.config.aiApiKey)J=await T0(X,this.config);else J=dW(X);break;default:continue}if(Q.set(G,J),Z.push(...J.issues),j.failFast&&!J.passed)break}let B=Array.from(Q.values()),q=B.every((G)=>G.passed),H=B.length>0?Math.round(B.reduce((G,J)=>G+J.score,0)/B.length):100,V=this.generateSummary(B,Z);return{passed:q,score:H,reports:Q,allIssues:Z,summary:V,duration:Date.now()-A}}verifyStructure($,W,j){return F0({spec:$,implementationCode:W,implementationPath:j})}verifyBehavior($,W,j){return nW({spec:$,implementationCode:W,implementationPath:j})}async verifyAI($,W,j){let A={spec:$,implementationCode:W,implementationPath:j};if(this.config.aiApiKey)return T0(A,this.config);return dW(A)}quickVerify($,W){return F0({spec:$,implementationCode:W})}formatAsMarkdown($){let W=[];W.push("# Verification Report"),W.push(""),W.push(`**Status:** ${$.passed?"✓ Passed":"✗ Failed"}`),W.push(`**Score:** ${$.score}/100`),W.push(`**Duration:** ${$.duration}ms`),W.push("");for(let[A,Q]of $.reports){if(W.push(`## ${this.formatTierName(A)}`),W.push(""),W.push(`**Status:** ${Q.passed?"✓ Passed":"✗ Failed"}`),W.push(`**Score:** ${Q.score}/100`),W.push(""),Q.issues.length>0){W.push("### Issues"),W.push("");for(let Z of Q.issues){let X=Z.severity==="error"?"❌":Z.severity==="warning"?"⚠️":"ℹ️";if(W.push(`${X} **${Z.category}**: ${Z.message}`),Z.suggestion)W.push(` - Suggestion: ${Z.suggestion}`)}W.push("")}if(Q.coverage.scenarios.total>0)W.push(`**Scenarios:** ${Q.coverage.scenarios.covered}/${Q.coverage.scenarios.total}`);if(Q.coverage.errors.total>0)W.push(`**Errors handled:** ${Q.coverage.errors.handled}/${Q.coverage.errors.total}`);W.push("")}let j=Array.from($.reports.values()).flatMap((A)=>A.suggestions);if(j.length>0){W.push("## Suggestions"),W.push("");for(let A of j.slice(0,10))W.push(`- ${A}`);if(j.length>10)W.push(`- ... and ${j.length-10} more`);W.push("")}return W.join(`
|
|
2128
|
+
`)}configure($){this.config={...this.config,...$}}generateSummary($,W){let j=[],A=$.every((B)=>B.passed),Q=$.length>0?Math.round($.reduce((B,q)=>B+q.score,0)/$.length):100;j.push(A?"✓ Verification passed":"✗ Verification failed"),j.push(`Score: ${Q}/100`),j.push("");for(let B of $){let q=B.passed?"✓":"✗";j.push(`${q} ${B.tier}: ${B.score}/100`)}j.push("");let Z=W.filter((B)=>B.severity==="error"),X=W.filter((B)=>B.severity==="warning"),Y=W.filter((B)=>B.severity==="info");if(Z.length>0)j.push(`Errors: ${Z.length}`);if(X.length>0)j.push(`Warnings: ${X.length}`);if(Y.length>0)j.push(`Info: ${Y.length}`);return j.join(`
|
|
2129
|
+
`)}formatTierName($){switch($){case"structure":return"Tier 1: Structure";case"behavior":return"Tier 2: Behavior";case"ai_review":return"Tier 3: AI Review";default:return $}}}function Qq($){return new cW($)}var Zq=new cW;var QA={};h(QA,{renderUpgradePrompt:()=>p$,renderUpgradeChecklist:()=>_9,renderPatchNotes:()=>ij,renderMigrationGuide:()=>K9,renderMaintainerSummary:()=>w9,renderCustomerPatchNote:()=>AB,renderCustomerGuide:()=>pj,parseConventionalCommit:()=>oW,isConventionalCommit:()=>Gq,initReleaseArtifacts:()=>$A,getHighestBumpType:()=>ej,getBumpTypeFromCommit:()=>sj,generateChangelogs:()=>s9,formatKeepAChangelog:()=>x0,formatConventionalChangelog:()=>f9,formatChangelogJson:()=>rW,filterCommitsByScope:()=>Jq,filterBumpableCommits:()=>bq,commitsToChangeEntries:()=>$5,commitToChangeEntry:()=>d9,checkReleaseArtifacts:()=>jA,buildReleaseArtifacts:()=>WA,applyVersionBump:()=>a9,analyzeVersionsFromCommits:()=>pW,analyzeVersions:()=>y0,DEFAULT_COMMIT_TYPE_MAP:()=>lW});import{basename as Xq,dirname as Yq}from"node:path";function x0($){let W=["# 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).",""],j=[...$].sort((A,Q)=>u9(A.version,Q.version));for(let A of j){W.push(`## [${A.version}] - ${A.date}`),W.push("");let Q=A.changes.filter((V)=>V.type==="added"),Z=A.changes.filter((V)=>V.type==="changed"),X=A.changes.filter((V)=>V.type==="deprecated"),Y=A.changes.filter((V)=>V.type==="removed"),B=A.changes.filter((V)=>V.type==="fixed"),q=A.changes.filter((V)=>V.type==="security"),H=A.breakingChanges??A.changes.filter((V)=>V.type==="breaking");if(H.length>0)W.push("### ⚠️ Breaking Changes"),H.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Q.length>0)W.push("### Added"),Q.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Z.length>0)W.push("### Changed"),Z.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(X.length>0)W.push("### Deprecated"),X.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(Y.length>0)W.push("### Removed"),Y.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(B.length>0)W.push("### Fixed"),B.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("");if(q.length>0)W.push("### Security"),q.forEach((V)=>{W.push(`- ${V.description}${V.path?` (${V.path})`:""}`)}),W.push("")}return W.join(`
|
|
2130
|
+
`)}function f9($){let W=["# Changelog",""],j=[...$].sort((A,Q)=>u9(A.version,Q.version));for(let A of j){let Q=A.bumpType==="major"?"\uD83D\uDCA5 BREAKING RELEASE":A.bumpType==="minor"?"\uD83D\uDE80 Minor Release":"\uD83D\uDD27 Patch Release";W.push(`## ${A.version} (${A.date}) - ${Q}`),W.push("");let Z={added:"feat",changed:"refactor",fixed:"fix",removed:"refactor",deprecated:"deprecate",breaking:"feat!",security:"security"};for(let X of A.changes){let Y=Z[X.type]??"chore",B=X.path?`(${X.path})`:"",q=X.type==="breaking"?"!":"";W.push(`- **${Y}${B}${q}**: ${X.description}`)}W.push("")}return W.join(`
|
|
2131
|
+
`)}function rW($,W){let j=$.analyses.filter((Z)=>Z.needsBump),A=new Date().toISOString(),Q=A.split("T")[0]??"";return{generatedAt:A,baseline:W,specs:j.map((Z)=>({key:Z.specKey,version:Z.suggestedVersion,path:Z.specPath,entries:[{version:Z.suggestedVersion,date:Q,bumpType:Z.bumpType,changes:Z.changes,breakingChanges:Z.changes.filter((X)=>X.type==="breaking")}]})),libraries:qq(j,Q)}}function Bq($){let W=$.split("/"),j=W.lastIndexOf("packages");if(j>=0&&j+2<W.length)return W.slice(0,j+3).join("/");return Yq($)}var g9={major:3,minor:2,patch:1};function qq($,W){let j=new Map;for(let A of $){let Q=Bq(A.specPath),Z=j.get(Q);if(Z)Z.push(A);else j.set(Q,[A])}return Array.from(j.entries()).flatMap(([A,Q])=>{let Z=Q[0];if(!Z)return[];let X=Q.reduce((Y,B)=>{return(g9[B.bumpType]??0)>(g9[Y.bumpType]??0)?B:Y},Z);return[{name:Xq(A),path:A,version:X.suggestedVersion,entries:[{version:X.suggestedVersion,date:W,bumpType:X.bumpType,changes:Q.flatMap((Y)=>Y.changes),breakingChanges:Q.flatMap((Y)=>Y.changes).filter((Y)=>Y.type==="breaking")}]}]})}function u9($,W){let j=(Z)=>{return Z.split(".").map((Y)=>parseInt(Y,10)||0)},A=j($),Q=j(W);for(let Z=0;Z<3;Z++){let X=A[Z]??0,Y=Q[Z]??0;if(X!==Y)return Y-X}return 0}var lW={feat:"minor",fix:"patch",perf:"patch",refactor:"patch",docs:null,style:null,test:null,chore:null,ci:null,build:null,revert:"patch"},Hq=/^(\w+)(?:\(([^)]+)\))?(!)?\s*:\s*(.+)$/,Vq=/^BREAKING[ -]CHANGE:\s*(.+)$/im;function oW($){let W=$.split(`
|
|
2132
|
+
`),j=W[0]?.trim();if(!j)return null;let A=j.match(Hq);if(!A)return null;let[,Q,Z,X,Y]=A;if(!Q||!Y)return null;let B=W.slice(1).join(`
|
|
2133
|
+
`).trim()||void 0,q=B?.match(Vq),H=q?.[1];return{type:Q.toLowerCase(),scope:Z?.toLowerCase(),breaking:!!X||!!q,description:Y.trim(),body:B,breakingDescription:H,raw:$}}function Gq($){return oW($)!==null}function sj($,W=lW){if($.breaking)return"major";return W[$.type]??null}function ej($,W=lW){let j=["major","minor","patch"],A=null;for(let Q of $){let Z=sj(Q,W);if(!Z)continue;if(!A){A=Z;continue}let X=j.indexOf(A);if(j.indexOf(Z)<X)A=Z}return A}function d9($){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 $5($){return $.map(d9)}function Jq($,W){return $.filter((j)=>j.scope?.toLowerCase()===W.toLowerCase())}function bq($,W=lW){return $.filter((j)=>sj(j,W)!==null)}import{GeneratedReleaseManifestSchema as xq}from"@contractspec/lib.contracts-spec";import{ContractsrcSchema as yq,DEFAULT_CONTRACTSRC as vq}from"@contractspec/lib.contracts-spec/workspace-config/contractsrc-schema";import{ReleaseCapsuleSchema as n9}from"@contractspec/lib.contracts-spec";import{dump as wq,load as Kq}from"js-yaml";var _q=".changeset/*.md",zq=".changeset/*.release.yaml",Uq=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,Lq=/^["']?([^"':]+(?:\/[^"':]+)?)["']?\s*:\s*(major|minor|patch|none)\s*$/;async function Oq($,W){return(await $.glob({pattern:_q,cwd:W,absolute:!0})).filter((A)=>$.basename(A)!=="README.md")}async function W5($,W){let j=await Oq($,W),A=[];for(let Q of j){let Z=await $.readFile(Q);A.push(Sq($.basename(Q),Z))}return A}async function j5($,W,j){let A=await $.glob({pattern:zq,cwd:W,absolute:!0}),Q=new Map(j.map((X)=>[X.slug,X.packages])),Z=new Map;for(let X of A){let Y=$.basename(X).replace(/\.release\.yaml$/,""),B=Kq(await $.readFile(X)),q=Iq(B,Y,Q.get(Y)??[]);Z.set(Y,q)}return Z}async function A5($,W){let j=await $.glob({patterns:["package.json","packages/*/*/package.json"],cwd:W,absolute:!0}),A=[];for(let Q of j){let Z=JSON.parse(await $.readFile(Q));if(!Z.name||!Z.version||Z.private===!0)continue;let X=$.relative(W,$.dirname(Q))||".";A.push({name:Z.name,dir:X,version:Z.version})}return A.sort((Q,Z)=>Q.dir.localeCompare(Z.dir))}function c9($,W){let j=new Set;for(let A of $){let Q=W.find((Z)=>Z.dir==="."?!A.startsWith("packages/"):A===Z.dir||A.startsWith(`${Z.dir}/`));if(Q)j.add(Q.name)}return Array.from(j).sort((A,Q)=>A.localeCompare(Q))}function r9($,W){return`---
|
|
2134
|
+
${W.map((A)=>`"${A.name}": ${A.releaseType}`).join(`
|
|
1890
2135
|
`)}
|
|
1891
2136
|
---
|
|
1892
2137
|
|
|
1893
2138
|
${$}
|
|
1894
|
-
`}function
|
|
1895
|
-
`)){let
|
|
1896
|
-
`)}function
|
|
1897
|
-
"${
|
|
2139
|
+
`}function l9($){return wq(n9.parse($),{noRefs:!0,lineWidth:100})}function Sq($,W){let j=$.replace(/\.md$/,""),A=W.match(Uq);if(!A)return{slug:j,summary:W.trim(),packages:[]};let Q=A[1]??"",Z=(A[2]??"").trim(),X=[];for(let Y of Q.split(`
|
|
2140
|
+
`)){let B=Y.trim().match(Lq);if(!B)continue;let q=B[1],H=B[2];if(!q||H==="none")continue;X.push({name:q,releaseType:H})}return{slug:j,summary:Z,packages:X}}function Iq($,W,j){let A=typeof $==="object"&&$!==null?$:{},Q=Array.isArray(A.packageNames)?A.packageNames.filter((Z)=>typeof Z==="string").map((Z)=>({name:Z,releaseType:A.releaseType??"patch"})):[];return n9.parse({...A,slug:W,packages:Array.isArray(A.packages)&&A.packages.length>0?A.packages:Q.length>0?Q:j})}import{bumpVersion as t9,determineBumpType as Mq}from"@contractspec/lib.contracts-spec";async function y0($,W={}){let{fs:j,git:A,logger:Q}=$,Z=W.workspaceRoot??process.cwd();Q.info("Starting version analysis...",{baseline:W.baseline});let X=W.pattern??"**/*.{operation,event,presentation}.ts",B=(await j.glob({pattern:X,cwd:Z})).filter((J)=>!J.includes(".test.")&&!J.includes(".spec.")&&!J.includes("node_modules"));Q.debug(`Found ${B.length} spec files`);let q=[],H=0,V=0;for(let J of B)try{let b=await j.readFile(J),w=iW(b);if(!w)continue;let L=null;if(W.baseline)try{L=await A.showFile(W.baseline,J)}catch{L=null}let z=Eq(b,L),S=z.some((I)=>I.type==="breaking"),U=z.length>0&&!S,O=z.length>0;if(S)H++;if(U)V++;let K=Mq(S,U),_=O?t9(w.version,K):w.version;q.push({specPath:J,specKey:w.key,currentVersion:w.version,suggestedVersion:_,bumpType:K,changes:z,hasBreaking:S,needsBump:O})}catch(b){Q.warn(`Failed to analyze ${J}:`,{error:b instanceof Error?b.message:String(b)})}let G=q.filter((J)=>J.needsBump).length;return Q.info("Version analysis complete",{totalSpecs:q.length,specsNeedingBump:G,totalBreaking:H,totalNonBreaking:V}),{analyses:q,totalSpecs:q.length,specsNeedingBump:G,totalBreaking:H,totalNonBreaking:V,baseline:W.baseline}}async function pW($,W={}){let{git:j,logger:A}=$,Q=W.baseline??"HEAD~10";A.info("Analyzing commits for version bump...",{baseline:Q});try{let Z=await j.log(Q),X=[],Y=[];for(let V of Z){let G=oW(V.message);if(G)X.push({hash:V.hash,message:V.message,type:G.type,scope:G.scope,breaking:G.breaking}),Y.push(G)}let B=ej(Y),q=$5(Y),H=X.filter((V)=>V.breaking).length;return A.info("Commit analysis complete",{totalCommits:X.length,breakingCommits:H,suggestedBumpType:B}),{suggestedBumpType:B,commits:X,changes:q,totalCommits:X.length,breakingCommits:H}}catch(Z){return A.warn("Failed to analyze commits",{error:Z instanceof Error?Z.message:String(Z)}),{suggestedBumpType:null,commits:[],changes:[],totalCommits:0,breakingCommits:0}}}async function a9($,W){let{fs:j,logger:A}=$,{specPath:Q,dryRun:Z=!1,config:X}=W;A.info("Applying version bump...",{specPath:Q,bumpType:W.bumpType});try{let Y=await j.readFile(Q),B=iW(Y);if(!B)return{success:!1,specPath:Q,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:"patch",changelogEntry:i9(),error:"Could not extract spec metadata"};let q=W.bumpType??"patch",H=t9(B.version,q),V=W.changes??[];if(W.changeDescription)V.push({type:q==="major"?"breaking":"changed",description:W.changeDescription});let G={version:H,date:new Date().toISOString().split("T")[0]??"",bumpType:q,changes:V,breakingChanges:V.filter((J)=>J.type==="breaking")};if(!Z){let J=Rq(Y,B.version,H);await j.writeFile(Q,J)}if(A.info("Version bump applied",{specPath:Q,previousVersion:B.version,newVersion:H}),X?.integrateWithChangesets)await Tq($,{specPath:Q,bumpType:q,summary:W.changeDescription??`Bump ${B.key} to ${H}`,dryRun:Z});return{success:!0,specPath:Q,specKey:B.key,previousVersion:B.version,newVersion:H,bumpType:q,changelogEntry:G}}catch(Y){let B=Y instanceof Error?Y.message:String(Y);return A.error("Version bump failed",{specPath:Q,error:B}),{success:!1,specPath:Q,specKey:"unknown",previousVersion:"unknown",newVersion:"unknown",bumpType:W.bumpType??"patch",changelogEntry:i9(),error:B}}}async function s9($,W={}){let{logger:j}=$,A=W.tiers??["spec","library","monorepo"],Q=W.format??"keep-a-changelog";j.info("Generating changelogs...",{tiers:A,format:Q});let Z=await y0($,{baseline:W.baseline,workspaceRoot:W.workspaceRoot}),X=[],Y=new Map,B="",q=0;if(A.includes("spec"))for(let V of Z.analyses.filter((G)=>G.needsBump)){let G={id:`changelog.${V.specKey}`,title:`Changelog for ${V.specKey}`,body:Cq(V),kind:"changelog",specKey:V.specKey,specVersion:V.suggestedVersion,entries:[{version:V.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:V.bumpType,changes:V.changes,breakingChanges:V.changes.filter((J)=>J.type==="breaking")}]};X.push(G),q++}if(A.includes("library")){let V=Dq(Z.analyses);for(let[G,J]of V){let b=J.filter((w)=>w.needsBump);if(b.length>0)Y.set(G,x0(b.map(p9))),q+=b.length}}if(A.includes("monorepo")){let V=Z.analyses.filter((G)=>G.needsBump).map(p9);B=x0(V)}let H=rW(Z,W.baseline);return j.info("Changelog generation complete",{totalEntries:q}),{specChangelogs:X,libraryMarkdown:Y,monorepoMarkdown:B,json:H,totalEntries:q}}function iW($){let W=$.match(/key:\s*['"`]([^'"`]+)['"`]/),j=$.match(/version:\s*['"`]([^'"`]+)['"`]/);if(!W||!j)return null;let A=W[1],Q=j[1];if(!A||!Q)return null;return{key:A,version:Q}}function Eq($,W){let j=[];if(!W)return j.push({type:"added",description:"New spec added"}),j;let A=iW($),Q=iW(W);if(!A||!Q)return j;if(A.version!==Q.version)j.push({type:"changed",description:`Version updated from ${Q.version} to ${A.version}`,path:"meta.version"});let Z=Nq($,W);if(Z.breaking)j.push({type:"breaking",description:"Breaking changes to input/output schema",path:"io"});else if(Z.nonBreaking)j.push({type:"changed",description:"Non-breaking changes to input/output schema",path:"io"});return j}function Nq($,W){let j=/io:\s*\{[\s\S]*?\}/,A=$.match(j)?.[0]??"",Q=W.match(j)?.[0]??"";if(A===Q)return{breaking:!1,nonBreaking:!1};let Z=o9(A),X=o9(Q),Y=X.filter((q)=>!Z.includes(q)),B=Z.filter((q)=>!X.includes(q));return{breaking:Y.length>0,nonBreaking:B.length>0&&Y.length===0}}function o9($){let W=/(\w+):/g;return[...$.matchAll(W)].map((A)=>A[1]).filter((A)=>!!A)}function Rq($,W,j){return $.replace(new RegExp(`version:\\s*['"\`]${W}['"\`]`),`version: '${j}'`)}function i9(){return{version:"0.0.0",date:new Date().toISOString().split("T")[0]??"",bumpType:"patch",changes:[]}}function Cq($){let W=[`## [${$.suggestedVersion}] - ${new Date().toISOString().split("T")[0]}`,""],j=$.changes.filter((Z)=>Z.type==="breaking"),A=$.changes.filter((Z)=>Z.type==="changed"),Q=$.changes.filter((Z)=>Z.type==="added");if(j.length>0)W.push("### Breaking Changes"),j.forEach((Z)=>W.push(`- ${Z.description}`)),W.push("");if(Q.length>0)W.push("### Added"),Q.forEach((Z)=>W.push(`- ${Z.description}`)),W.push("");if(A.length>0)W.push("### Changed"),A.forEach((Z)=>W.push(`- ${Z.description}`)),W.push("");return W.join(`
|
|
2141
|
+
`)}function Dq($){let W=new Map;for(let j of $){let Z=j.specPath.match(/(.+?\/src\/)/)?.[1]??j.specPath,X=W.get(Z)??[];X.push(j),W.set(Z,X)}return W}function p9($){return{version:$.suggestedVersion,date:new Date().toISOString().split("T")[0]??"",bumpType:$.bumpType,changes:$.changes,breakingChanges:$.changes.filter((W)=>W.type==="breaking")}}async function Tq($,W){let{fs:j,logger:A}=$,{specPath:Q,bumpType:Z,summary:X,dryRun:Y}=W;try{let B=f(Q),q=I$(B);if(!q){A.warn("Could not determine package name for changeset",{specPath:Q});return}let H=B,V=null;while(!0){let w=j.join(H,".changeset");if(await j.exists(w)){V=w;break}let L=j.dirname(H);if(L===H)break;H=L}if(!V){A.warn("No .changeset directory found, skipping changeset generation");return}let G=`${Fq()}.md`,J=j.join(V,G),b=`---
|
|
2142
|
+
"${q}": ${Z}
|
|
1898
2143
|
---
|
|
1899
2144
|
|
|
1900
2145
|
${X}
|
|
1901
|
-
`;if(!Y)await j.writeFile(
|
|
1902
|
-
`).map((
|
|
2146
|
+
`;if(!Y)await j.writeFile(J,b),A.info("Generated changeset",{filePath:J});else A.info("Would generate changeset",{filePath:J,content:b})}catch(B){A.error("Failed to generate changeset",{error:B instanceof Error?B.message:String(B)})}}function Fq(){let $=["neat","calm","wild","soft","bold","fair","cool"],W=["fox","cat","dog","bat","ant","elk","owl"],j=["run","fly","hop","eat","nap","cry","sing"],A=$[Math.floor(Math.random()*$.length)],Q=W[Math.floor(Math.random()*W.length)],Z=j[Math.floor(Math.random()*j.length)],X=Math.floor(Math.random()*1000);return`${A}-${Q}-${Z}-${X}`}var e9="generated/releases",tW=vq.release??{enforceOn:"release-branch",requireChangesetForPublished:!0,requireReleaseCapsule:!0,publishArtifacts:[],agentTargets:["codex"]};async function $A($,W={}){let{fs:j,git:A,logger:Q}=$,Z=D(W.workspaceRoot),X=await A5(j,Z),Y=W.baseline?await A.diffFiles(W.baseline):[],B=W.packages&&W.packages.length>0?W.packages:c9(Y,X),q=W.baseline?await pW($,{baseline:W.baseline,workspaceRoot:Z}):null,H=W.baseline?await F$($,{baseline:W.baseline,workspaceRoot:Z}):null,V=(H?.summary.breaking??0)>0?"major":q?.suggestedBumpType??mq(B),G=W.releaseType??V,J=W.summary??`Describe the ${G} release for ${B[0]??"the workspace"}`,b=W.slug??kq(J),w=B.map((K)=>({name:K,releaseType:G,version:X.find((_)=>_.name===K)?.version})),L={schemaVersion:"1",slug:b,summary:J,isBreaking:G==="major"||(H?.summary.breaking??0)>0,packages:w,affectedRuntimes:[],affectedFrameworks:[],audiences:[{kind:"maintainer",summary:J},{kind:"customer",summary:J}],deprecations:[],migrationInstructions:[],upgradeSteps:[],validation:{commands:["contractspec impact --baseline main --format markdown","contractspec version analyze --baseline main"],evidence:[]}},z=j.join(Z,".changeset",`${b}.md`),S=j.join(Z,".changeset",`${b}.release.yaml`);if(!W.force){if(await j.exists(z))throw Error(`Changeset already exists: ${z}`);if(await j.exists(S))throw Error(`Release capsule already exists: ${S}`)}let U=r9(J,w),O=l9(L);if(!W.dryRun)await j.writeFile(z,U),await j.writeFile(S,O);return Q.info("Initialized release artifacts",{slug:b,workspaceRoot:Z}),{slug:b,changesetPath:z,capsulePath:S,changesetContent:U,capsuleContent:O,packages:w,releaseType:G,isBreaking:L.isBreaking}}async function WA($,W={}){let{fs:j,logger:A}=$,Q=D(W.workspaceRoot),Z=await AA(j,Q),X=j.join(Q,W.outputDir??e9),Y=await W5(j,Q),B=await j5(j,Q,Y),q=await A5(j,Q),H=await Promise.all(Array.from(B.entries()).map(async([U,O])=>{let K=j.join(Q,".changeset",`${U}.release.yaml`),_=await j.stat(K);return{slug:U,version:Pq(O,q),summary:O.summary,date:_.mtime.toISOString().split("T")[0]??new Date().toISOString(),isBreaking:O.isBreaking,packages:O.packages.map((I)=>({...I,version:q.find((M)=>M.name===I.name)?.version??I.version})),affectedRuntimes:[...O.affectedRuntimes],affectedFrameworks:[...O.affectedFrameworks],audiences:[...O.audiences],deprecations:[...O.deprecations],migrationInstructions:[...O.migrationInstructions],upgradeSteps:[...O.upgradeSteps],validation:O.validation}})),V=xq.parse({generatedAt:new Date().toISOString(),releases:H}),G=W.agentTargets??Z.agentTargets??["codex"],J=D0(V,[],G,p$),b=j.join(X,"manifest.json"),w=j.join(X,"upgrade-manifest.json"),L=j.join(X,"patch-notes.md"),z=j.join(X,"customer-guide.md"),S=Object.fromEntries(J.agentPrompts.map((U)=>[U.agent,j.join(X,"prompts",`${U.agent}.md`)]));if(!W.dryRun){await j.writeFile(b,JSON.stringify(V,null,2)),await j.writeFile(w,JSON.stringify(V,null,2)),await j.writeFile(L,ij(V)),await j.writeFile(z,pj(V));for(let U of J.agentPrompts)await j.writeFile(S[U.agent]??"",U.prompt)}return A.info("Built release artifacts",{outputDir:X,releasesBuilt:V.releases.length}),{outputDir:X,manifestPath:b,upgradeManifestPath:w,patchNotesPath:L,customerGuidePath:z,promptPaths:S,manifest:V,upgradePlan:J,releasesBuilt:V.releases.length}}async function jA($,W={}){let{fs:j}=$,A=D(W.workspaceRoot),Q=await AA(j,A),Z=j.join(A,W.outputDir??e9),X=[],Y=[],B=[],q=await W5(j,A),H=await j5(j,A,q),V=q.length>0,G=!V&&H.size>0;t$(X,V||G,"changesets",V?`Found ${q.length} release changeset(s).`:G?"No pending release changesets found; release capsules are present.":"No release changesets found.");for(let J of q)if(!H.has(J.slug)&&Q.requireReleaseCapsule)B.push(`Missing release capsule for changeset ${J.slug}.`);for(let[J,b]of H){if(b.isBreaking&&b.migrationInstructions.length===0)B.push(`Breaking release ${J} is missing migration instructions.`);if(b.validation.commands.length===0)B.push(`Release capsule ${J} is missing validation commands.`);if(b.validation.evidence.length===0)B.push(`Release capsule ${J} is missing validation evidence.`)}if(W.baseline){try{let J=await F$($,{baseline:W.baseline,workspaceRoot:A});if(t$(X,!0,"impact",`Impact status: ${J.status}`),J.summary.breaking>0&&!Array.from(H.values()).some((b)=>b.isBreaking))B.push("Breaking impact detected without a breaking release capsule.")}catch(J){t$(X,!1,"impact",aW(J)),B.push(`Impact detection failed: ${aW(J)}`)}try{let J=await y0($,{baseline:W.baseline,workspaceRoot:A});t$(X,!0,"versioning",`${J.specsNeedingBump} spec(s) need version review.`)}catch(J){t$(X,!1,"versioning",aW(J)),B.push(`Version analysis failed: ${aW(J)}`)}}if(W.strict)for(let J of Q.publishArtifacts??[]){let b=j.join(Z,J);if(!await j.exists(b))B.push(`Missing generated release artifact: ${b}`)}if(t$(X,B.length===0,"capsules",B.length===0?"All release capsules are complete.":B[0]??""),!V&&!G)Y.push("No pending release changesets were found.");return{success:B.length===0,errors:B,warnings:Y,checks:X}}async function AA($,W){let j=$.join(W,".contractsrc.json");if(!await $.exists(j))return tW;try{let A=JSON.parse(await $.readFile(j)),Q=yq.safeParse(A);return Q.success?{...tW,...Q.data.release}:tW}catch{return tW}}function mq($){return $.length>0?"minor":"patch"}function Pq($,W){return $.packages.map((A)=>W.find((Q)=>Q.name===A.name)?.version??A.version).find((A)=>typeof A==="string")??"0.0.0"}function kq($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function t$($,W,j,A){$.push({name:j,ok:W,message:A})}function aW($){return $ instanceof Error?$.message:String($)}var wA={};h(wA,{silentLogger:()=>YA,runWorkflow:()=>BA,loadWorkflows:()=>X5,loadVibeConfig:()=>eW,installPack:()=>bA,getWorkflow:()=>HA,exportContext:()=>XA,consoleLogger:()=>Z5,builtinWorkflows:()=>$1,DEFAULT_VIBE_CONFIG:()=>sW});import{existsSync as hq}from"node:fs";import{readFile as gq}from"node:fs/promises";import{join as Q5}from"node:path";import fq from"js-yaml";var sW={canonicalRoot:"contracts",workRoot:".contractspec/work",generatedRoot:"src/generated",alwaysInjectFiles:[],contextExportAllowlist:[]};async function eW($){let W=$??process.cwd(),j=D(W)??W,A=[Q5(j,".contractspec","vibe","config.json"),Q5(j,".contractspec","vibe","config.yaml"),Q5(j,".contractspec","vibe","config.yml")],Q={};for(let Z of A)if(hq(Z))try{let X=await gq(Z,"utf-8");if(Z.endsWith(".json"))Q=JSON.parse(X);else Q=fq.load(X);break}catch(X){console.warn(`Warning: Failed to parse ${Z}`,X)}return{...sW,...Q}}import{existsSync as uq}from"node:fs";import{copyFile as dq,mkdir as ZA,readFile as nq,writeFile as cq}from"node:fs/promises";import{dirname as rq,join as a$}from"node:path";import{glob as lq}from"glob";var oq=["**/node_modules/**","**/dist/**","**/.git/**","**/.env*","**/id_rsa","**/*.pem","**/*.key","**/secrets.*"];async function XA($){let W=$??process.cwd(),j=D(W)??W,A=await eW(W),Q=a$(j,".contractspec","context"),Z=a$(Q,"files"),X=[...oq],Y=a$(j,".gitignore");if(uq(Y)){let w=(await nq(Y,"utf-8")).split(`
|
|
2147
|
+
`).map((L)=>L.trim()).filter((L)=>L&&!L.startsWith("#"));X=[...X,...w]}let B=A.contextExportAllowlist.length>0?A.contextExportAllowlist:["README.md","package.json","contracts/**/*.ts"],q=[];for(let b of B){let w=await lq(b,{cwd:j,ignore:X,nodir:!0,dot:!0});q.push(...w)}let H=Array.from(new Set(q)).sort();if(H.length===0)return{success:!1,files:[],indexPath:"",error:"No files matched the allowlist. Check your config."};await ZA(Z,{recursive:!0});let V=[];for(let b of H){let w=a$(j,b),L=a$(Z,b);await ZA(rq(L),{recursive:!0}),await dq(w,L),V.push({path:b,size:0})}let G=a$(Q,"index.json"),J={generatedAt:new Date().toISOString(),files:V.map((b)=>b.path),config:{allowlist:A.contextExportAllowlist,ignores:X.length}};return await cq(G,JSON.stringify(J,null,2)),{success:!0,files:H,indexPath:G}}var $1=[{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.
|
|
1903
2148
|
Please review them and move selected files to contracts/ directory.
|
|
1904
|
-
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"
|
|
1905
|
-
Running Workflow: ${$.name}`),$.description)
|
|
1906
|
-
`);let
|
|
1907
|
-
\uD83D\uDC49 Step: ${X.label}`),W.dryRun&&X.command)
|
|
2149
|
+
Continue when done.`},{id:"gap",label:"Analyze Gaps",command:"contractspec gap"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"},{id:"clean",label:"Clean Scaffolding",command:"contractspec clean --work"}]},{id:"change.feature",name:"Change: Feature Development",description:"Routine workflow for contract edits.",steps:[{id:"impact",label:"Check Impact",command:"contractspec impact"},{id:"generate",label:"Generate Artifacts",command:"contractspec generate"},{id:"ci",label:"Run CI Checks",command:"contractspec ci"}]},{id:"release",name:"Release: Version & Publish",description:"Prepare and publish a new contract version.",steps:[{id:"impact",label:"Verify Impact",command:"contractspec impact"},{id:"ci",label:"CI Check",command:"contractspec ci --fail-on-warnings"},{id:"bump",label:"Bump Version",command:"contractspec version bump",manualCheckpoint:!0,manualMessage:"Review version bump. Continue to publish?"},{id:"changelog",label:"Generate Changelog",command:"contractspec changelog"},{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 iq}from"node:child_process";var YA={log:()=>{},warn:()=>{},error:()=>{}},Z5={log:($)=>console.log($),warn:($)=>console.warn($),error:($)=>console.error($)};async function BA($,W,j){let A=j?.logger??Z5,Q=j?.prompter;if(A.log(`
|
|
2150
|
+
Running Workflow: ${$.name}`),$.description)A.log($.description);if(A.log(`Track: ${W.track}`),W.dryRun)A.warn(`\uD83D\uDEA7 DRY RUN MODE: No changes will be made.
|
|
2151
|
+
`);let Z={success:!0,steps:[],stepsExecuted:[],artifactsTouched:[]};for(let X of $.steps){let Y={id:X.id,name:X.label,status:"skip",command:X.command};if(X.tracks&&!X.tracks.includes(W.track)){Z.steps.push(Y);continue}if(X.condition){if(!await X.condition(W)){Z.steps.push(Y);continue}}if(A.log(`
|
|
2152
|
+
\uD83D\uDC49 Step: ${X.label}`),W.dryRun&&X.command)A.log(` Command: ${X.command}`);if(X.manualCheckpoint){if(W.dryRun)A.warn(" [Manual Checkpoint] Would pause here for user input.");else if(Q){if(X.manualMessage)A.log(X.manualMessage);let B=await Q.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(B==="abort")return A.warn("Workflow aborted by user."),Z.success=!1,Z.steps.push({...Y,status:"skip",error:"Aborted by user"}),Z;if(B==="skip"){A.warn(" → Skipped by user."),Z.steps.push(Y);continue}}}if(!W.dryRun)try{if(X.execute)await X.execute(W);else if(X.command)await pq(X.command,W.root);Y.status="pass",Z.stepsExecuted.push(X.id),Z.steps.push(Y),A.log(" ✓ Completed")}catch(B){let q=B instanceof Error?B.message:String(B);return A.error(` ❌ Failed: ${q}`),Z.success=!1,Z.error=B instanceof Error?B:Error(String(B)),Y.status="fail",Y.error=q,Z.stepsExecuted.push(X.id),Z.steps.push(Y),Z}else Z.steps.push(Y)}return Z}async function pq($,W){let j=$.split(" "),A=j[0],Q=j.slice(1);if(!A)throw Error("Invalid command");return new Promise((Z,X)=>{let Y=iq(A,Q,{cwd:W,stdio:"inherit",shell:!0});Y.on("error",X),Y.on("exit",(B)=>{if(B===0)Z();else X(Error(`Command exited with code ${B}`))})})}import{existsSync as tq}from"node:fs";import{readdir as aq,readFile as sq}from"node:fs/promises";import{join as qA}from"node:path";import eq from"js-yaml";async function X5($){let W=[...$1],j=$??process.cwd(),A=D(j)??j,Q=qA(A,".contractspec","vibe","workflows");if(tq(Q))try{let Z=await aq(Q);for(let X of Z)if(X.endsWith(".json")||X.endsWith(".yaml")||X.endsWith(".yml")){let Y=await sq(qA(Q,X),"utf-8");try{let B;if(X.endsWith(".json"))B=JSON.parse(Y);else B=eq.load(Y);if(B.id&&B.steps)W.push(B)}catch(B){console.warn(`Failed to parse workflow ${X}:`,B)}}}catch(Z){console.warn("Error loading user workflows:",Z)}return W}async function HA($,W){return(await X5(W)).find((A)=>A.id===$)}import{existsSync as Y5}from"node:fs";import{copyFile as VA,mkdir as GA,readdir as JA,stat as $H}from"node:fs/promises";import{join as U$,resolve as WH}from"node:path";async function bA($,W){let j=W??process.cwd(),A=D(j)??j;if($.startsWith("registry:"))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:"Registry pack install not yet implemented. Use local path."};let Q=WH(j,$);if(!Y5(Q))return{success:!1,workflowsInstalled:0,templatesInstalled:0,error:`Pack path not found: ${Q}`};let Z=0,X=0,Y=U$(Q,"workflows");if(Y5(Y)){let q=U$(A,".contractspec","vibe","workflows");await GA(q,{recursive:!0});let H=await JA(Y);for(let V of H)if(V.endsWith(".json")||V.endsWith(".yaml")||V.endsWith(".yml"))await VA(U$(Y,V),U$(q,V)),Z++}let B=U$(Q,"templates");if(Y5(B)){let q=U$(A,".contractspec","vibe","templates");await GA(q,{recursive:!0});let H=await JA(B);for(let V of H){let G=U$(B,V),J=U$(q,V);if((await $H(G)).isFile())await VA(G,J),X++}}return{success:!0,workflowsInstalled:Z,templatesInstalled:X}}import{loadSpecFromSource as jH}from"@contractspec/module.workspace";var KA=["product","eng","qa"];function AH($){return KA.includes($)}async function QN($,W){if(!AH(W.audience))throw Error(`Invalid audience: ${W.audience}. Must be one of: ${KA.join(", ")}`);let j,A,Q;if(W.specFiles&&W.specFiles.length>0)j=W.specFiles;else{let X=await QH($,{baseline:W.baseline});if(A=X.totalSpecs,Q=X.changedFilesCount,W.baseline){if(X.changedFilesCount===0)return{views:[],totalSpecs:A,changedFilesCount:0,status:"no_changes"};if(X.specFiles.length===0)return{views:[],totalSpecs:A,changedFilesCount:Q,status:"no_changed_specs"}}j=X.specFiles}if(j.length===0)return{views:[],totalSpecs:A,changedFilesCount:Q,status:"no_specs"};let Z=[];for(let X of j){let Y=await ZH(X,W.audience,$);Z.push({filePath:X,content:Y})}return{views:Z,totalSpecs:A,changedFilesCount:Q,status:"success"}}async function QH($,W={}){let A=(await $$({fs:$.fs})).map((Y)=>Y.filePath),Q=A.length;if(!W.baseline)return{specFiles:A,totalSpecs:Q};let Z=await $.git.diffFiles(W.baseline);if(Z.length===0)return{specFiles:[],totalSpecs:Q,changedFilesCount:0,hasChanges:!1};let X=A.filter((Y)=>Z.some((B)=>Y.endsWith(B)||B.endsWith(Y)||Y.includes(B)||B.includes(Y)));return{specFiles:X,totalSpecs:Q,changedFilesCount:Z.length,hasChanges:X.length>0}}async function ZH($,W,j){if(!await j.fs.exists($))throw Error(`File not found: ${$}`);let A=await jH($);if(A.length===0)return`No specs found in ${$} (Parse result empty)`;return A.map((Q)=>XH(Q,W)).join(`
|
|
1908
2153
|
|
|
1909
2154
|
---
|
|
1910
2155
|
|
|
1911
|
-
`)}function
|
|
1912
|
-
`)}function
|
|
2156
|
+
`)}function XH($,W){let j=[];switch(W){case"product":YH($,j);break;case"eng":BH($,j);break;case"qa":qH($,j);break}return j.join(`
|
|
2157
|
+
`)}function YH($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: Product (User Flow & Capabilities)"),W.push(""),$.meta.goal)W.push(`### Goal
|
|
1913
2158
|
${$.meta.goal}
|
|
1914
2159
|
`);if($.meta.context)W.push(`### Context
|
|
1915
2160
|
${$.meta.context}
|
|
1916
|
-
`);if($.specType==="feature"){if($.operations?.length)W.push("### Capabilities (Operations)"),$.operations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("");if($.presentations?.length)W.push("### User Interfaces (Presentations)"),$.presentations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("")}else if($.specType==="operation"){if(W.push("### Behavior"),$.hasPolicy)W.push("- ✅ Enforces Business Policies");if($.hasIo)W.push("- ✅ Validates Inputs/Outputs");if($.emittedEvents?.length)W.push("### Triggers"),$.emittedEvents.forEach((j)=>W.push(`- **${j.name}** (Event)`))}else W.push(`Type: ${$.specType}`)}function
|
|
1917
|
-
`);if($.testRefs?.length)W.push("### Linked Scenarios"),$.testRefs.forEach((j)=>W.push(`- \uD83E\uDDEA \`${j.name}\``)),W.push("");else W.push("### Linked Scenarios"),W.push("_(No explicit test refs found)_"),W.push("");if(W.push("### Verification Checklist"),$.specType==="operation"){if(W.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)W.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((j)=>W.push(`- [ ] Verify event \`${j.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((j)=>W.push(`- [ ] Test Operation flow: \`${j.name}\``));if($.presentations?.length)$.presentations.forEach((j)=>W.push(`- [ ] Test UI Component: \`${j.name}\``))}}function
|
|
1918
|
-
`)}export{
|
|
2161
|
+
`);if($.specType==="feature"){if($.operations?.length)W.push("### Capabilities (Operations)"),$.operations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("");if($.presentations?.length)W.push("### User Interfaces (Presentations)"),$.presentations.forEach((j)=>W.push(`- **${j.name}**`)),W.push("")}else if($.specType==="operation"){if(W.push("### Behavior"),$.hasPolicy)W.push("- ✅ Enforces Business Policies");if($.hasIo)W.push("- ✅ Validates Inputs/Outputs");if($.emittedEvents?.length)W.push("### Triggers"),$.emittedEvents.forEach((j)=>W.push(`- **${j.name}** (Event)`))}else W.push(`Type: ${$.specType}`)}function BH($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: Engineering (API, Schemas, Constraints)"),W.push(""),W.push(`- **Type**: \`${$.specType}\``),W.push(`- **Version**: \`${$.meta.version}\``),$.meta.stability)W.push(`- **Stability**: \`${$.meta.stability}\``);if(W.push(""),$.specType==="operation"){if(W.push("### Contract Details"),W.push(`- **I/O Schema**: ${$.hasIo?"✅ Defined":"❌ Missing"}`),W.push(`- **Policy Config**: ${$.hasPolicy?"✅ Defined":"❌ None"}`),W.push(""),$.emittedEvents?.length)W.push("### Emitted Events"),$.emittedEvents.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("")}else if($.specType==="feature"){if($.operations?.length)W.push("### Operations"),$.operations.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("");if($.events?.length)W.push("### Events"),$.events.forEach((j)=>W.push(`- \`${j.name}\``)),W.push("")}if($.sourceBlock)W.push("### Source Signature"),W.push("```typescript"),W.push($.sourceBlock),W.push("```")}function qH($,W){if(W.push(`# ${$.meta.key}`),W.push("**View**: QA (Scenarios, Test Coverage)"),W.push(""),$.meta.goal)W.push(`**Goal**: ${$.meta.goal}
|
|
2162
|
+
`);if($.testRefs?.length)W.push("### Linked Scenarios"),$.testRefs.forEach((j)=>W.push(`- \uD83E\uDDEA \`${j.name}\``)),W.push("");else W.push("### Linked Scenarios"),W.push("_(No explicit test refs found)_"),W.push("");if(W.push("### Verification Checklist"),$.specType==="operation"){if(W.push(`- [ ] Verify input validation for \`${$.meta.key}\` (Success/Fail cases)`),$.hasPolicy)W.push("- [ ] Verify policy enforcement rules");if($.emittedEvents?.length)$.emittedEvents.forEach((j)=>W.push(`- [ ] Verify event \`${j.name}\` is emitted`))}else if($.specType==="feature"){if($.operations?.length)$.operations.forEach((j)=>W.push(`- [ ] Test Operation flow: \`${j.name}\``));if($.presentations?.length)$.presentations.forEach((j)=>W.push(`- [ ] Test UI Component: \`${j.name}\``))}}function BN($,W,j,A){let{watcher:Q,fs:Z,logger:X}=$,Y=Q.watch(j),B=A?.validate??(async(H)=>{await m$(H,{fs:Z,logger:X})}),q=A?.build??(async(H)=>{await f$(H,{fs:Z,logger:X},W)});return Y.on(async(H)=>{if(H.type!=="change")return;if(X.info("watchSpecs.changed",{path:H.path}),j.runValidate)await B(H.path);if(j.runBuild)if(j.dryRun)X.info("[dry-run] watchSpecs skipped build",{path:H.path});else await q(H.path)}),Y}async function VN($,W){let j=N5(W),A=$.join(j.workspaceRoot,".contractsrc.json"),Q=$.join(j.packageRoot,".contractsrc.json"),Z=await $.exists(A),X=j.workspaceRoot!==j.packageRoot?await $.exists(Q):!1,Y;if(Z)try{let B=await $.readFile(A),q=JSON.parse(B);if(q.packages||q.excludePackages||q.recursive)Y={packages:q.packages,excludePackages:q.excludePackages,recursive:q.recursive}}catch{}return{...j,monorepoConfig:Y,workspaceConfigPath:Z?A:void 0,packageConfigPath:X?Q:void 0}}async function GN($,W){let j=[],A=$.join(W,".contractsrc.json");if(await $.exists(A))j.push(A);let Q=await $.glob({pattern:"**/.contractsrc.json",ignore:["node_modules/**",".git/**"]});for(let Z of Q)if(Z!==A)j.push(Z);return j}async function JN($,W,j){let A={};if(W&&await $.exists(W))try{let Q=await $.readFile(W);A=JSON.parse(Q)}catch{}if(j&&await $.exists(j))try{let Q=await $.readFile(j),Z=JSON.parse(Q);A=_A(A,Z)}catch{}return A}function _A($,W){let j={...$};for(let A of Object.keys(W)){let Q=$[A],Z=W[A];if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q)&&typeof Z==="object"&&Z!==null&&!Array.isArray(Z))j[A]=_A(Q,Z);else j[A]=Z}return j}function bN($){let W=[];if(W.push(`Package Manager: ${$.packageManager}`),W.push(`Workspace Root: ${$.workspaceRoot}`),$.isMonorepo){if(W.push("Monorepo: Yes"),W.push(`Package Root: ${$.packageRoot}`),$.packageName)W.push(`Current Package: ${$.packageName}`);if($.packages&&$.packages.length>0)W.push(`Package Patterns: ${$.packages.join(", ")}`)}else W.push("Monorepo: No");if($.workspaceConfigPath)W.push(`Workspace Config: ${$.workspaceConfigPath}`);if($.packageConfigPath)W.push(`Package Config: ${$.packageConfigPath}`);return W.join(`
|
|
2163
|
+
`)}export{BN as watchSpecs,wA as vibe,QA as versioning,gB as verifyWithAIEnhanced,T0 as verifyWithAI,F0 as verifyStructure,Zq as verifyService,k9 as verifySemanticFields,DY as verifyImportedContracts,OO as verifyImplementationAgainstParsedSpec,nW as verifyBehavior,_I as validateTenantConfig,VI as validateSpecs,m$ as validateSpec,Q9 as validateScannedSpec,XI as validatePackageScaffold,$I as validateImplementationWithAgent,KW as validateImplementationFiles,HI as validateDiscoveredSpecs,tS as validateBlueprint,AH as validateAudience,kU as validateAgainstOpenApiService,K8 as utils,R9 as upgrade,lI as updateSpec,g7 as toKebabCase,B8 as templates,vU as syncWithOpenApiService,CI as syncSpecs,xB as stringToCacheKey,EW as setupGitignore,AS as searchRegistry,r as safeParseJson,PI as runTests,kI as runTestSpecs,hS as runSetup,cO as runQuickstart,g8 as runDoctor,q_ as runCIChecks,S8 as resolveSetupTargets,b$ as resolveSetupPreset,mj as resolveRegistryUrl,r7 as resolveImplementations,L1 as resolveDefaultBuildTargets,p4 as resolveAuthoredModuleValue,a8 as resolveAllImplementations,P5 as prompts,M5 as parseGitModules,i8 as parseExplicitImplementations,ZG as operationRegistry,XR as module,JN as mergeMonorepoConfigs,dX as mergeGitignoreContent,m as loadWorkspaceConfig,Sw as loadPackageAuthoredDocBlocks,o4 as loadAuthoredModuleValue,PO as loadAuthoredModuleIfExists,vW as loadAuthoredModuleExports,Q$ as loadAuthoredModule,Ow as loadAuthoredDocBlocksFromSourceFiles,hI as listTests,QH as listSpecsForView,$$ as listSpecs,jS as listFromRegistry,w1 as listAgentTypes,e$ as isMonorepo,rO as isContractSpecInstalled,_b as isConnectPreset,Kb as isBuilderPreset,B0 as inferSetupPresetFromConfig,h7 as inferImplementationType,SY as importFromSourceService,y4 as importFromOpenApiService,H4 as impact,c4 as hooks,FK as groupSpecsByType,jQ as getWorkspacePackages,N5 as getWorkspaceInfo,iH as getRunCommand,yj as getProductionDependencies,I$ as getPackageName,QQ as getMetaRepoInfo,R5 as getInstallCommand,sw as getImplementationSummary,eJ as getGraphStats,VN as getExtendedWorkspaceInfo,pH as getExecCommand,vj as getDevDependencies,xj as getDependencies,o8 as getConventionPaths,aJ as getContractNode,qW as getClaudeDesktopConfigPath,I8 as getBuilderRuntimeModeForPreset,M8 as getBuilderBootstrapPresetForSetupPreset,J8 as getApiKey,UK as getAllSpecs,mb as getAllLayerLocations,$0 as getAgentAdapter,V1 as getAIProvider,l0 as genericMCPAdapter,Y8 as generateWorkflowSpec,jW as generateWorkflowRunnerTemplate,a0 as generateWorkflowDevkitWorkflowTemplate,$W as generateWorkflowDevkitStreamRouteTemplate,s0 as generateWorkflowDevkitStartRouteTemplate,WW as generateWorkflowDevkitGenericTemplate,e0 as generateWorkflowDevkitFollowUpRouteTemplate,BW as generateVscodeSettings,QN as generateViews,ZH as generateView,s5 as generateTestTemplate,X8 as generateTelemetrySpec,Z8 as generatePresentationSpec,Q8 as generateOperationSpec,A8 as generateMigrationSpec,UO as generateMermaidDiagram,RY as generateMarkdownReport,W8 as generateKnowledgeSpaceSpec,$8 as generateIntegrationSpec,t5 as generateHandlerTemplate,mY as generateGuideFromParsedSpec,p5 as generateFormSpec,i5 as generateFeatureSpec,NO as generateFeatureContextMarkdown,o5 as generateExperimentSpec,l5 as generateEventSpec,d8 as generateDocsFromSpecs,r5 as generateDataViewSpec,p0 as generateDataViewRendererTemplate,PY as generateCursorRulesFromParsedSpec,C8 as generateCursorRules,q0 as generateCursorMcpConfig,u$ as generateContractsrcConfig,a5 as generateComponentTemplate,CY as generateCliReport,R8 as generateClaudeMcpConfig,c8 as generateArtifacts,c5 as generateAppBlueprintSpec,D8 as generateAgentsGuide,g5 as formatters,bN as formatWorkspaceInfo,SO as formatVerificationReport,lO as formatQuickstartPreview,i4 as formatModuleLoadError,F as formatJson,lL as formatFiles,Hw as formatDoctorSummary,Vw as formatCheckResult,g4 as fix,D as findWorkspaceRoot,f as findPackageRoot,E5 as findMetaRepoRoot,GN as findAllConfigFiles,LK as filterIssuesByType,OK as filterIssuesBySeverity,m4 as features,r8 as extractSpecReferences,oU as extractContracts,RO as exportSpecForLLM,x2 as exportOpenApi,sJ as exportGraphAsDot,H8 as ensurePackageScaffold,QW as discoverSpecs,N$ as discoverSpecFiles,VW as discoverLayers,_W as discoverImplementationsForSpec,ow as discoverAllImplementations,p8 as determineStatus,ZQ as detectRepositoryType,k$ as detectPackageManager,zU as deleteSpec,p as deepMergePreserve,y1 as deepMergeOverwrite,c0 as cursorCLIAdapter,KM as createWorkspaceStateCacheStorage,CQ as createWorkspaceRegistry,Qq as createVerifyService,EM as createVerificationCacheService,GU as createSpecCreator,E8 as createSetupNextSteps,N8 as createSetupGitignorePatterns,eO as createRegeneratorService,dW as createQuickAIReview,V8 as createPackageTargetSpecSource,U5 as createNoopLoggerAdapter,L5 as createNodeWatcherAdapter,_5 as createNodeGitAdapter,w5 as createNodeFsAdapter,V5 as createNodeAiAdapter,kH as createNodeAdapters,bM as createInMemoryCacheStorage,GM as createFileSystemCacheStorage,l6 as createEmptyLayerInventory,z5 as createConsoleLoggerAdapter,nH as createBunFsAdapter,M6 as createBuilderWorkspaceId,hQ as createAgentGuideService,C4 as connect,y9 as computeContentHash,OU as compareSpecs,__ as cleanArtifacts,d0 as claudeCodeAdapter,v9 as cacheKeyToString,f$ as buildSpec,XW as analyzeWorkspaceDocBlocks,zW as analyzeIntegrity,tL as analyzeGap,_8 as analyzeDeps,gQ as agentGuideService,b1 as agentAdapters,WS as addToRegistry,kO as __moduleLoaderInternals,F9 as WorkspaceStateCacheStorage,cW as VerifyService,m9 as VerificationCacheService,KA as VALID_AUDIENCES,r3 as TestGeneratorService,T4 as SpecCreatorService,h0 as SimpleAgent,z8 as SETUP_TARGET_LABELS,L8 as SETUP_PRESET_LABELS,O8 as SETUP_PRESET_DESCRIPTIONS,Y0 as SETUP_GITIGNORE_PATTERNS,aY as RuleSyncService,mW as RegistryClient,FQ as PrActionService,k0 as OpenAICodexAgent,t4 as MINIMAL_DEPENDENCIES,T9 as InMemoryCacheStorage,r0 as GenericMCPAdapter,D9 as FileSystemCacheStorage,rY as FULL_DEPENDENCIES,DQ as DriftActionService,Y$ as DEFAULT_SPEC_PATTERNS,S$ as DEFAULT_FS_IGNORES,x9 as DEFAULT_CACHE_CONFIG,n0 as CursorCLIAdapter,P0 as CursorAgent,m0 as ClaudeCodeAgent,u0 as ClaudeCodeAdapter,G_ as CI_CHECK_CATEGORY_LABELS,h8 as CHECK_CATEGORY_LABELS,g0 as AgentOrchestrator,o0 as AgentGuideService,X0 as ALL_SETUP_TARGETS,U8 as ALL_SETUP_PRESETS,V_ as ALL_CI_CHECK_CATEGORIES,k8 as ALL_CHECK_CATEGORIES,CW as AIGenerator};
|