workspai 0.52.2 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +2 -0
  2. package/contracts/artifact-remediation-plan.v1.json +1 -0
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +36 -0
  4. package/contracts/extension-cli-compatibility.v1.json +24 -2
  5. package/contracts/pipeline-last-run.v1.json +6 -1
  6. package/contracts/published-contract-catalog.v1.json +113 -2
  7. package/contracts/runtime-command-surface.v1.json +216 -5
  8. package/contracts/studio-card-repair-capabilities.v1.json +378 -0
  9. package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +78 -0
  10. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +249 -0
  11. package/contracts/workspace-intelligence-chain.v1.json +6 -0
  12. package/contracts/workspace-repair-capabilities.v1.json +316 -0
  13. package/dist/analyze-AAZEJ4FC.js +1 -0
  14. package/dist/artifact-remediation-plan-CJSPCMWA.js +1 -0
  15. package/dist/autopilot-release-LZWNQQLY.js +1 -0
  16. package/dist/chunk-27AXFTKW.js +1 -0
  17. package/dist/{chunk-OTDGTAZJ.js → chunk-2FJW6GSW.js} +1 -1
  18. package/dist/chunk-3DONU3DU.js +1 -0
  19. package/dist/chunk-44VJHNZB.js +1 -0
  20. package/dist/chunk-5XDPQ3CB.js +1 -0
  21. package/dist/chunk-7AR5PDLD.js +1 -0
  22. package/dist/chunk-7KKP7RNB.js +3 -0
  23. package/dist/chunk-AMB42V2F.js +1 -0
  24. package/dist/chunk-BYVTHIC3.js +2 -0
  25. package/dist/chunk-E5YYVFM2.js +1 -0
  26. package/dist/{chunk-6PBSAAS5.js → chunk-EBKYSDCX.js} +1 -1
  27. package/dist/chunk-FQLB4BIC.js +7 -0
  28. package/dist/{chunk-ICLYL3N5.js → chunk-FZCYTRBQ.js} +1 -1
  29. package/dist/{chunk-ZVOEPWQM.js → chunk-GDU7VP6G.js} +1 -1
  30. package/dist/chunk-H7P7SSUW.js +75 -0
  31. package/dist/chunk-HOVJUP7K.js +8 -0
  32. package/dist/{chunk-MZFSINY7.js → chunk-HRN5J6PW.js} +12 -12
  33. package/dist/chunk-HY3RMPW5.js +10 -0
  34. package/dist/chunk-KFKZOPZC.js +1 -0
  35. package/dist/{chunk-HPWLSLMC.js → chunk-KVUYAYTY.js} +1 -1
  36. package/dist/chunk-MQ73VS4E.js +2 -0
  37. package/dist/{chunk-2OIBHUVH.js → chunk-MRFN5ZQP.js} +1 -1
  38. package/dist/{chunk-4UVGTFOX.js → chunk-NYHVCFBT.js} +1 -1
  39. package/dist/{chunk-IO54DFWR.js → chunk-OLX6LX77.js} +1 -1
  40. package/dist/chunk-OUBBBC7T.js +36 -0
  41. package/dist/{chunk-WJY7ZXVJ.js → chunk-P7K5RHJC.js} +1 -1
  42. package/dist/chunk-QZ7PNMVP.js +1 -0
  43. package/dist/chunk-RA24WQLF.js +1 -0
  44. package/dist/chunk-RMXXK64P.js +4 -0
  45. package/dist/{chunk-PTTZPDLX.js → chunk-S7Z4DP3P.js} +1 -1
  46. package/dist/chunk-SJLUE6AY.js +1 -0
  47. package/dist/chunk-SUV7Y2FH.js +3 -0
  48. package/dist/chunk-T6JI7GYZ.js +88 -0
  49. package/dist/chunk-USMLRNZ7.js +5 -0
  50. package/dist/chunk-WD2XDMGB.js +1 -0
  51. package/dist/chunk-WIO6L24E.js +2 -0
  52. package/dist/{chunk-QURMI7ID.js → chunk-WZA5ISAQ.js} +1 -1
  53. package/dist/chunk-XVRJVKOX.js +1 -0
  54. package/dist/{create-ESK3CQPK.js → create-R6A7EHQZ.js} +1 -1
  55. package/dist/{doctor-MYRJ5BFF.js → doctor-KNIYGDM7.js} +1 -1
  56. package/dist/index.d.ts +92 -23
  57. package/dist/index.js +246 -244
  58. package/dist/pipeline-PVCLAQDI.js +5 -0
  59. package/dist/{project-intelligence-lens-Q4SZDI2N.js → project-intelligence-lens-ZOAWXYC5.js} +1 -1
  60. package/dist/project-test-coverage-44ZPCOPV.js +1 -0
  61. package/dist/{verified-goal-23HZPMRK.js → verified-goal-MCSNMA3P.js} +1 -1
  62. package/dist/{workspace-LSOZM2CG.js → workspace-B53XH35L.js} +1 -1
  63. package/dist/{workspace-agent-sync-RZBQXCNJ.js → workspace-agent-sync-446AXPHJ.js} +1 -1
  64. package/dist/{workspace-archive-ZOWQXWJ6.js → workspace-archive-VHUPOBAV.js} +1 -1
  65. package/dist/{workspace-context-IYJKO5BN.js → workspace-context-XSECHC7O.js} +1 -1
  66. package/dist/{workspace-contract-AZFISDLS.js → workspace-contract-AYFTZIKM.js} +1 -1
  67. package/dist/workspace-explain-SZI2WAAD.js +1 -0
  68. package/dist/workspace-explain-contract-N2XQHAPM.js +1 -0
  69. package/dist/{workspace-feedback-LIHEWTNV.js → workspace-feedback-WXE7NVMV.js} +1 -1
  70. package/dist/{workspace-foundation-H5UTAUXQ.js → workspace-foundation-FFNCK5ZD.js} +1 -1
  71. package/dist/{workspace-graph-stream-KUDOZE73.js → workspace-graph-stream-AJPS45FD.js} +1 -1
  72. package/dist/{workspace-history-HULG5EFN.js → workspace-history-YY7YRDOH.js} +1 -1
  73. package/dist/{workspace-intelligence-A4UE4DZK.js → workspace-intelligence-FWRB47EJ.js} +1 -1
  74. package/dist/{workspace-intelligence-evaluation-AOLGHYHC.js → workspace-intelligence-evaluation-UP2K3L35.js} +1 -1
  75. package/dist/{workspace-intelligence-runner-VYGSASDP.js → workspace-intelligence-runner-JNCQLUH7.js} +1 -1
  76. package/dist/workspace-intelligence-runtime-registry-MRSF7RTT.js +1 -0
  77. package/dist/{workspace-knowledge-graph-LEM6X5CM.js → workspace-knowledge-graph-BMMM2FUE.js} +1 -1
  78. package/dist/{workspace-mcp-serve-N2QPR7VJ.js → workspace-mcp-serve-COA4FMCA.js} +1 -1
  79. package/dist/{workspace-model-FJXX3NET.js → workspace-model-MNJOGBPP.js} +1 -1
  80. package/dist/{workspace-onboarding-IKFISWWY.js → workspace-onboarding-2B7CYZ5H.js} +1 -1
  81. package/dist/{workspace-readme-E2M35RJH.js → workspace-readme-4S6PJ74A.js} +1 -1
  82. package/dist/{workspace-registry-summary-HOQ3OBNT.js → workspace-registry-summary-GPJEL7K7.js} +1 -1
  83. package/dist/workspace-repair-engine-SRWECKZO.js +3 -0
  84. package/dist/workspace-run-3U77TMKX.js +1 -0
  85. package/dist/{workspace-verify-32AWCJQG.js → workspace-verify-C6HWHRLJ.js} +1 -1
  86. package/dist/{workspace-watch-4WVNB26E.js → workspace-watch-DLPHLF5R.js} +1 -1
  87. package/docs/README.md +2 -0
  88. package/docs/commands-reference.md +10 -8
  89. package/docs/contracts/ARTIFACT_CATALOG.md +27 -22
  90. package/docs/contracts/README.md +3 -0
  91. package/docs/contracts/RUNTIME_ACCEPTANCE_MATRIX.md +20 -11
  92. package/docs/doctor-command.md +10 -4
  93. package/docs/workspace-intelligence-runner.md +2 -1
  94. package/docs/workspace-knowledge-graph.md +6 -1
  95. package/docs/workspace-operations.md +3 -1
  96. package/docs/workspace-repair-engine.md +113 -0
  97. package/docs/workspace-run.md +17 -14
  98. package/package.json +3 -2
  99. package/scripts/enterprise-package-smoke.mjs +9 -6
  100. package/dist/analyze-J7VNZMDH.js +0 -1
  101. package/dist/artifact-remediation-plan-2UKY4TKO.js +0 -3
  102. package/dist/autopilot-release-34H5BSI2.js +0 -1
  103. package/dist/chunk-23JDMHSD.js +0 -86
  104. package/dist/chunk-2E6WGUN6.js +0 -1
  105. package/dist/chunk-3D3PFPP5.js +0 -1
  106. package/dist/chunk-4D7DIGAB.js +0 -1
  107. package/dist/chunk-5XJRCP3D.js +0 -36
  108. package/dist/chunk-62K2H72S.js +0 -1
  109. package/dist/chunk-7MQZQ4UU.js +0 -1
  110. package/dist/chunk-AL237TSJ.js +0 -7
  111. package/dist/chunk-AYHNNPPH.js +0 -8
  112. package/dist/chunk-B4CPDK6J.js +0 -2
  113. package/dist/chunk-CZC5P2MF.js +0 -1
  114. package/dist/chunk-DZ4VKAXB.js +0 -75
  115. package/dist/chunk-FUPHQOJB.js +0 -1
  116. package/dist/chunk-GHB6QMQH.js +0 -1
  117. package/dist/chunk-JIUWK4ML.js +0 -1
  118. package/dist/chunk-KHEJO3JU.js +0 -4
  119. package/dist/chunk-LOCPNNSK.js +0 -1
  120. package/dist/chunk-LPCL4U4L.js +0 -1
  121. package/dist/chunk-MBRU3VWJ.js +0 -2
  122. package/dist/chunk-P4OSLAVD.js +0 -3
  123. package/dist/chunk-Q6CUJ3WF.js +0 -10
  124. package/dist/chunk-SQTV2OYU.js +0 -4
  125. package/dist/chunk-ULR66OJR.js +0 -2
  126. package/dist/chunk-XHRHNVCZ.js +0 -1
  127. package/dist/pipeline-FOZ46ELQ.js +0 -5
  128. package/dist/project-test-coverage-A677ZLW3.js +0 -1
  129. package/dist/workspace-explain-26UGV7L4.js +0 -1
  130. package/dist/workspace-explain-contract-GIWPCCEF.js +0 -1
  131. package/dist/workspace-intelligence-runtime-registry-YOQ5GFFJ.js +0 -1
  132. package/dist/workspace-run-GUW4EOYB.js +0 -1
