rapidkit 0.32.1 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export{b as CANONICAL_MODULE_ROOT,a as MODULE_LAYOUT_SCHEMA_VERSION,c as MODULE_PATH_PATTERN,d as MODULE_SLUG_PATTERN,e as MODULE_SLUG_PREFIX,i as auditProjectModulePaths,j as auditWorkspaceModulePaths,f as isCanonicalModuleSlug,k as moduleLayoutContractSummary,g as resolveCanonicalModulePath,h as resolveCanonicalModuleRelativePath}from'./chunk-4E6ZGX6V.js';
@@ -1 +1 @@
1
- export{k as __test__,b as checkRapidkitCoreAvailable,c as checkRapidkitCoreVersionCompatible,i as getCachedCoreTopLevelCommands,h as getCoreTopLevelCommands,j as getModulesCatalog,d as resolveRapidkitPython,e as runCoreRapidkit,g as runCoreRapidkitCapture,f as runCoreRapidkitStreamed}from'./chunk-BFCIY2QK.js';
1
+ export{k as __test__,b as checkRapidkitCoreAvailable,c as checkRapidkitCoreVersionCompatible,i as getCachedCoreTopLevelCommands,h as getCoreTopLevelCommands,j as getModulesCatalog,d as resolveRapidkitPython,e as runCoreRapidkit,g as runCoreRapidkitCapture,f as runCoreRapidkitStreamed}from'./chunk-W62Q2D3K.js';
@@ -1,6 +1,6 @@
1
1
  import {a}from'./chunk-VKLL63TL.js';import {c}from'./chunk-NFUXULIF.js';import {j}from'./chunk-Z5LKRG57.js';import {b}from'./chunk-AC6KIKII.js';import {promises}from'fs';import o from'path';import i from'chalk';import S from'ora';import {execa}from'execa';function _(e){let t=o.resolve(e);return process.platform==="win32"?t.toLowerCase():t}function O(e){let t=_(e.path),r=Array.isArray(e.projects)?e.projects:[],a=[],c=new Set;for(let s of r){if(!s||typeof s.name!="string"||typeof s.path!="string")continue;let n=_(s.path);c.has(n)||(c.add(n),a.push({name:s.name,path:n}));}return {name:e.name,path:t,mode:e.mode,projects:a}}function P(e){let t=[],r=new Set;for(let a of e.workspaces||[]){if(!a||typeof a.name!="string"||typeof a.path!="string")continue;let c=O(a);r.has(c.path)||(r.add(c.path),t.push(c));}return {workspaces:t}}async function B(e,t){try{let r=_(e),a=j(),c=o.join(a,"workspaces.json");await promises.mkdir(a,{recursive:true});let s={workspaces:[]};try{let p=await promises.readFile(c,"utf8"),d=JSON.parse(p);d&&Array.isArray(d.workspaces)&&(s=P(d));}catch{}s.workspaces.some(p=>p.path===r)||(s.workspaces.push({name:t,path:r,mode:"full",projects:[]}),await promises.writeFile(c,JSON.stringify(s,null,2)));}catch{console.warn(i.gray("Note: Could not register workspace in shared registry"));}}async function ae(e,t=false){try{let r=_(e),a=j(),c=o.join(a,"workspaces.json"),s={workspaces:[]};try{let m=await promises.readFile(c,"utf8"),y=JSON.parse(m);y&&Array.isArray(y.workspaces)&&(s=P(y));}catch{t||console.log("\u26A0\uFE0F Workspace registry not found");return}let n=s.workspaces.find(m=>m.path===r);if(!n){t||console.log("\u26A0\uFE0F Workspace not registered in registry");return}Array.isArray(n.projects)||(n.projects=[]);let p=0,d=0,u=[e],g=new Set;for(;u.length>0;){let m=u.shift();if(!m||g.has(m))continue;g.add(m);let y=await promises.readdir(m,{withFileTypes:true});for(let w of y){if(!w.isDirectory()||w.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(w.name))continue;let h=o.join(m,w.name),f=_(h),R=o.join(f,".rapidkit","context.json"),k=o.join(f,".rapidkit","project.json");try{let $=false;try{await promises.access(R),$=true;}catch{await promises.access(k),$=true;}if($){let x=o.basename(f);n.projects.some(j=>j.path===f||j.name===x)?d++:(n.projects.push({name:x,path:f}),p++,t||console.log(`\u2714 Added: ${o.relative(e,f)}`));continue}}catch{}u.push(h);}}p>0?(await promises.writeFile(c,JSON.stringify(s,null,2)),t||console.log(`
2
2
  \u2705 Synced ${p} project(s) to registry`)):t||console.log(`
3
- \u2705 All projects already registered (${d} found)`);}catch(r){t||console.error("\u274C Failed to sync projects:",r.message);}}async function oe(e,t,r){try{let a=_(e),c=_(r),s=j(),n=o.join(s,"workspaces.json"),p={workspaces:[]};try{let g=await promises.readFile(n,"utf8"),m=JSON.parse(g);m&&Array.isArray(m.workspaces)&&(p=P(m));}catch{return}let d=p.workspaces.find(g=>g.path===a);if(!d)return;Array.isArray(d.projects)||(d.projects=[]),d.projects.some(g=>g.path===c||g.name===t)||(d.projects.push({name:t,path:c}),await promises.writeFile(n,JSON.stringify(p,null,2)));}catch{}}async function ne(e,t){let r=S("Creating RapidKit workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(o.join(e,".rapidkit"),{recursive:true});let a={workspace_name:t.name,author:t.author,rapidkit_version:b(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(o.join(e,".rapidkit","config.json"),JSON.stringify(a,null,2));let{syncWorkspaceFoundationFiles:c}=await import('./create-6AMYKNEG.js');await c(e,{workspaceName:t.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=T();await promises.writeFile(o.join(e,"rapidkit"),s),await promises.chmod(o.join(e,"rapidkit"),493);let n=z();await promises.writeFile(o.join(e,"rapidkit.cmd"),n);let p=U(t.name);if(await promises.writeFile(o.join(e,"README.md"),p),await promises.writeFile(o.join(e,".gitignore"),`# RapidKit workspace
3
+ \u2705 All projects already registered (${d} found)`);}catch(r){t||console.error("\u274C Failed to sync projects:",r.message);}}async function oe(e,t,r){try{let a=_(e),c=_(r),s=j(),n=o.join(s,"workspaces.json"),p={workspaces:[]};try{let g=await promises.readFile(n,"utf8"),m=JSON.parse(g);m&&Array.isArray(m.workspaces)&&(p=P(m));}catch{return}let d=p.workspaces.find(g=>g.path===a);if(!d)return;Array.isArray(d.projects)||(d.projects=[]),d.projects.some(g=>g.path===c||g.name===t)||(d.projects.push({name:t,path:c}),await promises.writeFile(n,JSON.stringify(p,null,2)));}catch{}}async function ne(e,t){let r=S("Creating RapidKit workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(o.join(e,".rapidkit"),{recursive:true});let a={workspace_name:t.name,author:t.author,rapidkit_version:b(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(o.join(e,".rapidkit","config.json"),JSON.stringify(a,null,2));let{syncWorkspaceFoundationFiles:c}=await import('./create-M7LT6WF6.js');await c(e,{workspaceName:t.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=T();await promises.writeFile(o.join(e,"rapidkit"),s),await promises.chmod(o.join(e,"rapidkit"),493);let n=z();await promises.writeFile(o.join(e,"rapidkit.cmd"),n);let p=U(t.name);if(await promises.writeFile(o.join(e,"README.md"),p),await promises.writeFile(o.join(e,".gitignore"),`# RapidKit workspace
4
4
  .env
5
5
  .env.*
6
6
  !.env.example
@@ -0,0 +1 @@
1
+ export{a as WORKSPACE_CONTRACT_PATH,b as WORKSPACE_CONTRACT_SCHEMA_VERSION,d as buildWorkspaceContract,h as buildWorkspaceContractGraph,c as discoverProjectJsonFiles,g as readWorkspaceContract,f as syncWorkspaceContract,i as verifyWorkspaceContract,e as writeWorkspaceContract}from'./chunk-Y3UKTEZO.js';
@@ -0,0 +1 @@
1
+ import {a as a$1}from'./chunk-MSW2I3F3.js';import {a}from'./chunk-RV6HBTFC.js';import c from'path';import d from'fs-extra';async function v(e,r){let o=await a(e),f=o?.name||c.basename(e),n,i=c.join(e,".python-version");if(await d.pathExists(i)){let a=(await d.readFile(i,"utf-8")).trim();a&&(n=a);}let t=r?.profile||"polyglot",u=t==="python-only"||t==="polyglot"||t==="enterprise",m=r?.installMethod||o?.metadata?.npm?.installMethod||(u?"poetry":"venv"),s=await a$1(e,{workspaceName:f,installMethod:m,pythonVersion:n,profile:t,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force});return {workspacePath:e,created:s,status:s.length>0?"passed":"skipped"}}export{v as ensureWorkspaceFoundation};
@@ -0,0 +1 @@
1
+ export{a as runWorkspaceStage}from'./chunk-CXKXZUV6.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rapidkit",
3
- "version": "0.32.1",
3
+ "version": "0.33.0",
4
4
  "type": "module",
5
5
  "description": "Official CLI for RapidKit, an open-source workspace platform that standardizes how teams build, scale, and deploy backend services.",
6
6
  "keywords": [
@@ -34,6 +34,7 @@
34
34
  },
35
35
  "files": [
36
36
  "dist",
37
+ "contracts",
37
38
  "data/modules-embeddings.json",
38
39
  "scripts/enforce-package-manager.cjs",
39
40
  "scripts/check-cli-resolution.cjs"
@@ -52,23 +53,23 @@
52
53
  "dev:local": "npm run build && npm link",
53
54
  "install:local": "npm unlink -g rapidkit && npm run build && npm link",
54
55
  "uninstall:local": "npm unlink -g rapidkit",
55
- "prepare": "husky",
56
+ "prepare": "node scripts/prepare-husky.mjs",
56
57
  "test:e2e:first-install": "bash scripts/e2e-first-install.sh",
57
58
  "test:e2e:user-first-install": "bash scripts/e2e-user-first-install.sh",
58
59
  "test": "vitest run",
59
- "test:drift": "RAPIDKIT_DRIFT_GUARD=1 vitest run src/__tests__/drift-guard.test.ts",
60
+ "test:drift": "node scripts/run-drift-guard.mjs",
60
61
  "sync:parity-snapshot": "node scripts/sync-import-stack-parity-snapshot.mjs",
61
62
  "check:parity-snapshot": "node scripts/sync-import-stack-parity-snapshot.mjs --check",
62
63
  "test:parity-contract": "npm run sync:parity-snapshot -- --npm-only && vitest run src/__tests__/contracts/import-stack-parity.snapshot.test.ts",
63
64
  "test:watch": "vitest",
64
65
  "test:coverage": "vitest run --coverage",
65
- "test:prepare-embeddings": "npx tsx scripts/generate-mock-embeddings.ts",
66
+ "test:prepare-embeddings": "node scripts/prepare-mock-embeddings.mjs",
66
67
  "generate-embeddings": "npx tsx src/ai/generate-embeddings.ts",
67
68
  "verify:package-cli": "node scripts/verify-package-cli.mjs",
68
69
  "prepack": "npm run build && npm run test:prepare-embeddings && npm run verify:package-cli",
69
70
  "test:e2e": "vitest run src/__tests__/e2e.test.ts",
70
- "test:scenarios": "bash scripts/scenario-matrix-local.sh",
71
- "test:scenarios:full": "RAPIDKIT_SCENARIO_FULL_BOOTSTRAP=1 bash scripts/scenario-matrix-local.sh",
71
+ "test:scenarios": "node scripts/run-scenario-matrix-local.mjs",
72
+ "test:scenarios:full": "node scripts/run-scenario-matrix-local.mjs --full",
72
73
  "test:scenarios:docker": "bash scripts/scenario-matrix.sh",
73
74
  "test:runtime-matrix": "node scripts/runtime-acceptance-matrix.mjs",
74
75
  "test:runtime-matrix:full": "node scripts/runtime-acceptance-matrix.mjs --full",
@@ -88,7 +89,7 @@
88
89
  "validate:docs": "npm run check:markdown-links && npm run check:docs-drift && npm run validate:docs-examples && npm run smoke:readme",
89
90
  "sync:contracts": "node scripts/sync-contracts.mjs",
90
91
  "check:contracts": "node scripts/sync-contracts.mjs --check",
91
- "bundle-size": "npm run build && du -sh dist/ && ls -lh dist/",
92
+ "bundle-size": "npm run build && node scripts/report-dist-size.mjs",
92
93
  "analyze": "npm run build && node scripts/analyze-dist.mjs",
93
94
  "size-check": "npm run build && size-limit",
94
95
  "bench": "npx tsx scripts/benchmarks.ts",
@@ -1,33 +0,0 @@
1
- import {a as a$1,d,e,f,c,g as g$1}from'./chunk-Z5LKRG57.js';import {a}from'./chunk-2FIX2MDC.js';import pt from'crypto';import Z from'os';import u from'path';import*as p from'fs-extra';import {execa}from'execa';var dt=["version","project","create","add","list","info","upgrade","diff","doctor","license","commands","reconcile","rollback","uninstall","checkpoint","optimize","snapshot","frameworks","modules","merge"],$=new Set(dt);var g=a();function X(){return d()}function v(t,n){return t==="py"?["-3",...n]:n}function K(t){if(!t)return t;let n=["Installed Poetry version does not support '--no-update'. Falling back to 'poetry lock'."];return t.split(/\r?\n/).filter(i=>!n.some(o=>i.includes(o))).join(`
2
- `)}var w=class extends Error{code;constructor(n,r){super(r),this.code=n;}};function b(t){if(t instanceof w)switch(t.code){case "PYTHON_NOT_FOUND":return `RapidKit (npm) could not find Python (python3/python/py) on your PATH.
3
- Install Python 3.10+ and ensure \`${c()}\` is available, then retry.
4
- Tip: if you are inside a RapidKit project, use the local ./rapidkit launcher.`;case "BRIDGE_VENV_CREATE_FAILED":return `RapidKit (npm) failed to create its bridge virtual environment.
5
- `+(a$1()?`Ensure Python is installed with venv support.
6
- `:`Ensure Python venv support is installed (e.g., python3-venv).
7
- `)+`Details: ${t.message}`;case "BRIDGE_PIP_BOOTSTRAP_FAILED":return `RapidKit (npm) could not bootstrap pip inside the bridge virtual environment.
8
- `+(a$1()?`Ensure pip is available for your Python installation and retry.
9
- `:`Install python3-venv/python3-pip and retry.
10
- `)+`Details: ${t.message}`;case "BRIDGE_PIP_UPGRADE_FAILED":return `RapidKit (npm) could not upgrade pip in the bridge virtual environment.
11
- Check your network/proxy or disable RAPIDKIT_BRIDGE_UPGRADE_PIP.
12
- Details: ${t.message}`;case "BRIDGE_PIP_INSTALL_FAILED":return `RapidKit (npm) could not install rapidkit-core in the bridge virtual environment.
13
- Check your network/proxy, or install manually with: pipx install rapidkit-core.
14
- Details: ${t.message}`;default:return `RapidKit (npm) bridge error: ${t.message}`}return `RapidKit (npm) failed to run the Python core engine: ${t instanceof Error?t.message:String(t)}`}function A(){let t=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE;return t&&t.trim()?t.trim():"rapidkit-core"}function ut(){let t=A(),n=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE_ID,r=n&&n.trim()?`${t}|${n.trim()}`:t;return pt.createHash("sha256").update(r).digest("hex").slice(0,12)}function I(){let t=process.env.XDG_CACHE_HOME;return t&&t.trim()?t:u.join(Z.homedir(),".cache")}function lt(){return u.join(I(),"rapidkit","npm-bridge","venv")}function q(){let t=ut();return u.join(I(),"rapidkit","npm-bridge",`venv-${t}`)}function L(t){return f(t)}function J(t){return g$1(t)}function Q(t){return /[<>=!~]=|@|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(t)}function mt(t){return u.dirname(u.dirname(t))}function tt(){return u.join(I(),"rapidkit","npm-bridge","core-commands.json")}async function et(t){let n=!!process.env.RAPIDKIT_DEBUG,r=e=>{n&&process.stderr.write(`[DEBUG] tryRapidkit(${t}): ${e}
15
- `);};try{r("probing interpreter-specific rapidkit script");let i=((await execa(t,v(t,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"]),{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(r(`script path: ${i}`),i)try{if(await p.pathExists(i)){r(`found script at ${i}; invoking --version --json`);let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(r(`script exitCode=${o.exitCode}`),o.exitCode===0){let s=(o.stdout??"").toString().trim();try{let a=JSON.parse(s),c=!!a&&typeof a=="object"&&a!==null&&"version"in a;if(r(`script JSON parse ok=${c}`),c)return true}catch{r("script output not valid JSON");}}}}catch(o){r(`interpreter-specific script probe failed: ${String(o)}`);}}catch(e){r(`interpreter-specific script probe error: ${String(e)}`);}try{r('probing importlib.find_spec("rapidkit")');let e=await execa(t,v(t,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"]),{reject:false,stdio:"pipe",timeout:2e3});if(r(`import probe exitCode=${e.exitCode} stdout=${(e.stdout??"").toString().trim()}`),e.exitCode===0&&(e.stdout??"").toString().trim()==="1")return true}catch(e){r(`import probe error: ${String(e)}`);}try{r("probing python -m rapidkit");let e=await execa(t,v(t,["-m","rapidkit","--version","--json"]),{reject:false,stdio:"pipe",timeout:8e3});if(r(`-m probe exitCode=${e.exitCode}`),e.exitCode===0)return true}catch(e){r(`-m probe error: ${String(e)}`);}try{r("probing PATH for rapidkit executables");let e=(process.env.PATH??"").split(u.delimiter).filter(Boolean);for(let i of e){let o=u.join(i,a$1()?"rapidkit.exe":"rapidkit");try{if(await p.pathExists(o)){r(`found candidate on PATH: ${o}; invoking --version --json`);let s=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(r(`candidate exitCode=${s.exitCode}`),s.exitCode===0){let a=(s.stdout??"").toString().trim();try{let c=JSON.parse(a);if(c&&typeof c=="object"&&c!==null&&"version"in c)return true}catch{r("candidate output not valid JSON, skipping");}}}}catch(s){r(`error probing candidate ${o}: ${String(s)}`);}}return r("no valid rapidkit found on PATH"),false}catch(e){return r(`PATH probe error: ${String(e)}`),false}}async function M(t){let n=(t??"").toString().trim();if(!n)return false;try{let r=JSON.parse(n);return !!r&&typeof r=="object"&&r!==null&&"version"in r}catch{return false}}async function ft(t){let n=u.relative(".",g$1(".venv")),r=u.relative(".",f(".venv")),e=t;for(let i=0;i<25;i+=1){let o=u.join(e,n);if(await p.pathExists(o)){let c=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:e});if(c.exitCode===0&&await M(c.stdout))return {cmd:o,baseArgs:[]}}let s=u.join(e,r);if(await p.pathExists(s)){let c=await execa(s,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:e});if(c.exitCode===0&&await M(c.stdout))return {cmd:s,baseArgs:["-m","rapidkit"]}}let a=u.dirname(e);if(a===e)break;e=a;}return null}async function ht(t){try{let n=u.join(t,".python-version");if(await p.pathExists(n)){let e=(await p.readFile(n,"utf-8")).trim();if(e)return e}}catch{}try{let n=u.join(t,".rapidkit-workspace");if(await p.pathExists(n)){let r=await p.readFile(n,"utf-8"),e=JSON.parse(r);if(e.pythonVersion)return e.pythonVersion}}catch{}return null}async function B(t){if(t&&t.trim())try{let o=await ft(t);if(o){let s=u.dirname(o.cmd).includes(".venv")?u.dirname(u.dirname(u.dirname(o.cmd))):u.dirname(o.cmd),a=await ht(s);return a&&(process.env.PYENV_VERSION=a),o}}catch{}let n=await _t();if(n.kind==="venv"){let o=mt(n.pythonPath),s=J(o);return await p.pathExists(s)?{cmd:s,baseArgs:[]}:{cmd:n.pythonPath,baseArgs:["-m","rapidkit"]}}try{if((await execa(n.cmd,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:4e3})).exitCode===0)return {cmd:n.cmd,baseArgs:["-m","rapidkit"]}}catch{}try{let s=((await execa(n.cmd,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(s&&await p.pathExists(s))try{let a=await execa(s,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(a.exitCode===0&&await M(a.stdout))return {cmd:s,baseArgs:[]}}catch{}}catch{}let r=q(),e=await S(n.cmd),i=J(r);return await p.pathExists(i)?{cmd:i,baseArgs:[]}:{cmd:e,baseArgs:["-m","rapidkit"]}}async function V(){for(let t of X())try{return await execa(t,v(t,["--version"]),{reject:false,stdio:"pipe",timeout:2e3}),t}catch{}return null}async function gt(){let t=!!process.env.RAPIDKIT_DEBUG,n=e=>{t&&process.stderr.write(`[DEBUG] checkRapidkitCore: ${e}
16
- `);},r=Array.from(new Set([...d(),...e(14,10).map(e=>e.command)]));for(let e of r)try{n(`Method 1: trying ${e} import`);let i=await execa(e,v(e,["-c","import rapidkit_core; print(1)"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.trim()==="1")return n(`\u2713 Found via ${e} import`),true}catch{continue}for(let e of r)try{n(`Method 2: trying ${e} -m pip show`);let i=await execa(e,v(e,["-m","pip","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.includes("Name: rapidkit-core"))return n(`\u2713 Found via ${e} -m pip show`),true}catch{continue}for(let e of ["pip","pip3"])try{n(`Method 3: trying ${e} show`);let i=await execa(e,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.includes("Name: rapidkit-core"))return n(`\u2713 Found via ${e} show`),true}catch{continue}try{n("Method 4: checking pyenv versions");let e=await execa("pyenv",["versions","--bare"],{reject:false,stdio:"pipe",timeout:g});if(e.exitCode===0&&e.stdout){let i=e.stdout.split(`
17
- `).filter(o=>o.trim());n(`Found pyenv versions: ${i.join(", ")}`);for(let o of i){let s=process.env.PYENV_ROOT||u.join(Z.homedir(),".pyenv"),a=u.join(s,"versions",o.trim(),"bin","pip");try{let c=await execa(a,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(c.exitCode===0&&c.stdout?.includes("Name: rapidkit-core"))return n(`\u2713 Found in pyenv ${o}`),true}catch{try{let c=await execa("pyenv",["exec","pip","show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g,env:{...process.env,PYENV_VERSION:o.trim()}});if(c.exitCode===0&&c.stdout?.includes("Name: rapidkit-core"))return n(`\u2713 Found in pyenv ${o} via PYENV_VERSION`),true}catch{continue}}}}}catch{n("pyenv not available");}for(let e of r)try{n(`Method 5: checking ${e} user site`);let i=await execa(e,v(e,["-m","site","--user-site"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout){let o=i.stdout.trim(),s=u.join(o,"rapidkit_core");if(await p.pathExists(s))return n("\u2713 Found in user site-packages"),true}}catch{continue}try{n("Method 6: checking pipx");let e=await execa("pipx",["list"],{reject:false,stdio:"pipe",timeout:g});if(e.exitCode===0&&e.stdout?.includes("rapidkit-core"))return n("\u2713 Found via pipx"),true}catch{n("pipx not available");}for(let e of r)try{n(`Method 6: checking ${e} -m pipx list`);let i=await execa(e,v(e,["-m","pipx","list"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.includes("rapidkit-core"))return n(`\u2713 Found via ${e} -m pipx list`),true}catch{continue}try{if(n("Method 7: checking poetry"),(await execa("poetry",["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g})).exitCode===0)return n("\u2713 Found via poetry"),true}catch{n("poetry check failed");}for(let e of r)try{if(n(`Method 7: checking ${e} -m poetry show rapidkit-core`),(await execa(e,v(e,["-m","poetry","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:g})).exitCode===0)return n(`\u2713 Found via ${e} -m poetry`),true}catch{continue}try{n("Method 8: checking conda");let e=await execa("conda",["list","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(e.exitCode===0&&e.stdout?.includes("rapidkit-core"))return n("\u2713 Found via conda"),true}catch{n("conda not available");}return n("\u2717 Not found in any environment"),false}function yt(t){let n=t.trim();if(!n||!n.startsWith("rapidkit-core"))return null;let r=n.slice(13).trim();return !r||/[\/@]|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(r)?null:r}function U(t){let n=t.trim();if(!n)return null;let r=n.split("."),e=[];for(let i of r){let o=i.match(/^(\d+)/);if(!o){e.push(0);continue}e.push(Number.parseInt(o[1],10));}return e}function H(t,n){let r=Math.max(t.length,n.length);for(let e=0;e<r;e+=1){let i=e<t.length?t[e]:0,o=e<n.length?n[e]:0;if(i>o)return 1;if(i<o)return -1}return 0}function wt(t){return t.length<=1?[t[0]+1]:t.length===2?[t[0]+1,0]:[t[0],t[1]+1,0]}function vt(t){let n=t.split(",").map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=[];for(let e of n){let i=e.match(/^(==|>=|<=|>|<|~=)\s*([0-9][0-9A-Za-z+._-]*)$/);if(!i)return null;r.push({op:i[1],version:i[2]});}return r}function nt(t,n){let r=U(t);if(!r)return false;let e=vt(n);if(!e)return false;for(let i of e){let o=U(i.version);if(!o)return false;let s=H(r,o);if(i.op==="=="&&s!==0||i.op===">="&&s<0||i.op==="<="&&s>0||i.op===">"&&s<=0||i.op==="<"&&s>=0)return false;if(i.op==="~="){if(s<0)return false;let a=wt(o);if(H(r,a)>=0)return false}}return true}async function Ct(){let t=Array.from(new Set([...d(),...e(14,10).map(r=>r.command)])),n=r=>{let e=r.match(/^Version:\s*(.+)$/m);return e?e[1].trim():null};for(let r of t)try{let e=await execa(r,v(r,["-m","pip","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:g});if(e.exitCode===0){let i=n(e.stdout||"");if(i)return i}}catch{continue}for(let r of ["pip","pip3"])try{let e=await execa(r,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(e.exitCode===0){let i=n(e.stdout||"");if(i)return i}}catch{continue}try{let r=await execa("pipx",["list"],{reject:false,stdio:"pipe",timeout:g});if(r.exitCode===0&&r.stdout){let e=r.stdout.match(/rapidkit-core\s+([0-9][0-9A-Za-z+._-]*)/i);if(e?.[1])return e[1]}}catch{}return null}async function Pt(){let t=A(),n=yt(t);if(!n)return {isCompatible:false,installedVersion:null,expectedConstraint:null,reason:Q(t)?"constraint-unsupported":"constraint-missing"};let r=await Ct();if(!r)return {isCompatible:false,installedVersion:null,expectedConstraint:n,reason:"version-not-detected"};let e=nt(r,n);return {isCompatible:e,installedVersion:r,expectedConstraint:n,reason:e?"compatible":"incompatible-version"}}async function S(t){let n=q(),r=lt(),e=A(),i=[n];!Q(e)&&!await p.pathExists(n)&&await p.pathExists(r)&&i.push(r);for(let l of i){let h=L(l);if(await p.pathExists(h))try{let f=await execa(h,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"],{reject:false,stdio:"pipe",timeout:2e3});if(f.exitCode===0&&(f.stdout??"").toString().trim()==="1")return h;await p.remove(l);}catch{await p.remove(l);}}let o=n,s={...process.env,PIP_DISABLE_PIP_VERSION_CHECK:"1",PIP_NO_PYTHON_VERSION_WARNING:"1"},a=Math.max(0,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY??"2")),c=Math.max(200,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY_DELAY_MS??"800")),m=Math.max(1e4,Number(process.env.RAPIDKIT_BRIDGE_PIP_TIMEOUT_MS??"120000")),C=l=>new Promise(h=>setTimeout(h,l)),P=async(l,h,f)=>{let y=await execa(l,h,{reject:false,stdio:["ignore","pipe","inherit"],env:s,timeout:f});if(y.exitCode===0)return;let D=(y.stdout??"").toString(),O=(y.stderr??"").toString(),x=[D,O].filter(Boolean).join(`
18
- `),st=x?`${l} ${h.join(" ")}
19
- ${x}`:`${l} ${h.join(" ")}`;throw new Error(st)},E=async(l,h,f)=>{let y=0;for(;;)try{await P(l,h,f);return}catch(D){if(y>=a)throw D;let O=Math.floor(Math.random()*200),x=c*Math.pow(2,y)+O;y+=1,await C(x);}};try{await p.ensureDir(u.dirname(o));try{await P(t,v(t,["-m","venv",o]),6e4);}catch(f){let y=f instanceof Error?f.message:String(f);throw new w("BRIDGE_VENV_CREATE_FAILED",y)}let l=L(o);if((await execa(l,["-m","pip","--version"],{reject:false,stdio:"pipe",timeout:2e3})).exitCode!==0&&(await execa(l,["-m","ensurepip","--default-pip"],{reject:false,stdio:["ignore","pipe","inherit"],env:s,timeout:6e4})).exitCode!==0)throw new w("BRIDGE_PIP_BOOTSTRAP_FAILED","ensurepip failed; install python3-venv/python3-pip and retry.");if(process.env.RAPIDKIT_BRIDGE_UPGRADE_PIP==="1")try{await E(l,["-m","pip","install","-U","pip"],m);}catch(f){let y=f instanceof Error?f.message:String(f);throw new w("BRIDGE_PIP_UPGRADE_FAILED",y)}try{await E(l,["-m","pip","install","-U",A()],m);}catch(f){let y=f instanceof Error?f.message:String(f);throw new w("BRIDGE_PIP_INSTALL_FAILED",y)}return l}catch(l){if(l instanceof w)throw l;let h=l instanceof Error?l.message:String(l);throw new w("BRIDGE_VENV_BOOTSTRAP_FAILED",h)}}async function _t(){if(process.env.RAPIDKIT_BRIDGE_FORCE_VENV==="1"){let r=await V();if(!r)throw new w("PYTHON_NOT_FOUND","No Python interpreter found (python3/python/py).");return {kind:"venv",pythonPath:await S(r)}}for(let r of X())if(await et(r))return {kind:"system",cmd:r};let t=await V();if(!t)throw new w("PYTHON_NOT_FOUND","No Python interpreter found (python3/python/py).");return {kind:"venv",pythonPath:await S(t)}}async function $t(t,n){try{let r=await B(n?.cwd),e=r.cmd,i=[...r.baseArgs,...t];if(t[0]==="init"){let a=await execa(e,i,{cwd:n?.cwd,env:{...process.env,...n?.env},reject:false,stdio:"pipe"}),c=K((a.stdout??"").toString()),m=K((a.stderr??"").toString());return c&&process.stdout.write(c.endsWith(`
20
- `)?c:`${c}
21
- `),m&&process.stderr.write(m.endsWith(`
22
- `)?m:`${m}
23
- `),typeof a.exitCode=="number"?a.exitCode:1}let s=await execa(e,i,{cwd:n?.cwd,env:{...process.env,...n?.env},reject:false,stdio:"inherit"});return typeof s.exitCode=="number"?s.exitCode:1}catch(r){return process.stderr.write(`${b(r)}
24
- `),1}}var Et=[{pattern:/RapidKitError:\s*Directory '([^']+)' exists and force is not set/,message:t=>`\u274C Directory "${u.basename(t[1])}" already exists.
25
- \u{1F4A1} Choose a different name, or remove the existing directory first:
26
- rm -rf ${t[1]}`},{pattern:/RapidKitError:\s*Project name '([^']+)' is (invalid|not allowed)/i,message:t=>`\u274C Invalid project name: "${t[1]}"
27
- \u{1F4A1} Use lowercase letters, numbers, and hyphens only (e.g. my-api).`},{pattern:/RapidKitError:\s*Kit '([^']+)' not found/i,message:t=>`\u274C Unknown kit: "${t[1]}"
28
- \u{1F4A1} Run "npx rapidkit list" to see available kits.`},{pattern:/RapidKitError:\s*(.+)/,message:t=>`\u274C ${t[1].trim()}`}];async function Mt(t,n){let{spawn:r}=await import('child_process');try{let e=await B(n?.cwd),i=e.cmd,o=[...e.baseArgs,...t];return await new Promise(s=>{let a=r(i,o,{cwd:n?.cwd,env:{...process.env,...n?.env},stdio:["inherit","inherit","pipe"]}),c=[];a.stderr?.on("data",m=>{c.push(m);}),a.on("close",m=>{let C=m??1;if(C!==0&&c.length>0){let P=Buffer.concat(c).toString("utf8");for(let{pattern:E,message:l}of Et){let h=P.match(E);if(h){process.stderr.write(l(h)+`
29
- `),s(C);return}}process.stderr.write(P);}s(C);}),a.on("error",m=>{process.stderr.write(`${b(m)}
30
- `),s(1);});})}catch(e){return process.stderr.write(`${b(e)}
31
- `),1}}async function _(t,n){try{let r=await B(n?.cwd),e=r.cmd,i=[...r.baseArgs,...t],o=await execa(e,i,{cwd:n?.cwd,env:{...process.env,...n?.env},reject:false,stdio:"pipe"});return {exitCode:typeof o.exitCode=="number"?o.exitCode:1,stdout:(o.stdout??"").toString(),stderr:(o.stderr??"").toString()}}catch(r){return {exitCode:1,stdout:"",stderr:`${b(r)}
32
- `}}}function rt(t){let n=new Set,r=t.split(`
33
- `),e=false;for(let i of r){let o=i.replace(/\r$/,"");if(!e){/^\s*Commands:\s*$/i.test(o)&&(e=true);let c=o.match(/^\s*rapidkit\s+([a-z0-9_-]+)\b/i);if(c){let m=c[1].trim();m&&!m.startsWith("-")&&n.add(m);}continue}if(!o.trim())break;if(/^\s*(Options|Arguments|Usage|Commands)\s*:/i.test(o))continue;let s=o.match(/^\s*([a-z0-9][a-z0-9_-]*)\b/i);if(!s)continue;let a=s[1].trim();a&&!a.startsWith("-")&&n.add(a);}return n}async function it(){let t=tt();if(!await p.pathExists(t))return null;try{let n=await p.readJson(t);if(n&&n.schema_version===1&&Array.isArray(n.commands))return n}catch{}return null}async function Y(t){let n=tt();await p.ensureDir(u.dirname(n)),await p.writeJson(n,t,{spaces:2});}async function xt(){let t=await _(["version","--json"],{cwd:process.cwd()});if(t.exitCode===0)try{let r=JSON.parse(t.stdout)?.version;return typeof r=="string"?r:void 0}catch{return}}async function kt(){let t=await _(["commands","--json"],{cwd:process.cwd()});if(t.exitCode!==0)return null;try{let n=JSON.parse(t.stdout);if(n?.schema_version!==1||!Array.isArray(n.commands))return null;let r=n.commands.filter(e=>typeof e=="string");return r.length?r:null}catch{return null}}async function Vt(){let n=Date.now(),r=await it(),e=await xt(),i=!!r?.commands?.length;if(i&&n-r.fetched_at<864e5&&(!e||!r.rapidkit_version||r.rapidkit_version===e))return new Set(r.commands);let o=await kt();if(o?.length){let m=Array.from(new Set(o)).sort();return await Y({schema_version:1,fetched_at:n,rapidkit_version:e,commands:m}),new Set(m)}let s=await _(["--help"],{cwd:process.cwd()});if(s.exitCode!==0)return i&&r?.commands?new Set(r.commands):new Set($);let a=rt(s.stdout);if(a.size===0)return new Set($);let c=Array.from(a).sort();return await Y({schema_version:1,fetched_at:n,rapidkit_version:e,commands:c}),a}async function Bt(){let n=Date.now(),r=await it();return !r||n-r.fetched_at>=864e5||!r.commands?.length?null:new Set(r.commands)}function ot(){return u.join(I(),"rapidkit","npm-bridge","modules-catalog.json")}async function Rt(){let t=ot();if(!await p.pathExists(t))return null;try{let n=await p.readJson(t);if(n&&n.schema_version===1&&Array.isArray(n.modules))return n}catch{}return null}async function z(t){let n=ot();await p.ensureDir(u.dirname(n)),await p.writeJson(n,t,{spaces:2});}function W(t){try{return JSON.parse(t)}catch{return null}}async function Ft(t={}){let n=typeof t.ttlMs=="number"?t.ttlMs:18e5,r=Date.now(),e=await Rt();if(e?.fetched_at&&r-e.fetched_at<n)return e;let i=["modules","list","--json-schema","1"];t.category&&i.push("--category",t.category),t.tag&&i.push("--tag",t.tag),t.detailed&&i.push("--detailed");let o=await _(i,{cwd:t.cwd,env:t.env});if(o.exitCode===0){let a=W(o.stdout);if(a&&a.schema_version===1&&Array.isArray(a.modules)){let c={...a,fetched_at:r};return await z(c),c}}let s=await _(["modules","list","--json"],{cwd:t.cwd,env:t.env});if(s.exitCode===0){let a=W(s.stdout);if(Array.isArray(a)){let c={schema_version:1,generated_at:new Date().toISOString(),filters:{category:t.category??null,tag:t.tag??null,detailed:!!t.detailed},stats:{total:a.length,returned:a.length,invalid:0},modules:a,source:"legacy-json",fetched_at:r};return await z(c),c}}return e||null}var Gt={pickSystemPython:V,ensureBridgeVenv:S,parseCoreCommandsFromHelp:rt,tryRapidkit:et,checkRapidkitCoreAvailable:gt,checkRapidkitCoreVersionCompatible:Pt,isVersionSatisfyingConstraint:nt};export{$ as a,gt as b,Pt as c,_t as d,$t as e,Mt as f,_ as g,Vt as h,Bt as i,Ft as j,Gt as k};
@@ -1,50 +0,0 @@
1
- import {i as i$1}from'./chunk-QCZGNOTH.js';import {c as c$1,a as a$2,b as b$1}from'./chunk-NFUXULIF.js';import {e}from'./chunk-KXTXQODI.js';import {b,f,d,a as a$4,k,g,i as i$2}from'./chunk-Z5LKRG57.js';import {a}from'./chunk-VM2TOHNX.js';import {a as a$3}from'./chunk-2FIX2MDC.js';import c from'chalk';import {execa}from'execa';import a$1 from'fs-extra';import i from'path';import et from'inquirer';function tt(e){return [...new Set(e.filter(n=>n&&n.trim().length>0))]}function nt(){let e=k().map(t=>i.join(t,a$4()?"poetry.exe":"poetry")),n=a$4()?[i.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),i.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],r=a$4()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return tt([...e,...n,...r])}function st(e){let n=k().map(u=>({location:"Global (user-local)",path:i.join(u,a$4()?"rapidkit.exe":"rapidkit")})),r=[{location:"Global (pipx)",path:i.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:i.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:i.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],t=g(i.join(process.cwd(),".venv")),l=i$2(process.cwd()),o=[{location:"Workspace (.venv)",path:t},...l.map(u=>({location:"Workspace (launcher)",path:u}))],s=[...n,...r,...o],d=new Set;return s.filter(u=>d.has(u.path)?false:(d.add(u.path),true))}function ot(e){let n=new Map([["Workspace (.venv)",0],["Global (user-local)",1],["Global (pipx)",2],["Global (pyenv)",3],["Global (system)",4]]);return [...e].sort((r,t)=>{let l=n.get(r.location)??Number.MAX_SAFE_INTEGER,o=n.get(t.location)??Number.MAX_SAFE_INTEGER;return l!==o?l-o:r.path.localeCompare(t.path)})}function Y(e){let n=0,r=e.issues.some(t=>t.toLowerCase().includes("environment file missing"));return e.hasEnvFile===false&&!r&&(n+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&(n+=1),n}function he(e){return e.filter(n=>Y(n)>0).length}function we(e){return e.reduce((n,r)=>n+Y(r),0)}var it="doctor-project-scan-v2",Ne="doctor-workspace-cache-v1",at=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v1",generatedBy:"rapidkit-npm",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"});function de(){return {...at}}function ue(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function Me(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Ge(e,n){try{if(!await a$1.pathExists(e))return null;let r=await a$1.readJSON(e);return c$1(r,n)?r:null}catch{return null}}function We(e,n){if(!e?.system)return [];let r=[{id:"python",current:n.python},{id:"poetry",current:n.poetry},{id:"pipx",current:n.pipx},{id:"go",current:n.go},{id:"rapidkitCore",current:n.rapidkitCore}],t=[];for(let l of r){let o=e.system?.[l.id]?.status;!o||o===l.current.status||t.push({id:l.id,from:o,to:l.current.status});}return t}function rt(e,n){let r=new Map;for(let p of n.projects)r.set(p.path||p.name,p.issues.length);if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let t=Array.isArray(e.projects)?e.projects:[],l=new Map;for(let p of t){let h=p.path||p.name;h&&l.set(h,Me(p.issues));}let o=0,s=0,d=new Set,u=new Set,m=new Set([...Array.from(l.keys()),...Array.from(r.keys())]);for(let p of m){let h=l.get(p)??0,v=r.get(p)??0;v>h?(o+=v-h,d.add(p)):v<h&&(s+=h-v,u.add(p));}let f=ue(e.healthScore),g=ue(n.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:s,netIssueDelta:o-s,scoreDeltaPercent:f===null||g===null?null:g-f,systemStatusChanges:We(e,{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore}),regressedProjects:Array.from(d).sort(),improvedProjects:Array.from(u).sort()}}function ct(e,n){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let r=Me(e.project?.issues),t=n.project.issues.length,l=Math.max(t-r,0),o=Math.max(r-t,0),s=ue(e.healthScore),d=ue(n.healthScore),u=n.project.path||n.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:l,resolvedIssueCount:o,netIssueDelta:l-o,scoreDeltaPercent:s===null||d===null?null:d-s,systemStatusChanges:We(e,{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore}),regressedProjects:l>0?[u]:[],improvedProjects:o>0?[u]:[]}}function Be(e){let n=e??[],r=0,t=0;for(let s of n){if(s.scope==="project-scoped"){r+=1;continue}(s.scope==="workspace-aggregate"||s.scope==="host-system")&&(t+=1);}let l=r>0&&t>0?1:0,o=l>0?"mixed":r>0?"scoped":t>0?"aggregated":"unknown";return {scopedCount:r,aggregatedCount:t,mixedCount:l,dominantScope:o}}function P(e,n){return a$4()?`cd "${e}"; ${n}`:`cd ${e} && ${n}`}function L(e){return a$4()?P(e,"Copy-Item .env.example .env"):P(e,"cp .env.example .env")}function lt(e){return e==="FastAPI"||e==="NestJS"||e==="Go/Fiber"||e==="Go/Gin"||e==="Spring Boot"||e==="Rust"||e==="Phoenix"?"first-class":e==="Django"||e==="Flask"||e==="Express"||e==="Fastify"||e==="Koa"||e==="Elixir"||e==="Clojure"||e==="Scala"||e==="Kotlin"||e==="Deno"||e==="Bun"||e==="PHP"||e==="Laravel"||e==="Ruby"||e==="Ruby on Rails"||e==="ASP.NET"?"extended":"observed"}function dt(e){return e==="Next.js"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"?"frontend":e==="Unknown"||e==="Node.js"||e==="Python"?"generic":"backend"}function ut(e){return e==="NestJS"||e==="Next.js"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Bun"||e==="Express"||e==="Fastify"||e==="Koa"||e==="Node.js"?"node":e==="FastAPI"||e==="Django"||e==="Flask"||e==="Python"?"python":e==="Go/Fiber"||e==="Go/Gin"?"go":e==="Spring Boot"?"java":e==="Rust"?"rust":e==="Elixir"||e==="Phoenix"?"elixir":e==="Clojure"?"clojure":e==="Deno"?"deno":e==="Laravel"||e==="PHP"?"php":e==="Ruby on Rails"||e==="Ruby"?"ruby":e==="ASP.NET"?"dotnet":"unknown"}function le(e,n,r){e.framework=n,e.frameworkConfidence=r,e.supportTier=lt(n),e.projectKind=dt(n),e.runtimeFamily=ut(n);}function pt(e){return e==="python"?"python":e==="node"||e==="bun"?"node":e==="go"?"go":e==="java"?"java":e==="rust"?"rust":e==="elixir"?"elixir":e==="clojure"?"clojure":e==="deno"?"deno":e==="php"?"php":e==="ruby"?"ruby":e==="dotnet"?"dotnet":"unknown"}function Ke(e){switch(e.key){case "fastapi":return "FastAPI";case "django":return "Django";case "flask":return "Flask";case "python":return "Python";case "nestjs":return "NestJS";case "express":return "Express";case "fastify":return "Fastify";case "koa":return "Koa";case "node":return "Node.js";case "gofiber":return "Go/Fiber";case "gogin":return "Go/Gin";case "echo":return "Echo";case "go":return "Go";case "springboot":return "Spring Boot";case "java":return "Java";case "laravel":return "Laravel";case "php":return "PHP";case "rails":return "Ruby on Rails";case "ruby":return "Ruby";case "dotnet":return "ASP.NET";case "phoenix":return "Phoenix";case "elixir":return "Elixir";case "clojure":return "Clojure";case "scala":return "Scala";case "kotlin":return "Kotlin";case "deno":return "Deno";case "bun":return "Bun";case "actix":case "axum":case "rocket":case "rust":return "Rust";case "sinatra":case "symfony":case "unknown":return "Unknown";default:return "Unknown"}}function mt(e){return e.key==="python"||e.key==="node"||e.key==="go"||e.key==="java"||e.key==="php"||e.key==="ruby"||e.key==="dotnet"||e.key==="rust"||e.key==="elixir"||e.key==="clojure"||e.key==="scala"||e.key==="kotlin"||e.key==="deno"||e.key==="bun"||e.key==="unknown"}function _(e,n){e.framework=Ke(n),e.frameworkKey=n.key,e.importStack=n.importStack,e.frameworkConfidence=n.confidence,e.supportTier=n.supportTier,e.projectKind=mt(n)?"generic":"backend",e.runtimeFamily=pt(n.runtime);}function ft(e){let n=e.dependencies,r=e.scripts??{},t=(e.kitName??"").toLowerCase(),l=s=>!!n[s],o=Object.values(r).filter(s=>typeof s=="string").join(" ").toLowerCase();return l("next")||o.includes("next ")?{framework:"Next.js",confidence:"high"}:l("nuxt")||o.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:l("@nestjs/core")||t.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:l("express")?{framework:"Express",confidence:"high"}:l("fastify")?{framework:"Fastify",confidence:"high"}:l("koa")?{framework:"Koa",confidence:"high"}:l("@angular/core")?{framework:"Angular",confidence:"high"}:l("@sveltejs/kit")||o.includes("svelte-kit")?{framework:"SvelteKit",confidence:"high"}:l("vue")?{framework:"Vue",confidence:"medium"}:l("react")&&l("react-dom")?{framework:"React",confidence:"medium"}:{framework:"Node.js",confidence:"low"}}async function gt(e$1){let n=e(e$1);return n.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:Ke(n),confidence:n.confidence}}async function Re(e){try{let n=await a$1.stat(e);return `${i.basename(e)}:${n.isDirectory()?"d":"f"}:${n.size}:${n.mtimeMs}`}catch{return `${i.basename(e)}:missing`}}async function ht(e){try{let n=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),r=new Set;await pe(e)&&r.add(e);let t=async(l,o)=>{if(o<0)return;let s=await _e(l);for(let d of s){if(Te(d,n))continue;let u=i.join(l,d);if(await pe(u)){r.add(u);continue}o>0&&await t(u,o-1);}};return await t(e,1),r.size===0&&(await $t(e,3,n)).forEach(o=>r.add(o)),Array.from(r).sort((l,o)=>l.localeCompare(o))}catch{return []}}async function yt(e,n){let r=[i.join(e,".rapidkit-workspace"),i.join(e,".rapidkit","workspace.json"),i.join(e,".rapidkit","policies.yml"),i.join(e,".rapidkit","toolchain.lock"),i.join(e,".rapidkit","cache-config.yml")],t=[".rapidkit/project.json",".rapidkit/context.json",".rapidkit/file-hashes.json","package.json","pyproject.toml","composer.json","Gemfile","Gemfile.lock","go.mod","go.sum","pom.xml","requirements.txt","Dockerfile","Makefile",".env",".env.example","src","modules","tests","test",".venv","node_modules"],l=await Promise.all(r.map(Re)),o=await Promise.all(n.map(async s=>{let d=await Promise.all(t.map(u=>Re(i.join(s,u))));return `${s}::${d.join("|")}`}));return [it,...l,...o].join("||")}async function kt(e,n){try{if(!await a$1.pathExists(e))return null;let r=await a$1.readJSON(e);return !r||r.signature!==n||!Array.isArray(r.projects)||typeof r.schemaVersion=="string"&&r.schemaVersion!==Ne?null:r}catch{return null}}async function wt(e,n){try{await a$1.ensureDir(i.dirname(e)),await a$1.writeJSON(e,n,{spaces:2});}catch{}}async function vt(e,n,r){let t=i.join(e,".rapidkit","reports","doctor-last-run.json");try{return await a$1.ensureDir(i.dirname(t)),await a$1.writeJSON(t,{schemaVersion:a$2,evidenceType:"workspace",generatedAt:new Date().toISOString(),contract:de(),workspacePath:e,workspaceName:n.workspaceName,projectScanCached:n.projectScanCached??false,projectScanSignature:n.projectScanSignature,cachePath:r,healthScore:n.healthScore,system:{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore,versions:{core:n.coreVersion,npm:n.npmVersion}},projects:n.projects,summary:{totalProjects:n.projects.length,totalIssues:n.projects.reduce((l,o)=>l+o.issues.length,0),projectAdvisoryWarningProjects:he(n.projects),projectAdvisoryWarnings:we(n.projects),hasSystemErrors:[n.python,n.rapidkitCore].some(l=>l.status==="error"),scopeProvenance:n.scopeProvenance},driftDelta:n.driftDelta,scoreBreakdown:n.scoreBreakdown??[]},{spaces:2}),t}catch{return}}async function ve(){let[e,n,r,t,l]=await Promise.all([bt(),xt(),jt(),Ct(),Et()]);return {python:e,poetry:n,pipx:r,go:t,rapidkitCore:l}}async function bt(){let e=d();for(let n of e)try{let{stdout:r}=await execa(n,["--version"],{timeout:3e3}),t=r.match(/Python (\d+\.\d+\.\d+)/);if(t){let l=t[1],[o,s]=l.split(".").map(Number);return o<3||o===3&&s<10?{status:"warn",message:`Python ${l} (requires 3.10+)`,details:`${n} found but version is below minimum requirement`}:{status:"ok",message:`Python ${l}`,details:`Using ${n}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function xt(){try{let{stdout:e}=await execa("poetry",["--version"],{timeout:3e3}),n=e.match(/Poetry .*version ([\d.]+)/);return n?{status:"ok",message:`Poetry ${n[1]}`,details:"Available for dependency management"}:{status:"warn",message:"Poetry version unknown"}}catch{let e=d().map(n=>({cmd:n,args:n==="py"?["-3","-m","poetry","--version"]:["-m","poetry","--version"]}));for(let n of e)try{let{stdout:r}=await execa(n.cmd,n.args,{timeout:3e3,shell:b()}),t=r.match(/Poetry .*version ([\d.]+)/)||r.match(/([\d.]+)/);return {status:"ok",message:t?.[1]?`Poetry ${t[1]}`:"Poetry detected",details:`Available via ${n.cmd} ${n.args.join(" ")}`}}catch{continue}for(let n of nt())try{if(!await a$1.pathExists(n))continue;let{stdout:r}=await execa(n,["--version"],{timeout:3e3,shell:b()}),t=r.match(/Poetry .*version ([\d.]+)/)||r.match(/([\d.]+)/);return {status:"ok",message:t?.[1]?`Poetry ${t[1]}`:"Poetry detected",details:`Available at ${n}`}}catch{continue}return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function jt(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{let e=d();for(let n of e)try{let r=n==="py"?["-3","-m","pipx","--version"]:["-m","pipx","--version"],{stdout:t}=await execa(n,r,{timeout:3e3,shell:b()});return {status:"ok",message:`pipx ${t.trim()}`,details:`Available via ${n} ${r.join(" ")}`}}catch{continue}return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Ct(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),n=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return n?{status:"ok",message:`Go ${n[1]}`,details:"Available for Go/Fiber and Go/Gin projects"}:{status:"ok",message:"Go (version unknown)",details:"go found in PATH"}}catch{return {status:"warn",message:"Go not installed",details:"Optional: Required only for gofiber.standard / gogin.standard projects \u2014 https://go.dev/dl/"}}}async function Et(){let e=process.env.HOME||process.env.USERPROFILE||"",n=[],r=st(e);for(let{location:l,path:o}of r)try{if(await a$1.pathExists(o)){let{stdout:s,exitCode:d}=await execa(o,["--version"],{timeout:3e3,reject:false});if(d===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let u=s.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);u&&n.push({location:l,path:o,version:u[1]});}}}catch{continue}if(n.length>0){let l=n.filter(s=>s.location!=="Workspace (launcher)");if(l.length>0){let s=ot(l),d=s[0].version,u=s.some(g=>g.location==="Workspace (.venv)"),m=s.some(g=>g.location.startsWith("Global (")),f=!u&&m?"Workspace (.venv): not installed (optional). For best project-level performance and isolation, run npx rapidkit workspace run init inside this workspace.":void 0;return {status:"ok",message:`RapidKit Core ${d}`,details:f,paths:s.map(g=>({location:g.location,path:g.path,version:g.version}))}}return {status:"ok",message:`RapidKit Core ${n[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:l,exitCode:o}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(o===0&&(l.includes("RapidKit Version")||l.includes("RapidKit"))){let s=l.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:l,exitCode:o}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(o===0&&(l.includes("RapidKit Version")||l.includes("RapidKit"))){let s=l.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via Poetry"}}}catch{}let t=d();for(let l of t)try{let{stdout:o,exitCode:s}=await execa(l,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:false});if(s===0&&o&&!o.includes("Traceback")&&!o.includes("ModuleNotFoundError")){let d=o.trim();if(d)return {status:"ok",message:`RapidKit Core ${d}`,details:`Available in ${l} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function A(e,n){let r=i.join(e,"Dockerfile");n.hasDocker=await a$1.pathExists(r);let t=i.join(e,"tests"),l=i.join(e,"test"),o=i.join(e,"src","test"),s=await a$1.pathExists(t)||await a$1.pathExists(l)||await a$1.pathExists(o),d=false;if(n.framework==="Go/Fiber"||n.framework==="Go/Gin")try{let u=[{dir:e,depth:0}],m=4,f=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;u.length>0&&!d;){let g=u.shift();if(!g)break;let p=[];try{p=await a$1.readdir(g.dir);}catch{continue}for(let h of p){let v=i.join(g.dir,h),y;try{y=await a$1.stat(v);}catch{continue}if(y.isFile()&&h.endsWith("_test.go")){d=true;break}y.isDirectory()&&g.depth<m&&!f.has(h)&&!h.startsWith(".")&&u.push({dir:v,depth:g.depth+1});}}}catch{}if(n.hasTests=s||d,n.runtimeFamily==="node"){let u=i.join(e,".eslintrc.js"),m=i.join(e,".eslintrc.json");n.hasCodeQuality=await a$1.pathExists(u)||await a$1.pathExists(m);}else if(n.framework==="Go/Fiber"||n.framework==="Go/Gin"){let u=i.join(e,".golangci.yml"),m=i.join(e,".golangci.yaml"),f=i.join(e,"Makefile"),g=await a$1.pathExists(f)&&(await a$1.readFile(f,"utf8")).includes("golangci-lint");n.hasCodeQuality=await a$1.pathExists(u)||await a$1.pathExists(m)||g;}else if(n.runtimeFamily==="python"){let u=i.join(e,"ruff.toml"),m=i.join(e,"pyproject.toml");if(await a$1.pathExists(m))try{let f=await a$1.readFile(m,"utf8");n.hasCodeQuality=f.includes("[tool.ruff]")||await a$1.pathExists(u);}catch{n.hasCodeQuality=await a$1.pathExists(u);}}else if(n.framework==="Spring Boot"){let u=i.join(e,"pom.xml");if(await a$1.pathExists(u))try{let m=await a$1.readFile(u,"utf8");n.hasCodeQuality=m.includes("spotless")||m.includes("checkstyle")||m.includes("pmd")||m.includes("maven-enforcer-plugin");}catch{n.hasCodeQuality=false;}}try{if(n.runtimeFamily==="node"){let{stdout:u}=await execa("npm",["audit","--json"],{cwd:e,reject:false});if(u)try{let f=JSON.parse(u).metadata?.vulnerabilities;f&&(n.vulnerabilities=(f.high||0)+(f.critical||0)+(f.moderate||0));}catch{}}else if(n.runtimeFamily==="python"){let u=i.join(e,".venv"),m=f(u);if(await a$1.pathExists(m))try{let{stdout:f}=await execa(m,["-m","pip","list","--format=json"],{timeout:5e3,reject:false});if(f){JSON.parse(f);n.vulnerabilities=0;}}catch{}}}catch{}}function N(e,n){e.probes||(e.probes=[]),e.probes.push(n);}async function Pt(e,n){let r=n.runtimeFamily||"unknown";if(n.projectKind==="backend"||n.projectKind==="generic"){if(r==="node"){let l=await a$1.pathExists(i.join(e,"package-lock.json"))||await a$1.pathExists(i.join(e,"pnpm-lock.yaml"))||await a$1.pathExists(i.join(e,"yarn.lock"));N(n,{id:"adapter-node-lockfile-integrity",label:"Node adapter lockfile integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml).",recommendation:l?void 0:"Commit a lockfile for deterministic installs and CI parity."});let o=await a$1.pathExists(i.join(e,"src/main.ts"))||await a$1.pathExists(i.join(e,"src/main.js"))||await a$1.pathExists(i.join(e,"src/server.ts"))||await a$1.pathExists(i.join(e,"src/server.js"));N(n,{id:"adapter-node-boot-entrypoint",label:"Node adapter boot entrypoint",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Boot entrypoint markers detected for service startup path.":"No canonical Node boot entrypoint markers detected.",recommendation:o?void 0:"Define and document service bootstrap entrypoint (main/server)."});return}if(r==="python"){let l=await a$1.pathExists(i.join(e,"poetry.lock"))||await a$1.pathExists(i.join(e,"requirements.txt"))||await a$1.pathExists(i.join(e,"uv.lock"));N(n,{id:"adapter-python-lockfile-integrity",label:"Python adapter dependency integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Python dependency contract file detected.":"No Python dependency contract file detected (poetry.lock/requirements/uv.lock).",recommendation:l?void 0:"Pin dependency contract for deterministic setup and reproducible CI."});let o=await a$1.pathExists(i.join(e,"app/main.py"))||await a$1.pathExists(i.join(e,"main.py"))||await a$1.pathExists(i.join(e,"manage.py"));N(n,{id:"adapter-python-boot-entrypoint",label:"Python adapter boot entrypoint",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Python application entrypoint markers detected.":"No Python application entrypoint markers detected.",recommendation:o?void 0:"Expose explicit app/main entrypoint for deterministic boot probes."});return}if(r==="java"){let l=await a$1.pathExists(i.join(e,"mvnw"))||await a$1.pathExists(i.join(e,"gradlew"));N(n,{id:"adapter-java-build-wrapper",label:"Java adapter build wrapper",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Build wrapper detected (mvnw/gradlew).":"No Java build wrapper detected.",recommendation:l?void 0:"Commit mvnw or gradlew for reproducible enterprise pipelines."});return}if(r==="go"){let l=await a$1.pathExists(i.join(e,"go.sum"));N(n,{id:"adapter-go-module-integrity",label:"Go adapter module integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"go.sum detected for deterministic module verification.":"go.sum missing; module integrity baseline is incomplete.",recommendation:l?void 0:"Generate and commit go.sum in the repository baseline."});}}}async function St(e,n){let r=[i.join(e,".rapidkit","doctor.adapters.json"),i.join(e,"doctor.adapters.json")];for(let t of r)if(await a$1.pathExists(t))try{let l=await a$1.readJSON(t),o=Array.isArray(l?.checks)?l.checks:[];for(let s=0;s<o.length;s+=1){let d=o[s]||{},u=Array.isArray(d.runtimes)?d.runtimes:[];if(u.length>0&&!u.includes(n.runtimeFamily||"unknown"))continue;let m=typeof d.id=="string"&&d.id.trim().length>0?d.id.trim():`adapter-check-${s+1}`,f=typeof d.label=="string"&&d.label.trim().length>0?d.label.trim():m,g=d.severity||"warn",p=Array.isArray(d.anyOfPaths)?d.anyOfPaths.filter(Boolean):[],h=Array.isArray(d.allOfPaths)?d.allOfPaths.filter(Boolean):[],v=p.length===0;for(let T of p)if(await a$1.pathExists(i.join(e,T))){v=true;break}let y=true;for(let T of h)if(!await a$1.pathExists(i.join(e,T))){y=false;break}let b=v&&y;N(n,{id:m,label:f,status:b?"pass":g==="error"?"fail":"warn",severity:g,scope:"project-scoped",reason:b?d.passReason||"Custom adapter contract satisfied.":d.failReason||`Custom adapter check failed from ${i.basename(t)}.`,recommendation:d.recommendation});}}catch{N(n,{id:"custom-adapter-config",label:"Custom doctor adapter configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${i.basename(t)}.`,recommendation:"Fix JSON syntax in doctor.adapters.json to re-enable adapter checks."});}}async function I(e,n){if(!(n.projectKind==="backend"||n.projectKind==="generic"))return;let t=i.join(e,".env"),l=i.join(e,".env.example"),o=await a$1.pathExists(t)||await a$1.pathExists(l)||await a$1.pathExists(i.join(e,"config"));N(n,{id:"config-surface",label:"Configuration contract surface",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Configuration artifacts detected (.env/.env.example/config).":"No explicit configuration contract artifacts detected.",recommendation:o?void 0:"Add .env.example or explicit config contract documentation for deterministic setup."});let s={python:["alembic.ini","migrations","versions"],node:["prisma/schema.prisma","migrations","typeorm.config.ts","typeorm.config.js"],go:["migrations","db/migrations"],java:["src/main/resources/db/migration","src/main/resources/liquibase"],rust:["migrations","sqlx-data.json"],elixir:["priv/repo/migrations"],clojure:["resources/migrations","migrations"],deno:["migrations"],php:["database/migrations","migrations"],ruby:["db/migrate"],dotnet:["Migrations","Data/Migrations"],unknown:["migrations"]},d=n.runtimeFamily||"unknown",u=s[d]||s.unknown,m=false;for(let p of u)if(await a$1.pathExists(i.join(e,p))){m=true;break}N(n,{id:"migration-surface",label:"Migration/readiness surface",status:m?"pass":"warn",severity:"warn",scope:"project-scoped",reason:m?"Migration or schema evolution markers detected.":"No migration markers detected for this backend runtime.",recommendation:m?void 0:"Add migration tooling baseline (migrations dir or runtime-native migration config)."});let f=["src/health","src/healthcheck","src/main/resources/application.yml","src/main/resources/application.properties","app/health.py","routes/health.ts","routes/health.js"],g=false;for(let p of f)if(await a$1.pathExists(i.join(e,p))){g=true;break}N(n,{id:"runtime-health-surface",label:"Runtime health probe surface",status:g?"pass":"warn",severity:"warn",scope:"project-scoped",reason:g?"Health endpoint/config markers detected.":"No explicit runtime health endpoint markers detected.",recommendation:g?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await Pt(e,n);}async function H(e,n){let r=[i.join(e,".rapidkit","doctor.probes.json"),i.join(e,"doctor.probes.json")];for(let t of r)if(await a$1.pathExists(t))try{let l=await a$1.readJSON(t),o=Array.isArray(l?.probes)?l.probes:[];for(let s=0;s<o.length;s+=1){let d=o[s]||{},u=typeof d.id=="string"&&d.id.trim().length>0?d.id.trim():`custom-probe-${s+1}`,m=typeof d.label=="string"&&d.label.trim().length>0?d.label.trim():u,f=d.severity||"warn",g=Array.isArray(d.anyOfPaths)?d.anyOfPaths.filter(Boolean):[],p=Array.isArray(d.allOfPaths)?d.allOfPaths.filter(Boolean):[],h=g.length===0;for(let b of g)if(await a$1.pathExists(i.join(e,b))){h=true;break}let v=true;for(let b of p)if(!await a$1.pathExists(i.join(e,b))){v=false;break}let y=h&&v;N(n,{id:u,label:m,status:y?"pass":f==="error"?"fail":"warn",severity:f,scope:"project-scoped",reason:y?"Custom probe contract satisfied.":`Custom probe failed from ${i.basename(t)}.`,recommendation:d.recommendation});}}catch{N(n,{id:"custom-probe-config",label:"Custom doctor probe configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${i.basename(t)}.`,recommendation:"Fix JSON syntax in doctor.probes.json to re-enable custom probes."});}await St(e,n);}async function be(e$1,n={}){let t={name:i.basename(e$1),path:e$1,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},l=n.allowNonRapidkit===true,o=i.join(e$1,".rapidkit");if(!await a$1.pathExists(o)){if(!l)return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;t.issues.push("Not a RapidKit-managed project (running generic backend diagnostics)");}try{let k=i.join(e$1,"registry.json");if(await a$1.pathExists(k)){let w=await a$1.readJson(k);w.installed_modules&&(t.stats={modules:w.installed_modules.length});}}catch{}let s=null;try{let k=i.join(o,"project.json");if(await a$1.pathExists(k)){s=await a$1.readJson(k);let w=s?.kit_name||s?.kit;w&&(t.kit=w);}}catch{}try{let k=i.join(e$1,".git");if(await a$1.pathExists(k)){let{stdout:w}=await execa("git",["log","-1","--format=%cr"],{cwd:e$1,reject:false});w&&(t.lastModified=w.trim());}else {let w=await a$1.stat(e$1),S=Date.now()-w.mtime.getTime(),M=Math.floor(S/(1e3*60*60*24));t.lastModified=M===0?"today":`${M} day${M>1?"s":""} ago`;}}catch{}let d=i.join(e$1,"package.json"),u=i.join(e$1,"pyproject.toml"),m=i.join(e$1,"requirements.txt"),f$1=i.join(e$1,"go.mod"),g=i.join(e$1,"pom.xml"),p=i.join(e$1,"build.sbt"),h=i.join(e$1,"Cargo.toml"),v=i.join(e$1,"mix.exs"),y=i.join(e$1,"deps.edn"),b=i.join(e$1,"project.clj"),T=i.join(e$1,"deno.json"),W=i.join(e$1,"deno.jsonc"),J=i.join(e$1,"bun.lockb"),q=i.join(e$1,"bun.lock"),O=i.join(e$1,"composer.json"),ne=i.join(e$1,"Gemfile"),U=await a$1.pathExists(d),B=await a$1.pathExists(u)||await a$1.pathExists(m),R=await a$1.pathExists(O),ee=await a$1.pathExists(ne),se=await a$1.pathExists(h),Ue=await a$1.pathExists(v),ze=await a$1.pathExists(y)||await a$1.pathExists(b),Qe=await a$1.pathExists(p),Xe=await a$1.pathExists(T)||await a$1.pathExists(W),re=s?.runtime==="dotnet";try{re=re||await Fe(e$1,".csproj",3)||await Fe(e$1,".sln",2);}catch{re=s?.runtime==="dotnet";}let Ye=await a$1.pathExists(f$1)||s?.runtime==="go"||typeof s?.kit_name=="string"&&(s.kit_name.startsWith("gofiber")||s.kit_name.startsWith("gogin")),xe=U&&(await a$1.pathExists(J)||await a$1.pathExists(q)||typeof s?.packageManager=="string"&&(s?.packageManager).toLowerCase().startsWith("bun@"));if(Ye){_(t,e(e$1,s??null)),t.isGoProject=true,t.venvActive=true,t.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{t.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),t.fixCommands?.push("https://go.dev/dl/");}let k=i.join(e$1,"go.sum");return await a$1.pathExists(k)?t.depsInstalled=true:(t.depsInstalled=false,t.issues.push("Go dependencies not downloaded (go.sum missing)"),t.fixCommands?.push(P(e$1,"go mod tidy"))),await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(await a$1.pathExists(g)||s?.runtime==="java"||typeof s?.kit_name=="string"&&s.kit_name.startsWith("springboot")){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=await a$1.pathExists(g),w=await a$1.pathExists(i.join(e$1,"build.gradle"))||await a$1.pathExists(i.join(e$1,"build.gradle.kts")),j=await a$1.pathExists(i.join(e$1,"mvnw"))||await a$1.pathExists(i.join(e$1,"mvnw.cmd")),S=await a$1.pathExists(i.join(e$1,"gradlew"))||await a$1.pathExists(i.join(e$1,"gradlew.bat"));try{await execa("java",["-version"],{timeout:3e3,reject:false});}catch{t.issues.push("Java runtime not found \u2014 install JDK 21+ and ensure java is on PATH"),t.fixCommands?.push("https://adoptium.net/");}if(k){if(!j)try{await execa("mvn",["-version"],{timeout:3e3,reject:false});}catch{t.issues.push("Maven not found \u2014 install Maven 3.9+ or add Maven Wrapper"),t.fixCommands?.push("https://maven.apache.org/install.html");}}else if(w&&!S)try{await execa("gradle",["--version"],{timeout:3e3,reject:false});}catch{t.issues.push("Gradle not found \u2014 install Gradle 8+ or add Gradle Wrapper"),t.fixCommands?.push("https://gradle.org/install/");}let M=i.join(e$1,"target"),$=i.join(e$1,"build","libs"),F=i.join(e$1,".rapidkit","cache","java","m2"),C=i.join(e$1,".rapidkit","cache","java","gradle");t.depsInstalled=await a$1.pathExists(M)||await a$1.pathExists($)||await a$1.pathExists(F)||await a$1.pathExists(C),t.depsInstalled||(t.issues.push("Java dependencies are not warmed or built yet"),t.fixCommands?.push(P(e$1,"rapidkit init")));let G=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(G),!t.hasEnvFile){let z=i.join(e$1,".env.example");await a$1.pathExists(z)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}let V=i.join(e$1,"src","main","resources","application.yml");if(await a$1.pathExists(V))try{let z=await a$1.readFile(V,"utf-8");/include:\s*[^\n]*health/i.test(z)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(z)||(t.issues.push("Actuator health endpoint exposure is not clearly configured in application.yml"),t.fixCommands?.push(P(e$1,"Ensure management.endpoints.web.exposure.include contains health in src/main/resources/application.yml")));}catch{t.issues.push("Unable to read application.yml for Spring Actuator health checks");}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(se){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=i.join(e$1,"Cargo.lock"),w=i.join(e$1,"target");t.depsInstalled=await a$1.pathExists(k)||await a$1.pathExists(w),t.depsInstalled||(t.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),t.fixCommands?.push(P(e$1,"cargo fetch")));let j=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(j),!t.hasEnvFile){let S=i.join(e$1,".env.example");await a$1.pathExists(S)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(Ue){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=i.join(e$1,"mix.lock"),w=i.join(e$1,"deps");t.depsInstalled=await a$1.pathExists(k)||await a$1.pathExists(w),t.depsInstalled||(t.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),t.fixCommands?.push(P(e$1,"mix deps.get")));let j=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(j),!t.hasEnvFile){let S=i.join(e$1,".env.example");await a$1.pathExists(S)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(ze){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=i.join(e$1,".cpcache"),w=i.join(e$1,"target"),j=await a$1.pathExists(y)||await a$1.pathExists(b);return t.depsInstalled=await a$1.pathExists(k)||await a$1.pathExists(w)||j,t.depsInstalled||(t.issues.push("Clojure dependency cache not initialized"),t.fixCommands?.push(P(e$1,"clojure -P"))),await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(Qe){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=i.join(e$1,"target");t.depsInstalled=await a$1.pathExists(k),t.depsInstalled||(t.issues.push("Scala build artifacts missing (run dependency/build warmup)"),t.fixCommands?.push(P(e$1,"sbt compile")));let w=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(w),!t.hasEnvFile){let j=i.join(e$1,".env.example");await a$1.pathExists(j)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(Xe){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false,t.depsInstalled=true;let k=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(k),!t.hasEnvFile){let w=i.join(e$1,".env.example");await a$1.pathExists(w)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(U){let k=null;try{k=await a$1.readJson(d);}catch{k=null;}let w={...k?.dependencies??{},...k?.devDependencies??{}},j=k?.scripts??{},S=typeof s?.kit_name=="string"?s.kit_name.toLowerCase():typeof s?.kit=="string"?s.kit.toLowerCase():"",M=ft({dependencies:w,scripts:j,kitName:S});if(xe)le(t,"Bun","high");else {let C=e(e$1,s??null);C.key==="nestjs"||C.key==="express"||C.key==="fastify"||C.key==="koa"?_(t,C):le(t,M.framework,M.confidence);}t.venvActive=true;let $=i.join(e$1,"node_modules");if(await a$1.pathExists($))try{let G=(await a$1.readdir($)).filter(V=>!V.startsWith(".")&&!V.startsWith("_"));t.depsInstalled=G.length>0;}catch{t.depsInstalled=false;}if(t.depsInstalled||(t.issues.push("Dependencies not installed (node_modules empty or missing)"),t.fixCommands?.push(P(e$1,xe?"bun install":"rapidkit init"))),t.coreInstalled=false,t.projectKind==="frontend"){let C=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(C.map(V=>a$1.pathExists(i.join(e$1,V))))).some(Boolean))t.hasEnvFile=true;else {let V=i.join(e$1,".env.example");await a$1.pathExists(V)&&(t.hasEnvFile=false,t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}}else {let C=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(C),!t.hasEnvFile){let G=i.join(e$1,".env.example");await a$1.pathExists(G)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}}let F=i.join(e$1,"src");if(t.modulesHealthy=true,t.missingModules=[],await a$1.pathExists(F))try{let C=await a$1.readdir(F);t.modulesHealthy=C.length>0;}catch{t.modulesHealthy=false;}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(B){let k=await gt(e$1);le(t,k.framework,k.confidence);let w=i.join(e$1,".venv");if(await a$1.pathExists(w)){t.venvActive=true;let $=f(w);if(await a$1.pathExists($)){try{let{stdout:G}=await execa($,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=true,t.coreVersion=G.trim();}catch{t.coreInstalled=false;}let F="fastapi";t.framework==="Django"?F="django":t.framework==="Flask"?F="flask":t.framework==="Python"&&(F="");let C=true;if(F)try{await execa($,["-c",`import ${F}`],{timeout:2e3}),t.depsInstalled=true,C=false;}catch{C=true;}if(C)try{let G=i.join(w,"lib");if(await a$1.pathExists(G)){let z=(await a$1.readdir(G)).find(oe=>oe.startsWith("python"));if(z){let oe=i.join(G,z,"site-packages");if(await a$1.pathExists(oe)){let Ze=(await a$1.readdir(oe)).filter(me=>!me.startsWith("_")&&!me.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(me));t.depsInstalled=Ze.length>0;}}}t.depsInstalled||(t.issues.push("Dependencies not installed"),t.fixCommands?.push(P(e$1,"rapidkit init")));}catch{t.issues.push("Could not verify dependency installation");}}else t.issues.push("Virtual environment exists but Python executable not found");}else t.issues.push("Virtual environment not created"),t.fixCommands?.push(P(e$1,"rapidkit init"));let j=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(j),!t.hasEnvFile){let $=i.join(e$1,".env.example");await a$1.pathExists($)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}let S=i.join(e$1,"src"),M=i.join(e$1,"modules");if(t.modulesHealthy=true,t.missingModules=[],await a$1.pathExists(S)){let $=i.join(S,"__init__.py");await a$1.pathExists($)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await a$1.pathExists(M))try{let $=await _e(M);for(let F of $){let C=i.join(M,F,"__init__.py");await a$1.pathExists(C)||(t.modulesHealthy=false,t.missingModules.push(`modules/${F}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(R){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=i.join(e$1,"vendor");t.depsInstalled=await a$1.pathExists(k),t.depsInstalled||(t.issues.push("PHP dependencies not installed (vendor missing)"),t.fixCommands?.push(P(e$1,"composer install")));let w=i.join(e$1,".env");if(t.hasEnvFile=await a$1.pathExists(w),!t.hasEnvFile){let j=i.join(e$1,".env.example");await a$1.pathExists(j)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(L(e$1)));}return await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(ee){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=await a$1.pathExists(i.join(e$1,"Gemfile.lock")),w=await a$1.pathExists(i.join(e$1,"vendor","bundle"));t.depsInstalled=k||w,t.depsInstalled||(t.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),t.fixCommands?.push(P(e$1,"bundle install")));let j=i.join(e$1,".env");return t.hasEnvFile=await a$1.pathExists(j),await A(e$1,t),await I(e$1,t),await H(e$1,t),t}if(re){_(t,e(e$1,s??null)),t.venvActive=true,t.coreInstalled=false;let k=i.join(e$1,"obj"),w=i.join(e$1,"src","obj"),j=i.join(e$1,"packages.lock.json");t.depsInstalled=await a$1.pathExists(k)||await a$1.pathExists(w)||await a$1.pathExists(j),t.depsInstalled||(t.issues.push(".NET restore/build artifacts not found"),t.fixCommands?.push(P(e$1,"dotnet restore")));let S=i.join(e$1,".env");return t.hasEnvFile=await a$1.pathExists(S),await A(e$1,t),await I(e$1,t),await H(e$1,t),t}return le(t,"Unknown","low"),t.issues.push("Unknown project type (no recognized runtime marker files)"),await A(e$1,t),await I(e$1,t),await H(e$1,t),t}async function _e(e){try{return (await a$1.readdir(e,{withFileTypes:true})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{try{let n=await a$1.readdir(e),r=[];for(let t of n)try{(await a$1.stat(i.join(e,t))).isDirectory()&&r.push(t);}catch{continue}return r}catch{return []}}}async function Fe(e,n,r){let t=[{dir:e,depth:0}],l=new Set([".git",".rapidkit","node_modules","bin","obj","target"]);for(;t.length>0;){let o=t.shift();if(!o||o.depth>r)continue;let s;try{s=await a$1.readdir(o.dir,{withFileTypes:true});}catch{continue}for(let d of s){if(d.isFile()&&d.name.toLowerCase().endsWith(n.toLowerCase()))return true;d.isDirectory()&&!l.has(d.name)&&t.push({dir:i.join(o.dir,d.name),depth:o.depth+1});}}return false}async function pe(e){let n=i.join(e,".rapidkit");if(!await a$1.pathExists(n))return false;let r=["project.json","context.json","file-hashes.json"];for(let t of r)if(await a$1.pathExists(i.join(n,t)))return true;return false}function Te(e,n){if(n.has(e))return true;let r=e.toLowerCase();return !!(r==="dist"||r.startsWith("dist-")||r.startsWith("dist_")||r==="build"||r.startsWith("build-")||r.startsWith("build_"))}async function $t(e,n,r){let t=new Set,l=[{dir:e,depth:0}];for(;l.length>0;){let o=l.shift();if(!o)break;try{let s=await a$1.readdir(o.dir);for(let d of s){if(Te(d,r))continue;let u=i.join(o.dir,d),m;try{m=await a$1.stat(u);}catch{continue}if(m.isDirectory()){if(await pe(u)){t.add(u);continue}o.depth<n&&l.push({dir:u,depth:o.depth+1});}}}catch{continue}}return Array.from(t)}async function ae(e){let n=i.resolve(e),r=i.parse(n).root;for(;;){if(await Dt(n))return n;if(n===r)break;n=i.dirname(n);}return null}async function Rt(e){let n=i.resolve(e),r=await ae(n),t=r??i.parse(n).root;for(;;){if(await pe(n)||await Ft(n)&&(!r||n!==r))return n;if(n===t)break;n=i.dirname(n);}return null}function De(e){let n=i.resolve(e);return process.platform==="darwin"?n.replace(/^\/private(?=\/var\/)/,""):n}async function Ft(e){let n=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.sbt","Cargo.toml","mix.exs","deps.edn","project.clj","deno.json","deno.jsonc","composer.json","Gemfile"];for(let r of n)if(await a$1.pathExists(i.join(e,r)))return true;return false}async function Dt(e){let n=[i.join(e,".rapidkit-workspace"),i.join(e,".rapidkit","workspace-marker.json"),i.join(e,".rapidkit","config.json")];return Promise.all(n.map(r=>a$1.pathExists(r))).then(r=>r.some(Boolean))}function Oe(e,n){let r=0,t=0,l=0;return e.forEach(s=>{s.status==="ok"?r++:s.status==="warn"?t++:s.status==="error"&&l++;}),n.forEach(s=>{let d=Y(s),u=s.isGoProject?s.issues.length===0&&s.depsInstalled:s.issues.length===0&&s.venvActive&&s.depsInstalled;if(s.issues.length>0||d>0||!u){t++;return}r++;}),{total:r+t+l,passed:r,warnings:t,errors:l}}function Ve(e,n,r={}){let t=[];for(let o of e)t.push({id:o.id,label:o.label,status:o.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:o.result.details||o.result.message});let l=[...n].sort((o,s)=>{let d=`${o.path||""}|${o.name||""}`.toLowerCase(),u=`${s.path||""}|${s.name||""}`.toLowerCase();return d.localeCompare(u)});for(let o of l){let s=o.issues.length>0,d=Y(o),u=s||d>0?"warn":"ok",m=s?`${o.issues.length} blocking issue(s)`:d>0?`${d} advisory warning(s)`:"Project checks passed";t.push({id:`project:${o.name}`,label:`Project ${o.name}`,status:u,scope:"project-scoped",policyRuleId:s?"project-blocking-issues":d>0?"project-advisory-warnings":"project-checks-passed",reason:m});}if(r.includeWorkspaceAggregateRules){let o=n.reduce((u,m)=>u+m.issues.length,0),s=we(n),d=e.filter(u=>u.result.status==="error").length;t.push({id:"workspace:projects-discovered",label:"Workspace projects discovered",status:n.length>0?"ok":"warn",scope:"workspace-aggregate",policyRuleId:"workspace-project-discovery",reason:n.length>0?`${n.length} project(s) discovered for workspace analysis.`:"No projects discovered for workspace analysis."}),t.push({id:"workspace:system-error-gate",label:"Workspace system error gate",status:d>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-system-error-gate",reason:d>0?`${d} system requirement gate(s) failed.`:"All system requirement gates passed."}),t.push({id:"workspace:blocking-issues-gate",label:"Workspace blocking issues gate",status:o>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:o>0?`${o} blocking project issue(s) detected.`:"No blocking project issues detected."}),t.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:s>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:s>0?`${s} advisory warning(s) detected.`:"No advisory warnings detected."});}return t}async function Ae(e,n=true){let r=i.basename(e);try{let p=i.join(e,".rapidkit-workspace");await a$1.pathExists(p)&&(r=(await a$1.readJSON(p)).name||r);}catch{try{let p=i.join(e,".rapidkit","config.json");r=(await a$1.readJSON(p)).workspace_name||r;}catch{}}let[t,l]=await Promise.all([ve(),ht(e)]),o={workspacePath:e,workspaceName:r,python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,projects:[]};a.debug(`Workspace scan found ${l.length} project(s)`);let s=await yt(e,l),d=i.join(e,".rapidkit","reports","doctor-workspace-cache.json"),u=n?await kt(d,s):null;if(u){o.projects=u.projects;for(let p of o.projects)p.commandCapabilities=i$1(p.path);o.projectScanCached=true,a.debug(`Workspace project health cache hit: ${d}`);}else try{let p=await Promise.all(l.map(h=>be(h)));for(let h of p)h.commandCapabilities=i$1(h.path);o.projects=p,o.projectScanCached=false,await wt(d,{schemaVersion:Ne,signature:s,generatedAt:new Date().toISOString(),projects:p}),a.debug(`Workspace project health cache refreshed: ${d}`);}catch(p){a.debug(`Failed to scan workspace projects: ${p}`);}o.projectScanSignature=s,o.projectScanCachePath=d;let m=[o.python,o.poetry,o.pipx,o.go,o.rapidkitCore];if(o.healthScore=Oe(m,o.projects),o.scoreBreakdown=Ve([{id:"system-python",label:"Python",result:o.python},{id:"system-poetry",label:"Poetry",result:o.poetry},{id:"system-pipx",label:"pipx",result:o.pipx},{id:"system-go",label:"Go",result:o.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:o.rapidkitCore}],o.projects,{includeWorkspaceAggregateRules:true}),o.scopeProvenance=Be(o.scoreBreakdown),o.rapidkitCore.status==="ok"){let p=o.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);p&&(o.coreVersion=p[1]);}let f=i.join(e,".rapidkit","reports","doctor-last-run.json"),g=await Ge(f,"workspace");return o.driftDelta=rt(g,o),o.evidencePath=await vt(e,o,u?d:null),o}async function At(e,n){let r=e||n.projectPath,t=i.join(r,".rapidkit","reports","doctor-project-last-run.json");try{return await a$1.ensureDir(i.dirname(t)),await a$1.writeJSON(t,{schemaVersion:b$1,evidenceType:"project",generatedAt:new Date().toISOString(),contract:de(),workspacePath:e||null,projectPath:n.projectPath,projectName:n.projectName,healthScore:n.healthScore,system:{python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore},project:n.project,driftDelta:n.driftDelta,summary:{scopeProvenance:n.scopeProvenance},scoreBreakdown:n.scoreBreakdown??[]},{spaces:2}),t}catch{return}}async function It(e){let n=await ae(e),r=await ve(),t=await be(e,{allowNonRapidkit:true});t.commandCapabilities=i$1(e);let l=Oe([r.python,r.poetry,r.pipx,r.go,r.rapidkitCore],[t]),o={workspacePath:n||void 0,projectPath:e,projectName:i.basename(e),python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,project:t,healthScore:l};o.scoreBreakdown=Ve([{id:"system-python",label:"Python",result:o.python},{id:"system-poetry",label:"Poetry",result:o.poetry},{id:"system-pipx",label:"pipx",result:o.pipx},{id:"system-go",label:"Go",result:o.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:o.rapidkitCore}],[o.project]),o.scopeProvenance=Be(o.scoreBreakdown);let s=n||e,d=i.join(s,".rapidkit","reports","doctor-project-last-run.json"),u=await Ge(d,"project");return o.driftDelta=ct(u,o),o.evidencePath=await At(n||void 0,o),o}function E(e,n){let r=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",t=e.status==="ok"?c.green:e.status==="warn"?c.yellow:c.red;console.log(`${r} ${c.bold(n)}: ${t(e.message)}`),e.paths&&e.paths.length>0&&e.paths.forEach(l=>{let o=l.version?c.cyan(` -> ${l.version}`):"";console.log(` ${c.cyan("\u2022")} ${c.gray(l.location)}: ${c.dim(l.path)}${o}`);}),e.details&&console.log(` ${c.gray(e.details)}`);}function Ie(e){let n=e.issues.length>0,r=n?"\u26A0\uFE0F":"\u2705",t=n?c.yellow:c.green;if(console.log(`
2
- ${r} ${c.bold("Project")}: ${t(e.name)}`),e.framework){let s=e.framework==="FastAPI"||e.framework==="Django"||e.framework==="Flask"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":e.framework==="Next.js"||e.framework==="Nuxt"?"\u25B2":e.framework==="React"?"\u269B\uFE0F":e.framework==="Vue"?"\u{1F7E2}":e.framework==="Angular"?"\u{1F170}\uFE0F":e.framework==="SvelteKit"?"\u{1F9E1}":e.framework==="Spring Boot"?"\u2615":e.framework==="Rust"?"\u{1F980}":e.framework==="Elixir"||e.framework==="Phoenix"?"\u{1F9EA}":e.framework==="Clojure"?"\u2699\uFE0F":e.framework==="Scala"?"\u{1F53A}":e.framework==="Kotlin"?"\u{1F7E3}":e.framework==="Deno"?"\u{1F995}":e.framework==="Bun"?"\u{1F956}":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"\u{1F439}":e.framework==="Laravel"||e.framework==="PHP"?"\u{1F418}":e.framework==="Ruby on Rails"||e.framework==="Ruby"?"\u{1F48E}":e.framework==="ASP.NET"?"\u{1F537}":"\u{1F4E6}";console.log(` ${s} Framework: ${c.cyan(e.framework)}${e.kit?c.gray(` (${e.kit})`):""}`);let d=[];e.runtimeFamily&&d.push(`runtime: ${e.runtimeFamily}`),e.projectKind&&d.push(`kind: ${e.projectKind}`),e.supportTier&&d.push(`support: ${e.supportTier}`),e.frameworkConfidence&&d.push(`confidence: ${e.frameworkConfidence}`),d.length>0&&console.log(` ${c.dim("\u21B3")} ${c.gray(d.join(" \u2022 "))}`);}if(console.log(` ${c.gray(`Path: ${e.path}`)}`),e.runtimeFamily==="python"&&(e.venvActive?console.log(` \u2705 Virtual environment: ${c.green("Active")}`):console.log(` \u274C Virtual environment: ${c.red("Not found")}`),e.coreInstalled?console.log(` ${c.dim("\u2139")} RapidKit Core: ${c.gray(e.coreVersion||"In venv")} ${c.dim("(optional)")}`):console.log(` ${c.dim("\u2139")} RapidKit Core: ${c.gray("Using global installation")} ${c.dim("(recommended)")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${c.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${c.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${c.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${c.yellow(".env missing")}`)),e.modulesHealthy!==void 0&&(e.modulesHealthy?console.log(` \u2705 Modules: ${c.green("Healthy")}`):e.missingModules&&e.missingModules.length>0&&console.log(` \u26A0\uFE0F Modules: ${c.yellow(`Missing ${e.missingModules.length} init file(s)`)}`)),e.stats){let s=[];e.stats.modules!==void 0&&s.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),s.length>0&&console.log(` \u{1F4CA} Stats: ${c.cyan(s.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${c.gray(e.lastModified)}`);let o=[];if(e.hasTests!==void 0&&o.push(e.hasTests?"\u2705 Tests":c.dim("\u2298 No tests")),e.hasDocker!==void 0&&o.push(e.hasDocker?"\u2705 Docker":c.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let s=e.runtimeFamily==="node"?"ESLint":e.runtimeFamily==="rust"?"clippy":e.runtimeFamily==="elixir"?"Credo":e.runtimeFamily==="clojure"?"clj-kondo":e.runtimeFamily==="deno"?"deno lint":e.framework==="Spring Boot"?"Static analysis":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"golangci-lint":e.runtimeFamily==="python"?"Ruff":"Lint";o.push(e.hasCodeQuality?`\u2705 ${s}`:c.dim(`\u2298 No ${s}`));}if(o.length>0&&console.log(` ${o.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${c.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${c.bold("Issues:")}`),e.issues.forEach(s=>{console.log(` \u2022 ${c.yellow(s)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
3
- ${c.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(s=>{console.log(` ${c.cyan("$")} ${c.white(s)}`);}))),e.probes&&e.probes.length>0){console.log(` ${c.bold("Probe checks:")}`);for(let s of e.probes){let d=s.status==="pass"?"\u2705":s.status==="warn"?"\u26A0\uFE0F":"\u274C";console.log(` ${d} ${s.label}: ${c.gray(s.reason)}`),s.recommendation&&console.log(` ${c.dim("\u21B3")} ${c.gray(s.recommendation)}`);}}if(e.commandCapabilities){let s=e.commandCapabilities;if(console.log(` ${c.bold("Command support:")}`),console.log(` ${c.green("supported")} ${s.supportedCommands.length} \u2022 ${c.yellow("unsupported")} ${s.unsupportedCommands.length} \u2022 ${c.gray("global")} ${s.globalCommands.length}`),s.unsupportedCommands.length>0){let d=s.unsupportedCommands.slice(0,8).join(", "),u=s.unsupportedCommands.length>8?", ...":"";console.log(` ${c.dim("\u21B3")} ${c.gray(`Unsupported here: ${d}${u}`)}`);}}}async function Le(){try{return (await execa("go",["version"],{timeout:a$3(),reject:false})).exitCode===0}catch{return false}}function Z(e,n){let r=[new RegExp(`^cd\\s+"([^"]+)"\\s*(?:&&|;)\\s*${n}\\s*$`,"i"),new RegExp(`^cd\\s+'([^']+)'\\s*(?:&&|;)\\s*${n}\\s*$`,"i"),new RegExp(`^cd\\s+(.+?)\\s*(?:&&|;)\\s*${n}\\s*$`,"i")];for(let t of r){let l=e.match(t);if(l?.[1])return {projectPath:l[1].trim()}}return null}function Je(e){return Z(e,"cp\\s+\\.env\\.example\\s+\\.env")||Z(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function qe(e){let n=[{pattern:"npm\\s+install",command:"npm",args:["install"]},{pattern:"npm\\s+ci",command:"npm",args:["ci"]},{pattern:"pnpm\\s+install",command:"pnpm",args:["install"]},{pattern:"yarn\\s+install",command:"yarn",args:["install"]},{pattern:"poetry\\s+install",command:"poetry",args:["install"]},{pattern:"pip\\s+install\\s+-r\\s+requirements\\.txt",command:"pip",args:["install","-r","requirements.txt"]},{pattern:"composer\\s+install",command:"composer",args:["install"]},{pattern:"bundle\\s+install",command:"bundle",args:["install"]},{pattern:"dotnet\\s+restore",command:"dotnet",args:["restore"]},{pattern:"cargo\\s+fetch",command:"cargo",args:["fetch"]},{pattern:"mix\\s+deps\\.get",command:"mix",args:["deps.get"]},{pattern:"clojure\\s+-P",command:"clojure",args:["-P"]},{pattern:"sbt\\s+compile",command:"sbt",args:["compile"]}];for(let r of n){let t=Z(e,r.pattern);if(t)return {projectPath:t.projectPath,command:r.command,args:r.args}}return null}function ye(e,n){return /^https?:\/\//i.test(n.trim())?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"manual-url",risk:"safe",executable:false,reason:"Manual guidance URL"}:Je(n)?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"}:Z(n,"rapidkit\\s+init")?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"rapidkit-init",risk:"guarded",executable:true,reason:"RapidKit initializer may mutate dependencies and configs"}:Z(n,"go\\s+mod\\s+tidy")?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"go-mod-tidy",risk:"guarded",executable:true,reason:"Go module graph reconciliation"}:qe(n)?{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"dependency-sync",risk:"guarded",executable:true,reason:"Dependency synchronization command"}:{projectName:e.name,projectPath:e.path,originalCommand:n,kind:"shell",risk:"invasive",executable:true,reason:"Generic shell command"}}async function ke(e){let n=e.filter(m=>m.fixCommands&&m.fixCommands.length>0),r=n.flatMap(m=>(m.fixCommands??[]).map(f=>ye(m,f))),t=null,l=[],o=0,s=0,d=0,u=0;for(let m of r){let f=m.executable,g;m.kind==="go-mod-tidy"&&(t===null&&(t=await Le()),t||(f=false,g="Go toolchain not available")),f&&(o+=1,m.risk==="safe"&&(s+=1),m.risk==="guarded"&&(d+=1),m.risk==="invasive"&&(u+=1)),l.push({...m,executableInCurrentEnvironment:f,blockedReason:g});}return {generatedAt:new Date().toISOString(),fixableProjects:n.length,totalSteps:l.length,executableSteps:o,risk:{safe:s,guarded:d,invasive:u},steps:l}}function He(e){let n=e instanceof Error?e.message:String(e),r=["ETIMEDOUT","ECONNRESET","ECONNREFUSED","EAI_AGAIN","ENOTFOUND","network","503","504"],t=n.toLowerCase();return r.some(l=>t.includes(l.toLowerCase()))}async function Ht(e,n){let r=e.get(n);if(r)return r;let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,l=i.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_"),o=i.join(n,".rapidkit","reports","fix-snapshots",`${l}-${t}`);await a$1.ensureDir(o);let s=[".env","package-lock.json","pnpm-lock.yaml","yarn.lock","poetry.lock","requirements.txt","go.mod","go.sum","Cargo.lock","composer.lock","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile"],d=new Map;for(let m of s){let f=i.join(n,m);if(!await a$1.pathExists(f))continue;let g=i.join(o,m);await a$1.ensureDir(i.dirname(g)),await a$1.copy(f,g,{overwrite:true}),d.set(f,g);}let u={snapshotRoot:o,files:d};return e.set(n,u),u}async function Nt(e){for(let[n,r]of e.files.entries())await a$1.pathExists(r)&&(await a$1.ensureDir(i.dirname(n)),await a$1.copy(r,n,{overwrite:true}));}async function Mt(e){let n=await be(e,{allowNonRapidkit:true});return {issues:n.issues.length,healthy:n.issues.length===0}}async function te(e,n=false,r={}){let t=await ke(e),l=e.filter(h=>h.fixCommands&&h.fixCommands.length>0),o=null,s=t.steps.some(h=>h.kind==="go-mod-tidy"&&!h.executableInCurrentEnvironment),d=new Map;if(l.length===0){console.log(c.green(`
4
- \u2705 No fixes needed - all projects are healthy!`));return}console.log(c.bold.cyan(`
5
- \u{1F527} Available Fixes:
6
- `));for(let h of l){let v=h.fixCommands??[];console.log(c.bold(`Project: ${c.yellow(h.name)}`)),v.forEach((y,b)=>{console.log(` ${b+1}. ${c.cyan(y)}`);}),console.log();}if(r.planOnly){if(r.json){console.log(JSON.stringify(t,null,2));return}console.log(c.bold(`
7
- \u{1F9ED} Remediation Plan
8
- `)),console.log(c.gray(`Executable steps: ${t.executableSteps}/${t.totalSteps} | risk: safe=${t.risk.safe}, guarded=${t.risk.guarded}, invasive=${t.risk.invasive}`));for(let h of t.steps){let v=h.executableInCurrentEnvironment?c.green("ready"):c.yellow(`blocked${h.blockedReason?` (${h.blockedReason})`:""}`);console.log(` - ${c.cyan(h.projectName)} [${h.risk}] ${h.originalCommand} ${c.gray(`=> ${v}`)}`);}console.log(c.gray(`
9
- Use --apply to execute this plan non-interactively, or --fix for interactive confirmation.`));return}let u=t.executableSteps,m=t.risk.safe,f=t.risk.guarded,g=t.risk.invasive;if(u===0){console.log(c.gray("\u{1F4A1} No automatic fixes can be applied right now.")),s&&console.log(c.gray(" Install Go to enable go mod tidy fixes, then rerun `rapidkit doctor workspace --fix`."));return}if(!n){console.log(c.gray('\u{1F4A1} Run "npx rapidkit doctor workspace --fix" to apply fixes automatically'));return}if(console.log(c.gray(`Risk policy: safe=${m}, guarded=${f}, invasive=${g}. Guarded/invasive fixes use snapshot + rollback.`)),!r.skipConfirmation){let{confirm:h}=await et.prompt([{type:"confirm",name:"confirm",message:`Apply ${l.reduce((v,y)=>v+(y.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!h){console.log(c.yellow(`
10
- \u26A0\uFE0F Fixes cancelled by user`));return}}console.log(c.bold.cyan(`
11
- \u{1F680} Applying fixes...
12
- `));let p=new Set;for(let h of l){let v=h.fixCommands??[];console.log(c.bold(`Fixing ${c.cyan(h.name)}...`));for(let y of v){let b$1=ye(h,y),T=`${h.path}::${y}`;if(!p.has(T)){p.add(T);try{if(console.log(c.gray(` $ ${y}`)),b$1.kind==="manual-url"){console.log(c.yellow(` \u2139 Manual action required: open ${y}`)),console.log(c.green(` \u2705 Recorded as guidance
13
- `));continue}if(!b$1.executable){console.log(c.yellow(" \u26A0 Step is non-executable by policy")),console.log(c.green(` \u2705 Recorded as guidance
14
- `));continue}b$1.risk!=="safe"&&await Ht(d,b$1.projectPath);let W=Je(y);if(W){let B=i.join(W.projectPath,".env.example"),R=i.join(W.projectPath,".env");if(!await a$1.pathExists(B))throw new Error(`.env.example not found at ${B}`);if(await a$1.pathExists(R)){console.log(c.green(` \u2705 .env already exists
15
- `));continue}await a$1.copy(B,R,{overwrite:false,errorOnExist:false}),console.log(c.green(` \u2705 Success
16
- `));continue}let J=Z(y,"rapidkit\\s+init");if(J){await execa("rapidkit",["init"],{cwd:J.projectPath,shell:b(),stdio:"inherit"}),console.log(c.green(` \u2705 Success
17
- `));continue}let q=Z(y,"go\\s+mod\\s+tidy");if(q){if(o===null&&(o=await Le()),!o){console.log(c.yellow(" \u26A0 Go toolchain is not installed \u2014 skipping go mod tidy; install Go to apply this fix.")),console.log(c.green(` \u2705 Recorded as guidance
18
- `));continue}await execa("go",["mod","tidy"],{cwd:q.projectPath,shell:b(),stdio:"inherit"}),console.log(c.green(` \u2705 Success
19
- `));continue}let O=qe(y);if(O){let R;for(let ee=1;ee<=2;ee+=1)try{await execa(O.command,O.args,{cwd:O.projectPath,shell:b(),stdio:"inherit"}),R=null;break}catch(se){if(R=se,ee<2&&He(se)){console.log(c.yellow(` \u26A0 Retrying dependency sync (${ee}/1)...`));continue}throw se}if(R)throw R;console.log(c.green(` \u2705 Success
20
- `));continue}let ne=b$1.kind==="shell"?2:1,U;for(let B=1;B<=ne;B+=1)try{await execa(y,{shell:true,stdio:"inherit"}),U=null;break}catch(R){if(U=R,B<ne&&He(R)){console.log(c.yellow(` \u26A0 Retrying command (${B}/${ne-1})...`));continue}throw R}if(U)throw U;console.log(c.green(` \u2705 Success
21
- `));}catch(W){let J=ye(h,y);if(J.risk!=="safe"){let q=d.get(J.projectPath);if(q)try{await Nt(q),console.log(c.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(O){console.log(c.red(` \u274C Rollback failed: ${O instanceof Error?O.message:String(O)}`));}}console.log(c.red(` \u274C Failed: ${W instanceof Error?W.message:String(W)}
22
- `));}}}try{let y=await Mt(h.path);console.log(y.healthy?c.green(` \u2705 Post-fix verification passed for ${h.name}`):c.yellow(` \u26A0 Post-fix verification: ${y.issues} issue(s) remain for ${h.name}`));}catch(y){console.log(c.yellow(` \u26A0 Post-fix verification skipped: ${y instanceof Error?y.message:String(y)}`));}}console.log(c.bold.green(`
23
- \u2705 Fix process completed!`));}async function Yt(e={}){let n=!!(e.fix||e.plan||e.apply),r=!e.workspace&&!e.project&&n?await ae(process.cwd()):null,t=e.workspace||!!r,l=!!e.project&&!t;if(e.json||console.log(c.bold.cyan(`
24
- \u{1FA7A} RapidKit Health Check
25
- `)),t){let o=r??await ae(process.cwd());o||(a.error("No RapidKit workspace found in current directory or parents"),a.info('Run this command from within a workspace, or use "rapidkit doctor" for system check'),process.exit(1)),e.json||(r&&console.log(c.gray("\u2139\uFE0F Detected workspace context; enabling workspace checks for --fix")),console.log(c.bold(`Workspace: ${c.cyan(i.basename(o))}`)),console.log(c.gray(`Path: ${o}`)));let s=await Ae(o);if(e.json||(s.projectScanCached&&console.log(c.gray(`\u2139\uFE0F Reused cached project scan${s.projectScanCachePath?` (${i.basename(s.projectScanCachePath)})`:""}`)),s.evidencePath&&console.log(c.gray(`\u2139\uFE0F Evidence saved: ${s.evidencePath}`))),e.json){let f=e.plan?await ke(s.projects):void 0,g={contract:de(),workspace:{name:i.basename(o),path:o},cache:{projectScan:s.projectScanCached??false,projectScanPath:s.projectScanCachePath,evidencePath:s.evidencePath},healthScore:s.healthScore,system:{python:s.python,poetry:s.poetry,pipx:s.pipx,rapidkitCore:s.rapidkitCore,versions:{core:s.coreVersion,npm:s.npmVersion}},projects:s.projects.map(p=>({name:p.name,path:p.path,framework:p.framework,frameworkKey:p.frameworkKey,importStack:p.importStack,runtimeFamily:p.runtimeFamily,projectKind:p.projectKind,supportTier:p.supportTier,frameworkConfidence:p.frameworkConfidence,venvActive:p.venvActive,depsInstalled:p.depsInstalled,hasEnvFile:p.hasEnvFile,vulnerabilities:p.vulnerabilities,coreInstalled:p.coreInstalled,coreVersion:p.coreVersion,issues:p.issues,fixCommands:p.fixCommands,probes:p.probes,commandCapabilities:p.commandCapabilities})),summary:{totalProjects:s.projects.length,totalIssues:s.projects.reduce((p,h)=>p+h.issues.length,0),projectAdvisoryWarningProjects:he(s.projects),projectAdvisoryWarnings:we(s.projects),hasSystemErrors:[s.python,s.rapidkitCore].some(p=>p.status==="error"),scopeProvenance:s.scopeProvenance},driftDelta:s.driftDelta,scoreBreakdown:s.scoreBreakdown??[],...f?{remediationPlan:f}:{}};console.log(JSON.stringify(g,null,2));return}if(s.healthScore){let f=s.healthScore,g=Math.round(f.passed/f.total*100),p=g>=80?c.green:g>=50?c.yellow:c.red,h="\u2588".repeat(Math.floor(g/5))+"\u2591".repeat(20-Math.floor(g/5));console.log(c.bold(`
26
- \u{1F4CA} Health Score:`)),console.log(` ${p(`${g}%`)} ${c.gray(h)}`),console.log(` ${c.green(`\u2705 ${f.passed} passed`)} ${c.gray("|")} ${c.yellow(`\u26A0\uFE0F ${f.warnings} warnings`)} ${c.gray("|")} ${c.red(`\u274C ${f.errors} errors`)}`);}if(console.log(c.bold(`
27
-
28
- System Tools:
29
- `)),E(s.python,"Python"),E(s.poetry,"Poetry"),E(s.pipx,"pipx"),E(s.go,"Go"),E(s.rapidkitCore,"RapidKit Core"),s.coreVersion&&s.npmVersion){let f=s.coreVersion.split(".")[1],g=s.npmVersion.split(".")[1];f!==g&&(console.log(c.yellow(`
30
- \u26A0\uFE0F Version mismatch: Core ${s.coreVersion} / CLI ${s.npmVersion}`)),console.log(c.gray(" Consider updating to matching versions for best compatibility")));}s.projects.length>0?(console.log(c.bold(`
31
- \u{1F4E6} Projects (${s.projects.length}):`)),s.projects.forEach(f=>Ie(f))):(console.log(c.bold(`
32
- \u{1F4E6} Projects:`)),console.log(c.gray(" No RapidKit projects found in workspace")));let d=s.projects.reduce((f,g)=>f+g.issues.length,0),u=he(s.projects),m=[s.python,s.rapidkitCore].some(f=>f.status==="error");if(m||d>0||u>0){let f=u>0?` and ${u} advisory warning project(s)`:"";if(console.log(c.bold.yellow(`
33
- \u26A0\uFE0F Found ${d} project issue(s)${f}`)),m&&console.log(c.bold.red("\u274C System requirements not met")),e.plan)await te(s.projects,false,{planOnly:true,json:e.json});else if(e.fix||e.apply){if(await te(s.projects,true,{skipConfirmation:e.apply===true}),!e.json){let g=await Ae(o,false),p=g.projects.reduce((v,y)=>v+y.issues.length,0),h=[g.python,g.rapidkitCore].some(v=>v.status==="error");h||p>0?(console.log(c.bold.yellow(`
34
- \u26A0\uFE0F Post-fix verification found ${p} remaining issue(s)`)),h&&console.log(c.bold.red("\u274C System requirements still not met"))):console.log(c.bold.green(`
35
- \u2705 Post-fix verification passed. Workspace is healthy.`)),g.projectScanCached&&console.log(c.gray(`\u2139\uFE0F Reused cached project scan${g.projectScanCachePath?` (${i.basename(g.projectScanCachePath)})`:""}`)),g.evidencePath&&console.log(c.gray(`\u2139\uFE0F Evidence refreshed: ${g.evidencePath}`));}}else d>0&&await te(s.projects,false);}else console.log(c.bold.green(`
36
- \u2705 All checks passed! Workspace is healthy.`));}else if(l){let o=await Rt(process.cwd());o||(await ae(process.cwd())?(a.error("No backend project found in current directory within this workspace"),a.info("Run this command from inside a project directory in the workspace")):a.error("No RapidKit project found in current directory or parents"),a.info('Run this command from within a project, or use "rapidkit doctor workspace" for workspace checks'),process.exit(1));let s=await It(o),d=s.workspacePath?De(s.workspacePath):null,u=De(s.project.path);if(e.json){let b=e.plan?await ke([s.project]):void 0,T={contract:de(),scope:"project",workspace:d?{name:i.basename(d),path:d}:null,project:{name:s.project.name,path:u,framework:s.project.framework,frameworkKey:s.project.frameworkKey,importStack:s.project.importStack,runtimeFamily:s.project.runtimeFamily,projectKind:s.project.projectKind,supportTier:s.project.supportTier,frameworkConfidence:s.project.frameworkConfidence,venvActive:s.project.venvActive,depsInstalled:s.project.depsInstalled,hasEnvFile:s.project.hasEnvFile,vulnerabilities:s.project.vulnerabilities,coreInstalled:s.project.coreInstalled,coreVersion:s.project.coreVersion,issues:s.project.issues,fixCommands:s.project.fixCommands,probes:s.project.probes,commandCapabilities:s.project.commandCapabilities},evidencePath:s.evidencePath,healthScore:s.healthScore,system:{python:s.python,poetry:s.poetry,pipx:s.pipx,go:s.go,rapidkitCore:s.rapidkitCore},summary:{totalProjects:1,totalIssues:s.project.issues.length,projectAdvisoryWarningProjects:Y(s.project)>0?1:0,projectAdvisoryWarnings:Y(s.project),hasSystemErrors:[s.python,s.rapidkitCore].some(W=>W.status==="error"),scopeProvenance:s.scopeProvenance},driftDelta:s.driftDelta,scoreBreakdown:s.scoreBreakdown??[],...b?{remediationPlan:b}:{}};console.log(JSON.stringify(T,null,2));return}console.log(c.bold(`Project: ${c.cyan(i.basename(o))}`)),console.log(c.gray(`Path: ${o}`)),s.workspacePath&&console.log(c.gray(`Workspace: ${i.basename(s.workspacePath)}`)),s.evidencePath&&console.log(c.gray(`\u2139\uFE0F Evidence saved: ${s.evidencePath}`));let m=s.healthScore,f=m.total>0?Math.round(m.passed/m.total*100):0,g=f>=80?c.green:f>=50?c.yellow:c.red,p="\u2588".repeat(Math.floor(f/5))+"\u2591".repeat(20-Math.floor(f/5));console.log(c.bold(`
37
- \u{1F4CA} Health Score:`)),console.log(` ${g(`${f}%`)} ${c.gray(p)}`),console.log(` ${c.green(`\u2705 ${m.passed} passed`)} ${c.gray("|")} ${c.yellow(`\u26A0\uFE0F ${m.warnings} warnings`)} ${c.gray("|")} ${c.red(`\u274C ${m.errors} errors`)}`),console.log(c.bold(`
38
-
39
- System Tools:
40
- `)),E(s.python,"Python"),E(s.poetry,"Poetry"),E(s.pipx,"pipx"),E(s.go,"Go"),E(s.rapidkitCore,"RapidKit Core"),console.log(c.bold(`
41
- \u{1F4E6} Project (1):`)),Ie(s.project);let h=[s.python,s.rapidkitCore].some(b=>b.status==="error"),v=s.project.issues.length,y=Y(s.project);if(h||v>0||y>0){let b=y>0?` and ${y} advisory warning(s)`:"";console.log(c.bold.yellow(`
42
- \u26A0\uFE0F Found ${v} project issue(s)${b}`)),h&&console.log(c.bold.red("\u274C System requirements not met")),e.plan?await te([s.project],false,{planOnly:true,json:e.json}):e.fix||e.apply?await te([s.project],true,{skipConfirmation:e.apply===true}):v>0&&await te([s.project],false);}else console.log(c.bold.green(`
43
- \u2705 All checks passed! Project is healthy.`));}else {console.log(c.bold(`System Tools:
44
- `));let o=await ve(),s=o.python,d=o.poetry,u=o.pipx,m=o.go,f=o.rapidkitCore;E(s,"Python"),E(d,"Poetry"),E(u,"pipx"),E(m,"Go"),E(f,"RapidKit Core"),[s,f].some(p=>p.status==="error")?(console.log(c.bold.red(`
45
- \u274C Some required tools are missing`)),(e.fix||e.apply)&&console.log(c.gray(`
46
- Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "rapidkit doctor workspace --fix"`)),console.log(c.gray(`
47
- Tip: Run "rapidkit doctor workspace" for workspace-wide checks, or "rapidkit doctor project" for the current project`))):(console.log(c.bold.green(`
48
- \u2705 All required tools are installed!`)),(e.fix||e.apply)&&console.log(c.gray(`
49
- Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "rapidkit doctor workspace --fix"`)),console.log(c.gray(`
50
- Tip: Run "rapidkit doctor workspace" for workspace-wide checks, or "rapidkit doctor project" for the current project`)));}console.log("");}export{Yt as runDoctor};
@@ -1,2 +0,0 @@
1
- import u from'path';import l from'fs-extra';var w=".rapidkit/workspace.contract.json",h=1;function C(r){return r.replace(/\\/g,"/")}function v(r){let n=C(r).trim();return !n||n.startsWith("/")||n.startsWith("~")||/^[a-zA-Z]:\//.test(n)||n.includes("\0")?false:!n.split("/").filter(Boolean).some(e=>e===".."||e===".")}function b(r){return Array.isArray(r)?r.filter(n=>typeof n=="string"&&n.trim().length>0):[]}async function W(r){let n=u.join(r,".rapidkit","workspace.json");try{let e=await l.readJson(n);return {name:typeof e.workspace_name=="string"&&e.workspace_name.trim()||typeof e.name=="string"&&e.name.trim()||u.basename(r),profile:typeof e.profile=="string"?e.profile:void 0}}catch{return {name:u.basename(r)}}}async function A(r){let n=[],e=[r],s=new Set,i=new Set([".git","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;e.length>0;){let c=e.shift();if(!c||s.has(c))continue;s.add(c);let p=u.join(c,".rapidkit","project.json");if(await l.pathExists(p)){n.push(p);continue}let o;try{o=await l.readdir(c,{withFileTypes:true});}catch{continue}for(let t of o)!t.isDirectory()||i.has(t.name)||e.push(u.join(c,t.name));}return n.sort()}function S(r){let n=(r||"").toLowerCase();if(n.includes("fastapi"))return "fastapi";if(n.includes("nestjs"))return "nestjs";if(n.includes("springboot"))return "springboot";if(n.includes("gofiber"))return "fiber";if(n.includes("gogin"))return "gin"}function $(r,n){let e=(r||"").toLowerCase(),s=(n||"").toLowerCase();return e.includes("fastapi")?8e3:e.includes("nestjs")?3e3:e.includes("springboot")?8080:e.includes("gofiber")?3e3:e.includes("gogin")?8080:s==="node"?3e3:s==="python"?8e3:s==="java"||s==="go"?8080:null}function E(r,n){let e=r;for(;n.has(e)&&e<65535;)e+=1;return e}function k(r,n,e){let s=$(n.kit,n.runtime),i=r?.ports||[],c=i.length>0?i:s?[{name:"http",port:E(s,e),protocol:"http"}]:[];for(let t of c)e.add(t.port);let p={...n,...r,slug:r?.slug||n.slug,relativePath:r?.relativePath||n.relativePath,runtime:r?.runtime||n.runtime,framework:r?.framework||n.framework,kit:r?.kit||n.kit,modules:r?.modules?.length?r.modules:n.modules,ports:c,contracts:{owns:r?.contracts?.owns||[],apis:r?.contracts?.apis||[],publishes:r?.contracts?.publishes||[],consumes:r?.contracts?.consumes||[],dependsOn:r?.contracts?.dependsOn||[],env:r?.contracts?.env||[]}},o=JSON.stringify(r||null)!==JSON.stringify(p);return {project:p,changed:o}}async function j(r){let n=u.resolve(r.workspacePath),e=await W(n),s=await A(n),i=[];for(let c of s){let p=u.dirname(u.dirname(c)),o=C(u.relative(n,p)),t=await l.readJson(c),a=typeof t.kit_name=="string"&&t.kit_name||typeof t.kit=="string"&&t.kit||void 0,f=typeof t.framework=="string"&&t.framework||S(a);i.push({slug:o||u.basename(p),relativePath:o,runtime:typeof t.runtime=="string"?t.runtime:void 0,framework:f,kit:a,modules:b(t.modules),ports:[],contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}return {schemaVersion:h,kind:"rapidkit.workspace.contract",generatedAt:(r.now??new Date).toISOString(),workspace:e,projects:i}}async function _(r){let n=u.resolve(r.outputPath||u.join(r.workspacePath,w));if(await l.pathExists(n)&&r.force!==true)throw new Error(`Workspace contract already exists: ${n}. Use --force to overwrite.`);let e=await j({workspacePath:r.workspacePath,now:r.now}),s=new Set,i={...e,projects:e.projects.map(c=>k(void 0,c,s).project)};return await l.ensureDir(u.dirname(n)),await l.writeJson(n,i,{spaces:2}),{contractPath:n,contract:i}}async function J(r){let n=u.resolve(r.workspacePath),e=u.join(n,w),s=await j({workspacePath:n,now:r.now}),i=await l.pathExists(e)?await l.readJson(e):null,c=new Map((i?.projects||[]).map(d=>[d.slug,d])),p=new Set,o=[],t=[],a=[];for(let d of s.projects){let g=c.get(d.slug),P=k(g,d,p);g?P.changed&&t.push(d.slug):o.push(d.slug),a.push(P.project),c.delete(d.slug);}for(let d of c.values()){let g=k(d,d,p);a.push(g.project);}let f={schemaVersion:h,kind:"rapidkit.workspace.contract",generatedAt:(r.now??new Date).toISOString(),workspace:{...s.workspace,...i?.workspace||{},name:i?.workspace?.name||s.workspace.name},projects:a.sort((d,g)=>d.slug.localeCompare(g.slug))};await l.ensureDir(u.dirname(e)),await l.writeJson(e,f,{spaces:2});let m=await O({workspacePath:n});return {contractPath:e,contract:f,addedProjects:o,updatedProjects:t,verification:m}}async function y(r){let n=u.resolve(r.contractPath||u.join(r.workspacePath,w)),e=await l.readJson(n);return {contractPath:n,contract:e}}async function D(r){let{contractPath:n,contract:e}=await y(r),s=e.projects.map(t=>({id:t.slug,label:t.slug,relativePath:t.relativePath,runtime:t.runtime,framework:t.framework,kit:t.kit,modules:t.modules,ports:t.ports,apis:t.contracts.apis,owns:t.contracts.owns,env:t.contracts.env})),i=new Set(s.map(t=>t.id)),c=new Map,p=[];for(let t of e.projects){for(let a of t.contracts.dependsOn||[])i.has(a)&&p.push({from:a,to:t.slug,type:"dependency",label:"dependsOn"});for(let a of t.contracts.publishes||[])c.has(a)||c.set(a,new Set),c.get(a)?.add(t.slug);}for(let t of e.projects)for(let a of t.contracts.consumes||[]){let f=c.get(a);if(f)for(let m of f)m!==t.slug&&p.push({from:m,to:t.slug,type:"event",label:a});}let o={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:e.workspace,generatedAt:new Date().toISOString(),nodes:s.sort((t,a)=>t.id.localeCompare(a.id)),edges:p.sort((t,a)=>`${t.from}:${t.to}:${t.type}:${t.label}`.localeCompare(`${a.from}:${a.to}:${a.type}:${a.label}`)),summary:{projectCount:s.length,dependencyEdges:p.filter(t=>t.type==="dependency").length,eventEdges:p.filter(t=>t.type==="event").length,portCount:s.reduce((t,a)=>t+a.ports.length,0),apiCount:s.reduce((t,a)=>t+a.apis.length,0)}};return {contractPath:n,graph:o}}async function O(r){let{contractPath:n,contract:e}=await y(r),s=[],i=[];e.kind!=="rapidkit.workspace.contract"&&s.push("Contract kind must be rapidkit.workspace.contract."),e.schemaVersion!==h&&s.push(`Contract schemaVersion must be ${h}.`),e.workspace?.name||s.push("Contract workspace.name is required."),Array.isArray(e.projects)||s.push("Contract projects must be an array.");let c=new Set,p=new Map;for(let o of e.projects||[]){if(!o.slug){s.push("Every project must declare slug.");continue}c.has(o.slug)&&s.push(`Duplicate project slug: ${o.slug}.`),c.add(o.slug),o.relativePath?v(o.relativePath)||s.push(`Project ${o.slug} declares unsafe relativePath: ${o.relativePath}.`):s.push(`Project ${o.slug} must declare relativePath.`);for(let t of o.ports||[]){(!Number.isInteger(t.port)||t.port<1||t.port>65535)&&s.push(`Project ${o.slug} declares invalid port: ${t.port}.`);let a=p.get(t.port);a&&s.push(`Port ${t.port} is claimed by both ${a} and ${o.slug}.`),p.set(t.port,o.slug);}for(let t of o.contracts?.apis||[])(!t.name?.trim()||!t.basePath?.startsWith("/"))&&s.push(`Project ${o.slug} declares invalid API contract.`);for(let t of [...o.contracts?.publishes||[],...o.contracts?.consumes||[]])t.trim()||s.push(`Project ${o.slug} declares an empty event contract.`);for(let t of o.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(t)||s.push(`Project ${o.slug} declares invalid env contract: ${t}.`);for(let t of o.contracts?.dependsOn||[])c.has(t);}for(let o of e.projects||[])for(let t of o.contracts?.dependsOn||[])c.has(t)||s.push(`Project ${o.slug} depends on unknown project: ${t}.`);return i.push({id:"schema",status:e.kind==="rapidkit.workspace.contract"&&e.schemaVersion===h?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(e.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(e.projects)?e.projects.length:0} project(s).`}),i.push({id:"ports",status:s.some(o=>o.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:s.some(o=>o.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:s.some(o=>o.includes("unsafe relativePath")||o.includes("invalid API contract")||o.includes("event contract")||o.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."}),{status:s.length>0?"failed":"passed",contractPath:n,projectCount:Array.isArray(e.projects)?e.projects.length:0,checks:i,violations:s}}
2
- export{w as WORKSPACE_CONTRACT_PATH,h as WORKSPACE_CONTRACT_SCHEMA_VERSION,j as buildWorkspaceContract,D as buildWorkspaceContractGraph,y as readWorkspaceContract,J as syncWorkspaceContract,O as verifyWorkspaceContract,_ as writeWorkspaceContract};
@@ -1 +0,0 @@
1
- export{a as runWorkspaceStage}from'./chunk-LSFRHYMD.js';