workspai 0.52.0 → 0.52.2

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.
@@ -1,86 +0,0 @@
1
- import {f as f$3,e as e$2,i,d as d$6,b as b$8,c as c$4,g as g$1,h}from'./chunk-ZTKIBREF.js';import {c,b,d as d$2}from'./chunk-CZC5P2MF.js';import {f as f$1,e as e$1}from'./chunk-T3GJ7YVG.js';import {b as b$2}from'./chunk-2OIBHUVH.js';import {b as b$1}from'./chunk-KVSYBHUR.js';import {c as c$3,a as a$5,d as d$3,b as b$5}from'./chunk-7MQZQ4UU.js';import {j,g}from'./chunk-ZVOEPWQM.js';import {d as d$5}from'./chunk-PS5F4DCT.js';import {b as b$4,c as c$2}from'./chunk-P4OSLAVD.js';import {b as b$3}from'./chunk-FUPHQOJB.js';import {a as a$3}from'./chunk-27UR373Z.js';import {a as a$1}from'./chunk-Y5YAP4F3.js';import {a as a$2}from'./chunk-B4CPDK6J.js';import {w}from'./chunk-6HJJHEL6.js';import {j as j$3,d as d$4,b as b$7,a as a$9}from'./chunk-2PY65U6X.js';import {a as a$8}from'./chunk-GR6442P7.js';import {d as d$1,e,f as f$2}from'./chunk-MBRU3VWJ.js';import {a as a$4}from'./chunk-AFIFZTOY.js';import {a}from'./chunk-62K2H72S.js';import {f}from'./chunk-VRW6KXNK.js';import {a as a$7}from'./chunk-TQEMLBAG.js';import {s,j as j$1,t}from'./chunk-MOSXTVPU.js';import {c as c$1,j as j$2,b as b$6,t as t$1,n,p as p$1,m}from'./chunk-RJIYCDVC.js';import {a as a$6}from'./chunk-2FIX2MDC.js';import p from'chalk';import {createHash}from'crypto';import {execa}from'execa';import u from'fs-extra';import d from'path';import {existsSync}from'fs';var si=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],ai=["tests","test","src/test","__tests__","e2e","playwright","cypress"],ci=["vitest.config.ts","vitest.config.js","vitest.config.mjs","jest.config.js","jest.config.ts","jest.config.mjs","playwright.config.ts","playwright.config.js","cypress.config.js","cypress.config.ts"],li=["src","app","pages"],di=["dev","build","test","lint"];function kn(e){let t=e?.scripts;if(!t||typeof t!="object"||Array.isArray(t))return {};let i={};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.trim().length>0&&(i[n]=o);return i}async function vn(e,t){for(let o of si)if(await u.pathExists(d.join(e,o)))return true;let i=t??(await u.pathExists(d.join(e,"package.json"))?await u.readJson(d.join(e,"package.json")):null);if(!i)return false;if(i.eslintConfig)return true;let n={...i.dependencies??{},...i.devDependencies??{}};return !!(n.eslint||n["@eslint/js"]||n["@eslint/eslintrc"])}async function bn(e,t){for(let o of ai)if(await u.pathExists(d.join(e,o)))return true;for(let o of ci)if(await u.pathExists(d.join(e,o)))return true;let i=kn(t);if(i.test||i["test:unit"]||i["test:e2e"]||i["test:ci"]||i["test:watch"])return true;let n={...t?.dependencies??{},...t?.devDependencies??{}};return n.vitest||n.jest||n["@playwright/test"]||n.cypress?true:await ui(e)}async function ui(e){let t=["src","app","pages","components"],i=/\.(test|spec)\.(tsx?|jsx?|vue|svelte)$/i,o=new Set(["node_modules",".git","dist","build",".next","coverage",".turbo"]);for(let s of t){let a=d.join(e,s);if(!await u.pathExists(a))continue;let r=[{dir:a,depth:0}];for(;r.length>0;){let c=r.shift();if(!c)break;let l=[];try{l=await u.readdir(c.dir);}catch{continue}for(let m of l){let h=d.join(c.dir,m);if(i.test(m))return true;if(!(c.depth>=3||o.has(m)||m.startsWith(".")))try{(await u.stat(h)).isDirectory()&&r.push({dir:h,depth:c.depth+1});}catch{continue}}}}return false}async function jt(e){for(let t of li){let i=d.join(e,t);if(await u.pathExists(i))try{if((await u.readdir(i)).some(o=>!o.startsWith(".")))return true}catch{continue}}return false}function pi(e){let t=e.key;return b$7(t).key}function mi(e,t,i){return a$9(t,i).some(o=>!!e[o])}async function wn(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=pi(i),s=b$7(o),a=kn(n),r=[],c=await u.pathExists(d.join(t,"package-lock.json"))||await u.pathExists(d.join(t,"pnpm-lock.yaml"))||await u.pathExists(d.join(t,"yarn.lock"))||await u.pathExists(d.join(t,"bun.lockb"));r.push({id:"frontend-lockfile-integrity",label:"Frontend lockfile integrity",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml/bun.lockb).",recommendation:c?void 0:"Commit a lockfile for deterministic installs and CI parity."});let l=await u.pathExists(d.join(t,"tsconfig.json")),m=await u.pathExists(d.join(t,"jsconfig.json")),h=l||m;r.push({id:"frontend-typescript-surface",label:"TypeScript project surface",status:h?"pass":"warn",severity:"warn",scope:"project-scoped",reason:h?l?"tsconfig.json detected.":"jsconfig.json detected.":"No tsconfig.json or jsconfig.json detected.",recommendation:h?void 0:"Add tsconfig.json (or jsconfig.json) for typed frontend builds and IDE parity."});let v=s.fileHints.length>0&&s.fileHints.some(g=>existsSync(d.join(t,g)));r.push({id:"frontend-framework-config",label:`${s.displayName} config surface`,status:v?"pass":"warn",severity:"warn",scope:"project-scoped",reason:v?`${s.displayName} configuration artifacts detected.`:`No ${s.displayName} config markers detected (${s.fileHints.join(", ")||"n/a"}).`,recommendation:v?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let g of di){let k=mi(a,o,g),y=g==="dev"||g==="build",w=!k&&g==="test"?f$3({projectPath:t,frameworkDisplayName:s.displayName,scriptName:g,scriptValue:e$2(a)}):void 0;r.push({id:`frontend-script-${g}`,label:`${g} script surface`,status:k?"pass":y?"fail":"warn",severity:y?"error":"warn",scope:"project-scoped",reason:k?`package.json exposes a ${g} script for ${s.displayName}.`:`No ${g} script detected for ${s.displayName}.`,recommendation:k?void 0:`Add a "${a$9(o,g)[0]??g}" script to package.json.`,repairCapability:w});}let C=await jt(t);return r.push({id:"frontend-source-tree",label:"Frontend source tree",status:C?"pass":"warn",severity:"warn",scope:"project-scoped",reason:C?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:C?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),r}var fi={node:["package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"],deno:["deno.lock"],bun:["bun.lock","bun.lockb"],python:["uv.lock","poetry.lock","requirements.txt","requirements.lock"],go:["go.sum"],java:["gradle.lockfile","gradle/libs.versions.toml"],rust:["Cargo.lock"],elixir:["mix.lock"],clojure:["deps.edn","project.clj"],php:["composer.lock"],ruby:["Gemfile.lock"],dotnet:["packages.lock.json","Directory.Packages.props"],scala:["project/build.properties","project/plugins.sbt"],kotlin:["gradle.lockfile","gradle/libs.versions.toml"],c:["conan.lock","vcpkg-lock.json"],cpp:["conan.lock","vcpkg-lock.json"],unknown:[]},gi={node:["package.json"],deno:["deno.json","deno.jsonc"],bun:["package.json","bunfig.toml"],python:["pyproject.toml","requirements.txt","setup.py"],go:["go.mod"],java:["pom.xml","build.gradle","build.gradle.kts"],rust:["Cargo.toml"],elixir:["mix.exs"],clojure:["deps.edn","project.clj"],php:["composer.json"],ruby:["Gemfile"],dotnet:["*.csproj","*.sln"],scala:["build.sbt"],kotlin:["build.gradle","build.gradle.kts","pom.xml"],c:["CMakeLists.txt","meson.build","Makefile"],cpp:["CMakeLists.txt","meson.build","Makefile"],unknown:[]},yi=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
2
- `),xt=[".env",".env.*","!.env.example"];function xe(e){return e&&(e==="python"||e==="node"||e==="go"||e==="java"||e==="rust"||e==="elixir"||e==="clojure"||e==="deno"||e==="bun"||e==="php"||e==="ruby"||e==="dotnet"||e==="scala"||e==="kotlin"||e==="c"||e==="cpp")?e:"unknown"}async function je(e,t){for(let i of t){if(i.includes("*")){let n=i.replace("*","");if(await hi(e,n,2))return true;continue}if(await u.pathExists(d.join(e,i)))return true}return false}async function hi(e,t,i){let n=[{dir:e,depth:0}],o=new Set(["node_modules",".git",".workspai",".rapidkit","dist","build","coverage"]);for(;n.length>0;){let s=n.shift();if(!s)break;let a=[];try{a=await u.readdir(s.dir,{withFileTypes:true});}catch{continue}for(let r of a){if(o.has(r.name))continue;let c=d.join(s.dir,r.name);if(r.isFile()&&r.name.endsWith(t))return true;r.isDirectory()&&s.depth<i&&!r.name.startsWith(".")&&n.push({dir:c,depth:s.depth+1});}}return false}async function et(e){try{return await u.pathExists(e)?await u.readFile(e,"utf8"):""}catch{return ""}}async function tt(e,t){let i=[];for(let n of t){let o=await et(d.join(e,n));o&&i.push(o);}return i.join(`
3
- `)}async function ki(e){if(e.runtime==="node"){let t=typeof e.packageJsonData?.packageManager=="string"?e.packageJsonData.packageManager.split("@")[0]:null;return {command:t==="pnpm"?"pnpm install":t==="yarn"?"yarn install":t==="bun"?"bun install":"npm install",title:"Generate Node dependency lockfile",files:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock"],limitations:["Review dependency and lockfile changes before committing."]}}if(e.runtime==="go"&&await u.pathExists(d.join(e.projectPath,"go.mod")))return {command:"go mod tidy",title:"Reconcile Go module graph",files:["go.mod","go.sum"],limitations:["Review go.mod/go.sum changes before committing."]};if(e.runtime==="java"){let t=await u.pathExists(d.join(e.projectPath,"pom.xml")),i=await u.pathExists(d.join(e.projectPath,"mvnw"))||await u.pathExists(d.join(e.projectPath,"mvnw.cmd")),n=await u.pathExists(d.join(e.projectPath,"gradlew"))||await u.pathExists(d.join(e.projectPath,"gradlew.bat"));return {command:t?i?process.platform==="win32"?".\\mvnw.cmd -B -DskipTests dependency:go-offline":"./mvnw -B -DskipTests dependency:go-offline":"mvn -B -DskipTests dependency:go-offline":n?process.platform==="win32"?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies",title:"Prepare Java dependency baseline",files:["pom.xml","build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]}}if(e.runtime==="scala")return {command:"sbt update",title:"Prepare Scala dependency baseline",files:["build.sbt","project/build.properties","project/plugins.sbt"],limitations:["Review resolved dependency and plugin changes before committing."]};if(e.runtime==="kotlin")return {command:process.platform==="win32"?".\\gradlew.bat dependencies":"./gradlew dependencies",title:"Prepare Kotlin dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]};if(e.runtime==="rust")return {command:"cargo fetch",title:"Generate Rust dependency baseline",files:["Cargo.toml","Cargo.lock"],limitations:["Review Cargo.lock changes before committing."]};if(e.runtime==="php")return {command:"composer install",title:"Generate Composer lockfile",files:["composer.json","composer.lock"],limitations:["Review composer.lock changes before committing."]};if(e.runtime==="ruby")return {command:"bundle install",title:"Generate Bundler lockfile",files:["Gemfile","Gemfile.lock"],limitations:["Review Gemfile.lock changes before committing."]};if(e.runtime==="dotnet")return {command:"dotnet restore",title:".NET dependency restore",files:["*.sln","*.csproj","packages.lock.json","Directory.Packages.props"],limitations:["Enable NuGet lock files in the project when release policy requires deterministic restore."]};if(e.runtime==="elixir")return {command:"mix deps.get",title:"Generate Elixir dependency lockfile",files:["mix.exs","mix.lock"],limitations:["Review mix.lock changes before committing."]};if(e.runtime==="clojure")return {command:"clojure -P",title:"Prepare Clojure dependency baseline",files:["deps.edn","project.clj"],limitations:["Review dependency cache and CI restore policy before release."]};if(e.runtime==="python"){let t=await et(d.join(e.projectPath,"pyproject.toml"));if(/\[tool\.poetry\]/.test(t))return {command:"poetry install --no-root",title:"Install Poetry dependency baseline",files:["pyproject.toml","poetry.lock"],limitations:["Review poetry.lock changes before committing when Poetry resolves or updates the lockfile."]};if(/\[tool\.uv\]|\[project\]/.test(t))return {command:"uv lock",title:"Generate uv lockfile",files:["pyproject.toml","uv.lock"],limitations:["Review uv.lock changes before committing."]}}return null}function Me(e){let t=e?.scripts;if(!t||typeof t!="object"||Array.isArray(t))return {};let i={};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.trim().length>0&&(i[n]=o);return i}function vi(e){if(e.runtime==="node"){let i=Me(e.packageJsonData);if(!e.packageJsonData)return null;if(e.kind==="test"){let n=i.lint?"npm run lint":i.build?"npm run build":null;return n?{command:n,title:"Define Node test script",targetName:"test",files:["package.json"],limitations:["Replace this fallback with real tests when product coverage is required."]}:null}return e.kind==="security"?{command:"npm audit --audit-level=moderate",title:"Define Node security audit script",targetName:"audit",files:["package.json"]}:null}return {deno:{test:{command:"deno test --allow-none",title:"Define Deno test command",targetName:"test",files:["Makefile","deno.json","deno.jsonc"]},quality:{command:"deno fmt --check && deno lint",title:"Define Deno quality command",targetName:"quality",files:["Makefile","deno.json","deno.jsonc"]},security:{command:"deno info --json",title:"Define Deno dependency inspection command",targetName:"security",files:["Makefile","deno.json","deno.jsonc","deno.lock"],limitations:["Pair dependency inspection with the organization vulnerability service used by CI."]}},bun:{test:{command:"bun test",title:"Define Bun test script",targetName:"test",files:["package.json","bun.lock","bun.lockb"]},quality:{command:"bunx eslint .",title:"Define Bun quality script",targetName:"quality",files:["package.json"],limitations:["Ensure ESLint is declared before enforcing this command in CI."]},security:{command:"bun audit",title:"Define Bun security audit script",targetName:"audit",files:["package.json","bun.lock","bun.lockb"]}},python:{test:{command:"python -m pytest",title:"Define Python test command",targetName:"test",files:["Makefile","pyproject.toml"]},quality:{command:"python -m ruff check .",title:"Define Python quality command",targetName:"quality",files:["Makefile","pyproject.toml"],limitations:["Ensure ruff is declared in project dev dependencies before enforcing in CI."]},security:{command:"python -m pip_audit",title:"Define Python security audit command",targetName:"security",files:["Makefile","pyproject.toml"],limitations:["Ensure pip-audit is available in the project toolchain before enforcing in CI."]}},go:{test:{command:"go test ./...",title:"Define Go test command",targetName:"test",files:["Makefile","go.mod"]},quality:{command:"gofmt -w .",title:"Define Go formatting command",targetName:"quality",files:["Makefile","go.mod"],limitations:["Use CI-specific check mode if formatting should not mutate files in pipelines."]},security:{command:"govulncheck ./...",title:"Define Go vulnerability scan command",targetName:"security",files:["Makefile","go.mod"],limitations:["Ensure govulncheck is installed or provisioned by CI before enforcing."]}},rust:{test:{command:"cargo test",title:"Define Rust test command",targetName:"test",files:["Makefile","Cargo.toml"]},quality:{command:"cargo fmt -- --check && cargo clippy --all-targets -- -D warnings",title:"Define Rust quality command",targetName:"quality",files:["Makefile","Cargo.toml"]},security:{command:"cargo audit",title:"Define Rust security audit command",targetName:"security",files:["Makefile","Cargo.toml"],limitations:["Ensure cargo-audit is installed or provisioned by CI before enforcing."]}},php:{test:{command:"vendor/bin/phpunit",title:"Define PHP test command",targetName:"test",files:["Makefile","composer.json"]},quality:{command:"vendor/bin/phpstan analyse",title:"Define PHP static analysis command",targetName:"quality",files:["Makefile","composer.json"],limitations:["Ensure phpstan is declared in require-dev before enforcing in CI."]},security:{command:"composer audit",title:"Define Composer security audit command",targetName:"security",files:["Makefile","composer.json"]}},ruby:{test:{command:"bundle exec rspec",title:"Define Ruby test command",targetName:"test",files:["Makefile","Gemfile"],limitations:["Use bundle exec ruby -Itest when the project uses minitest instead of RSpec."]},quality:{command:"bundle exec rubocop",title:"Define Ruby quality command",targetName:"quality",files:["Makefile","Gemfile"]},security:{command:"bundle exec bundler-audit check",title:"Define Ruby security audit command",targetName:"security",files:["Makefile","Gemfile"],limitations:["Ensure bundler-audit is installed or provisioned by CI before enforcing."]}},dotnet:{test:{command:"dotnet test",title:"Define .NET test command",targetName:"test",files:["Makefile","*.sln","*.csproj"]},quality:{command:"dotnet format --verify-no-changes",title:"Define .NET formatting gate",targetName:"quality",files:["Makefile","*.sln","*.csproj"]},security:{command:"dotnet list package --vulnerable",title:"Define .NET package vulnerability check",targetName:"security",files:["Makefile","*.sln","*.csproj"]}},java:{test:{command:"mvn test",title:"Define Java test command",targetName:"test",files:["Makefile","pom.xml","build.gradle","build.gradle.kts"],limitations:["Use ./gradlew test when the project is Gradle-first."]},quality:{command:"mvn verify",title:"Define Java verification command",targetName:"quality",files:["Makefile","pom.xml","build.gradle","build.gradle.kts"],limitations:["Use ./gradlew check when the project is Gradle-first."]},security:{command:"mvn org.owasp:dependency-check-maven:check",title:"Define Java dependency vulnerability check",targetName:"security",files:["Makefile","pom.xml"],limitations:["Review OWASP dependency-check policy and cache behavior before enforcing in CI."]}},elixir:{test:{command:"mix test",title:"Define Elixir test command",targetName:"test",files:["Makefile","mix.exs"]},quality:{command:"mix format --check-formatted && mix credo --strict",title:"Define Elixir quality command",targetName:"quality",files:["Makefile","mix.exs",".formatter.exs","credo.exs"],limitations:["Ensure Credo is declared before enforcing the strict quality command."]},security:{command:"mix hex.audit",title:"Define Hex dependency audit command",targetName:"security",files:["Makefile","mix.exs","mix.lock"]}},clojure:{test:{command:"clojure -M:test",title:"Define Clojure test command",targetName:"test",files:["Makefile","deps.edn","project.clj"],limitations:["Align the alias with the test runner declared by the project."]},quality:{command:"clj-kondo --lint src test",title:"Define Clojure quality command",targetName:"quality",files:["Makefile","deps.edn","project.clj"],limitations:["Ensure clj-kondo is provisioned before enforcing this command in CI."]},security:{command:"clojure -Stree",title:"Define Clojure dependency inspection command",targetName:"security",files:["Makefile","deps.edn","project.clj"],limitations:["Pair dependency-tree inspection with the vulnerability scanner selected by the organization."]}},scala:{test:{command:"sbt test",title:"Define Scala test command",targetName:"test",files:["Makefile","build.sbt"]},quality:{command:"sbt scalafmtCheckAll scalafixAll",title:"Define Scala quality command",targetName:"quality",files:["Makefile","build.sbt",".scalafmt.conf"],limitations:["Declare Scalafmt and Scalafix plugins before enforcing this command."]},security:{command:"sbt dependencyTree",title:"Define Scala dependency inspection command",targetName:"security",files:["Makefile","build.sbt"],limitations:["Pair dependency inspection with the organization vulnerability scanner."]}},kotlin:{test:{command:"./gradlew test",title:"Define Kotlin test command",targetName:"test",files:["Makefile","build.gradle","build.gradle.kts"]},quality:{command:"./gradlew check",title:"Define Kotlin quality command",targetName:"quality",files:["Makefile","build.gradle","build.gradle.kts"]},security:{command:"./gradlew dependencies",title:"Define Kotlin dependency inspection command",targetName:"security",files:["Makefile","build.gradle","build.gradle.kts"],limitations:["Pair dependency inspection with the organization vulnerability scanner."]}},c:{test:{command:"ctest --test-dir build --output-on-failure",title:"Define C test command",targetName:"test",files:["Makefile","CMakeLists.txt"]},quality:{command:"clang-tidy src/**/*.c --",title:"Define C quality command",targetName:"quality",files:["Makefile","CMakeLists.txt",".clang-tidy"],limitations:["Align source globs and compile database with the project build."]},security:{command:"cmake --build build --target sbom",title:"Define C dependency evidence command",targetName:"security",files:["Makefile","CMakeLists.txt"],limitations:["Declare the SBOM target or replace it with the organization scanner."]}},cpp:{test:{command:"ctest --test-dir build --output-on-failure",title:"Define C++ test command",targetName:"test",files:["Makefile","CMakeLists.txt"]},quality:{command:"clang-tidy src/**/*.cpp --",title:"Define C++ quality command",targetName:"quality",files:["Makefile","CMakeLists.txt",".clang-tidy"],limitations:["Align source globs and compile database with the project build."]},security:{command:"cmake --build build --target sbom",title:"Define C++ dependency evidence command",targetName:"security",files:["Makefile","CMakeLists.txt"],limitations:["Declare the SBOM target or replace it with the organization scanner."]}}}[e.runtime]?.[e.kind]??null}async function bi(e){return h({issueId:e.issueId,title:e.contract.title,projectPath:e.projectPath,targetName:e.contract.targetName,command:e.contract.command,reason:e.reason,risk:"guarded",requiresReview:true,limitations:e.contract.limitations})}async function Ct(e){let t=vi({runtime:e.runtime,kind:e.kind,packageJsonData:e.packageJsonData});if(t)return (e.runtime==="node"||e.runtime==="bun")&&e.packageJsonData?g$1({issueId:e.issueId,title:t.title,projectPath:e.projectPath,scriptName:t.targetName,scriptValue:t.command,reason:e.reason,risk:"guarded",limitations:t.limitations}):bi({issueId:e.issueId,projectPath:e.projectPath,contract:t,reason:e.reason})}function Ce(e){return {id:`${e.issueId}.manual`,issueId:e.issueId,title:e.title,status:"manual",fixKind:"manual",risk:"guarded",canAutoFix:false,canEditFiles:false,requiresApproval:true,requiresReview:true,files:e.files.map(t=>d.join(e.projectPath,t)),refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function wi(e){return b$8({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${yi}
4
- `,reason:"Create a Docker build ignore baseline to keep secrets, dependencies, and reports out of container contexts."})}async function ji(e){if(!await u.pathExists(d.join(e,".gitignore")))return b$8({issueId:"surface-security-hygiene",title:"Create .gitignore secret baseline",projectPath:e,relativePath:".gitignore",content:`${xt.join(`
5
- `)}
6
- `,reason:"Create a minimal ignore baseline so local env files are not committed accidentally."});let t=await et(d.join(e,".gitignore")),i=xt.filter(n=>!t.split(/\r?\n/).includes(n));return c$4({issueId:"surface-security-hygiene",title:"Append .gitignore secret baseline",projectPath:e,relativePath:".gitignore",lines:i,reason:"Append missing env-file ignore rules so local secrets stay out of source control."})}async function xi(e){let t=gi[e.runtime]??[],i$1=fi[e.runtime]??[];if(t.length===0&&i$1.length===0)return null;let n=await je(e.projectPath,t),o=await je(e.projectPath,i$1),s=n&&!o?await ki({projectPath:e.projectPath,runtime:e.runtime,packageJsonData:e.packageJsonData}):null;return {id:"surface-dependency-contract",label:"Dependency contract",status:!n||o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:n?o?"Dependency manifest and deterministic lock/baseline markers detected.":`Dependency manifest detected, but no deterministic baseline found (${i$1.join(", ")}).`:"No dependency manifest markers detected for this runtime.",recommendation:n&&!o?"Generate and commit the runtime-native lockfile or package baseline before release.":void 0,repairCapability:n&&!o&&s?i({issueId:"surface-dependency-contract",title:s.title,projectPath:e.projectPath,command:s.command,files:s.files,fixKind:"dependency-sync",reason:"Generate the runtime-native dependency baseline so CI, Doctor, and Studio share deterministic dependency evidence.",limitations:s.limitations}):void 0}}async function Ci(e){let t=await u.pathExists(d.join(e.projectPath,".env.example")),i=await u.pathExists(d.join(e.projectPath,".env")),n=await u.pathExists(d.join(e.projectPath,"docs","env.md"))||await u.pathExists(d.join(e.projectPath,"ENVIRONMENT.md")),o=await u.pathExists(d.join(e.projectPath,"config")),s=t||n||o,a=e.projectKind==="frontend";return {id:"surface-env-contract",label:"Environment/config contract",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Environment/config contract marker detected.":a?"No frontend environment contract marker detected.":"No environment/config contract marker detected.",recommendation:s?void 0:"Add .env.example, config schema, or environment documentation for deterministic setup.",repairCapability:s?t&&!i?d$6({issueId:"surface-env-contract",title:"Create local .env from .env.example",projectPath:e.projectPath,sourceRelativePath:".env.example",targetRelativePath:".env",reason:"Seed the local environment file from the reviewed example without overwriting an existing .env."}):void 0:Ce({issueId:"surface-env-contract",title:"Define environment contract",projectPath:e.projectPath,files:[".env.example"],reason:"Environment contracts are product-specific; Doctor can identify the missing baseline, but values must be reviewed by the project owner."})}}async function Pi(e){let t=await u.pathExists(d.join(e.projectPath,"Dockerfile")),i=await u.pathExists(d.join(e.projectPath,".dockerignore")),n=await u.pathExists(d.join(e.projectPath,"docker-compose.yml"))||await u.pathExists(d.join(e.projectPath,"compose.yml"));return t?{id:"surface-dockerignore",label:"Container build context hygiene",status:i?"pass":"warn",severity:"warn",scope:"project-scoped",reason:i?"Dockerfile and .dockerignore detected.":"Dockerfile detected without .dockerignore.",recommendation:i?void 0:"Add .dockerignore to exclude dependencies, reports, git metadata, and local env files from image builds.",repairCapability:i?void 0:wi(e.projectPath)}:{id:"surface-container-contract",label:"Container contract",status:n?"pass":"warn",severity:"warn",scope:"project-scoped",reason:n?"Compose surface detected; project has a local container orchestration baseline.":"No Dockerfile or compose surface detected.",recommendation:e.projectKind==="backend"||e.projectKind==="fullstack"?"Add Dockerfile or compose baseline when this service is expected to run in containerized environments.":"Add a container baseline only when this project is shipped through containerized environments."}}async function Di(e){let t=["k8s","kubernetes","deploy","deployments","charts","helm","kustomization.yaml","kustomization.yml"];if(!await je(e.projectPath,t)){let r=["DEPLOYMENT.md","docs/deployment.md","docs/deploy.md","Procfile","fly.toml","render.yaml","railway.json","vercel.json","netlify.toml","serverless.yml","serverless.yaml","sst.config.ts","cdk.json","terraform","infra"],c=await je(e.projectPath,r);return {id:"surface-deploy-contract",label:"Deployment contract",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"A documented or provider-managed non-Kubernetes deployment surface was detected.":"No declared deployment surface or deployment-path documentation was detected.",recommendation:c?void 0:e.projectKind==="backend"||e.projectKind==="fullstack"?"Add deployment manifests or document the non-Kubernetes deployment path.":"Document the distribution or deployment path when this project is production-hosted."}}let n=await tt(e.projectPath,["k8s/deployment.yaml","k8s/deployment.yml","kubernetes/deployment.yaml","deploy/deployment.yaml","deployment.yaml","deployment.yml","values.yaml","charts/values.yaml"]),o=/readinessProbe|livenessProbe|startupProbe/.test(n),s=/resources:\s*[\s\S]*(limits:|requests:)/.test(n),a=o&&s;return {id:"surface-kubernetes-readiness",label:"Deployment readiness controls",status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?"Deployment surface includes probe and resource-control markers.":"Deployment surface detected, but readiness/liveness probes or resource controls are incomplete.",recommendation:a?void 0:"Add readiness/liveness/startup probes and resource requests/limits to production deployment manifests.",repairCapability:a?void 0:Ce({issueId:"surface-kubernetes-readiness",title:"Harden deployment readiness controls",projectPath:e.projectPath,files:["k8s/","helm/","deploy/"],reason:"Deployment manifests are environment-specific and should be reviewed before mutation."})}}async function Si(e){let t=await u.pathExists(d.join(e.projectPath,".gitignore")),n=(await et(d.join(e.projectPath,".gitignore"))).split(/\r?\n/),o=t&&xt.every(f=>n.includes(f)),s=Me(e.packageJsonData),a=!!(s.audit||s["security:audit"]||s["audit:security"]||s["npm:audit"]),r=e.dependencyAudit,c=Number(r?.blockingFindingCount??r?.findingCount??e.vulnerabilities??0),l=c>0,m=r?.status==="clean",h=r?.status==="tool-unavailable"||r?.status==="unsupported"||r?.status==="failed",v=xe(e.runtimeFamily),g=["package.json","package-lock.json",...await u.pathExists(d.join(e.projectPath,"npm-shrinkwrap.json"))?["npm-shrinkwrap.json"]:[]],k=r?.invocation,y=l&&(r?.tool==="npm audit"||!r&&v==="node")?{cwd:e.projectPath,executable:"npm",args:["audit","fix","--audit-level=moderate"]}:l&&r?.tool==="bun audit"?{cwd:e.projectPath,executable:"bun",args:["update"]}:l&&r?.tool==="deno audit"?{cwd:e.projectPath,executable:"deno",args:["audit","--fix"]}:void 0,w=l?[{id:"audit-live-state",kind:"diagnose",description:"Read the current advisory graph and classify direct, transitive, fixable, and breaking findings.",risk:"safe",invocation:k,continueWhen:"always"},...y?[{id:"apply-compatible-fixes",kind:"safe-fix",description:"Apply runtime-authored compatible dependency and lockfile updates without forcing breaking upgrades.",risk:"guarded",invocation:y,continueWhen:"previous-passed"}]:[],{id:"upgrade-owning-dependencies",kind:"targeted-upgrade",description:"Upgrade the smallest set of direct dependencies that own unresolved advisory paths, then run tests and build.",risk:"guarded",continueWhen:y?"blocker-remains":"always"},{id:"recheck-advisory-graph",kind:"verify",description:"Re-run the runtime-native audit and retain only unresolved advisory paths.",risk:"safe",invocation:k,continueWhen:"blocker-remains"},{id:"review-unfixable-advisories",kind:"exception-review",description:"For advisories without a compatible fix, require a time-bounded policy exception or an explicit replacement plan.",risk:"invasive",continueWhen:"manual-decision"}]:void 0,b=l&&y?i({issueId:"surface-security-hygiene",title:`Apply compatible ${r?.ecosystem??v} vulnerability fixes`,projectPath:e.projectPath,command:[y.executable,...y.args].join(" "),invocation:{executable:y.executable,args:y.args},strategy:w,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:r?.ecosystem??y.executable??v,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}},files:g,reason:"Apply runtime-authored compatible vulnerability remediations, then regenerate Doctor and release-readiness evidence.",risk:"guarded",requiresReview:true,limitations:["Never add --force automatically; unresolved advisories require an evidence-backed dependency upgrade plan.","Review lockfile changes and rerun the complete Workspace Intelligence verification loop."]}):void 0,E=o&&m,$=r?.reason;return {id:"surface-security-hygiene",label:"Security hygiene surface",status:E?"pass":l?"fail":"warn",severity:l?"error":"warn",scope:"project-scoped",reason:l?`${c} moderate/high/critical dependency vulnerability(ies) reported.`:h?`${$} Doctor did not treat unavailable audit evidence as a clean result.`:o&&m?"Repository ignore baseline covers env-file secrets and the runtime-native dependency audit is clean.":o?"Repository ignore baseline covers env-file secrets, but no current dependency audit evidence is available.":t?"Repository ignore baseline exists, but env-file secret rules are incomplete.":"No .gitignore baseline detected for local secrets/build artifacts.",recommendation:l?"Run the runtime-native audit fix path without force, review lockfile changes, then rerun Doctor.":h?"Install or declare the runtime-native audit tool, rerun Doctor, and keep the command available to CI and Studio.":o?a?void 0:"Consider adding a security audit script for CI parity.":"Add .gitignore entries for env files, build output, dependency directories, and local reports.",repairCapability:l?b??{...Ce({issueId:"surface-security-hygiene",title:`Resolve ${r?.ecosystem??v} dependency vulnerabilities`,projectPath:e.projectPath,files:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","Directory.Packages.props"],reason:"Dependency remediation can change direct and transitive graphs; use the audit evidence to upgrade the owning dependencies.",limitations:["Never force a breaking dependency upgrade automatically.","Review lock or baseline changes, run project tests/build, then rerun the complete Workspace Intelligence verification loop."]}),strategy:w,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:r?.ecosystem??y?.executable??v,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}}}:o?void 0:await ji(e.projectPath)}}async function Ei(e){let t=xe(e.runtimeFamily),i=e.hasTests===true,n=i?void 0:await Ct({issueId:"surface-test-contract",projectPath:e.projectPath,runtime:t,kind:"test",packageJsonData:e.packageJsonData,reason:"Create a deterministic runtime-native test command contract so Doctor, CI, and Studio can verify changes consistently."});return {id:"surface-test-contract",label:"Test contract",status:i?"pass":"warn",severity:"warn",scope:"project-scoped",reason:i?"Test surface detected through scripts, config, directories, or test files.":"No test surface detected by Doctor.",recommendation:i?void 0:"Add at least one deterministic test command or test baseline before release.",repairCapability:n??(i?void 0:Ce({issueId:"surface-test-contract",title:"Define test contract",projectPath:e.projectPath,files:["package.json","pyproject.toml","go.mod","pom.xml"],reason:"Doctor can identify missing test surfaces, but the correct test runner depends on product intent."}))}}async function Ri(e){let t=d.join(e.projectPath,".workspai","reports","project-test-coverage-last-run.json"),i$1=await u.readJson(t).catch(()=>null);if(!(i$1?.schemaVersion==="workspai.project-test-coverage.v1"))return {id:"test-coverage-evidence",label:"Test coverage evidence",status:"warn",severity:"warn",scope:"project-scoped",reason:"No normalized project coverage evidence has been generated yet.",recommendation:"Run project coverage once to establish a measurable baseline before selecting a coverage goal.",repairCapability:i({issueId:"test-coverage-evidence",title:"Generate project coverage baseline",projectPath:e.projectPath,command:"npx workspai project coverage --run --json",invocation:{executable:"npx",args:["workspai","project","coverage","--run","--json"]},files:[".workspai/reports/project-test-coverage-last-run.json"],reason:"Run the runtime-native test coverage adapter and publish normalized evidence for Doctor, CI, Studio, and IDE consumers.",risk:"safe",requiresReview:false})};let o=i$1.target?.metric??"lines",s=$i(i$1.target?.percent),a=i$1.metrics?.[o]?.percent,r=typeof a=="number"?`${a}%`:"unavailable",c=i$1.status==="passed"?"pass":i$1.status==="below-target"||i$1.status==="failed"?"fail":"warn";return {id:"test-coverage-evidence",label:"Test coverage evidence",status:c,severity:c==="fail"?"error":"warn",scope:"project-scoped",reason:i$1.status==="passed"?`${o} coverage ${r} satisfies the ${s}% project target.`:i$1.status==="below-target"?`${o} coverage ${r} is below the ${s}% project target.`:i$1.status==="failed"?"The runtime-native coverage command failed; the target cannot be verified.":"Coverage evidence exists, but no supported metric could be normalized.",recommendation:i$1.status==="passed"?void 0:i$1.status==="below-target"?`Add targeted tests for the lowest-coverage source paths, then rerun project coverage with target ${s}%.`:"Repair the runtime-native coverage command or reporter and regenerate evidence.",repairCapability:i$1.status==="passed"?void 0:Ce({issueId:"test-coverage-evidence",title:"Reach the project coverage goal",projectPath:e.projectPath,files:[".workspai/reports/project-test-coverage-last-run.json",...(i$1.lowCoverageFiles??[]).map(l=>l.path).filter(l=>typeof l=="string").slice(0,20)],reason:"Test creation requires source-aware assertions. Studio should use the normalized low-coverage paths, edit tests, and rerun the same target until verified.",limitations:["Do not lower thresholds, exclude difficult source files, remove assertions, or skip failing tests to satisfy the goal."]})}}function $i(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Ai(e){let t=Me(e.packageJsonData),i=!!(t.format||t["format:check"]||t.prettier);return {id:"surface-format-contract",label:"Format contract",status:i?"pass":"warn",severity:"warn",scope:"project-scoped",reason:i?"Format script detected in package.json.":"No explicit format script detected by Doctor.",recommendation:i?void 0:"Add a formatter command or document the formatting tool used by CI."}}async function Fi(e){let t=xe(e.runtimeFamily),n={node:["test","tests","__tests__","vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","jest.config.ts","jest.config.js","jest.config.cjs","jest.config.mjs","playwright.config.ts","playwright.config.js","cypress.config.ts","cypress.config.js","*.spec.ts","*.spec.js","*.test.ts","*.test.js"],deno:["deno.json","deno.jsonc"],bun:["bunfig.toml","test","tests","*.test.ts","*.spec.ts"],python:["pytest.ini","tox.ini","noxfile.py","tests","test","conftest.py","*_test.py"],go:["*_test.go"],java:["src/test","*Test.java","*Tests.java","*IT.java"],rust:["tests","*_test.rs"],elixir:["test","*_test.exs"],clojure:["test","*_test.clj","*_test.cljc"],php:["phpunit.xml","phpunit.xml.dist","tests"],ruby:["spec","test",".rspec"],dotnet:["*.Tests.csproj","*.Test.csproj","*Tests.cs"],scala:["src/test","*Spec.scala","*Suite.scala"],kotlin:["src/test","*Test.kt","*Tests.kt"],c:["test","tests","*_test.c","test_*.c"],cpp:["test","tests","*_test.cpp","test_*.cpp","*Test.cpp"],unknown:[]}[t]??[];if(n.length===0)return null;let o=await je(e.projectPath,n),s=Me(e.packageJsonData),a=Object.values(s).join(`
7
- `),r=await tt(e.projectPath,["pyproject.toml","Cargo.toml","mix.exs","deps.edn","project.clj","composer.json","Gemfile","pom.xml","build.gradle","build.gradle.kts","deno.json","deno.jsonc"]),l={node:/\b(jest|vitest|mocha|ava|tap|playwright|cypress|node\s+--test|bun\s+test)\b/i,bun:/\bbun\s+test\b/i,deno:/\bdeno\s+test\b/i,python:/\b(pytest|unittest|tox|nox)\b/i,java:/\b(junit|testng|surefire|failsafe|gradle[^]*\btest\b)\b/i,rust:/\b(cargo\s+test|dev-dependencies)\b/i,elixir:/\b(ex_unit|mix\s+test)\b/i,clojure:/\b(clojure\.test|kaocha|eftest)\b/i,php:/\b(phpunit|pestphp|pest)\b/i,ruby:/\b(rspec|minitest)\b/i,dotnet:/\b(Microsoft\.NET\.Test\.Sdk|xunit|nunit|mstest)\b/i,scala:/\b(scalatest|munit|specs2|sbt\s+test)\b/i,kotlin:/\b(kotest|junit|gradle[^]*\btest\b)\b/i,c:/\b(ctest|cmocka|criterion|unity)\b/i,cpp:/\b(ctest|catch2|gtest|googletest|doctest)\b/i}[t]?.test(`${a}
8
- ${r}`)??false,m=e.hasTests===true&&(o||l);return {id:"runtime-test-depth",label:"Runtime-native test depth",status:m?"pass":("warn"),severity:"warn",scope:"project-scoped",reason:m?"Runtime-native test markers detected.":e.hasTests?"Generic test surface detected, but runtime-native test markers are incomplete.":"No runtime-native test markers detected.",recommendation:m?void 0:"Add runtime-native tests/config so Doctor, CI, and Studio can verify changes deterministically."}}async function Ii(e){let t=xe(e.runtimeFamily),n={node:["eslint.config.js","eslint.config.cjs","eslint.config.mjs","eslint.config.ts","eslint.config.mts",".eslintrc",".eslintrc.js",".eslintrc.cjs",".eslintrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs",".prettierrc",".prettierrc.json","biome.json","biome.jsonc"],deno:["deno.json","deno.jsonc"],bun:["eslint.config.js","biome.json","bunfig.toml"],python:["ruff.toml","pyproject.toml",".flake8","mypy.ini","Makefile"],go:[".golangci.yml",".golangci.yaml","Makefile"],java:["checkstyle.xml","pom.xml","build.gradle","build.gradle.kts"],rust:["rustfmt.toml","clippy.toml","Cargo.toml"],elixir:[".formatter.exs","credo.exs","mix.exs"],clojure:["cljfmt.edn",".clj-kondo","deps.edn"],php:["phpcs.xml","phpstan.neon","pint.json","composer.json"],ruby:[".rubocop.yml","Gemfile"],dotnet:[".editorconfig","Directory.Build.props","global.json"],scala:[".scalafmt.conf",".scalafix.conf","build.sbt"],kotlin:[".editorconfig","detekt.yml","build.gradle","build.gradle.kts"],c:[".clang-format",".clang-tidy","CMakeLists.txt"],cpp:[".clang-format",".clang-tidy","CMakeLists.txt"],unknown:[]}[t]??[];if(n.length===0)return null;let o=await tt(e.projectPath,[...n,"package.json","pyproject.toml","Makefile","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","mix.exs","deps.edn","project.clj","composer.json","Gemfile","Directory.Build.props"]),s=Me(e.packageJsonData),a=Object.entries(s).filter(([m])=>/lint|format|quality|check|typecheck|static/i.test(m)).map(([,m])=>m).join(`
9
- `),r=await je(e.projectPath,n),c=/eslint|prettier|biome|ruff|black|mypy|golangci|checkstyle|spotless|pmd|clippy|rustfmt|credo|clj-kondo|phpstan|phpcs|pint|rubocop|editorconfig|dotnet format|scalafmt|scalafix|detekt|ktlint|clang-tidy|clang-format/i.test(`${o}
10
- ${a}`)||r,l=c?void 0:await Ct({issueId:"runtime-quality-tooling",projectPath:e.projectPath,runtime:t,kind:"quality",packageJsonData:e.packageJsonData,reason:"Create a deterministic runtime-native quality command contract so CI and Studio can verify formatting/static-analysis consistently."});return {id:"runtime-quality-tooling",label:"Runtime-native quality tooling",status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?"Runtime-native lint/format/static-analysis markers detected.":"No runtime-native lint/format/static-analysis markers detected.",recommendation:c?void 0:"Add runtime-native lint/format/static-analysis tooling and expose it to CI.",repairCapability:l}}async function Ni(e){let t=xe(e.runtimeFamily),n={node:["package.json"],deno:["deno.json","deno.jsonc"],bun:["package.json","bunfig.toml"],python:["pyproject.toml","requirements.txt","Makefile"],go:["Makefile","go.mod"],java:["pom.xml","build.gradle","build.gradle.kts"],rust:["Cargo.toml"],elixir:["mix.exs"],clojure:["deps.edn","project.clj"],php:["composer.json"],ruby:["Gemfile",".bundler-audit.yml"],dotnet:["Directory.Build.props","*.csproj"],scala:["build.sbt","project/plugins.sbt"],kotlin:["build.gradle","build.gradle.kts","pom.xml"],c:["CMakeLists.txt","conanfile.py","conanfile.txt","vcpkg.json"],cpp:["CMakeLists.txt","conanfile.py","conanfile.txt","vcpkg.json"],unknown:[]}[t]??[];if(n.length===0)return null;let o=await tt(e.projectPath,n),s=/npm audit|pnpm audit|yarn audit|bun audit|pip[-_]audit|safety|bandit|govulncheck|gosec|dependency-check|owasp|cargo audit|mix hex.audit|composer audit|bundler-audit|brakeman|NuGetAudit|dotnet list package --vulnerable|dependencyCheck|dependency-check|snyk|trivy|osv-scanner|cyclonedx|sbom/i.test(o),a=s?void 0:await Ct({issueId:"runtime-security-tooling",projectPath:e.projectPath,runtime:t,kind:"security",packageJsonData:e.packageJsonData,reason:"Create a deterministic runtime-native security audit command contract so CI and Studio can verify dependency risk consistently."});return {id:"runtime-security-tooling",label:"Runtime-native security tooling",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Runtime-native security audit tooling marker detected.":"No runtime-native security audit tooling marker detected.",recommendation:s?void 0:"Expose a runtime-native dependency/security audit command for CI and Studio verification.",repairCapability:s?void 0:a||Ce({issueId:"runtime-security-tooling",title:"Define runtime security audit command",projectPath:e.projectPath,files:["package.json","pyproject.toml","Makefile","pom.xml","Cargo.toml"],reason:"Security tooling differs by runtime and organization policy; Doctor records the missing contract for review."})}}async function jn(e){let t=xe(e.runtimeFamily),i=[],n=await xi({projectPath:e.projectPath,runtime:t,packageJsonData:e.packageJsonData});n&&i.push(n),i.push(await Ci(e)),i.push(await Pi(e)),i.push(await Di(e)),i.push(await Si(e)),i.push(await Ei(e)),i.push(await Ri(e)),(t==="node"||t==="bun")&&i.push(Ai(e));let o=await Promise.all([Fi(e),Ii(e),Ni(e)]);for(let s of o)s&&i.push(s);return i}var ce={low:0,moderate:0,high:0,critical:0,unknown:0};function Oi(e){let t=String(e??"unknown").toLowerCase();return t==="medium"?"moderate":t==="low"||t==="moderate"||t==="high"||t==="critical"?t:"unknown"}function ae(e){let t=typeof e.name=="string"?e.name.trim():"";return t?{name:t,...typeof e.version=="string"&&e.version.trim()?{version:e.version.trim()}:{},...typeof e.direct=="boolean"?{direct:e.direct}:{},advisoryIds:[...new Set((e.advisoryIds??[]).map(i=>typeof i=="string"||typeof i=="number"?String(i).trim():"").filter(Boolean))].sort(),severities:[...new Set((e.severities??[]).map(i=>Oi(i)))].sort()}:null}function se(e){let t=new Map;for(let i of e){if(!i)continue;let n=i.name.toLowerCase(),o=t.get(n);if(!o){t.set(n,i);continue}t.set(n,{name:o.name,...o.version||i.version?{version:o.version??i.version}:{},...o.direct!==void 0||i.direct!==void 0?{direct:o.direct??i.direct}:{},advisoryIds:[...new Set([...o.advisoryIds,...i.advisoryIds])].sort(),severities:[...new Set([...o.severities,...i.severities])].sort()});}return [...t.values()].sort((i,n)=>i.name.localeCompare(n.name))}var Pt=new Map,Ti=["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock",".yarnrc.yml","bun.lock","bun.lockb","deno.lock","pyproject.toml","requirements.txt","uv.lock","poetry.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deps.edn","project.clj","Directory.Packages.props","packages.lock.json"];function _i(){let e=Number(process.env.RAPIDKIT_DOCTOR_AUDIT_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.trunc(e):15e3}async function Gi(e,t){let i=[];for(let n of Ti){let o=d.join(e,n);try{let s=await u.stat(o);i.push(`${n}:${s.size}:${s.mtimeMs}`);}catch{}}return `${d.resolve(e)}\0${t}\0${i.join("|")}`}function he(e){let t=e.trim();if(!t)return null;try{let i=JSON.parse(t);return i&&typeof i=="object"&&!Array.isArray(i)?i:null}catch{return null}}function Oe(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function xn(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {low:Oe(t.low),moderate:Oe(t.moderate??t.medium),high:Oe(t.high),critical:Oe(t.critical),unknown:Oe(t.unknown)}}function _e(e){return e.low+e.moderate+e.high+e.critical+e.unknown}function Pe(e,t,i=1){let n=String(t??"unknown").toLowerCase();n==="low"?e.low+=i:n==="moderate"||n==="medium"?e.moderate+=i:n==="high"?e.high+=i:n==="critical"?e.critical+=i:e.unknown+=i;}function Ge(e,t){if(Array.isArray(e)){for(let n of e)Ge(n,t);return}if(!e||typeof e!="object")return;let i=e;t(i);for(let n of Object.values(i))Ge(n,t);}function Ki(e){let t=he(e);if(!t){let c={...ce},l=[],m=0,h=false;for(let v of e.split(/\r?\n/)){let C=he(v);if(!C)continue;let g=C.data&&typeof C.data=="object"?C.data:{};if(C.type==="auditAdvisory"){let k=g.advisory&&typeof g.advisory=="object"?g.advisory:{};m+=1,Pe(c,k.severity);let y=ae({name:k.module_name??k.name,advisoryIds:[k.id,k.github_advisory_id,k.url],severities:[k.severity]});y&&l.push(y);}if(C.type==="auditSummary"){h=true;let k=xn(g.vulnerabilities);if(_e(k)>=m)return {findingCount:_e(k),severityCounts:k,subjects:se(l)}}}return m>0||h?{findingCount:m,severityCounts:c,subjects:se(l)}:null}let i=t.metadata&&typeof t.metadata=="object"?t.metadata:null,n=xn(i?.vulnerabilities),o=t.vulnerabilities&&typeof t.vulnerabilities=="object"?Object.entries(t.vulnerabilities):[],s=se(o.map(([c,l])=>{let m=l&&typeof l=="object"?l:{},h=Array.isArray(m.via)?m.via:[];return ae({name:m.name??c,direct:m.isDirect,advisoryIds:h.flatMap(v=>{let C=v&&typeof v=="object"?v:{};return [C.source,C.url]}),severities:[m.severity]})}));if(_e(n)>0||i?.vulnerabilities)return {findingCount:_e(n),severityCounts:n,subjects:s};let a=t.advisories&&typeof t.advisories=="object"?Object.entries(t.advisories):[],r=[];for(let[c,l]of a){let m=l&&typeof l=="object"?l:{};Pe(n,m.severity);let h=ae({name:m.module_name??m.name,advisoryIds:[m.id,m.github_advisory_id,m.url,c],severities:[m.severity]});h&&r.push(h);}return {findingCount:a.length,severityCounts:n,subjects:se([...s,...r])}}function Bi(e){let t=(()=>{try{return JSON.parse(e.trim())}catch{return null}})(),i=Array.isArray(t)?t:t&&typeof t=="object"?t.dependencies:null;if(!Array.isArray(i))return null;let n={...ce},o=[],s=0;for(let a of i){let r=a&&typeof a=="object"?a:{},c=Array.isArray(r.vulns)?r.vulns:[];if(s+=c.length,n.unknown+=c.length,c.length>0){let l=ae({name:r.name,version:r.version,advisoryIds:c.flatMap(m=>{let h=m&&typeof m=="object"?m:{};return [h.id,h.aliases].flatMap(v=>Array.isArray(v)?v:[v])}),severities:c.map(()=>"unknown")});l&&o.push(l);}}return {findingCount:s,severityCounts:n,subjects:se(o)}}function Wi(e){if(!e.trim())return null;let t=new Set,i=new Map;for(let n of e.split(/\r?\n/)){let o=he(n),s=o?.osv&&typeof o.osv=="object"?o.osv:null;typeof s?.id=="string"&&t.add(s.id);let a=o?.finding&&typeof o.finding=="object"?o.finding:null;typeof a?.osv=="string"&&t.add(a.osv);let r=Array.isArray(a?.trace)?a.trace:[];for(let c of r){let l=c&&typeof c=="object"?c:{},m=typeof l.module=="string"?l.module:typeof l.package=="string"?l.package:"";if(!m)continue;let h=i.get(m)??{advisoryIds:new Set};typeof l.version=="string"&&(h.version=l.version),typeof a?.osv=="string"&&h.advisoryIds.add(a.osv),i.set(m,h);}}return {findingCount:t.size,severityCounts:{...ce,unknown:t.size},subjects:[...i.entries()].map(([n,o])=>ae({name:n,version:o.version,advisoryIds:[...o.advisoryIds],severities:["unknown"]})).filter(n=>!!n)}}function Hi(e){let t=he(e);if(!t)return null;let i=t.vulnerabilities&&typeof t.vulnerabilities=="object"?t.vulnerabilities:{},n=Array.isArray(i.list)?i.list:[],o={...ce},s=[];for(let a of n){let r=a&&typeof a=="object"?a:{},c=r.advisory&&typeof r.advisory=="object"?r.advisory:{};Pe(o,c.severity);let l=r.package&&typeof r.package=="object"?r.package:{},m=ae({name:l.name,version:l.version,advisoryIds:[c.id,c.url],severities:[c.severity]});m&&s.push(m);}return {findingCount:n.length,severityCounts:o,subjects:se(s)}}function qi(e){let t=he(e);if(!t)return null;let i=t.advisories&&typeof t.advisories=="object"?t.advisories:{},n={...ce},o=0,s=[];for(let[a,r]of Object.entries(i)){let c=Array.isArray(r)?r:[r],l=ae({name:a,advisoryIds:c.flatMap(m=>{let h=m&&typeof m=="object"?m:{};return [h.advisoryId,h.cve,h.link]}),severities:c.map(m=>(m&&typeof m=="object"?m:{}).severity)});l&&s.push(l);}return Ge(i,a=>{(typeof a.advisoryId=="string"||typeof a.cve=="string")&&(o+=1,Pe(n,a.severity));}),{findingCount:o,severityCounts:n,subjects:se(s)}}function Li(e){let t=he(e);if(!t)return null;let i={...ce},n=0,o=[];return Ge(t,s=>{if(!Array.isArray(s.vulnerabilities))return;for(let r of s.vulnerabilities){let c=r&&typeof r=="object"?r:{};n+=1,Pe(i,c.severity);}let a=ae({name:s.id??s.name??s.packageId,version:s.resolvedVersion??s.version,direct:s.isTransitive===false,advisoryIds:s.vulnerabilities.flatMap(r=>{let c=r&&typeof r=="object"?r:{};return [c.advisoryurl,c.advisoryUrl,c.url]}),severities:s.vulnerabilities.map(r=>(r&&typeof r=="object"?r:{}).severity)});a&&o.push(a);}),{findingCount:n,severityCounts:i,subjects:se(o)}}function Vi(e){let t=he(e);if(!t)return null;let i={...ce},n=new Set,o=[];return Ge(t,s=>{let a=s.id??s.cve??s.advisory??s.url;if(typeof a!="string")return;n.add(a),Pe(i,s.severity??s.criticality);let r=s.gem&&typeof s.gem=="object"?s.gem:{},c=ae({name:r.name??s.gemName??s.name,version:r.version??s.version,advisoryIds:[a],severities:[s.severity??s.criticality]});c&&o.push(c);}),{findingCount:n.size,severityCounts:n.size>0&&_e(i)===0?{...i,unknown:n.size}:i,subjects:se(o)}}function Cn(e,t){let i=`${e}
11
- ${t}`.trim();if(!i)return null;let n=i.match(/(?:found|total:?)\s+(\d+)\s+vulnerabilit/i),o=/no (?:known )?vulnerabilit|no retired packages found|no insecure dependencies found/i.test(i);if(!n&&!o)return null;let s=n?Number(n[1]):0;return {findingCount:s,severityCounts:{...ce,unknown:s},subjects:[]}}function Ji(e,t,i){return e==="node"||e==="bun"?Ki(t):e==="python"?Bi(t):e==="go"?Wi(t):e==="rust"?Hi(t):e==="php"?qi(t):e==="dotnet"?Li(t):e==="ruby"?Vi(t)??Cn(t,i):e==="deno"||e==="elixir"?Cn(t,i):null}async function Te(e,t){return u.pathExists(d.join(e,t))}async function zi(e,t){if(t==="bun")return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(t==="node"){if(await Te(e,"bun.lock")||await Te(e,"bun.lockb"))return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(await Te(e,"pnpm-lock.yaml"))return {ecosystem:"npm",tool:"pnpm audit",invocation:{cwd:e,executable:"pnpm",args:["audit","--json"]}};if(await Te(e,"yarn.lock")){let i=await Te(e,".yarnrc.yml");return {ecosystem:"npm",tool:"yarn audit",invocation:{cwd:e,executable:"yarn",args:i?["npm","audit","--json","--severity","moderate"]:["audit","--json","--level","moderate"]}}}return {ecosystem:"npm",tool:"npm audit",invocation:{cwd:e,executable:"npm",args:["audit","--json"]}}}if(t==="deno")return {ecosystem:"deno",tool:"deno audit",invocation:{cwd:e,executable:"deno",args:["audit"]}};if(t==="python"){let i=d.join(e,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");return {ecosystem:"PyPI",tool:"pip-audit",invocation:{cwd:e,executable:await u.pathExists(i)?i:process.platform==="win32"?"python":"python3",args:["-m","pip_audit","--format","json"]}}}return t==="go"?{ecosystem:"Go modules",tool:"govulncheck",invocation:{cwd:e,executable:"govulncheck",args:["-json","./..."]}}:t==="rust"?{ecosystem:"crates.io",tool:"cargo-audit",invocation:{cwd:e,executable:"cargo",args:["audit","--json"]}}:t==="php"?{ecosystem:"Packagist",tool:"Composer audit",invocation:{cwd:e,executable:"composer",args:["audit","--format=json"]}}:t==="ruby"?{ecosystem:"RubyGems",tool:"bundler-audit",invocation:{cwd:e,executable:"bundle-audit",args:["check","--format","json"]}}:t==="dotnet"?{ecosystem:"NuGet",tool:".NET package audit",invocation:{cwd:e,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"]}}:t==="elixir"?{ecosystem:"Hex",tool:"mix hex.audit",invocation:{cwd:e,executable:"mix",args:["hex.audit"]}}:t==="java"?{ecosystem:"Maven/Gradle",tool:"OWASP Dependency-Check",unsupportedReason:"No universal zero-configuration Java vulnerability scanner is safe to invoke. Declare OWASP Dependency-Check or an organization-approved equivalent in the build."}:t==="scala"||t==="kotlin"?{ecosystem:"Maven/JVM",tool:"organization-selected JVM dependency scanner",unsupportedReason:"No universal zero-configuration JVM vulnerability scanner is safe to invoke. Declare an organization-approved scanner in the project build."}:t==="c"||t==="cpp"?{ecosystem:t==="c"?"C/native":"C++/native",tool:"organization-selected native dependency scanner",unsupportedReason:"Native dependency provenance depends on the build and package manager. Declare an organization-approved SBOM or vulnerability scanner in the project command contract."}:t==="clojure"?{ecosystem:"Clojars/Maven",tool:"organization-selected Clojure audit",unsupportedReason:"No portable Clojure vulnerability command is declared. Configure an organization-approved scanner and expose it through the project command contract."}:{ecosystem:"unknown",tool:"none",unsupportedReason:"Doctor could not determine a supported dependency ecosystem."}}function Pn(e){let t=e&&typeof e=="object"?e:void 0,i=String(t?.code??""),n=String(t?.message??"");return i==="ENOENT"||/not found|is not recognized|no module named pip_audit/i.test(n)}async function Ui(e){let t=new Date().toISOString(),i=await zi(e.projectPath,e.runtime),n={schemaVersion:"doctor-dependency-audit-v1",runtime:e.runtime,ecosystem:i.ecosystem,tool:i.tool,generatedAt:t,findingCount:null,blockingFindingCount:null,severityCounts:{...ce},subjects:[],limitations:["A clean result covers known advisories available to the selected runtime-native audit tool at execution time.","Doctor never treats a missing scanner, malformed output, registry failure, or timeout as a clean audit."]};if(!i.invocation)return {...n,status:"unsupported",reason:i.unsupportedReason??"No supported audit invocation is available."};try{let o=await execa(i.invocation.executable,i.invocation.args,{cwd:i.invocation.cwd,timeout:_i(),reject:false}),s=Ji(e.runtime,o.stdout,o.stderr);if(!s){let r=/not found|no module named pip_audit|unknown command|unrecognized (?:command|option)/i.test(`${o.stdout}
12
- ${o.stderr}`);return {...n,invocation:i.invocation,exitCode:o.exitCode,status:r?"tool-unavailable":"failed",reason:r?`${i.tool} is not installed or not supported by the detected runtime version.`:`${i.tool} did not produce parseable vulnerability evidence.`}}let a=s.severityCounts.moderate+s.severityCounts.high+s.severityCounts.critical+s.severityCounts.unknown;return {...n,invocation:i.invocation,exitCode:o.exitCode,findingCount:s.findingCount,blockingFindingCount:a,severityCounts:s.severityCounts,subjects:s.subjects,status:s.findingCount>0?"vulnerable":"clean",reason:s.findingCount>0?`${i.tool} reported ${s.findingCount} known dependency vulnerability finding(s).`:`${i.tool} completed without known dependency vulnerability findings.`}}catch(o){return {...n,invocation:i.invocation,status:Pn(o)?"tool-unavailable":"failed",reason:Pn(o)?`${i.tool} is not installed or cannot be resolved from this project environment.`:`${i.tool} could not complete: ${o instanceof Error?o.message:String(o)}`}}}async function Dn(e){let t=await Gi(e.projectPath,e.runtime),i=Pt.get(t);if(i)return i;let n=Ui(e);Pt.set(t,n);try{return await n}catch(o){throw Pt.delete(t),o}}var Rn="Graph paths identify evidence-backed structural reachability and verification candidates; they do not prove runtime causality or that every affected surface has been discovered.",Sn={dependency:["package","module"],security:["package","module"],test:["test-suite"],quality:["file","symbol","module"],container:["container"],deployment:["deployment","container","environment"],environment:["environment"],configuration:["environment","file"],runtime:["service","container","deployment"],"workspace-contract":["project","service","api","endpoint"],"source-tree":["file","module","symbol"],framework:["service","project","package"],custom:["project"],unknown:["project"]},Yi=new Set(["project","service","api","endpoint","schema","database","queue","container","deployment","pipeline","environment","document","decision","test-suite","owner"]),Qi=new Set(["test-suite","pipeline"]);function Et(e,t){if(!e)return ".";let i=d.relative(e,t).split(d.sep).join("/");return i&&!i.startsWith("../")?i:"."}function St(e){return {id:e.id,kind:e.kind,label:e.label,...e.projectId?{projectId:e.projectId}:{}}}function De(e,t,i,n={artifact:b$4}){return {schemaVersion:d$2,generatedAt:(e.now??new Date).toISOString(),status:t,claimBoundary:Rn,graph:n,project:{name:e.projectName,path:Et(e.workspacePath,e.projectPath)},summary:{findingCount:0,rootEntityCount:0,affectedEntityCount:0,verificationTargetCount:0,proofPathCount:0,subjectCount:0,unresolvedSubjectCount:0,unknownCount:1},findings:[],diagnostics:[i]}}function Xi(e,t){let i=Et(t.workspacePath,t.projectPath).toLowerCase(),n=new Set([t.projectName,d.basename(t.projectPath),i].map(o=>o.trim().toLowerCase()).filter(Boolean));return e.entities.filter(o=>o.kind==="project").find(o=>[o.projectId,o.label,o.identity.key,...o.identity.aliases,typeof o.attributes.path=="string"?o.attributes.path:void 0].filter(a=>typeof a=="string").map(a=>a.toLowerCase()).some(a=>n.has(a)||n.has(d.basename(a))))}function Zi(e,t){let i=t.projectId??t.label,n=e.entities.filter(a=>a.id===t.id||a.projectId===i||a.projectId===t.projectId),o=new Set(n.map(a=>a.id)),s=new Set;for(let a of e.relations)o.has(a.from)&&s.add(a.to),o.has(a.to)&&s.add(a.from);return e.entities.filter(a=>o.has(a.id)||s.has(a.id))}function eo(e){let t=new Map,i=(n,o)=>{let s=t.get(n)??[];s.push(o),t.set(n,s);};for(let n of e.relations)i(n.from,n.to),i(n.to,n.from);for(let n of t.values())n.sort();return t}function to(e,t,i){let n=eo(e),o=new Set(t),s=t.map(a=>({id:a,depth:0}));for(let a=0;a<s.length;a+=1){let r=s[a];if(!(!r||r.depth>=i))for(let c of n.get(r.id)??[])o.has(c)||(o.add(c),s.push({id:c,depth:r.depth+1}));}return [...o]}function En(e){let t=["name","specifier","package","module"].flatMap(i=>{let n=e.attributes[i];return Array.isArray(n)?n:[n]});return new Set([e.label,...e.identity.aliases,...t].filter(i=>typeof i=="string").map(i=>i.trim().toLowerCase()).filter(Boolean))}function no(e,t,i,n){let o=Zi(e,t),s=Sn[i]??Sn.unknown,a=[...new Set(n.map(c=>c.trim().toLowerCase()).filter(Boolean))];if(a.length>0){let c=o.filter(m=>s?.includes(m.kind)&&a.some(h=>En(m).has(h))),l=new Set(a.filter(m=>c.some(h=>En(h).has(m))));return {roots:c.length>0?c.slice(0,12):[t],unresolvedSubjects:n.filter(m=>!l.has(m.trim().toLowerCase()))}}let r=o.filter(c=>s?.includes(c.kind)).slice(0,6);return {roots:r.length>0?r:[t],unresolvedSubjects:[]}}function io(e,t,i){let n=i.issueClass??"unknown",o=[...new Set((i.subjects??[]).map(y=>y.trim()).filter(Boolean))],{roots:s,unresolvedSubjects:a}=no(e,t,n,o),r=new Map(e.entities.map(y=>[y.id,y])),c=to(e,s.map(y=>y.id),3).map(y=>r.get(y)).filter(y=>!!y),l=c.filter(y=>!s.some(w=>w.id===y.id)&&Yi.has(y.kind)).slice(0,20),m=c.filter(y=>Qi.has(y.kind)).slice(0,8),v=[...l,...m].filter((y,w,b)=>b.findIndex(E=>E.id===y.id)===w).slice(0,12).flatMap(y=>{let b=s.map(E=>d$5(e,E.id,y.id)).filter(E=>E.found).sort((E,$)=>E.hops.length-$.hops.length)[0];return b?[{from:b.resolvedFrom??b.from,to:b.resolvedTo??b.to,entityPath:b.entityPath,hops:b.hops,proofIds:b.proofs.map(E=>E.id)}]:[]}),C=new Set([...s.flatMap(y=>y.proofIds),...v.flatMap(y=>y.proofIds)]),g=e.proofs.filter(y=>C.has(y.id)).map(y=>y.artifact).filter((y,w,b)=>b.indexOf(y)===w).sort().slice(0,20),k=[];return l.length===0&&k.push("No affected surface is structurally reachable from the selected root evidence."),m.length===0&&k.push("No graph-connected test suite or pipeline is available as a verification target."),g.length===0&&k.push("The selected graph entities do not carry portable source evidence."),a.length>0&&k.push(`No canonical graph entity resolved for ${a.length} reported subject(s): ${a.join(", ")}.`),{issueId:i.id,issueClass:n,status:i.status==="fail"?"fail":"warn",reason:i.reason,scope:"structural-impact-candidates",subjects:o,unresolvedSubjects:a,rootEntities:s.map(St),affectedEntities:l.map(St),verificationTargets:m.map(St),proofPaths:v,sourceArtifacts:g,unknowns:k}}async function Rt(e){if(!e.workspacePath)return De(e,"graph-missing","Project is not attached to a Workspai workspace; no workspace graph can be consulted.");let t=d.join(e.workspacePath,b$4),i=d.join(e.workspacePath,a.model);if(!await u.pathExists(t))return De(e,"graph-missing","Workspace knowledge graph is missing. Run workspace model before relying on graph-aware diagnosis.");if(!await u.pathExists(i))return De(e,"model-missing","Canonical workspace model is missing, so graph source binding cannot be verified.");let n,o;try{let c=await u.readJSON(t),l=await u.readJSON(i);a$4(c,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Doctor graph diagnosis source"),a$4(l,"contracts/workspace-intelligence/workspace-model.v1.json","Doctor graph diagnosis model"),n=c,o=l;}catch(c){return De(e,"invalid",`Graph-aware diagnosis rejected invalid evidence: ${c instanceof Error?c.message:String(c)}`)}let s={artifact:b$4,schemaVersion:n.schemaVersion,sourceArtifact:n.source.artifact,sourceHash:n.source.hash,entityCount:n.entities.length,relationCount:n.relations.length,proofCount:n.proofs.length};try{c$2(n,o);}catch(c){return De(e,"stale",c instanceof Error?c.message:String(c),s)}let a$1=Xi(n,e);if(!a$1)return De(e,"project-unresolved","The current project could not be resolved to one canonical project entity.",s);let r=[...(e.probes??[]).filter(c=>c.status!=="pass"),...(e.issues??[]).map((c,l)=>({id:`legacy-project-issue-${l+1}`,status:"fail",reason:c,issueClass:"runtime"}))].map(c=>io(n,a$1,c));return {schemaVersion:d$2,generatedAt:(e.now??new Date).toISOString(),status:"available",claimBoundary:Rn,graph:s,project:{name:e.projectName,path:Et(e.workspacePath,e.projectPath),entityId:a$1.id},summary:{findingCount:r.length,rootEntityCount:new Set(r.flatMap(c=>c.rootEntities.map(l=>l.id))).size,affectedEntityCount:new Set(r.flatMap(c=>c.affectedEntities.map(l=>l.id))).size,verificationTargetCount:new Set(r.flatMap(c=>c.verificationTargets.map(l=>l.id))).size,proofPathCount:r.reduce((c,l)=>c+l.proofPaths.length,0),subjectCount:new Set(r.flatMap(c=>c.subjects)).size,unresolvedSubjectCount:new Set(r.flatMap(c=>c.unresolvedSubjects)).size,unknownCount:r.reduce((c,l)=>c+l.unknowns.length,0)},findings:r,diagnostics:[]}}var It=a.doctor;function Ln(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function $n(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function oo(){let e=t$1().map(n=>d.join(n,b$6()?"poetry.exe":"poetry")),t=b$6()?[d.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),d.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],i=b$6()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return Ln([...e,...t,...i])}function ro(e,t=process.cwd()){let i=t$1().map(l=>({location:"Global (user-local)",path:d.join(l,b$6()?"rapidkit.exe":"rapidkit")})),n$1=[{location:"Global (pipx)",path:d.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:d.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:d.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],o=n(d.join(t,".venv")),s=p$1(t),a=[{location:"Workspace (.venv)",path:o},...s.map(l=>({location:"Workspace (launcher)",path:l}))],r=[...i,...n$1,...a],c=new Set;return r.filter(l=>c.has(l.path)?false:(c.add(l.path),true))}function so(e){let t=new Map([["Workspace (.venv)",0],["Global (user-local)",1],["Global (pipx)",2],["Global (pyenv)",3],["Global (system)",4]]);return [...e].sort((i,n)=>{let o=t.get(i.location)??Number.MAX_SAFE_INTEGER,s=t.get(n.location)??Number.MAX_SAFE_INTEGER;return o!==s?o-s:i.path.localeCompare(n.path)})}function ao(e){let i=(e.probes??[]).filter(a=>a.status==="warn").length,n=e.issues.some(a=>a.toLowerCase().includes("environment file missing")),o=(e.probes??[]).some(a=>a.id==="surface-env-contract"),s=(e.probes??[]).some(a=>a.id==="surface-security-hygiene");return e.hasEnvFile===false&&!n&&!o&&(i+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&!s&&(i+=1),i}function co(e){let t=e.coreVersion?.split(".")[0],i=e.npmVersion?.split(".")[0];return !t||!i?false:t!==i}var lo="doctor-project-scan-v2",Vn="doctor-workspace-cache-v2",uo=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v2",generatedBy:"workspai",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"}),Ke=Object.freeze({local:{name:"local",exitOnErrors:true,exitOnWarnings:false,warningExitCode:0,advisoryWarningsBlockRelease:false,description:"Local diagnostics: report warnings without blocking the developer loop."},ci:{name:"ci",exitOnErrors:true,exitOnWarnings:true,warningExitCode:2,advisoryWarningsBlockRelease:false,description:"CI diagnostics: errors fail, warnings return a distinct warning exit code."},release:{name:"release",exitOnErrors:true,exitOnWarnings:true,warningExitCode:1,advisoryWarningsBlockRelease:true,description:"Release gate: any warning/error blocks release readiness."},"enterprise-strict":{name:"enterprise-strict",exitOnErrors:true,exitOnWarnings:true,warningExitCode:1,advisoryWarningsBlockRelease:true,description:"Enterprise strict gate: all warnings/errors block release and must carry evidence or repair guidance."}});function Re(){return {...uo}}function at(e){let t=e.profile?.trim();return t&&t in Ke?{...Ke[t]}:e.strict?{...Ke.release}:e.ci?{...Ke.ci}:{...Ke.local}}function st(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function po(e){return e.id==="surface-security-hygiene"&&/vulnerabilit/i.test(`${e.reason} ${e.recommendation??""}`)?{category:"state",ttlSeconds:300,reason:"Dependency vulnerability evidence is live state and must be refreshed before release use."}:e.id.includes("script")||e.id.includes("test")||e.id.includes("quality")||e.id.includes("format")||e.id.includes("runtime")||e.id.includes("lockfile")?{category:"verification",ttlSeconds:1440*60,reason:"Verification/tooling evidence can drift with dependency and config changes; refresh daily or before release."}:e.id.includes("dependency")||e.id.includes("env")||e.id.includes("container")||e.id.includes("docker")||e.id.includes("deploy")||e.id.includes("kubernetes")||e.id.includes("source-tree")||e.id.includes("framework")||e.id.includes("typescript")?{category:"structure",ttlSeconds:10080*60,reason:"Structural workspace/project evidence is durable but should be refreshed when files or manifests change."}:{category:"verification",ttlSeconds:1440*60,reason:"Default Doctor evidence freshness contract for project-scoped verification."}}function mo(e,t){let i=po(e),n=Date.parse(t),o=typeof i.ttlSeconds=="number"?i.ttlSeconds*1e3:null,s=o!==null&&Number.isFinite(n)?new Date(n+o).toISOString():void 0,a=!Number.isFinite(n)||o!==null&&!s?"unknown":o!==null&&Date.now()>n+o?"stale":"fresh";return {category:i.category,generatedAt:t,ttlSeconds:i.ttlSeconds,...s?{expiresAt:s}:{},status:a,verifyBeforeUse:i.category!=="structure"||a!=="fresh",reason:i.reason}}function fo(e){let t=e.id.toLowerCase(),i=`${e.label} ${e.reason} ${e.recommendation??""}`.toLowerCase();return t.includes("dependency")||t.includes("lockfile")||i.includes("lockfile")?"dependency":t.includes("security")||i.includes("vulnerabilit")||i.includes("audit")?"security":t.includes("env")||i.includes(".env")||i.includes("environment")?"environment":t.includes("test")?"test":t.includes("quality")||t.includes("format")||t.includes("lint")?"quality":t.includes("docker")||t.includes("container")?"container":t.includes("deploy")||t.includes("kubernetes")?"deployment":t.includes("runtime")?"runtime":t.includes("contract")?"workspace-contract":t.includes("source-tree")?"source-tree":t.includes("framework")||t.includes("typescript")?"framework":t.includes("custom")?"custom":t.includes("script")||t.includes("config")?"configuration":"unknown"}function Jn(e){let t=e.dependencyAudit?.subjects.map(i=>i.name)??[];return (e.probes??[]).map(i=>({...i,...i.id==="surface-security-hygiene"&&t.length>0?{subjects:t}:{}}))}function go(e,t){return e.status==="pass"?"none":t==="security"?"security-risk":t==="deployment"||t==="runtime"?"runtime-risk":t==="dependency"||t==="test"||t==="quality"||t==="workspace-contract"?e.severity==="error"||e.status==="fail"?"release-risk":"ci-risk":t==="container"||t==="environment"?"release-risk":"developer-friction"}function yo(e){let{probe:t,freshness:i}=e,n=t.repairCapability;if(t.status==="pass")return {mode:"none",confidence:"high",primaryActionLabel:"No action required",requiresApproval:false,requiresFreshEvidence:false,reason:"Probe is passing.",relatedCommands:[]};if(i.status!=="fresh")return {mode:"refresh-evidence",confidence:"high",primaryActionLabel:"Refresh evidence",requiresApproval:false,requiresFreshEvidence:true,reason:`Evidence is ${i.status}; refresh Doctor before applying repairs.`,relatedCommands:["npx workspai doctor project --json"]};if(i.verifyBeforeUse&&i.category==="state")return {mode:"verify-before-fix",confidence:"high",primaryActionLabel:"Verify live state",requiresApproval:false,requiresFreshEvidence:true,reason:"Live state evidence must be re-read before Studio claims a fix path.",relatedCommands:["npx workspai doctor project --json"]};if(n?.status==="available"&&n.canAutoFix){let o=n.canEditFiles;return {mode:o?"edit-file":"run-command",confidence:"high",primaryActionLabel:o?"Apply file fix":"Run fix command",requiresApproval:n.requiresApproval,requiresFreshEvidence:i.verifyBeforeUse,reason:n.reason,relatedCommands:$n([...n.command?[n.command]:[],...n.verifyCommand?[n.verifyCommand]:[],...n.refreshCommands])}}return n?.status==="manual"||n?.requiresReview?{mode:"review-required",confidence:"medium",primaryActionLabel:"Review fix path",requiresApproval:true,requiresFreshEvidence:i.verifyBeforeUse,reason:n?.reason??t.recommendation??t.reason,relatedCommands:$n(n?.refreshCommands??["npx workspai doctor project --json"])}:t.recommendation?{mode:"manual-guidance",confidence:"medium",primaryActionLabel:"Inspect guidance",requiresApproval:false,requiresFreshEvidence:i.verifyBeforeUse,reason:t.recommendation,relatedCommands:["npx workspai doctor project --json"]}:{mode:"manual-guidance",confidence:"low",primaryActionLabel:"Inspect issue",requiresApproval:false,requiresFreshEvidence:i.verifyBeforeUse,reason:"Doctor classified the issue but does not have a deterministic repair path yet.",relatedCommands:["npx workspai doctor project --json"]}}function zn(e,t){let i=mo(e,e.freshness?.generatedAt??t),n=e.issueClass??fo(e),o=e.operationalImpact??go(e,n),s=e.repairIntent??yo({probe:e,freshness:i});return {...e,freshness:i,issueClass:n,operationalImpact:o,repairIntent:s}}function An(e,t){Array.isArray(e.probes)&&(e.probes=e.probes.map(i=>zn(i,t)));}function Un(e,t){let i=e.flatMap(c=>Array.isArray(c.probes)?c.probes.map(l=>l.freshness).filter(l=>!!l):[]),n=i.filter(c=>c.status==="stale").length,o=i.filter(c=>c.status==="unknown").length,s=i.filter(c=>c.category==="state").length,a=i.filter(c=>c.verifyBeforeUse).length,r=i.map(c=>c.generatedAt).filter(Boolean).sort()[0];return {generatedAt:t,status:n>0?"stale":o>0?"unknown":"fresh",staleProbeCount:n,unknownProbeCount:o,liveStateProbeCount:s,verifyBeforeUseProbeCount:a,...r?{oldestProbeGeneratedAt:r}:{}}}function Yn(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Qn(e,t){try{if(!await u.pathExists(e))return null;let i=await u.readJSON(e);return c$3(i,t)?i:null}catch{return null}}function Xn(e,t){if(!e?.system)return [];let i=[{id:"python",current:t.python},{id:"poetry",current:t.poetry},{id:"pipx",current:t.pipx},{id:"go",current:t.go},{id:"rapidkitCore",current:t.rapidkitCore}],n=[];for(let o of i){let s=e.system?.[o.id]?.status;!s||s===o.current.status||n.push({id:o.id,from:s,to:o.current.status});}return n}function ho(e,t){let i=new Map;for(let v of t.projects)i.set(v.path||v.name,v.issues.length);if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let n=Array.isArray(e.projects)?e.projects:[],o=new Map;for(let v of n){let C=v.path||v.name;C&&o.set(C,Yn(v.issues));}let s=0,a=0,r=new Set,c=new Set,l=new Set([...Array.from(o.keys()),...Array.from(i.keys())]);for(let v of l){let C=o.get(v)??0,g=i.get(v)??0;g>C?(s+=g-C,r.add(v)):g<C&&(a+=C-g,c.add(v));}let m=st(e.healthScore),h=st(t.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:s,resolvedIssueCount:a,netIssueDelta:s-a,scoreDeltaPercent:m===null||h===null?null:h-m,systemStatusChanges:Xn(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore}),regressedProjects:Array.from(r).sort(),improvedProjects:Array.from(c).sort()}}function ko(e,t){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=Yn(e.project?.issues),n=t.project.issues.length,o=Math.max(n-i,0),s=Math.max(i-n,0),a=st(e.healthScore),r=st(t.healthScore),c=t.project.path||t.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:s,netIssueDelta:o-s,scoreDeltaPercent:a===null||r===null?null:r-a,systemStatusChanges:Xn(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore}),regressedProjects:o>0?[c]:[],improvedProjects:s>0?[c]:[]}}function Zn(e){let t=e??[],i=0,n=0;for(let a of t){if(a.scope==="project-scoped"){i+=1;continue}(a.scope==="workspace-aggregate"||a.scope==="host-system")&&(n+=1);}let o=i>0&&n>0?1:0,s=o>0?"mixed":i>0?"scoped":n>0?"aggregated":"unknown";return {scopedCount:i,aggregatedCount:n,mixedCount:o,dominantScope:s}}function H(e,t){return b$6()?`Set-Location -LiteralPath "${e.replace(/"/g,'`"')}"; ${t}`:`cd '${e.replace(/'/g,`'"'"'`)}' && ${t}`}function le(e){return b$6()?H(e,"Copy-Item .env.example .env"):H(e,"cp .env.example .env")}function Fn(e){return H(e,"poetry install --no-root")}function vo(e){return e==="FastAPI"||e==="NestJS"?"first-class":e==="Django"||e==="Flask"||e==="Express"||e==="Fastify"||e==="Koa"||e==="Go/Fiber"||e==="Go/Gin"||e==="Spring Boot"||e==="Rust"||e==="Phoenix"||e==="Elixir"||e==="Clojure"||e==="Scala"||e==="Kotlin"||e==="C"||e==="C++"||e==="Deno"||e==="Bun"||e==="PHP"||e==="Laravel"||e==="Ruby"||e==="Ruby on Rails"||e==="ASP.NET"?"extended":"observed"}function bo(e){return e==="Tauri"||e==="Electron"?"desktop":e==="VS Code Extension"?"extension":e==="Next.js"||e==="Remix"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Svelte"||e==="Vite"||e==="Astro"||e==="Solid"?"frontend":e==="Unknown"||e==="Node.js"||e==="Python"||e==="Go"||e==="Java"||e==="Scala"||e==="Kotlin"||e==="C"||e==="C++"?"generic":"backend"}function wo(e){return e==="NestJS"||e==="Next.js"||e==="Remix"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Svelte"||e==="Vite"||e==="Astro"||e==="Solid"||e==="Express"||e==="Fastify"||e==="Koa"||e==="Tauri"||e==="Electron"||e==="VS Code Extension"||e==="Node.js"?"node":e==="Bun"?"bun":e==="FastAPI"||e==="Django"||e==="Flask"||e==="Python"?"python":e==="Go/Fiber"||e==="Go/Gin"||e==="Go"||e==="Echo"?"go":e==="Spring Boot"||e==="Java"?"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":e==="Scala"?"scala":e==="Kotlin"?"kotlin":e==="C"?"c":e==="C++"?"cpp":"unknown"}function Nt(e,t){let i=w(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function ot(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=vo(t),e.projectKind=bo(t),e.runtimeFamily=wo(t);}function ei(e){return e==="python"?"python":e==="node"?"node":e==="bun"?"bun":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":e==="scala"?"scala":e==="kotlin"?"kotlin":e==="c"?"c":e==="cpp"?"cpp":"unknown"}function Tt(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 "nextjs":return "Next.js";case "remix":return "Remix";case "nuxt":return "Nuxt";case "react":return "React";case "vite":return "Vite";case "vue":return "Vue";case "sveltekit":return "SvelteKit";case "svelte":return "Svelte";case "angular":return "Angular";case "astro":return "Astro";case "solid":return "Solid";case "express":return "Express";case "fastify":return "Fastify";case "koa":return "Koa";case "tauri":return "Tauri";case "electron":return "Electron";case "vscode-extension":return "VS Code Extension";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":return e.key==="sinatra"?"Ruby":"PHP";case "c":return "C";case "cpp":return "C++";case "unknown":return "Unknown";default:return "Unknown"}}function jo(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 xo(e,t){e.framework=Tt(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=ei(t.runtime);}function Z(e,t){e.framework=Tt(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind=t.key==="tauri"||t.key==="electron"?"desktop":t.key==="vscode-extension"?"extension":jo(t)?"generic":"backend",e.runtimeFamily=ei(t.runtime);}function Co(e){let t=e.dependencies,i=e.scripts??{},n=(e.kitName??"").toLowerCase(),o=a=>!!t[a],s=Object.values(i).filter(a=>typeof a=="string").join(" ").toLowerCase();return o("next")||s.includes("next ")?{framework:"Next.js",confidence:"high"}:o("nuxt")||s.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:o("@nestjs/core")||n.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:o("express")?{framework:"Express",confidence:"high"}:o("fastify")?{framework:"Fastify",confidence:"high"}:o("koa")?{framework:"Koa",confidence:"high"}:o("@angular/core")?{framework:"Angular",confidence:"high"}:o("@sveltejs/kit")||s.includes("svelte-kit")?{framework:"SvelteKit",confidence:"high"}:o("vue")?{framework:"Vue",confidence:"medium"}:o("react")&&o("react-dom")?{framework:"React",confidence:"medium"}:{framework:"Node.js",confidence:"low"}}async function Po(e,t){let i=j$3(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:Tt(i),confidence:i.confidence}}async function In(e){try{let t=await u.stat(e);return `${d.basename(e)}:${t.isDirectory()?"d":"f"}:${t.size}:${t.mtimeMs}`}catch{return `${d.basename(e)}:missing`}}async function Do(e){try{let t=new Set([".git",".venv","node_modules",".workspai",".rapidkit","dist","build","coverage","__pycache__"]),i=new Set,n=async a=>{if(await We(a))return true;let r=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","*.csproj","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","deno.json","deno.jsonc"];for(let c of r){if(c==="*.csproj"){if((await u.readdir(a).catch(()=>[])).some(m=>m.endsWith(".csproj")))return true;continue}if(await u.pathExists(d.join(a,c)))return true}return false};await We(e)&&i.add(e);let o=await a$2(e);for(let a of o){let r=d.isAbsolute(a.path)?a.path:d.join(e,a.path);await n(r)&&i.add(r);}return (await a$3(e,{skipDirs:t,descendIntoMatchedProjects:false,isProjectDir:async(a,r)=>d.resolve(a)===d.resolve(r)?We(a):n(a)})).forEach(a=>i.add(a)),i.size===0&&(await Vo(e,3,t)).forEach(r=>i.add(r)),i.size===0&&!await b$2(e)&&await n(e)&&i.add(e),Array.from(i).sort((a,r)=>a.localeCompare(r))}catch{return []}}async function So(e,t){let i=[d.join(e,".workspai-workspace"),d.join(e,".workspai","workspace.json"),d.join(e,".workspai","imported-projects.json"),d.join(e,".workspai","policies.yml"),d.join(e,".workspai","toolchain.lock"),d.join(e,".workspai","cache-config.yml"),d.join(e,".rapidkit-workspace"),d.join(e,".rapidkit","workspace.json"),d.join(e,".rapidkit","imported-projects.json"),d.join(e,".rapidkit","policies.yml"),d.join(e,".rapidkit","toolchain.lock"),d.join(e,".rapidkit","cache-config.yml")],n=[".workspai/project.json",".workspai/context.json",".workspai/file-hashes.json",".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"],o=await Promise.all(i.map(In)),s=await Promise.all(t.map(async a=>{let r=await Promise.all(n.map(c=>In(d.join(a,c))));return `${a}::${r.join("|")}`}));return [lo,...o,...s].join("||")}async function Eo(e,t){try{if(!await u.pathExists(e))return null;let i=await u.readJSON(e);a$4(i,"contracts/doctor-workspace-cache.v2.json",`Doctor workspace cache ${e}`);let n=i;return !n||n.signature!==t||!Array.isArray(n.projects)||typeof n.schemaVersion=="string"&&n.schemaVersion!==Vn?null:n}catch{return null}}async function Ro(e,t){try{a$4(t,"contracts/doctor-workspace-cache.v2.json",`Doctor workspace cache ${e}`),await u.ensureDir(d.dirname(e)),await u.writeJSON(e,t,{spaces:2});}catch{}}async function $o(e$2,t,i){let n=d.join(e$2,It);try{let o=[];for(let l of t.projects){for(let m of l.issues??[])typeof m=="string"&&m.trim()&&o.push(`${l.name}: ${m.trim()}`);for(let m of l.probes??[])m.status==="fail"&&m.reason.trim()&&o.push(`${l.name}: ${m.reason.trim()}`);}for(let[l,m]of [["python",t.python],["rapidkitCore",t.rapidkitCore]])if(m?.status==="error"){let h=typeof m.message=="string"?m.message:`${l} check failed`;o.push(`${l}: ${h}`);}let s=t.projects.map(ee),a=s.reduce((l,m)=>l+m.blockingFindings,0),r=s.reduce((l,m)=>l+m.advisoryFindings,0),c=f$1({schemaVersion:a$5,evidenceType:"workspace",contract:Re(),policyProfile:t.policyProfile,workspacePath:e$2,workspaceName:t.workspaceName,projectScanCached:t.projectScanCached??false,projectScanSignature:t.projectScanSignature,cachePath:i,healthScore:t.healthScore,evidenceFreshness:t.evidenceFreshness,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,versions:{core:t.coreVersion,npm:t.npmVersion}},projects:t.projects,summary:{totalProjects:t.projects.length,totalIssues:t.projects.reduce((l,m)=>l+m.issues.length,0),verdict:t.healthScore?.verdict??"passed",blockingFindings:a,advisoryFindings:r,projectAdvisoryWarningProjects:s.filter(l=>l.advisoryFindings>0).length,projectAdvisoryWarnings:r,hasSystemErrors:[t.python,t.rapidkitCore].some(l=>l.status==="error"),scopeProvenance:t.scopeProvenance},driftDelta:t.driftDelta,scoreBreakdown:t.scoreBreakdown??[]},{commandId:"checkWorkspaceHealth",exitCode:qe(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:o.slice(0,12),runId:e$1()});return d$3(c),await e(e$2,It,c),n}catch(o){if(o instanceof Error&&o.message.includes("violates contracts/"))throw o;return}}async function _t(e=process.cwd()){let[t,i,n,o,s]=await Promise.all([Ao(),Fo(),Io(),No(),Mo(e)]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:s}}async function Ao(){let e=j$2(),t;for(let i of e)try{let n=i==="py"?["-3","--version"]:["--version"],{stdout:o,stderr:s}=await execa(i,n,{timeout:3e3,reject:false}),r=`${o??""}
13
- ${s??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(r){let c=r[1],[l,m]=c.split(".").map(Number);if(l<3||l===3&&m<10){t??={version:c,command:[i,...n.slice(0,-1)].join(" ")};continue}return {status:"ok",message:`Python ${c}`,details:`Using ${[i,...n.slice(0,-1)].join(" ")}`}}}catch{continue}return t?{status:"warn",message:`Python ${t.version} (requires 3.10+)`,details:`${t.command} found but version is below minimum requirement`}:{status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Fo(){try{let{stdout:e}=await execa("poetry",["--version"],{timeout:3e3}),t=e.match(/Poetry .*version ([\d.]+)/);return t?{status:"ok",message:`Poetry ${t[1]}`,details:"Available for dependency management"}:{status:"warn",message:"Poetry version unknown"}}catch{let e=j$2().map(t=>({cmd:t,args:t==="py"?["-3","-m","poetry","--version"]:["-m","poetry","--version"]}));for(let t of e)try{let{stdout:i}=await execa(t.cmd,t.args,{timeout:3e3,shell:c$1()}),n=i.match(/Poetry .*version ([\d.]+)/)||i.match(/([\d.]+)/);return {status:"ok",message:n?.[1]?`Poetry ${n[1]}`:"Poetry detected",details:`Available via ${t.cmd} ${t.args.join(" ")}`}}catch{continue}for(let t of oo())try{if(!await u.pathExists(t))continue;let{stdout:i}=await execa(t,["--version"],{timeout:3e3,shell:c$1()}),n=i.match(/Poetry .*version ([\d.]+)/)||i.match(/([\d.]+)/);return {status:"ok",message:n?.[1]?`Poetry ${n[1]}`:"Poetry detected",details:`Available at ${t}`}}catch{continue}return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function Io(){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=j$2();for(let t of e)try{let i=t==="py"?["-3","-m","pipx","--version"]:["-m","pipx","--version"],{stdout:n}=await execa(t,i,{timeout:3e3,shell:c$1()});return {status:"ok",message:`pipx ${n.trim()}`,details:`Available via ${t} ${i.join(" ")}`}}catch{continue}return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function No(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),t=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return t?{status:"ok",message:`Go ${t[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 Mo(e=process.cwd()){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],n=ro(t,e);for(let{location:s,path:a}of n)try{if(await u.pathExists(a)){let{stdout:r,exitCode:c}=await execa(a,["--version"],{timeout:3e3,reject:false});if(c===0&&(r.includes("RapidKit Version")||r.includes("RapidKit"))){let l=r.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);l&&i.push({location:s,path:a,version:l[1]});}}}catch{continue}if(i.length>0){let s=i.filter(r=>r.location!=="Workspace (launcher)");if(s.length>0){let r=so(s),c=r[0].version,l=r.some(v=>v.location==="Workspace (.venv)"),m=r.some(v=>v.location.startsWith("Global (")),h=!l&&m?"Workspace (.venv): not installed (optional). For RapidKit Core module-enabled projects, run npx workspai workspace run init inside this workspace to install the local Python engine.":void 0;return {status:"ok",message:`RapidKit Core ${c}`,details:h,paths:r.map(v=>({location:v.location,path:v.path,version:v.version}))}}return {status:"ok",message:`RapidKit Core ${i[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:s,exitCode:a}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(a===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let r=s.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(r)return {status:"ok",message:`RapidKit Core ${r[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:s,exitCode:a}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(a===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let r=s.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(r)return {status:"ok",message:`RapidKit Core ${r[1]}`,details:"Available via Poetry"}}}catch{}let o=j$2();for(let s of o)try{let a=s==="py"?["-3","-c","import rapidkit_core; print(rapidkit_core.__version__)"]:["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{stdout:r,exitCode:c}=await execa(s,a,{timeout:3e3,reject:false});if(c===0&&r&&!r.includes("Traceback")&&!r.includes("ModuleNotFoundError")){let l=r.trim();if(l)return {status:"ok",message:`RapidKit Core ${l}`,details:`Available in ${s} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function z(e,t,i){let n=d.join(e,"Dockerfile");t.hasDocker=await u.pathExists(n);let o=d.join(e,"tests"),s=d.join(e,"test"),a=d.join(e,"src","test"),r=await u.pathExists(o)||await u.pathExists(s)||await u.pathExists(a),c=false;if(t.framework==="Go/Fiber"||t.framework==="Go/Gin")try{let l=[{dir:e,depth:0}],m=4,h=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;l.length>0&&!c;){let v=l.shift();if(!v)break;let C=[];try{C=await u.readdir(v.dir);}catch{continue}for(let g of C){let k=d.join(v.dir,g),y;try{y=await u.stat(k);}catch{continue}if(y.isFile()&&g.endsWith("_test.go")){c=true;break}y.isDirectory()&&v.depth<m&&!h.has(g)&&!g.startsWith(".")&&l.push({dir:k,depth:v.depth+1});}}}catch{}if(t.hasTests=r||c,(t.runtimeFamily==="node"||t.runtimeFamily==="bun")&&!t.hasTests&&(t.hasTests=await bn(e,i)),t.runtimeFamily==="node"||t.runtimeFamily==="bun")t.hasCodeQuality=await vn(e,i);else if(t.framework==="Go/Fiber"||t.framework==="Go/Gin"){let l=d.join(e,".golangci.yml"),m=d.join(e,".golangci.yaml"),h=d.join(e,"Makefile"),v=await u.pathExists(h)&&(await u.readFile(h,"utf8")).includes("golangci-lint");t.hasCodeQuality=await u.pathExists(l)||await u.pathExists(m)||v;}else if(t.runtimeFamily==="python"){let l=d.join(e,"ruff.toml"),m=d.join(e,"pyproject.toml");if(await u.pathExists(m))try{let h=await u.readFile(m,"utf8");t.hasCodeQuality=h.includes("[tool.ruff]")||await u.pathExists(l);}catch{t.hasCodeQuality=await u.pathExists(l);}}else if(t.framework==="Spring Boot"){let l=d.join(e,"pom.xml");if(await u.pathExists(l))try{let m=await u.readFile(l,"utf8");t.hasCodeQuality=m.includes("spotless")||m.includes("checkstyle")||m.includes("pmd")||m.includes("maven-enforcer-plugin");}catch{t.hasCodeQuality=false;}}t.dependencyAudit=await Dn({projectPath:e,runtime:t.runtimeFamily??"unknown"}),t.vulnerabilities=t.dependencyAudit.status==="vulnerable"?t.dependencyAudit.blockingFindingCount??t.dependencyAudit.findingCount??0:void 0;}function Oo(e){return Ln([m(e),d.join(e,"Scripts","python.exe"),d.join(e,"Scripts","python"),d.join(e,"bin","python"),d.join(e,"bin","python3")])}function To(e){let t=e.indexOf("["),i=e.lastIndexOf("]");if(t<0||i<t)return null;try{let n=JSON.parse(e.slice(t,i+1));return Array.isArray(n)?n:null}catch{return null}}async function Nn(e){for(let t of Oo(e.environmentPath)){if(!await u.pathExists(t))continue;let i;try{let n=await execa(t,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3,reject:false});n.exitCode===0&&n.stdout.trim()&&(i=n.stdout.trim());}catch{}if(e.frameworkImport)try{if((await execa(t,["-c",`import ${e.frameworkImport}`],{timeout:2e3,reject:false})).exitCode===0)return {interpreter:t,coreVersion:i,dependenciesInstalled:true}}catch{}try{let n=await execa(t,["-m","pip","list","--format=json"],{timeout:5e3,reject:false}),o=To(`${n.stdout??""}
14
- ${n.stderr??""}`),s=new Set(["pip","setuptools","wheel"]),a=o?.some(r=>typeof r.name=="string"&&!s.has(r.name.toLowerCase()))??false;return {interpreter:t,coreVersion:i,dependenciesInstalled:a}}catch{return {interpreter:t,coreVersion:i,dependenciesInstalled:false}}}return {dependenciesInstalled:false}}async function _o(e,t,i){let n=d.join(e,".venv");if(await u.pathExists(n))return {environmentPath:n,...await Nn({environmentPath:n,frameworkImport:t})};if(i)try{let o=await execa("poetry",["env","info","--path"],{cwd:e,timeout:3e3,reject:false}),s=o.stdout.trim();if(o.exitCode===0&&s&&await u.pathExists(s))return {environmentPath:s,...await Nn({environmentPath:s,frameworkImport:t})}}catch{}return {dependenciesInstalled:false}}function T(e,t){e.probes||(e.probes=[]);let i=zn(t,new Date().toISOString());e.probes.push(i),i.repairCapability&&(e.repairCapabilities||(e.repairCapabilities=[]),e.repairCapabilities.push(i.repairCapability),i.repairCapability.status==="available"&&i.repairCapability.canAutoFix&&i.repairCapability.command&&(e.fixCommands=e.fixCommands??[],e.fixCommands.includes(i.repairCapability.command)||e.fixCommands.push(i.repairCapability.command)));}async function Be(e,t){return (await Promise.all(t.map(i=>u.pathExists(d.join(e,i))))).some(Boolean)}async function $t(e,t){let i=new Set(t.ignoreDirs??["node_modules",".git","bin","obj","dist"]),o=(t.under&&t.under.length>0?t.under:["."]).map(s=>d.join(e,s));for(;o.length>0;){let s=o.shift(),a;try{a=await u.readdir(s,{withFileTypes:true});}catch{continue}for(let r of a){if(r.isFile()&&(t.name&&r.name===t.name||t.suffix&&r.name.endsWith(t.suffix)))return true;r.isDirectory()&&!i.has(r.name)&&o.push(d.join(s,r.name));}}return false}async function Go(e,t){let i=t.runtimeFamily||"unknown";if(t.projectKind==="backend"||t.projectKind==="generic"||t.projectKind==="desktop"||t.projectKind==="extension"){if(i==="node"){let o=await u.pathExists(d.join(e,"package-lock.json"))||await u.pathExists(d.join(e,"pnpm-lock.yaml"))||await u.pathExists(d.join(e,"yarn.lock"));T(t,{id:"adapter-node-lockfile-integrity",label:"Node adapter lockfile integrity",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml).",recommendation:o?void 0:"Commit a lockfile for deterministic installs and CI parity."});let s=t.projectKind==="extension"?["src/extension.ts","src/extension.js","extension.ts","extension.js"]:t.projectKind==="desktop"?["src/main.ts","src/main.js","src/index.ts","src/index.js","src-tauri/src/main.rs"]:["src/main.ts","src/main.js","src/server.ts","src/server.js","server.ts","server.js","index.ts","index.js"],a=await Be(e,s);T(t,{id:"adapter-node-boot-entrypoint",label:t.projectKind==="extension"?"Extension activation entrypoint":t.projectKind==="desktop"?"Desktop application entrypoint":"Node adapter boot entrypoint",status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?`${t.projectKind==="extension"?"Extension":t.projectKind==="desktop"?"Desktop application":"Service"} entrypoint markers detected.`:`No canonical ${t.projectKind==="extension"?"extension activation":t.projectKind==="desktop"?"desktop application":"Node boot"} entrypoint markers detected.`,recommendation:a?void 0:t.projectKind==="extension"?"Expose the extension activation module declared by package.json.":t.projectKind==="desktop"?"Expose and document the desktop main-process or Tauri entrypoint.":"Define and document service bootstrap entrypoint (main/server)."});return}if(i==="python"){let o=await u.pathExists(d.join(e,"poetry.lock"))||await u.pathExists(d.join(e,"requirements.txt"))||await u.pathExists(d.join(e,"uv.lock"));T(t,{id:"adapter-python-lockfile-integrity",label:"Python adapter dependency integrity",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Python dependency contract file detected.":"No Python dependency contract file detected (poetry.lock/requirements/uv.lock).",recommendation:o?void 0:"Pin dependency contract for deterministic setup and reproducible CI."});let a=await Be(e,["src/main.py","src/app/main.py","app/main.py","main.py","manage.py","asgi.py","wsgi.py"]);T(t,{id:"adapter-python-boot-entrypoint",label:"Python adapter boot entrypoint",status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?"Python application entrypoint markers detected.":"No Python application entrypoint markers detected.",recommendation:a?void 0:"Expose explicit app/main entrypoint for deterministic boot probes."});return}if(i==="java"){let o=await u.pathExists(d.join(e,"mvnw"))||await u.pathExists(d.join(e,"gradlew"));T(t,{id:"adapter-java-build-wrapper",label:"Java adapter build wrapper",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"Build wrapper detected (mvnw/gradlew).":"No Java build wrapper detected.",recommendation:o?void 0:"Commit mvnw or gradlew for reproducible enterprise pipelines."});let s=await Be(e,["src/main/java/Application.java","src/main/kotlin/Application.kt"])||await $t(e,{suffix:"Application.java",under:["src/main/java"]})||await $t(e,{suffix:"Application.kt",under:["src/main/kotlin"]});T(t,{id:"adapter-java-boot-entrypoint",label:"Java adapter boot entrypoint",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Java application entrypoint markers detected.":"No Java application entrypoint markers detected.",recommendation:s?void 0:"Expose a Spring Boot Application class under src/main/java or src/main/kotlin."});return}if(i==="go"){let o=await u.pathExists(d.join(e,"go.sum"));T(t,{id:"adapter-go-module-integrity",label:"Go adapter module integrity",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?"go.sum detected for deterministic module verification.":"go.sum missing; module integrity baseline is incomplete.",recommendation:o?void 0:"Generate and commit go.sum in the repository baseline."});let s=await Be(e,["cmd/server/main.go","cmd/api/main.go","main.go"]);T(t,{id:"adapter-go-boot-entrypoint",label:"Go adapter boot entrypoint",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Go application entrypoint markers detected.":"No Go application entrypoint markers detected.",recommendation:s?void 0:"Expose a Go main package entrypoint such as cmd/server/main.go."});return}if(i==="dotnet"){let o=await Be(e,["Program.cs","src/Program.cs"])||await $t(e,{name:"Program.cs"});T(t,{id:"adapter-dotnet-boot-entrypoint",label:".NET adapter boot entrypoint",status:o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?".NET application entrypoint markers detected.":"No .NET application entrypoint markers detected.",recommendation:o?void 0:"Expose Program.cs at the project root or under src for deterministic boot probes."});}}}async function Ko(e,t){let i=[d.join(e,".workspai","doctor.adapters.json"),d.join(e,".rapidkit","doctor.adapters.json"),d.join(e,"doctor.adapters.json")];for(let n of i)if(await u.pathExists(n))try{let o=await u.readJSON(n),s=Array.isArray(o?.checks)?o.checks:[];for(let a=0;a<s.length;a+=1){let r=s[a]||{},c=Array.isArray(r.runtimes)?r.runtimes:[];if(c.length>0&&!c.includes(t.runtimeFamily||"unknown"))continue;let l=typeof r.id=="string"&&r.id.trim().length>0?r.id.trim():`adapter-check-${a+1}`,m=typeof r.label=="string"&&r.label.trim().length>0?r.label.trim():l,h=r.severity||"warn",v=Array.isArray(r.anyOfPaths)?r.anyOfPaths.filter(Boolean):[],C=Array.isArray(r.allOfPaths)?r.allOfPaths.filter(Boolean):[],g=v.length===0;for(let w of v)if(await u.pathExists(d.join(e,w))){g=true;break}let k=true;for(let w of C)if(!await u.pathExists(d.join(e,w))){k=false;break}let y=g&&k;T(t,{id:l,label:m,status:y?"pass":h==="error"?"fail":"warn",severity:h,scope:"project-scoped",reason:y?r.passReason||"Custom adapter contract satisfied.":r.failReason||`Custom adapter check failed from ${d.basename(n)}.`,recommendation:r.recommendation});}}catch{T(t,{id:"custom-adapter-config",label:"Custom doctor adapter configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${d.basename(n)}.`,recommendation:"Fix JSON syntax in doctor.adapters.json to re-enable adapter checks."});}}async function U(e,t){if(!(t.projectKind==="backend"||t.projectKind==="generic"))return;let n=d.join(e,".env"),o=d.join(e,".env.example"),s=await u.pathExists(n)||await u.pathExists(o)||await u.pathExists(d.join(e,"config"));T(t,{id:"config-surface",label:"Configuration contract surface",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Configuration artifacts detected (.env/.env.example/config).":"No explicit configuration contract artifacts detected.",recommendation:s?void 0:"Add .env.example or explicit config contract documentation for deterministic setup."});let a={python:["alembic.ini","migrations","versions"],node:["prisma/schema.prisma","migrations","typeorm.config.ts","typeorm.config.js"],bun:["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"],scala:["src/main/resources/db/migration","conf/evolutions"],kotlin:["src/main/resources/db/migration","src/main/resources/liquibase"],c:["migrations","db/migrations"],cpp:["migrations","db/migrations"],unknown:["migrations"]},r=t.runtimeFamily||"unknown",c=a[r]||a.unknown,l=false;for(let v of c)if(await u.pathExists(d.join(e,v))){l=true;break}T(t,{id:"migration-surface",label:"Migration/readiness surface",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Migration or schema evolution markers detected.":"No migration markers detected for this backend runtime.",recommendation:l?void 0:"Add migration tooling baseline (migrations dir or runtime-native migration config)."});let m=["src/health","src/healthcheck","src/main/resources/application.yml","src/main/resources/application.properties","app/health.py","routes/health.ts","routes/health.js"],h=false;for(let v of m)if(await u.pathExists(d.join(e,v))){h=true;break}T(t,{id:"runtime-health-surface",label:"Runtime health probe surface",status:h?"pass":"warn",severity:"warn",scope:"project-scoped",reason:h?"Health endpoint/config markers detected.":"No explicit runtime health endpoint markers detected.",recommendation:h?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await Go(e,t);}async function Bo(e,t,i,n){let o=await wn({projectPath:e,detection:n,packageJsonData:i});for(let s of o)T(t,s);}async function Y(e,t,i){let n=await jn({projectPath:e,runtimeFamily:t.runtimeFamily,projectKind:t.projectKind,packageJsonData:i,hasTests:t.hasTests,vulnerabilities:t.vulnerabilities,dependencyAudit:t.dependencyAudit});for(let o of n)T(t,o);}async function Q(e,t){let i=[d.join(e,".workspai","doctor.probes.json"),d.join(e,".rapidkit","doctor.probes.json"),d.join(e,"doctor.probes.json")];for(let n of i)if(await u.pathExists(n))try{let o=await u.readJSON(n),s=Array.isArray(o?.probes)?o.probes:[];for(let a=0;a<s.length;a+=1){let r=s[a]||{},c=typeof r.id=="string"&&r.id.trim().length>0?r.id.trim():`custom-probe-${a+1}`,l=typeof r.label=="string"&&r.label.trim().length>0?r.label.trim():c,m=r.severity||"warn",h=Array.isArray(r.anyOfPaths)?r.anyOfPaths.filter(Boolean):[],v=Array.isArray(r.allOfPaths)?r.allOfPaths.filter(Boolean):[],C=h.length===0;for(let y of h)if(await u.pathExists(d.join(e,y))){C=true;break}let g=true;for(let y of v)if(!await u.pathExists(d.join(e,y))){g=false;break}let k=C&&g;T(t,{id:c,label:l,status:k?"pass":m==="error"?"fail":"warn",severity:m,scope:"project-scoped",reason:k?"Custom probe contract satisfied.":`Custom probe failed from ${d.basename(n)}.`,recommendation:r.recommendation});}}catch{T(t,{id:"custom-probe-config",label:"Custom doctor probe configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${d.basename(n)}.`,recommendation:"Fix JSON syntax in doctor.probes.json to re-enable custom probes."});}await Ko(e,t);}async function Wo(e,t$1={}){let n={name:d.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},o=t$1.allowNonRapidkit===true;if(!(await u.pathExists(d.join(e,".workspai"))||await u.pathExists(d.join(e,".rapidkit")))){if(!o)return n.issues.push("Not a valid Workspai project (missing .workspai metadata)"),n;n.issues.push("Not a Workspai-managed project (running generic backend diagnostics)");}try{let j=d.join(e,"registry.json");if(await u.pathExists(j)){let S=await u.readJson(j);S.installed_modules&&(n.stats={modules:S.installed_modules.length});}}catch{}try{let{auditProjectModulePaths:j}=await import('./module-layout-NZ43RSC5.js'),S=await j(e);if(S.issues.length>0){for(let F of S.issues)n.issues.push(`${F.message} (${F.slug})`);n.fixCommands=n.fixCommands??[],n.fixCommands.push("npx workspai workspace contract verify --strict --json"),n.fixCommands.push("npx workspai add module <slug> # reinstall via Core-backed module install");}}catch{}let a=null;try{for(let j of t(e,"project.json")){if(!await u.pathExists(j))continue;a=await u.readJson(j);let S=a?.kit_name||a?.kit;S&&(n.kit=S);break}}catch{}try{let j=d.join(e,".git");if(await u.pathExists(j)){let{stdout:S}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false,env:a$7()});S&&(n.lastModified=S.trim());}else {let S=await u.stat(e),O=Date.now()-S.mtime.getTime(),_=Math.floor(O/(1e3*60*60*24));n.lastModified=_===0?"today":`${_} day${_>1?"s":""} ago`;}}catch{}let r=d.join(e,"package.json"),c=d.join(e,"pyproject.toml"),l=d.join(e,"requirements.txt"),m=d.join(e,"go.mod"),h=d.join(e,"pom.xml"),v=d.join(e,"build.sbt"),C=d.join(e,"Cargo.toml"),g=d.join(e,"mix.exs"),k=d.join(e,"deps.edn"),y=d.join(e,"project.clj"),w=d.join(e,"deno.json"),b=d.join(e,"deno.jsonc"),E=d.join(e,"bun.lockb"),$=d.join(e,"bun.lock"),f=d.join(e,"composer.json"),P=d.join(e,"Gemfile"),D=await u.pathExists(r),q=await u.pathExists(c)||await u.pathExists(l),x=await u.pathExists(f),L=await u.pathExists(P),M=await u.pathExists(C),oe=await u.pathExists(g),Le=await u.pathExists(k)||await u.pathExists(y),Ve=await u.pathExists(v),Je=await u.pathExists(w)||await u.pathExists(b),V=a?.runtime==="dotnet";try{V=V||await Mn(e,".csproj",3)||await Mn(e,".sln",2);}catch{V=a?.runtime==="dotnet";}let Ie=await u.pathExists(m)||a?.runtime==="go"||typeof a?.kit_name=="string"&&(a.kit_name.startsWith("gofiber")||a.kit_name.startsWith("gogin")),me=D&&(await u.pathExists(E)||await u.pathExists($)||typeof a?.packageManager=="string"&&(a?.packageManager).toLowerCase().startsWith("bun@"));if(Ie){Z(n,j$3(e,a??null)),n.isGoProject=true,n.venvActive=true,n.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{n.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),n.fixCommands?.push("https://go.dev/dl/");}let j=d.join(e,"go.sum");return await u.pathExists(j)?n.depsInstalled=true:(n.depsInstalled=false,n.issues.push("Go dependencies not downloaded (go.sum missing)"),n.fixCommands?.push(H(e,"go mod tidy"))),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(await u.pathExists(h)||a?.runtime==="java"||typeof a?.kit_name=="string"&&a.kit_name.startsWith("springboot")){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=await u.pathExists(h),S=await u.pathExists(d.join(e,"build.gradle"))||await u.pathExists(d.join(e,"build.gradle.kts")),F=await u.pathExists(d.join(e,"mvnw"))||await u.pathExists(d.join(e,"mvnw.cmd")),O=await u.pathExists(d.join(e,"gradlew"))||await u.pathExists(d.join(e,"gradlew.bat"));try{await execa("java",["-version"],{timeout:3e3,reject:false});}catch{n.issues.push("Java runtime not found \u2014 install JDK 21+ and ensure java is on PATH"),n.fixCommands?.push("https://adoptium.net/");}if(j){if(!F)try{await execa("mvn",["-version"],{timeout:3e3,reject:false});}catch{n.issues.push("Maven not found \u2014 install Maven 3.9+ or add Maven Wrapper"),n.fixCommands?.push("https://maven.apache.org/install.html");}}else if(S&&!O)try{await execa("gradle",["--version"],{timeout:3e3,reject:false});}catch{n.issues.push("Gradle not found \u2014 install Gradle 8+ or add Gradle Wrapper"),n.fixCommands?.push("https://gradle.org/install/");}let _=d.join(e,"target"),te=d.join(e,"build","libs"),de=d.join(e,".workspai","cache","java","m2"),R=d.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await u.pathExists(_)||await u.pathExists(te)||await u.pathExists(de)||await u.pathExists(R),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let be=j?F?b$6()?".\\mvnw.cmd -B -DskipTests dependency:go-offline":"./mvnw -B -DskipTests dependency:go-offline":"mvn -B -DskipTests dependency:go-offline":O?b$6()?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies";n.fixCommands?.push(H(e,be));}let W=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(W),!n.hasEnvFile){let be=d.join(e,".env.example");await u.pathExists(be)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}let ne=d.join(e,"src","main","resources","application.yml");if(await u.pathExists(ne))try{let be=await u.readFile(ne,"utf-8");/include:\s*[^\n]*health/i.test(be)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(be)||(n.issues.push("Actuator health endpoint exposure is not clearly configured in application.yml"),n.fixCommands?.push(H(e,"Ensure management.endpoints.web.exposure.include contains health in src/main/resources/application.yml")));}catch{n.issues.push("Unable to read application.yml for Spring Actuator health checks");}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(M){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=d.join(e,"Cargo.lock"),S=d.join(e,"target");n.depsInstalled=await u.pathExists(j)||await u.pathExists(S),n.depsInstalled||(n.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),n.fixCommands?.push(H(e,"cargo fetch")));let F=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(F),!n.hasEnvFile){let O=d.join(e,".env.example");await u.pathExists(O)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(oe){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=d.join(e,"mix.lock"),S=d.join(e,"deps");n.depsInstalled=await u.pathExists(j)||await u.pathExists(S),n.depsInstalled||(n.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),n.fixCommands?.push(H(e,"mix deps.get")));let F=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(F),!n.hasEnvFile){let O=d.join(e,".env.example");await u.pathExists(O)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(Le){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=d.join(e,".cpcache"),S=d.join(e,"target"),F=await u.pathExists(k)||await u.pathExists(y);return n.depsInstalled=await u.pathExists(j)||await u.pathExists(S)||F,n.depsInstalled||(n.issues.push("Clojure dependency cache not initialized"),n.fixCommands?.push(H(e,"clojure -P"))),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(Ve){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=d.join(e,"target");n.depsInstalled=await u.pathExists(j),n.depsInstalled||(n.issues.push("Scala build artifacts missing (run dependency/build warmup)"),n.fixCommands?.push(H(e,"sbt compile")));let S=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(S),!n.hasEnvFile){let F=d.join(e,".env.example");await u.pathExists(F)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(Je){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true;let j=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(j),!n.hasEnvFile){let S=d.join(e,".env.example");await u.pathExists(S)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(D){let j=null;try{j=await u.readJson(r);}catch{j=null;}let S={...j?.dependencies??{},...j?.devDependencies??{}},F=j?.scripts??{},O=typeof a?.kit_name=="string"?a.kit_name.toLowerCase():typeof a?.kit=="string"?a.kit.toLowerCase():"",_=d$4(e,a),te=Co({dependencies:S,scripts:F,kitName:O});if(me)ot(n,"Bun","high");else {let R=j$3(e,a??null);R.key==="nestjs"||R.key==="express"||R.key==="fastify"||R.key==="koa"||R.key==="tauri"||R.key==="electron"||R.key==="vscode-extension"?Z(n,R):_.key!=="unknown"?xo(n,_):R.key!=="unknown"&&R.key!=="node"?Z(n,R):ot(n,te.framework,te.confidence);}n.venvActive=true;let de=d.join(e,"node_modules");if(await u.pathExists(de))try{let W=(await u.readdir(de)).filter(ne=>!ne.startsWith(".")&&!ne.startsWith("_"));n.depsInstalled=W.length>0;}catch{n.depsInstalled=false;}if(!n.depsInstalled){n.issues.push("Dependencies not installed (node_modules empty or missing)");let R=typeof j?.packageManager=="string"?j.packageManager.split("@")[0]:void 0,W=me?"bun install":R==="pnpm"||await u.pathExists(d.join(e,"pnpm-lock.yaml"))?"pnpm install":R==="yarn"||await u.pathExists(d.join(e,"yarn.lock"))?"yarn install":"npm install";n.fixCommands?.push(H(e,W));}if(n.coreInstalled=false,n.projectKind==="frontend"){let R=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(R.map(ne=>u.pathExists(d.join(e,ne))))).some(Boolean))n.hasEnvFile=true;else {let ne=d.join(e,".env.example");await u.pathExists(ne)&&(n.hasEnvFile=false,n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}}else {let R=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(R),!n.hasEnvFile){let W=d.join(e,".env.example");await u.pathExists(W)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}}if(n.projectKind==="frontend")n.modulesHealthy=await jt(e),n.missingModules=[];else {let R=d.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await u.pathExists(R))try{let W=await u.readdir(R);n.modulesHealthy=W.length>0;}catch{n.modulesHealthy=false;}}return await z(e,n,j),await Y(e,n,j),n.projectKind==="frontend"?await Bo(e,n,j,_.key!=="unknown"?_:d$4(e,a)):await U(e,n),await Q(e,n),n}if(q){let j=await Po(e,a);ot(n,j.framework,j.confidence);let S="fastapi";n.framework==="Django"?S="django":n.framework==="Flask"?S="flask":n.framework==="Python"&&(S="");let F=await ut(c),O=await _o(e,S,/\[tool\.poetry\]/.test(F));n.venvActive=!!O.environmentPath,n.depsInstalled=O.dependenciesInstalled,n.coreInstalled=!!O.coreVersion,n.coreVersion=O.coreVersion,O.environmentPath?O.interpreter?n.depsInstalled||(n.issues.push("Dependencies not installed"),n.fixCommands?.push(Fn(e))):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Fn(e)));let _=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(_),!n.hasEnvFile){let R=d.join(e,".env.example");await u.pathExists(R)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}let te=d.join(e,"src"),de=d.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await u.pathExists(te)){let R=d.join(te,"__init__.py");await u.pathExists(R)||(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await u.pathExists(de))try{let R=await qo(de);for(let W of R){let ne=d.join(de,W,"__init__.py");await u.pathExists(ne)||(n.modulesHealthy=false,n.missingModules.push(`modules/${W}/__init__.py`));}}catch{}return !n.modulesHealthy&&n.missingModules.length>0&&n.issues.push(`Missing module init files: ${n.missingModules.join(", ")}`),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(x){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=d.join(e,"vendor");n.depsInstalled=await u.pathExists(j),n.depsInstalled||(n.issues.push("PHP dependencies not installed (vendor missing)"),n.fixCommands?.push(H(e,"composer install")));let S=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(S),!n.hasEnvFile){let F=d.join(e,".env.example");await u.pathExists(F)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(L){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=await u.pathExists(d.join(e,"Gemfile.lock")),S=await u.pathExists(d.join(e,"vendor","bundle"));n.depsInstalled=j||S,n.depsInstalled||(n.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),n.fixCommands?.push(H(e,"bundle install")));let F=d.join(e,".env");return n.hasEnvFile=await u.pathExists(F),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(V){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let j=d.join(e,"obj"),S=d.join(e,"src","obj"),F=d.join(e,"packages.lock.json");n.depsInstalled=await u.pathExists(j)||await u.pathExists(S)||await u.pathExists(F),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(H(e,"dotnet restore")));let O=d.join(e,".env");return n.hasEnvFile=await u.pathExists(O),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}return ot(n,"Unknown","low"),n.issues.push("Unknown project type (no recognized runtime marker files)"),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}function Ho(e){if(!e.fixCommands)return e;let t=new Set;return e.fixCommands=e.fixCommands.filter(i=>{let n=i.trim();return !n||t.has(n)?false:(t.add(n),true)}),e}async function ct(e,t={}){let i=Ho(await Wo(e,t)),n=await b$3(e);return n==="backend"||n==="service"||n==="worker"?i.projectKind="backend":n==="frontend"||n==="desktop"||n==="extension"?i.projectKind=n:i.projectKind||(i.projectKind="generic"),i}async function qo(e){try{return (await u.readdir(e,{withFileTypes:true})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{try{let t=await u.readdir(e),i=[];for(let n of t)try{(await u.stat(d.join(e,n))).isDirectory()&&i.push(n);}catch{continue}return i}catch{return []}}}async function Mn(e,t,i){let n=[{dir:e,depth:0}],o=new Set([".git",".workspai",".rapidkit","node_modules","bin","obj","target"]);for(;n.length>0;){let s=n.shift();if(!s||s.depth>i)continue;let a;try{a=await u.readdir(s.dir,{withFileTypes:true});}catch{continue}for(let r of a){if(r.isFile()&&r.name.toLowerCase().endsWith(t.toLowerCase()))return true;r.isDirectory()&&!o.has(r.name)&&!a$8(r.name)&&n.push({dir:d.join(s.dir,r.name),depth:s.depth+1});}}return false}async function We(e){let t=["project.json","context.json","file-hashes.json"];for(let i of [".workspai",".rapidkit"])for(let n of t)if(await u.pathExists(d.join(e,i,n)))return true;return false}function Lo(e,t){if(t.has(e)||a$8(e))return true;let i=e.toLowerCase();return !!(i==="dist"||i.startsWith("dist-")||i.startsWith("dist_")||i==="build"||i.startsWith("build-")||i.startsWith("build_"))}async function Vo(e,t,i){let n=new Set,o=[{dir:e,depth:0}];for(;o.length>0;){let s=o.shift();if(!s)break;try{let a=await u.readdir(s.dir);for(let r of a){if(Lo(r,i))continue;let c=d.join(s.dir,r),l;try{l=await u.stat(c);}catch{continue}if(l.isDirectory()){if(await We(c)){n.add(c);continue}s.depth<t&&o.push({dir:c,depth:s.depth+1});}}}catch{continue}}return Array.from(n)}async function He(e){let t=d.resolve(e),i=d.parse(t).root;for(;;){if(await Uo(t))return t;if(t===i)break;t=d.dirname(t);}return null}async function Jo(e){let t=d.resolve(e),i=await He(t),n=i??d.parse(t).root;for(;;){if(await We(t)||await zo(t)&&(!i||t!==i))return t;if(t===n)break;t=d.dirname(t);}return null}function On(e){let t=d.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function zo(e){let t=["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 i of t)if(await u.pathExists(d.join(e,i)))return true;return false}async function Uo(e){if(j$1(e))return true;let t=[d.join(e,".rapidkit","workspace-marker.json"),d.join(e,".rapidkit","config.json")];return Promise.all(t.map(i=>u.pathExists(i))).then(i=>i.some(Boolean))}function Gt(e,t){let i={total:0,passed:0,warnings:0,errors:0},n={total:0,passed:0,warnings:0,errors:0};e.forEach(r=>{i.total+=1,r.status==="ok"?i.passed+=1:r.status==="warn"?i.warnings+=1:r.status==="error"&&(i.errors+=1);}),t.forEach(r=>{let c=r.probes??[];if(c.length>0){for(let h of c)n.total+=1,h.status==="pass"?n.passed+=1:h.status==="warn"?n.warnings+=1:n.errors+=1;r.issues.length>0&&(n.total+=r.issues.length,n.errors+=r.issues.length);return}n.total+=1;let l=ao(r),m=r.isGoProject?r.issues.length===0&&r.depsInstalled:r.issues.length===0&&r.venvActive&&r.depsInstalled;r.issues.length>0||!m?n.errors+=1:l>0?n.warnings+=1:n.passed+=1;});let o=i.passed+n.passed,s=i.warnings+n.warnings,a=i.errors+n.errors;return {total:i.total+n.total,passed:o,warnings:s,errors:a,verdict:a>0?"blocked":s>0?"attention":"passed",components:{host:i,projects:n}}}function ee(e){let t=e.probes??[],i=t.filter(r=>r.status==="pass").length,n=t.filter(r=>r.status==="warn").length,o=t.filter(r=>r.status==="fail").length,s=o+e.issues.length,a=n;return {total:t.length,passed:i,warnings:n,failed:o,blockingFindings:s,advisoryFindings:a,verdict:s>0?"blocked":a>0?"attention":"passed"}}function Yo(e){let t=ee(e);e.probeSummary=t,e.verdict=t.verdict;}function ti(e,t,i={}){let n=[];for(let s of e)n.push({id:s.id,label:s.label,status:s.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:s.result.details||s.result.message});let o=[...t].sort((s,a)=>{let r=`${s.path||""}|${s.name||""}`.toLowerCase(),c=`${a.path||""}|${a.name||""}`.toLowerCase();return r.localeCompare(c)});for(let s of o){Yo(s);for(let a of s.probes??[])n.push({id:`project:${s.name}:probe:${a.id}`,label:`${s.name} \xB7 ${a.label}`,status:a.status==="pass"?"ok":a.status==="warn"?"warn":"error",scope:"project-scoped",policyRuleId:`project-probe-${a.id}`,reason:a.reason});for(let[a,r]of s.issues.entries())n.push({id:`project:${s.name}:legacy:${a+1}`,label:`${s.name} \xB7 Runtime issue`,status:"error",scope:"project-scoped",policyRuleId:"project-runtime-issue",reason:r});(s.probes?.length??0)===0&&s.issues.length===0&&n.push({id:`project:${s.name}`,label:`Project ${s.name}`,status:"ok",scope:"project-scoped",policyRuleId:"project-checks-passed",reason:"Project checks passed"});}if(i.includeWorkspaceAggregateRules){let s=t.reduce((c,l)=>c+ee(l).blockingFindings,0),a=t.reduce((c,l)=>c+ee(l).advisoryFindings,0),r=e.filter(c=>c.result.status==="error").length;n.push({id:"workspace:projects-discovered",label:"Workspace projects discovered",status:t.length>0?"ok":"warn",scope:"workspace-aggregate",policyRuleId:"workspace-project-discovery",reason:t.length>0?`${t.length} project(s) discovered for workspace analysis.`:"No projects discovered for workspace analysis."}),n.push({id:"workspace:system-error-gate",label:"Workspace system error gate",status:r>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-system-error-gate",reason:r>0?`${r} system requirement gate(s) failed.`:"All system requirement gates passed."}),n.push({id:"workspace:blocking-issues-gate",label:"Workspace blocking issues gate",status:s>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:s>0?`${s} blocking project issue(s) detected.`:"No blocking project issues detected."}),n.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:a>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:a>0?`${a} advisory warning(s) detected.`:"No advisory warnings detected."});}return n}async function At(e,t=true,i=at({})){let n=d.basename(e),o=await a$1(e);if(typeof o?.name=="string"&&o.name.trim().length>0)n=o.name;else try{for(let g of s(e,"workspace.json")){if(!await u.pathExists(g))continue;let k=await u.readJSON(g);n=k.workspace_name||k.name||n;break}}catch{}let[s$1,a]=await Promise.all([_t(e),Do(e)]),r={workspacePath:e,workspaceName:n,python:s$1.python,poetry:s$1.poetry,pipx:s$1.pipx,go:s$1.go,rapidkitCore:s$1.rapidkitCore,projects:[],policyProfile:i};f.debug(`Workspace scan found ${a.length} project(s)`);let c=await So(e,a),l=d.join(e,".workspai","reports","doctor-workspace-cache.json"),m=t?await Eo(l,c):null;if(m){r.projects=m.projects;for(let g of r.projects)An(g,m.generatedAt),Nt(g,g.path);r.projectScanCached=true,f.debug(`Workspace project health cache hit: ${l}`);}else try{let g=new Date().toISOString(),k=await Promise.all(a.map(y=>ct(y,{allowNonRapidkit:true})));for(let y of k)An(y,g),Nt(y,y.path);r.projects=k,r.projectScanCached=false,await Ro(l,{schemaVersion:Vn,signature:c,generatedAt:g,projects:k}),f.debug(`Workspace project health cache refreshed: ${l}`);}catch(g){f.debug(`Failed to scan workspace projects: ${g}`);}r.projectScanSignature=c,r.projectScanCachePath=l,await Promise.all(r.projects.map(async g=>{g.graphDiagnosis=await Rt({workspacePath:e,projectPath:g.path,projectName:g.name,probes:Jn(g),issues:g.issues});}));let h=[r.python,r.poetry,r.pipx,r.go,r.rapidkitCore];if(r.healthScore=Gt(h,r.projects),r.scoreBreakdown=ti([{id:"system-python",label:"Python",result:r.python},{id:"system-poetry",label:"Poetry",result:r.poetry},{id:"system-pipx",label:"pipx",result:r.pipx},{id:"system-go",label:"Go",result:r.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:r.rapidkitCore}],r.projects,{includeWorkspaceAggregateRules:true}),r.scopeProvenance=Zn(r.scoreBreakdown),r.evidenceFreshness=Un(r.projects,new Date().toISOString()),r.rapidkitCore.status==="ok"){let g=r.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);g&&(r.coreVersion=g[1]);}let v=await d$1(e,It),C=v?await Qn(v,"workspace"):null;return r.driftDelta=ho(C,r),r.evidencePath=await $o(e,r,m?l:null),r}function Tn(e){return {name:e.name,path:e.path,framework:e.framework,frameworkKey:e.frameworkKey,importStack:e.importStack,runtimeFamily:e.runtimeFamily,projectKind:e.projectKind,supportTier:e.supportTier,frameworkConfidence:e.frameworkConfidence,kit:e.kit,venvActive:e.venvActive,depsInstalled:e.depsInstalled,hasEnvFile:e.hasEnvFile,modulesHealthy:e.modulesHealthy,missingModules:e.missingModules,hasTests:e.hasTests,hasDocker:e.hasDocker,hasCodeQuality:e.hasCodeQuality,vulnerabilities:e.vulnerabilities,dependencyAudit:e.dependencyAudit,coreInstalled:e.coreInstalled,coreVersion:e.coreVersion,lastModified:e.lastModified,stats:e.stats,issues:e.issues,fixCommands:e.fixCommands,probes:e.probes,verdict:e.verdict??ee(e).verdict,probeSummary:e.probeSummary??ee(e),repairCapabilities:e.repairCapabilities,commandCapabilities:e.commandCapabilities,graphDiagnosis:e.graphDiagnosis}}function ni(e,t){let i=e?d.relative(e,t).split(d.sep).join("/"):d.resolve(t),n=d.basename(t).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",o=createHash("sha256").update(i).digest("hex").slice(0,12);return `.workspai/reports/projects/${n}--${o}/doctor-project-last-run.json`}async function Qo(e$2,t){let i=e$2||t.projectPath,n=".workspai/reports/doctor-project-last-run.json",o=ni(e$2,t.projectPath),s=d.join(i,n);try{let a=[...t.project.issues,...(t.project.probes??[]).filter(l=>l.status==="fail").map(l=>l.reason)].filter(l=>typeof l=="string"&&l.trim().length>0).slice(0,12),r=ee(t.project),c=f$1({schemaVersion:b$5,evidenceType:"project",contract:Re(),policyProfile:t.policyProfile,workspacePath:e$2||null,projectPath:t.projectPath,projectName:t.projectName,healthScore:t.healthScore,evidenceFreshness:t.evidenceFreshness,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore},project:t.project,driftDelta:t.driftDelta,summary:{scopeProvenance:t.scopeProvenance,verdict:r.verdict,probeSummary:r,blockingFindings:r.blockingFindings,advisoryFindings:r.advisoryFindings},scoreBreakdown:t.scoreBreakdown??[]},{commandId:"projectDoctor",exitCode:qe(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:a,runId:e$1()});return d$3(c),e$2?await f$2(e$2,n,[{relativePath:n,payload:c},{relativePath:o,payload:c}]):await e(i,n,c),e$2&&d.resolve(e$2)!==d.resolve(t.projectPath)&&await e(t.projectPath,n,c),s}catch(a){if(a instanceof Error&&a.message.includes("violates contracts/"))throw a;return}}async function Mt(e$1,t,i=[]){let n=d.join(e$1,".workspai","reports","doctor-remediation-plan-last-run.json");try{await e(e$1,".workspai/reports/doctor-remediation-plan-last-run.json",t);for(let o of i)d.resolve(o)!==d.resolve(e$1)&&await e(o,".workspai/reports/doctor-remediation-plan-last-run.json",t);return n}catch(o){if(o instanceof Error&&o.message.includes("violates contracts/"))throw o;return}}async function $e(e$1,t,i=[]){let n=d.join(e$1,".workspai","reports","doctor-fix-result-last-run.json");try{await e(e$1,".workspai/reports/doctor-fix-result-last-run.json",t);for(let o of i)d.resolve(o)!==d.resolve(e$1)&&await e(o,".workspai/reports/doctor-fix-result-last-run.json",t);return n}catch{return}}async function Ae(e,t,i){try{await j(e,g(t,i));}catch{}}async function _n(e,t=at({})){let i=await He(e),n=await _t(i||e),o=await ct(e,{allowNonRapidkit:true});Nt(o,e),o.graphDiagnosis=await Rt({workspacePath:i||void 0,projectPath:e,projectName:o.name,probes:Jn(o),issues:o.issues});let s=Gt([n.python,n.poetry,n.pipx,n.go,n.rapidkitCore],[o]),a={workspacePath:i||void 0,projectPath:e,projectName:d.basename(e),python:n.python,poetry:n.poetry,pipx:n.pipx,go:n.go,rapidkitCore:n.rapidkitCore,project:o,healthScore:s,policyProfile:t};a.scoreBreakdown=ti([{id:"system-python",label:"Python",result:a.python},{id:"system-poetry",label:"Poetry",result:a.poetry},{id:"system-pipx",label:"pipx",result:a.pipx},{id:"system-go",label:"Go",result:a.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:a.rapidkitCore}],[a.project]),a.scopeProvenance=Zn(a.scoreBreakdown),a.evidenceFreshness=Un([a.project],new Date().toISOString());let r=await d$1(e,".workspai/reports/doctor-project-last-run.json"),c=i?await d$1(i,ni(i,e)):null,l=r??c,m=l?await Qn(l,"project"):null;return a.driftDelta=ko(m,a),a.evidencePath=await Qo(i||void 0,a),a}function B(e,t){let i=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",n=e.status==="ok"?p.green:e.status==="warn"?p.yellow:p.red;console.log(`${i} ${p.bold(t)}: ${n(e.message)}`),e.paths&&e.paths.length>0&&e.paths.forEach(o=>{let s=o.version?p.cyan(` -> ${o.version}`):"";console.log(` ${p.cyan("\u2022")} ${p.gray(o.location)}: ${p.dim(o.path)}${s}`);}),e.details&&console.log(` ${p.gray(e.details)}`);}function rt(e,t){let i=Kt(e,t);if(/^(?:workspai|rapidkit):doctor:repair\s/.test(t))return i?.title??"Apply Doctor-managed project repair";if(/^https?:\/\//i.test(t.trim()))return `Open: ${t.trim()}`;let n=t.match(/\s+(?:&&|;)\s+/);return `Run in project: ${n?t.slice((n.index??0)+n[0].length):t}`}function Gn(e,t){let i=e.issues.length>0,n=i?"\u26A0\uFE0F":"\u2705",o=i?p.yellow:p.green;if(console.log(`
15
- ${n} ${p.bold("Project")}: ${o(e.name)}`),e.framework){let r=e.framework==="FastAPI"||e.framework==="Django"||e.framework==="Flask"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":e.framework==="Next.js"||e.framework==="Nuxt"||e.framework==="Remix"?"\u25B2":e.framework==="React"||e.framework==="Vite"?"\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(` ${r} Framework: ${p.cyan(e.framework)}${e.kit?p.gray(` (${e.kit})`):""}`);let c=[];e.runtimeFamily&&c.push(`runtime: ${e.runtimeFamily}`),e.projectKind&&c.push(`kind: ${e.projectKind}`),e.supportTier&&c.push(`support: ${e.supportTier}`),e.frameworkConfidence&&c.push(`confidence: ${e.frameworkConfidence}`),c.length>0&&console.log(` ${p.dim("\u21B3")} ${p.gray(c.join(" \u2022 "))}`);}if(console.log(` ${p.gray(`Path: ${e.path}`)}`),e.runtimeFamily==="python"&&(e.venvActive?console.log(` \u2705 Virtual environment: ${p.green("Active")}`):console.log(` \u274C Virtual environment: ${p.red("Not found")}`),e.coreInstalled?console.log(` ${p.dim("\u2139")} RapidKit Core: ${p.gray(e.coreVersion||"In venv")} ${p.dim("(optional)")}`):t?.status==="ok"?console.log(` ${p.dim("\u2139")} RapidKit Core: ${p.gray("Using global installation")} ${p.dim("(recommended)")}`):console.log(` \u274C RapidKit Core: ${p.red("Not detected locally or globally")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${p.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${p.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${p.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${p.yellow(".env missing")}`)),e.modulesHealthy!==void 0){let r=e.projectKind==="frontend"?"Source tree":e.projectKind==="desktop"?"Application source":e.projectKind==="extension"?"Extension source":"Modules";e.modulesHealthy?console.log(` \u2705 ${r}: ${p.green("Healthy")}`):e.missingModules&&e.missingModules.length>0?console.log(` \u26A0\uFE0F ${r}: ${p.yellow(`Missing ${e.missingModules.length} init file(s)`)}`):(e.projectKind==="frontend"||e.projectKind==="desktop"||e.projectKind==="extension")&&console.log(` \u26A0\uFE0F ${r}: ${p.yellow("No application directories detected")}`);}if(e.stats){let r=[];e.stats.modules!==void 0&&r.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),r.length>0&&console.log(` \u{1F4CA} Stats: ${p.cyan(r.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${p.gray(e.lastModified)}`);let a=[];if(e.hasTests!==void 0&&a.push(e.hasTests?"\u2705 Tests":p.dim("\u2298 No tests")),e.hasDocker!==void 0&&a.push(e.hasDocker?"\u2705 Docker":p.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let r=e.runtimeFamily==="node"||e.runtimeFamily==="bun"?"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";a.push(e.hasCodeQuality?`\u2705 ${r}`:p.dim(`\u2298 No ${r}`));}if(a.length>0&&console.log(` ${a.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${p.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${p.bold("Issues:")}`),e.issues.forEach(r=>{console.log(` \u2022 ${p.yellow(r)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
16
- ${p.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(r=>{console.log(` ${p.white(rt(e,r))}`);}))),e.probes&&e.probes.length>0){console.log(` ${p.bold("Probe checks:")}`);for(let r of e.probes){let c=r.status==="pass"?"\u2705":r.status==="warn"?"\u26A0\uFE0F":"\u274C";console.log(` ${c} ${r.label}: ${p.gray(r.reason)}`),r.recommendation&&console.log(` ${p.dim("\u21B3")} ${p.gray(r.recommendation)}`);}}if(e.graphDiagnosis?.status==="available"){let r=e.graphDiagnosis.summary;console.log(` ${p.bold("Graph-aware diagnosis:")}`),console.log(` ${r.findingCount} finding(s) \u2022 ${r.affectedEntityCount} affected candidate(s) \u2022 ${r.verificationTargetCount} verification target(s) \u2022 ${r.proofPathCount} proof path(s)`),r.unknownCount>0&&console.log(` ${p.dim("\u21B3")} ${p.gray(`${r.unknownCount} explicit unknown(s); inspect JSON evidence before expanding impact claims.`)}`);}else e.graphDiagnosis&&["stale","invalid","project-unresolved"].includes(e.graphDiagnosis.status)&&console.log(` \u26A0\uFE0F Graph-aware diagnosis: ${p.yellow(e.graphDiagnosis.status)} ${p.dim("(refresh workspace model evidence)")}`);if(e.commandCapabilities){let r=e.commandCapabilities;if(console.log(` ${p.bold("Command support:")}`),console.log(` ${p.green("supported")} ${r.supportedCommands.length} \u2022 ${p.yellow("unsupported")} ${r.unsupportedCommands.length} \u2022 ${p.gray("global")} ${r.globalCommands.length}`),r.unsupportedCommands.length>0){let c=r.unsupportedCommands.slice(0,8).join(", "),l=r.unsupportedCommands.length>8?", ...":"";console.log(` ${p.dim("\u21B3")} ${p.gray(`Unsupported here: ${c}${l}`)}`);}}}async function ii(){try{return (await execa("go",["version"],{timeout:a$6(),reject:false})).exitCode===0}catch{return false}}function ke(e,t){let i=[new RegExp(`^Set-Location\\s+-LiteralPath\\s+"([^"]+)"\\s*;\\s*${t}\\s*$`,"i"),new RegExp(`^cd\\s+"([^"]+)"\\s*(?:&&|;)\\s*${t}\\s*$`,"i"),new RegExp(`^cd\\s+'([^']+)'\\s*(?:&&|;)\\s*${t}\\s*$`,"i"),new RegExp(`^cd\\s+(.+?)\\s*(?:&&|;)\\s*${t}\\s*$`,"i")];for(let n of i){let o=e.match(n);if(o?.[1])return {projectPath:o[1].trim()}}return null}function lt(e){return ke(e,"cp\\s+\\.env\\.example\\s+\\.env")||ke(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function oi(e){let t=[{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:"bun\\s+install",command:"bun",args:["install"]},{pattern:"poetry\\s+install",command:"poetry",args:["install"]},{pattern:"poetry\\s+install\\s+--no-root",command:"poetry",args:["install","--no-root"]},{pattern:"poetry\\s+lock",command:"poetry",args:["lock"]},{pattern:"uv\\s+lock",command:"uv",args:["lock"]},{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 i of t){let n=ke(e,i.pattern);if(n)return {projectPath:n.projectPath,command:i.command,args:i.args}}return null}function Xo(){let e=process.env.RAPIDKIT_DOCTOR_FIX_COMMAND_TIMEOUT_MS;if(e){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return 6e4}function dt(e){let t=[/^cd\s+"([^"]+)"\s*(?:&&|;)\s*npm\s+pkg\s+set\s+"scripts\.([^=]+)=([^"]+)"\s*$/i,/^cd\s+'([^']+)'\s*(?:&&|;)\s*npm\s+pkg\s+set\s+'scripts\.([^=]+)=([^']+)'\s*$/i,/^cd\s+(.+?)\s*(?:&&|;)\s*npm\s+pkg\s+set\s+scripts\.([^=\s]+)=(.+)\s*$/i];for(let i of t){let n=e.match(i);if(!(!n?.[1]||!n?.[2]||!n?.[3]))return {projectPath:n[1].trim(),scriptName:n[2].trim(),scriptValue:n[3].trim().replace(/\\"/g,'"').replace(/\\\\/g,"\\")}}return null}function Fe(e){let t=e.trim().match(/^(?:workspai|rapidkit):doctor:repair\s+([A-Za-z0-9_-]+)$/);if(!t?.[1])return null;try{let i=Buffer.from(t[1],"base64url").toString("utf8"),n=JSON.parse(i);if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n;return o.type==="file-create"&&typeof o.path=="string"&&typeof o.content=="string"&&o.overwrite===false||o.type==="file-append"&&typeof o.path=="string"&&Array.isArray(o.lines)&&o.lines.every(s=>typeof s=="string")&&typeof o.ensureNewline=="boolean"||o.type==="file-copy"&&typeof o.sourcePath=="string"&&typeof o.path=="string"&&o.overwrite===false||o.type==="package-json-script"&&typeof o.path=="string"&&typeof o.scriptName=="string"&&typeof o.scriptValue=="string"||o.type==="json-edit"&&typeof o.path=="string"&&Array.isArray(o.edits)&&o.edits.every(s=>{if(!s||typeof s!="object"||Array.isArray(s))return false;let a=s;return typeof a.pointer=="string"&&a.pointer.startsWith("/")&&(typeof a.value=="string"||typeof a.value=="number"||typeof a.value=="boolean"||a.value===null)})||o.type==="env-key-add"&&typeof o.path=="string"&&Array.isArray(o.keys)&&o.keys.every(s=>{if(!s||typeof s!="object"||Array.isArray(s))return false;let a=s;return typeof a.name=="string"&&/^[A-Z_][A-Z0-9_]*$/i.test(a.name)&&typeof a.value=="string"&&(a.comment===void 0||typeof a.comment=="string")})||o.type==="makefile-target"&&typeof o.path=="string"&&typeof o.target=="string"&&/^[A-Za-z0-9_.:-]+$/.test(o.target)&&typeof o.command=="string"&&o.command.trim().length>0&&typeof o.phony=="boolean"?o:null}catch{return null}}function Zo(e){let t=e.operation?er(e.operation):`command:${e.command}`,i=createHash("sha256").update(t).digest("base64url").slice(0,16);return `${e.projectName}:${e.kind}:${i}`}function er(e){switch(e.type){case "file-create":return `file-create:${e.path}:${e.overwrite}:${e.content}`;case "file-append":return `file-append:${e.path}:${e.ensureNewline}:${e.lines.join(`
17
- `)}`;case "file-copy":return `file-copy:${e.sourcePath}:${e.path}:${e.overwrite}`;case "package-json-script":return `package-json-script:${e.path}:${e.scriptName}:${e.scriptValue}`;case "json-edit":return `json-edit:${e.path}:${e.edits.map(t=>`${t.pointer}=${JSON.stringify(t.value)}`).join("|")}`;case "env-key-add":return `env-key-add:${e.path}:${e.keys.map(t=>`${t.name}=${t.value??""}`).join("|")}`;case "makefile-target":return `makefile-target:${e.path}:${e.target}:${e.command}:${e.phony}`;default:return `operation:${JSON.stringify(e)}`}}function ve(e,t){let i=d.resolve(e),n=d.isAbsolute(t)?d.resolve(t):d.resolve(i,t),o=d.relative(i,n);if(o.startsWith("..")||d.isAbsolute(o))throw new Error(`Repair target escapes project boundary: ${t}`);return n}async function tr(e){if(!/^[A-Za-z0-9:_-]+$/.test(e.scriptName))throw new Error(`Unsafe package script name: ${e.scriptName}`);let t=d.join(e.projectPath,"package.json");if(!await u.pathExists(t))throw new Error(`package.json not found at ${t}`);let i=await u.readJSON(t),n=i.scripts&&typeof i.scripts=="object"&&!Array.isArray(i.scripts)?i.scripts:{},o=n[e.scriptName];typeof o=="string"&&o.trim().length>0||(i.scripts={...n,[e.scriptName]:e.scriptValue},await u.writeJSON(t,i,{spaces:2}));}async function nr(e){let t=ve(e.projectPath,e.operation.path);await u.pathExists(t)||(await u.ensureDir(d.dirname(t)),await u.writeFile(t,e.operation.content,"utf8"));}async function ir(e){let t=ve(e.projectPath,e.operation.path);await u.ensureDir(d.dirname(t));let i=await ut(t),n=i.split(/\r?\n/),o=e.operation.lines.filter(a=>!n.includes(a));if(o.length===0)return;let s=i.length===0||i.endsWith(`
18
- `)||!e.operation.ensureNewline?"":`
19
- `;await u.appendFile(t,`${s}${o.join(`
20
- `)}
21
- `,"utf8");}async function or(e){let t=ve(e.projectPath,e.operation.sourcePath),i=ve(e.projectPath,e.operation.path);if(!await u.pathExists(t))throw new Error(`Repair source file not found at ${t}`);await u.pathExists(i)||(await u.ensureDir(d.dirname(i)),await u.copy(t,i,{overwrite:e.operation.overwrite,errorOnExist:false}));}function rr(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}async function sr(e){let t=ve(e.projectPath,e.operation.path);if(!await u.pathExists(t))throw new Error(`JSON repair target not found at ${t}`);let i=await u.readJSON(t);for(let n of e.operation.edits){let o=n.pointer.split("/").slice(1).map(rr);if(o.length===0||o.some(a=>a.length===0))throw new Error(`Unsupported JSON pointer: ${n.pointer}`);let s=i;for(let a of o.slice(0,-1)){let r=s[a];(!r||typeof r!="object"||Array.isArray(r))&&(s[a]={}),s=s[a];}s[o[o.length-1]]=n.value;}await u.writeJSON(t,i,{spaces:2});}async function ar(e){let t=ve(e.projectPath,e.operation.path);await u.ensureDir(d.dirname(t));let i=await ut(t),n=new Set(i.split(/\r?\n/).map(a=>a.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)=/)?.[1]).filter(a=>!!a)),o=[];for(let a of e.operation.keys)n.has(a.name)||(a.comment&&o.push(`# ${a.comment}`),o.push(`${a.name}=${a.value}`));if(o.length===0)return;let s=i.length===0||i.endsWith(`
22
- `)?"":`
23
- `;await u.appendFile(t,`${s}${o.join(`
24
- `)}
25
- `,"utf8");}async function cr(e){let t=ve(e.projectPath,e.operation.path);await u.ensureDir(d.dirname(t));let i=await ut(t);if(new RegExp(`(^|\\n)${e.operation.target.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}:`,"m").test(i))return;let o=[...e.operation.phony?[`.PHONY: ${e.operation.target}`]:[],`${e.operation.target}:`,` ${e.operation.command}`],s=i.length===0||i.endsWith(`
26
- `)?"":`
27
- `;await u.appendFile(t,`${s}${o.join(`
28
- `)}
29
- `,"utf8");}async function ut(e){try{return await u.pathExists(e)?await u.readFile(e,"utf8"):""}catch{return ""}}function lr(e,t){if(/^https?:\/\//i.test(t.trim()))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"manual-url",risk:"safe",executable:false,reason:"Manual guidance URL"};if(lt(t))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"};if(dt(t))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"package-json-script",risk:"guarded",executable:true,reason:"package.json lifecycle script repair"};let i=Fe(t);return i?.type==="file-create"?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"file-create",risk:"safe",executable:true,reason:"Project-scoped file create repair"}:i?.type==="file-append"?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"file-append",risk:"safe",executable:true,reason:"Project-scoped file append repair"}:i?.type==="file-copy"?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-copy",risk:"safe",executable:true,reason:"Project-scoped file copy repair"}:i?.type==="json-edit"?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"json-edit",risk:"guarded",executable:true,reason:"Project-scoped JSON document repair"}:i?.type==="env-key-add"?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-key-add",risk:"guarded",executable:true,reason:"Project-scoped environment key repair"}:i?.type==="makefile-target"?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"makefile-target",risk:"guarded",executable:true,reason:"Project-scoped Makefile target repair"}:ke(t,"rapidkit\\s+init")?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"rapidkit-init",risk:"guarded",executable:true,reason:"RapidKit initializer may mutate dependencies and configs"}:ke(t,"go\\s+mod\\s+tidy")?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"go-mod-tidy",risk:"guarded",executable:true,reason:"Go module graph reconciliation"}:oi(t)?{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"dependency-sync",risk:"guarded",executable:true,reason:"Dependency synchronization command"}:{projectName:e.name,projectPath:e.path,originalCommand:t,kind:"shell",risk:"invasive",executable:true,reason:"Generic shell command"}}function Kt(e,t){return e.repairCapabilities?.find(i=>i.command===t)}function dr(e,t){if(t)return e.probes?.find(i=>i.repairCapability?.id===t.id)}function ur(e){let{step:t,capability:i,operation:n}=e;return n?.type==="file-create"?{title:i?.title??"Create file",summary:`Create ${d.basename(n.path)} if it does not already exist.`,changes:[`create ${n.path}`,"do not overwrite an existing file"]}:n?.type==="file-append"?{title:i?.title??"Append file rules",summary:`Append ${n.lines.length} missing line(s) to ${d.basename(n.path)}.`,changes:[`append to ${n.path}`,...n.lines.map(o=>`ensure line: ${o}`)]}:n?.type==="file-copy"?{title:i?.title??"Copy file",summary:`Copy ${d.basename(n.sourcePath)} to ${d.basename(n.path)} if the target is missing.`,changes:[`copy ${n.sourcePath} -> ${n.path}`,"do not overwrite an existing target file"]}:n?.type==="package-json-script"?{title:i?.title??"Update package.json script",summary:`Ensure package.json script "${n.scriptName}" exists.`,changes:[`set scripts.${n.scriptName}=${n.scriptValue}`]}:n?.type==="json-edit"?{title:i?.title??"Update JSON document",summary:`Apply ${n.edits.length} JSON pointer edit(s) to ${d.basename(n.path)}.`,changes:n.edits.map(o=>`set ${o.pointer}=${JSON.stringify(o.value)}`)}:n?.type==="env-key-add"?{title:i?.title??"Add environment keys",summary:`Ensure ${n.keys.length} environment key(s) exist in ${d.basename(n.path)}.`,changes:n.keys.map(o=>`ensure ${o.name}`)}:n?.type==="makefile-target"?{title:i?.title??"Add Makefile target",summary:`Ensure Makefile target "${n.target}" exists.`,changes:[`target ${n.target}`,`command ${n.command}`,...n.phony?["mark target as .PHONY"]:[]]}:t.kind==="env-copy"?{title:"Create .env from example",summary:"Copy .env.example to .env when the local env file is missing.",changes:["copy .env.example -> .env","do not overwrite existing .env"]}:t.kind==="manual-url"?{title:"Open manual guidance",summary:"Manual remediation is required outside Doctor.",changes:[t.originalCommand]}:{title:i?.title??"Run remediation command",summary:t.reason??"Run the planned remediation command.",changes:[t.originalCommand]}}function pr(e,t){let i=t.endsWith(`
30
- `)?t.slice(0,-1).split(`
31
- `):t.split(`
32
- `);return ["--- /dev/null",`+++ ${e}`,"@@",...i.map(n=>`+${n}`)]}function mr(e){let{step:t,operation:i}=e;if(!i)return {available:false,format:"none",summary:t.executable?"Command execution has no deterministic file diff preview.":"Guidance-only remediation has no file diff preview.",hunks:[]};if(i.type==="file-create")return {available:true,format:"unified",summary:`Create ${i.path} without overwriting an existing file.`,hunks:pr(i.path,i.content)};if(i.type==="file-append")return {available:true,format:"unified",summary:`Append ${i.lines.length} line(s) to ${i.path} when missing.`,hunks:[`--- ${i.path}`,`+++ ${i.path}`,"@@",...i.lines.map(n=>`+${n}`)]};if(i.type==="file-copy")return {available:true,format:"summary",summary:`Copy ${i.sourcePath} to ${i.path} when target is missing.`,hunks:[`copy ${i.sourcePath} -> ${i.path}`],limitations:["Source content is read during apply to avoid stale preview data."]};if(i.type==="package-json-script")return {available:true,format:"unified",summary:`Add scripts.${i.scriptName} to package.json when missing.`,hunks:[`--- ${i.path}`,`+++ ${i.path}`,"@@ scripts",`+ "${i.scriptName}": "${i.scriptValue}"`]};if(i.type==="json-edit")return {available:true,format:"summary",summary:`Apply ${i.edits.length} JSON pointer edit(s) to ${i.path}.`,hunks:i.edits.map(n=>`set ${n.pointer}=${JSON.stringify(n.value)}`)};if(i.type==="env-key-add")return {available:true,format:"unified",summary:`Add ${i.keys.length} env key(s) to ${i.path} when missing.`,hunks:[`--- ${i.path}`,`+++ ${i.path}`,"@@",...i.keys.flatMap(n=>[...n.comment?[`+# ${n.comment}`]:[],`+${n.name}=${n.value}`])]};if(i.type==="makefile-target"){let n=[...i.phony?[`.PHONY: ${i.target}`]:[],`${i.target}:`,` ${i.command}`];return {available:true,format:"unified",summary:`Add Makefile target "${i.target}" when missing.`,hunks:[`--- ${i.path}`,`+++ ${i.path}`,"@@",...n.map(o=>`+${o}`)]}}return {available:false,format:"none",summary:"No deterministic file diff preview is available for this remediation.",hunks:[]}}function fr(e){return e.kind==="manual-url"?{available:false,strategy:"none"}:e.kind==="env-copy"||e.kind==="file-create"||e.kind==="file-append"?{available:true,strategy:"snapshot"}:e.risk==="guarded"||e.risk==="invasive"?{available:true,strategy:"snapshot"}:{available:true,strategy:"idempotent"}}function gr(e){return e.executableInCurrentEnvironment?e.step.executable?e.policyProfile==="enterprise-strict"&&e.step.risk!=="safe"?{state:"review-required",reason:"Enterprise-strict policy requires review before guarded or invasive remediation."}:e.capability?.requiresReview?{state:"review-required",reason:"Repair capability requires human review before applying."}:{state:"ready",reason:"Remediation step is ready for approved execution."}:{state:"guidance-only",reason:e.step.reason??"This remediation is guidance-only."}:{state:"blocked",reason:e.blockedReason??"Required tool or environment is not available."}}function yr(e){let{step:t,issueClass:i,repairIntent:n,operation:o}=e;return t.kind==="manual-url"||n?.mode==="manual-guidance"?"manual-review":t.kind==="dependency-sync"||t.kind==="go-mod-tidy"||i==="dependency"?"dependency-baseline":t.kind==="env-copy"||i==="environment"?"local-environment":t.kind==="package-json-script"||t.kind==="json-edit"||t.kind==="makefile-target"||o?.type==="file-append"&&(i==="test"||i==="quality"||i==="security")?"command-contract":t.kind==="env-key-add"?"local-environment":t.kind==="rapidkit-init"||i==="workspace-contract"?"runtime-governance":o?.type==="file-create"||o?.type==="file-append"?"source-hygiene":"generic-execution"}function Kn(e){return {"dependency-baseline":10,"local-environment":20,"source-hygiene":30,"command-contract":40,"runtime-governance":50,"manual-review":80,"generic-execution":90}[e]}function hr(e){return [...e].sort((i,n)=>{let o=Kn(i.phase)-Kn(n.phase);if(o!==0)return o;let s=i.projectName.localeCompare(n.projectName);return s!==0?s:i.id.localeCompare(n.id)}).map((i,n)=>({...i,order:n+1}))}function kr(e){let t=new Map;for(let i of e){if(i.phase!=="dependency-baseline")continue;let n=t.get(i.projectPath)??[];n.push(i.id),t.set(i.projectPath,n);}return e.map(i=>{if(i.phase==="dependency-baseline")return i;let n=t.get(i.projectPath)??[];return n.length===0?i:{...i,dependsOn:[...new Set([...i.dependsOn,...n])]}})}function vr(e,t,i){if(i.kind==="dependency-sync"||i.kind==="go-mod-tidy")return `${e.path}:dependency-baseline`;let n=Fe(t);if(n?.type==="file-copy")return `${e.path}:file-copy:${n.path}`;if(n?.type==="file-create")return `${e.path}:file-create:${n.path}`;if(n?.type==="file-append")return `${e.path}:file-append:${n.path}`;if(n?.type==="package-json-script")return `${e.path}:package-json-script:${n.path}:${n.scriptName}`;if(n?.type==="json-edit")return `${e.path}:json-edit:${n.path}:${n.edits.map(a=>a.pointer).join(",")}`;if(n?.type==="env-key-add")return `${e.path}:env-key-add:${n.path}:${n.keys.map(a=>a.name).join(",")}`;if(n?.type==="makefile-target")return `${e.path}:makefile-target:${n.path}:${n.target}`;let o=lt(t);if(o)return `${e.path}:file-copy:${d.join(o.projectPath,".env")}`;let s=dt(t);return s?`${e.path}:package-json-script:${d.join(s.projectPath,"package.json")}:${s.scriptName}`:null}function br(e,t){return Kt(e,t)?4:Fe(t)?3:dt(t)?2:lt(t)?1:0}async function Ot(e,t="local"){let i=e.filter(g=>g.fixCommands&&g.fixCommands.length>0),n=i.flatMap(g=>(g.fixCommands??[]).map(k=>({project:g,step:lr(g,k),command:k}))),o=[],s=new Map;for(let g of n){let k=vr(g.project,g.command,g.step);if(!k){o.push(g);continue}let y=br(g.project,g.command),w=s.get(k);if(!w){s.set(k,{index:o.length,priority:y}),o.push(g);continue}y>w.priority&&(o[w.index]=g,s.set(k,{index:w.index,priority:y}));}let a=o,r=null,c=[],l=0,m=0,h=0,v=0;for(let g of a){let{project:k,step:y,command:w}=g,b=y.executable,E;y.kind==="go-mod-tidy"&&(r===null&&(r=await ii()),r||(b=false,E="Go toolchain not available")),b&&(l+=1,y.risk==="safe"&&(m+=1),y.risk==="guarded"&&(h+=1),y.risk==="invasive"&&(v+=1));let $=Kt(k,w),f=dr(k,$),P=$?.operation??Fe(w)??void 0,D=$?.files??(P&&"path"in P?[P.path]:[]),q=f?.repairIntent,x=gr({step:y,capability:$,executableInCurrentEnvironment:b,blockedReason:E,policyProfile:t}),L=yr({step:y,issueClass:f?.issueClass,repairIntent:q,operation:P});c.push({...y,id:Zo({projectName:k.name,kind:y.kind,command:w,operation:P}),phase:L,order:0,dependsOn:[],issueId:$?.issueId,issueClass:f?.issueClass,operationalImpact:f?.operationalImpact,repairIntent:q,files:D,...P?{operation:P}:{},...$?.strategy?{strategy:$.strategy.map(M=>structuredClone(M))}:{},...$?.transaction?{transaction:structuredClone($.transaction)}:{},preview:ur({step:y,capability:$,operation:P}),diffPreview:mr({step:y,operation:P}),verifyCommand:$?.verifyCommand,refreshCommands:$?.refreshCommands??["npx workspai doctor project --json"],rollback:fr(y),studioStatus:x,executableInCurrentEnvironment:b,blockedReason:E});}let C=kr(hr(c));return {schemaVersion:"doctor-remediation-plan-v2",generatedAt:new Date().toISOString(),policyProfile:t,fixableProjects:i.length,totalSteps:C.length,executableSteps:l,risk:{safe:m,guarded:h,invasive:v},steps:C}}function Bn(e){let t=e instanceof Error?e.message:String(e),i=["ETIMEDOUT","ECONNRESET","ECONNREFUSED","EAI_AGAIN","ENOTFOUND","network","503","504"],n=t.toLowerCase();return i.some(o=>n.includes(o.toLowerCase()))}async function wr(e,t){let i=e.get(t);if(i)return i;let n=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=d.basename(t).replace(/[^a-zA-Z0-9._-]/g,"_"),s=d.join(t,".workspai","reports","fix-snapshots",`${o}-${n}`);await u.ensureDir(s);let a=[".env","package.json","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"],r=new Map;for(let l of a){let m=d.join(t,l);if(!await u.pathExists(m))continue;let h=d.join(s,l);await u.ensureDir(d.dirname(h)),await u.copy(m,h,{overwrite:true}),r.set(m,h);}let c={snapshotRoot:s,files:r,missingFiles:new Set};return e.set(t,c),c}async function Ee(e,t){if(e.files.has(t)||e.missingFiles.has(t))return;if(!await u.pathExists(t)){e.missingFiles.add(t);return}let i=d.basename(t),n=d.join(e.snapshotRoot,"ad-hoc",`${Date.now()}-${Math.random().toString(36).slice(2,8)}-${i}`);await u.ensureDir(d.dirname(n)),await u.copy(t,n,{overwrite:true}),e.files.set(t,n);}async function jr(e){for(let[t,i]of e.files.entries())await u.pathExists(i)&&(await u.ensureDir(d.dirname(t)),await u.copy(i,t,{overwrite:true}));for(let t of e.missingFiles)await u.pathExists(t)&&await u.remove(t);}async function xr(e){let t=await ct(e,{allowNonRapidkit:true});return {issues:t.issues.length,healthy:t.issues.length===0}}async function Ft(e){let t=[];for(let i of e){let n=await ct(i.path,{allowNonRapidkit:true});for(let o of n.issues)typeof o=="string"&&o.trim()&&t.push(`${i.name}: ${o.trim()}`);}return t.slice(0,24)}function Wn(e){let t=[];for(let i of e)for(let n of i.issues)typeof n=="string"&&n.trim()&&t.push(`${i.name}: ${n.trim()}`);return t.slice(0,24)}async function pe(e,t=false,i={}){let n=await Ot(e,i.policyProfile);i.artifactRoot&&(i.planOnly||t)&&await Mt(i.artifactRoot,n,i.artifactMirrorRoots);let o=e.filter(f=>f.fixCommands&&f.fixCommands.length>0),s=[],a=i.json===true,r=(...f)=>{a||console.log(...f);},c$2=null,l=n.steps.some(f=>f.kind==="go-mod-tidy"&&!f.executableInCurrentEnvironment),m=new Map;if(o.length===0){if(a||console.log(p.green(`
33
- \u2705 No fixes needed - all projects are healthy!`)),t){let f=c({appliedFixes:[],remainingBlockers:[],verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,f,i.artifactMirrorRoots),await Ae(i.artifactRoot,f,i.historyScope??"project")),f}return}if(!a){console.log(p.bold.cyan(`
34
- \u{1F527} Available Fixes:
35
- `));for(let f of o){let P=f.fixCommands??[];console.log(p.bold(`Project: ${p.yellow(f.name)}`)),P.forEach((D,q)=>{console.log(` ${q+1}. ${p.cyan(rt(f,D))}`);}),console.log();}}if(i.planOnly){if(i.json){console.log(JSON.stringify(n,null,2));return}console.log(p.bold(`
36
- \u{1F9ED} Remediation Plan
37
- `)),console.log(p.gray(`Executable steps: ${n.executableSteps}/${n.totalSteps} | risk: safe=${n.risk.safe}, guarded=${n.risk.guarded}, invasive=${n.risk.invasive}`));for(let f of n.steps){let P=o.find(q=>q.path===f.projectPath),D=f.executableInCurrentEnvironment?p.green("ready"):p.yellow(`blocked${f.blockedReason?` (${f.blockedReason})`:""}`);console.log(` - ${p.cyan(f.projectName)} [${f.risk}] ${P?rt(P,f.originalCommand):f.preview.title} ${p.gray(`=> ${D}`)}`);}console.log(p.gray(`
38
- Use --apply to execute this plan non-interactively, or --fix for interactive confirmation.`));return}let h=n.executableSteps,v=n.risk.safe,C=n.risk.guarded,g=n.risk.invasive;if(h===0){if(a||(console.log(p.gray("\u{1F4A1} No automatic fixes can be applied right now.")),l&&console.log(p.gray(" Install Go to enable go mod tidy fixes, then rerun `workspai doctor workspace --fix`."))),t){let f=c({appliedFixes:[],remainingBlockers:await Ft(e),verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,f,i.artifactMirrorRoots),await Ae(i.artifactRoot,f,i.historyScope??"project")),f}return}if(!t){a||console.log(p.gray('\u{1F4A1} Run "npx workspai doctor workspace --fix" to apply fixes automatically'));return}if(a||console.log(p.gray(`Risk policy: safe=${v}, guarded=${C}, invasive=${g}. Guarded/invasive fixes use snapshot + rollback.`)),!i.skipConfirmation){let{confirm:f}=await b$1([{type:"confirm",name:"confirm",message:`Apply ${o.reduce((P,D)=>P+(D.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!f){a||console.log(p.yellow(`
39
- \u26A0\uFE0F Fixes cancelled by user`));let P=c({appliedFixes:[],remainingBlockers:await Ft(e),verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,P,i.artifactMirrorRoots),await Ae(i.artifactRoot,P,i.historyScope??"project")),P}}a||console.log(p.bold.cyan(`
40
- \u{1F680} Applying fixes...
41
- `));let k=new Set,y=new Map(o.map(f=>[f.path,f])),w=new Set,b$2=Xo(),E=process.env.RAPIDKIT_DOCTOR_FIX_ALLOW_GUARDED_COMMANDS==="1"||process.env.RAPIDKIT_DOCTOR_FIX_ALLOW_DEPENDENCY_SYNC==="1",$="";for(let f of n.steps){let P=y.get(f.projectPath);if(!P)continue;let D=f.originalCommand;a||$!==f.projectName&&($=f.projectName,console.log(p.bold(`Fixing ${p.cyan(f.projectName)}...`)));let q=`${f.projectPath}::${D}`;if(!k.has(q)){k.add(q);try{if(r(p.gray(` ${rt(P,D)}`)),f.kind==="manual-url"){r(p.yellow(` \u2139 Manual action required: open ${D}`)),r(p.green(` \u2705 Recorded as guidance
42
- `));continue}if(!f.executable||!f.executableInCurrentEnvironment){let X=f.blockedReason?`: ${f.blockedReason}`:"";r(p.yellow(` \u26A0 Step is non-executable by policy${X}`)),r(p.green(` \u2705 Recorded as guidance
43
- `));continue}let x=Fe(D),M=f.risk!=="safe"||x?.type==="file-create"||x?.type==="file-append"||x?.type==="file-copy"||x?.type==="json-edit"||x?.type==="env-key-add"||x?.type==="makefile-target"?await wr(m,f.projectPath):null;M&&x?.type==="file-create"&&await Ee(M,x.path),M&&x?.type==="file-append"&&await Ee(M,x.path),M&&x?.type==="file-copy"&&await Ee(M,x.path),M&&x?.type==="json-edit"&&await Ee(M,x.path),M&&x?.type==="env-key-add"&&await Ee(M,x.path),M&&x?.type==="makefile-target"&&await Ee(M,x.path);let oe=lt(D);if(oe){let X=d.join(oe.projectPath,".env.example"),j=d.join(oe.projectPath,".env");if(!await u.pathExists(X))throw new Error(`.env.example not found at ${X}`);if(await u.pathExists(j)){r(p.green(` \u2705 .env already exists
44
- `));continue}await u.copy(X,j,{overwrite:false,errorOnExist:false}),w.add(f.projectPath),s.push({path:j,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
45
- `));continue}if(x?.type==="file-copy"){await or({projectPath:f.projectPath,operation:x}),w.add(f.projectPath),s.push({path:x.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
46
- `));continue}let Le=dt(D);if(Le){await tr(Le),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
47
- `));continue}if(x?.type==="file-create"){await nr({projectPath:f.projectPath,operation:x}),w.add(f.projectPath),s.push({path:x.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
48
- `));continue}if(x?.type==="file-append"){await ir({projectPath:f.projectPath,operation:x}),w.add(f.projectPath),s.push({path:x.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
49
- `));continue}if(x?.type==="json-edit"){await sr({projectPath:f.projectPath,operation:x}),w.add(f.projectPath),s.push({path:x.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
50
- `));continue}if(x?.type==="env-key-add"){await ar({projectPath:f.projectPath,operation:x}),w.add(f.projectPath),s.push({path:x.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
51
- `));continue}if(x?.type==="makefile-target"){await cr({projectPath:f.projectPath,operation:x}),w.add(f.projectPath),s.push({path:x.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
52
- `));continue}let Ve=ke(D,"(?:npx\\s+workspai|rapidkit)\\s+init");if(Ve){if(!E){r(p.yellow(" \u26A0 workspai init is a guarded dependency/setup action; recording guidance instead of executing. Set RAPIDKIT_DOCTOR_FIX_ALLOW_GUARDED_COMMANDS=1 to opt in.")),s.push({path:f.projectPath,action:f.kind,outcome:"guidance",projectName:f.projectName,command:D,detail:"Guarded setup command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}await execa("rapidkit",["init"],{cwd:Ve.projectPath,shell:c$1(),stdio:a?"pipe":"inherit",timeout:b$2,forceKillAfterDelay:1e3}),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
53
- `));continue}let Je=ke(D,"go\\s+mod\\s+tidy");if(Je){if(c$2===null&&(c$2=await ii()),!c$2){r(p.yellow(" \u26A0 Go toolchain is not installed \u2014 skipping go mod tidy; install Go to apply this fix.")),r(p.green(` \u2705 Recorded as guidance
54
- `));continue}await execa("go",["mod","tidy"],{cwd:Je.projectPath,shell:c$1(),stdio:a?"pipe":"inherit",timeout:b$2,forceKillAfterDelay:1e3}),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
55
- `));continue}let V=oi(D);if(V){if(!E&&new Set(["npm","pnpm","yarn","bun","poetry","pip","pip3","pipenv"]).has(V.command)){r(p.yellow(" \u26A0 dependency sync is a guarded install action; recording guidance instead of executing. Set RAPIDKIT_DOCTOR_FIX_ALLOW_GUARDED_COMMANDS=1 to opt in.")),s.push({path:f.projectPath,action:f.kind,outcome:"guidance",projectName:f.projectName,command:D,detail:"Guarded dependency command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}let j=2,S,O=V.command==="poetry"&&V.args[0]==="install"?{...process.env,POETRY_CACHE_DIR:d.join(V.projectPath,".workspai","cache","python","poetry")}:process.env;for(let _=1;_<=j;_+=1)try{await execa(V.command,V.args,{cwd:V.projectPath,env:O,shell:c$1(),stdio:a?"pipe":"inherit",timeout:b$2,forceKillAfterDelay:1e3}),S=null;break}catch(te){if(S=te,_<j&&Bn(te)){r(p.yellow(` \u26A0 Retrying dependency sync (${_}/${j-1})...`));continue}throw te}if(S)throw S;w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:D}),r(p.green(` \u2705 Success
56
- `));continue}let Ie=f.kind==="shell"?2:1,me;for(let X=1;X<=Ie;X+=1)try{await execa(D,{shell:true,stdio:a?"pipe":"inherit",timeout:b$2,forceKillAfterDelay:1e3}),me=null;break}catch(j){if(me=j,X<Ie&&Bn(j)){r(p.yellow(` \u26A0 Retrying command (${X}/${Ie-1})...`));continue}throw j}if(me)throw me;a||console.log(p.green(` \u2705 Success
57
- `)),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:D});}catch(x){let L=Fe(D);if(f.risk!=="safe"||L?.type==="file-create"||L?.type==="file-append"||L?.type==="file-copy"||L?.type==="json-edit"||L?.type==="env-key-add"||L?.type==="makefile-target"){let M=m.get(f.projectPath);if(M)try{await jr(M),a||console.log(p.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(oe){a||console.log(p.red(` \u274C Rollback failed: ${oe instanceof Error?oe.message:String(oe)}`));}}a||console.log(p.red(` \u274C Failed: ${x instanceof Error?x.message:String(x)}
58
- `)),s.push({path:f.projectPath,action:f.kind,outcome:"failed",projectName:f.projectName,command:D,detail:x instanceof Error?x.message:String(x)});}}}for(let f of o)if(w.has(f.path))try{let P=await xr(f.path);a||console.log(P.healthy?p.green(` \u2705 Post-fix verification passed for ${f.name}`):p.yellow(` \u26A0 Post-fix verification: ${P.issues} issue(s) remain for ${f.name}`));}catch(P){a||console.log(p.yellow(` \u26A0 Post-fix verification skipped: ${P instanceof Error?P.message:String(P)}`));}if(a||console.log(p.bold.green(`
59
- \u2705 Fix process completed!`)),t){let f=c({appliedFixes:s,remainingBlockers:await Ft(e),verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,f,i.artifactMirrorRoots),await Ae(i.artifactRoot,f,i.historyScope??"project")),f}}function qe(e,t){let i=at(t),n=Number(e?.errors??0),o=Number(e?.warnings??0);return i.exitOnErrors&&n>0?1:i.exitOnWarnings&&o>0?i.warningExitCode:0}function Hn(e,t,i){let n=qe(e,t);return i?.appliedFixes.some(s=>s.outcome==="failed")??false?Math.max(n,1):n}async function Rs(e={}){let t=at({profile:e.profile,strict:e.strict,ci:e.ci}),i=!!(e.fix||e.plan||e.apply),n=typeof e.workspace=="string"&&e.workspace.trim().length>0?d.resolve(e.workspace):null,o=!n&&!e.workspace&&!e.project&&i?await He(process.cwd()):null,s=!!e.workspace||!!o,a=!!e.project&&!s;if(e.json||console.log(p.bold.cyan(`
60
- \u{1FA7A} Workspai Health Check
61
- `)),s){let r=n??o??await He(process.cwd());r||(f.error("No Workspai workspace found in current directory or parents"),f.info('Run this command from within a workspace, or use "workspai doctor" for system check'),process.exit(1)),e.json||(o&&console.log(p.gray("\u2139\uFE0F Detected workspace context; enabling workspace checks for --fix")),console.log(p.bold(`Workspace: ${p.cyan(d.basename(r))}`)),console.log(p.gray(`Path: ${r}`)));let c$1=!(e.plan||e.fix||e.apply),l=await At(r,c$1,t);if(e.json||(l.projectScanCached&&console.log(p.gray(`\u2139\uFE0F Reused cached project scan${l.projectScanCachePath?` (${d.basename(l.projectScanCachePath)})`:""}`)),l.evidencePath&&console.log(p.gray(`\u2139\uFE0F Evidence saved: ${l.evidencePath}`))),e.json){let g,k=e.plan||e.fix||e.apply?await Ot(l.projects,t.name):void 0,y=k?await Mt(r,k):void 0,w;(e.fix||e.apply)&&!e.plan&&(g=await pe(l.projects,true,{skipConfirmation:e.apply===true||e.fix===true,json:true,policyProfile:t.name})??c({appliedFixes:[],remainingBlockers:[],verifyRecommended:b}),l=await At(r,false,t),g={...g,remainingBlockers:Wn(l.projects)},w=await $e(r,g),await Ae(r,g,"workspace"));let b$1=l.projects.map(ee),E=b$1.reduce((P,D)=>P+D.blockingFindings,0),$=b$1.reduce((P,D)=>P+D.advisoryFindings,0),f={contract:Re(),policyProfile:t,workspace:{name:l.workspaceName,path:r},cache:{projectScan:l.projectScanCached??false,projectScanPath:l.projectScanCachePath,evidencePath:l.evidencePath},healthScore:l.healthScore,evidenceFreshness:l.evidenceFreshness,system:{python:l.python,poetry:l.poetry,pipx:l.pipx,rapidkitCore:l.rapidkitCore,versions:{core:l.coreVersion,npm:l.npmVersion}},projects:l.projects.map(P=>Tn(P)),summary:{totalProjects:l.projects.length,totalIssues:l.projects.reduce((P,D)=>P+D.issues.length,0),verdict:l.healthScore?.verdict??"passed",blockingFindings:E,advisoryFindings:$,projectAdvisoryWarningProjects:b$1.filter(P=>P.advisoryFindings>0).length,projectAdvisoryWarnings:$,hasSystemErrors:[l.python,l.rapidkitCore].some(P=>P.status==="error"),scopeProvenance:l.scopeProvenance},driftDelta:l.driftDelta,scoreBreakdown:l.scoreBreakdown??[],...k?{remediationPlan:k,remediationPlanPath:y}:{},...g?{appliedFixes:g.appliedFixes,remainingBlockers:g.remainingBlockers,verifyRecommended:g.verifyRecommended,fixResult:g,fixResultPath:w}:{}};return e.quiet||console.log(JSON.stringify(f,null,2)),Hn(l.healthScore,{profile:t.name},g)}if(l.healthScore){let g=l.healthScore,k=Math.round(g.passed/g.total*100),y=k>=80?p.green:k>=50?p.yellow:p.red,w="\u2588".repeat(Math.floor(k/5))+"\u2591".repeat(20-Math.floor(k/5));console.log(p.bold(`
62
- \u{1F4CA} Health Score:`)),console.log(` ${y(`${k}%`)} ${p.gray(w)}`),console.log(` ${p.green(`\u2705 ${g.passed} passed`)} ${p.gray("|")} ${p.yellow(`\u26A0\uFE0F ${g.warnings} warnings`)} ${p.gray("|")} ${p.red(`\u274C ${g.errors} errors`)}`);}console.log(p.bold(`
63
-
64
- System Tools:
65
- `)),B(l.python,"Python"),B(l.poetry,"Poetry"),B(l.pipx,"pipx"),B(l.go,"Go"),B(l.rapidkitCore,"RapidKit Core"),co({coreVersion:l.coreVersion,npmVersion:l.npmVersion})&&(console.log(p.yellow(`
66
- \u26A0\uFE0F Version mismatch: Core ${l.coreVersion} / CLI ${l.npmVersion}`)),console.log(p.gray(" Consider updating to compatible major versions."))),l.projects.length>0?(console.log(p.bold(`
67
- \u{1F4E6} Projects (${l.projects.length}):`)),l.projects.forEach(g=>Gn(g,l.rapidkitCore))):(console.log(p.bold(`
68
- \u{1F4E6} Projects:`)),console.log(p.gray(" No Workspai projects found in workspace")));let m=l.projects.map(ee),h=m.reduce((g,k)=>g+k.blockingFindings,0),v=m.reduce((g,k)=>g+k.advisoryFindings,0),C=[l.python,l.rapidkitCore].some(g=>g.status==="error");if(C||h>0||v>0)if(console.log(p.bold.yellow(`
69
- \u26A0\uFE0F Doctor verdict: ${l.healthScore?.verdict??"attention"} \xB7 ${h} blocking finding(s) \xB7 ${v} advisory finding(s)`)),C&&console.log(p.bold.red("\u274C System requirements not met")),e.plan)await pe(l.projects,false,{planOnly:true,json:e.json,policyProfile:t.name,artifactRoot:r,historyScope:"workspace"});else if(e.fix||e.apply){if(await pe(l.projects,true,{skipConfirmation:e.apply===true,policyProfile:t.name,artifactRoot:r,historyScope:"workspace"}),!e.json){let g=await At(r,false,t),k=g.projects.map(ee).reduce((w,b)=>w+b.blockingFindings,0),y=[g.python,g.rapidkitCore].some(w=>w.status==="error");y||k>0?(console.log(p.bold.yellow(`
70
- \u26A0\uFE0F Post-fix verification found ${k} remaining issue(s)`)),y&&console.log(p.bold.red("\u274C System requirements still not met"))):console.log(p.bold.green(`
71
- \u2705 Post-fix verification passed. Workspace is healthy.`)),g.projectScanCached&&console.log(p.gray(`\u2139\uFE0F Reused cached project scan${g.projectScanCachePath?` (${d.basename(g.projectScanCachePath)})`:""}`)),g.evidencePath&&console.log(p.gray(`\u2139\uFE0F Evidence refreshed: ${g.evidencePath}`));}}else h>0&&await pe(l.projects,false);else console.log(p.bold.green(`
72
- \u2705 All checks passed! Workspace is healthy.`));return qe(l.healthScore,{profile:t.name})}else if(a){let r=await Jo(process.cwd());if(!r){let b=await He(process.cwd());if(e.json){let E={contract:Re(),policyProfile:t,scope:"project",status:"error",generatedAt:new Date().toISOString(),workspace:b?{name:d.basename(b),path:b}:null,project:null,healthScore:{total:1,passed:0,warnings:0,errors:1,verdict:"blocked",components:{host:{total:0,passed:0,warnings:0,errors:0},projects:{total:1,passed:0,warnings:0,errors:1}}},summary:{totalProjects:0,totalIssues:1,projectAdvisoryWarningProjects:0,projectAdvisoryWarnings:0,hasSystemErrors:false},error:{code:b?"doctor.project.scope.not_found_in_workspace":"doctor.project.scope.not_found",message:b?"No project found in the current directory within this workspace.":"No Workspai project found in the current directory or parents.",recommendation:b?"Run this command from inside a registered project directory, or use doctor workspace for workspace-wide checks.":"Run this command from within a project, or use doctor workspace from a Workspai workspace.",relatedCommands:b?["npx workspai doctor workspace --json","npx workspai workspace list --json"]:["npx workspai doctor workspace --json","npx workspai adopt --json"]}};return e.quiet||console.log(JSON.stringify(E,null,2)),1}b?(f.error("No backend project found in current directory within this workspace"),f.info("Run this command from inside a project directory in the workspace")):f.error("No Workspai project found in current directory or parents"),f.info('Run this command from within a project, or use "workspai doctor workspace" for workspace checks'),process.exit(1);}let c$1=await _n(r,t),l=c$1.workspacePath?On(c$1.workspacePath):null;if(e.json){let b$1,E=e.plan||e.fix||e.apply?await Ot([c$1.project],t.name):void 0,$=r,f=[],P=E?await Mt($,E,f):void 0,D;(e.fix||e.apply)&&!e.plan&&(b$1=await pe([c$1.project],true,{skipConfirmation:e.apply===true||e.fix===true,json:true,policyProfile:t.name})??c({appliedFixes:[],remainingBlockers:[],verifyRecommended:b}),c$1=await _n(r,t),b$1={...b$1,remainingBlockers:Wn([c$1.project])},D=await $e($,b$1,f),await Ae($,b$1,"project"));let q=On(c$1.project.path),x=ee(c$1.project),L={contract:Re(),policyProfile:t,scope:"project",workspace:l?{name:d.basename(l),path:l}:null,project:{...Tn(c$1.project),path:q},evidencePath:c$1.evidencePath,healthScore:c$1.healthScore,evidenceFreshness:c$1.evidenceFreshness,system:{python:c$1.python,poetry:c$1.poetry,pipx:c$1.pipx,go:c$1.go,rapidkitCore:c$1.rapidkitCore},summary:{totalProjects:1,totalIssues:c$1.project.issues.length,verdict:x.verdict,probeSummary:x,blockingFindings:x.blockingFindings,advisoryFindings:x.advisoryFindings,projectAdvisoryWarningProjects:x.advisoryFindings>0?1:0,projectAdvisoryWarnings:x.advisoryFindings,hasSystemErrors:[c$1.python,c$1.rapidkitCore].some(M=>M.status==="error"),scopeProvenance:c$1.scopeProvenance},driftDelta:c$1.driftDelta,scoreBreakdown:c$1.scoreBreakdown??[],...E?{remediationPlan:E,remediationPlanPath:P}:{},...b$1?{appliedFixes:b$1.appliedFixes,remainingBlockers:b$1.remainingBlockers,verifyRecommended:b$1.verifyRecommended,fixResult:b$1,fixResultPath:D}:{}};return e.quiet||console.log(JSON.stringify(L,null,2)),Hn(c$1.healthScore,{profile:t.name},b$1)}console.log(p.bold(`Project: ${p.cyan(d.basename(r))}`)),console.log(p.gray(`Path: ${r}`)),c$1.workspacePath&&console.log(p.gray(`Workspace: ${d.basename(c$1.workspacePath)}`)),c$1.evidencePath&&console.log(p.gray(`\u2139\uFE0F Evidence saved: ${c$1.evidencePath}`));let m=c$1.healthScore,h=m.total>0?Math.round(m.passed/m.total*100):0,v=h>=80?p.green:h>=50?p.yellow:p.red,C="\u2588".repeat(Math.floor(h/5))+"\u2591".repeat(20-Math.floor(h/5));console.log(p.bold(`
73
- \u{1F4CA} Health Score:`)),console.log(` ${v(`${h}%`)} ${p.gray(C)}`),console.log(` ${p.green(`\u2705 ${m.passed} passed`)} ${p.gray("|")} ${p.yellow(`\u26A0\uFE0F ${m.warnings} warnings`)} ${p.gray("|")} ${p.red(`\u274C ${m.errors} errors`)}`),console.log(p.bold(`
74
-
75
- System Tools:
76
- `)),B(c$1.python,"Python"),B(c$1.poetry,"Poetry"),B(c$1.pipx,"pipx"),B(c$1.go,"Go"),B(c$1.rapidkitCore,"RapidKit Core"),console.log(p.bold(`
77
- \u{1F4E6} Project (1):`)),Gn(c$1.project,c$1.rapidkitCore);let g=[c$1.python,c$1.rapidkitCore].some(b=>b.status==="error"),k=ee(c$1.project),y=k.blockingFindings,w=k.advisoryFindings;if(g||y>0||w>0)if(console.log(p.bold.yellow(`
78
- \u26A0\uFE0F Doctor verdict: ${k.verdict} \xB7 ${y} blocking finding(s) \xB7 ${w} advisory finding(s)`)),g&&console.log(p.bold.red("\u274C System requirements not met")),e.plan){let b=c$1.workspacePath??r,E=c$1.workspacePath&&d.resolve(c$1.workspacePath)!==d.resolve(r)?[r]:[];await pe([c$1.project],false,{planOnly:true,json:e.json,policyProfile:t.name,artifactRoot:b,artifactMirrorRoots:E,historyScope:"project"});}else if(e.fix||e.apply){let b=c$1.workspacePath??r,E=c$1.workspacePath&&d.resolve(c$1.workspacePath)!==d.resolve(r)?[r]:[];await pe([c$1.project],true,{skipConfirmation:e.apply===true,policyProfile:t.name,artifactRoot:b,artifactMirrorRoots:E,historyScope:"project"});}else y>0&&await pe([c$1.project],false);else console.log(p.bold.green(`
79
- \u2705 All checks passed! Project is healthy.`));return qe(c$1.healthScore,{profile:t.name})}else {let r=await _t(),c=r.python,l=r.poetry,m=r.pipx,h=r.go,v=r.rapidkitCore,C=[c,l,m,h,v],g=Gt(C,[]),k=[c,v].filter(w=>w.status==="error").length;if(e.json){let w={contract:Re(),policyProfile:t,scope:"system",status:k>0?"error":"ok",generatedAt:new Date().toISOString(),healthScore:g,system:{python:c,poetry:l,pipx:m,go:h,rapidkitCore:v},summary:{totalChecks:C.length,errors:k,warnings:C.filter(b=>b.status==="warn").length,recommendedScopes:["workspace","project"]},nextActions:["npx workspai doctor workspace --json","npx workspai doctor project --json"]};return e.quiet||console.log(JSON.stringify(w,null,2)),(e.strict||e.ci)&&k>0?1:0}return console.log(p.bold(`System Tools:
80
- `)),B(c,"Python"),B(l,"Poetry"),B(m,"pipx"),B(h,"Go"),B(v,"RapidKit Core"),[c,v].some(w=>w.status==="error")?(console.log(p.bold.red(`
81
- \u274C Some required tools are missing`)),(e.fix||e.apply)&&console.log(p.gray(`
82
- Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "workspai doctor workspace --fix"`)),console.log(p.gray(`
83
- Tip: Run "workspai doctor workspace" for workspace-wide checks, or "workspai doctor project" for the current project`))):(console.log(p.bold.green(`
84
- \u2705 All required tools are installed!`)),(e.fix||e.apply)&&console.log(p.gray(`
85
- Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "workspai doctor workspace --fix"`)),console.log(p.gray(`
86
- Tip: Run "workspai doctor workspace" for workspace-wide checks, or "workspai doctor project" for the current project`))),console.log(""),(e.strict||e.ci)&&k>0?1:0}}export{It as a,at as b,dt as c,Fe as d,er as e,ve as f,tr as g,nr as h,ir as i,or as j,rr as k,sr as l,ar as m,cr as n,qe as o,Hn as p,Rs as q};
@@ -1 +0,0 @@
1
- export{a as runWorkspaceStage}from'./chunk-F4KBYFZ5.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-GHB6QMQH.js';
File without changes