rapidkit 0.41.1 → 0.41.3
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/README.md +132 -58
- package/contracts/agent-customization-pack.v1.json +15 -0
- package/contracts/doctor-project-evidence.v1.json +260 -2
- package/contracts/doctor-remediation-plan.v1.json +496 -0
- package/contracts/doctor-workspace-evidence.v1.json +260 -2
- package/contracts/extension-cli-compatibility.v1.json +5 -2
- package/contracts/runtime-command-surface.v1.json +3 -1
- package/contracts/workspace-intelligence/doctor-fix-result.v1.json +11 -1
- package/contracts/workspace-intelligence/fact-freshness.v1.json +58 -0
- package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +24 -0
- package/contracts/workspace-intelligence/workspace-context.v1.json +84 -1
- package/contracts/workspace-intelligence/workspace-intelligence-history.v1.json +6 -2
- package/contracts/workspace-intelligence/workspace-model.v1.json +80 -0
- package/dist/analyze-UTB3PNKM.js +1 -0
- package/dist/autopilot-release-GBH7PIIZ.js +1 -0
- package/dist/{chunk-CKXJR3YT.js → chunk-3CYEVV6H.js} +1 -1
- package/dist/{chunk-RSYUNEH7.js → chunk-42ARJBM7.js} +1 -1
- package/dist/chunk-6UBWN4EE.js +2 -0
- package/dist/chunk-7BEZH5LE.js +2 -0
- package/dist/{chunk-ITJ6RKUW.js → chunk-AM5OJWXF.js} +1 -1
- package/dist/{chunk-KIUSCFHF.js → chunk-C4ASE2DV.js} +1 -1
- package/dist/chunk-COBMOVUK.js +1 -0
- package/dist/{chunk-ELU3G6DQ.js → chunk-DKNVDNT4.js} +1 -1
- package/dist/chunk-GD6VML5K.js +32 -0
- package/dist/chunk-GH674HP5.js +4 -0
- package/dist/chunk-HT3G7HOV.js +78 -0
- package/dist/{chunk-BFEBZABL.js → chunk-KZLRUBQ5.js} +19 -19
- package/dist/chunk-O74N26AD.js +1 -0
- package/dist/chunk-TDSIF42O.js +1 -0
- package/dist/chunk-TSUQQTHI.js +1 -0
- package/dist/chunk-ULIVVMT6.js +1 -0
- package/dist/{chunk-CDPR2YKL.js → chunk-XRGBKUJO.js} +1 -1
- package/dist/chunk-XY3SGMAJ.js +2 -0
- package/dist/{create-RNP5ACQL.js → create-XTKHAYH7.js} +1 -1
- package/dist/doctor-4UQZIELO.js +1 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.js +165 -140
- package/dist/pipeline-ZCJ6NVRC.js +5 -0
- package/dist/{workspace-E554C5SM.js → workspace-VKUBU4M4.js} +1 -1
- package/dist/{workspace-agent-sync-2HRPM5ZD.js → workspace-agent-sync-QJWXK3RT.js} +1 -1
- package/dist/{workspace-context-VJTXW3K4.js → workspace-context-I5OXR6XB.js} +1 -1
- package/dist/workspace-explain-YFKDZRVX.js +1 -0
- package/dist/{workspace-feedback-65NR3EZH.js → workspace-feedback-KCDFF7YS.js} +1 -1
- package/dist/{workspace-foundation-LISDH53T.js → workspace-foundation-V6SLZRBY.js} +1 -1
- package/dist/workspace-history-DSCH7PQZ.js +1 -0
- package/dist/{workspace-intelligence-E3KXEZCM.js → workspace-intelligence-4SGJDZ6H.js} +1 -1
- package/dist/{workspace-marker-IOPQ42A7.js → workspace-marker-HAC7BMEG.js} +1 -1
- package/dist/workspace-mcp-serve-4QN7ZU6C.js +3 -0
- package/dist/workspace-model-R6XYEQZO.js +1 -0
- package/dist/workspace-run-QRT3JJDB.js +1 -0
- package/dist/{workspace-verify-NRYH7RNB.js → workspace-verify-TEQWZOXM.js} +1 -1
- package/dist/{workspace-watch-H2AETGFI.js → workspace-watch-WERGZE5P.js} +1 -1
- package/docs/contracts/ARTIFACT_CATALOG.md +59 -20
- package/docs/contracts/NAMING_AND_COEXISTENCE.md +3 -2
- package/docs/contracts/README.md +12 -0
- package/docs/doctor-command.md +217 -13
- package/package.json +1 -1
- package/scripts/enterprise-package-smoke.mjs +50 -45
- package/dist/analyze-QYHMGLSG.js +0 -1
- package/dist/autopilot-release-AHMQEUFH.js +0 -1
- package/dist/chunk-33LR2QEM.js +0 -2
- package/dist/chunk-46AGNYI7.js +0 -50
- package/dist/chunk-EN6YCX36.js +0 -1
- package/dist/chunk-JW2FSKT3.js +0 -2
- package/dist/chunk-LKX3L7TE.js +0 -2
- package/dist/chunk-RV6HBTFC.js +0 -2
- package/dist/chunk-TJN7G2MA.js +0 -1
- package/dist/chunk-UQR6G7KH.js +0 -32
- package/dist/chunk-VKLL63TL.js +0 -1
- package/dist/chunk-VMJA36WD.js +0 -1
- package/dist/doctor-XM6QDTDC.js +0 -1
- package/dist/pipeline-DH6Z47O4.js +0 -5
- package/dist/workspace-explain-3WSJLIJ6.js +0 -1
- package/dist/workspace-history-VPDADQKG.js +0 -1
- package/dist/workspace-mcp-serve-RFYDCA2L.js +0 -3
- package/dist/workspace-model-YL7W3573.js +0 -1
- package/dist/workspace-run-GCIQD73R.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-GH674HP5.js';import {a as a$2}from'./chunk-KMUWWZRT.js';import {a as a$1,e}from'./chunk-64RTZBHU.js';import l from'chalk';import Y from'fs';import y from'path';import {execa}from'execa';var Z="autopilot-release-last-run.json",ee="autopilot-release.json";function $(s){try{return JSON.parse(s)}catch{return null}}function ge(s){let t=y.resolve(s),o=a$2(t);if(!o)throw new Error("No RapidKit workspace found in current directory or parents");return o}async function b(s,t){let o=process.argv[1];if(!o)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for autopilot execution.",crashed:true};try{let a=await execa(process.execPath,[o,...s],{cwd:t,reject:false,env:{...process.env,RAPIDKIT_AUTOPILOT_CHILD:"1"}});return {exitCode:Number(a.exitCode??1),stdout:a.stdout,stderr:a.stderr,crashed:false}}catch(a){return {exitCode:1,stdout:"",stderr:a instanceof Error?a.message:String(a),crashed:true}}}function te(s){let t=s.toLowerCase();return t==="pass"?"pass":t==="warn"?"warn":t==="fail"?"fail":"warn"}function se(s){return s.summary.failed>0||s.gates.results.some(t=>t.status==="fail")?"fail":s.gates.results.some(t=>t.status==="warn")?"warn":"pass"}function we(s){let t=s.filter(a=>a.status!=="skipped");if(t.length===0)return 100;let o=t.reduce((a,e)=>e.status==="pass"?a+1:e.status==="warn"?a+.6:a,0);return Math.round(o/t.length*100)}function he(s){return s.executionError?["Re-run: npx rapidkit autopilot release --mode audit --json","Inspect .rapidkit/reports/autopilot-release-last-run.json for execution failure details"]:s.blockers.length>0?["Run: npx rapidkit doctor workspace --plan","Run: npx rapidkit readiness --json --strict","Run: npx rapidkit workspace run test --affected --strict"]:s.hasWarnings&&s.mode!=="enforce"?["Review warning-level findings in autopilot report","Optionally run: npx rapidkit autopilot release --mode safe-fix"]:["Workspace is release-ready based on current autopilot policy"]}async function U(s,t){await Y.promises.mkdir(y.dirname(s),{recursive:true}),await Y.promises.writeFile(s,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,"utf-8");}async function je(s){let t=ge(s.workspacePath),o=s.mode,a$2=[],e$1=[],F,B,C,O,J,G=0,f=false,I=0,T=0,D=-1,N=-1,c="skipped",p="skipped",re=o==="enforce"?["doctor","workspace","--json","--strict"]:["doctor","workspace","--json","--ci"];if(s.skipPipelineStages)a$2.push({name:"doctor-workspace",status:"skipped",durationMs:0,summary:"doctor stage skipped (pipeline already executed)"},{name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped (pipeline already executed)"},{name:"readiness",status:"skipped",durationMs:0,summary:"readiness stage skipped (pipeline already executed)"});else {let r=Date.now(),i=await b([...re],t),m=Date.now()-r;if(c="pass",i.crashed)c="fail",f=true,e$1.push(`doctor workspace execution error: ${i.stderr||"unknown error"}`);else if(i.exitCode===1)c="fail",e$1.push("doctor workspace command failed or reported errors");else if(i.exitCode===2)c="warn",e$1.push("doctor workspace reported warnings");else if(i.exitCode!==0)c="fail",e$1.push("doctor workspace command failed");else {let d=$(i.stdout),j=d&&d.healthScore&&typeof d.healthScore=="object"?d.healthScore:{},k=Number(j.errors??0),E=Number(j.warnings??0);Number.isFinite(k)&&k>0?(c="fail",e$1.push(`doctor workspace reports ${k} error(s)`)):Number.isFinite(E)&&E>0&&(c="warn");}D=a$2.push({name:"doctor-workspace",status:c,durationMs:m,summary:c==="pass"?"doctor workspace passed":c==="warn"?"doctor workspace reported warnings":"doctor workspace reported errors"})-1,o==="enforce"&&c==="warn"&&e$1.push("doctor workspace reported warnings under enforce mode");let g=Date.now(),w=await b(["analyze","--json"],t),v=Date.now()-g;B=y.join(t,".rapidkit","reports","analyze-last-run.json");let n="pass";if(w.crashed)n="fail",f=true,e$1.push(`analyze execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)n=w.exitCode===2?"warn":"fail",e$1.push(w.exitCode===2?"analyze reported needs-attention verdict":"analyze command failed or reported blocked verdict");else {let d=$(w.stdout),j=d&&d.summary&&typeof d.summary=="object"?d.summary:{},k=String(j.verdict??"ready");k==="blocked"?(n="fail",e$1.push("analyze reported blocked verdict")):k==="needs-attention"&&(n="warn");}a$2.push({name:"analyze",status:n,durationMs:v,summary:n==="pass"?"analyze passed":n==="warn"?"analyze reported needs-attention":"analyze reported blocked verdict"}),o==="enforce"&&n==="warn"&&e$1.push("analyze reported warnings under enforce mode");let P=Date.now(),h=await b(["readiness","--json"],t),R=Date.now()-P;if(p="fail",h.crashed)p="fail",f=true,e$1.push(`readiness execution error: ${h.stderr||"unknown error"}`);else if(h.exitCode!==0)p="fail",e$1.push("readiness command failed");else {let d=$(h.stdout),j=String(d?.overallStatus??"fail");if(p=te(j),typeof d?.evidencePath=="string"&&d.evidencePath.trim().length>0&&(F=d.evidencePath),p==="fail"){let k=Array.isArray(d?.blockingReasons)?d?.blockingReasons.filter(E=>typeof E=="string"):[];k.length>0?e$1.push(...k.map(E=>`readiness: ${E}`)):e$1.push("readiness overall status is fail");}}N=a$2.push({name:"readiness",status:p,durationMs:R,summary:`readiness overall status is ${p}`})-1,o==="enforce"&&p==="warn"&&e$1.push("readiness reported warnings under enforce mode");}let ae=Date.now(),M=await b(["doctor","workspace","--plan","--json"],t),oe=Date.now()-ae,S="warn";if(M.crashed)S="fail",f=true,e$1.push(`doctor remediation plan execution error: ${M.stderr||"unknown error"}`);else if(M.exitCode!==0)S="fail",e$1.push("doctor remediation plan command failed");else {let r=$(M.stdout),i=r&&r.remediationPlan&&typeof r.remediationPlan=="object"?r.remediationPlan:null,m=Number(i?.totalSteps??0),g=Number(i?.executableSteps??0);Number.isFinite(m)&&m>0&&(I=m),Number.isFinite(g)&&g>0&&(T=g),Number.isFinite(m)&&m===0?S="pass":S="warn";}if(a$2.push({name:"remediation-plan",status:S,durationMs:oe,summary:S==="pass"?"no remediation steps required":"remediation steps available"}),o==="enforce"&&S==="warn"&&e$1.push("remediation plan has pending steps under enforce mode"),o==="safe-fix"){let r=Date.now(),i=await b(["doctor","workspace","--apply"],t),m=Date.now()-r,g=i.crashed||i.exitCode!==0?"fail":"pass";if(i.crashed)f=true,e$1.push(`doctor remediation apply execution error: ${i.stderr||"unknown error"}`);else if(g==="fail")e$1.push("doctor remediation apply failed");else {G=T>0?T:I>0?I:1;let w=await b(["doctor","workspace","--json"],t);if(w.crashed)c="fail",f=true,e$1.push(`post-apply doctor execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)c="fail",e$1.push("post-apply doctor workspace command failed");else {let n=$(w.stdout),P=n&&n.healthScore&&typeof n.healthScore=="object"?n.healthScore:{},h=Number(P.errors??0),R=Number(P.warnings??0);Number.isFinite(h)&&h>0?(c="fail",e$1.push(`post-apply doctor reports ${h} error(s)`)):Number.isFinite(R)&&R>0?c="warn":c="pass";}D>=0&&(a$2[D].status=c,a$2[D].summary=`doctor workspace post-apply status is ${c}`);let v=await b(["readiness","--json"],t);if(v.crashed)p="fail",f=true,e$1.push(`post-apply readiness execution error: ${v.stderr||"unknown error"}`);else if(v.exitCode!==0)p="fail",e$1.push("post-apply readiness command failed");else {let n=$(v.stdout),P=String(n?.overallStatus??"fail");if(p=te(P),typeof n?.evidencePath=="string"&&n.evidencePath.trim().length>0&&(F=n.evidencePath),p==="fail"){let h=Array.isArray(n?.blockingReasons)?n?.blockingReasons.filter(R=>typeof R=="string"):[];h.length>0?e$1.push(...h.map(R=>`post-apply readiness: ${R}`)):e$1.push("post-apply readiness overall status is fail");}}N>=0&&(a$2[N].status=p,a$2[N].summary=`readiness post-apply overall status is ${p}`);}a$2.push({name:"remediation-apply",status:g,durationMs:m,summary:g==="pass"?"safe remediation apply completed":"safe remediation apply failed"});}else a$2.push({name:"remediation-apply",status:"skipped",durationMs:0,summary:"remediation apply is skipped for this mode"});let ne=Date.now(),x="pass",A="workspace test/build completed for selected projects";try{let r=await a({workspacePath:t,stage:"test",affected:true,since:s.since,parallel:s.parallel,maxWorkers:s.maxWorkers,strict:true,json:true,enforceGates:false});C=y.join(t,".rapidkit","reports",a$1),await e(t,r),O=C;let i=se(r);if(i==="fail")x="fail",A="workspace test stage failed for selected projects",e$1.push("workspace run test failed for selected projects");else {i==="warn"&&(x="warn",A="workspace test stage completed with warnings",o==="enforce"&&e$1.push("workspace run test reported warnings under enforce mode"));let m=await a({workspacePath:t,stage:"build",affected:true,since:s.since,parallel:s.parallel,maxWorkers:s.maxWorkers,strict:true,json:true,enforceGates:false});await e(t,m),J=C;let g=se(m);g==="fail"?(x="fail",A="workspace build stage failed for selected projects",e$1.push("workspace run build failed for selected projects")):g==="warn"&&(x="warn",A="workspace test/build completed with warnings",o==="enforce"&&e$1.push("workspace run test/build reported warnings under enforce mode"));}}catch(r){x="fail",A="workspace test/build orchestration failed",f=true,e$1.push(`workspace run orchestration error: ${r instanceof Error?r.message:String(r)}`);}let ie=Date.now()-ne;a$2.push({name:"workspace-run-test-build",status:x,durationMs:ie,summary:A});let z=a$2.filter(r=>r.status==="warn").length,le=a$2.filter(r=>r.status==="fail").length,L=o==="enforce"?a$2.some(r=>r.status==="warn"||r.status==="fail"):le>0,W=[...new Set(e$1)],ce=f||L?Math.max(1,W.length):0,de=we(a$2),pe=f||L?"blocked":z>0?"partial":"approved",ue=f?3:L?1:z>0?2:0,fe=he({mode:o,executionError:f,blockers:W,hasWarnings:z>0}),V=y.join(t,".rapidkit","reports"),H=y.join(V,Z),q=y.join(V,ee),u={schemaVersion:"autopilot-release-v1",generatedAt:new Date().toISOString(),workspacePath:t,mode:o,summary:{releaseScore:de,verdict:pe,blockers:ce,warnings:z,safeFixesApplied:G,manualActions:W.length,exitCode:ue},stages:a$2,blockingReasons:W,nextActions:fe,artifacts:{reportPath:H,aliasEvidencePath:q,analyzeEvidencePath:B,readinessEvidencePath:F,workspaceRunEvidencePath:C,workspaceRunTestPath:O,workspaceRunBuildPath:J},enterpriseControls:{jsonReady:true,evidencePath:`.rapidkit/reports/${Z}`,aliasEvidencePath:`.rapidkit/reports/${ee}`}};if(await U(H,u),await U(q,u),s.output&&await U(y.resolve(s.output),u),!s.json){console.log(l.bold.cyan(`
|
|
3
3
|
\u{1F680} RapidKit Autopilot Release
|
|
4
4
|
`)),console.log(l.bold(`Workspace: ${l.cyan(y.basename(t))}`)),console.log(l.gray(`Path: ${t}`)),console.log(l.white(`Mode: ${o}`)),console.log(l.white(`Verdict: ${u.summary.verdict==="approved"?l.green("approved"):u.summary.verdict==="partial"?l.yellow("partial"):l.red("blocked")}`)),console.log(l.white(`Release score: ${u.summary.releaseScore}`));for(let r of u.stages){let i=r.status==="pass"?l.green("PASS"):r.status==="warn"?l.yellow("WARN"):r.status==="skipped"?l.gray("SKIP"):l.red("FAIL");console.log(` - ${r.name}: ${i} ${r.summary} (${r.durationMs}ms)`);}if(u.blockingReasons.length>0){console.log(l.bold.red(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {k,e as e$1}from'./chunk-JU3VNLTY.js';import {b as b$2}from'./chunk-CDCYRBAY.js';import {e,g,f as f$1,b as b$4,c as c$1,d as d$1}from'./chunk-E5ZVQL3C.js';import {a,d,b as b$1}from'./chunk-
|
|
1
|
+
import {k,e as e$1}from'./chunk-JU3VNLTY.js';import {b as b$2}from'./chunk-CDCYRBAY.js';import {e,g,f as f$1,b as b$4,c as c$1,d as d$1}from'./chunk-E5ZVQL3C.js';import {a,d,b as b$1}from'./chunk-7BEZH5LE.js';import {b}from'./chunk-Q2KZIBV4.js';import {f,c,e as e$2}from'./chunk-OLDPVVSV.js';import {b as b$3,j,i,l,h,q}from'./chunk-WRMCPKGA.js';import {promises}from'fs';import*as P from'fs-extra';import m from'path';import t from'chalk';import {execa}from'execa';async function H(e,o={}){let n=m.resolve(e),r=o.workspaceName??m.basename(n);try{let{registerWorkspace:a}=await import('./workspace-VKUBU4M4.js');await a(n,r);}catch(a){o.silent||console.warn(t.gray(`Note: Could not register workspace in shared registry: ${a?.message??a}`));}try{let{syncWorkspaceContract:a}=await import('./workspace-contract-OO4GMENV.js'),c=await a({workspacePath:n});if(o.silent||console.log(t.gray(`\u2139\uFE0F Workspace intelligence synced (contract + registry summary, ${c.contract.projects.length} project(s)).`)),!o.silent&&c.verification.status!=="passed"){console.log(t.yellow("\u26A0\uFE0F Workspace contract verification reported issues."));for(let d of c.verification.violations)console.log(t.gray(` Violation: ${d}`));console.log(t.white(" Next: npx rapidkit workspace contract inspect"));}}catch(a){o.silent||console.warn(t.gray(`Note: Could not sync workspace intelligence layer: ${a?.message??a}`));}}function S(){return h()}async function B(e,o,n,r){let a=d(o,b(),n);r&&(a.metadata||(a.metadata={}),a.metadata.python={version:r}),await b$1(e,a);}async function z(e){await P.outputFile(m.join(e,".gitignore"),`.venv/
|
|
2
2
|
__pycache__/
|
|
3
3
|
*.pyc
|
|
4
4
|
.env
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {n,k as k$1,j}from'./chunk-TSUQQTHI.js';import {a as a$1}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {a}from'./chunk-3PTJID76.js';import de from'crypto';import m from'path';import y from'fs-extra';import {spawnSync}from'child_process';function F(e,t){let r=spawnSync("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return r.status!==0?{ok:false,stdout:""}:{ok:true,stdout:(r.stdout??"").trim()}}function pe(e){let t=[],r=[],n=[];for(let c of e.split(`
|
|
2
|
+
`)){if(!c.trim())continue;let a=c.slice(0,2),i=c.slice(3).trim();if(i){if(a==="??"){r.push(i);continue}a.includes("D")&&n.push(i),t.push(i);}}return {changedFiles:[...new Set(t)].sort(),untrackedFiles:[...new Set(r)].sort(),deletedFiles:[...new Set(n)].sort()}}function L(e,t){let r={available:false,dirty:false,changedFiles:[],untrackedFiles:[],deletedFiles:[]},n=F(e,["rev-parse","--is-inside-work-tree"]);if(!n.ok||n.stdout!=="true")return r;let c=F(e,["rev-parse","--abbrev-ref","HEAD"]),a=F(e,["rev-parse","HEAD"]),i=F(e,["status","--porcelain=v1","--untracked-files=all"]),p=pe(i.stdout),f=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:c.ok?c.stdout:void 0,commit:a.ok?a.stdout:void 0,ref:t?.ref,dirty:f,changedFiles:p.changedFiles,untrackedFiles:p.untrackedFiles,deletedFiles:p.deletedFiles}}var X="workspace-model-snapshot.v1",V="workspace-model-diff.v1",$=".rapidkit/reports/workspace-model-snapshot.json",Z=".rapidkit/reports/workspace-model-diff-last-run.json",le="workspace-impact.v1",fe=".rapidkit/reports/workspace-impact-last-run.json";function ee(e){let t=e.trim().toLowerCase();return t==="git"||t.startsWith("git:")}function me(e){let t=e.trim();return t.toLowerCase()==="git"?"HEAD":t.toLowerCase().startsWith("git:")&&t.slice(4).trim()||"HEAD"}function _(e){if(Array.isArray(e))return e.map(t=>_(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=_(e[r]);return t}return e}function k(e){return JSON.stringify(_(e))}function ue(e){return e.facts?.map(t=>({...t,freshness:{schemaVersion:t.freshness.schemaVersion,kind:t.freshness.kind,category:t.freshness.category,ttlSeconds:t.freshness.ttlSeconds,verifyBeforeUse:t.freshness.verifyBeforeUse,sourceArtifact:t.freshness.sourceArtifact,sourcePath:t.freshness.sourcePath,inputsHash:t.freshness.inputsHash,reason:t.freshness.reason}}))}function E(e){let{runId:t,...r}=e,n={...r,generatedAt:"<ignored>",graph:e.graph?{...e.graph,generatedAt:"<ignored>"}:void 0,facts:ue(e),factFreshness:e.factFreshness?{schemaVersion:e.factFreshness.schemaVersion,totalFacts:e.factFreshness.totalFacts,liveFacts:e.factFreshness.liveFacts,verifyBeforeUseFacts:e.factFreshness.verifyBeforeUseFacts,byKind:e.factFreshness.byKind,byCategory:e.factFreshness.byCategory}:void 0,validation:e.validation?{...e.validation,issues:e.validation.issues.map(c=>({...c})).sort((c,a)=>{let i=`${c.severity}:${c.code}:${c.target}:${c.message}`,p=`${a.severity}:${a.code}:${a.target}:${a.message}`;return i.localeCompare(p)})}:void 0};return de.createHash("sha256").update(k(n)).digest("hex")}function te(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ge(e){let t=await y.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace model input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion===X){let n=r;if(!n.model||n.model.schemaVersion!==j)throw new Error(`Invalid workspace model snapshot: ${e}`);return {model:n.model,hash:n.modelHash||E(n.model)}}if(r.schemaVersion===j){let n=r;return {model:n,hash:E(n)}}throw r.schemaVersion===V?new Error(`workspace diff --from received a diff report (${m.basename(e)}). Use a workspace model snapshot or model report as baseline, e.g. ${$}. To analyze an existing diff report, run: npx rapidkit workspace impact --from ${m.basename(e)} --json`):new Error(`Unsupported workspace model input schema: ${String(r.schemaVersion)}`)}async function ke(e){let t=await y.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace diff input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==V)return null;let n=r;if(!n.currentModel||n.currentModel.schemaVersion!==j||!n.summary||!Array.isArray(n.changes))throw new Error(`Invalid workspace model diff report: ${e}`);return n}async function Ne(e){let t=e.model??await n({workspacePath:e.workspacePath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {schemaVersion:X,generatedAt:(e.now??new Date).toISOString(),modelHash:E(t),modelRef:k$1,model:t}}async function Be(e,t){let r=m.join(t,$);return await y.ensureDir(m.dirname(r)),await y.writeJson(r,a(e),{spaces:2}),r}function A(e){return {name:e.name,path:e.path,kind:e.kind,runtime:e.runtime,framework:e.framework,generator:e.generator,supportTier:e.supportTier,commands:e.commands,importantFiles:e.importantFiles}}function h(e,t){e.push(t);}function he(e,t){let r=[],n=["name","profile","type"],c=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let a of n){let i=e.workspace[a],p=t.workspace[a];k(i)!==k(p)&&h(r,{type:"workspace.changed",severity:"info",target:`workspace.${a}`,message:`Workspace metadata field changed: ${String(a)}`,before:i,after:p});}for(let a of c){let i=e.identity[a],p=t.identity[a];k(i)!==k(p)&&h(r,{type:"workspace.changed",severity:"info",target:`identity.${a}`,message:`Workspace identity field changed: ${String(a)}`,before:i,after:p});}return k(e.policies)!==k(t.policies)&&h(r,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),k(e.evidence)!==k(t.evidence)&&h(r,{type:"workspace.changed",severity:"info",target:"evidence",message:"Workspace evidence summary changed.",before:e.evidence,after:t.evidence}),k(e.discovery)!==k(t.discovery)&&h(r,{type:"workspace.changed",severity:"info",target:"discovery",message:"Workspace discovery settings changed.",before:e.discovery,after:t.discovery}),e.contracts.exists!==t.contracts.exists&&h(r,{type:"workspace.changed",severity:t.contracts.exists?"info":"warning",target:t.contracts.workspaceContractPath,message:"Workspace contract presence changed.",before:e.contracts.exists,after:t.contracts.exists}),r}function we(e,t){let r=e.validation??null,n=t.validation??null;return k(r)===k(n)?[]:[{type:"validation.changed",severity:n?.status==="failed"?"critical":"warning",target:"validation",message:"Workspace model validation changed.",before:r,after:n}]}function ye(e,t){let r=[],n=new Map(e.projects.map(a=>[a.path,a])),c=new Map(t.projects.map(a=>[a.path,a]));for(let[a,i]of c.entries()){let p=n.get(a);if(!p){h(r,{type:"project.added",severity:"info",target:a,message:`Project added: ${i.name}`,after:A(i)});continue}let f=A(p),l=A(i);if(k(f)!==k(l)){let g=p.runtime!==i.runtime||p.framework!==i.framework;h(r,{type:"project.changed",severity:g?"warning":"info",target:a,message:`Project changed: ${i.name}`,before:f,after:l});}}for(let[a,i]of n.entries())c.has(a)||h(r,{type:"project.removed",severity:"warning",target:a,message:`Project removed: ${i.name}`,before:A(i)});return r.sort((a,i)=>`${a.type}:${a.target}`.localeCompare(`${i.type}:${i.target}`))}async function We(e){let t=m.resolve(e.workspacePath),r=ee(e.fromPath),n$1=r?me(e.fromPath):void 0,c=e.fromPath;if(r){let u=m.join(t,$);if(!await y.pathExists(u))throw new Error("Git-aware workspace diff requires an existing snapshot at .rapidkit/reports/workspace-model-snapshot.json. Run: npx rapidkit workspace snapshot --json");c=$;}let a=te(t,c),i=await ge(a),p=e.model??await n({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),f=E(p),l=[...he(i.model,p),...ye(i.model,p),...we(i.model,p)],g;e.includeGitObservation!==false&&(g=e.gitObservation??L(t,{ref:n$1}),g.available&&Me(l,g,p));let b=l.filter(u=>u.type.startsWith("git.")).length,C=i.hash!==f,W=r?`git:${n$1??"HEAD"}`:m.relative(t,a).split(m.sep).join("/");return {schemaVersion:V,generatedAt:(e.now??new Date).toISOString(),fromRef:W,toRef:k$1,fromHash:i.hash,toHash:f,summary:{changed:C||b>0,addedProjects:l.filter(u=>u.type==="project.added").length,removedProjects:l.filter(u=>u.type==="project.removed").length,changedProjects:l.filter(u=>u.type==="project.changed").length,workspaceChanges:l.filter(u=>u.type==="workspace.changed").length,validationChanges:l.filter(u=>u.type==="validation.changed").length,gitChangedFiles:b},git:g?.available?Pe(g,n$1):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p}}async function Ke(e,t){let r=m.join(t,Z);return await y.ensureDir(m.dirname(r)),await y.writeJson(r,a(e),{spaces:2}),r}function P(e){return {none:0,low:1,medium:2,high:3,critical:4}[e]}function J(e){return e.reduce((t,r)=>P(r)>P(t)?r:t,"none")}var T=["none","low","medium","high","critical"];function ve(e){let t=Math.max(1,P(e)-1);return T[t]}function be(e){let t=Math.min(T.length-1,P(e)+1);return T[t]}function U(e){return e.join(" ")}function w(e,t,r,n){return {id:e,label:t,scope:n.scope,project:n.project,display:U(["npx","rapidkit",...r]),execute:U(["npx","--yes","--package","rapidkit","rapidkit",...r]),required:n.required!==false}}function Y(e){let t=`project:${e.name}`,r=e.commands.fleetStages;return [w(`project.${e.name}.init`,`Run init for ${e.name}`,["workspace","run","init","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("init")}),w(`project.${e.name}.test`,`Run tests for ${e.name}`,["workspace","run","test","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("test")}),w(`project.${e.name}.build`,`Run build for ${e.name}`,["workspace","run","build","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("build")}),w(`project.${e.name}.start`,`Run start for ${e.name}`,["workspace","run","start","--scope",t,"--json"],{scope:"project",project:e.name,required:r.includes("start")})]}function D(){return [w("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),w("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),w("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),w("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),w("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false}),w("workspace.doctor-fix","Verify doctor fix result",["doctor","workspace","--fix","--json"],{scope:"workspace",required:false})]}function je(e,t){let r=t.split(m.sep).join("/");return e.projects.filter(c=>{let a=c.path.split(m.sep).join("/");return r===a||r.startsWith(`${a}/`)}).sort((c,a)=>a.path.length-c.path.length)[0]}function Me(e,t,r){let n=new Set(e.map(a=>a.target)),c=(a,i)=>{let p=i.split(m.sep).join("/"),f=`git:${p}`;if(n.has(f))return;let l=je(r,p),g=l?`${l.name} (${l.path})`:"workspace";h(e,{type:a,severity:a==="git.deleted"?"warning":"info",target:f,message:`Git ${a==="git.untracked"?"untracked":a==="git.deleted"?"deleted":"changed"} file affects ${g}: ${p}`,after:{path:p,project:l?.name,projectPath:l?.path}}),n.add(f);};for(let a of t.changedFiles)c("git.file.changed",a);for(let a of t.untrackedFiles)c("git.untracked",a);for(let a of t.deletedFiles)c("git.deleted",a);}function Pe(e,t){return {available:true,ref:t??e.ref,branch:e.branch,commit:e.commit,dirty:e.dirty,changedFiles:e.changedFiles.length,untrackedFiles:e.untrackedFiles.length,deletedFiles:e.deletedFiles.length}}function Ie(e){let t=new Set,r=[];for(let n of e){let c=`${n.scope}:${n.project??""}:${n.display}`;t.has(c)||(t.add(c),r.push(n));}return r}function Ce(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function Re(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function Oe(e){return e.affectedProjects>0||e.projectCount>0||!e.changes.every(r=>r.severity==="critical"?false:r.type.startsWith("git.")||r.type==="validation.changed")?e.risk:P(e.risk)>=P("high")||e.risk==="medium"?"low":e.risk}function Q(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return [t.name,t.path,m.basename(t.path),t.absolutePath].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim().toLowerCase()).includes(r)}function Se(e){if(!e.changed)return {headline:"No workspace model impact detected.",bullets:["The current workspace model matches the provided snapshot/report."],unsafeAssumptions:["Do not claim runtime verification passed unless a report exists."]};let t=e.affectedProjects.map(r=>r.project?.name??r.target);return {headline:`Workspace impact risk: ${e.risk}.`,bullets:[`Affected projects: ${t.length?t.join(", "):"none"}.`,`Workspace-level items: ${e.workspaceImpact.length}.`,"Use the verification plan before recommending apply, rollback, or release actions."],unsafeAssumptions:["Do not infer test/build success from impact alone.","Do not apply fixes without project scope and verification evidence.","Use display commands for users and execute commands for automation."]}}async function qe(e){let t=m.resolve(e.workspacePath),r=ee(e.fromPath),n=e.diff;if(!n&&!r){let s=te(t,e.fromPath);n=await ke(s)??void 0;}n||(n=await We({workspacePath:t,fromPath:e.fromPath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,includeGitObservation:e.includeGitObservation,gitObservation:e.gitObservation,now:e.now,model:e.model}));let c$1=new Map(n.currentModel.projects.map(s=>[s.path,s])),a=new Map(n.currentModel.projects.map(s=>[s.name,s])),i=n.changes.filter(s=>s.type.startsWith("project.")),p=new Map;for(let s of i){let d=(c$1.get(s.target)??(typeof s.before?.name=="string"?a.get(s.before.name):void 0))?.path??s.target,v=p.get(d)??[];v.push(s),p.set(d,v);}let f=[];for(let[s,o]of p.entries()){let d=c$1.get(s);if(d&&!Q(e.scope,d))continue;let v=J(o.map(Ce)),R=d?.name??(typeof o[0]?.before?.name=="string"?String(o[0].before.name):s);f.push({id:`project:${R}`,scope:"project",target:s,title:`Project impact: ${R}`,summary:o.map(j=>j.message).join(" "),risk:v,reasons:o.map(j=>`${j.type}: ${j.message}`),project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?Y(d):D()});}let l=n.currentModel.graph,g=l?a$1(l):void 0,b=new Set(f.map(s=>s.project?.name).filter(s=>typeof s=="string")),C=new Map;for(let s of f)if(s.project?.name){let o=g?.byId.get(s.project.name);o&&(s.centrality={fanIn:o.fanIn,fanOut:o.fanOut,reach:o.reach,betweenness:o.betweenness,isHotspot:o.isHotspot},o.isHotspot&&(s.risk=be(s.risk),s.reasons=[...s.reasons,`graph.hotspot: critical-path project with ${o.reach} transitive dependent(s); risk escalated.`])),s.origin="direct",s.distance=0,C.set(s.project.name,s.risk);}let W=[],u=0;if(l&&b.size>0){let s=c(l,b);for(let o of s.values()){if(o.distance===0||b.has(o.id))continue;let d=a.get(o.id);if(d&&!Q(e.scope,d))continue;let v=o.path[0],R=o.path[o.path.length-2]??v,j=C.get(v)??"medium",ae=ve(j),M=g?.byId.get(o.id);u=Math.max(u,o.distance),W.push({id:`transitive:${o.id}`,scope:"project",target:d?.path??o.id,title:`Transitive impact: ${o.id}`,summary:`Depends on changed project ${v}${o.via?` via ${o.via}`:""} (distance ${o.distance}).`,risk:ae,reasons:[`graph.dependent: depends on ${R}${o.via?` via ${o.via}`:""} (path ${o.path.join(" -> ")})`],project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?Y(d):D(),origin:"transitive",distance:o.distance,path:o.path,via:o.via,...M?{centrality:{fanIn:M.fanIn,fanOut:M.fanOut,reach:M.reach,betweenness:M.betweenness,isHotspot:M.isHotspot}}:{}});}}W.sort((s,o)=>s.target.localeCompare(o.target));let re=g?g.hotspots.flatMap(s=>{let o=g.byId.get(s);return o?[{project:s,fanIn:o.fanIn,fanOut:o.fanOut,reach:o.reach,betweenness:o.betweenness}]:[]}):[],ne=n.changes.filter(s=>!s.type.startsWith("project.")),G=n.currentModel.summary?.projectCount??n.currentModel.projects.length,I=ne.map(s=>({id:`workspace:${s.target}`,scope:"workspace",target:s.target,title:`Workspace impact: ${s.target}`,summary:s.message,risk:Re(s,{projectCount:G}),reasons:[`${s.type}: ${s.message}`],verification:D()})),N=Ie([...f.flatMap(s=>s.verification),...W.flatMap(s=>s.verification),...I.flatMap(s=>s.verification),...n.summary.changed?D():[]]).filter(s=>s.required),se=J([...f.map(s=>s.risk),...W.map(s=>s.risk),...I.map(s=>s.risk)]),B=Oe({risk:se,affectedProjects:f.length,projectCount:G,changes:n.changes}),K={changed:n.summary.changed,risk:B,affectedProjects:f.length,workspaceItems:I.length,recommendedCommands:N.length,blastRadius:{directlyAffected:f.length,transitivelyAffected:W.length,maxDistance:u,graphEdges:l?.edges.length??0}};return {schemaVersion:le,generatedAt:(e.now??new Date).toISOString(),fromRef:n.fromRef,diffRef:Z,workspace:{name:n.currentModel.workspace.name,profile:n.currentModel.workspace.profile,type:n.currentModel.workspace.type},summary:K,affectedProjects:f.sort((s,o)=>s.target.localeCompare(o.target)),transitiveImpact:W,criticalPathHotspots:re,workspaceImpact:I.sort((s,o)=>s.target.localeCompare(o.target)),verificationPlan:N,agentBrief:Se({changed:K.changed,risk:B,affectedProjects:f,workspaceImpact:I}),diff:n}}async function ze(e,t){let r=m.join(t,fe);return await y.ensureDir(m.dirname(r)),await y.writeJson(r,a(e),{spaces:2}),r}export{X as a,V as b,$ as c,Z as d,le as e,fe as f,ee as g,me as h,Ne as i,Be as j,We as k,Ke as l,D as m,qe as n,ze as o};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import r from'fs-extra';import o from'path';async function i(a){let t=o.join(a,".rapidkit-workspace");try{if(await r.pathExists(t))return await r.readJson(t)}catch{return null}return null}async function s(a,t){let e=o.join(a,".rapidkit-workspace"),n=await i(a);n?.metadata&&(t.metadata={...n.metadata,...t.metadata}),await r.outputFile(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
`,"utf-8");}async function m(a,t){let e=await i(a);return e?(e.metadata={...e.metadata,...t,vscode:t.vscode?{...e.metadata?.vscode,...t.vscode}:e.metadata?.vscode,npm:t.npm?{...e.metadata?.npm,...t.npm}:e.metadata?.npm,python:t.python?{...e.metadata?.python,...t.python}:e.metadata?.python},await s(a,e),true):false}function u(a,t,e){return {signature:"RAPIDKIT_WORKSPACE",createdBy:"rapidkit-npm",version:t,createdAt:new Date().toISOString(),name:a,metadata:{npm:{packageVersion:t,installMethod:e,lastUsedAt:new Date().toISOString()}}}}function g(a){if(!a||typeof a!="object")return false;let t=a;return t.signature==="RAPIDKIT_WORKSPACE"&&typeof t.createdBy=="string"&&typeof t.version=="string"&&typeof t.createdAt=="string"&&typeof t.name=="string"}export{i as a,s as b,m as c,u as d,g as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a,b}from'./chunk-KMUWWZRT.js';import {f,e}from'./chunk-PCXSTKZ5.js';import {c as c$1}from'./chunk-NFUXULIF.js';import {a as a$1,b as b$1,d as d$1,c,f as f$1}from'./chunk-YBS2HGO3.js';import u from'chalk';import d from'fs';import h from'fs-extra';import l from'path';var $="release-readiness-v1";function I(t,e){let a=l.resolve(t);if(!b(a))return a;let s=l.join(e,".rapidkit","workspace.contract.json");if(d.existsSync(s))try{let i=JSON.parse(d.readFileSync(s,"utf-8")),n=Array.isArray(i.projects)?i.projects:[];for(let c of n){let f=p(c),g=typeof f.relativePath=="string"?f.relativePath.trim():"";if(g)return l.join(e,g)}}catch{}let r=x(e),o=Array.isArray(r.payload?.projects)?r.payload.projects:[];for(let i of o){let n=p(i),c=typeof n.path=="string"?n.path.trim():"";if(c)return l.resolve(c)}return a}function V(t){let e=a$1(t);return b$1(e,t)?"go":d$1(e,t)?"java":c(e,t)?"node":f$1(e,t)?"python":"unknown"}function O(t,e){if(!d.existsSync(t))return null;let a=d.readdirSync(t).filter(s=>s.endsWith(".json")&&e.some(r=>r.test(s))).map(s=>l.join(t,s));return a.length===0?null:(a.sort((s,r)=>d.statSync(r).mtimeMs-d.statSync(s).mtimeMs),a[0])}function p(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}async function z(t){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:a}=await import('./workspace-registry-summary-X5WRUU3T.js'),s=await e(t);return s?s.projectCount:(await a(t)).summary.projectCount}function L(t,e,a){let s=l.join(t,".rapidkit","toolchain.lock");if(!d.existsSync(s))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run rapidkit bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:s};try{let r=JSON.parse(d.readFileSync(s,"utf-8")),o=p(r.runtime),n=["python","node","go","java"].filter(c=>{let f=p(o[c]);return typeof f.version=="string"&&f.version.trim().length>0});if(n.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via rapidkit setup <runtime> and re-run bootstrap."],evidencePath:s};if(e!=="unknown"){let c=p(o[e]);if(typeof c.version!="string"||c.version.trim().length===0)return {gate:"env",status:"fail",summary:`${a?.hasRegisteredProjects?"Project runtime":"Workspace"} (${e}) is not pinned in toolchain.lock`,details:[`Run rapidkit setup ${e} and rapidkit bootstrap to lock ${e} for this workspace.`],evidencePath:s}}return {gate:"env",status:"pass",summary:`Pinned runtimes: ${n.join(", ")}`,details:[],evidencePath:s}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with rapidkit bootstrap."],evidencePath:s}}}function x(t){let e=l.join(t,".rapidkit","reports","doctor-last-run.json");if(!d.existsSync(e))return {payload:null,path:e};try{let a=JSON.parse(d.readFileSync(e,"utf-8"));return c$1(a,"workspace")?{payload:a,path:e}:{payload:null,path:e}}catch{return {payload:null,path:e}}}function D(t){let e=x(t);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run rapidkit doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let a=p(e.payload.summary),s=Number(a.totalIssues??0);return a.hasSystemErrors?{gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload}:s>0?{gate:{gate:"doctor",status:"warn",summary:`Doctor found ${s} issue(s)`,details:["Run rapidkit doctor workspace --fix and re-run readiness checks."],evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function J(t){let e=l.join(t,".rapidkit","reports","analyze-last-run.json");if(!d.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run rapidkit analyze --json before release readiness checks."],evidencePath:e};try{let a=JSON.parse(d.readFileSync(e,"utf-8")),s=p(a.summary),r=String(s.verdict??"").toLowerCase(),o=Number(s.score??0),i=p(s.findings),n=Number(i.fail??0);return r==="blocked"||n>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${o}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:r==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${o}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${o}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid JSON",details:["Re-run rapidkit analyze --json to regenerate evidence."],evidencePath:e}}}function W(t){try{let e=JSON.parse(d.readFileSync(t,"utf-8")),a=String(e.status??"").toLowerCase(),s=p(e.summary),r=Number(s.failedChecks??0);return a==="fail"||r>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:t}:a==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:t}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:t}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:t}}}async function F(t,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let a=l.join(t,".rapidkit","reports"),s=O(a,[/verify-pack-contract/i,/^verify.*\.json$/i]);if(s)return W(s);let r=l.join(a,"workspace-contract-verify-last-run.json"),o=O(a,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i]);if(o)try{let i=JSON.parse(d.readFileSync(o,"utf-8")),n=String(i.status??"").toLowerCase();if(n==="passed"||n==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(n==="failed"||n==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(i.violations)?i.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:i}=await import('./workspace-contract-OO4GMENV.js'),n=await i({workspacePath:t}),c={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:n.status,contractPath:n.contractPath,projectCount:n.projectCount,checks:n.checks,violations:n.violations};return await h.ensureDir(a),await h.writeJSON(r,c,{spaces:2}),n.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:n.violations.slice(0,5),evidencePath:r}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:r}}catch(i){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run rapidkit workspace contract verify --json or export verify-pack contract from CI.",i instanceof Error?i.message:String(i)],evidencePath:l.join(a,"*verify*.json")}}}function M(t,e){let a=l.join(e,".rapidkit","reports","doctor-last-run.json");if(!t)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run rapidkit doctor workspace --json to include dependency findings."],evidencePath:a};let s=Array.isArray(t.projects)?t.projects:[],r=s.reduce((i,n)=>{let c=Number(n.vulnerabilities??0);return Number.isFinite(c)?i+Math.max(0,c):i},0),o=s.filter(i=>i.depsInstalled===false).length;return r>0?{gate:"dependency",status:"fail",summary:`${r} dependency vulnerability(ies) reported`,details:["Resolve vulnerabilities (npm/pip/go audit pipelines) before release."],evidencePath:a}:o>0?{gate:"dependency",status:"warn",summary:`${o} project(s) report missing dependencies`,details:["Run project init/bootstrap and regenerate doctor evidence."],evidencePath:a}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:a}}function _(t){return t.some(e=>e.status==="fail")?"fail":t.some(e=>e.status==="warn")?"warn":"pass"}async function K(t,e){let a=l.join(t,".rapidkit","reports","release-readiness-last-run.json");return await h.ensureDir(l.dirname(a)),await h.writeJSON(a,e,{spaces:2}),a}async function H(t={}){let e$1=l.resolve(t.startPath??process.cwd()),a$1=a(e$1)??e$1,s=I(e$1,a$1),
|
|
1
|
+
import {a,b}from'./chunk-KMUWWZRT.js';import {f,e}from'./chunk-PCXSTKZ5.js';import {c as c$1}from'./chunk-NFUXULIF.js';import {a as a$1,b as b$1,d as d$1,c,f as f$1}from'./chunk-YBS2HGO3.js';import u from'chalk';import d from'fs';import h from'fs-extra';import l from'path';var $="release-readiness-v1";function I(t,e){let a=l.resolve(t);if(!b(a))return a;let s=l.join(e,".rapidkit","workspace.contract.json");if(d.existsSync(s))try{let i=JSON.parse(d.readFileSync(s,"utf-8")),n=Array.isArray(i.projects)?i.projects:[];for(let c of n){let f=p(c),g=typeof f.relativePath=="string"?f.relativePath.trim():"";if(g)return l.join(e,g)}}catch{}let r=x(e),o=Array.isArray(r.payload?.projects)?r.payload.projects:[];for(let i of o){let n=p(i),c=typeof n.path=="string"?n.path.trim():"";if(c)return l.resolve(c)}return a}function V(t){let e=a$1(t);return b$1(e,t)?"go":d$1(e,t)?"java":c(e,t)?"node":f$1(e,t)?"python":"unknown"}function O(t,e){if(!d.existsSync(t))return null;let a=d.readdirSync(t).filter(s=>s.endsWith(".json")&&e.some(r=>r.test(s))).map(s=>l.join(t,s));return a.length===0?null:(a.sort((s,r)=>d.statSync(r).mtimeMs-d.statSync(s).mtimeMs),a[0])}function p(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}async function z(t){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:a}=await import('./workspace-registry-summary-X5WRUU3T.js'),s=await e(t);return s?s.projectCount:(await a(t)).summary.projectCount}function L(t,e,a){let s=l.join(t,".rapidkit","toolchain.lock");if(!d.existsSync(s))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run rapidkit bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:s};try{let r=JSON.parse(d.readFileSync(s,"utf-8")),o=p(r.runtime),n=["python","node","go","java"].filter(c=>{let f=p(o[c]);return typeof f.version=="string"&&f.version.trim().length>0});if(n.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via rapidkit setup <runtime> and re-run bootstrap."],evidencePath:s};if(e!=="unknown"){let c=p(o[e]);if(typeof c.version!="string"||c.version.trim().length===0)return {gate:"env",status:"fail",summary:`${a?.hasRegisteredProjects?"Project runtime":"Workspace"} (${e}) is not pinned in toolchain.lock`,details:[`Run rapidkit setup ${e} and rapidkit bootstrap to lock ${e} for this workspace.`],evidencePath:s}}return {gate:"env",status:"pass",summary:`Pinned runtimes: ${n.join(", ")}`,details:[],evidencePath:s}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with rapidkit bootstrap."],evidencePath:s}}}function x(t){let e=l.join(t,".rapidkit","reports","doctor-last-run.json");if(!d.existsSync(e))return {payload:null,path:e};try{let a=JSON.parse(d.readFileSync(e,"utf-8"));return c$1(a,"workspace")?{payload:a,path:e}:{payload:null,path:e}}catch{return {payload:null,path:e}}}function D(t){let e=x(t);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run rapidkit doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let a=p(e.payload.summary),s=Number(a.totalIssues??0);return a.hasSystemErrors?{gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload}:s>0?{gate:{gate:"doctor",status:"warn",summary:`Doctor found ${s} issue(s)`,details:["Run rapidkit doctor workspace --fix and re-run readiness checks."],evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function J(t){let e=l.join(t,".rapidkit","reports","analyze-last-run.json");if(!d.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run rapidkit analyze --json before release readiness checks."],evidencePath:e};try{let a=JSON.parse(d.readFileSync(e,"utf-8")),s=p(a.summary),r=String(s.verdict??"").toLowerCase(),o=Number(s.score??0),i=p(s.findings),n=Number(i.fail??0);return r==="blocked"||n>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${o}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:r==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${o}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${o}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid JSON",details:["Re-run rapidkit analyze --json to regenerate evidence."],evidencePath:e}}}function W(t){try{let e=JSON.parse(d.readFileSync(t,"utf-8")),a=String(e.status??"").toLowerCase(),s=p(e.summary),r=Number(s.failedChecks??0);return a==="fail"||r>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:t}:a==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:t}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:t}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:t}}}async function F(t,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let a=l.join(t,".rapidkit","reports"),s=O(a,[/verify-pack-contract/i,/^verify.*\.json$/i]);if(s)return W(s);let r=l.join(a,"workspace-contract-verify-last-run.json"),o=O(a,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i]);if(o)try{let i=JSON.parse(d.readFileSync(o,"utf-8")),n=String(i.status??"").toLowerCase();if(n==="passed"||n==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(n==="failed"||n==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(i.violations)?i.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:i}=await import('./workspace-contract-OO4GMENV.js'),n=await i({workspacePath:t}),c={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:n.status,contractPath:n.contractPath,projectCount:n.projectCount,checks:n.checks,violations:n.violations};return await h.ensureDir(a),await h.writeJSON(r,c,{spaces:2}),n.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:n.violations.slice(0,5),evidencePath:r}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:r}}catch(i){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run rapidkit workspace contract verify --json or export verify-pack contract from CI.",i instanceof Error?i.message:String(i)],evidencePath:l.join(a,"*verify*.json")}}}function M(t,e){let a=l.join(e,".rapidkit","reports","doctor-last-run.json");if(!t)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run rapidkit doctor workspace --json to include dependency findings."],evidencePath:a};let s=Array.isArray(t.projects)?t.projects:[],r=s.reduce((i,n)=>{let c=Number(n.vulnerabilities??0);return Number.isFinite(c)?i+Math.max(0,c):i},0),o=s.filter(i=>i.depsInstalled===false).length;return r>0?{gate:"dependency",status:"fail",summary:`${r} dependency vulnerability(ies) reported`,details:["Resolve vulnerabilities (npm/pip/go audit pipelines) before release."],evidencePath:a}:o>0?{gate:"dependency",status:"warn",summary:`${o} project(s) report missing dependencies`,details:["Run project init/bootstrap and regenerate doctor evidence."],evidencePath:a}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:a}}function _(t){return t.some(e=>e.status==="fail")?"fail":t.some(e=>e.status==="warn")?"warn":"pass"}async function K(t,e){let a=l.join(t,".rapidkit","reports","release-readiness-last-run.json");return await h.ensureDir(l.dirname(a)),await h.writeJSON(a,e,{spaces:2}),a}async function H(t={}){let e$1=l.resolve(t.startPath??process.cwd()),a$1=a(e$1)??e$1,s=await z(a$1)>0,r=s&&b(e$1)?a$1:I(e$1,a$1),o=r===a$1?"unknown":V(r),n=L(a$1,s?o:"unknown",{hasRegisteredProjects:s}),c=D(a$1),f$1=J(a$1),g=await F(a$1,{skipVerify:t.skipVerify}),G=M(c.payload,a$1),k=[n,c.gate,f$1,g,G],v=_(k),m={schemaVersion:$,generatedAt:new Date().toISOString(),workspacePath:a$1,projectPath:r,action:t.action,overallStatus:v,blocking:v==="fail",blockingReasons:k.filter(y=>y.status==="fail").map(y=>`${y.gate}: ${y.summary}`),gates:k};if(t.writeReport!==false){let y=f(m,{commandId:"workspaceReadiness",exitCode:v==="fail"?2:v==="warn"?1:0,generatedAt:m.generatedAt,blockers:m.blockingReasons,runId:e()});m.evidencePath=await K(a$1,y);}return m}function B(t){return t==="pass"?u.green("PASS"):t==="warn"?u.yellow("WARN"):u.red("FAIL")}function U(t){return t==="pass"?u.green("PASS"):t==="warn"?u.yellow("WARN"):u.red("FAIL")}async function ne(t){let e=await H({writeReport:true,skipVerify:t.skipVerify===true});if(t.json)console.log(JSON.stringify(e,null,2));else {console.log(u.bold.cyan(`
|
|
2
2
|
\u{1F6A6} RapidKit Release Readiness
|
|
3
3
|
`)),console.log(u.bold(`Workspace: ${u.cyan(l.basename(e.workspacePath))}`)),console.log(u.gray(`Path: ${e.workspacePath}`)),console.log(`Overall: ${U(e.overallStatus)}`);for(let a of e.gates){console.log(` - ${a.gate}: ${B(a.status)} ${a.summary}`);for(let s of a.details)console.log(u.gray(` ${s}`));a.evidencePath&&console.log(u.gray(` evidence: ${a.evidencePath}`));}e.evidencePath&&console.log(u.gray(`
|
|
4
4
|
Evidence saved: ${e.evidencePath}`));}t.strict&&e.overallStatus!=="pass"&&process.exit(1);}export{H as a,ne as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-TSUQQTHI.js';import {a,b as b$1}from'./chunk-S5KTATOU.js';function f(r){let s=new Map;for(let n of r.projects)s.has(n.name)||s.set(n.name,b(n));return s}function j(r){let s=f(r),n=r.graph??{nodes:r.projects.map(t=>({id:t.name,path:t.path})),edges:[]},a$1=a(n),o=new Map;for(let t of n.nodes){let e=s.get(t.id)??b({missing:t.id}),g=[...b$1(a$1,[t.id],{direction:"dependencies"}).keys()].filter(c=>c!==t.id).sort((c,l)=>c.localeCompare(l)).map(c=>({id:c,hash:s.get(c)??"<unknown>"}));o.set(t.id,{id:t.id,ownHash:e,transitiveInputsHash:b({own:e,dependencies:g})});}return o}function v(r,s){if(!s||Object.keys(s).length===0)return {verdict:"unknown",baseline:"none",changed:[],added:[],removed:[]};let n=[],a=[];for(let[e,i]of r.entries())e in s?s[e]!==i.transitiveInputsHash&&n.push(e):a.push(e);let o=[];for(let e of Object.keys(s))r.has(e)||o.push(e);return n.sort((e,i)=>e.localeCompare(i)),a.sort((e,i)=>e.localeCompare(i)),o.sort((e,i)=>e.localeCompare(i)),{verdict:n.length>0||a.length>0||o.length>0?"stale":"fresh",baseline:"recorded",changed:n,added:a,removed:o}}function w(r){let s={};for(let[n,a]of [...r.entries()].sort((o,t)=>o[0].localeCompare(t[0])))s[n]=a.transitiveInputsHash;return s}export{f as a,j as b,v as c,w as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import p from'path';import a from'fs-extra';var y="workspace-intelligence-history.v1",l=".rapidkit/reports/workspace-intelligence-history.json",d=50;function m(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.generatedAt!="string"?null:e.kind==="agent-action"?typeof e.actionId!="string"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"agent-action",generatedAt:e.generatedAt,actionId:e.actionId,scope:typeof e.scope=="string"?e.scope:"workspace",summary:e.summary,outcome:e.outcome,...typeof e.evidenceSha256=="string"?{evidenceSha256:e.evidenceSha256}:{}}:e.kind==="doctor-fix"?e.scope!=="workspace"&&e.scope!=="project"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"doctor-fix",generatedAt:e.generatedAt,scope:e.scope,summary:e.summary,outcome:e.outcome,applied:typeof e.applied=="number"?e.applied:0,failed:typeof e.failed=="number"?e.failed:0,skipped:typeof e.skipped=="number"?e.skipped:0,remainingBlockers:typeof e.remainingBlockers=="number"?e.remainingBlockers:0}:typeof e.verdict!="string"||typeof e.risk!="string"||typeof e.gatePassed!="boolean"?null:{kind:"verify",generatedAt:e.generatedAt,verdict:e.verdict,risk:String(e.risk),affectedProjects:typeof e.affectedProjects=="number"?e.affectedProjects:0,freshness:e.freshness??"unknown",gatePassed:e.gatePassed,blockingReasons:typeof e.blockingReasons=="number"?e.blockingReasons:0,policyViolations:typeof e.policyViolations=="number"?e.policyViolations:0}}function E(t,e){return {kind:"verify",generatedAt:t.generatedAt,verdict:t.summary.verdict,risk:t.impact.risk,affectedProjects:t.impact.affectedProjects,freshness:t.freshness.verdict,gatePassed:e,blockingReasons:t.blockingReasons.length,policyViolations:t.policyViolations.length}}function H(t){return {kind:"agent-action",generatedAt:t.generatedAt,actionId:t.actionId,scope:t.scope,summary:t.summary,outcome:t.outcome,...t.evidenceSha256?{evidenceSha256:t.evidenceSha256}:{}}}function W(t,e){let r=t.appliedFixes.filter(i=>i.outcome==="applied").length,o=t.appliedFixes.filter(i=>i.outcome==="failed").length,n=t.appliedFixes.filter(i=>i.outcome==="skipped").length,s=t.appliedFixes.filter(i=>i.outcome==="guidance").length,c=t.remainingBlockers.length,f=o>0||c>0?"failed":"ok";return {kind:"doctor-fix",generatedAt:t.generatedAt,scope:e,summary:`${r} applied, ${o} failed, ${n} skipped, ${s} guidance, ${c} blocker(s) remaining`,outcome:f,applied:r,failed:o,skipped:n,remainingBlockers:c}}async function u(t){let e=p.join(t,l);try{if(!await a.pathExists(e))return null;let r=await a.readJson(e);return r?.schemaVersion!==y||!Array.isArray(r.entries)?null:{schemaVersion:y,retention:typeof r.retention=="number"?r.retention:d,entries:r.entries.map(o=>m(o)).filter(o=>o!=null)}}catch{return null}}function k(t,e,r=d){let o=Math.max(1,Math.floor(r)),n=[...t?.entries??[],e],s=n.slice(Math.max(0,n.length-o));return {schemaVersion:y,retention:o,entries:s}}async function b(t,e,r){let o=await u(t),n=k(o,e,r?.retention??d),s=p.join(t,l);return await a.ensureDir(p.dirname(s)),await a.writeJson(s,n,{spaces:2}),n}export{y as a,l as b,d as c,m as d,E as e,H as f,W as g,u as h,k as i,b as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a,b}from'./chunk-KMUWWZRT.js';import {f as f$1,e}from'./chunk-PCXSTKZ5.js';import {h,i}from'./chunk-UZW5QFRW.js';import {a as a$1}from'./chunk-
|
|
1
|
+
import {a,b}from'./chunk-KMUWWZRT.js';import {f as f$1,e}from'./chunk-PCXSTKZ5.js';import {h,i}from'./chunk-UZW5QFRW.js';import {a as a$1}from'./chunk-TDSIF42O.js';import y from'fs';import o from'path';import s from'chalk';var T=new Set([".git",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function k(e){try{return await y.promises.access(e,y.constants.F_OK),true}catch{return false}}async function z(e){try{let n=JSON.parse(await y.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function N(e){try{return await y.promises.readFile(e,"utf-8")}catch{return ""}}function O(e){return a(e)}async function K(e,n){return await k(o.join(e,".rapidkit","project.json"))||await k(o.join(e,".rapidkit","context.json"))?true:b(e)?false:o.resolve(e)===o.resolve(n)?h(e).length>0:h(e).length>0}async function M(e){let n=await a$1(e,{skipDirs:T,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:K});return n.length>0?n:b(e)?[]:h(e).length>0?[e]:[]}function _(e,n){return o.relative(e,n).replace(/\\/g,"/")||"."}async function A(e,n){for(let t of n)if(await k(o.join(e,t)))return true;return false}async function J(e){return A(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function W(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let t=await z(o.join(e,"package.json")),i=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return typeof i.test=="string"&&i.test.trim().length>0}async function H(e){let n=await z(o.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function f(e,n,t,i,r,d){return {id:e,severity:n,target:t,title:i,detail:r,remediation:d}}function B(e){let n=e.reduce((t,i)=>i.severity==="fail"?t+28:i.severity==="warn"?t+12:t+3,0);return Math.max(0,100-n)}async function U(e,n){let t=await z(o.join(n,".rapidkit","project.json")),i$1=i(n,t),r=h(n),d=i$1.runtime==="unknown"?r[0]||"unknown":i$1.runtime,a=_(e,n),p=a,g=await H(n),u=await k(o.join(n,".rapidkit","project.json"))||await k(o.join(n,".rapidkit","context.json")),l=await W(n),h$1=await A(n,["Dockerfile","dockerfile"]),w=await A(n,[".env.example","env.example","config/env.example"]),P=await A(n,[".github/workflows/ci.yml",".github/workflows/ci.yaml",".github/workflows/main.yml",".github/workflows/build.yml",".github/workflows/test.yml",".github/workflows/deploy.yml",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]),R=await J(n),m=[];return i$1.key==="unknown"&&m.push(f("project.stack.unknown","fail",p,"Project stack is unknown","RapidKit cannot confidently classify this backend project.","Add .rapidkit/project.json metadata or import the project with `rapidkit import`.")),u||m.push(f("project.marker.missing","warn",p,"RapidKit marker is missing","The project can be detected by files, but it is not registered with RapidKit metadata.","Run `rapidkit import <path>` from a workspace or create the project through RapidKit.")),l||m.push(f("project.tests.missing","warn",p,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `rapidkit workspace run test --affected` can gate changes.")),w||m.push(f("project.env.example.missing","info",p,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),P||m.push(f("project.ci.missing","warn",p,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.")),R||m.push(f("project.health.missing","info",p,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h$1||m.push(f("project.container.missing","info",p,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:o.basename(n),path:n,relativePath:a,runtime:d,framework:i$1.key,confidence:i$1.confidence,supportTier:i$1.supportTier,hasRapidKitMarker:u,hasTests:l,hasDockerfile:h$1,hasEnvExample:w,hasCiConfig:P,hasHealthEndpoint:R,scripts:g,findings:m,score:B(m)}}function V(e){return e.name.toLowerCase()}async function L(e){let n=new Map(e.map(r=>[V(r),r])),t=[];for(let r of e){let d=await z(o.join(r.path,"package.json")),a={...d?.dependencies??{},...d?.devDependencies??{},...d?.peerDependencies??{}};for(let g of Object.keys(a)){let u=g.replace(/^@[^/]+\//,"").toLowerCase(),l=n.get(u);l&&l.relativePath!==r.relativePath&&t.push({from:r.relativePath,to:l.relativePath,kind:"package"});}let p=await N(o.join(r.path,"pyproject.toml"));for(let g of e)g.relativePath!==r.relativePath&&p.includes(g.name)&&t.push({from:r.relativePath,to:g.relativePath,kind:"workspace-reference"});}let i=new Set;return t.filter(r=>{let d=`${r.from}\0${r.to}\0${r.kind}`;return i.has(d)?false:(i.add(d),true)})}function q(e,n){let t=new Map;for(let i of e)t.set(i.relativePath,{project:i.relativePath,directDependents:0,directDependencies:0});for(let i of n){let r=t.get(i.from),d=t.get(i.to);r&&(r.directDependencies+=1),d&&(d.directDependents+=1);}return Array.from(t.values()).sort((i,r)=>r.directDependents-i.directDependents||r.directDependencies-i.directDependencies)}async function Q(e){let n=await z(o.join(e,".rapidkit","workspace.json"));return typeof n?.profile=="string"?n.profile:null}function X(e){return {fail:e.filter(n=>n.severity==="fail").length,warn:e.filter(n=>n.severity==="warn").length,info:e.filter(n=>n.severity==="info").length}}function Y(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx rapidkit create project <name> --kit <kit>","Import an existing service: npx rapidkit import <path>"]:["Create a RapidKit workspace: npx rapidkit create workspace my-workspace --profile polyglot","Import an existing service: npx rapidkit import ../service"];let n=[];return e.findings.some(t=>t.id==="workspace.marker.missing")&&n.push("Initialize workspace metadata with `rapidkit bootstrap --profile polyglot`."),e.findings.some(t=>t.id==="project.marker.missing")&&n.push("Register detected projects with `rapidkit import <path>` or recreate them via `rapidkit create project`."),e.findings.some(t=>t.id==="project.tests.missing")&&n.push("Add test entrypoints, then gate changes with `rapidkit workspace run test --affected --strict`."),e.findings.some(t=>t.id==="project.ci.missing")&&n.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(t=>t.id==="project.health.missing")&&n.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||n.push("Create `.rapidkit/workspace-dependency-graph.json` or use analyze output as the first graph seed."),n.push("Run `rapidkit autopilot release --mode audit --json` before release."),Array.from(new Set(n))}async function ce(e$1={}){let n=o.resolve(e$1.workspacePath||process.cwd());if(!await k(n))throw new Error(`Workspace path does not exist: ${n}`);let t=O(n)??n,i=await k(o.join(t,".rapidkit-workspace"))||await k(o.join(t,".rapidkit","workspace.json")),r=await Q(t),d=await M(t),a=await Promise.all(d.map(c=>U(t,c))),p=await L(a),g=q(a,p),u=[];i||u.push(f("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered RapidKit workspace.","Run `rapidkit create workspace` or `rapidkit bootstrap --profile polyglot` in a workspace root.")),a.length===0&&u.push(f("workspace.projects.missing","warn",".","No backend projects detected","RapidKit did not find runtime markers or project metadata under this root.","Create a project with `rapidkit create project` or import one with `rapidkit import <path>`."));let l=[...u,...a.flatMap(c=>c.findings)],h=X(l),w={};for(let c of a)w[c.runtime]=(w[c.runtime]||0)+1;let P=a.length>0?Math.round(a.reduce((c,v)=>c+v.score,0)/a.length):0,R=u.reduce((c,v)=>c+(v.severity==="fail"?20:v.severity==="warn"?8:2),0),m=Math.max(0,P-R),E=a.length===0&&h.fail===0&&l.length>0&&l.every(c=>c.id==="workspace.projects.missing"&&c.severity==="warn"),S=h.fail>0||e$1.strict&&h.warn>0&&!E?"blocked":h.warn>0?"needs-attention":"ready",j={schemaVersion:"rapidkit-analyze-v1",generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:i,profile:r,summary:{score:m,verdict:S,projectCount:a.length,runtimeCount:Object.keys(w).length,findings:h},runtimes:w,projects:a,dependencyGraph:{status:p.length>0?"generated":"empty",edges:p,topImpactedProjects:g.slice(0,5)},findings:l,nextActions:Y({findings:l,projectCount:a.length,hasGraph:p.length>0,workspaceDetected:i}),enterpriseControls:{jsonReady:true,ciGateCommand:"rapidkit analyze --json --strict",releaseGateCommand:"rapidkit autopilot release --mode enforce --json",evidencePath:".rapidkit/reports/analyze-last-run.json"}};if(e$1.output&&(await y.promises.mkdir(o.dirname(o.resolve(e$1.output)),{recursive:true}),await y.promises.writeFile(o.resolve(e$1.output),`${JSON.stringify(j,null,2)}
|
|
2
2
|
`)),!e$1.output&&i){let c=o.join(t,".rapidkit","reports","analyze-last-run.json");await y.promises.mkdir(o.dirname(c),{recursive:true});let v=f$1(j,{commandId:"workspaceAnalyze",exitCode:j.summary.verdict==="blocked"?2:j.summary.verdict==="needs-attention"?1:0,generatedAt:j.generatedAt,blockers:j.findings.filter(x=>x.severity==="fail").map(x=>x.title).slice(0,12),runId:e()});await y.promises.writeFile(c,`${JSON.stringify(v,null,2)}
|
|
3
3
|
`);}return j}function de(e){let n=e.summary.verdict==="ready"?s.green:e.summary.verdict==="needs-attention"?s.yellow:s.red;if(console.log(s.bold(`
|
|
4
4
|
RapidKit Workspace Analysis
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import {b,c,d}from'./chunk-XY3SGMAJ.js';import {d as d$1}from'./chunk-O74N26AD.js';import {b as b$1,f,a,g as g$1}from'./chunk-GBJBQ43T.js';import {n,k as k$1,b as b$2,j as j$1}from'./chunk-TSUQQTHI.js';import {j}from'./chunk-3PTJID76.js';import s from'path';import g from'fs-extra';var _=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var Se="workspace-operational-skill.v1";function je(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function pe(e){let t=je(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:Se,skillId:t,canonicalPath:f(t),title:e.title,triggers:[...e.triggers].sort((r,i)=>r.localeCompare(i)),requiredReports:[...e.requiredReports].sort((r,i)=>r.localeCompare(i)),scopedProjects:[...e.scopedProjects??[]].sort((r,i)=>r.localeCompare(i)),verificationCommands:[...e.verificationCommands],answerContractSections:[..._],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var ve="workspace-skills-index.v1";function de(e){let t=[...e.skills].sort((i,o)=>i.skillId.localeCompare(o.skillId)),r=e.inputsHash??b$2({skillIds:t.map(i=>i.skillId),paths:t.map(i=>i.canonicalPath)});return {schemaVersion:ve,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(i=>({skillId:i.skillId,path:i.canonicalPath,schemaVersion:i.schemaVersion,title:i.title}))}}var le=[".rapidkit/reports/INDEX.json",b,d$1],Pe=[{skillId:"rapidkit-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using RapidKit evidence before editing application code.",steps:["Read `.rapidkit/reports/INDEX.json` and identify fail/warn reports for the scoped project.","Read `.rapidkit/reports/doctor-last-run.json`, `doctor-project-last-run.json`, and project-scoped run evidence if present.","If a fix was requested, read `doctor-remediation-plan-last-run.json` before editing and `doctor-fix-result-last-run.json` before claiming completion.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"rapidkit-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed RapidKit gates.",steps:["Read `.rapidkit/reports/release-readiness-last-run.json` and `pipeline-last-run.json`.","Read `.rapidkit/reports/workspace-verify-last-run.json` for verdict and blocking reasons.","List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"rapidkit-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"rapidkit-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"rapidkit-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:["Read `.rapidkit/workspace.contract.json` for publishes/consumes/owns edges.","List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function D(e){return `npx rapidkit ${e}`.trim()}function Ce(e){let t=[`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...le.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,i)=>`${i+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",D("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
|
|
2
|
+
`)}function Ee(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[D("workspace verify --json"),D("doctor workspace --json")]}function Ie(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let i=r.contracts.owns.join(", ")||"none",o=r.contracts.publishes.join(", ")||"none",p=r.contracts.consumes.join(", ")||"none";return `- **${r.slug}**: owns \`${i}\`; publishes \`${o}\`; consumes \`${p}\``}).join(`
|
|
3
|
+
`):void 0}function ue(e){let t=e.model.workspace.name,r=e.model.projects.map(p=>p.name).sort(),i=Ee(e.context??null),o=Ie(e.contract??null);return Pe.map(p=>{let c=Ce({template:p,workspaceName:t,scopedProjects:r,verificationCommands:i,contractSummary:o});return pe({skillId:p.skillId,title:p.title,triggers:p.triggers,requiredReports:[...le],scopedProjects:r,verificationCommands:i,promptStem:g$1[p.skillId],markdown:c})})}async function ge(e){let t=s.resolve(e.workspacePath),r=[],i=b$2({skills:e.skills.map(p=>({id:p.skillId,path:p.canonicalPath,hash:b$2({markdown:p.markdown})}))}),o=de({generatedAt:e.generatedAt,skills:e.skills,inputsHash:i});if(e.write){for(let c of e.skills){let n=s.join(t,c.canonicalPath);await g.ensureDir(s.dirname(n)),await g.writeFile(n,c.markdown,"utf8"),r.push(c.canonicalPath);}let p=s.join(t,b$1);await g.ensureDir(s.dirname(p)),await g.writeJson(p,o,{spaces:2}),r.push(b$1);}return {skills:e.skills,index:o,writtenPaths:r}}function me(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.rapidkit/skills/` before generic repo scans:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",D("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
4
|
+
`)}var Oe={"rapidkit-diagnose-api-failure":".github/prompts/rapidkit-diagnose.prompt.md","rapidkit-release-readiness":".github/prompts/rapidkit-release-readiness.prompt.md"},B="## Workspace verification (hydrated)";function Te(e){let t=[B,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx rapidkit workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
|
|
5
|
+
`)}async function ke(e){let t=s.resolve(e.workspacePath),r=[];for(let i of e.skills){let o=Oe[i.skillId];if(!o)continue;let p=s.join(t,o);if(!await g.pathExists(p))continue;let c=await g.readFile(p,"utf8"),n=Te(i),m=c.includes(B)?c.replace(new RegExp(`${B}[\\s\\S]*$`),n.trimEnd()):`${c.trimEnd()}
|
|
6
|
+
|
|
7
|
+
${n}`;e.write&&await g.writeFile(p,`${m.trimEnd()}
|
|
8
|
+
`,"utf8"),r.push(o);}return r}var We="rapidkit-agent-customization-pack.v1";function fe(){return {schemaVersion:We,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[".rapidkit/reports/INDEX.json",".rapidkit/reports/agent-customization-pack.json","AGENTS.md"]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[".rapidkit/reports/INDEX.json",".rapidkit/reports/agent-customization-pack.json","AGENTS.md",".github/instructions/rapidkit-workspace.instructions.md",".github/prompts/rapidkit-diagnose.prompt.md",".github/skills/rapidkit-workspace-intelligence/SKILL.md",".github/agents/workspai-advisor.agent.md",".rapidkit/reports/rapidkit-mcp-design.json",b$1]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},orca:{meaning:"Use AGENTS.md and the report index as the Orca/Grok grounding layer.",outputFamilies:["portable"]}},standardAnswerContract:[..._],requiredReports:O.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".rapidkit/reports/",`${a}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md"]}}}var Ne="rapidkit-agent-reports-index.v1",_e="rapidkit-agent-customization-pack.v1",J=".rapidkit/reports/INDEX.json",he=".rapidkit/AGENT-GROUNDING.md",G=".rapidkit/reports/agent-customization-pack.json",O=[{relativePath:b,label:"Agent context pack",required:true},{relativePath:b$1,label:"Operational skills index",required:true},{relativePath:".rapidkit/reports/workspace-model.json",label:"Workspace model graph",required:false},{relativePath:".rapidkit/reports/doctor-last-run.json",label:"Workspace doctor",required:false},{relativePath:".rapidkit/reports/doctor-project-last-run.json",label:"Project doctor",required:false},{relativePath:".rapidkit/reports/doctor-remediation-plan-last-run.json",label:"Doctor remediation plan",required:false},{relativePath:".rapidkit/reports/doctor-fix-result-last-run.json",label:"Doctor fix result",required:false},{relativePath:".rapidkit/reports/analyze-last-run.json",label:"Workspace analyze",required:false},{relativePath:".rapidkit/reports/pipeline-last-run.json",label:"Governance pipeline",required:false},{relativePath:".rapidkit/reports/release-readiness-last-run.json",label:"Release readiness",required:false},{relativePath:".rapidkit/reports/workspace-impact-last-run.json",label:"Workspace impact",required:false},{relativePath:".rapidkit/reports/workspace-verify-last-run.json",label:"Workspace verify",required:false},{relativePath:".rapidkit/reports/workspace-model-snapshot.json",label:"Workspace model snapshot",required:false},{relativePath:".rapidkit/reports/workspace-model-diff-last-run.json",label:"Workspace model diff",required:false},{relativePath:".rapidkit/reports/workspace-explain-last-run.json",label:"Workspace explain",required:false},{relativePath:".rapidkit/reports/workspace-contract-verify-last-run.json",label:"Workspace contract verify",required:false},{relativePath:".rapidkit/reports/workspace-intelligence-history.json",label:"Workspace intelligence history",required:false}];function k(e){return `npx rapidkit ${e}`.trim()}function be(e){return e&&typeof e=="object"?e:null}function Z(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function De(e){let t=Z(e.blockers,12);if(t.length>0)return t;let r=Z(e.blockingReasons,12);if(r.length>0)return r;let i=be(e.summary);return i&&Array.isArray(i.blockingReasons)?Z(i.blockingReasons,12):[]}function Ge(e){for(let t of ["generatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function Ke(e,t,r){if(!e)return true;let i=Date.parse(e);return Number.isFinite(i)?r.getTime()-i>t*60*60*1e3:true}function Le(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]):new Set(t)}function w(e,t){return e.has("all")||e.has(t)}function Me(e){return w(e,"copilot")||w(e,"vscode")}function qe(e){return e??"enterprise"}function $e(e){return e===b$1?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":e.startsWith(".rapidkit/skills/")&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e.endsWith("rapidkit-agent-hooks.json")?"hook":e.includes("mcp")||e.endsWith("rapidkit-mcp-design.json")?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function He(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Ve(e,t){return fe().presets[t].requiredOutputs.includes(e)}function ze(e){return e.schemaVersion===j$1&&typeof e.generatedAt=="string"&&e.summary!=null&&typeof e.summary=="object"&&!Array.isArray(e.summary)&&Array.isArray(e.projects)}async function Fe(e,t){if(t)return t;let r=s.join(e,k$1);if(await g.pathExists(r))try{let i=await g.readJson(r);if(ze(i))return i}catch{}return n({workspacePath:e,includeEvidence:true})}function Ue(e){return e.length>0&&!s.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function Xe(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(i=>i.targets.includes(r)).map(i=>i.path).sort()}]))}async function Be(e){try{if(!await g.pathExists(e))return null;let t=await g.readJson(e);return be(t)}catch{return null}}async function we(e){let t=e.now??new Date,r=e.staleAfterHours??24,i=[],o=[];for(let c of O){let n=s.join(e.workspacePath,c.relativePath),m=await Be(n),j=m!==null;j&&m&&o.push(...De(m)),i.push({path:c.relativePath,label:c.label,required:c.required,exists:j,generatedAt:m?Ge(m):void 0,commandId:typeof m?.commandId=="string"?m.commandId:void 0,exitCode:typeof m?.exitCode=="number"?m.exitCode:void 0});}let p=[...new Set(o.map(c=>c.trim()).filter(Boolean))].slice(0,16);return {schemaVersion:Ne,generatedAt:t.toISOString(),workspaceRoot:e.workspacePath,readOrder:O.map(c=>c.relativePath),blockers:p,staleAfterHours:r,reports:i,refreshCommand:k("workspace agent-sync --write --refresh-context")}}function Ae(e){let t=["# RapidKit agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","","1. `.rapidkit/reports/INDEX.json` \u2014 latest blockers, timestamps, and report paths","2. `.rapidkit/reports/workspace-context-agent.json` \u2014 canonical agent context pack","3. Evidence artifacts listed in the index (doctor, analyze, pipeline, readiness, impact, verify)","","Do **not** full-repo scan until these reports are read or regenerated.","","## Regenerate intelligence","","```bash",k("workspace agent-sync --write --refresh-context"),k("workspace context --for-agent --json --write"),k("pipeline --json --write"),"```",""];if(e.index.blockers.length>0){t.push("## Current blockers","");for(let r of e.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.rapidkit/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic RapidKit CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.",""),t.join(`
|
|
9
|
+
`)}function Je(e){return ["# RapidKit agent grounding","",`Generated: ${e.generatedAt}`,"","This file is tool-agnostic. Synced agents should read it together with `.rapidkit/reports/INDEX.json`.","","## Mandatory read order","",...e.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e.blockers.length>0?"## Blockers":"",...e.blockers.length>0?e.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e.refreshCommand,"```",""].filter(t=>t!=="").join(`
|
|
10
|
+
`)}function Ze(){return ["# RapidKit workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed RapidKit section).","2. Read `.rapidkit/reports/INDEX.json` and `.rapidkit/reports/workspace-context-agent.json`.","3. Use evidence reports before scanning the full repository.","","Regenerate stale intelligence:","","```bash",k("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
11
|
+
`)}function Ye(){return ["## Claude Code","","- Load `.rapidkit/reports/INDEX.json` before diagnosing blockers.","- Use `.claude/rules/rapidkit-evidence.md` when editing files under `.rapidkit/`.","- Refresh grounding with `npx rapidkit workspace agent-sync --write`.",""].join(`
|
|
12
|
+
`)}function Qe(){return ["---","description: RapidKit workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","Before proposing fixes in this workspace:","","1. Read `AGENTS.md` and `.rapidkit/reports/INDEX.json`.","2. Read `.rapidkit/reports/workspace-context-agent.json`.","3. Prefer evidence in `.rapidkit/reports/*` over full-repo exploration.","","Refresh when stale:","","```bash",k("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
13
|
+
`)}function et(){return ["---",'applyTo: ".rapidkit/**,**/.rapidkit/**"',"description: RapidKit evidence and intelligence artifacts","---","","When working under `.rapidkit/`:","","- Treat JSON reports as canonical gate and health evidence.","- Start from `reports/INDEX.json` for read order and blockers.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
|
|
14
|
+
`)}function tt(){return ["---",'applyTo: "**"',"description: RapidKit workspace scope, evidence, and command discipline","---","","# RapidKit Workspace Intelligence","","Use RapidKit reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Scope rules","","- Start from `.rapidkit/reports/INDEX.json` and `.rapidkit/reports/workspace-context-agent.json`.","- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
|
|
15
|
+
`)}function rt(){return ["# RapidKit evidence","","Applies when reading or editing `.rapidkit/reports/*`.","","- Start from `INDEX.json`, then `workspace-context-agent.json`.","- Use report blockers as the primary fix target.","- Regenerate with `npx rapidkit workspace agent-sync --write`.",""].join(`
|
|
16
|
+
`)}function it(){return ["---","description: Diagnose RapidKit workspace blockers from evidence reports","---","","Diagnose this workspace using RapidKit evidence only.","","Read:","","- `.rapidkit/reports/INDEX.json`","- `.rapidkit/reports/workspace-context-agent.json`","- Any fail/warn reports referenced in the index","","Return:","","1. Root cause grounded in report blockers","2. Smallest safe fix path (commands + file edits)","3. One verification command to prove recovery",""].join(`
|
|
17
|
+
`)}function K(e){return ["---",`description: ${e.description}`,"---","",e.objective,"","Read first:","","- `.rapidkit/reports/INDEX.json`","- `.rapidkit/reports/workspace-context-agent.json`","- Any report referenced by the current blocker or task","","Return:","",...e.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard RapidKit answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
|
|
18
|
+
`)}function S(e){return ["# "+e.title,"",...e.lines,""].join(`
|
|
19
|
+
`)}function nt(){return S({title:"MCP Tool Design",lines:["RapidKit MCP is a future read-mostly bridge. Use the CLI reports today; do not assume a running MCP server exists.","","Candidate read tools:","- `getWorkspaceModel` \u2014 read `.rapidkit/reports/workspace-model.json`.","- `getEvidenceIndex` \u2014 read `.rapidkit/reports/INDEX.json`.","- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.","- `listOperationalSkills` \u2014 read `.rapidkit/reports/workspace-skills-index.json`.","- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function st(e){return `${JSON.stringify({schemaVersion:"rapidkit-mcp-design.v1",generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[".rapidkit/reports/workspace-model.json"],mutates:false},{name:"getEvidenceIndex",reads:[".rapidkit/reports/INDEX.json"],mutates:false},{name:"getBlockers",reads:[".rapidkit/reports/INDEX.json",".rapidkit/reports/workspace-verify-last-run.json",".rapidkit/reports/pipeline-last-run.json"],mutates:false},{name:"getSafeCommands",reads:[".rapidkit/reports/workspace-context-agent.json"],mutates:false},{name:"getProjectContext",reads:[".rapidkit/reports/workspace-model.json",".rapidkit/reports/workspace-context-agent.json"],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[".rapidkit/reports/workspace-skills-index.json"],mutates:false},{name:"getWorkspaceExplain",reads:[".rapidkit/reports/workspace-explain-last-run.json",".rapidkit/reports/workspace-verify-last-run.json",".rapidkit/reports/workspace-impact-last-run.json"],mutates:false},{name:"refreshWorkspaceIntelligence",command:k("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
|
|
20
|
+
`}function ot(e){return `${JSON.stringify({schemaVersion:"rapidkit-agent-hooks.v1",generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,enabledByDefault:false,mode:"advisory",hooks:[{name:"rapidkit-pre-tool-use-workspace-boundary",event:"PreToolUse",purpose:"Block or warn on state-changing commands outside the active workspace root.",defaultAction:"warn",rules:["Allow read-only commands.","Warn before write/delete commands outside workspaceRoot.","Never run destructive commands without explicit user approval."]},{name:"rapidkit-post-tool-use-verify-suggestion",event:"PostToolUse",purpose:"Suggest non-destructive verification commands after edits.",defaultAction:"suggest",commands:[k("doctor workspace"),k("workspace verify --strict --json")]},{name:"rapidkit-user-prompt-submit-scope-hint",event:"UserPromptSubmit",purpose:"Inject lightweight workspace scope and evidence index hints.",defaultAction:"inject-context-hint",reads:[".rapidkit/reports/INDEX.json",".rapidkit/reports/workspace-context-agent.json"]}]},null,2)}
|
|
21
|
+
`}function at(e){let t=["---","name: rapidkit-workspace-intelligence","description: Use RapidKit workspace intelligence reports to answer, repair, verify, and release with evidence","---","","# RapidKit Workspace Intelligence","","Use this skill for workspace architecture, project lifecycle, blocker repair, release readiness, agent grounding, and CI evidence questions.","","## Decision flow","","1. Load `resources/scope-model.md`.","2. Load `.rapidkit/reports/INDEX.json`.","3. Load `.rapidkit/reports/workspace-context-agent.json`.","4. Load `.rapidkit/reports/workspace-skills-index.json` when operational playbooks are needed.","5. Load the smallest evidence report required for the task.","6. Answer with Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Rules","","- Prefer RapidKit reports over full-repo scans.","- Never claim a gate passed without a cited report.","- Separate display commands from execution requests.","- Keep project-scoped fixes inside the active project unless workspace evidence says otherwise.",""];return e?.trim()&&t.push(e.trim(),""),t.join(`
|
|
22
|
+
`)}function L(e){return ["---",`name: ${e.name}`,`description: ${e.description}`,`tools: [${e.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e.name} agent for RapidKit Workspace Intelligence.`,"",`Mode: ${e.mode}.`,"","Start every task by reading `.rapidkit/reports/INDEX.json` and `.rapidkit/reports/workspace-context-agent.json`.","","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
|
|
23
|
+
`)}function ct(){return ["---","name: rapidkit-grounding","description: Load RapidKit workspace intelligence reports before diagnosing or changing code","---","","# RapidKit grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","","1. Read `.rapidkit/reports/INDEX.json`","2. Read `.rapidkit/reports/workspace-context-agent.json`","3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands","","## Refresh stale evidence","","```bash",k("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
24
|
+
`)}async function u(e,t,r){return r?(await g.ensureDir(s.dirname(e)),await g.writeFile(e,t,"utf8"),"written"):"skipped"}async function Y(e){if(!e.write)return "skipped";let t=await g.pathExists(e.absolutePath)?await g.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-AXUM75OE.js'),i=r(t,e.generatedBody),o=e.preamble?`${e.preamble.trimEnd()}
|
|
25
|
+
|
|
26
|
+
${i}`:i;return await g.ensureDir(s.dirname(e.absolutePath)),await g.writeFile(e.absolutePath,o,"utf8"),"written"}function Vt(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]),r=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>t.has(i));return r.length>0?r:void 0}function pt(e){let t=[...e.outputs].sort((r,i)=>r.path.localeCompare(i.path));return {schemaVersion:_e,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(r=>r.exists).map(r=>r.path).sort(),outputInventory:t,capabilityMatrix:Xe({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:k(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(r=>r.kind==="mcp-design")}}}async function zt(e){let t=s.resolve(e.workspacePath),r=new Date,i=e.staleAfterHours??24,o=Le(e.targets),p=[...o].sort(),c$1=qe(e.preset),n$1=e.write===true,m=e.strict===true,j$1,v=null,M;e.refreshContext&&(M=await n({workspacePath:t,includeEvidence:true}),v=await c({workspacePath:t,model:M,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),n$1&&(j$1=await d(v,t)));let A=await we({workspacePath:t,staleAfterHours:i,now:r}),P=[],q=[],$=[],H=[],d$1=(a,l)=>{a==="written"?q.push(l):$.push(l),H.push({path:l,kind:$e(l),targets:He(l),required:Ve(l,c$1),status:a==="written"?"written":e.dryRun?"planned":"skipped"});};d$1(await u(s.join(t,J),`${JSON.stringify(A,null,2)}
|
|
27
|
+
`,n$1),J),d$1(await u(s.join(t,he),`${Je(A)}
|
|
28
|
+
`,n$1),he);let Q="",Re=await Fe(t,M),V=null;try{V=(await j({workspacePath:t})).contract;}catch{V=null;}let xe=ue({model:Re,context:v,contract:V}),z=await ge({workspacePath:t,skills:xe,generatedAt:r.toISOString(),write:n$1});for(let a of z.skills)d$1(n$1?"written":"skipped",a.canonicalPath);if(d$1(n$1?"written":"skipped",b$1),Q=me(z.index),(w(o,"agents")||w(o,"vscode"))&&d$1(await Y({absolutePath:s.join(t,"AGENTS.md"),generatedBody:Ae({index:A,context:v}),write:n$1}),"AGENTS.md"),w(o,"claude")){let a=s.join(t,"CLAUDE.md");if(n$1){let{upsertManagedAgentSection:l}=await import('./managed-agent-markers-AXUM75OE.js'),f=await g.pathExists(a)?await g.readFile(a,"utf8"):"",b=l(f,Ye()),R=b.includes("@AGENTS.md")?b:`@AGENTS.md
|
|
29
|
+
|
|
30
|
+
${b}`;await g.ensureDir(s.dirname(a)),await g.writeFile(a,R,"utf8"),q.push("CLAUDE.md");}else $.push("CLAUDE.md");d$1(await u(s.join(t,".claude/rules/rapidkit-evidence.md"),`${rt()}
|
|
31
|
+
`,n$1),".claude/rules/rapidkit-evidence.md");}if(w(o,"cursor")&&d$1(await u(s.join(t,".cursor/rules/rapidkit-grounding.mdc"),Qe(),n$1),".cursor/rules/rapidkit-grounding.mdc"),Me(o)){if(d$1(await Y({absolutePath:s.join(t,".github/copilot-instructions.md"),generatedBody:Ze(),write:n$1}),".github/copilot-instructions.md"),d$1(await u(s.join(t,".github/instructions/rapidkit-workspace.instructions.md"),tt(),n$1),".github/instructions/rapidkit-workspace.instructions.md"),d$1(await u(s.join(t,".github/instructions/rapidkit-evidence.instructions.md"),et(),n$1),".github/instructions/rapidkit-evidence.instructions.md"),d$1(await u(s.join(t,".github/prompts/rapidkit-diagnose.prompt.md"),it(),n$1),".github/prompts/rapidkit-diagnose.prompt.md"),c$1==="enterprise"){let a=[[".github/prompts/rapidkit-repair.prompt.md",K({description:"Repair RapidKit blockers with evidence and verification",objective:"Plan the smallest safe repair for the current RapidKit blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[".github/prompts/rapidkit-release-readiness.prompt.md",K({description:"Assess RapidKit release readiness from evidence",objective:"Assess whether this workspace is release-ready using RapidKit gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[".github/prompts/rapidkit-project-onboard.prompt.md",K({description:"Onboard a project into RapidKit Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, external create-adopt, or adopt-only lane","Safe commands","Post-onboarding verification"]})],[".github/prompts/rapidkit-adopt-project.prompt.md",K({description:"Adopt an existing project into RapidKit governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[l,f]of a)d$1(await u(s.join(t,l),f,n$1),l);if(e.hydratePrompts===true)for(let l of await ke({workspacePath:t,skills:z.skills,write:n$1}))d$1(n$1?"written":"skipped",l);}if(d$1(await u(s.join(t,".github/skills/rapidkit-grounding/SKILL.md"),ct(),n$1),".github/skills/rapidkit-grounding/SKILL.md"),c$1==="enterprise"){d$1(await u(s.join(t,".github/skills/rapidkit-workspace-intelligence/SKILL.md"),at(Q),n$1),".github/skills/rapidkit-workspace-intelligence/SKILL.md");let a=[["artifact-map.md",S({title:"Artifact Map",lines:O.map(f=>`- \`${f.relativePath}\` \u2014 ${f.label}`)})],["command-map.md",S({title:"Command Map",lines:["- `npx rapidkit workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx rapidkit workspace model --json --write` \u2014 refresh workspace model.","- `npx rapidkit doctor workspace` \u2014 refresh health evidence.","- `npx rapidkit workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",S({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",S({title:"Runtime Support",lines:["- Native create is available only for RapidKit-owned scaffold contracts.","- Unsupported stacks should use external-create-adopt when a stable ecosystem generator exists.","- Existing projects should use adopt-only when native create is unavailable."]})],["create-planner-capabilities.md",S({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native-create, external-create-adopt, or adopt-only.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",nt()]];for(let[f,b]of a){let R=`.github/skills/rapidkit-workspace-intelligence/resources/${f}`;d$1(await u(s.join(t,R),b,n$1),R);}let l=[["workspai-advisor.agent.md",L({name:"Workspai Advisor",description:"Read-only workspace and project guidance using RapidKit evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",L({name:"Workspai Repair",description:"Turn RapidKit blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",L({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",L({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with RapidKit contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[f,b]of l){let R=`.github/agents/${f}`;d$1(await u(s.join(t,R),b,n$1),R);}}}c$1==="enterprise"&&d$1(await u(s.join(t,".rapidkit/reports/rapidkit-mcp-design.json"),st({workspacePath:t,generatedAt:A.generatedAt}),n$1),".rapidkit/reports/rapidkit-mcp-design.json"),c$1==="enterprise"&&e.experimentalHooks===true&&d$1(await u(s.join(t,".vscode/rapidkit-agent-hooks.json"),ot({workspacePath:t,generatedAt:A.generatedAt}),n$1),".vscode/rapidkit-agent-hooks.json"),(w(o,"codex")||w(o,"orca"))&&(w(o,"agents")||d$1(await Y({absolutePath:s.join(t,"AGENTS.md"),generatedBody:Ae({index:A,context:v}),write:n$1}),"AGENTS.md"));let F=n$1?await we({workspacePath:t,staleAfterHours:i,now:r}):A,T=F.reports.filter(a=>a.required&&!a.exists).map(a=>a.path),W=F.reports.filter(a=>a.exists&&Ke(a.generatedAt,i,r)).map(a=>a.path);if(m){T.length>0&&P.push(`Missing required reports: ${T.join(", ")}`),W.length>0&&P.push(`Stale reports (>${i}h): ${W.join(", ")}`);let a=H.map(l=>l.path).filter(l=>!Ue(l));a.length>0&&P.push(`Unsafe generated output paths: ${a.join(", ")}`);}let ee=pt({workspacePath:t,generatedAt:r.toISOString(),preset:c$1,targets:p,index:F,outputs:[...H,{path:G,kind:"report",targets:["agents","vscode","copilot","codex","orca"],required:true,status:n$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:T,staleReports:W,strictViolations:P,experimentalHooks:e.experimentalHooks===true});return d$1(await u(s.join(t,G),`${JSON.stringify(ee,null,2)}
|
|
32
|
+
`,n$1),G),{workspacePath:t,indexPath:s.join(t,J),packPath:s.join(t,G),pack:ee,contextPath:j$1,writtenFiles:q,skippedFiles:$,blockers:A.blockers,missingRequired:T,staleReports:W,strictViolations:P}}export{Se as a,ve as b,Ne as c,_e as d,J as e,he as f,G as g,O as h,we as i,Vt as j,zt as k,We as l};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {d,a,b,e}from'./chunk-64RTZBHU.js';import {n,q,g}from'./chunk-YBS2HGO3.js';import {h,i,f,e as e$1}from'./chunk-UZW5QFRW.js';import {d as d$1}from'./chunk-S5KTATOU.js';import {a as a$1}from'./chunk-TDSIF42O.js';import {e as e$2,g as g$1}from'./chunk-WRMCPKGA.js';import _ from'fs';import k from'path';import E from'chalk';import {execa}from'execa';function xe(e){return _.existsSync(k.join(e,"bun.lock"))||_.existsSync(k.join(e,"bunfig.toml"))?"bun":_.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":_.existsSync(k.join(e,"yarn.lock"))?"yarn":(_.existsSync(k.join(e,"package-lock.json")),"npm")}function Re(e,t,r=xe(e)){return r==="npm"?`npm run ${t}`:`${r} run ${t}`}function ve(e,t=xe(e)){return `${t} install`}var Me={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},Ie={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],elixir:["mix deps.get"],ruby:["bundle install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],elixir:["mix compile"],ruby:["gem build *.gemspec"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function te(e,t){if(t){let r=t.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=e$1(t),a=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:r==="fiber"?"fiber":r==="aspnetcore"||r==="asp-net-core"?"aspnetcore":r}`;return Me[a]}}function Se(e,t,r){if(t){let n=te(e,t);if(n&&n.commands[r])return n.commands[r]}if(["init","test","build","start"].includes(r)){let n=Ie[r]?.[e]??[];return n.length>0?n[0]:void 0}}var Le={test:"test",build:"build",start:"start"};function re(e){if(e.stage==="init")return e.runtime==="node"?ve(e.projectPath):Se(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let t=Le[e.stage];if(t){let r=g(e.projectPath,t,{framework:e.framework});if(r)return Re(e.projectPath,r.scriptName)}}return Se(e.runtime,e.framework,e.stage)}function _e(e){let t=h(e).map(r=>r==="python"?"python":r==="node"||r==="bun"?"node":r==="go"?"go":r==="java"?"java":r==="php"?"php":r==="rust"?"rust":r==="dotnet"?"dotnet":r==="elixir"?"elixir":r==="ruby"?"ruby":r==="clojure"||r==="scala"||r==="kotlin"?"jvm-generic":null).filter(r=>r!==null).filter((r,n,o)=>o.indexOf(r)===n);return {primary:t.length>0?t[0]:"unknown",secondary:t.slice(1)}}function je(e){return _e(e).primary}function ne(e,t){if(!e)return "unknown";t||(t={setup:["ModuleNotFoundError","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[r,n]of Object.entries(t))for(let o of n)if(new RegExp(o,"i").test(e))return r;return "unknown"}async function U(e){let t=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(t))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[t],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${t}' not found or not executable`}}function Ee(e,t,r){if(!t)return e;let n=typeof t=="object"&&!Array.isArray(t)&&("dev"in t||"staging"in t||"prod"in t||"default"in t)&&!Object.keys(t).some(o=>["init","test","build","start"].includes(o))?t:{};return r&&typeof n[r]=="string"?n[r]:typeof n.default=="string"?n.default:e}var Ce={init:"init",test:"test",build:"build",start:"start"};function Ge(e){return e in Ce?Ce[e]:null}function Be(e,t){let n$1=n(e)?.contextJson?.commands;if(!n$1||typeof n$1!="object"||Array.isArray(n$1))return;let o=n$1[t];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c=a.default??a.dev;if(typeof c=="string"&&c.trim().length>0)return c.trim()}}function Pe(e,t,r=q(e)){let n=Ge(t);if(!n)return Be(e,t)?{supported:true}:{supported:false,reason:`Workspace stage "${t}" is not part of the RapidKit fleet contract.`};if(!r.projectRoot)return {supported:false,reason:"No RapidKit project metadata was detected for this target."};let o=r.commandMap[n];return !o||o.status!=="supported"?{supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`}:{supported:true}}var Ke=new Set(["init","test","build","start"]),ze=new Set([".git","node_modules",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function I(e){try{return await _.promises.access(e,_.constants.F_OK),true}catch{return false}}async function Ve(e,t,r){if(t==="python"){let o=k.join(e,".rapidkit","cli.py");return await I(o)?{valid:true}:{valid:false,reason:"Project-local .rapidkit/cli.py is missing. Run `rapidkit init` in this project first."}}let n=r.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let o=e$2(n);if((await execa(o.command,[...o.prefixArgs,"--version"],{reject:false,env:g$1()})).exitCode===0)return {valid:true}}return U(r)}async function se(e){let t=await _.promises.readFile(e,"utf-8");return JSON.parse(t)}function N(e){return e.replace(/\\/g,"/")}function He(e){let t=e?.trim();return t?t.startsWith("project:")?t.slice(8).trim()||null:t:null}async function Ue(e){return a$1(e,{skipDirs:ze,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,r)=>await I(k.join(t,".rapidkit","context.json"))||await I(k.join(t,".rapidkit","project.json"))?true:k.resolve(t)===k.resolve(r)?false:h(t).length>0})}async function Je(e){for(let t of [k.join(".rapidkit","project.json"),k.join(".rapidkit","context.json")]){let r=k.join(e,t);if(await I(r))try{let n=await se(r),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function qe(e,t,r){let n=He(r);if(!n)return {projects:t,normalizedScope:null};let o=N(n).toLowerCase(),a=[];for(let c of t){let u=N(k.relative(e,c)),p=k.basename(c),m=await Je(c);[u,p,m].filter(s=>typeof s=="string"&&s.length>0).map(s=>N(s).toLowerCase()).includes(o)&&a.push(c);}if(a.length===0)throw new Error(`Workspace run scope did not match any project: ${r}`);return {projects:a,normalizedScope:n}}async function Ye(e,t,r){let n=await execa("git",["diff","--name-only",`${r}...HEAD`],{cwd:e,reject:false});if(n.exitCode!==0)return new Set(t);let o=n.stdout.split(/\r?\n/).map(c=>c.trim()).filter(c=>c.length>0).map(c=>N(c));if(o.length===0)return new Set;let a=new Set;for(let c of t){let u=N(k.relative(e,c));if(!u||u===".")continue;let p=`${u}/`;o.some(m=>m===u||m.startsWith(p))&&a.add(c);}return a}async function Qe(e,t,r){let n=k.join(e,".rapidkit","workspace.contract.json");if(await I(n))try{let g=await Xe(e,t,r,n);if(g.graphStatus!=="missing")return g}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let o=k.join(e,".rapidkit","workspace-dependency-graph.json");if(!await I(o))return {expanded:r,graphStatus:"missing",expansionDepth:0};let a;try{a=await se(o);}catch{return {expanded:r,graphStatus:"invalid",expansionDepth:0}}let c=new Set(t.map(g=>k.resolve(g))),u=new Map;if(!a||typeof a!="object"||Array.isArray(a))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let p=Array.isArray(a.projects)?a.projects:[];for(let g of p){if(!g||typeof g!="object"||Array.isArray(g))continue;let s=g,d=typeof s.path=="string"?s.path:"",y=k.resolve(e,d);if(!c.has(y))continue;let h=Array.isArray(s.dependsOn)?s.dependsOn.filter(b=>typeof b=="string"):[];for(let b of h){let x=k.resolve(e,b);c.has(x)&&(u.has(x)||u.set(x,new Set),u.get(x)?.add(y));}}let m=d$1(u,r);return {expanded:m.reached,graphStatus:"loaded",expansionDepth:m.added}}async function Xe(e,t,r,n){let o=await se(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:r,graphStatus:"invalid",expansionDepth:0};let a=o,c=Array.isArray(a.projects)?a.projects:null;if(!c)return {expanded:r,graphStatus:"invalid",expansionDepth:0};let u=new Map,p=new Map;for(let y of t){let h=N(k.relative(e,y));p.set(h,k.resolve(y));}let m=new Map,g=new Map,s=new Map;for(let y of c){if(!y||typeof y!="object"||Array.isArray(y))continue;let h=y,b=typeof h.slug=="string"?h.slug:"",x=typeof h.relativePath=="string"?N(h.relativePath):b,v=p.get(x);!b||!v||u.set(b,v);}for(let y of c){if(!y||typeof y!="object"||Array.isArray(y))continue;let h=y,b=typeof h.slug=="string"?h.slug:"",x=u.get(b);if(!x)continue;let v=h.contracts&&typeof h.contracts=="object"&&!Array.isArray(h.contracts)?h.contracts:{},S=Array.isArray(v.dependsOn)?v.dependsOn.filter(R=>typeof R=="string"):[],O=Array.isArray(v.publishes)?v.publishes.filter(R=>typeof R=="string"):[],$=Array.isArray(v.consumes)?v.consumes.filter(R=>typeof R=="string"):[];for(let R of S){let j=u.get(R);j&&(s.has(j)||s.set(j,new Set),s.get(j)?.add(x));}for(let R of O)m.has(R)||m.set(R,new Set),m.get(R)?.add(x);for(let R of $)g.has(R)||g.set(R,new Set),g.get(R)?.add(x);}for(let[y,h]of m.entries()){let b=g.get(y);if(b)for(let x of h){s.has(x)||s.set(x,new Set);for(let v of b)v!==x&&s.get(x)?.add(v);}}let d=d$1(s,r);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function Ze(e,t){if(typeof t=="boolean")return t;let r=k.join(e,".rapidkit","policies.yml");if(!await I(r))return true;let n="";try{n=await _.promises.readFile(r,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function et(e){let t=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(t){let r=Number.parseInt(t,10);if(Number.isFinite(r)&&r>0)return r}return e==="init"?12e4:9e4}async function oe(e,t,r){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=await execa(process.execPath,[n,...e],{cwd:t,reject:false,timeout:r,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function tt(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"}function rt(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}async function nt(e){let t=process.cwd();try{process.chdir(e);let{handleInitCommand:r}=await import('./index.js');return {exitCode:await r(["init"]),stdout:"",stderr:""}}finally{process.chdir(t);}}async function ot(e){let t=s=>{let d=f(s);return d==="node"||d==="bun"?"node":d==="python"?"python":d==="go"?"go":d==="java"?"java":d==="php"?"php":d==="ruby"?"ruby":d==="rust"?"rust":d==="dotnet"?"dotnet":d==="elixir"?"elixir":d==="clojure"||d==="scala"||d==="kotlin"?"jvm-generic":je(e)},r=s=>{if(!s)return;let d=e$1(s);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(d))return d},n$1=n(e),o=n$1?.detection??i(e,n$1?.projectJson??null),a=n$1?.contextJson,c=t(o.runtime),u=r(o.key),p={},m=new Set(["init","test","build","start"]);if(a?.commands&&typeof a.commands=="object")for(let[s,d]of Object.entries(a.commands))typeof d=="string"&&m.has(s)&&(p[s]=d);let g;if(a?.commandEnvironments&&typeof a.commandEnvironments=="object"){let s=a.commandEnvironments;g={dev:typeof s.dev=="string"?s.dev:void 0,staging:typeof s.staging=="string"?s.staging:void 0,prod:typeof s.prod=="string"?s.prod:void 0,default:typeof s.default=="string"?s.default:void 0};}return {runtime:c,framework:u,commandOverrides:Object.keys(p).length>0?p:void 0,environmentCommandVariants:g,environment:typeof a?.environment=="string"?a.environment:void 0}}async function st(e,t,r,n,o,a,c){let u=!o?.[t]&&tt(r),p;if(o&&o[t]?p=o[t]:u?p=`rapidkit ${t}`:p=re({projectPath:e,runtime:r,framework:n,stage:t}),!p)return {exitCode:127,command:`<stage not supported for ${r}>`,message:`No stage command found for runtime '${r}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let m=Ee(p,a,c);if(!m)return {exitCode:127,command:p,message:"Failed to resolve stage command",errorCategory:"runtime"};let g=re({projectPath:e,runtime:r,framework:n,stage:t});if(u){if(g){let f=u?await Ve(e,r,g):await U(g);if(!f.valid)return {exitCode:127,command:m,message:f.reason||"Command not available",errorCategory:"setup"}}}else {let f=await U(m);if(!f.valid)return {exitCode:127,command:m,message:f.reason||"Command not available",errorCategory:"setup"}}let s=0,d="",y="",h,b=et(t),x=Date.now();try{let f=u?t==="init"&&rt()?await nt(e):await oe([t],e,b):await execa(m,[],{cwd:e,reject:false,shell:true,timeout:b});if(s=Number(f.exitCode??0),d=f.stdout,y=f.stderr,s!==0){let C=`${d}
|
|
2
|
+
${y}`,B=Date.now()-x;h=s===124||ne(C)==="timeout"||s===143&&B>=Math.floor(b*.8)?"timeout":ne(C);}}catch(f){let C=typeof f=="object"&&f!==null&&"timedOut"in f&&!!f.timedOut;return {exitCode:C?124:1,command:m,message:C?`Stage timed out after ${b}ms`:f instanceof Error?f.message:"Command execution failed",errorCategory:C?"timeout":"runtime"}}let v,S=`${d}
|
|
3
|
+
${y}`.split(/\r?\n/).map(f=>f.trim()).filter(Boolean),O=S.slice(0,6).join(`
|
|
4
|
+
`),$=Date.now()-x,R=s===124||h==="timeout"||s===143&&$>=Math.floor(b*.8),j=s===0?void 0:R?"timeout":h,T=s===0||!j?void 0:{category:j,exitCode:s,command:m,timedOut:R,timeoutMs:b,...O?{outputExcerpt:O}:{}};return {exitCode:s,command:m,errorCategory:j,healthStatus:v,failureDiagnostic:T,message:R?`Stage timed out after ${b}ms`:s!==0?O?`Stage failed with exit code ${s}: ${S[0]}`:`Stage failed with exit code ${s}`:void 0}}function Fe(e){try{return JSON.parse(e)}catch{return null}}function at(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx rapidkit setup dotnet` or `npx rapidkit init`.";case "go":return "Install Go 1.21+, then rerun `npx rapidkit setup go` or `npx rapidkit init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx rapidkit setup java` or `npx rapidkit init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx rapidkit setup node` or `npx rapidkit init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx rapidkit setup python` or `npx rapidkit init`.";default:return null}}async function it(e){let t=[],r=await oe(["doctor","workspace","--json"],e);if(r.exitCode!==0)t.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let a=Fe(r.stdout)?.healthScore,c=Number(a?.errors??0);Number.isFinite(c)&&c>0?t.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${c} error(s)`}):t.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await oe(["readiness","--json"],e);if(n.exitCode!==0)t.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=Fe(n.stdout),a=String(o?.overallStatus??"").toLowerCase();a==="fail"?t.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):a==="warn"?t.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):t.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return t}var ct=new Set(["dev","stop"]);function ut(e){let t=e.trim();return !t||ct.has(t.toLowerCase())?false:Ke.has(t)?true:/^[a-z][a-z0-9_-]*$/i.test(t)}function Ae(e,t,r){let n=N(k.relative(r,t));return (Array.isArray(e.projects)?e.projects:[]).some(a=>{if(!a||typeof a!="object")return false;let c=a,u=[c.relativePath,c.path].filter(p=>typeof p=="string"&&p.length>0).map(p=>N(p));return c.status==="passed"&&(u.includes(n)||u.some(p=>p.endsWith(`/${n}`)))})}function dt(e,t){return te(e,t)?.dependencies??[]}function lt(e,t){let r=Math.max(1,Math.min(4,t)),n=Number(e??r);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):r}async function Kt(e$1){if(!ut(e$1.stage))throw new Error(`Unsupported workspace run stage: ${e$1.stage}`);let t=Date.now(),r=k.resolve(e$1.workspacePath),n=await d(r),o=await Ue(r),{projects:a$1,normalizedScope:c}=await qe(r,o,e$1.scope),u=e$1.affected===true,p=e$1.blastRadius===true,m=e$1.since?.trim()||"HEAD~1",g=u?await Ye(r,a$1,m):new Set(a$1),s,d$1="not-applicable",y=0,h="all";if(u&&p){let l=await Qe(r,o,g);s=l.expanded,d$1=l.graphStatus,y=l.expansionDepth,h="affected+blast-radius";}else u?(s=g,h="affected"):(s=g,h="all");let b$1=e$1.stage==="init"?false:await Ze(r,e$1.enforceGates),x=b$1?await it(r):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],v=x.find(l=>l.status==="fail"),S=a$1.filter(l=>s.has(l)),O=e$1.continueOnError===true||e$1.stage==="init",$=e$1.parallel===true,R=lt(e$1.maxWorkers,S.length),j=S.length,T=0;e$1.json||console.log(E.gray(`Workspace run (${e$1.stage}) started: ${j} target(s), ${$?`parallel x${R}`:"sequential"}`));let f=new Map;for(let l of o){let w=N(k.relative(r,l)),i=a$1.includes(l),F=i&&s.has(l);f.set(l,{path:l,relativePath:w,projectName:k.basename(w)||k.basename(l),selected:F,affected:F,status:"skipped",exitCode:null,durationMs:0,reason:F?void 0:i?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(v)for(let l of S){let w=f.get(l);w&&(w.status="skipped",w.reason=`blocked by ${v.gate}`);}else {let l=async w=>{let i=f.get(w);if(!i)return;let F=N(k.relative(r,w));e$1.json||console.log(E.gray(`\u23F3 [${T}/${j}] ${e$1.stage} ${F}`)),i.selected=true,i.affected=true;let A=Date.now(),{runtime:P,framework:D,commandOverrides:De,environmentCommandVariants:Te,environment:We}=await ot(w);i.runtimeDetected=P,i.framework=D;let ue=Pe(w,e$1.stage);if(!ue.supported){i.status="skipped",i.reason=ue.reason??`stage "${e$1.stage}" unsupported for project`,i.durationMs=Date.now()-A,i.exitCode=null,T+=1;return}if(e$1.reusePassed&&n){let M=n.stages[e$1.stage]??n.stages[e$1.stage];if(M&&Ae(M,w,r)){i.status="passed",i.reason="reused passed result from workspace-run-last.json",i.durationMs=Date.now()-A,i.exitCode=0,T+=1,e$1.json||console.log(E.gray(`\u21BA reused passed cache for ${F}`));return}}let de=dt(P,D);if(de.length>0&&n){let M=de.find(Y=>{let L=n.stages[Y];return !L||!Ae(L,w,r)});if(M){i.status="skipped",i.reason=`dependency stage "${M}" not satisfied in workspace-run-last.json`,i.durationMs=Date.now()-A,i.exitCode=null,T+=1;return}}let W=await st(w,e$1.stage,P,D,De,Te,We);if(i.executionCommand=W.command,i.errorCategory=W.errorCategory,i.healthStatus=W.healthStatus,i.failureDiagnostic=W.failureDiagnostic,i.durationMs=Date.now()-A,i.exitCode=W.exitCode,W.exitCode===0?(i.status="passed",i.reason=void 0):(i.status="failed",i.reason=W.message||"stage command failed",i.errorMessage=W.message),T+=1,!e$1.json){let M=j>0?Math.round(T/j*100):100,Y=i.status==="passed"?E.green("\u2705"):E.red("\u274C");if(console.log(E.gray(`${Y} [${T}/${j}] (${M}%) ${F} ${i.durationMs}ms`)),i.status==="failed"){i.reason&&console.log(E.red(` Reason: ${i.reason}`)),i.executionCommand&&console.log(E.gray(` Command: ${i.executionCommand}`));let L=at(i.runtimeDetected);L&&i.errorCategory==="setup"&&console.log(E.gray(` Hint: ${L}`));}}};if($&&S.length>1){let w=0,i=false,F=new Array(R).fill(null).map(async()=>{for(;w<S.length;){if(i&&!O)return;let A=w;w+=1;let P=S[A];await l(P),f.get(P)?.status==="failed"&&(i=true);}});if(await Promise.all(F),!O&&i){let A=false;for(let P of S){let D=f.get(P);if(D){if(D.status==="failed"){A=true;continue}A&&D.status==="skipped"&&(D.reason=D.reason||"stopped after failure");}}}}else for(let w of S){await l(w);let i=f.get(w);if(!O&&i?.status==="failed"){let F=S.slice(S.indexOf(w)+1);for(let A of F){let P=f.get(A);P&&(P.status="skipped",P.reason="stopped after failure");}break}}}let C=[];for(let l of o){let w=f.get(l);w&&C.push(w);}let B=C.filter(l=>l.status==="passed").length,K=C.filter(l=>l.status==="failed").length,ae=C.filter(l=>l.status==="skipped").length,ie=e$1.strict===true,Ne=K>0||ie&&x.some(l=>l.status==="fail"||l.status==="warn")?1:0,ce={schemaVersion:"1.0",workspacePath:r,stage:e$1.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-t,options:{affected:u,blastRadius:p,since:u?m:null,parallel:$,maxWorkers:R,continueOnError:O,strict:ie,enforceGates:b$1,scope:c,reusePassed:e$1.reusePassed===true},selection:{mode:h,since:u?m:null,scope:c,graphStatus:d$1,expansionDepth:y},gates:{enforced:b$1,results:x,blocked:!!v,blockingGate:v?.gate},summary:{projectCount:o.length,selectedCount:S.length,passed:B,failed:K,skipped:ae,exitCode:Ne},projects:C,enterpriseControls:{jsonReady:true,evidencePath:b}},Oe=k.join(r,".rapidkit","reports",a);return await e(r,ce),e$1.json||(v&&(console.log(E.red(`\u274C Workspace run blocked by ${v.gate}`)),console.log(E.gray(` ${v.summary}`))),console.log(E.cyan(`Workspace run (${e$1.stage}) => passed: ${B}, failed: ${K}, skipped: ${ae}`)),console.log(E.gray(`Report: ${Oe}`))),ce}export{Kt as a};
|