@@ -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 li=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],di=["tests","test","src/test","__tests__","e2e","playwright","cypress"],ui=["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"],pi=["src","app","pages"],mi=["dev","build","test","lint"];function bn(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 li)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 wn(e,t){for(let o of di)if(await u.pathExists(d.join(e,o)))return true;for(let o of ui)if(await u.pathExists(d.join(e,o)))return true;let i=bn(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 fi(e)}async function fi(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 Ct(e){for(let t of pi){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 gi(e){let t=e.key;return b$7(t).key}function yi(e,t,i){return a$9(t,i).some(o=>!!e[o])}async function jn(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=gi(i),s=b$7(o),a=bn(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 b=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:b?"pass":"warn",severity:"warn",scope:"project-scoped",reason:b?`${s.displayName} configuration artifacts detected.`:`No ${s.displayName} config markers detected (${s.fileHints.join(", ")||"n/a"}).`,recommendation:b?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let g of mi){let y=yi(a,o,g),k=g==="dev"||g==="build",w=!y&&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:y?"pass":k?"fail":"warn",severity:k?"error":"warn",scope:"project-scoped",reason:y?`package.json exposes a ${g} script for ${s.displayName}.`:`No ${g} script detected for ${s.displayName}.`,recommendation:y?void 0:`Add a "${a$9(o,g)[0]??g}" script to package.json.`,repairCapability:w});}let j=await Ct(t);return r.push({id:"frontend-source-tree",label:"Frontend source tree",status:j?"pass":"warn",severity:"warn",scope:"project-scoped",reason:j?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:j?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),r}var hi={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:[]},ki={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:[]},bi=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
2
- `),Pt=[".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 vi(e,n,2))return true;continue}if(await u.pathExists(d.join(e,i)))return true}return false}async function vi(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 nt(e){try{return await u.pathExists(e)?await u.readFile(e,"utf8"):""}catch{return ""}}async function it(e,t){let i=[];for(let n of t){let o=await nt(d.join(e,n));o&&i.push(o);}return i.join(`
3
- `)}async function wi(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 nt(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 Oe(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 ji(e){if(e.runtime==="node"){let i=Oe(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 xi(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 Dt(e){let t=ji({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}):xi({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 Ci(e){return b$8({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${bi}
4
- `,reason:"Create a Docker build ignore baseline to keep secrets, dependencies, and reports out of container contexts."})}async function Pi(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:`${Pt.join(`
5
- `)}
6
- `,reason:"Create a minimal ignore baseline so local env files are not committed accidentally."});let t=await nt(d.join(e,".gitignore")),i=Pt.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 Di(e){let t=ki[e.runtime]??[],i$1=hi[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 wi({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 Si(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 Ri(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:Ci(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 Ei(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 it(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 Ai(e){let t=await u.pathExists(d.join(e.projectPath,".gitignore")),n=(await nt(d.join(e.projectPath,".gitignore"))).split(/\r?\n/),o=t&&Pt.every(W=>n.includes(W)),s=Oe(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",b=xe(e.runtimeFamily),g=["package.json","package-lock.json",...await u.pathExists(d.join(e.projectPath,"npm-shrinkwrap.json"))?["npm-shrinkwrap.json"]:[]],y=r?.invocation,k=r?.remediation?.disposition,w=r?.remediation?.resolutionCandidates?.length??0,v=k==="compatible"||k==="mixed"||!r&&b==="node",D=l&&v&&(r?.tool==="npm audit"||!r&&b==="node")?{cwd:e.projectPath,executable:"npm",args:["audit","fix","--audit-level=moderate"]}:l&&v&&r?.tool==="bun audit"?{cwd:e.projectPath,executable:"bun",args:["update"]}:l&&v&&r?.tool==="deno audit"?{cwd:e.projectPath,executable:"deno",args:["audit","--fix"]}:void 0,A=l?[{id:"audit-live-state",kind:"diagnose",description:"Read the current advisory graph and classify direct, transitive, fixable, and breaking findings.",risk:"safe",invocation:y,continueWhen:"always"},...D?[{id:"apply-compatible-fixes",kind:"safe-fix",description:"Apply runtime-authored compatible dependency and lockfile updates without forcing breaking upgrades.",risk:"guarded",invocation:D,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:D?"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:y,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,f=l&&D?i({issueId:"surface-security-hygiene",title:`Apply compatible ${r?.ecosystem??b} vulnerability fixes`,projectPath:e.projectPath,command:[D.executable,...D.args].join(" "),invocation:{executable:D.executable,args:D.args},strategy:A,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:r?.ecosystem??D.executable??b,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,S=o&&m,x=r?.reason;return {id:"surface-security-hygiene",label:"Security hygiene surface",status:S?"pass":l?"fail":"warn",severity:l?"error":"warn",scope:"project-scoped",reason:l?`${c} moderate/high/critical dependency vulnerability(ies) reported.`:h?`${x} 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?w>0&&!v?`No direct automatic fix is currently authorized. Evaluate the ${w} structured dependency resolution candidate(s) through a guarded reconcile, audit, test, and build transaction before considering a breaking change.`:k==="breaking-only"||k==="none"?w>0?`No direct automatic fix is currently available. Evaluate the ${w} structured dependency resolution candidate(s) through a guarded install, audit, test, and build transaction before considering a breaking change.`:"No compatible automatic fix is currently available. Review an explicit replacement, a time-bounded exception, or wait for an upstream patch.":"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?f??{...Ce({issueId:"surface-security-hygiene",title:`Resolve ${r?.ecosystem??b} 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:k==="breaking-only"?w>0?"The runtime-native direct fix is breaking or a downgrade. Doctor preserved bounded owner, constraint, or transitive resolution candidates for guarded compatibility verification before requesting an engineering decision.":"The runtime-native audit exposes only breaking or downgrade remediation. Doctor requires an explicit engineering decision instead of presenting it as an automatic fix.":k==="none"?w>0?"The runtime-native audit reports no direct fix. Evaluate its structured transitive or constraint resolution candidates through the dependency transaction before choosing replacement, exception, or upstream wait.":"The runtime-native audit reports no available fix. Use an explicit replacement plan, time-bounded exception, or upstream patch.":"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:A,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:r?.ecosystem??D?.executable??b,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}}}:o?void 0:await Pi(e.projectPath)}}async function $i(e){let t=xe(e.runtimeFamily),i=e.hasTests===true,n=i?void 0:await Dt({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 Fi(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=Ni(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 Ni(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Ii(e){let t=Oe(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 Mi(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=Oe(e.packageJsonData),a=Object.values(s).join(`
7
- `),r=await it(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 Oi(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 it(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=Oe(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 Dt({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 Ti(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 it(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 Dt({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 xn(e){let t=xe(e.runtimeFamily),i=[],n=await Di({projectPath:e.projectPath,runtime:t,packageJsonData:e.packageJsonData});n&&i.push(n),i.push(await Si(e)),i.push(await Ri(e)),i.push(await Ei(e)),i.push(await Ai(e)),i.push(await $i(e)),i.push(await Fi(e)),(t==="node"||t==="bun")&&i.push(Ii(e));let o=await Promise.all([Mi(e),Oi(e),Ti(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 Gi(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=>Gi(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))}function Cn(e){return e.map(t=>{let i=t.direct===true?"direct":t.direct===false?"transitive":"unknown";return {packageName:t.name,relationship:i,strategies:i==="direct"?["direct-upgrade","constraint-update","replacement","policy-exception","upstream-wait"]:["owner-upgrade","constraint-update","replacement","policy-exception","upstream-wait"],risk:"guarded",autoExecutable:false,requiresCompatibilityVerification:true,...t.version?{currentVersion:t.version}:{},ownerPackages:[],advisoryIds:[...t.advisoryIds],reason:"Resolve the advisory through the runtime-native dependency manifest and lock/baseline, then prove compatibility with audit, tests, build, and canonical verification."}})}var St=new Map,Bi=["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 Ki(){let e=Number(process.env.RAPIDKIT_DOCTOR_AUDIT_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.trunc(e):15e3}async function Wi(e,t){let i=[];for(let n of Bi){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 pe(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 Te(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function Pn(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {low:Te(t.low),moderate:Te(t.moderate??t.medium),high:Te(t.high),critical:Te(t.critical),unknown:Te(t.unknown)}}function Ge(e){return e.low+e.moderate+e.high+e.critical+e.unknown}function Hi(e){if(typeof e!="string")return;let t=e.trim(),i=t.match(/^<\s*(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/);if(i)return `>=${i[1]}`;let n=t.match(/^<=\s*(\d+)\.(\d+)\.(\d+)$/);if(n)return `>=${n[1]}.${n[2]}.${Number(n[3])+1}`}async function qi(e){let t=new Map;try{let i=await u.readJSON(d.join(e,"package.json"));for(let n of ["dependencies","devDependencies","optionalDependencies","peerDependencies"]){let o=i[n];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let[s,a]of Object.entries(o))typeof a=="string"&&a.trim()&&t.set(s.toLowerCase(),a.trim());}}catch{}return t}async function Li(e,t){let i=pe(t),n=i?.vulnerabilities&&typeof i.vulnerabilities=="object"&&!Array.isArray(i.vulnerabilities)?i.vulnerabilities:void 0;if(!n)return [];let[o,s]=await Promise.all([Rn(e),qi(e)]),a=new Map;for(let[r,c]of Object.entries(n)){let l=c&&typeof c=="object"?c:{},m=typeof l.name=="string"&&l.name.trim()?l.name.trim():r.trim();if(!m)continue;let h=l.isDirect===true?"direct":l.isDirect===false?"transitive":"unknown",b=Array.isArray(l.effects)?[...new Set(l.effects.filter(A=>typeof A=="string").map(A=>A.trim()).filter(Boolean))].sort():[],j=Array.isArray(l.via)?l.via:[],g=[...new Set(j.flatMap(A=>{let f=A&&typeof A=="object"?A:{};return [f.source,f.url].filter(S=>typeof S=="string"||typeof S=="number").map(String)}))].sort(),y=typeof l.range=="string"?l.range.trim():void 0,k=Hi(y),w=s.get(m.toLowerCase()),v=o.get(m.toLowerCase()),D=h==="direct"?["direct-upgrade","constraint-update","replacement","policy-exception","upstream-wait"]:[...b.length>0?["owner-upgrade"]:[],"transitive-override","replacement","policy-exception","upstream-wait"];a.set(m.toLowerCase(),{packageName:m,relationship:h,strategies:D,risk:"guarded",autoExecutable:false,requiresCompatibilityVerification:true,...v?{currentVersion:v}:{},...w?{currentRange:w}:{},...y?{vulnerableRange:y}:{},...k?{safeVersionConstraint:k}:{},ownerPackages:b,advisoryIds:g,reason:h==="direct"?"Resolve the direct dependency inside its declared compatibility boundary, then reconcile and verify the complete dependency transaction.":"Resolve the vulnerable transitive path through a compatible owner upgrade or a guarded package-manager constraint; never infer safety from an audit downgrade."});}return [...a.values()].sort((r,c)=>r.packageName.localeCompare(c.packageName))}function De(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 Be(e,t){if(Array.isArray(e)){for(let n of e)Be(n,t);return}if(!e||typeof e!="object")return;let i=e;t(i);for(let n of Object.values(i))Be(n,t);}function Vi(e,t){if(t===0)return {disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]};let i=false,n=false,o=false,s=[];for(let[r,c]of e){let l=c&&typeof c=="object"?c:{};if(!Object.prototype.hasOwnProperty.call(l,"fixAvailable"))continue;i=true;let m=l.fixAvailable;if(m===true){n=true,s.push({packageName:r,breaking:false});continue}if(!m||typeof m!="object"||Array.isArray(m))continue;let h=m,b=typeof h.name=="string"&&h.name.trim()?h.name.trim():r,j=h.isSemVerMajor===true;n||=!j,o||=j,s.push({packageName:b,...typeof h.version=="string"&&h.version.trim()?{version:h.version.trim()}:{},breaking:j});}return {disposition:n?o?"mixed":"compatible":o?"breaking-only":i?"none":"unknown",compatibleFixAvailable:n,breakingFixAvailable:o,candidates:s.sort((r,c)=>`${r.packageName}@${r.version??""}`.localeCompare(`${c.packageName}@${c.version??""}`))}}function Ji(e,t){let i=s=>{let a=s.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.+)?$/);return a?[Number(a[1]),Number(a[2]),Number(a[3]),a[4]??""]:null},n=i(e),o=i(t);if(!n||!o)return null;for(let s=0;s<3;s+=1)if(n[s]!==o[s])return Number(n[s])>Number(o[s])?1:-1;return n[3]===o[3]?0:n[3]?o[3]?n[3].localeCompare(o[3]):-1:1}async function Rn(e){let t=new Map;try{let i=await u.readJSON(d.join(e,"package-lock.json")),n=i.packages&&typeof i.packages=="object"&&!Array.isArray(i.packages)?i.packages:{};for(let[s,a]of Object.entries(n)){if(!s.startsWith("node_modules/"))continue;let r=s.replace(/^node_modules\//,"").split("/node_modules/").at(-1)?.trim()??"";if(!r)continue;let c=a&&typeof a=="object"?a:{};!t.has(r.toLowerCase())&&typeof c.version=="string"&&c.version.trim()&&t.set(r.toLowerCase(),c.version.trim());}let o=i.dependencies&&typeof i.dependencies=="object"&&!Array.isArray(i.dependencies)?i.dependencies:{};for(let[s,a]of Object.entries(o)){if(t.has(s.toLowerCase()))continue;let r=a&&typeof a=="object"?a:{};typeof r.version=="string"&&r.version.trim()&&t.set(s.toLowerCase(),r.version.trim());}}catch{}return t}async function zi(e,t){if(t.disposition==="not-needed")return t;let i=await Rn(e),n=new Map;for(let c of t.candidates){let l=i.get(c.packageName.toLowerCase());if(c.version&&l){let b=Ji(c.version,l);if(b!==null&&b<=0)continue}let m=`${c.packageName.toLowerCase()}\0${c.version??""}`,h=n.get(m);n.set(m,{packageName:h?.packageName??c.packageName,...c.version?{version:c.version}:{},breaking:!!(h?.breaking||c.breaking)});}let o=[...n.values()].sort((c,l)=>`${c.packageName}@${c.version??""}`.localeCompare(`${l.packageName}@${l.version??""}`)),s=o.some(c=>!c.breaking),a=o.some(c=>c.breaking);return {disposition:s?a?"mixed":"compatible":a?"breaking-only":"none",compatibleFixAvailable:s,breakingFixAvailable:a,candidates:o}}function Ui(e){let t=pe(e);if(!t){let c={...ce},l=[],m=0,h=false;for(let b of e.split(/\r?\n/)){let j=pe(b);if(!j)continue;let g=j.data&&typeof j.data=="object"?j.data:{};if(j.type==="auditAdvisory"){let y=g.advisory&&typeof g.advisory=="object"?g.advisory:{};m+=1,De(c,y.severity);let k=ae({name:y.module_name??y.name,advisoryIds:[y.id,y.github_advisory_id,y.url],severities:[y.severity]});k&&l.push(k);}if(j.type==="auditSummary"){h=true;let y=Pn(g.vulnerabilities);if(Ge(y)>=m)return {findingCount:Ge(y),severityCounts:y,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=Pn(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(b=>{let j=b&&typeof b=="object"?b:{};return [j.source,j.url]}),severities:[m.severity]})}));if(Ge(n)>0||i?.vulnerabilities){let c=Ge(n);return {findingCount:c,severityCounts:n,subjects:s,remediation:Vi(o,c)}}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:{};De(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 Yi(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(b=>Array.isArray(b)?b:[b])}),severities:c.map(()=>"unknown")});l&&o.push(l);}}return {findingCount:s,severityCounts:n,subjects:se(o)}}function Qi(e){if(!e.trim())return null;let t=new Set,i=new Map;for(let n of e.split(/\r?\n/)){let o=pe(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 Xi(e){let t=pe(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:{};De(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 Zi(e){let t=pe(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 Be(i,a=>{(typeof a.advisoryId=="string"||typeof a.cve=="string")&&(o+=1,De(n,a.severity));}),{findingCount:o,severityCounts:n,subjects:se(s)}}function eo(e){let t=pe(e);if(!t)return null;let i={...ce},n=0,o=[];return Be(t,s=>{if(!Array.isArray(s.vulnerabilities))return;for(let r of s.vulnerabilities){let c=r&&typeof r=="object"?r:{};n+=1,De(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 to(e){let t=pe(e);if(!t)return null;let i={...ce},n=new Set,o=[];return Be(t,s=>{let a=s.id??s.cve??s.advisory??s.url;if(typeof a!="string")return;n.add(a),De(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&&Ge(i)===0?{...i,unknown:n.size}:i,subjects:se(o)}}function Dn(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 no(e,t,i){return e==="node"||e==="bun"?Ui(t):e==="python"?Yi(t):e==="go"?Qi(t):e==="rust"?Xi(t):e==="php"?Zi(t):e==="dotnet"?eo(t):e==="ruby"?to(t)??Dn(t,i):e==="deno"||e==="elixir"?Dn(t,i):null}async function _e(e,t){return u.pathExists(d.join(e,t))}async function io(e,t){if(t==="bun")return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(t==="node"){if(await _e(e,"bun.lock")||await _e(e,"bun.lockb"))return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(await _e(e,"pnpm-lock.yaml"))return {ecosystem:"npm",tool:"pnpm audit",invocation:{cwd:e,executable:"pnpm",args:["audit","--json"]}};if(await _e(e,"yarn.lock")){let i=await _e(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 Sn(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 oo(e){let t=new Date().toISOString(),i=await io(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:Ki(),reject:false}),s=no(e.runtime,o.stdout,o.stderr);if(!s){let c=/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:c?"tool-unavailable":"failed",reason:c?`${i.tool} is not installed or not supported by the detected runtime version.`:`${i.tool} did not produce parseable vulnerability evidence.`}}if((e.runtime==="node"||e.runtime==="bun")&&s.remediation&&(s.remediation=await zi(e.projectPath,s.remediation),s.findingCount>0&&!s.remediation.compatibleFixAvailable)){let c=await Li(e.projectPath,o.stdout);s.remediation.resolutionCandidates=c.length>0?c:Cn(s.subjects);}let a=s.severityCounts.moderate+s.severityCounts.high+s.severityCounts.critical+s.severityCounts.unknown,r=s.remediation??(s.findingCount===0?{disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]}:{disposition:"unknown",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[],resolutionCandidates:Cn(s.subjects)});return {...n,invocation:i.invocation,exitCode:o.exitCode,findingCount:s.findingCount,blockingFindingCount:a,severityCounts:s.severityCounts,subjects:s.subjects,remediation:r,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:Sn(o)?"tool-unavailable":"failed",reason:Sn(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 En(e){let t=await Wi(e.projectPath,e.runtime),i=St.get(t);if(i)return i;let n=oo(e);St.set(t,n);try{return await n}catch(o){throw St.delete(t),o}}var Fn="Graph paths identify evidence-backed structural reachability and verification candidates; they do not prove runtime causality or that every affected surface has been discovered.",An={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"]},ro=new Set(["project","service","api","endpoint","schema","database","queue","container","deployment","pipeline","environment","document","decision","test-suite","owner"]),so=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 Rt(e){return {id:e.id,kind:e.kind,label:e.label,...e.projectId?{projectId:e.projectId}:{}}}function Se(e,t,i,n={artifact:b$4}){return {schemaVersion:d$2,generatedAt:(e.now??new Date).toISOString(),status:t,claimBoundary:Fn,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 ao(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 co(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 lo(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 uo(e,t,i){let n=lo(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 $n(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 po(e,t,i,n){let o=co(e,t),s=An[i]??An.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=>$n(m).has(h))),l=new Set(a.filter(m=>c.some(h=>$n(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 mo(e,t,i){let n=i.issueClass??"unknown",o=[...new Set((i.subjects??[]).map(k=>k.trim()).filter(Boolean))],{roots:s,unresolvedSubjects:a}=po(e,t,n,o),r=new Map(e.entities.map(k=>[k.id,k])),c=uo(e,s.map(k=>k.id),3).map(k=>r.get(k)).filter(k=>!!k),l=c.filter(k=>!s.some(w=>w.id===k.id)&&ro.has(k.kind)).slice(0,20),m=c.filter(k=>so.has(k.kind)).slice(0,8),b=[...l,...m].filter((k,w,v)=>v.findIndex(D=>D.id===k.id)===w).slice(0,12).flatMap(k=>{let v=s.map(D=>d$5(e,D.id,k.id)).filter(D=>D.found).sort((D,A)=>D.hops.length-A.hops.length)[0];return v?[{from:v.resolvedFrom??v.from,to:v.resolvedTo??v.to,entityPath:v.entityPath,hops:v.hops,proofIds:v.proofs.map(D=>D.id)}]:[]}),j=new Set([...s.flatMap(k=>k.proofIds),...b.flatMap(k=>k.proofIds)]),g=e.proofs.filter(k=>j.has(k.id)).map(k=>k.artifact).filter((k,w,v)=>v.indexOf(k)===w).sort().slice(0,20),y=[];return l.length===0&&y.push("No affected surface is structurally reachable from the selected root evidence."),m.length===0&&y.push("No graph-connected test suite or pipeline is available as a verification target."),g.length===0&&y.push("The selected graph entities do not carry portable source evidence."),a.length>0&&y.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(Rt),affectedEntities:l.map(Rt),verificationTargets:m.map(Rt),proofPaths:b,sourceArtifacts:g,unknowns:y}}async function At(e){if(!e.workspacePath)return Se(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 Se(e,"graph-missing","Workspace knowledge graph is missing. Run workspace model before relying on graph-aware diagnosis.");if(!await u.pathExists(i))return Se(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 Se(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 Se(e,"stale",c instanceof Error?c.message:String(c),s)}let a$1=ao(n,e);if(!a$1)return Se(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=>mo(n,a$1,c));return {schemaVersion:d$2,generatedAt:(e.now??new Date).toISOString(),status:"available",claimBoundary:Fn,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 Mt=a.doctor;function zn(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Nn(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function fo(){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 zn([...e,...t,...i])}function go(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 yo(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 ho(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 ko(e){let t=e.coreVersion?.split(".")[0],i=e.npmVersion?.split(".")[0];return !t||!i?false:t!==i}var bo="doctor-project-scan-v2",Un="doctor-workspace-cache-v2",vo=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v2",generatedBy:"workspai",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"}),We=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 Ae(){return {...vo}}function lt(e){let t=e.profile?.trim();return t&&t in We?{...We[t]}:e.strict?{...We.release}:e.ci?{...We.ci}:{...We.local}}function at(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function wo(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 jo(e,t){let i=wo(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 xo(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 Yn(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 Co(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 Po(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(n?.status==="manual"||n?.requiresReview)return {mode:"review-required",confidence:"medium",primaryActionLabel:"Review fix path",requiresApproval:true,requiresFreshEvidence:i.verifyBeforeUse,reason:n?.reason??t.recommendation??t.reason,relatedCommands:Nn(n?.refreshCommands??["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:Nn([...n.command?[n.command]:[],...n.verifyCommand?[n.verifyCommand]:[],...n.refreshCommands])}}return 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 Qn(e,t){let i=jo(e,e.freshness?.generatedAt??t),n=e.issueClass??xo(e),o=e.operationalImpact??Co(e,n),s=Po({probe:e,freshness:i});return {...e,freshness:i,issueClass:n,operationalImpact:o,repairIntent:s}}function In(e,t){Array.isArray(e.probes)&&(e.probes=e.probes.map(i=>Qn(i,t)));}function Xn(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 Zn(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function ei(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 ti(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 Do(e,t){let i=new Map;for(let b of t.projects)i.set(b.path||b.name,b.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 b of n){let j=b.path||b.name;j&&o.set(j,Zn(b.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 b of l){let j=o.get(b)??0,g=i.get(b)??0;g>j?(s+=g-j,r.add(b)):g<j&&(a+=j-g,c.add(b));}let m=at(e.healthScore),h=at(t.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:s,resolvedIssueCount:a,netIssueDelta:s-a,scoreDeltaPercent:m===null||h===null?null:h-m,systemStatusChanges:ti(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 So(e,t){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=Zn(e.project?.issues),n=t.project.issues.length,o=Math.max(n-i,0),s=Math.max(i-n,0),a=at(e.healthScore),r=at(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:ti(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 ni(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 q(e,t){return b$6()?`Set-Location -LiteralPath "${e.replace(/"/g,'`"')}"; ${t}`:`cd '${e.replace(/'/g,`'"'"'`)}' && ${t}`}function le(e){return b$6()?q(e,"Copy-Item .env.example .env"):q(e,"cp .env.example .env")}function Mn(e){return q(e,"poetry install --no-root")}function Ro(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 Eo(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 Ao(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 Ot(e,t){let i=w(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function rt(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=Ro(t),e.projectKind=Eo(t),e.runtimeFamily=Ao(t);}function ii(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 Gt(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 $o(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 Fo(e,t){e.framework=Gt(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=ii(t.runtime);}function Z(e,t){e.framework=Gt(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":$o(t)?"generic":"backend",e.runtimeFamily=ii(t.runtime);}function No(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 Io(e,t){let i=j$3(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:Gt(i),confidence:i.confidence}}async function On(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 Mo(e){try{let t=new Set([".git",".venv","node_modules",".workspai",".rapidkit","dist","build","coverage","__pycache__"]),i=new Set,n=async a=>{if(await qe(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 qe(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)?qe(a):n(a)})).forEach(a=>i.add(a)),i.size===0&&(await tr(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 Oo(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(On)),s=await Promise.all(t.map(async a=>{let r=await Promise.all(n.map(c=>On(d.join(a,c))));return `${a}::${r.join("|")}`}));return [bo,...o,...s].join("||")}async function To(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!==Un?null:n}catch{return null}}async function _o(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 Go(e$2,t,i){let n=d.join(e$2,Mt);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:Ae(),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:Ve(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,Mt,c),n}catch(o){if(o instanceof Error&&o.message.includes("violates contracts/"))throw o;return}}async function Bt(e=process.cwd()){let[t,i,n,o,s]=await Promise.all([Bo(),Ko(),Wo(),Ho(),qo(e)]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:s}}async function Bo(){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 Ko(){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 fo())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 Wo(){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 Ho(){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 qo(e=process.cwd()){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],n=go(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=yo(s),c=r[0].version,l=r.some(b=>b.location==="Workspace (.venv)"),m=r.some(b=>b.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(b=>({location:b.location,path:b.path,version:b.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 b=l.shift();if(!b)break;let j=[];try{j=await u.readdir(b.dir);}catch{continue}for(let g of j){let y=d.join(b.dir,g),k;try{k=await u.stat(y);}catch{continue}if(k.isFile()&&g.endsWith("_test.go")){c=true;break}k.isDirectory()&&b.depth<m&&!h.has(g)&&!g.startsWith(".")&&l.push({dir:y,depth:b.depth+1});}}}catch{}if(t.hasTests=r||c,(t.runtimeFamily==="node"||t.runtimeFamily==="bun")&&!t.hasTests&&(t.hasTests=await wn(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"),b=await u.pathExists(h)&&(await u.readFile(h,"utf8")).includes("golangci-lint");t.hasCodeQuality=await u.pathExists(l)||await u.pathExists(m)||b;}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 En({projectPath:e,runtime:t.runtimeFamily??"unknown"}),t.vulnerabilities=t.dependencyAudit.status==="vulnerable"?t.dependencyAudit.blockingFindingCount??t.dependencyAudit.findingCount??0:void 0;}function Lo(e){return zn([m(e),d.join(e,"Scripts","python.exe"),d.join(e,"Scripts","python"),d.join(e,"bin","python"),d.join(e,"bin","python3")])}function Vo(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 Tn(e){for(let t of Lo(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=Vo(`${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 Jo(e,t,i){let n=d.join(e,".venv");if(await u.pathExists(n))return {environmentPath:n,...await Tn({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 Tn({environmentPath:s,frameworkImport:t})}}catch{}return {dependenciesInstalled:false}}function T(e,t){e.probes||(e.probes=[]);let i=Qn(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 He(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 zo(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 He(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 He(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 He(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 He(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 He(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 Uo(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",b=Array.isArray(r.anyOfPaths)?r.anyOfPaths.filter(Boolean):[],j=Array.isArray(r.allOfPaths)?r.allOfPaths.filter(Boolean):[],g=b.length===0;for(let w of b)if(await u.pathExists(d.join(e,w))){g=true;break}let y=true;for(let w of j)if(!await u.pathExists(d.join(e,w))){y=false;break}let k=g&&y;T(t,{id:l,label:m,status:k?"pass":h==="error"?"fail":"warn",severity:h,scope:"project-scoped",reason:k?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 b of c)if(await u.pathExists(d.join(e,b))){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 b of m)if(await u.pathExists(d.join(e,b))){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 zo(e,t);}async function Yo(e,t,i,n){let o=await jn({projectPath:e,detection:n,packageJsonData:i});for(let s of o)T(t,s);}async function Y(e,t,i){let n=await xn({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):[],b=Array.isArray(r.allOfPaths)?r.allOfPaths.filter(Boolean):[],j=h.length===0;for(let k of h)if(await u.pathExists(d.join(e,k))){j=true;break}let g=true;for(let k of b)if(!await u.pathExists(d.join(e,k))){g=false;break}let y=j&&g;T(t,{id:c,label:l,status:y?"pass":m==="error"?"fail":"warn",severity:m,scope:"project-scoped",reason:y?"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 Uo(e,t);}async function Qo(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 C=d.join(e,"registry.json");if(await u.pathExists(C)){let R=await u.readJson(C);R.installed_modules&&(n.stats={modules:R.installed_modules.length});}}catch{}try{let{auditProjectModulePaths:C}=await import('./module-layout-NZ43RSC5.js'),R=await C(e);if(R.issues.length>0){for(let F of R.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 C of t(e,"project.json")){if(!await u.pathExists(C))continue;a=await u.readJson(C);let R=a?.kit_name||a?.kit;R&&(n.kit=R);break}}catch{}try{let C=d.join(e,".git");if(await u.pathExists(C)){let{stdout:R}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false,env:a$7()});R&&(n.lastModified=R.trim());}else {let R=await u.stat(e),O=Date.now()-R.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"),b=d.join(e,"build.sbt"),j=d.join(e,"Cargo.toml"),g=d.join(e,"mix.exs"),y=d.join(e,"deps.edn"),k=d.join(e,"project.clj"),w=d.join(e,"deno.json"),v=d.join(e,"deno.jsonc"),D=d.join(e,"bun.lockb"),A=d.join(e,"bun.lock"),f=d.join(e,"composer.json"),S=d.join(e,"Gemfile"),x=await u.pathExists(r),W=await u.pathExists(c)||await u.pathExists(l),P=await u.pathExists(f),L=await u.pathExists(S),M=await u.pathExists(j),te=await u.pathExists(g),Je=await u.pathExists(y)||await u.pathExists(k),ze=await u.pathExists(b),Ue=await u.pathExists(w)||await u.pathExists(v),V=a?.runtime==="dotnet";try{V=V||await _n(e,".csproj",3)||await _n(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")),fe=x&&(await u.pathExists(D)||await u.pathExists(A)||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 C=d.join(e,"go.sum");return await u.pathExists(C)?n.depsInstalled=true:(n.depsInstalled=false,n.issues.push("Go dependencies not downloaded (go.sum missing)"),n.fixCommands?.push(q(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 C=await u.pathExists(h),R=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(C){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(R&&!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"),ne=d.join(e,"build","libs"),de=d.join(e,".workspai","cache","java","m2"),E=d.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await u.pathExists(_)||await u.pathExists(ne)||await u.pathExists(de)||await u.pathExists(E),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let ve=C?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(q(e,ve));}let H=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(H),!n.hasEnvFile){let ve=d.join(e,".env.example");await u.pathExists(ve)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}let ie=d.join(e,"src","main","resources","application.yml");if(await u.pathExists(ie))try{let ve=await u.readFile(ie,"utf-8");/include:\s*[^\n]*health/i.test(ve)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(ve)||(n.issues.push("Actuator health endpoint exposure is not clearly configured in application.yml"),n.fixCommands?.push(q(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 C=d.join(e,"Cargo.lock"),R=d.join(e,"target");n.depsInstalled=await u.pathExists(C)||await u.pathExists(R),n.depsInstalled||(n.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),n.fixCommands?.push(q(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(te){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let C=d.join(e,"mix.lock"),R=d.join(e,"deps");n.depsInstalled=await u.pathExists(C)||await u.pathExists(R),n.depsInstalled||(n.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),n.fixCommands?.push(q(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(Je){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let C=d.join(e,".cpcache"),R=d.join(e,"target"),F=await u.pathExists(y)||await u.pathExists(k);return n.depsInstalled=await u.pathExists(C)||await u.pathExists(R)||F,n.depsInstalled||(n.issues.push("Clojure dependency cache not initialized"),n.fixCommands?.push(q(e,"clojure -P"))),await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(ze){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let C=d.join(e,"target");n.depsInstalled=await u.pathExists(C),n.depsInstalled||(n.issues.push("Scala build artifacts missing (run dependency/build warmup)"),n.fixCommands?.push(q(e,"sbt compile")));let R=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(R),!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(Ue){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true;let C=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(C),!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)));}return await z(e,n),await Y(e,n),await U(e,n),await Q(e,n),n}if(x){let C=null;try{C=await u.readJson(r);}catch{C=null;}let R={...C?.dependencies??{},...C?.devDependencies??{}},F=C?.scripts??{},O=typeof a?.kit_name=="string"?a.kit_name.toLowerCase():typeof a?.kit=="string"?a.kit.toLowerCase():"",_=d$4(e,a),ne=No({dependencies:R,scripts:F,kitName:O});if(fe)rt(n,"Bun","high");else {let E=j$3(e,a??null);E.key==="nestjs"||E.key==="express"||E.key==="fastify"||E.key==="koa"||E.key==="tauri"||E.key==="electron"||E.key==="vscode-extension"?Z(n,E):_.key!=="unknown"?Fo(n,_):E.key!=="unknown"&&E.key!=="node"?Z(n,E):rt(n,ne.framework,ne.confidence);}n.venvActive=true;let de=d.join(e,"node_modules");if(await u.pathExists(de))try{let H=(await u.readdir(de)).filter(ie=>!ie.startsWith(".")&&!ie.startsWith("_"));n.depsInstalled=H.length>0;}catch{n.depsInstalled=false;}if(!n.depsInstalled){n.issues.push("Dependencies not installed (node_modules empty or missing)");let E=typeof C?.packageManager=="string"?C.packageManager.split("@")[0]:void 0,H=fe?"bun install":E==="pnpm"||await u.pathExists(d.join(e,"pnpm-lock.yaml"))?"pnpm install":E==="yarn"||await u.pathExists(d.join(e,"yarn.lock"))?"yarn install":"npm install";n.fixCommands?.push(q(e,H));}if(n.coreInstalled=false,n.projectKind==="frontend"){let E=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(E.map(ie=>u.pathExists(d.join(e,ie))))).some(Boolean))n.hasEnvFile=true;else {let ie=d.join(e,".env.example");await u.pathExists(ie)&&(n.hasEnvFile=false,n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}}else {let E=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(E),!n.hasEnvFile){let H=d.join(e,".env.example");await u.pathExists(H)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}}if(n.projectKind==="frontend")n.modulesHealthy=await Ct(e),n.missingModules=[];else {let E=d.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await u.pathExists(E))try{let H=await u.readdir(E);n.modulesHealthy=H.length>0;}catch{n.modulesHealthy=false;}}return await z(e,n,C),await Y(e,n,C),n.projectKind==="frontend"?await Yo(e,n,C,_.key!=="unknown"?_:d$4(e,a)):await U(e,n),await Q(e,n),n}if(W){let C=await Io(e,a);rt(n,C.framework,C.confidence);let R="fastapi";n.framework==="Django"?R="django":n.framework==="Flask"?R="flask":n.framework==="Python"&&(R="");let F=await mt(c),O=await Jo(e,R,/\[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(Mn(e))):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Mn(e)));let _=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(_),!n.hasEnvFile){let E=d.join(e,".env.example");await u.pathExists(E)&&(n.issues.push("Environment file missing (found .env.example)"),n.fixCommands?.push(le(e)));}let ne=d.join(e,"src"),de=d.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await u.pathExists(ne)){let E=d.join(ne,"__init__.py");await u.pathExists(E)||(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await u.pathExists(de))try{let E=await Zo(de);for(let H of E){let ie=d.join(de,H,"__init__.py");await u.pathExists(ie)||(n.modulesHealthy=false,n.missingModules.push(`modules/${H}/__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(P){Z(n,j$3(e,a??null)),n.venvActive=true,n.coreInstalled=false;let C=d.join(e,"vendor");n.depsInstalled=await u.pathExists(C),n.depsInstalled||(n.issues.push("PHP dependencies not installed (vendor missing)"),n.fixCommands?.push(q(e,"composer install")));let R=d.join(e,".env");if(n.hasEnvFile=await u.pathExists(R),!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 C=await u.pathExists(d.join(e,"Gemfile.lock")),R=await u.pathExists(d.join(e,"vendor","bundle"));n.depsInstalled=C||R,n.depsInstalled||(n.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),n.fixCommands?.push(q(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 C=d.join(e,"obj"),R=d.join(e,"src","obj"),F=d.join(e,"packages.lock.json");n.depsInstalled=await u.pathExists(C)||await u.pathExists(R)||await u.pathExists(F),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(q(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 rt(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 Xo(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 dt(e,t={}){let i=Xo(await Qo(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 Zo(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 _n(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 qe(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 er(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 tr(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(er(r,i))continue;let c=d.join(s.dir,r),l;try{l=await u.stat(c);}catch{continue}if(l.isDirectory()){if(await qe(c)){n.add(c);continue}s.depth<t&&o.push({dir:c,depth:s.depth+1});}}}catch{continue}}return Array.from(n)}async function Le(e){let t=d.resolve(e),i=d.parse(t).root;for(;;){if(await or(t))return t;if(t===i)break;t=d.dirname(t);}return null}async function nr(e){let t=d.resolve(e),i=await Le(t),n=i??d.parse(t).root;for(;;){if(await qe(t)||await ir(t)&&(!i||t!==i))return t;if(t===n)break;t=d.dirname(t);}return null}function Gn(e){let t=d.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function ir(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 or(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 Kt(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=ho(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 rr(e){let t=ee(e);e.probeSummary=t,e.verdict=t.verdict;}function oi(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){rr(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 Ft(e,t=true,i=lt({})){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 y=await u.readJSON(g);n=y.workspace_name||y.name||n;break}}catch{}let[s$1,a]=await Promise.all([Bt(e),Mo(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 Oo(e,a),l=d.join(e,".workspai","reports","doctor-workspace-cache.json"),m=t?await To(l,c):null;if(m){r.projects=m.projects;for(let g of r.projects)In(g,m.generatedAt),Ot(g,g.path);r.projectScanCached=true,f.debug(`Workspace project health cache hit: ${l}`);}else try{let g=new Date().toISOString(),y=await Promise.all(a.map(k=>dt(k,{allowNonRapidkit:true})));for(let k of y)In(k,g),Ot(k,k.path);r.projects=y,r.projectScanCached=false,await _o(l,{schemaVersion:Un,signature:c,generatedAt:g,projects:y}),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 At({workspacePath:e,projectPath:g.path,projectName:g.name,probes:Yn(g),issues:g.issues});}));let h=[r.python,r.poetry,r.pipx,r.go,r.rapidkitCore];if(r.healthScore=Kt(h,r.projects),r.scoreBreakdown=oi([{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=ni(r.scoreBreakdown),r.evidenceFreshness=Xn(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 b=await d$1(e,Mt),j=b?await ei(b,"workspace"):null;return r.driftDelta=Do(j,r),r.evidencePath=await Go(e,r,m?l:null),r}function Bn(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 ri(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 sr(e$2,t){let i=e$2||t.projectPath,n=".workspai/reports/doctor-project-last-run.json",o=ri(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:Ae(),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:Ve(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 Tt(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 Fe(e,t,i){try{await j(e,g(t,i));}catch{}}async function Kn(e,t=lt({})){let i=await Le(e),n=await Bt(i||e),o=await dt(e,{allowNonRapidkit:true});Ot(o,e),o.graphDiagnosis=await At({workspacePath:i||void 0,projectPath:e,projectName:o.name,probes:Yn(o),issues:o.issues});let s=Kt([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=oi([{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=ni(a.scoreBreakdown),a.evidenceFreshness=Xn([a.project],new Date().toISOString());let r=await d$1(e,".workspai/reports/doctor-project-last-run.json"),c=i?await d$1(i,ri(i,e)):null,l=r??c,m=l?await ei(l,"project"):null;return a.driftDelta=So(m,a),a.evidencePath=await sr(i||void 0,a),a}function K(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 st(e,t){let i=ct(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 Wn(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(st(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 si(){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 ut(e){return ke(e,"cp\\s+\\.env\\.example\\s+\\.env")||ke(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function ai(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 ar(){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 pt(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 Ne(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 cr(e){let t=e.operation?lr(e.operation):e.capabilityId?`capability:${e.capabilityId}`:`command:${e.command}`,i=createHash("sha256").update(t).digest("base64url").slice(0,16);return `${e.projectName}:${e.kind}:${i}`}function lr(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 be(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 dr(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 ur(e){let t=be(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 pr(e){let t=be(e.projectPath,e.operation.path);await u.ensureDir(d.dirname(t));let i=await mt(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 mr(e){let t=be(e.projectPath,e.operation.sourcePath),i=be(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 fr(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}async function gr(e){let t=be(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(fr);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 yr(e){let t=be(e.projectPath,e.operation.path);await u.ensureDir(d.dirname(t));let i=await mt(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 hr(e){let t=be(e.projectPath,e.operation.path);await u.ensureDir(d.dirname(t));let i=await mt(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 mt(e){try{return await u.pathExists(e)?await u.readFile(e,"utf8"):""}catch{return ""}}function kr(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(ut(t))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"};if(pt(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=Ne(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"}:ai(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 ct(e,t){return e.repairCapabilities?.find(i=>i.command===t)}function Nt(e,t){if(t)return e.probes?.find(i=>i.repairCapability?.id===t.id)}function br(e){let{step:t,capability:i,operation:n}=e;if(n?.type==="file-create")return {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"]};if(n?.type==="file-append")return {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}`)]};if(n?.type==="file-copy")return {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"]};if(n?.type==="package-json-script")return {title:i?.title??"Update package.json script",summary:`Ensure package.json script "${n.scriptName}" exists.`,changes:[`set scripts.${n.scriptName}=${n.scriptValue}`]};if(n?.type==="json-edit")return {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)}`)};if(n?.type==="env-key-add")return {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}`)};if(n?.type==="makefile-target")return {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"]:[]]};if(t.kind==="env-copy")return {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"]};if(t.kind==="manual-url")return {title:"Open manual guidance",summary:"Manual remediation is required outside Doctor.",changes:[t.originalCommand]};if(i?.status==="manual"||i?.requiresReview){let o=i.transaction?.kind==="dependency-security";return {title:i.title,summary:i.reason,changes:o?["review the dependency remediation candidates","approve a breaking change, replacement, exception, or upstream wait explicitly"]:["review the project-specific requirements and proposed guidance","approve the intended source or configuration change explicitly"]}}return {title:i?.title??"Run remediation command",summary:t.reason??"Run the planned remediation command.",changes:[t.originalCommand]}}function vr(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 wr(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:vr(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 jr(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 xr(e){return e.step.executable?e.executableInCurrentEnvironment?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:"blocked",reason:e.blockedReason??"Required tool or environment is not available."}:e.capability?.status==="manual"||e.capability?.requiresReview?{state:"review-required",reason:e.capability.reason}:{state:"guidance-only",reason:e.step.reason??"This remediation is guidance-only."}}function Cr(e){let{step:t,issueClass:i,repairIntent:n,operation:o}=e;return t.kind==="dependency-sync"||t.kind==="go-mod-tidy"||i==="dependency"?"dependency-baseline":!t.executable||t.kind==="manual-url"||n?.mode==="manual-guidance"?"manual-review":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 Hn(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 Pr(e){return [...e].sort((i,n)=>{let o=Hn(i.phase)-Hn(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 Dr(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 Sr(e,t,i){if(i.kind==="dependency-sync"||i.kind==="go-mod-tidy")return `${e.path}:dependency-baseline`;let n=Ne(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=ut(t);if(o)return `${e.path}:file-copy:${d.join(o.projectPath,".env")}`;let s=pt(t);return s?`${e.path}:package-json-script:${d.join(s.projectPath,"package.json")}:${s.scriptName}`:null}function Rr(e,t){return ct(e,t)?4:Ne(t)?3:pt(t)?2:ut(t)?1:0}async function _t(e,t="local"){let n=e.filter(y=>(y.fixCommands?.length??0)>0||(y.repairCapabilities??[]).some(k=>k.status==="manual")).flatMap(y=>{let k=(y.fixCommands??[]).map(v=>{let D=ct(y,v);return {project:y,step:kr(y,v),command:v,capability:D,probe:Nt(y,D)}}),w=(y.repairCapabilities??[]).filter(v=>v.status==="manual").map(v=>({project:y,step:{projectName:y.name,projectPath:y.path,originalCommand:v.command??"",kind:"shell",risk:v.risk,executable:false,reason:v.reason},command:v.command??"",capability:v,probe:Nt(y,v)}));return [...k,...w]}),o=[],s=new Map;for(let y of n){let k=Sr(y.project,y.command,y.step);if(!k){o.push(y);continue}let w=Rr(y.project,y.command),v=s.get(k);if(!v){s.set(k,{index:o.length,priority:w}),o.push(y);continue}w>v.priority&&(o[v.index]=y,s.set(k,{index:v.index,priority:w}));}let a=o,r=null,c=[],l=0,m=0,h=0,b=0;for(let y of a){let{project:k,step:w,command:v}=y,D=w.executable,A;w.kind==="go-mod-tidy"&&(r===null&&(r=await si()),r||(D=false,A="Go toolchain not available")),D&&(l+=1,w.risk==="safe"&&(m+=1),w.risk==="guarded"&&(h+=1),w.risk==="invasive"&&(b+=1));let f=y.capability??ct(k,v),S=y.probe??Nt(k,f),x=f?.operation??Ne(v)??void 0,W=f?.files??(x&&"path"in x?[x.path]:[]),P=S?.repairIntent,L=xr({step:w,capability:f,executableInCurrentEnvironment:D,blockedReason:A,policyProfile:t}),M=Cr({step:w,issueClass:S?.issueClass,repairIntent:P,operation:x});c.push({...w,id:cr({projectName:k.name,kind:w.kind,command:v,operation:x,capabilityId:f?.id}),phase:M,order:0,dependsOn:[],issueId:f?.issueId,issueClass:S?.issueClass,operationalImpact:S?.operationalImpact,repairIntent:P,files:W,...x?{operation:x}:{},...f?.strategy?{strategy:f.strategy.map(te=>structuredClone(te))}:{},...f?.transaction?{transaction:structuredClone(f.transaction)}:{},preview:br({step:w,capability:f,operation:x}),diffPreview:wr({step:w,operation:x}),verifyCommand:f?.verifyCommand,refreshCommands:f?.refreshCommands??["npx workspai doctor project --json"],rollback:jr(w),studioStatus:L,executableInCurrentEnvironment:D,blockedReason:A});}let j=Dr(Pr(c)),g=new Set(j.map(y=>y.projectPath)).size;return {schemaVersion:"doctor-remediation-plan-v2",generatedAt:new Date().toISOString(),policyProfile:t,fixableProjects:g,totalSteps:j.length,executableSteps:l,risk:{safe:m,guarded:h,invasive:b},steps:j}}function qn(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 Er(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 Ar(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 $r(e){let t=await dt(e,{allowNonRapidkit:true});return {issues:t.issues.length,healthy:t.issues.length===0}}async function It(e){let t=[];for(let i of e){let n=await dt(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 Ln(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 me(e,t=false,i={}){let n=await _t(e,i.policyProfile);i.artifactRoot&&(i.planOnly||t)&&await Tt(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 Fe(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 S=f.fixCommands??[];console.log(p.bold(`Project: ${p.yellow(f.name)}`)),S.forEach((x,W)=>{console.log(` ${W+1}. ${p.cyan(st(f,x))}`);}),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 S=o.find(W=>W.path===f.projectPath),x=f.executableInCurrentEnvironment?p.green("ready"):p.yellow(`blocked${f.blockedReason?` (${f.blockedReason})`:""}`);console.log(` - ${p.cyan(f.projectName)} [${f.risk}] ${S?st(S,f.originalCommand):f.preview.title} ${p.gray(`=> ${x}`)}`);}console.log(p.gray(`
38
- Use --apply to execute this plan non-interactively, or --fix for interactive confirmation.`));return}let h=n.executableSteps,b$2=n.risk.safe,j=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 It(e),verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,f,i.artifactMirrorRoots),await Fe(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=${b$2}, guarded=${j}, invasive=${g}. Guarded/invasive fixes use snapshot + rollback.`)),!i.skipConfirmation){let{confirm:f}=await b$1([{type:"confirm",name:"confirm",message:`Apply ${o.reduce((S,x)=>S+(x.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!f){a||console.log(p.yellow(`
39
- \u26A0\uFE0F Fixes cancelled by user`));let S=c({appliedFixes:[],remainingBlockers:await It(e),verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,S,i.artifactMirrorRoots),await Fe(i.artifactRoot,S,i.historyScope??"project")),S}}a||console.log(p.bold.cyan(`
40
- \u{1F680} Applying fixes...
41
- `));let y=new Set,k=new Map(o.map(f=>[f.path,f])),w=new Set,v=ar(),D=process.env.RAPIDKIT_DOCTOR_FIX_ALLOW_GUARDED_COMMANDS==="1"||process.env.RAPIDKIT_DOCTOR_FIX_ALLOW_DEPENDENCY_SYNC==="1",A="";for(let f of n.steps){let S=k.get(f.projectPath);if(!S)continue;let x=f.originalCommand;a||A!==f.projectName&&(A=f.projectName,console.log(p.bold(`Fixing ${p.cyan(f.projectName)}...`)));let W=`${f.projectPath}::${x}`;if(!y.has(W)){y.add(W);try{if(r(p.gray(` ${st(S,x)}`)),f.kind==="manual-url"){r(p.yellow(` \u2139 Manual action required: open ${x}`)),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 P=Ne(x),M=f.risk!=="safe"||P?.type==="file-create"||P?.type==="file-append"||P?.type==="file-copy"||P?.type==="json-edit"||P?.type==="env-key-add"||P?.type==="makefile-target"?await Er(m,f.projectPath):null;M&&P?.type==="file-create"&&await Ee(M,P.path),M&&P?.type==="file-append"&&await Ee(M,P.path),M&&P?.type==="file-copy"&&await Ee(M,P.path),M&&P?.type==="json-edit"&&await Ee(M,P.path),M&&P?.type==="env-key-add"&&await Ee(M,P.path),M&&P?.type==="makefile-target"&&await Ee(M,P.path);let te=ut(x);if(te){let X=d.join(te.projectPath,".env.example"),C=d.join(te.projectPath,".env");if(!await u.pathExists(X))throw new Error(`.env.example not found at ${X}`);if(await u.pathExists(C)){r(p.green(` \u2705 .env already exists
44
- `));continue}await u.copy(X,C,{overwrite:false,errorOnExist:false}),w.add(f.projectPath),s.push({path:C,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
45
- `));continue}if(P?.type==="file-copy"){await mr({projectPath:f.projectPath,operation:P}),w.add(f.projectPath),s.push({path:P.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
46
- `));continue}let Je=pt(x);if(Je){await dr(Je),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
47
- `));continue}if(P?.type==="file-create"){await ur({projectPath:f.projectPath,operation:P}),w.add(f.projectPath),s.push({path:P.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
48
- `));continue}if(P?.type==="file-append"){await pr({projectPath:f.projectPath,operation:P}),w.add(f.projectPath),s.push({path:P.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
49
- `));continue}if(P?.type==="json-edit"){await gr({projectPath:f.projectPath,operation:P}),w.add(f.projectPath),s.push({path:P.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
50
- `));continue}if(P?.type==="env-key-add"){await yr({projectPath:f.projectPath,operation:P}),w.add(f.projectPath),s.push({path:P.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
51
- `));continue}if(P?.type==="makefile-target"){await hr({projectPath:f.projectPath,operation:P}),w.add(f.projectPath),s.push({path:P.path,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
52
- `));continue}let ze=ke(x,"(?:npx\\s+workspai|rapidkit)\\s+init");if(ze){if(!D){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:x,detail:"Guarded setup command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}await execa("rapidkit",["init"],{cwd:ze.projectPath,shell:c$1(),stdio:a?"pipe":"inherit",timeout:v,forceKillAfterDelay:1e3}),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
53
- `));continue}let Ue=ke(x,"go\\s+mod\\s+tidy");if(Ue){if(c$2===null&&(c$2=await si()),!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:Ue.projectPath,shell:c$1(),stdio:a?"pipe":"inherit",timeout:v,forceKillAfterDelay:1e3}),w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
55
- `));continue}let V=ai(x);if(V){if(!D&&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:x,detail:"Guarded dependency command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}let C=2,R,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;_<=C;_+=1)try{await execa(V.command,V.args,{cwd:V.projectPath,env:O,shell:c$1(),stdio:a?"pipe":"inherit",timeout:v,forceKillAfterDelay:1e3}),R=null;break}catch(ne){if(R=ne,_<C&&qn(ne)){r(p.yellow(` \u26A0 Retrying dependency sync (${_}/${C-1})...`));continue}throw ne}if(R)throw R;w.add(f.projectPath),s.push({path:f.projectPath,action:f.kind,outcome:"applied",projectName:f.projectName,command:x}),r(p.green(` \u2705 Success
56
- `));continue}let Ie=f.kind==="shell"?2:1,fe;for(let X=1;X<=Ie;X+=1)try{await execa(x,{shell:true,stdio:a?"pipe":"inherit",timeout:v,forceKillAfterDelay:1e3}),fe=null;break}catch(C){if(fe=C,X<Ie&&qn(C)){r(p.yellow(` \u26A0 Retrying command (${X}/${Ie-1})...`));continue}throw C}if(fe)throw fe;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:x});}catch(P){let L=Ne(x);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 Ar(M),a||console.log(p.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(te){a||console.log(p.red(` \u274C Rollback failed: ${te instanceof Error?te.message:String(te)}`));}}a||console.log(p.red(` \u274C Failed: ${P instanceof Error?P.message:String(P)}
58
- `)),s.push({path:f.projectPath,action:f.kind,outcome:"failed",projectName:f.projectName,command:x,detail:P instanceof Error?P.message:String(P)});}}}for(let f of o)if(w.has(f.path))try{let S=await $r(f.path);a||console.log(S.healthy?p.green(` \u2705 Post-fix verification passed for ${f.name}`):p.yellow(` \u26A0 Post-fix verification: ${S.issues} issue(s) remain for ${f.name}`));}catch(S){a||console.log(p.yellow(` \u26A0 Post-fix verification skipped: ${S instanceof Error?S.message:String(S)}`));}if(a||console.log(p.bold.green(`
59
- \u2705 Fix process completed!`)),t){let f=c({appliedFixes:s,remainingBlockers:await It(e),verifyRecommended:b});return i.artifactRoot&&(await $e(i.artifactRoot,f,i.artifactMirrorRoots),await Fe(i.artifactRoot,f,i.historyScope??"project")),f}}function Ve(e,t){let i=lt(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 Vn(e,t,i){let n=Ve(e,t);return i?.appliedFixes.some(s=>s.outcome==="failed")??false?Math.max(n,1):n}async function Ts(e={}){let t=lt({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 Le(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 Le(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 Ft(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,y=e.plan||e.fix||e.apply?await _t(l.projects,t.name):void 0,k=y?await Tt(r,y):void 0,w;(e.fix||e.apply)&&!e.plan&&(g=await me(l.projects,true,{skipConfirmation:e.apply===true||e.fix===true,json:true,policyProfile:t.name})??c({appliedFixes:[],remainingBlockers:[],verifyRecommended:b}),l=await Ft(r,false,t),g={...g,remainingBlockers:Ln(l.projects)},w=await $e(r,g),await Fe(r,g,"workspace"));let v=l.projects.map(ee),D=v.reduce((S,x)=>S+x.blockingFindings,0),A=v.reduce((S,x)=>S+x.advisoryFindings,0),f={contract:Ae(),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(S=>Bn(S)),summary:{totalProjects:l.projects.length,totalIssues:l.projects.reduce((S,x)=>S+x.issues.length,0),verdict:l.healthScore?.verdict??"passed",blockingFindings:D,advisoryFindings:A,projectAdvisoryWarningProjects:v.filter(S=>S.advisoryFindings>0).length,projectAdvisoryWarnings:A,hasSystemErrors:[l.python,l.rapidkitCore].some(S=>S.status==="error"),scopeProvenance:l.scopeProvenance},driftDelta:l.driftDelta,scoreBreakdown:l.scoreBreakdown??[],...y?{remediationPlan:y,remediationPlanPath:k}:{},...g?{appliedFixes:g.appliedFixes,remainingBlockers:g.remainingBlockers,verifyRecommended:g.verifyRecommended,fixResult:g,fixResultPath:w}:{}};return e.quiet||console.log(JSON.stringify(f,null,2)),Vn(l.healthScore,{profile:t.name},g)}if(l.healthScore){let g=l.healthScore,y=Math.round(g.passed/g.total*100),k=y>=80?p.green:y>=50?p.yellow:p.red,w="\u2588".repeat(Math.floor(y/5))+"\u2591".repeat(20-Math.floor(y/5));console.log(p.bold(`
62
- \u{1F4CA} Health Score:`)),console.log(` ${k(`${y}%`)} ${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
- `)),K(l.python,"Python"),K(l.poetry,"Poetry"),K(l.pipx,"pipx"),K(l.go,"Go"),K(l.rapidkitCore,"RapidKit Core"),ko({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=>Wn(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,y)=>g+y.blockingFindings,0),b$1=m.reduce((g,y)=>g+y.advisoryFindings,0),j=[l.python,l.rapidkitCore].some(g=>g.status==="error");if(j||h>0||b$1>0)if(console.log(p.bold.yellow(`
69
- \u26A0\uFE0F Doctor verdict: ${l.healthScore?.verdict??"attention"} \xB7 ${h} blocking finding(s) \xB7 ${b$1} advisory finding(s)`)),j&&console.log(p.bold.red("\u274C System requirements not met")),e.plan)await me(l.projects,false,{planOnly:true,json:e.json,policyProfile:t.name,artifactRoot:r,historyScope:"workspace"});else if(e.fix||e.apply){if(await me(l.projects,true,{skipConfirmation:e.apply===true,policyProfile:t.name,artifactRoot:r,historyScope:"workspace"}),!e.json){let g=await Ft(r,false,t),y=g.projects.map(ee).reduce((w,v)=>w+v.blockingFindings,0),k=[g.python,g.rapidkitCore].some(w=>w.status==="error");k||y>0?(console.log(p.bold.yellow(`
70
- \u26A0\uFE0F Post-fix verification found ${y} remaining issue(s)`)),k&&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 me(l.projects,false);else console.log(p.bold.green(`
72
- \u2705 All checks passed! Workspace is healthy.`));return Ve(l.healthScore,{profile:t.name})}else if(a){let r=await nr(process.cwd());if(!r){let v=await Le(process.cwd());if(e.json){let D={contract:Ae(),policyProfile:t,scope:"project",status:"error",generatedAt:new Date().toISOString(),workspace:v?{name:d.basename(v),path:v}: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:v?"doctor.project.scope.not_found_in_workspace":"doctor.project.scope.not_found",message:v?"No project found in the current directory within this workspace.":"No Workspai project found in the current directory or parents.",recommendation:v?"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:v?["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(D,null,2)),1}v?(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 Kn(r,t),l=c$1.workspacePath?Gn(c$1.workspacePath):null;if(e.json){let v,D=e.plan||e.fix||e.apply?await _t([c$1.project],t.name):void 0,A=r,f=[],S=D?await Tt(A,D,f):void 0,x;(e.fix||e.apply)&&!e.plan&&(v=await me([c$1.project],true,{skipConfirmation:e.apply===true||e.fix===true,json:true,policyProfile:t.name})??c({appliedFixes:[],remainingBlockers:[],verifyRecommended:b}),c$1=await Kn(r,t),v={...v,remainingBlockers:Ln([c$1.project])},x=await $e(A,v,f),await Fe(A,v,"project"));let W=Gn(c$1.project.path),P=ee(c$1.project),L={contract:Ae(),policyProfile:t,scope:"project",workspace:l?{name:d.basename(l),path:l}:null,project:{...Bn(c$1.project),path:W},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:P.verdict,probeSummary:P,blockingFindings:P.blockingFindings,advisoryFindings:P.advisoryFindings,projectAdvisoryWarningProjects:P.advisoryFindings>0?1:0,projectAdvisoryWarnings:P.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??[],...D?{remediationPlan:D,remediationPlanPath:S}:{},...v?{appliedFixes:v.appliedFixes,remainingBlockers:v.remainingBlockers,verifyRecommended:v.verifyRecommended,fixResult:v,fixResultPath:x}:{}};return e.quiet||console.log(JSON.stringify(L,null,2)),Vn(c$1.healthScore,{profile:t.name},v)}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,b$1=h>=80?p.green:h>=50?p.yellow:p.red,j="\u2588".repeat(Math.floor(h/5))+"\u2591".repeat(20-Math.floor(h/5));console.log(p.bold(`
73
- \u{1F4CA} Health Score:`)),console.log(` ${b$1(`${h}%`)} ${p.gray(j)}`),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
- `)),K(c$1.python,"Python"),K(c$1.poetry,"Poetry"),K(c$1.pipx,"pipx"),K(c$1.go,"Go"),K(c$1.rapidkitCore,"RapidKit Core"),console.log(p.bold(`
77
- \u{1F4E6} Project (1):`)),Wn(c$1.project,c$1.rapidkitCore);let g=[c$1.python,c$1.rapidkitCore].some(v=>v.status==="error"),y=ee(c$1.project),k=y.blockingFindings,w=y.advisoryFindings;if(g||k>0||w>0)if(console.log(p.bold.yellow(`
78
- \u26A0\uFE0F Doctor verdict: ${y.verdict} \xB7 ${k} blocking finding(s) \xB7 ${w} advisory finding(s)`)),g&&console.log(p.bold.red("\u274C System requirements not met")),e.plan){let v=c$1.workspacePath??r,D=c$1.workspacePath&&d.resolve(c$1.workspacePath)!==d.resolve(r)?[r]:[];await me([c$1.project],false,{planOnly:true,json:e.json,policyProfile:t.name,artifactRoot:v,artifactMirrorRoots:D,historyScope:"project"});}else if(e.fix||e.apply){let v=c$1.workspacePath??r,D=c$1.workspacePath&&d.resolve(c$1.workspacePath)!==d.resolve(r)?[r]:[];await me([c$1.project],true,{skipConfirmation:e.apply===true,policyProfile:t.name,artifactRoot:v,artifactMirrorRoots:D,historyScope:"project"});}else k>0&&await me([c$1.project],false);else console.log(p.bold.green(`
79
- \u2705 All checks passed! Project is healthy.`));return Ve(c$1.healthScore,{profile:t.name})}else {let r=await Bt(),c=r.python,l=r.poetry,m=r.pipx,h=r.go,b=r.rapidkitCore,j=[c,l,m,h,b],g=Kt(j,[]),y=[c,b].filter(w=>w.status==="error").length;if(e.json){let w={contract:Ae(),policyProfile:t,scope:"system",status:y>0?"error":"ok",generatedAt:new Date().toISOString(),healthScore:g,system:{python:c,poetry:l,pipx:m,go:h,rapidkitCore:b},summary:{totalChecks:j.length,errors:y,warnings:j.filter(v=>v.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)&&y>0?1:0}return console.log(p.bold(`System Tools:
80
- `)),K(c,"Python"),K(l,"Poetry"),K(m,"pipx"),K(h,"Go"),K(b,"RapidKit Core"),[c,b].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)&&y>0?1:0}}export{Mt as a,lt as b,pt as c,Ne as d,lr as e,be as f,dr as g,ur as h,pr as i,mr as j,fr as k,gr as l,yr as m,hr as n,Ve as o,Vn as p,Ts as q};