workspai 0.73.0 → 0.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/contracts/agent-framework-capabilities.v1.json +454 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +166 -0
- package/contracts/create-planner-capabilities.v1.json +24 -0
- package/contracts/extension-cli-compatibility.v1.json +6 -0
- package/contracts/published-contract-catalog.v1.json +30 -0
- package/contracts/runtime-command-surface.v1.json +78 -4
- package/contracts/workspace-intelligence/agent-framework-adapter-manifest.v1.json +2127 -0
- package/contracts/workspace-intelligence/agent-framework-admission-candidate.v1.json +193 -0
- package/contracts/workspace-intelligence/agent-framework-change-plan.v1.json +280 -0
- package/contracts/workspace-intelligence/agent-framework-conformance-report.v1.json +269 -0
- package/contracts/workspace-intelligence/agent-framework-ownership-receipt.v1.json +147 -0
- package/contracts/workspace-intelligence/workspace-model.v1.json +4 -0
- package/contracts/workspace-intelligence-architecture.v1.json +28 -2
- package/dist/analyze-FRQVJ3VJ.js +1 -0
- package/dist/{artifact-remediation-plan-WDK5ISRU.js → artifact-remediation-plan-HD5K52UJ.js} +1 -1
- package/dist/autopilot-release-D3UES53H.js +1 -0
- package/dist/capabilities-command-VK3LQLP2.js +1 -0
- package/dist/chunk-252EKOR6.js +2 -0
- package/dist/chunk-36VNERGC.js +1 -0
- package/dist/{chunk-TZK2R6RD.js → chunk-4DX4HBG3.js} +1 -1
- package/dist/chunk-4KEZQLBU.js +2 -0
- package/dist/{chunk-PKKSRXUS.js → chunk-6B7L4NZE.js} +1 -1
- package/dist/chunk-7NKM6EHE.js +7 -0
- package/dist/{chunk-FE5R6EUV.js → chunk-BLEIUQL6.js} +1 -1
- package/dist/{chunk-37SWTS2B.js → chunk-BR6QIYQS.js} +1 -1
- package/dist/chunk-CGNMS32W.js +97 -0
- package/dist/{chunk-3GO7BJ5J.js → chunk-CK73SQFF.js} +1 -1
- package/dist/chunk-CMLLERGG.js +418 -0
- package/dist/{chunk-MGL6DBOR.js → chunk-COOVCORC.js} +1 -1
- package/dist/chunk-D4AMCZJU.js +7 -0
- package/dist/chunk-DFREJHG7.js +1 -0
- package/dist/{chunk-OIGI7MP6.js → chunk-DJH2CH42.js} +1 -1
- package/dist/chunk-DT3LRKZQ.js +1 -0
- package/dist/{chunk-D3N2WFDV.js → chunk-FS3WLRQ4.js} +1 -1
- package/dist/chunk-G3ZC5W4U.js +1 -0
- package/dist/{chunk-TIZCESKY.js → chunk-GE46XKD2.js} +1 -1
- package/dist/chunk-GIFAGOMK.js +2 -0
- package/dist/{chunk-FRH7AIGY.js → chunk-HLSOZOL3.js} +3 -3
- package/dist/chunk-J4J3RYCL.js +4 -0
- package/dist/{chunk-JK6XEF7K.js → chunk-JKAAKE4Z.js} +1 -1
- package/dist/chunk-LMOTDLJF.js +2 -0
- package/dist/{chunk-DNKELRK6.js → chunk-MXI2DWLL.js} +1 -1
- package/dist/chunk-NFWUAEVQ.js +12 -0
- package/dist/chunk-NGU7RYXA.js +9 -0
- package/dist/{chunk-3WHE7V4M.js → chunk-NLRZFIC6.js} +1 -1
- package/dist/chunk-O2CFT2A3.js +1 -0
- package/dist/{chunk-EBQS5T7Q.js → chunk-OA2YJN22.js} +1 -1
- package/dist/chunk-OH6LV5JP.js +6 -0
- package/dist/{chunk-J44PN2FX.js → chunk-P5RZO5BY.js} +18 -18
- package/dist/{chunk-TSYDTKXO.js → chunk-RPM67N7A.js} +1 -1
- package/dist/{chunk-XVTN5DDV.js → chunk-RU3UT7GJ.js} +1 -1
- package/dist/{chunk-IPZT6WKM.js → chunk-RX3U7JKF.js} +4 -4
- package/dist/chunk-SRCZX2KC.js +13 -0
- package/dist/chunk-TXVMHEJS.js +1 -0
- package/dist/chunk-V5WVGPOP.js +1 -0
- package/dist/{chunk-FY4X2VOE.js → chunk-VHMDWRDG.js} +2 -2
- package/dist/chunk-W7I65IXY.js +3 -0
- package/dist/chunk-WOPZX56J.js +2 -0
- package/dist/chunk-XF65LQ6M.js +1 -0
- package/dist/chunk-YP436V7Q.js +2 -0
- package/dist/{chunk-HAZGSAKP.js → chunk-ZI54C2AO.js} +1 -1
- package/dist/chunk-ZKYH44ER.js +1 -0
- package/dist/chunk-ZS7JHATN.js +1 -0
- package/dist/{chunk-NSMRQOWP.js → chunk-ZW4QV6SB.js} +1 -1
- package/dist/{create-XYKXS3JB.js → create-7UENFCJK.js} +1 -1
- package/dist/{demo-kit-RKTHTXHJ.js → demo-kit-ALW6OSQV.js} +1 -1
- package/dist/doctor-KGADT4PI.js +1 -0
- package/dist/{dotnet-webapi-clean-VJX6SGGP.js → dotnet-webapi-clean-6Z4EXEJY.js} +1 -1
- package/dist/{goal-lifecycle-BIX2JVNO.js → goal-lifecycle-HIQGDEEP.js} +1 -1
- package/dist/goal-pack-63PEP2ND.js +1 -0
- package/dist/{gofiber-standard-I6ASLOEE.js → gofiber-standard-TDJQIVQZ.js} +1 -1
- package/dist/{gogin-standard-U2LSRLIP.js → gogin-standard-UEF3IHSJ.js} +1 -1
- package/dist/index.d.ts +18 -0
- package/dist/index.js +266 -248
- package/dist/pipeline-VFI35PR4.js +5 -0
- package/dist/{project-agent-entry-Y3NEHZED.js → project-agent-entry-Z3OY3S7T.js} +1 -1
- package/dist/{project-intelligence-lens-6Q6XSUDJ.js → project-intelligence-lens-YWICXW6P.js} +1 -1
- package/dist/{project-test-coverage-5PXAHBYQ.js → project-test-coverage-3P5FH6E5.js} +1 -1
- package/dist/proof-carrying-change-BAP2C3KV.js +1 -0
- package/dist/{pythonRapidkitExec-44ORGQ4R.js → pythonRapidkitExec-UMFLDIYR.js} +1 -1
- package/dist/{rust-axum-JMV7UPO7.js → rust-axum-4TRVPFMB.js} +1 -1
- package/dist/{springboot-standard-OC2RS3KC.js → springboot-standard-COWL75GT.js} +1 -1
- package/dist/verified-goal-A6WOMNTU.js +1 -0
- package/dist/{workspace-ROUEA3RT.js → workspace-PAXTJCMH.js} +1 -1
- package/dist/{workspace-agent-sync-6UYG33EQ.js → workspace-agent-sync-MGCEF4ON.js} +1 -1
- package/dist/{workspace-archive-OSMU3CK6.js → workspace-archive-3AURTMYA.js} +1 -1
- package/dist/{workspace-context-H7ZXR6VI.js → workspace-context-2G6QZ6D3.js} +1 -1
- package/dist/{workspace-contract-2V2BI6A3.js → workspace-contract-VWPOIYHJ.js} +1 -1
- package/dist/{workspace-explain-IBMTRUSF.js → workspace-explain-HLEBUK4K.js} +1 -1
- package/dist/{workspace-feedback-D6HJLKBQ.js → workspace-feedback-FF34CSJE.js} +1 -1
- package/dist/{workspace-foundation-H5B3TTZD.js → workspace-foundation-X7LOGTS3.js} +1 -1
- package/dist/{workspace-graph-stream-YDEET5LK.js → workspace-graph-stream-XGSRDRLI.js} +1 -1
- package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
- package/dist/{workspace-history-WWPS4U7H.js → workspace-history-EQG5UBKW.js} +1 -1
- package/dist/{workspace-intelligence-DXKQXTTM.js → workspace-intelligence-GFJKIWBX.js} +1 -1
- package/dist/{workspace-intelligence-benchmark-L46EGZZM.js → workspace-intelligence-benchmark-R5MEGJQS.js} +1 -1
- package/dist/{workspace-intelligence-evaluation-QDSOOUHH.js → workspace-intelligence-evaluation-4AB4BBRP.js} +1 -1
- package/dist/{workspace-intelligence-runner-SCB44IXU.js → workspace-intelligence-runner-BU6JKNUD.js} +1 -1
- package/dist/{workspace-knowledge-graph-BNEVFEOW.js → workspace-knowledge-graph-OUTCLYS2.js} +1 -1
- package/dist/{workspace-knowledge-graph-query-GOC365ZR.js → workspace-knowledge-graph-query-TT2KK3SF.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-XWJRUMAC.js +1 -0
- package/dist/workspace-marker-7U3NYRPJ.js +1 -0
- package/dist/workspace-mcp-serve-JYUKX3YS.js +3 -0
- package/dist/workspace-model-DUGPW5IB.js +1 -0
- package/dist/{workspace-onboarding-IRBVZTT4.js → workspace-onboarding-C4CKWTJ3.js} +1 -1
- package/dist/{workspace-python-engine-state-BE4A3BL5.js → workspace-python-engine-state-VCOLSEWV.js} +2 -2
- package/dist/{workspace-readme-HA6XLDME.js → workspace-readme-4FCKAQME.js} +1 -1
- package/dist/{workspace-registry-summary-CBZDSG6I.js → workspace-registry-summary-4KX4QD55.js} +1 -1
- package/dist/workspace-repair-engine-OVW4J3DI.js +3 -0
- package/dist/workspace-run-NVQGRZYO.js +1 -0
- package/dist/{workspace-verify-QTRY7WW3.js → workspace-verify-B7HEFYO6.js} +1 -1
- package/dist/workspace-watch-TQYAMLIV.js +1 -0
- package/docs/README.md +4 -1
- package/docs/agent-framework-adapters.md +279 -0
- package/docs/ci-workflows.md +1 -1
- package/docs/commands-reference.md +16 -0
- package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +5 -0
- package/docs/creating-workspaces-and-projects.md +18 -4
- package/package.json +7 -1
- package/scripts/enterprise-package-smoke.mjs +98 -0
- package/dist/analyze-WC2TY5AT.js +0 -1
- package/dist/autopilot-release-LJDRECFW.js +0 -1
- package/dist/capabilities-command-NFGX42CH.js +0 -1
- package/dist/chunk-2BCECNIW.js +0 -1
- package/dist/chunk-2LIVMG5C.js +0 -2
- package/dist/chunk-3SNP6M4M.js +0 -2
- package/dist/chunk-46QH3ZVI.js +0 -105
- package/dist/chunk-4HQU2GQM.js +0 -1
- package/dist/chunk-4JAURS76.js +0 -13
- package/dist/chunk-7O7P4MRD.js +0 -1
- package/dist/chunk-AQNU5RXV.js +0 -2
- package/dist/chunk-CQBM6BBP.js +0 -2
- package/dist/chunk-CY4QZ3PE.js +0 -3
- package/dist/chunk-EDDGQ6LM.js +0 -2
- package/dist/chunk-F6CTGVJA.js +0 -9
- package/dist/chunk-K3O3HENC.js +0 -5
- package/dist/chunk-LDJAUIAG.js +0 -1
- package/dist/chunk-LGC4CRUF.js +0 -3
- package/dist/chunk-ND5YAC4T.js +0 -1
- package/dist/chunk-NNQE4DS2.js +0 -2
- package/dist/chunk-NSH7TTSV.js +0 -1
- package/dist/chunk-R5OJD5K2.js +0 -1
- package/dist/chunk-SO4CGS35.js +0 -4
- package/dist/chunk-T5NBSCVX.js +0 -97
- package/dist/chunk-UCNIXOTL.js +0 -2
- package/dist/chunk-UNXG3ZFV.js +0 -1
- package/dist/chunk-VBMWFT7Q.js +0 -1
- package/dist/chunk-YYELANJO.js +0 -7
- package/dist/chunk-ZZWGD3X3.js +0 -12
- package/dist/doctor-LQ7FT6AZ.js +0 -1
- package/dist/goal-pack-SUWH6K7U.js +0 -1
- package/dist/pipeline-NSPPWD7U.js +0 -5
- package/dist/proof-carrying-change-456TYEDW.js +0 -1
- package/dist/verified-goal-GRH5UOJR.js +0 -1
- package/dist/workspace-graph-token-efficiency-XM3LYFUC.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-2NMV7LEJ.js +0 -1
- package/dist/workspace-marker-XGAWZZDX.js +0 -1
- package/dist/workspace-mcp-serve-JLZTTEVG.js +0 -3
- package/dist/workspace-model-XSNLDUI2.js +0 -1
- package/dist/workspace-repair-engine-TDUNQSFJ.js +0 -3
- package/dist/workspace-run-I2W5PIPK.js +0 -1
- package/dist/workspace-watch-PDQKYBYQ.js +0 -1
- /package/dist/{chunk-K33JJVQZ.js → chunk-VN2MKTQO.js} +0 -0
package/dist/chunk-T5NBSCVX.js
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import {b}from'./chunk-B6FJ6RG6.js';import {a as a$3}from'./chunk-7Q7X4X5I.js';import {j,g as g$1}from'./chunk-XVTN5DDV.js';import {d as d$1}from'./chunk-7O7P4MRD.js';import {a as a$a}from'./chunk-JK6XEF7K.js';import {c as c$3,a as a$8,d,b as b$4}from'./chunk-N4B2M44I.js';import {a,c as c$4,h as h$1,g as g$3,k as k$1,f as f$2,d as d$3,e as e$3,i as i$1,j as j$3}from'./chunk-AO2ZI42U.js';import {f as f$1,e as e$1,g as g$2}from'./chunk-NSH7TTSV.js';import {a as a$1,b as b$1}from'./chunk-MGL6DBOR.js';import {c as c$2}from'./chunk-TIZCESKY.js';import {a as a$7,b as b$2}from'./chunk-ZZWGD3X3.js';import {a as a$e}from'./chunk-CQBM6BBP.js';import {b as b$3}from'./chunk-ND5YAC4T.js';import {a as a$5}from'./chunk-NMXGSVMD.js';import {a as a$4}from'./chunk-NNQE4DS2.js';import {z}from'./chunk-LGC4CRUF.js';import {j as j$2,l,m as m$1,d as d$2,e as e$2,b as b$6,a as a$d}from'./chunk-YYELANJO.js';import {a as a$c}from'./chunk-GR6442P7.js';import {g,h,i}from'./chunk-FE5R6EUV.js';import {a as a$6}from'./chunk-AFIFZTOY.js';import {a as a$2}from'./chunk-2LIVMG5C.js';import {s,p,t as t$1}from'./chunk-ODK4LCEL.js';import {e}from'./chunk-PKKSRXUS.js';import {a as a$b}from'./chunk-TQEMLBAG.js';import {c}from'./chunk-25AWHAB5.js';import {c as c$1,j as j$1,b as b$5,t as t$2,n,p as p$1,m as m$2}from'./chunk-RGNCL5OB.js';import {a as a$9}from'./chunk-2FIX2MDC.js';import {t,k,u as u$1}from'./chunk-VQZ5PI5J.js';import f from'chalk';import {createHash}from'crypto';import {execa}from'execa';import m from'fs-extra';import u from'path';import {existsSync}from'fs';var Xi=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],Qi=["tests","test","src/test","__tests__","e2e","playwright","cypress"],eo=["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"],to=["src","app","pages"],no=["dev","build","test","lint"];function Xn(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 Qn(e,t){for(let o of Xi)if(await m.pathExists(u.join(e,o)))return true;let i=t??(await m.pathExists(u.join(e,"package.json"))?await m.readJson(u.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 ei(e,t){for(let o of Qi)if(await m.pathExists(u.join(e,o)))return true;for(let o of eo)if(await m.pathExists(u.join(e,o)))return true;let i=Xn(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 io(e)}async function io(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 r=u.join(e,s);if(!await m.pathExists(r))continue;let c=[{dir:r,depth:0}];for(;c.length>0;){let a=c.shift();if(!a)break;let l=[];try{l=await m.readdir(a.dir);}catch{continue}for(let d of l){let p=u.join(a.dir,d);if(i.test(d))return true;if(!(a.depth>=3||o.has(d)||d.startsWith(".")))try{(await m.stat(p)).isDirectory()&&c.push({dir:p,depth:a.depth+1});}catch{continue}}}}return false}async function Ut(e){for(let t of to){let i=u.join(e,t);if(await m.pathExists(i))try{if((await m.readdir(i)).some(o=>!o.startsWith(".")))return true}catch{continue}}return false}function oo(e){let t=e.key;return b$6(t).key}function ro(e,t,i){return a$d(t,i).some(o=>!!e[o])}async function ti(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=oo(i),s=b$6(o),r=Xn(n),c=[],a=await m.pathExists(u.join(t,"package-lock.json"))||await m.pathExists(u.join(t,"pnpm-lock.yaml"))||await m.pathExists(u.join(t,"yarn.lock"))||await m.pathExists(u.join(t,"bun.lockb"));c.push({id:"frontend-lockfile-integrity",label:"Frontend lockfile integrity",status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml/bun.lockb).",recommendation:a?void 0:"Commit a lockfile for deterministic installs and CI parity."});let l=await m.pathExists(u.join(t,"tsconfig.json")),d=await m.pathExists(u.join(t,"jsconfig.json")),p=l||d;c.push({id:"frontend-typescript-surface",label:"TypeScript project surface",status:p?"pass":"warn",severity:"warn",scope:"project-scoped",reason:p?l?"tsconfig.json detected.":"jsconfig.json detected.":"No tsconfig.json or jsconfig.json detected.",recommendation:p?void 0:"Add tsconfig.json (or jsconfig.json) for typed frontend builds and IDE parity."});let y=s.fileHints.length>0&&s.fileHints.some(v=>existsSync(u.join(t,v)));c.push({id:"frontend-framework-config",label:`${s.displayName} config surface`,status:y?"pass":"warn",severity:"warn",scope:"project-scoped",reason:y?`${s.displayName} configuration artifacts detected.`:`No ${s.displayName} config markers detected (${s.fileHints.join(", ")||"n/a"}).`,recommendation:y?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let v of no){let C=ro(r,o,v),h=v==="dev"||v==="build",w=!C&&v==="test"?h$1({projectPath:t,frameworkDisplayName:s.displayName,scriptName:v,scriptValue:g$3(r)}):void 0;c.push({id:`frontend-script-${v}`,label:`${v} script surface`,status:C?"pass":h?"fail":"warn",severity:h?"error":"warn",scope:"project-scoped",reason:C?`package.json exposes a ${v} script for ${s.displayName}.`:`No ${v} script detected for ${s.displayName}.`,recommendation:C?void 0:`Add a "${a$d(o,v)[0]??v}" script to package.json.`,repairCapability:w});}let b=await Ut(t);return c.push({id:"frontend-source-tree",label:"Frontend source tree",status:b?"pass":"warn",severity:"warn",scope:"project-scoped",reason:b?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:b?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),c}var so=s.doctorFixResult.schemaVersion,Ce="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function Me(e){return {schemaVersion:so,generatedAt:new Date().toISOString(),appliedFixes:e.appliedFixes,remainingBlockers:e.remainingBlockers,verifyRecommended:e.verifyRecommended??Ce}}var ao=["python","node","go","java","rust","elixir","clojure","deno","bun","php","ruby","dotnet","scala","kotlin","c","cpp","unknown"],ni={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","MODULE.bazel.lock","requirements.bazel.lock"],cpp:["conan.lock","vcpkg-lock.json","MODULE.bazel.lock","requirements.bazel.lock"],unknown:[]},ii={node:["package.json"],deno:["deno.json","deno.jsonc"],bun:["package.json","bunfig.toml",".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","MODULE.bazel","WORKSPACE"],cpp:["CMakeLists.txt","meson.build","Makefile","MODULE.bazel","WORKSPACE"],unknown:[]},co=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
|
|
2
|
-
`),Yt=[".env",".env.*","!.env.example"];function We(e){return e&&ao.includes(e)?e:"unknown"}async function Pe(e,t){for(let i of t){if(i.includes("*")){let n=i.replace("*","");if(await lo(e,n,2))return true;continue}if(await m.pathExists(u.join(e,i)))return true}return false}async function lo(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 r=[];try{r=await m.readdir(s.dir,{withFileTypes:true});}catch{continue}for(let c of r){if(o.has(c.name))continue;let a=u.join(s.dir,c.name);if(c.isFile()&&c.name.endsWith(t))return true;c.isDirectory()&&s.depth<i&&!c.name.startsWith(".")&&n.push({dir:a,depth:s.depth+1});}}return false}async function Zt(e,t=6){let i=await m.pathExists(u.join(e,"Dockerfile")),n=false,o=false,s=new Set(["docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml"]),r=new Set(["node_modules",".git",".workspai",".rapidkit","dist","build","coverage","target","vendor"]),c=[{dir:e,depth:0}];for(;c.length>0&&(!n||!o);){let a=c.shift();if(!a)break;let l=[];try{l=await m.readdir(a.dir,{withFileTypes:true});}catch{continue}for(let d of l)r.has(d.name)||(d.isFile()?(a.depth>0&&d.name==="Dockerfile"&&(n=true),s.has(d.name)&&(o=true)):d.isDirectory()&&a.depth<t&&!d.name.startsWith(".")&&c.push({dir:u.join(a.dir,d.name),depth:a.depth+1}));}return {rootDockerfile:i,nestedDockerfile:n,compose:o}}async function et(e){try{return await m.pathExists(e)?await m.readFile(e,"utf8"):""}catch{return ""}}async function Dt(e,t){let i=[];for(let n of t){let o=await et(u.join(e,n));o&&i.push(o);}return i.join(`
|
|
3
|
-
`)}async function po(e){let t=u.join(e,".github","workflows"),i=[];try{i=await m.readdir(t,{withFileTypes:true});}catch{return ""}let n=[],o=0;for(let s of i.filter(r=>r.isFile()&&/\.(?:ya?ml)$/i.test(r.name)).sort((r,c)=>r.name.localeCompare(c.name)).slice(0,64)){let r=u.join(t,s.name);try{let c=await m.stat(r);if(c.size>512*1024||o+c.size>1024*1024)continue;n.push(await m.readFile(r,"utf8")),o+=c.size;}catch{}}return n.join(`
|
|
4
|
-
`)}var uo=new Set([".c",".cc",".clj",".cljs",".cpp",".cs",".ex",".exs",".go",".h",".hpp",".java",".js",".jsx",".kt",".kts",".mjs",".cjs",".php",".py",".rb",".rs",".scala",".svelte",".ts",".tsx",".vue"]),mo=[/\bprocess\.env(?:\.([A-Z][A-Z0-9_]*)|\[['"]([A-Z][A-Z0-9_]*)['"]\])/g,/\bimport\.meta\.env\.([A-Z][A-Z0-9_]*)/g,/\b(?:Deno\.env\.get|os\.getenv|os\.Getenv|os\.LookupEnv|System\.getenv|std::env::var|env!|option_env!|getenv|Environment\.GetEnvironmentVariable)\(\s*['"]([A-Z][A-Z0-9_]*)['"]/g,/\bos\.environ(?:\.get\(\s*['"]([A-Z][A-Z0-9_]*)['"]|\[\s*['"]([A-Z][A-Z0-9_]*)['"]\s*\])/g,/\bENV(?:\.fetch\(\s*['"]([A-Z][A-Z0-9_]*)['"]|\[\s*['"]([A-Z][A-Z0-9_]*)['"]\s*\])/g,/\$_ENV\[\s*['"]([A-Z][A-Z0-9_]*)['"]\s*\]/g,/@Value\(\s*['"]\$\{([A-Z][A-Z0-9_]*)(?::[^}]*)?\}['"]\s*\)/g],fo=new Set(["BROWSER","CI","GITHUB_WORKSPACE","HOME","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PAGER","PATH","PROCESSOR_ARCHITEW6432","SSH_CLIENT","SSH_TTY","SYSTEMROOT","TEMP","TMP","TMPDIR","XDG_CACHE_HOME"]);async function go(e){let t=new Set,i=new Set([".git",".next",".nuxt",".output",".rapidkit",".svelte-kit",".venv",".workspai","build","coverage","dist","node_modules","target","vendor"]),n=[{dir:e,depth:0}],o=0;for(;n.length>0&&o<300;){let r=n.shift();if(!r)break;let c=[];try{c=await m.readdir(r.dir,{withFileTypes:true});}catch{continue}for(let a of c){if(i.has(a.name))continue;let l=u.join(r.dir,a.name);if(a.isDirectory()){r.depth<6&&!a.name.startsWith(".")&&n.push({dir:l,depth:r.depth+1});continue}if(!a.isFile()||!uo.has(u.extname(a.name).toLowerCase()))continue;o+=1;let d="";try{if((await m.stat(l)).size>512*1024)continue;d=await m.readFile(l,"utf8");}catch{continue}for(let p of mo){p.lastIndex=0;for(let y of d.matchAll(p)){let b=y.slice(1).find(v=>typeof v=="string"&&v.length>0);b&&!fo.has(b)&&t.add(b);}}}}let s=await et(u.join(e,".env"));for(let r of s.split(/\r?\n/)){let c=r.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/);c?.[1]&&t.add(c[1]);}return [...t].sort((r,c)=>r.localeCompare(c))}async function yo(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 m.pathExists(u.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 m.pathExists(u.join(e.projectPath,"pom.xml")),i=await m.pathExists(u.join(e.projectPath,"mvnw"))||await m.pathExists(u.join(e.projectPath,"mvnw.cmd")),n=await m.pathExists(u.join(e.projectPath,"gradlew"))||await m.pathExists(u.join(e.projectPath,"gradlew.bat")),o=t?i?process.platform==="win32"?".\\mvnw.cmd -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"./mvnw -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"mvn -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":n?process.platform==="win32"?".\\gradlew.bat --project-cache-dir .workspai/cache/java/gradle dependencies":"./gradlew --project-cache-dir .workspai/cache/java/gradle dependencies":"gradle --project-cache-dir .workspai/cache/java/gradle dependencies";return t?{command:o,title:"Warm Maven dependency graph",files:["pom.xml"],limitations:["Maven does not provide a native transitive lockfile; dependency:go-offline warms dependencies but does not create reproducibility evidence."]}:{command:o,title:"Prepare Gradle dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]}}if(e.runtime==="scala")return {command:"sbt update",title:"Prepare Scala dependency baseline",files:["build.sbt","project/build.properties","project/plugins.sbt"],limitations:["Review resolved dependency and plugin changes before committing."]};if(e.runtime==="kotlin")return {command:process.platform==="win32"?".\\gradlew.bat dependencies":"./gradlew dependencies",title:"Prepare Kotlin dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]};if(e.runtime==="rust")return {command:"cargo fetch",title:"Generate Rust dependency baseline",files:["Cargo.toml","Cargo.lock"],limitations:["Review Cargo.lock changes before committing."]};if(e.runtime==="php")return {command:"composer install",title:"Generate Composer lockfile",files:["composer.json","composer.lock"],limitations:["Review composer.lock changes before committing."]};if(e.runtime==="ruby")return {command:"bundle install",title:"Generate Bundler lockfile",files:["Gemfile","Gemfile.lock"],limitations:["Review Gemfile.lock changes before committing."]};if(e.runtime==="dotnet")return {command:"dotnet restore",title:".NET dependency restore",files:["*.sln","*.csproj","packages.lock.json","Directory.Packages.props"],limitations:["Enable NuGet lock files in the project when release policy requires deterministic restore."]};if(e.runtime==="elixir")return {command:"mix deps.get",title:"Generate Elixir dependency lockfile",files:["mix.exs","mix.lock"],limitations:["Review mix.lock changes before committing."]};if(e.runtime==="clojure")return {command:"clojure -P",title:"Prepare Clojure dependency baseline",files:["deps.edn","project.clj"],limitations:["Review dependency cache and CI restore policy before release."]};if(e.runtime==="python"){let t=await et(u.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 tt(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 ho(e){if(e.runtime==="node"){let i=tt(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}if(e.kind==="security"){let n=a$e(e.projectPath);return {command:n==="pnpm"?"pnpm audit --audit-level=moderate":n==="yarn"?m.existsSync(u.join(e.projectPath,".yarnrc.yml"))?"yarn npm audit --severity moderate":"yarn audit --level moderate":n==="bun"?"bun audit":"npm audit --audit-level=moderate",title:"Define Node security audit script",targetName:"audit",files:["package.json"]}}return 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 bo(e){return j$3({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 Xt(e){let t=ho({runtime:e.runtime,kind:e.kind,projectPath:e.projectPath,packageJsonData:e.packageJsonData});if(t)return (e.runtime==="node"||e.runtime==="bun")&&e.packageJsonData?i$1({issueId:e.issueId,title:t.title,projectPath:e.projectPath,scriptName:t.targetName,scriptValue:t.command,reason:e.reason,risk:"guarded",limitations:t.limitations}):await m.pathExists(u.join(e.projectPath,"Makefile"))?bo({issueId:e.issueId,projectPath:e.projectPath,contract:t,reason:e.reason}):De({issueId:e.issueId,title:t.title,projectPath:e.projectPath,files:t.files.filter(i=>i!=="Makefile"),reason:`${e.reason} The repository does not expose a Makefile, so Doctor will not invent a new command surface.`,limitations:t.limitations})}function De(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=>u.join(e.projectPath,t)),refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function ko(e){return d$3({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${co}
|
|
5
|
-
`,reason:"Create a Docker build ignore baseline to keep secrets, dependencies, and reports out of container contexts."})}async function vo(e){if(!await m.pathExists(u.join(e,".gitignore")))return d$3({issueId:"surface-security-hygiene",title:"Create .gitignore secret baseline",projectPath:e,relativePath:".gitignore",content:`${Yt.join(`
|
|
6
|
-
`)}
|
|
7
|
-
`,reason:"Create a minimal ignore baseline so local env files are not committed accidentally."});let t=await et(u.join(e,".gitignore")),i=Yt.filter(n=>!t.split(/\r?\n/).includes(n));return e$3({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 wo(e){let t=ii[e.runtime]??[],i=ni[e.runtime]??[];if(t.length===0&&i.length===0)return null;let n=(e.runtime==="c"||e.runtime==="cpp")&&e$2(e.projectPath)||await Pe(e.projectPath,t),o=await Pe(e.projectPath,i),s=e.runtime==="java"&&await m.pathExists(u.join(e.projectPath,"pom.xml"))&&!await Pe(e.projectPath,["build.gradle","build.gradle.kts"]),r=n&&!o?await yo({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.":s?"Maven manifest detected. Maven has no native transitive lockfile, so reproducibility requires pinned dependency and plugin versions plus published resolved-dependency evidence.":`Dependency manifest detected, but no deterministic baseline found (${i.join(", ")}).`:"No dependency manifest markers detected for this runtime.",recommendation:n&&!o?s?"Pin dependency and plugin versions, then publish a resolved dependency tree or SBOM as release evidence.":"Generate and commit the runtime-native lockfile or package baseline before release.":void 0,repairCapability:n&&!o&&r?k$1({issueId:"surface-dependency-contract",title:r.title,projectPath:e.projectPath,command:r.command,files:r.files,fixKind:"dependency-sync",reason:s?"Warm the Maven dependency graph for inspection; reproducibility still requires pinned versions and published resolved-dependency evidence.":"Generate the runtime-native dependency baseline so CI, Doctor, and Studio share deterministic dependency evidence.",limitations:r.limitations}):void 0}}async function jo(e){let t=await m.pathExists(u.join(e.projectPath,".env.example")),i=await Pe(e.projectPath,[".env.sample",".env.template",".env.public"]),n=await m.pathExists(u.join(e.projectPath,".env")),o=await m.pathExists(u.join(e.projectPath,"docs","env.md"))||await m.pathExists(u.join(e.projectPath,"ENVIRONMENT.md")),s=await m.pathExists(u.join(e.projectPath,"config")),r=t||i||o||s,c=e.projectKind==="frontend",a=r?[]:await go(e.projectPath),l=n||a.length>0,d=!r&&!l,p=n||e.projectKind==="backend"||e.projectKind==="frontend"||e.projectKind==="fullstack",y=a.map(b=>`${b}=`).join(`
|
|
8
|
-
`);return {id:"surface-env-contract",label:"Environment/config contract",status:r||d?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:d?"not-applicable":"applicable",reason:r?"Environment/config contract marker detected.":d?"No runtime environment-variable usage was detected; an environment contract is not currently applicable.":c?"No frontend environment contract marker detected.":"No environment/config contract marker detected.",recommendation:r||d?void 0:p?"Add .env.example, config schema, or environment documentation for deterministic setup.":"Document the governed build/runtime variables or declare an explicit configuration schema; do not infer a dotenv contract from host-tooling references alone.",repairCapability:r?t&&!n?f$2({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:d?void 0:a.length>0&&p?d$3({issueId:"surface-env-contract",title:"Create environment contract skeleton",projectPath:e.projectPath,relativePath:".env.example",content:`${y}
|
|
9
|
-
`,reason:"Create a secret-free .env.example from environment keys observed in source. Values remain empty for project-owner review.",limitations:["Only variable names are copied; secrets and local values are never read into the generated contract.","Review required and optional variables before committing the example."]}):De({issueId:"surface-env-contract",title:n?"Define environment contract":"Review environment/config contract",projectPath:e.projectPath,files:n?[".env.example"]:["ENVIRONMENT.md"],reason:n?"A local .env exists, but no safe variable names could be inferred. Review the required keys before publishing an example.":"Environment-variable references were observed, but this project kind does not prove a dotenv contract. Document the governed build/runtime variables or declare an explicit configuration schema before generating files."})}}async function xo(e){let t=await Zt(e.projectPath),i=t.rootDockerfile,n=await m.pathExists(u.join(e.projectPath,".dockerignore")),o=t.compose;return i?{id:"surface-dockerignore",label:"Container build context hygiene",status:n?"pass":"warn",severity:"warn",scope:"project-scoped",reason:n?"Dockerfile and .dockerignore detected.":"Dockerfile detected without .dockerignore.",recommendation:n?void 0:"Add .dockerignore to exclude dependencies, reports, git metadata, and local env files from image builds.",repairCapability:n?void 0:ko(e.projectPath)}:{id:"surface-container-contract",label:"Container contract",status:"pass",severity:"warn",scope:"project-scoped",applicability:o||t.nestedDockerfile?"applicable":"not-applicable",reason:o?`Compose surface detected${t.nestedDockerfile?" with a nested Dockerfile":""}; container ownership remains scoped to its module.`:t.nestedDockerfile?"Nested Dockerfile detected; container ownership remains scoped to its module.":"No container intent was detected; a container contract is not currently applicable."}}async function Co(e){let t=["k8s","kubernetes","deploy","deployments","charts","helm","kustomization.yaml","kustomization.yml"];if(!await Pe(e.projectPath,t)){let c=["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"],a=await Pe(e.projectPath,c);return {id:"surface-deploy-contract",label:"Deployment contract",status:"pass",severity:"warn",scope:"project-scoped",applicability:a?"applicable":"not-applicable",reason:a?"A documented or provider-managed non-Kubernetes deployment surface was detected.":"No deployment intent was detected; a deployment contract is not currently applicable."}}let n=await Dt(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),r=o&&s;return {id:"surface-kubernetes-readiness",label:"Deployment readiness controls",status:r?"pass":"warn",severity:"warn",scope:"project-scoped",reason:r?"Deployment surface includes probe and resource-control markers.":"Deployment surface detected, but readiness/liveness probes or resource controls are incomplete.",recommendation:r?void 0:"Add readiness/liveness/startup probes and resource requests/limits to production deployment manifests.",repairCapability:r?void 0:De({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 Po(e){let t=await m.pathExists(u.join(e.projectPath,".gitignore")),n=(await et(u.join(e.projectPath,".gitignore"))).split(/\r?\n/),o=t&&Yt.every(j=>n.includes(j)),s=tt(e.packageJsonData),r=!!(s.audit||s["security:audit"]||s["audit:security"]||s["npm:audit"]),c=e.dependencyAudit,a=Number(c?.blockingFindingCount??c?.findingCount??e.vulnerabilities??0),l=a>0,d=c?.status==="clean",p=c?.status==="tool-unavailable"||c?.status==="unsupported"||c?.status==="failed",y=We(e.runtimeFamily),v=["package.json","package-lock.json",...await m.pathExists(u.join(e.projectPath,"npm-shrinkwrap.json"))?["npm-shrinkwrap.json"]:[]],C=c?.invocation,h=c?.remediation?.disposition,w=c?.remediation?.resolutionCandidates?.length??0,P=h==="compatible"||h==="mixed"||!c&&y==="node",R=l&&P&&(c?.tool==="npm audit"||!c&&y==="node")?{cwd:e.projectPath,executable:"npm",args:["audit","fix","--audit-level=moderate"]}:l&&P&&c?.tool==="bun audit"?{cwd:e.projectPath,executable:"bun",args:["update"]}:l&&P&&c?.tool==="deno audit"?{cwd:e.projectPath,executable:"deno",args:["audit","--fix"]}:void 0,x=l?[{id:"audit-live-state",kind:"diagnose",description:"Read the current advisory graph and classify direct, transitive, fixable, and breaking findings.",risk:"safe",invocation:C,continueWhen:"always"},...R?[{id:"apply-compatible-fixes",kind:"safe-fix",description:"Apply runtime-authored compatible dependency and lockfile updates without forcing breaking upgrades.",risk:"guarded",invocation:R,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:R?"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:C,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,g=l&&R?k$1({issueId:"surface-security-hygiene",title:`Apply compatible ${c?.ecosystem??y} vulnerability fixes`,projectPath:e.projectPath,command:[R.executable,...R.args].join(" "),invocation:{executable:R.executable,args:R.args},strategy:x,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:c?.ecosystem??R.executable??y,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}},files:v,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,D=p?De({issueId:"surface-security-hygiene",title:`Establish ${c?.ecosystem??y} security audit evidence`,projectPath:e.projectPath,files:Array.from(new Set([...ii[y]??[],...ni[y]??[],...y==="node"?["package.json"]:[],...y==="python"?["pyproject.toml","requirements.txt"]:[]])),reason:`${c?.tool??"The runtime-native audit tool"} is unavailable. Add or declare the audit tool in the project's governed dependency/tooling surface, then rerun Doctor.`,limitations:["Do not install an unpinned global scanner as an implicit repair.","The selected project environment and CI must resolve the same audit command."]}):void 0,k=o&&d,A=c?.reason;return {id:"surface-security-hygiene",label:"Security hygiene surface",status:k?"pass":l?"fail":"warn",severity:l?"error":"warn",scope:"project-scoped",reason:l?`${a} moderate/high/critical dependency vulnerability(ies) reported.`:p?`${A} Doctor did not treat unavailable audit evidence as a clean result.`:o&&d?"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&&!P?`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.`:h==="breaking-only"||h==="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.":p?"Install or declare the runtime-native audit tool, rerun Doctor, and keep the command available to CI and Studio.":o?r?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?g??{...De({issueId:"surface-security-hygiene",title:`Resolve ${c?.ecosystem??y} 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:h==="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.":h==="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:x,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:c?.ecosystem??R?.executable??y,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}}}:D||(o?void 0:await vo(e.projectPath))}}async function Do(e){let t=We(e.runtimeFamily),i=e.hasTests===true,n=i?void 0:await Xt({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:De({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 Ro(e){let t=u.join(e.projectPath,".workspai","reports","project-test-coverage-last-run.json"),i=await m.readJson(t).catch(()=>null);if(!(i?.schemaVersion===s.projectTestCoverage.schemaVersion))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:k$1({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:[t$1.projectTestCoverage],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.target?.metric??"lines",s$1=So(i.target?.percent),r=i.metrics?.[o]?.percent,c=typeof r=="number"?`${r}%`:"unavailable",a=i.status==="passed"?"pass":i.status==="below-target"||i.status==="failed"?"fail":"warn";return {id:"test-coverage-evidence",label:"Test coverage evidence",status:a,severity:a==="fail"?"error":"warn",scope:"project-scoped",reason:i.status==="passed"?`${o} coverage ${c} satisfies the ${s$1}% project target.`:i.status==="below-target"?`${o} coverage ${c} is below the ${s$1}% project target.`:i.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.status==="passed"?void 0:i.status==="below-target"?`Add targeted tests for the lowest-coverage source paths, then rerun project coverage with target ${s$1}%.`:"Repair the runtime-native coverage command or reporter and regenerate evidence.",repairCapability:i.status==="passed"?void 0:De({issueId:"test-coverage-evidence",title:"Reach the project coverage goal",projectPath:e.projectPath,files:[t$1.projectTestCoverage,...(i.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 So(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Eo(e){let t=tt(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 Ao(e){let t=We(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",".bunfig.toml","test","tests","vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","jest.config.ts","jest.config.js","playwright.config.ts","playwright.config.js","*.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 g$2(e.projectPath),s=await Pe(e.projectPath,n)||o.runtimeFamilies.some(y=>y===t),r=tt(e.packageJsonData),c=Object.values(r).join(`
|
|
10
|
-
`),a=await Dt(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"]),d={node:/\b(jest|vitest|mocha|ava|tap|playwright|cypress|node\s+--test|bun\s+test)\b/i,bun:/\b(bun\s+test|jest|vitest|mocha|ava|tap|playwright|cypress)\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(`${c}
|
|
11
|
-
${a}`)??false,p=s||d;return {id:"runtime-test-depth",label:"Runtime-native test depth",status:p?"pass":("warn"),severity:"warn",scope:"project-scoped",reason:p?"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:p?void 0:"Add runtime-native tests/config so Doctor, CI, and Studio can verify changes deterministically."}}async function Fo(e){let t=We(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"],python:["ruff.toml",".flake8","mypy.ini"],go:[".golangci.yml",".golangci.yaml"],java:["checkstyle.xml"],rust:["rustfmt.toml","clippy.toml"],elixir:[".formatter.exs","credo.exs"],clojure:["cljfmt.edn",".clj-kondo"],php:["phpcs.xml","phpstan.neon","pint.json"],ruby:[".rubocop.yml"],dotnet:[".editorconfig"],scala:[".scalafmt.conf",".scalafix.conf"],kotlin:[".editorconfig","detekt.yml"],c:[".clang-format",".clang-tidy"],cpp:[".clang-format",".clang-tidy"],unknown:[]}[t]??[];if(n.length===0)return null;let o=await Dt(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=tt(e.packageJsonData),r=Object.entries(s).filter(([d])=>/lint|format|quality|check|typecheck|static/i.test(d)).map(([,d])=>d).join(`
|
|
12
|
-
`),c=await Pe(e.projectPath,n),a=/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}
|
|
13
|
-
${r}`)||c,l=a?void 0:await Xt({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:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?"Runtime-native lint/format/static-analysis markers detected.":"No runtime-native lint/format/static-analysis markers detected.",recommendation:a?void 0:"Add runtime-native lint/format/static-analysis tooling and expose it to CI.",repairCapability:l}}async function $o(e){let t=We(e.runtimeFamily),n={node:["package.json"],deno:["deno.json","deno.jsonc"],bun:["package.json","bunfig.toml",".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 Dt(e.projectPath,n),await po(e.projectPath)].join(`
|
|
14
|
-
`),s=/npm audit|pnpm audit|yarn audit|bun audit|pip[-_]audit|safety|bandit|govulncheck|gosec|dependency-check|dependency-review-action|codeql-action|zizmor|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),r=s?void 0:await Xt({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:r||De({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 oi(e){let t=We(e.runtimeFamily),i=[],n=await wo({projectPath:e.projectPath,runtime:t,packageJsonData:e.packageJsonData});n&&i.push(n),i.push(await jo(e)),i.push(await xo(e)),i.push(await Co(e)),i.push(await Po(e)),i.push(await Do(e)),i.push(await Ro(e)),(t==="node"||t==="bun")&&i.push(Eo(e));let o=await Promise.all([Ao(e),Fo(e),$o(e)]);for(let s of o)s&&i.push(s);return i}var ke={low:0,moderate:0,high:0,critical:0,unknown:0};function Mo(e){let t=String(e??"unknown").toLowerCase();return t==="medium"?"moderate":t==="low"||t==="moderate"||t==="high"||t==="critical"?t:"unknown"}function be(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=>Mo(i)))].sort()}:null}function he(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 ri(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 Te=new Map,To=256,Oo=["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 _o(){let e=Number(process.env.RAPIDKIT_DOCTOR_AUDIT_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.trunc(e):15e3}async function Bo(e,t){let i=[];for(let n of Oo){let o=u.join(e,n);try{let s=await m.readFile(o);i.push(`${n}:${s.byteLength}:${createHash("sha256").update(s).digest("hex")}`);}catch{}}return `${u.resolve(e)}\0${t}\0${i.join("|")}`}function Re(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 nt(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function si(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {low:nt(t.low),moderate:nt(t.moderate??t.medium),high:nt(t.high),critical:nt(t.critical),unknown:nt(t.unknown)}}function it(e){return e.low+e.moderate+e.high+e.critical+e.unknown}function Go(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 Ko(e){let t=new Map;try{let i=await m.readJSON(u.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,r]of Object.entries(o))typeof r=="string"&&r.trim()&&t.set(s.toLowerCase(),r.trim());}}catch{}return t}async function Wo(e,t){let i=Re(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([li(e),Ko(e)]),r=new Map;for(let[c,a]of Object.entries(n)){let l=a&&typeof a=="object"?a:{},d=typeof l.name=="string"&&l.name.trim()?l.name.trim():c.trim();if(!d)continue;let p=l.isDirect===true?"direct":l.isDirect===false?"transitive":"unknown",y=Array.isArray(l.effects)?[...new Set(l.effects.filter(x=>typeof x=="string").map(x=>x.trim()).filter(Boolean))].sort():[],b=Array.isArray(l.via)?l.via:[],v=[...new Set(b.flatMap(x=>{let g=x&&typeof x=="object"?x:{};return [g.source,g.url].filter(D=>typeof D=="string"||typeof D=="number").map(String)}))].sort(),C=typeof l.range=="string"?l.range.trim():void 0,h=Go(C),w=s.get(d.toLowerCase()),P=o.get(d.toLowerCase()),R=p==="direct"?["direct-upgrade","constraint-update","replacement","policy-exception","upstream-wait"]:[...y.length>0?["owner-upgrade"]:[],"transitive-override","replacement","policy-exception","upstream-wait"];r.set(d.toLowerCase(),{packageName:d,relationship:p,strategies:R,risk:"guarded",autoExecutable:false,requiresCompatibilityVerification:true,...P?{currentVersion:P}:{},...w?{currentRange:w}:{},...C?{vulnerableRange:C}:{},...h?{safeVersionConstraint:h}:{},ownerPackages:y,advisoryIds:v,reason:p==="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 [...r.values()].sort((c,a)=>c.packageName.localeCompare(a.packageName))}function Le(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 ot(e,t){if(Array.isArray(e)){for(let n of e)ot(n,t);return}if(!e||typeof e!="object")return;let i=e;t(i);for(let n of Object.values(i))ot(n,t);}function Ho(e,t){if(t===0)return {disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]};let i=false,n=false,o=false,s=[];for(let[c,a]of e){let l=a&&typeof a=="object"?a:{};if(!Object.prototype.hasOwnProperty.call(l,"fixAvailable"))continue;i=true;let d=l.fixAvailable;if(d===true){n=true,s.push({packageName:c,breaking:false});continue}if(!d||typeof d!="object"||Array.isArray(d))continue;let p=d,y=typeof p.name=="string"&&p.name.trim()?p.name.trim():c,b=p.isSemVerMajor===true;n||=!b,o||=b,s.push({packageName:y,...typeof p.version=="string"&&p.version.trim()?{version:p.version.trim()}:{},breaking:b});}return {disposition:n?o?"mixed":"compatible":o?"breaking-only":i?"none":"unknown",compatibleFixAvailable:n,breakingFixAvailable:o,candidates:s.sort((c,a)=>`${c.packageName}@${c.version??""}`.localeCompare(`${a.packageName}@${a.version??""}`))}}function Lo(e,t){let i=s=>{let r=s.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.+)?$/);return r?[Number(r[1]),Number(r[2]),Number(r[3]),r[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 li(e){let t=new Map;try{let i=await m.readJSON(u.join(e,"package-lock.json")),n=i.packages&&typeof i.packages=="object"&&!Array.isArray(i.packages)?i.packages:{};for(let[s,r]of Object.entries(n)){if(!s.startsWith("node_modules/"))continue;let c=s.replace(/^node_modules\//,"").split("/node_modules/").at(-1)?.trim()??"";if(!c)continue;let a=r&&typeof r=="object"?r:{};!t.has(c.toLowerCase())&&typeof a.version=="string"&&a.version.trim()&&t.set(c.toLowerCase(),a.version.trim());}let o=i.dependencies&&typeof i.dependencies=="object"&&!Array.isArray(i.dependencies)?i.dependencies:{};for(let[s,r]of Object.entries(o)){if(t.has(s.toLowerCase()))continue;let c=r&&typeof r=="object"?r:{};typeof c.version=="string"&&c.version.trim()&&t.set(s.toLowerCase(),c.version.trim());}}catch{}return t}async function qo(e,t){if(t.disposition==="not-needed")return t;let i=await li(e),n=new Map;for(let a of t.candidates){let l=i.get(a.packageName.toLowerCase());if(a.version&&l){let y=Lo(a.version,l);if(y!==null&&y<=0)continue}let d=`${a.packageName.toLowerCase()}\0${a.version??""}`,p=n.get(d);n.set(d,{packageName:p?.packageName??a.packageName,...a.version?{version:a.version}:{},breaking:!!(p?.breaking||a.breaking)});}let o=[...n.values()].sort((a,l)=>`${a.packageName}@${a.version??""}`.localeCompare(`${l.packageName}@${l.version??""}`)),s=o.some(a=>!a.breaking),r=o.some(a=>a.breaking);return {disposition:s?r?"mixed":"compatible":r?"breaking-only":"none",compatibleFixAvailable:s,breakingFixAvailable:r,candidates:o}}function Vo(e){let t=Re(e);if(!t){let l={...ke},d=[],p=0,y=false;for(let b of e.split(/\r?\n/)){let v=Re(b);if(!v)continue;let C=v.data&&typeof v.data=="object"?v.data:{};if(v.type==="auditAdvisory"){let h=C.advisory&&typeof C.advisory=="object"?C.advisory:{};p+=1,Le(l,h.severity);let w=be({name:h.module_name??h.name,advisoryIds:[h.id,h.github_advisory_id,h.url],severities:[h.severity]});w&&d.push(w);}if(v.type==="auditSummary"){y=true;let h=si(C.vulnerabilities);if(it(h)>=p)return {findingCount:it(h),severityCounts:h,subjects:he(d)}}}return p>0||y?{findingCount:p,severityCounts:l,subjects:he(d)}:null}let i=t.metadata&&typeof t.metadata=="object"?t.metadata:null,n=si(i?.vulnerabilities),o=t.vulnerabilities&&typeof t.vulnerabilities=="object"?Object.entries(t.vulnerabilities):[],s=he(o.map(([l,d])=>{let p=d&&typeof d=="object"?d:{},y=Array.isArray(p.via)?p.via:[];return be({name:p.name??l,direct:p.isDirect,advisoryIds:y.flatMap(b=>{let v=b&&typeof b=="object"?b:{};return [v.source,v.url]}),severities:[p.severity]})}));if(it(n)>0||i?.vulnerabilities){let l=it(n);return {findingCount:l,severityCounts:n,subjects:s,remediation:Ho(o,l)}}let r=t.advisories&&typeof t.advisories=="object"?Object.entries(t.advisories):[];if(!(t.advisories!==null&&typeof t.advisories=="object"&&!Array.isArray(t.advisories)))return null;let a=[];for(let[l,d]of r){let p=d&&typeof d=="object"?d:{};Le(n,p.severity);let y=be({name:p.module_name??p.name,advisoryIds:[p.id,p.github_advisory_id,p.url,l],severities:[p.severity]});y&&a.push(y);}return {findingCount:r.length,severityCounts:n,subjects:he([...s,...a])}}function zo(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={...ke},o=[],s=0;for(let r of i){let c=r&&typeof r=="object"?r:{},a=Array.isArray(c.vulns)?c.vulns:[];if(s+=a.length,n.unknown+=a.length,a.length>0){let l=be({name:c.name,version:c.version,advisoryIds:a.flatMap(d=>{let p=d&&typeof d=="object"?d:{};return [p.id,p.aliases].flatMap(y=>Array.isArray(y)?y:[y])}),severities:a.map(()=>"unknown")});l&&o.push(l);}}return {findingCount:s,severityCounts:n,subjects:he(o)}}function Jo(e){if(!e.trim())return null;let t=new Set,i=new Map;for(let n of e.split(/\r?\n/)){let o=Re(n),s=o?.osv&&typeof o.osv=="object"?o.osv:null;typeof s?.id=="string"&&t.add(s.id);let r=o?.finding&&typeof o.finding=="object"?o.finding:null;typeof r?.osv=="string"&&t.add(r.osv);let c=Array.isArray(r?.trace)?r.trace:[];for(let a of c){let l=a&&typeof a=="object"?a:{},d=typeof l.module=="string"?l.module:typeof l.package=="string"?l.package:"";if(!d)continue;let p=i.get(d)??{advisoryIds:new Set};typeof l.version=="string"&&(p.version=l.version),typeof r?.osv=="string"&&p.advisoryIds.add(r.osv),i.set(d,p);}}return {findingCount:t.size,severityCounts:{...ke,unknown:t.size},subjects:[...i.entries()].map(([n,o])=>be({name:n,version:o.version,advisoryIds:[...o.advisoryIds],severities:["unknown"]})).filter(n=>!!n)}}function Uo(e){let t=Re(e);if(!t)return null;let i=t.vulnerabilities&&typeof t.vulnerabilities=="object"?t.vulnerabilities:{},n=Array.isArray(i.list)?i.list:[],o={...ke},s=[];for(let r of n){let c=r&&typeof r=="object"?r:{},a=c.advisory&&typeof c.advisory=="object"?c.advisory:{};Le(o,a.severity);let l=c.package&&typeof c.package=="object"?c.package:{},d=be({name:l.name,version:l.version,advisoryIds:[a.id,a.url],severities:[a.severity]});d&&s.push(d);}return {findingCount:n.length,severityCounts:o,subjects:he(s)}}function Yo(e){let t=Re(e);if(!t)return null;let i=t.advisories&&typeof t.advisories=="object"?t.advisories:{},n={...ke},o=0,s=[];for(let[r,c]of Object.entries(i)){let a=Array.isArray(c)?c:[c],l=be({name:r,advisoryIds:a.flatMap(d=>{let p=d&&typeof d=="object"?d:{};return [p.advisoryId,p.cve,p.link]}),severities:a.map(d=>(d&&typeof d=="object"?d:{}).severity)});l&&s.push(l);}return ot(i,r=>{(typeof r.advisoryId=="string"||typeof r.cve=="string")&&(o+=1,Le(n,r.severity));}),{findingCount:o,severityCounts:n,subjects:he(s)}}function Zo(e){let t=Re(e);if(!t)return null;let i={...ke},n=0,o=[];return ot(t,s=>{if(!Array.isArray(s.vulnerabilities))return;for(let c of s.vulnerabilities){let a=c&&typeof c=="object"?c:{};n+=1,Le(i,a.severity);}let r=be({name:s.id??s.name??s.packageId,version:s.resolvedVersion??s.version,direct:s.isTransitive===false,advisoryIds:s.vulnerabilities.flatMap(c=>{let a=c&&typeof c=="object"?c:{};return [a.advisoryurl,a.advisoryUrl,a.url]}),severities:s.vulnerabilities.map(c=>(c&&typeof c=="object"?c:{}).severity)});r&&o.push(r);}),{findingCount:n,severityCounts:i,subjects:he(o)}}function Xo(e){let t=Re(e);if(!t)return null;let i={...ke},n=new Set,o=[];return ot(t,s=>{let r=s.id??s.cve??s.advisory??s.url;if(typeof r!="string")return;n.add(r),Le(i,s.severity??s.criticality);let c=s.gem&&typeof s.gem=="object"?s.gem:{},a=be({name:c.name??s.gemName??s.name,version:c.version??s.version,advisoryIds:[r],severities:[s.severity??s.criticality]});a&&o.push(a);}),{findingCount:n.size,severityCounts:n.size>0&&it(i)===0?{...i,unknown:n.size}:i,subjects:he(o)}}function ai(e,t){let i=`${e}
|
|
15
|
-
${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:{...ke,unknown:s},subjects:[]}}function Qo(e,t,i){return e==="node"||e==="bun"?Vo(t):e==="python"?zo(t):e==="go"?Jo(t):e==="rust"?Uo(t):e==="php"?Yo(t):e==="dotnet"?Zo(t):e==="ruby"?Xo(t)??ai(t,i):e==="deno"||e==="elixir"?ai(t,i):null}async function er(e,t){return m.pathExists(u.join(e,t))}async function tr(e,t){if(t==="bun")return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(t==="node"){let i=a$e(e);if(i==="bun")return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(i==="pnpm")return {ecosystem:"npm",tool:"pnpm audit",invocation:{cwd:e,executable:"pnpm",args:["audit","--json"]}};if(i==="yarn"){let n=await er(e,".yarnrc.yml");return {ecosystem:"npm",tool:"yarn audit",invocation:{cwd:e,executable:"yarn",args:n?["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=u.join(e,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");return {ecosystem:"PyPI",tool:"pip-audit",invocation:{cwd:e,executable:await m.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 ci(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 nr(e){let t=new Date().toISOString(),i=await tr(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:{...ke},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:_o(),reject:false}),s=Qo(e.runtime,o.stdout,o.stderr);if(!s){let a=String(o.code??"")==="ENOENT"||/not found|no such (?:command|subcommand)|script not found|no module named pip_audit|unknown command|unrecognized (?:command|option)/i.test(`${o.stdout}
|
|
16
|
-
${o.stderr}
|
|
17
|
-
${o.shortMessage??""}`);return {...n,invocation:i.invocation,exitCode:o.exitCode,status:a?"tool-unavailable":"failed",reason:a?`${i.tool} is not installed or not supported by the detected runtime version.`:`${i.tool} did not produce parseable vulnerability evidence.`}}if(s.findingCount===0&&o.exitCode!==0)return {...n,invocation:i.invocation,exitCode:o.exitCode,status:"failed",reason:`${i.tool} emitted a clean-looking payload but exited with ${o.exitCode}; Doctor refuses to treat contradictory audit execution as healthy.`};if((e.runtime==="node"||e.runtime==="bun")&&s.remediation&&(s.remediation=await qo(e.projectPath,s.remediation),s.findingCount>0&&!s.remediation.compatibleFixAvailable)){let a=await Wo(e.projectPath,o.stdout);s.remediation.resolutionCandidates=a.length>0?a:ri(s.subjects);}let r=s.severityCounts.moderate+s.severityCounts.high+s.severityCounts.critical+s.severityCounts.unknown,c=s.remediation??(s.findingCount===0?{disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]}:{disposition:"unknown",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[],resolutionCandidates:ri(s.subjects)});return {...n,invocation:i.invocation,exitCode:o.exitCode,findingCount:s.findingCount,blockingFindingCount:r,severityCounts:s.severityCounts,subjects:s.subjects,remediation:c,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:ci(o)?"tool-unavailable":"failed",reason:ci(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 di(e){let t=await Bo(e.projectPath,e.runtime);e.fresh&&Te.delete(t);let i=Te.get(t);if(i)return i;let n=nr(e);for(Te.set(t,n);Te.size>To;){let o=Te.keys().next().value;if(!o)break;Te.delete(o);}try{return await n}catch(o){throw Te.delete(t),o}}var Qt="doctor-graph-diagnosis.v1";var fi="Graph paths identify evidence-backed structural reachability and verification candidates; they do not prove runtime causality or that every affected surface has been discovered.",pi={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"]},ir=new Set(["project","service","api","endpoint","schema","database","queue","container","deployment","pipeline","environment","document","decision","test-suite","owner"]),or=new Set(["test-suite","pipeline"]),st=new Map;async function rr(e,t){let[i,n]=await Promise.all([m.stat(e),m.stat(t)]),o=[e,i.size,i.mtimeMs,t,n.size,n.mtimeMs].join(":"),s=st.get(o);if(s)return s;st.size>=4&&st.clear();let r=(async()=>{let[c,a]=await Promise.all([m.readJSON(e),m.readJSON(t)]);a$6(c,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Doctor graph diagnosis source"),a$6(a,"contracts/workspace-intelligence/workspace-model.v1.json","Doctor graph diagnosis model");let l=c;return {graph:l,model:a,entitiesById:new Map(l.entities.map(d=>[d.id,d])),edges:cr(l)}})();st.set(o,r);try{return await r}catch(c){throw st.delete(o),c}}function Rt(e,t){if(!e)return ".";let i=u.relative(e,t).split(u.sep).join("/");return i&&!i.startsWith("../")?i:"."}function en(e){return {id:e.id,kind:e.kind,label:e.label,...e.projectId?{projectId:e.projectId}:{}}}function qe(e,t,i,n={artifact:a$7}){return {schemaVersion:Qt,generatedAt:(e.now??new Date).toISOString(),status:t,claimBoundary:fi,graph:n,project:{name:e.projectName,path:Rt(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 sr(e,t){let i=Rt(t.workspacePath,t.projectPath).toLowerCase(),n=new Set([t.projectName,u.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(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>n.has(r)||n.has(u.basename(r))))}function ar(e,t){let i=t.projectId??t.label,n=e.entities.filter(r=>r.id===t.id||r.projectId===i||r.projectId===t.projectId),o=new Set(n.map(r=>r.id)),s=new Set;for(let r of e.relations)o.has(r.from)&&s.add(r.to),o.has(r.to)&&s.add(r.from);return e.entities.filter(r=>o.has(r.id)||s.has(r.id))}function cr(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 lr(e,t,i){let n=new Set(t),o=t.map(s=>({id:s,depth:0}));for(let s=0;s<o.length;s+=1){let r=o[s];if(!(!r||r.depth>=i))for(let c of e.get(r.id)??[])n.has(c)||(n.add(c),o.push({id:c,depth:r.depth+1}));}return [...n]}function ui(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 mi(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function dr(e,t){let i=mi(e);return i?t.some(n=>{let o=mi(n.reason);return o===i||o.includes(i)||i.includes(o)}):true}function pr(e,t,i,n){let o=pi[i]??pi.unknown,s=[...new Set(n.map(c=>c.trim().toLowerCase()).filter(Boolean))];if(s.length>0){let c=t.filter(l=>o?.includes(l.kind)&&s.some(d=>ui(l).has(d))),a=new Set(s.filter(l=>c.some(d=>ui(d).has(l))));return {roots:c.length>0?c.slice(0,4):[e],unresolvedSubjects:n.filter(l=>!a.has(l.trim().toLowerCase()))}}let r=t.filter(c=>o?.includes(c.kind)).slice(0,4);return {roots:r.length>0?r:[e],unresolvedSubjects:[]}}function ur(e,t,i,n){let o=n.issueClass??"unknown",s=[...new Set((n.subjects??[]).map(h=>h.trim()).filter(Boolean))],{roots:r,unresolvedSubjects:c}=pr(t,i.scoped,o,s),a=lr(i.edges,r.map(h=>h.id),3).map(h=>i.entitiesById.get(h)).filter(h=>!!h),l=a.filter(h=>i.scopedIds.has(h.id)&&!r.some(w=>w.id===h.id)&&ir.has(h.kind)).slice(0,6),d=a.filter(h=>i.scopedIds.has(h.id)&&or.has(h.kind)).slice(0,2),y=[...l,...d].filter((h,w,P)=>P.findIndex(R=>R.id===h.id)===w).slice(0,3).flatMap(h=>{let P=r.map(R=>d$1(e,R.id,h.id)).filter(R=>R.found).sort((R,x)=>R.hops.length-x.hops.length)[0];return P?[{from:P.resolvedFrom??P.from,to:P.resolvedTo??P.to,entityPath:P.entityPath,hops:P.hops,proofIds:P.proofs.map(R=>R.id)}]:[]}),b=new Set([...r.flatMap(h=>h.proofIds),...y.flatMap(h=>h.proofIds)]),v=e.proofs.filter(h=>b.has(h.id)).map(h=>h.artifact).filter(h=>i.projectRelativePath==="."?true:h.split(u.sep).join("/").replace(/^\.\//,"").startsWith(`${i.projectRelativePath}/`)).filter((h,w,P)=>P.indexOf(h)===w).sort().slice(0,4),C=[];return l.length===0&&C.push("No affected surface is structurally reachable from the selected root evidence."),d.length===0&&C.push("No graph-connected test suite or pipeline is available as a verification target."),v.length===0&&C.push("The selected graph entities do not carry portable source evidence."),c.length>0&&C.push(`No canonical graph entity resolved for ${c.length} reported subject(s): ${c.join(", ")}.`),{issueId:n.id,issueClass:o,status:n.status==="fail"?"fail":"warn",reason:n.reason,scope:"structural-impact-candidates",subjects:s,unresolvedSubjects:c,rootEntities:r.map(en),affectedEntities:l.map(en),verificationTargets:d.map(en),proofPaths:y,sourceArtifacts:v,unknowns:C}}async function tn(e){if(!e.workspacePath)return qe(e,"graph-missing","Project is not attached to a Workspai workspace; no workspace graph can be consulted.");let t=u.join(e.workspacePath,a$7),i=u.join(e.workspacePath,p.model);if(!await m.pathExists(t))return qe(e,"graph-missing","Workspace knowledge graph is missing. Run workspace model before relying on graph-aware diagnosis.");if(!await m.pathExists(i))return qe(e,"model-missing","Canonical workspace model is missing, so graph source binding cannot be verified.");let n,o,s,r;try{({graph:n,model:o,entitiesById:s,edges:r}=await rr(t,i));}catch(b){return qe(e,"invalid",`Graph-aware diagnosis rejected invalid evidence: ${b instanceof Error?b.message:String(b)}`)}let c={artifact:a$7,schemaVersion:n.schemaVersion,sourceArtifact:n.source.artifact,sourceHash:n.source.hash,entityCount:n.entities.length,relationCount:n.relations.length,proofCount:n.proofs.length};try{b$2(n,o);}catch(b){return qe(e,"stale",b instanceof Error?b.message:String(b),c)}let a=sr(n,e);if(!a)return qe(e,"project-unresolved","The current project could not be resolved to one canonical project entity.",c);let l=ar(n,a),d={scoped:l,scopedIds:new Set(l.map(b=>b.id)),entitiesById:s,edges:r,projectRelativePath:Rt(e.workspacePath,e.projectPath)},p$1=(e.probes??[]).filter(b=>b.status!=="pass"),y=[...p$1,...(e.issues??[]).filter(b=>!dr(b,p$1)).map((b,v)=>({id:`legacy-project-issue-${v+1}`,status:"fail",reason:b,issueClass:"runtime"}))].map(b=>ur(n,a,d,b));return {schemaVersion:Qt,generatedAt:(e.now??new Date).toISOString(),status:"available",claimBoundary:fi,graph:c,project:{name:e.projectName,path:Rt(e.workspacePath,e.projectPath),entityId:a.id},summary:{findingCount:y.length,rootEntityCount:new Set(y.flatMap(b=>b.rootEntities.map(v=>v.id))).size,affectedEntityCount:new Set(y.flatMap(b=>b.affectedEntities.map(v=>v.id))).size,verificationTargetCount:new Set(y.flatMap(b=>b.verificationTargets.map(v=>v.id))).size,proofPathCount:y.reduce((b,v)=>b+v.proofPaths.length,0),subjectCount:new Set(y.flatMap(b=>b.subjects)).size,unresolvedSubjectCount:new Set(y.flatMap(b=>b.unresolvedSubjects)).size,unknownCount:y.reduce((b,v)=>b+v.unknowns.length,0)},findings:y,diagnostics:[]}}var St="workspai.doctor-summary.v1";function yi(e){let t=e.trim().match(/^(?:Python\s+)?(\d+(?:\.\d+){0,3})/i);return t?{raw:t[1],parts:t[1].split(".").map(i=>Number.parseInt(i,10))}:null}function gi(e,t){let i=Math.max(e.length,t.length);for(let n=0;n<i;n+=1){let o=(e[n]??0)-(t[n]??0);if(o!==0)return o<0?-1:1}return 0}function mr(e,t){return t.replace(/\.\*$/u,"").split(".").map(n=>Number.parseInt(n,10)).every((n,o)=>e[o]===n)}function fr(e){if(e.length<=2)return [(e[0]??0)+1];let t=e.slice(0,-1);return t[t.length-1]=(t[t.length-1]??0)+1,t}function gr(e,t){let i=t.trim().match(/^(===|~=|==|!=|>=|<=|>|<)\s*(.+)$/u);if(!i)return null;let[,n,o]=i;if((n==="=="||n==="!=")&&/\.\*$/u.test(o)){let c=mr(e.parts,o);return n==="=="?c:!c}let s=yi(o);if(!s)return null;let r=gi(e.parts,s.parts);return n==="==="?e.raw===s.raw:n==="=="?r===0:n==="!="?r!==0:n===">="?r>=0:n==="<="?r<=0:n===">"?r>0:n==="<"?r<0:n==="~="?r>=0&&gi(e.parts,fr(s.parts))<0:null}function hi(e,t){let i=yi(e),n=t.trim(),o=n.replace(/^\(|\)$/gu,"").split(",").map(c=>c.trim()).filter(Boolean);if(!i||o.length===0)return {version:i?.raw??e.trim(),specifier:n,satisfied:null,unsupportedSpecifiers:o.length===0?[n]:o};let s=o.map(c=>({clause:c,result:gr(i,c)})),r=s.filter(c=>c.result===null).map(c=>c.clause);return {version:i.raw,specifier:n,satisfied:r.length>0?null:s.every(c=>c.result===true),unsupportedSpecifiers:r}}function bi(e){return u.win32.normalize(e.trim()).replace(/\\/g,"/").toLowerCase()}function ki(e,t){return bi(u.win32.dirname(e))===bi(t)&&/^workspai(?:\.cmd|\.exe|\.ps1)?$/i.test(u.win32.basename(e))}async function yr(){let e=await execa("where.exe",["workspai"],{reject:false,timeout:5e3,windowsHide:true});return e.exitCode!==0?[]:e.stdout.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}async function hr(){let e=process.env.npm_config_prefix?.trim();if(e)return e;let t=await execa("npm",["prefix","--global"],{reject:false,timeout:5e3,windowsHide:true});if(t.exitCode===0)return t.stdout.trim()||void 0}async function wi(e={}){if((e.platform??process.platform)!=="win32")return {status:"ok",applicability:"not-applicable",command:"workspai",resolutionStatus:"not-applicable",candidates:[],message:"Windows PATH resolution check is not applicable on this host."};let[i,n]=await Promise.allSettled([(e.resolveCandidates??yr)(),(e.resolveNpmGlobalPrefix??hr)()]);if(i.status==="rejected")return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unverified",candidates:[],message:"Windows PATH resolution could not be inspected.",details:"The bounded `where.exe workspai` probe failed. Retry Doctor from a standard Windows shell or use `npx --yes workspai <command>`."};let o=i.value,s=n.status==="fulfilled"?n.value:void 0,r=[...new Set(o.map(d=>d.trim()).filter(Boolean))],c=r.map((d,p)=>({location:p===0?"Active PATH match":"Additional PATH match",path:d}));if(r.length===0)return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unresolved",candidates:r,...s?{npmGlobalPrefix:s}:{},message:"`workspai` is not resolvable from Windows PATH.",details:"Add the npm global prefix to PATH, or use `npx --yes workspai <command>` while repairing the host configuration."};let a=r[0];if(!s)return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unverified",activePath:a,candidates:r,paths:c,message:"The active `workspai` PATH target could not be verified against npm.",details:"Run `npm prefix --global`, then ensure that directory precedes conflicting command locations in PATH."};let l=r.find(d=>ki(d,s));return ki(a,s)?{status:"ok",applicability:"applicable",command:"workspai",resolutionStatus:"canonical",activePath:a,npmGlobalPrefix:s,candidates:r,paths:c,message:"`workspai` resolves to the npm global shim.",...r.length>1?{details:"Additional PATH matches exist, but the npm global shim has precedence."}:{}}:{status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"shadowed",activePath:a,npmGlobalPrefix:s,candidates:r,paths:c,message:"Another executable shadows the npm global `workspai` shim.",details:l?`Move ${s} before ${u.win32.dirname(a)} in PATH. Until then, use \`npx --yes workspai <command>\`.`:`Add ${s} to PATH before ${u.win32.dirname(a)}. Until then, use \`npx --yes workspai <command>\`.`}}var sn=p.doctor;function Ii(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function ji(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Ni(){let e=t$2().map(n=>u.join(n,b$5()?"poetry.exe":"poetry")),t=b$5()?[u.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),u.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],i=b$5()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return Ii([...e,...t,...i])}function br(e,t=process.cwd()){let i=t$2().map(l=>({location:"Global (user-local)",path:u.join(l,b$5()?"rapidkit.exe":"rapidkit")})),n$1=[{location:"Global (pipx)",path:u.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:u.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:u.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],o=n(u.join(t,".venv")),s=p$1(t),r=[{location:"Workspace (.venv)",path:o},...s.map(l=>({location:"Workspace (launcher)",path:l}))],c=[...i,...n$1,...r],a=new Set;return c.filter(l=>a.has(l.path)?false:(a.add(l.path),true))}function kr(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 ct(e,t){let i=[e.details,t].filter(n=>typeof n=="string"&&n.trim().length>0).join(" ");return {...e,status:e.status==="error"?"warn":e.status,applicability:"not-applicable",...i?{details:i}:{}}}function Mi(e,t){let i=t.some(c=>c.runtimeFamily==="python"),n=t.some(c=>c.runtimeFamily==="go"),o=t.find(c=>c.pythonRequirement?.satisfied===false),s=t.find(c=>c.pythonRequirement?.satisfied===null),r=o?.pythonRequirement?{...e.python,status:"error",message:`Python ${o.pythonRequirement.detectedVersion??"unknown"} does not satisfy ${o.pythonRequirement.specifier}`,details:`Project ${o.name} declares requires-python ${o.pythonRequirement.specifier}.`}:s?.pythonRequirement?{...e.python,status:e.python.status==="error"?"error":"warn",details:`Project ${s.name} declares requires-python ${s.pythonRequirement.specifier}, but compatibility could not be evaluated.`}:e.python;return {...e,python:i?r:ct(e.python,"Python is optional because this scope has no detected Python project."),poetry:i?e.poetry:ct(e.poetry,"Poetry is not applicable to this project scope."),pipx:i?e.pipx:ct(e.pipx,"pipx is not applicable to this project scope."),go:n?e.go:ct(e.go,"Go is not applicable to this project scope."),rapidkitCore:/not installed/i.test(e.rapidkitCore.message)||!i&&e.rapidkitCore.status!=="error"?ct(e.rapidkitCore,"RapidKit Core is an optional engine for Python-backed kits and modules; Workspai CLI diagnostics remain available without it."):e.rapidkitCore}}function vr(e){let i=(e.probes??[]).filter(r=>r.status==="warn").length,n=e.issues.some(r=>r.toLowerCase().includes("environment file missing")),o=(e.probes??[]).some(r=>r.id==="surface-env-contract"),s=(e.probes??[]).some(r=>r.id==="surface-security-hygiene");return e.hasEnvFile===false&&!n&&!o&&(i+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&!s&&(i+=1),i}function wr(e){let t=e.coreVersion?.split(".")[0],i=e.npmVersion?.split(".")[0];return !t||!i?false:t!==i}var jr="doctor-project-scan-v2",xr="doctor-project-scan-policy-v5",Ti=s.doctorWorkspaceCache.schemaVersion,Cr=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v2",generatedBy:"workspai",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"}),lt=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 Ue(){return {...Cr}}function Nt(e){let t=e.profile?.trim();return t&&t in lt?{...lt[t]}:e.strict?{...lt.release}:e.ci?{...lt.ci}:{...lt.local}}function Ft(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function Pr(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 Dr(e,t){let i=Pr(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,r=!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:r,verifyBeforeUse:i.category!=="structure"||r!=="fresh",reason:i.reason}}function Rr(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("migration")||t.includes("database")?"configuration":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 Oi(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 Sr(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 Er(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:ji(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:ji([...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 ln(e,t){let i=Dr(e,e.freshness?.generatedAt??t),n=e.issueClass??Rr(e),o=e.operationalImpact??Sr(e,n),s=Er({probe:e,freshness:i});return {...e,freshness:i,issueClass:n,operationalImpact:o,repairIntent:s}}function Ar(e,t){Array.isArray(e.probes)&&(e.probes=e.probes.map(i=>ln(i,t)));}function Fr(e){e.diagnosis=a$a({projectName:e.name,projectPath:e.path,runtimeFamily:e.runtimeFamily,runtimeFamilies:e.runtimeFamilies,framework:e.framework,projectKind:e.projectKind,projectArchetype:e.projectArchetype,probes:e.probes??[],legacyIssues:e.issues,dependencySubjects:e.dependencyAudit?.subjects});}function $t(e,t=new Date().toISOString()){Ar(e,t),Gr(e,e.path),Fr(e);}function _i(e){if(!e.diagnosis||e.graphDiagnosis?.status!=="available")return;let t=new Map(e.graphDiagnosis.findings.map(i=>[i.issueId,i]));for(let i of e.diagnosis.findings){let n=t.get(i.probeId);if(!n)continue;let o=[{kind:"graph",role:"impact",ref:`doctor-graph:${e.name}:${n.issueId}`,claim:`Canonical graph diagnosis retained ${n.proofPaths.length} bounded proof path(s), ${n.affectedEntities.length} affected candidate(s), and ${n.verificationTargets.length} verification target(s); structural reachability is not runtime causality.`}],s=new Set(i.proofs.map(r=>`${r.kind}:${r.role}:${r.ref}`));for(let r of o){let c=`${r.kind}:${r.role}:${r.ref}`;s.has(c)||i.proofs.push(r);}}}function dn(e,t){let i=e.flatMap(a=>Array.isArray(a.probes)?a.probes.map(l=>l.freshness).filter(l=>!!l):[]),n=i.filter(a=>a.status==="stale").length,o=i.filter(a=>a.status==="unknown").length,s=i.filter(a=>a.category==="state").length,r=i.filter(a=>a.verifyBeforeUse).length,c=i.map(a=>a.generatedAt).filter(Boolean).sort()[0];return {generatedAt:t,status:n>0?"stale":o>0?"unknown":"fresh",staleProbeCount:n,unknownProbeCount:o,liveStateProbeCount:s,verifyBeforeUseProbeCount:r,...c?{oldestProbeGeneratedAt:c}:{}}}function Bi(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Gi(e,t){try{if(!await m.pathExists(e))return null;let i=await m.readJSON(e);return c$3(i,t)?i:null}catch{return null}}function Ki(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},{id:"cliResolution",current:t.cliResolution}],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 $r(e,t){let i=new Map;for(let y of t.projects)i.set(y.path||y.name,y.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 y of n){let b=y.path||y.name;b&&o.set(b,Bi(y.issues));}let s=0,r=0,c=new Set,a=new Set,l=new Set([...Array.from(o.keys()),...Array.from(i.keys())]);for(let y of l){let b=o.get(y)??0,v=i.get(y)??0;v>b?(s+=v-b,c.add(y)):v<b&&(r+=b-v,a.add(y));}let d=Ft(e.healthScore),p=Ft(t.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:s,resolvedIssueCount:r,netIssueDelta:s-r,scoreDeltaPercent:d===null||p===null?null:p-d,systemStatusChanges:Ki(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,cliResolution:t.cliResolution}),regressedProjects:Array.from(c).sort(),improvedProjects:Array.from(a).sort()}}function Ir(e,t){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=Bi(e.project?.issues),n=t.project.issues.length,o=Math.max(n-i,0),s=Math.max(i-n,0),r=Ft(e.healthScore),c=Ft(t.healthScore),a=t.project.path||t.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:s,netIssueDelta:o-s,scoreDeltaPercent:r===null||c===null?null:c-r,systemStatusChanges:Ki(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,cliResolution:t.cliResolution}),regressedProjects:o>0?[a]:[],improvedProjects:s>0?[a]:[]}}function Wi(e){let t=e??[],i=0,n=0;for(let r of t){if(r.scope==="project-scoped"){i+=1;continue}(r.scope==="workspace-aggregate"||r.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$5()?`Set-Location -LiteralPath "${e.replace(/"/g,'`"')}"; ${t}`:`cd '${e.replace(/'/g,`'"'"'`)}' && ${t}`}function Nr(e){return e.manager==="project-script"&&e.projectScript?Q(e.projectPath,e.projectScript):e.manager==="poetry"?Q(e.projectPath,"poetry install --no-root"):e.manager==="uv"?Q(e.projectPath,"uv sync"):Q(e.projectPath,b$5()?"py -3 -m venv .venv":"python3 -m venv .venv")}async function Mr(e){let t=b$5()?["script/setup.cmd","script/setup.ps1","scripts/setup.cmd","scripts/setup.ps1","script/setup","scripts/setup","bin/setup"]:["script/setup","scripts/setup","bin/setup"];for(let i of t)if(await m.pathExists(u.join(e,i)))return i}async function Tr(e){let t=e?[e]:j$1();for(let i of t)try{let o=await execa(i,i==="py"?["-3","--version"]:["--version"],{timeout:3e3,reject:false}),s=`${o.stdout??""}
|
|
18
|
-
${o.stderr??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(s)return s[1]}catch{}}function Or(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 _r(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 Br(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 Gr(e,t){let i=z(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function dt(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=Or(t),e.projectKind=_r(t),e.runtimeFamily=Br(t);}function Hi(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 pn(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 Kr(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 Wr(e,t){e.framework=pn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=Hi(t.runtime);}function ie(e,t){e.framework=pn(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":Kr(t)?"generic":"backend",e.runtimeFamily=Hi(t.runtime);}function Hr(e){let t=e.dependencies,i=e.scripts??{},n=(e.kitName??"").toLowerCase(),o=r=>!!t[r],s=Object.values(i).filter(r=>typeof r=="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 Lr(e,t){let i=m$1(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:pn(i),confidence:i.confidence}}async function xi(e){try{let t=await m.stat(e);if(t.isFile()&&t.size<=1048576){let i=await m.readFile(e);return `${u.basename(e)}:f:${t.size}:${createHash("sha256").update(i).digest("hex")}`}if(t.isDirectory()){if(["node_modules",".venv"].includes(u.basename(e))){let l=await m.readdir(e).catch(()=>[]);return `${u.basename(e)}:materialized:${l.length}:${t.mtimeMs}`}let i=createHash("sha256"),n=[e],o=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","coverage","target","bin","obj","__pycache__"]),s=0,r=0,c=2e4,a=32*1024*1024;for(;n.length>0&&s<c;){let l=n.shift();if(!l)break;let d=await m.readdir(l,{withFileTypes:true}).catch(()=>[]);d.sort((p,y)=>p.name.localeCompare(y.name));for(let p of d){if(o.has(p.name))continue;let y=u.join(l,p.name),b=u.relative(e,y).split(u.sep).join("/");if(p.isDirectory()){i.update(`d:${b}\0`),n.push(y);continue}if(!p.isFile())continue;let v=await m.stat(y).catch(()=>null);if(v){if(s+=1,i.update(`f:${b}:${v.size}:${v.mtimeMs}\0`),v.size<=262144&&r+v.size<=a){let C=await m.readFile(y).catch(()=>null);C&&(r+=C.length,i.update(C));}if(s>=c)break}}}return i.update(`files:${s}:bytes:${r}:remaining:${n.length}`),`${u.basename(e)}:d:${i.digest("hex")}`}return `${u.basename(e)}:other:${t.size}:${t.mtimeMs}`}catch{return `${u.basename(e)}:missing`}}async function qr(e){try{let t=new Set([".git",".venv","node_modules",".workspai",".rapidkit","dist","build","coverage","__pycache__"]),i=new Set,n=new Set,o=async a=>{if(await ut(a))return true;let l=["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","project.clj","build.sbt","deno.json","deno.jsonc","CMakeLists.txt","meson.build"];for(let d of l){if(d==="*.csproj"){if((await m.readdir(a).catch(()=>[])).some(y=>y.endsWith(".csproj")))return true;continue}if(await m.pathExists(u.join(a,d)))return true}return false};await ut(e)&&i.add(e);let s=await c$2(e);for(let a of s.summary.projects){let l=u.resolve(e,a.relativePath);await o(l)&&(i.add(l),n.add(l));}let r=await a$4(e);for(let a of r){let l=u.isAbsolute(a.path)?a.path:u.join(e,a.path);if(await o(l)){let d=u.resolve(l);i.add(d),n.add(d);}}return (await a$5(e,{skipDirs:t,descendIntoMatchedProjects:true,isProjectDir:async(a,l)=>u.resolve(a)===u.resolve(l)?ut(a):o(a)})).forEach(a=>{let l=u.resolve(a);(![...n].some(p=>l!==p&&l.startsWith(`${p}${u.sep}`))||n.has(l))&&i.add(l);}),i.size===0&&(await ys(e,3,t)).forEach(l=>i.add(l)),i.size===0&&!await b$1(e)&&await o(e)&&i.add(e),Array.from(i).sort((a,l)=>a.localeCompare(l))}catch{return []}}async function Vr(e,t){let i=[u.join(e,".workspai-workspace"),u.join(e,".workspai","workspace.json"),u.join(e,".workspai","imported-projects.json"),u.join(e,".workspai","policies.yml"),u.join(e,".workspai","toolchain.lock"),u.join(e,".workspai","cache-config.yml"),u.join(e,".rapidkit-workspace"),u.join(e,".rapidkit","workspace.json"),u.join(e,".rapidkit","imported-projects.json"),u.join(e,".rapidkit","policies.yml"),u.join(e,".rapidkit","toolchain.lock"),u.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(xi)),s=await Promise.all(t.map(async r=>{let c=await Promise.all(n.map(a=>xi(u.join(r,a))));return `${r}::${c.join("|")}`}));return [jr,xr,...o,...s].join("||")}async function zr(e,t){try{if(!await m.pathExists(e))return null;let i=await m.readJSON(e);a$6(i,"contracts/doctor-workspace-cache.v2.json",`Doctor workspace cache ${e}`);let n=i;if(!n||n.signature!==t||!Array.isArray(n.projects)||typeof n.schemaVersion=="string"&&n.schemaVersion!==Ti)return null;let o=Date.parse(n.generatedAt),s=Number(process.env.WORKSPAI_DOCTOR_CACHE_MAX_AGE_SECONDS),r=Number.isFinite(s)&&s>=0?s:300;return !Number.isFinite(o)||Date.now()-o>r*1e3?null:n}catch{return null}}async function Jr(e,t){try{a$6(t,"contracts/doctor-workspace-cache.v2.json",`Doctor workspace cache ${e}`),await h(e,t$1.doctorWorkspaceCache,t);}catch{}}async function Ur(e,t){let i=Number.parseInt(process.env.RAPIDKIT_DOCTOR_SCAN_CONCURRENCY??"4",10),n=Number.isFinite(i)?Math.min(32,Math.max(1,i)):4,o=new Array(e.length),s=0,r=Array.from({length:Math.min(n,e.length)},async()=>{for(;s<e.length;){let c=s;s+=1;let a=e[c];if(a===void 0)break;o[c]=await t(a);}});return await Promise.all(r),o}async function Yr(e,t,i){let n=u.join(e,sn);try{let o=[];for(let d of t.projects)if(d.diagnosis)for(let p of d.diagnosis.findings)p.status==="blocking"&&p.symptom.trim()&&o.push(`${d.name}: ${p.symptom.trim()}`);else {for(let p of d.issues??[])typeof p=="string"&&p.trim()&&o.push(`${d.name}: ${p.trim()}`);for(let p of d.probes??[])p.status==="fail"&&p.reason.trim()&&o.push(`${d.name}: ${p.reason.trim()}`);}for(let[d,p]of [["python",t.python],["rapidkitCore",t.rapidkitCore]])if(p?.status==="error"){let y=typeof p.message=="string"?p.message:`${d} check failed`;o.push(`${d}: ${y}`);}let s=t.projects.map(ee),r=s.reduce((d,p)=>d+p.blockingFindings,0),c=s.reduce((d,p)=>d+p.advisoryFindings,0),a=Ee(t.projects,[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore,t.cliResolution]),l=f$1({schemaVersion:a$8,evidenceType:"workspace",contract:Ue(),policyProfile:t.policyProfile,workspacePath:e,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,cliResolution:t.cliResolution,versions:{core:t.coreVersion,npm:t.npmVersion}},projects:t.projects,summary:{counts:a,totalProjects:t.projects.length,totalIssues:t.projects.reduce((d,p)=>d+p.issues.length,0),verdict:t.healthScore?.verdict??"passed",blockingFindings:r,advisoryFindings:c,projectAdvisoryWarningProjects:s.filter(d=>d.advisoryFindings>0).length,projectAdvisoryWarnings:c,hasSystemErrors:[t.python,t.rapidkitCore].some(d=>d.status==="error"),scopeProvenance:t.scopeProvenance},driftDelta:t.driftDelta,scoreBreakdown:t.scoreBreakdown??[]},{commandId:"checkWorkspaceHealth",exitCode:ft(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:o.slice(0,12),runId:e$1()});return d(l),await h(e,sn,l),n}catch(o){throw o}}async function un(e=process.cwd()){let[t,i,n,o,s,r]=await Promise.all([Zr(),Xr(),Qr(),es(),ts(e),wi()]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:s,cliResolution:r}}async function Zr(){let e=j$1(),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}),c=`${o??""}
|
|
19
|
-
${s??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(c){let a=c[1],[l,d]=a.split(".").map(Number);if(l<3||l===3&&d<10){t??={version:a,command:[i,...n.slice(0,-1)].join(" ")};continue}return {status:"ok",message:`Python ${a}`,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 Xr(){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$1().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 Ni())try{if(!await m.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 Qr(){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$1();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 es(){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 ts(e=process.cwd()){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],n=[],o=br(t,e);for(let{location:r,path:c}of o)try{if(await m.pathExists(c)){let{stdout:a,exitCode:l}=await execa(c,["--version"],{timeout:3e3,reject:false});if(l===0&&(a.includes("RapidKit Version")||a.includes("RapidKit"))){let d=a.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(d){let p=await execa(c,["list","--json"],{timeout:5e3,reject:false});p.exitCode===0?i.push({location:r,path:c,version:d[1]}):n.push({location:r,path:c,version:d[1],reason:pt(p.stderr||p.stdout)});}}}}catch(a){await m.pathExists(c)&&n.push({location:r,path:c,reason:pt(a instanceof Error?a.message:String(a))});continue}if(i.length>0){let r=i.filter(a=>a.location!=="Workspace (launcher)");if(r.length>0){let a=kr(r),l=a[0].version,d=a.some(b=>b.location==="Workspace (.venv)"),p=a.some(b=>b.location.startsWith("Global (")),y=!d&&p?"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 ${l}`,details:y,paths:a.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:r,exitCode:c}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(c===0&&(r.includes("RapidKit Version")||r.includes("RapidKit"))){let a=r.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a){let l=await execa("rapidkit",["list","--json"],{timeout:5e3,reject:false});if(l.exitCode===0)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via PATH"};n.push({location:"PATH",path:"rapidkit",version:a[1],reason:pt(l.stderr||l.stdout)});}}}catch{}try{let{stdout:r,exitCode:c}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(c===0&&(r.includes("RapidKit Version")||r.includes("RapidKit"))){let a=r.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a){let l=await execa("poetry",["run","rapidkit","list","--json"],{timeout:5e3,reject:false});if(l.exitCode===0)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via Poetry"};n.push({location:"Poetry",path:"poetry run rapidkit",version:a[1],reason:pt(l.stderr||l.stdout)});}}}catch{}let s=j$1();for(let r of s)try{let c=r==="py"?["-3","-c","import rapidkit_core; print(rapidkit_core.__version__)"]:["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{stdout:a,exitCode:l}=await execa(r,c,{timeout:3e3,reject:false});if(l===0&&a&&!a.includes("Traceback")&&!a.includes("ModuleNotFoundError")){let d=a.trim();if(d){let y=await execa(r,r==="py"?["-3","-m","rapidkit","list","--json"]:["-m","rapidkit","list","--json"],{timeout:5e3,reject:false});if(y.exitCode===0)return {status:"ok",message:`RapidKit Core ${d}`,details:`Available in ${r} environment`};n.push({location:`${r} environment`,path:`${r} -m rapidkit`,version:d,reason:pt(y.stderr||y.stdout)});}}}catch{continue}if(n.length>0){let r=n[0];return {status:"error",message:r.version?`RapidKit Core ${r.version} installed but unusable`:"RapidKit Core installed but unusable",details:`${r.reason} Reinstall or repair this Python environment before running Core-backed commands.`,paths:n.map(({location:c,path:a,version:l})=>({location:c,path:a,...l?{version:l}:{}}))}}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}function pt(e){let t=e.replace(/\x1b\[[0-9;]*m/g,"").replace(/\s+/g," ").trim();return t?t.length>240?`${t.slice(0,237)}...`:t:"A real Core catalog command failed without diagnostics."}async function Y(e,t,i){let n=await Zt(e);t.hasDocker=n.rootDockerfile||n.nestedDockerfile||n.compose;let o=u.join(e,"tests"),s=u.join(e,"test"),r=u.join(e,"src","test"),c=await m.pathExists(o)||await m.pathExists(s)||await m.pathExists(r),a=false;if(t.framework==="Go/Fiber"||t.framework==="Go/Gin")try{let d=[{dir:e,depth:0}],p=4,y=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;d.length>0&&!a;){let b=d.shift();if(!b)break;let v=[];try{v=await m.readdir(b.dir);}catch{continue}for(let C of v){let h=u.join(b.dir,C),w;try{w=await m.stat(h);}catch{continue}if(w.isFile()&&C.endsWith("_test.go")){a=true;break}w.isDirectory()&&b.depth<p&&!y.has(C)&&!C.startsWith(".")&&d.push({dir:h,depth:b.depth+1});}}}catch{}let l=await g$2(e);if(t.hasTests=c||a||l.detected,(t.runtimeFamily==="node"||t.runtimeFamily==="bun")&&!t.hasTests&&(t.hasTests=await ei(e,i)),t.runtimeFamily==="python"&&!t.hasTests&&(t.hasTests=await ss(e)),t.runtimeFamily==="node"||t.runtimeFamily==="bun")t.hasCodeQuality=await Qn(e,i);else if(t.framework==="Go/Fiber"||t.framework==="Go/Gin"){let d=u.join(e,".golangci.yml"),p=u.join(e,".golangci.yaml"),y=u.join(e,"Makefile"),b=await m.pathExists(y)&&(await m.readFile(y,"utf8")).includes("golangci-lint");t.hasCodeQuality=await m.pathExists(d)||await m.pathExists(p)||b;}else if(t.runtimeFamily==="python"){let d=u.join(e,"ruff.toml"),p=u.join(e,"pyproject.toml");if(await m.pathExists(p))try{let y=await m.readFile(p,"utf8");t.hasCodeQuality=y.includes("[tool.ruff]")||await m.pathExists(d);}catch{t.hasCodeQuality=await m.pathExists(d);}}else if(t.framework==="Spring Boot"){let d=u.join(e,"pom.xml");if(await m.pathExists(d))try{let p=await m.readFile(d,"utf8");t.hasCodeQuality=p.includes("spotless")||p.includes("checkstyle")||p.includes("pmd")||p.includes("maven-enforcer-plugin");}catch{t.hasCodeQuality=false;}}t.dependencyAudit=await di({projectPath:e,runtime:t.runtimeFamily??"unknown",fresh:t._freshDependencyAudit===true}),t.vulnerabilities=t.dependencyAudit.status==="vulnerable"?t.dependencyAudit.blockingFindingCount??t.dependencyAudit.findingCount??0:void 0;}function ns(e){return Ii([m$2(e),u.join(e,"Scripts","python.exe"),u.join(e,"Scripts","python"),u.join(e,"bin","python"),u.join(e,"bin","python3")])}function is(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 Ci(e){for(let t of ns(e.environmentPath)){if(!await m.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=is(`${n.stdout??""}
|
|
20
|
-
${n.stderr??""}`),s=new Set(["pip","setuptools","wheel"]),r=o?.some(c=>typeof c.name=="string"&&!s.has(c.name.toLowerCase()))??false;return {interpreter:t,coreVersion:i,dependenciesInstalled:r}}catch{return {interpreter:t,coreVersion:i,dependenciesInstalled:false}}}return {dependenciesInstalled:false}}async function os(e){let t=["env","info","--path"],i=[{executable:"poetry",args:t},...j$1().map(o=>({executable:o,args:o==="py"?["-3","-m","poetry",...t]:["-m","poetry",...t]})),...Ni().map(o=>({executable:o,args:t}))],n=new Set;for(let o of i){let s=`${o.executable}\0${o.args.join("\0")}`;if(!n.has(s)&&(n.add(s),!(u.isAbsolute(o.executable)&&!await m.pathExists(o.executable))))try{let r=await execa(o.executable,o.args,{cwd:e,timeout:Math.max(a$9(),15e3),reject:false,shell:c$1()}),c=r.stdout.trim();if(r.exitCode===0&&c&&await m.pathExists(c))return c}catch{}}}async function rs(e,t,i){let n=u.join(e,".venv");if(await m.pathExists(n))return {environmentPath:n,...await Ci({environmentPath:n,frameworkImport:t})};if(i){let o=await os(e);if(o)return {environmentPath:o,...await Ci({environmentPath:o,frameworkImport:t})}}return {dependenciesInstalled:false}}function _(e,t){e.probes||(e.probes=[]);let i=ln(t,new Date().toISOString()),n=i.status==="pass"&&i.repairCapability?{...i,repairCapability:void 0}:i;e.probes.push(n),n.repairCapability&&(e.repairCapabilities||(e.repairCapabilities=[]),e.repairCapabilities.push(n.repairCapability),n.status!=="pass"&&n.repairCapability.status==="available"&&n.repairCapability.canAutoFix&&n.repairCapability.command&&(e.fixCommands=e.fixCommands??[],e.fixCommands.includes(n.repairCapability.command)||e.fixCommands.push(n.repairCapability.command)));}async function ve(e,t){return (await Promise.all(t.map(i=>m.pathExists(u.join(e,i))))).some(Boolean)}async function Li(e){let t=["pyproject.toml","requirements.txt","package.json","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","composer.json","Gemfile"],i=[];for(let n of t)try{let o=await m.readFile(u.join(e,n),"utf8");i.push(o.slice(0,256e3));}catch{}return i.join(`
|
|
21
|
-
`)}async function ss(e){if(await ve(e,["pytest.ini","tox.ini","noxfile.py","conftest.py","tests","test"]))return true;let t=await Li(e);return /\[tool\.pytest(?:\.|\])|\bpytest\b|\bunittest\b|\btox\b|\bnox\b/i.test(t)}async function ae(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=>u.join(e,s));for(;o.length>0;){let s=o.shift(),r;try{r=await m.readdir(s,{withFileTypes:true});}catch{continue}for(let c of r){if(c.isFile()&&(t.name&&c.name===t.name||t.suffix&&c.name.endsWith(t.suffix)))return true;c.isDirectory()&&!i.has(c.name)&&o.push(u.join(s,c.name));}}return false}async function as(e,t){let i=t.runtimeFamily||"unknown";if(!(t.projectKind==="backend"||t.projectKind==="generic"||t.projectKind==="desktop"||t.projectKind==="extension"))return;if(i==="node"){let l=await m.pathExists(u.join(e,"package-lock.json"))||await m.pathExists(u.join(e,"pnpm-lock.yaml"))||await m.pathExists(u.join(e,"yarn.lock"));_(t,{id:"adapter-node-lockfile-integrity",label:"Node adapter lockfile integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml).",recommendation:l?void 0:"Commit a lockfile for deterministic installs and CI parity."});let d=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"],p=await ve(e,d);_(t,{id:"adapter-node-boot-entrypoint",label:t.projectKind==="extension"?"Extension activation entrypoint":t.projectKind==="desktop"?"Desktop application entrypoint":"Node adapter boot entrypoint",status:p?"pass":"warn",severity:"warn",scope:"project-scoped",reason:p?`${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:p?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 l=await m.pathExists(u.join(e,"poetry.lock"))||await m.pathExists(u.join(e,"requirements.txt"))||await m.pathExists(u.join(e,"uv.lock"));_(t,{id:"adapter-python-lockfile-integrity",label:"Python adapter dependency integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Python dependency contract file detected.":"No Python dependency contract file detected (poetry.lock/requirements/uv.lock).",recommendation:l?void 0:"Pin dependency contract for deterministic setup and reproducible CI."});let d=["src/main.py","src/app/main.py","app/main.py","main.py","manage.py","asgi.py","wsgi.py"],p=await m.readFile(u.join(e,"pyproject.toml"),"utf8").catch(()=>""),b=/\[(?:project\.scripts|tool\.poetry\.scripts)\]/i.test(p)||await ve(e,d);_(t,{id:"adapter-python-boot-entrypoint",label:"Python adapter boot entrypoint",status:b?"pass":"warn",severity:"warn",scope:"project-scoped",reason:b?"Python application or command entrypoint markers detected.":"No Python application or command entrypoint markers detected.",recommendation:b?void 0:"Expose an explicit app/main module or package script for deterministic launch probes."});return}if(i==="java"){let l=await m.pathExists(u.join(e,"mvnw"))||await m.pathExists(u.join(e,"gradlew"));_(t,{id:"adapter-java-build-wrapper",label:"Java adapter build wrapper",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Build wrapper detected (mvnw/gradlew).":"No Java build wrapper detected.",recommendation:l?void 0:"Commit mvnw or gradlew for reproducible enterprise pipelines."});let d=await ve(e,["src/main/java/Application.java","src/main/kotlin/Application.kt"])||await ae(e,{suffix:"Application.java",under:["src/main/java"]})||await ae(e,{suffix:"Application.kt",under:["src/main/kotlin"]});_(t,{id:"adapter-java-boot-entrypoint",label:"Java adapter boot entrypoint",status:d?"pass":"warn",severity:"warn",scope:"project-scoped",reason:d?"Java application entrypoint markers detected.":"No Java application entrypoint markers detected.",recommendation:d?void 0:"Expose a Spring Boot Application class under src/main/java or src/main/kotlin."});return}if(i==="go"){let l=await m.pathExists(u.join(e,"go.sum"));_(t,{id:"adapter-go-module-integrity",label:"Go adapter module integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"go.sum detected for deterministic module verification.":"go.sum missing; module integrity baseline is incomplete.",recommendation:l?void 0:"Generate and commit go.sum in the repository baseline."});let d=await ve(e,["cmd/server/main.go","cmd/api/main.go","main.go"]);_(t,{id:"adapter-go-boot-entrypoint",label:"Go adapter boot entrypoint",status:d?"pass":"warn",severity:"warn",scope:"project-scoped",reason:d?"Go application entrypoint markers detected.":"No Go application entrypoint markers detected.",recommendation:d?void 0:"Expose a Go main package entrypoint such as cmd/server/main.go."});return}if(i==="dotnet"){let l=await ve(e,["Program.cs","src/Program.cs"])||await ae(e,{name:"Program.cs"});_(t,{id:"adapter-dotnet-boot-entrypoint",label:".NET adapter boot entrypoint",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?".NET application entrypoint markers detected.":"No .NET application entrypoint markers detected.",recommendation:l?void 0:"Expose Program.cs at the project root or under src for deterministic boot probes."});return}let s={rust:{dependencyMarkers:["Cargo.lock"],entrypointMarkers:["src/main.rs","src/lib.rs"],dependencyLabel:"Rust lockfile integrity",entrypointLabel:"Rust crate entrypoint"},php:{dependencyMarkers:["composer.lock"],entrypointMarkers:["public/index.php","artisan","index.php"],dependencyLabel:"Composer lockfile integrity",entrypointLabel:"PHP application entrypoint"},ruby:{dependencyMarkers:["Gemfile.lock"],entrypointMarkers:["config.ru","app.rb","config/application.rb"],dependencyLabel:"Bundler lockfile integrity",entrypointLabel:"Ruby application entrypoint"},elixir:{dependencyMarkers:["mix.lock"],entrypointMarkers:["lib/application.ex","lib/*/application.ex"],dependencyLabel:"Mix lockfile integrity",entrypointLabel:"Elixir application entrypoint"},clojure:{dependencyMarkers:["deps.edn","project.clj"],entrypointMarkers:["src/core.clj","src/main.clj"],dependencyLabel:"Clojure dependency contract",entrypointLabel:"Clojure application entrypoint"},deno:{dependencyMarkers:["deno.lock","deno.json","deno.jsonc"],entrypointMarkers:["main.ts","mod.ts","src/main.ts","src/mod.ts"],dependencyLabel:"Deno dependency contract",entrypointLabel:"Deno application entrypoint"},bun:{dependencyMarkers:["bun.lock","bun.lockb"],entrypointMarkers:["src/index.ts","src/main.ts","index.ts"],dependencyLabel:"Bun lockfile integrity",entrypointLabel:"Bun application entrypoint"},scala:{dependencyMarkers:["build.sbt","project/build.properties"],entrypointMarkers:["src/main/scala/Main.scala","src/main/scala/Application.scala"],dependencyLabel:"Scala build contract",entrypointLabel:"Scala application entrypoint"},kotlin:{dependencyMarkers:["build.gradle.kts","gradle.lockfile"],entrypointMarkers:["src/main/kotlin/Application.kt","src/main/kotlin/Main.kt"],dependencyLabel:"Kotlin build contract",entrypointLabel:"Kotlin application entrypoint"},c:{dependencyMarkers:["CMakeLists.txt","meson.build","Makefile"],entrypointMarkers:["src/main.c","main.c"],dependencyLabel:"C build contract",entrypointLabel:"C application entrypoint"},cpp:{dependencyMarkers:["CMakeLists.txt","meson.build","Makefile"],entrypointMarkers:["src/main.cpp","main.cpp","src/main.cc","main.cc"],dependencyLabel:"C++ build contract",entrypointLabel:"C++ application entrypoint"}}[i];if(!s)return;let r=(i==="c"||i==="cpp")&&e$2(e),c=r||await ve(e,s.dependencyMarkers);_(t,{id:`adapter-${i}-dependency-contract`,label:s.dependencyLabel,status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?r?`${s.dependencyLabel} detected across multiple native workspace components.`:`${s.dependencyLabel} detected.`:`${s.dependencyLabel} is missing.`,recommendation:c?void 0:`Add a runtime-native dependency/build contract: ${s.dependencyMarkers.join(", ")}.`,issueClass:"dependency",operationalImpact:"ci-risk"});let a=await ve(e,s.entrypointMarkers);!a&&i==="elixir"&&(a=await ae(e,{name:"application.ex",under:["lib"]})),!a&&i==="scala"&&(a=await ae(e,{name:"Main.scala",under:["src/main/scala"]})||await ae(e,{name:"Application.scala",under:["src/main/scala"]})),!a&&i==="kotlin"&&(a=await ae(e,{name:"Application.kt",under:["src/main/kotlin"]})||await ae(e,{name:"Main.kt",under:["src/main/kotlin"]})),_(t,{id:`adapter-${i}-boot-entrypoint`,label:s.entrypointLabel,status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?`${s.entrypointLabel} detected.`:`${s.entrypointLabel} is not explicitly declared.`,recommendation:a?void 0:`Expose a conventional entrypoint or declare a custom Doctor adapter for this ${i} project.`,issueClass:"runtime",operationalImpact:"runtime-risk"});}async function cs(e,t){let i=[u.join(e,".workspai","doctor.adapters.json"),u.join(e,".rapidkit","doctor.adapters.json"),u.join(e,"doctor.adapters.json")];for(let n of i)if(await m.pathExists(n))try{let o=await m.readJSON(n),s=Array.isArray(o?.checks)?o.checks:[];for(let r=0;r<s.length;r+=1){let c=s[r]||{},a=Array.isArray(c.runtimes)?c.runtimes:[];if(a.length>0&&!a.includes(t.runtimeFamily||"unknown"))continue;let l=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`adapter-check-${r+1}`,d=typeof c.label=="string"&&c.label.trim().length>0?c.label.trim():l,p=c.severity||"warn",y=Array.isArray(c.anyOfPaths)?c.anyOfPaths.filter(Boolean):[],b=Array.isArray(c.allOfPaths)?c.allOfPaths.filter(Boolean):[],v=y.length===0;for(let w of y)if(await m.pathExists(u.join(e,w))){v=true;break}let C=true;for(let w of b)if(!await m.pathExists(u.join(e,w))){C=false;break}let h=v&&C;_(t,{id:l,label:d,status:h?"pass":p==="error"?"fail":"warn",severity:p,scope:"project-scoped",reason:h?c.passReason||"Custom adapter contract satisfied.":c.failReason||`Custom adapter check failed from ${u.basename(n)}.`,recommendation:c.recommendation});}}catch{_(t,{id:"custom-adapter-config",label:"Custom doctor adapter configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${u.basename(n)}.`,recommendation:"Fix JSON syntax in doctor.adapters.json to re-enable adapter checks."});}}async function Z(e,t){if(!(t.projectKind==="backend"||t.projectKind==="generic"))return;let n=await ve(e,[".env",".env.example",".env.sample",".env.template",".env.public","config","docs/env.md","ENVIRONMENT.md"]);_(t,{id:"config-surface",label:"Configuration contract surface",status:n?"pass":"warn",severity:"warn",scope:"project-scoped",reason:n?"Configuration contract artifacts or documentation detected.":"No explicit configuration contract artifacts detected.",recommendation:n?void 0:"Add a secret-free environment example or explicit config contract documentation for deterministic setup."});let o={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"]},s=t.runtimeFamily||"unknown",r=o[s]||o.unknown,c=false;for(let b of r)if(await m.pathExists(u.join(e,b))){c=true;break}let a=await Li(e),l=c||/\b(alembic|sqlalchemy|prisma|typeorm|sequelize|django|drizzle|flyway|liquibase|gorm|diesel|sqlx|entity\s*framework|postgres(?:ql)?|mysql|mariadb|sqlite)\b/i.test(a);_(t,{id:"migration-surface",label:"Migration/readiness surface",status:c||!l?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:l?"applicable":"not-applicable",reason:c?"Migration or schema evolution markers detected.":l?"No migration markers detected for this backend runtime.":"No relational persistence or schema-migration intent was detected; a migration surface is not currently applicable.",recommendation:c||!l?void 0:"Add migration tooling baseline (migrations dir or runtime-native migration config)."});let d=["src/health","src/healthcheck","src/main/resources/application.yml","src/main/resources/application.properties","app/health.py","routes/health.ts","routes/health.js"],p=false;for(let b of d)if(await m.pathExists(u.join(e,b))){p=true;break}let y=p||/\b(fastapi|flask|django|express|nestjs|spring[ -]?boot|axum|actix(?:-web)?|gin-gonic|gofiber|asp\.net|laravel|rails)\b/i.test(`${t.framework??""}
|
|
22
|
-
${a}`);_(t,{id:"runtime-health-surface",label:"Runtime health probe surface",status:p||!y?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:y?"applicable":"not-applicable",reason:p?"Health endpoint/config markers detected.":y?"No explicit runtime health endpoint markers detected.":"No HTTP service runtime intent was detected; an endpoint health surface is not currently applicable.",recommendation:p||!y?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await as(e,t);}async function ls(e,t,i,n){let o=await ti({projectPath:e,detection:n,packageJsonData:i});for(let s of o)_(t,s);}async function X(e,t,i){let n=await oi({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,o);}async function q(e,t){let i=[u.join(e,".workspai","doctor.probes.json"),u.join(e,".rapidkit","doctor.probes.json"),u.join(e,"doctor.probes.json")];for(let n of i)if(await m.pathExists(n))try{let o=await m.readJSON(n),s=Array.isArray(o?.probes)?o.probes:[];for(let r=0;r<s.length;r+=1){let c=s[r]||{},a=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`custom-probe-${r+1}`,l=typeof c.label=="string"&&c.label.trim().length>0?c.label.trim():a,d=c.severity||"warn",p=Array.isArray(c.anyOfPaths)?c.anyOfPaths.filter(Boolean):[],y=Array.isArray(c.allOfPaths)?c.allOfPaths.filter(Boolean):[],b=p.length===0;for(let h of p)if(await m.pathExists(u.join(e,h))){b=true;break}let v=true;for(let h of y)if(!await m.pathExists(u.join(e,h))){v=false;break}let C=b&&v;_(t,{id:a,label:l,status:C?"pass":d==="error"?"fail":"warn",severity:d,scope:"project-scoped",reason:C?"Custom probe contract satisfied.":`Custom probe failed from ${u.basename(n)}.`,recommendation:c.recommendation});}}catch{_(t,{id:"custom-probe-config",label:"Custom doctor probe configuration",status:"warn",severity:"warn",scope:"project-scoped",reason:`Failed to parse ${u.basename(n)}.`,recommendation:"Fix JSON syntax in doctor.probes.json to re-enable custom probes."});}await cs(e,t);}async function ds(e,t={}){let n={name:u.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[],_freshDependencyAudit:t.freshAudit===true},o=t.allowNonRapidkit===true;if(!(await m.pathExists(u.join(e,".workspai"))||await m.pathExists(u.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 S=u.join(e,"registry.json");if(await m.pathExists(S)){let E=await m.readJson(S);E.installed_modules&&(n.stats={modules:E.installed_modules.length});}}catch{}try{let{auditProjectModulePaths:S}=await import('./module-layout-NZ43RSC5.js'),E=await S(e);if(E.issues.length>0){for(let B of E.issues)n.issues.push(`${B.message} (${B.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 r=null;try{for(let S of u$1(e,"project.json")){if(!await m.pathExists(S))continue;r=await m.readJson(S);let E=typeof r?.name=="string"?r.name:typeof r?.slug=="string"?r.slug:void 0;E?.trim()&&(n.name=E.trim());let B=j$2(r)?void 0:r?.kit_name||r?.kit;B&&(n.kit=B);break}}catch{}try{let S=u.join(e,".git");if(await m.pathExists(S)){let{stdout:E}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false,env:a$b()});E&&(n.lastModified=E.trim());}else {let E=await m.stat(e),ce=Date.now()-E.mtime.getTime(),J=Math.floor(ce/(1e3*60*60*24));n.lastModified=J===0?"today":`${J} day${J>1?"s":""} ago`;}}catch{}let c=u.join(e,"package.json"),a=u.join(e,"pyproject.toml"),l$1=u.join(e,"requirements.txt"),d=u.join(e,"go.mod"),p=u.join(e,"pom.xml"),y=u.join(e,"build.sbt"),b=u.join(e,"Cargo.toml"),v=u.join(e,"mix.exs"),C=u.join(e,"deps.edn"),h=u.join(e,"project.clj"),w=u.join(e,"deno.json"),P=u.join(e,"deno.jsonc"),R=u.join(e,"bun.lockb"),x=u.join(e,"bun.lock"),g=u.join(e,"composer.json"),D=u.join(e,"Gemfile"),k=await m.pathExists(c),A=await m.pathExists(a)||await m.pathExists(l$1),j=await m.pathExists(g),G=await m.pathExists(D),F=await m.pathExists(b),V=await m.pathExists(v),se=await m.pathExists(C)||await m.pathExists(h),W=await m.pathExists(y),K=await m.pathExists(w)||await m.pathExists(P),T=k&&(await m.pathExists(R)||await m.pathExists(x)||typeof r?.packageManager=="string"&&(r?.packageManager).toLowerCase().startsWith("bun@")),me=(await m.readdir(e).catch(()=>[])).some(S=>S.endsWith(".csproj")||S.endsWith(".sln")),oe=k||A||j||G||F||V||se||W||K||await m.pathExists(d)||await m.pathExists(p)||await m.pathExists(u.join(e,"build.gradle"))||await m.pathExists(u.join(e,"build.gradle.kts"))||me||await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),re=oe?[]:l(e),Be=!oe&&re.length>=2,Ge=m$1(e,r??null),z=Ge.runtime;if(Be)return ie(n,Ge),n.venvActive=true,n.depsInstalled=true,n.coreInstalled=false,_(n,{id:"composite-project-boundary",label:"Composite project boundary",status:"warn",severity:"warn",scope:"project-scoped",reason:`This adopted root contains ${re.length} nested runtime families but no root-owned runtime manifest. Doctor did not apply one nested runtime's dependency lifecycle to the aggregate boundary.`,recommendation:"Register independently operated nested projects as explicit workspace project boundaries, or add doctor.adapters.json checks for the aggregate contract.",issueClass:"runtime",operationalImpact:"ci-risk"}),await q(e,n),n;if(Ge.runtime==="c"||Ge.runtime==="cpp")return ie(n,Ge),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true,n.modulesHealthy=true,n.missingModules=[],await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n;if(z==="go"){ie(n,m$1(e,r??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/");}let S=u.join(e,"go.sum");return await m.pathExists(S)?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 Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="kotlin"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=await m.pathExists(u.join(e,"gradlew"))||await m.pathExists(u.join(e,"gradlew.bat"));if(n.depsInstalled=await m.pathExists(u.join(e,"build"))||await m.pathExists(u.join(e,".gradle")),!n.depsInstalled){n.issues.push("Kotlin dependencies/build artifacts are not initialized");let B=S?b$5()?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies";n.fixCommands?.push(Q(e,B));}let E=u.join(e,".env");return n.hasEnvFile=await m.pathExists(E),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="java"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=await m.pathExists(p),E=await m.pathExists(u.join(e,"build.gradle"))||await m.pathExists(u.join(e,"build.gradle.kts")),B=await m.pathExists(u.join(e,"mvnw"))||await m.pathExists(u.join(e,"mvnw.cmd")),ce=await m.pathExists(u.join(e,"gradlew"))||await m.pathExists(u.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");}if(S){if(!B)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");}}else if(E&&!ce)try{await execa("gradle",["--version"],{timeout:3e3,reject:false});}catch{n.issues.push("Gradle not found \u2014 install Gradle 8+ or add Gradle Wrapper");}let J=u.join(e,"target"),Ke=u.join(e,"build","libs"),Fe=u.join(e,".workspai","cache","java","m2"),I=u.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await m.pathExists(J)||await m.pathExists(Ke)||await m.pathExists(Fe)||await m.pathExists(I),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let $e=S?B?b$5()?".\\mvnw.cmd -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"./mvnw -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"mvn -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":ce?b$5()?".\\gradlew.bat --project-cache-dir .workspai/cache/java/gradle dependencies":"./gradlew --project-cache-dir .workspai/cache/java/gradle dependencies":"gradle --project-cache-dir .workspai/cache/java/gradle dependencies";n.fixCommands?.push(Q(e,$e));}let H=u.join(e,".env");n.hasEnvFile=await m.pathExists(H);let le=u.join(e,"src","main","resources","application.yml");if(await m.pathExists(le))try{let $e=await m.readFile(le,"utf-8");/include:\s*[^\n]*health/i.test($e)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test($e)||(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 Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="rust"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"Cargo.lock"),E=u.join(e,"target");n.depsInstalled=await m.pathExists(S)||await m.pathExists(E),n.depsInstalled||(n.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),n.fixCommands?.push(Q(e,"cargo fetch")));let B=u.join(e,".env");return n.hasEnvFile=await m.pathExists(B),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="elixir"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"mix.lock"),E=u.join(e,"deps");n.depsInstalled=await m.pathExists(S)||await m.pathExists(E),n.depsInstalled||(n.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),n.fixCommands?.push(Q(e,"mix deps.get")));let B=u.join(e,".env");return n.hasEnvFile=await m.pathExists(B),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="clojure"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,".cpcache"),E=u.join(e,"target"),B=await m.pathExists(C)||await m.pathExists(h);return n.depsInstalled=await m.pathExists(S)||await m.pathExists(E)||B,n.depsInstalled||(n.issues.push("Clojure dependency cache not initialized"),n.fixCommands?.push(Q(e,await m.pathExists(C)?"clojure -P":"lein deps"))),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="scala"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"target");n.depsInstalled=await m.pathExists(S),n.depsInstalled||(n.issues.push("Scala build artifacts missing (run dependency/build warmup)"),n.fixCommands?.push(Q(e,"sbt compile")));let E=u.join(e,".env");return n.hasEnvFile=await m.pathExists(E),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="deno"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true;let S=u.join(e,".env");return n.hasEnvFile=await m.pathExists(S),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="node"||z==="bun"){let S=null;try{S=await m.readJson(c);}catch{S=null;}let E={...S?.dependencies??{},...S?.devDependencies??{}},B=S?.scripts??{},ce=typeof r?.kit_name=="string"?r.kit_name.toLowerCase():typeof r?.kit=="string"?r.kit.toLowerCase():"",J=d$2(e,r),Ke=Hr({dependencies:E,scripts:B,kitName:ce});if(T)dt(n,"Bun","high");else {let I=m$1(e,r??null);I.key==="nestjs"||I.key==="express"||I.key==="fastify"||I.key==="koa"||I.key==="tauri"||I.key==="electron"||I.key==="vscode-extension"?ie(n,I):J.key!=="unknown"?Wr(n,J):I.key!=="unknown"&&I.key!=="node"?ie(n,I):dt(n,Ke.framework,Ke.confidence);}n.venvActive=true;let Fe=u.join(e,"node_modules");if(await m.pathExists(Fe))try{let H=(await m.readdir(Fe)).filter(le=>!le.startsWith(".")&&!le.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 I=typeof S?.packageManager=="string"?S.packageManager.split("@")[0]:void 0,H=T?"bun install":I==="pnpm"||await m.pathExists(u.join(e,"pnpm-lock.yaml"))?"pnpm install":I==="yarn"||await m.pathExists(u.join(e,"yarn.lock"))?"yarn install":"npm install";n.fixCommands?.push(Q(e,H));}if(n.coreInstalled=false,n.projectKind==="frontend"){let I=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(I.map(le=>m.pathExists(u.join(e,le))))).some(Boolean))n.hasEnvFile=true;else {let le=u.join(e,".env.example");await m.pathExists(le)&&(n.hasEnvFile=false);}}else {let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);}if(n.projectKind==="frontend")n.modulesHealthy=await Ut(e),n.missingModules=[];else {let I=u.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(I))try{let H=await m.readdir(I);n.modulesHealthy=H.length>0;}catch{n.modulesHealthy=false;}}return await Y(e,n,S),await X(e,n,S),n.projectKind==="frontend"?await ls(e,n,S,J.key!=="unknown"?J:d$2(e,r)):await Z(e,n),await q(e,n),n}if(z==="python"){let S=await Lr(e,r);dt(n,S.framework,S.confidence);let E="fastapi";n.framework==="Django"?E="django":n.framework==="Flask"?E="flask":n.framework==="Python"&&(E="");let B=await _t(a),ce=/\[tool\.poetry\]/.test(B),J=await Mr(e),Ke=J?"project-script":ce?"poetry":await m.pathExists(u.join(e,"uv.lock"))?"uv":"venv",Fe=Nr({projectPath:e,manager:Ke,...J?{projectScript:J}:{}}),I=await rs(e,E,ce);n.venvActive=!!I.environmentPath,n.depsInstalled=I.dependenciesInstalled,n.coreInstalled=!!I.coreVersion,n.coreVersion=I.coreVersion;let H=B.match(/^\s*requires-python\s*=\s*["']([^"']+)["']/m)?.[1];if(H){let fe=await Tr(I.interpreter),we=fe?hi(fe,H):{version:"unknown",satisfied:null};if(n.pythonRequirement={specifier:H,...fe?{detectedVersion:fe}:{},satisfied:we.satisfied},we.satisfied===false){let ht=`Python ${we.version} does not satisfy requires-python ${H}`;n.issues.push(ht),_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"fail",severity:"error",scope:"project-scoped",reason:ht,recommendation:J?`Install a compatible Python interpreter, then run the repository-authored ${J} setup command.`:"Install a Python interpreter satisfying requires-python, then materialize the project environment.",issueClass:"runtime",operationalImpact:"release-risk"});}else we.satisfied===null?_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"warn",severity:"warn",scope:"project-scoped",reason:fe?`Python ${fe} could not be evaluated against requires-python ${H}.`:`No executable Python version could be verified against requires-python ${H}.`,recommendation:"Verify the selected project interpreter against the complete requires-python constraint before setup or release.",issueClass:"runtime",operationalImpact:"ci-risk"}):_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"pass",severity:"info",scope:"project-scoped",reason:`Python ${we.version} satisfies requires-python ${H}.`,issueClass:"runtime",operationalImpact:"none"});}I.environmentPath?I.interpreter?n.depsInstalled||(n.issues.push("Dependencies not installed"),n.fixCommands?.push(Fe)):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Fe));let le=u.join(e,".env");n.hasEnvFile=await m.pathExists(le);let $e=u.join(e,"src"),yt=u.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists($e)){let fe=u.join($e,"__init__.py");await m.pathExists(fe)||(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await m.pathExists(yt))try{let fe=await fs(yt);for(let we of fe){let ht=u.join(yt,we,"__init__.py");await m.pathExists(ht)||(n.modulesHealthy=false,n.missingModules.push(`modules/${we}/__init__.py`));}}catch{}return !n.modulesHealthy&&n.missingModules.length>0&&n.issues.push(`Missing module init files: ${n.missingModules.join(", ")}`),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="php"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"vendor");n.depsInstalled=await m.pathExists(S),n.depsInstalled||(n.issues.push("PHP dependencies not installed (vendor missing)"),n.fixCommands?.push(Q(e,"composer install")));let E=u.join(e,".env");return n.hasEnvFile=await m.pathExists(E),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="ruby"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=await m.pathExists(u.join(e,"Gemfile.lock")),E=await m.pathExists(u.join(e,"vendor","bundle"));n.depsInstalled=S||E,n.depsInstalled||(n.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),n.fixCommands?.push(Q(e,"bundle install")));let B=u.join(e,".env");return n.hasEnvFile=await m.pathExists(B),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="dotnet"){ie(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"obj"),E=u.join(e,"src","obj"),B=u.join(e,"packages.lock.json");n.depsInstalled=await m.pathExists(S)||await m.pathExists(E)||await m.pathExists(B),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(Q(e,"dotnet restore")));let ce=u.join(e,".env");return n.hasEnvFile=await m.pathExists(ce),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build"))){let S=await ae(e,{suffix:".cpp",under:["src","."]});return dt(n,S?"C++":"C","medium"),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true,await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}return dt(n,"Unknown","low"),_(n,{id:"runtime-classification",label:"Runtime classification",status:"warn",severity:"warn",scope:"project-scoped",applicability:"unknown",issueClass:"runtime",operationalImpact:"developer-friction",reason:"No recognized runtime marker files were found. Doctor is applying runtime-neutral checks without claiming runtime-specific coverage.",recommendation:"If this repository executes code, add or configure its canonical runtime/build manifest; otherwise retain it as an observed runtime-neutral project."}),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}function qi(e){if(!e.fixCommands)return e;let t=new Set;return e.fixCommands=e.fixCommands.filter(i=>{let n=i.trim();return /^https?:\/\/\S+$/i.test(n)||!n||t.has(n)?false:(t.add(n),true)}),e}async function ps(e){let t=l(e);if(t.length>0)return t;let i=async a=>m.pathExists(u.join(e,a)),n=await m.readdir(e).catch(()=>[]),o=[],s=(a,l)=>{l&&!o.includes(a)&&o.push(a);},r=await i("package.json");return s("bun",r&&(await i("bun.lock")||await i("bun.lockb"))),s("deno",await i("deno.json")||await i("deno.jsonc")),s("node",r&&!o.includes("bun")),s("python",await i("pyproject.toml")||await i("requirements.txt")),s("go",await i("go.mod")),s("kotlin",await i("build.gradle.kts")&&await ae(e,{suffix:".kt",under:["src"]})),s("java",await i("pom.xml")||await i("build.gradle")||await i("build.gradle.kts")&&!o.includes("kotlin")),s("rust",await i("Cargo.toml")),s("elixir",await i("mix.exs")),s("clojure",await i("deps.edn")||await i("project.clj")),s("scala",await i("build.sbt")),s("php",await i("composer.json")),s("ruby",await i("Gemfile")),s("dotnet",n.some(a=>a.endsWith(".csproj"))||await i("global.json")),(await i("CMakeLists.txt")||await i("meson.build"))&&(s("cpp",await ae(e,{suffix:".cpp",under:["src","."]})),s("c",await ae(e,{suffix:".c",under:["src","."]})),!o.includes("c")&&!o.includes("cpp")&&s("cpp",true)),o.length>0?o:["unknown"]}async function us(e,t){if(t.projectKind==="extension")return "plugin";if(t.projectKind==="platform")return (await m.readJson(u.join(e,"package.json")).catch(()=>null))?.workspaces?"monorepo":"platform";if(t.projectKind==="library")return "library";if(t.projectKind==="frontend"||t.projectKind==="desktop"||t.projectKind==="fullstack")return "application";let i=await m.readJson(u.join(e,"package.json")).catch(()=>null),n=!!(i&&(Array.isArray(i.workspaces)||i.workspaces&&typeof i.workspaces=="object")),o=await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),s=await m.pathExists(u.join(e,"include")),r=(await Promise.all(["bindings","src/proto","proto","python","ruby","php","csharp","objective-c"].map(d=>m.pathExists(u.join(e,d))))).some(Boolean);if((t.runtimeFamilies?.length??0)>=3||(t.runtimeFamilies?.length??0)>=2&&o&&r)return "platform";if(n)return "monorepo";let c=i?.scripts&&typeof i.scripts=="object"?i.scripts:{},a=!!(i?.exports||i?.types||i?.main),l=!!(c.start||c.dev||c.serve);return a&&!l?/sdk|client/i.test(String(i?.name??t.name))?"sdk":"library":o&&s?"library":t.projectKind==="backend"?"service":"unknown"}function ms(e){let t=e.probes??[],i=t.map((r,c)=>r.id==="config-surface"?c:-1).filter(r=>r>=0);t.some(r=>r.id==="surface-env-contract")&&(e.probes=t.filter((r,c)=>!i.includes(c)));let n=new Set(["library","sdk","platform","plugin","monorepo"]);if(!e.projectArchetype||!n.has(e.projectArchetype))return;let o=new Set;e.probes=(e.probes??[]).map(r=>{let c=r.id==="frontend-framework-config"||r.id==="frontend-source-tree"||r.id.startsWith("frontend-script-");return r.id==="migration-surface"||r.id==="runtime-health-surface"||r.id==="surface-kubernetes-readiness"||c||r.id.endsWith("-boot-entrypoint")||r.id==="runtime-security-tooling"&&e.probes?.some(l=>l.id==="surface-security-hygiene")||r.id==="surface-env-contract"&&r.status!=="pass"?(r.repairCapability?.command&&o.add(r.repairCapability.command),{...r,status:"pass",severity:"info",applicability:"not-applicable",reason:`${r.label} is not required for the detected ${e.projectArchetype} archetype.`,recommendation:void 0,repairCapability:void 0,repairIntent:void 0}):r});let s=new Set((e.probes??[]).map(r=>r.repairCapability?.id).filter(r=>!!r));e.repairCapabilities=(e.repairCapabilities??[]).filter(r=>s.has(r.id)),e.fixCommands=(e.fixCommands??[]).filter(r=>!o.has(r));}async function Mt(e,t={}){let i=qi(await ds(e,t));delete i._freshDependencyAudit,Cs(i),i.runtimeFamilies=await ps(e),i.runtimeFamily&&i.runtimeFamily!=="unknown"&&!i.runtimeFamilies.includes(i.runtimeFamily)&&i.runtimeFamilies.unshift(i.runtimeFamily),i.runtimeFamily&&i.runtimeFamily!=="unknown"&&(i.runtimeFamilies=i.runtimeFamilies.filter(o=>o!=="unknown")),i.runtimeFamilies.length>1&&_(i,{id:"runtime-composition",label:"Composite runtime coverage",status:"warn",severity:"warn",scope:"project-scoped",reason:`Multiple runtime families share one project boundary: ${i.runtimeFamilies.join(", ")}. Primary adapters evaluated ${i.runtimeFamily??"unknown"} only.`,recommendation:"Declare nested project boundaries or add doctor.adapters.json checks for every secondary runtime.",issueClass:"runtime",operationalImpact:"ci-risk"});let n=await b$3(e);if(n==="backend"||n==="service"||n==="worker"?i.projectKind="backend":n==="frontend"||n==="desktop"||n==="extension"||n==="platform"||n==="library"?i.projectKind=n:i.projectKind||(i.projectKind="generic"),i.projectArchetype=await us(e,i),i.projectArchetype==="platform"){let o=i.probes?.find(s=>s.id==="runtime-composition");o&&(o.reason=`Cross-language platform boundary detected: ${i.runtimeFamilies.join(", ")}. The primary ${i.runtimeFamily??"unknown"} adapter is combined with portable cross-runtime evidence.`,o.recommendation="Add explicit adapters only for runtime-specific checks that are not represented by the portable evidence contract.");}return ms(i),$t(i),i}async function fs(e){try{return (await m.readdir(e,{withFileTypes:true})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{try{let t=await m.readdir(e),i=[];for(let n of t)try{(await m.stat(u.join(e,n))).isDirectory()&&i.push(n);}catch{continue}return i}catch{return []}}}async function ut(e){let t=["project.json","context.json","file-hashes.json"];for(let i of [".workspai",".rapidkit"])for(let n of t)if(await m.pathExists(u.join(e,i,n)))return true;return false}function gs(e,t){if(t.has(e)||a$c(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 ys(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 r=await m.readdir(s.dir);for(let c of r){if(gs(c,i))continue;let a=u.join(s.dir,c),l;try{l=await m.stat(a);}catch{continue}if(l.isDirectory()){if(await ut(a)){n.add(a);continue}s.depth<t&&o.push({dir:a,depth:s.depth+1});}}}catch{continue}}return Array.from(n)}async function mt(e){let t=a$1(e);if(t)return t;let i=u.resolve(e),n=u.parse(i).root;for(;;){if(await ks(i))return i;if(i===n)return null;i=u.dirname(i);}}async function hs(e){let t=u.resolve(e),i=await mt(t),n=i??u.parse(t).root;for(;;){if(await ut(t)||await bs(t)&&(!i||t!==i))return t;if(t===n)break;t=u.dirname(t);}return null}function Pi(e){let t=u.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function bs(e){let t=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","build.sbt","Cargo.toml","mix.exs","deps.edn","project.clj","deno.json","deno.jsonc","composer.json","Gemfile","global.json","CMakeLists.txt","meson.build"];for(let n of t)if(await m.pathExists(u.join(e,n)))return true;return !!(await m.readdir(e).catch(()=>[])).some(n=>n.endsWith(".csproj")||n.endsWith(".sln"))}async function ks(e){if(k(e))return true;let t=[u.join(e,".rapidkit","workspace-marker.json"),u.join(e,".rapidkit","config.json")];return Promise.all(t.map(i=>m.pathExists(i))).then(i=>i.some(Boolean))}function mn(e,t){let i={total:0,passed:0,warnings:0,errors:0},n={total:0,passed:0,warnings:0,errors:0};e.forEach(l=>{l.applicability!=="not-applicable"&&(i.total+=1,l.status==="ok"?i.passed+=1:l.status==="warn"?i.warnings+=1:l.status==="error"&&(i.errors+=1));}),t.forEach(l=>{let d=l.diagnosis;if(d){let v=d.coverage.passingObservations,C=d.coverage.blockingFindings,h=d.coverage.advisoryFindings+d.coverage.unknownFindings+d.coverage.contradictionCount;n.passed+=v,n.warnings+=h,n.errors+=C,n.total+=v+h+C;return}let p=l.probes??[];if(p.length>0){for(let v of p)n.total+=1,v.status==="pass"?n.passed+=1:v.status==="warn"?n.warnings+=1:n.errors+=1;l.issues.length>0&&(n.total+=l.issues.length,n.errors+=l.issues.length);return}n.total+=1;let y=vr(l),b=l.isGoProject?l.issues.length===0&&l.depsInstalled:l.issues.length===0&&l.venvActive&&l.depsInstalled;l.issues.length>0||!b?n.errors+=1:y>0?n.warnings+=1:n.passed+=1;});let o=i.passed+n.passed,s=i.warnings+n.warnings,r=i.errors+n.errors,c=Ee(t,e),a=i.total+n.total;return {total:a,passed:o,warnings:s,errors:r,verdict:r>0?"blocked":s>0?"attention":"passed",presentation:{policy:"doctor-multi-axis-v1",diagnosticPassRatePercent:a>0?Math.round(o/a*100):null,blockingFindings:c.blockingCauses+c.systemErrors,advisoryFindings:c.advisoryFindings,unknownFindings:c.unknownFindings,contradictionFindings:c.contradictionFindings,notApplicableChecks:c.notApplicableChecks,label:"diagnostic-pass-rate"},components:{host:i,projects:n}}}function ee(e){let t=(e.probes??[]).filter(l=>l.applicability!=="not-applicable"),i=t.filter(l=>l.status==="pass").length,n=t.filter(l=>l.status==="warn").length,o=t.filter(l=>l.status==="fail").length,s=e.diagnosis?.coverage.blockingFindings??o+e.issues.length,r=e.diagnosis?e.diagnosis.coverage.advisoryFindings:n,c=e.diagnosis?.coverage.unknownFindings??0,a=e.diagnosis?.coverage.contradictionCount??0;return {total:t.length,passed:i,warnings:n,failed:o,blockingFindings:s,advisoryFindings:r,unknownFindings:c,contradictionFindings:a,verdict:s>0?"blocked":r+c+a>0?"attention":"passed"}}function Ee(e,t=[]){let i=e.map(o=>o.diagnosis).filter(Boolean),n=e.map(ee);return {projectsScanned:e.length,affectedProjects:n.filter(o=>o.verdict!=="passed").length,projectsBlocked:n.filter(o=>o.blockingFindings>0).length,projectsNeedingAttention:n.filter(o=>o.blockingFindings===0&&o.verdict==="attention").length,blockingCauses:i.reduce((o,s)=>o+(s?.coverage.blockingFindings??0),0),advisoryFindings:i.reduce((o,s)=>o+(s?.coverage.advisoryFindings??0),0),unknownFindings:i.reduce((o,s)=>o+(s?.coverage.unknownFindings??0),0),contradictionFindings:i.reduce((o,s)=>o+(s?.coverage.contradictionCount??0),0),repairableFindings:i.reduce((o,s)=>o+(s?.coverage.repairableFindings??0),0),manualFindings:i.reduce((o,s)=>o+(s?.coverage.manualFindings??0),0),unsupportedFindings:i.reduce((o,s)=>o+(s?.coverage.unsupportedFindings??0),0),dependencyAdvisorySubjects:e.reduce((o,s)=>o+(s.dependencyAudit?.subjects.length??0),0),dependencyVulnerabilityFindings:e.reduce((o,s)=>o+(s.dependencyAudit?.findingCount??0),0),notApplicableChecks:e.reduce((o,s)=>o+(s.probes??[]).filter(r=>r.applicability==="not-applicable").length,0)+t.filter(o=>o.applicability==="not-applicable").length,systemErrors:t.filter(o=>o.status==="error").length}}function vs(e){let t=ee(e);e.probeSummary=t,e.verdict=t.verdict;}function Vi(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,r)=>{let c=`${s.path||""}|${s.name||""}`.toLowerCase(),a=`${r.path||""}|${r.name||""}`.toLowerCase();return c.localeCompare(a)});for(let s of o){if(vs(s),s.diagnosis){for(let r of (s.probes??[]).filter(c=>c.status==="pass"))n.push({id:`project:${s.name}:probe:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:"ok",scope:"project-scoped",policyRuleId:`project-probe-${r.id}`,reason:r.reason});for(let r of s.diagnosis.findings)n.push({id:`project:${s.name}:diagnosis:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:r.status==="blocking"?"error":"warn",scope:"project-scoped",policyRuleId:`project-diagnosis-${r.issueClass}`,reason:r.symptom});}else {for(let r of s.probes??[])n.push({id:`project:${s.name}:probe:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:r.status==="pass"?"ok":r.status==="warn"?"warn":"error",scope:"project-scoped",policyRuleId:`project-probe-${r.id}`,reason:r.reason});for(let[r,c]of s.issues.entries())n.push({id:`project:${s.name}:legacy:${r+1}`,label:`${s.name} \xB7 Runtime issue`,status:"error",scope:"project-scoped",policyRuleId:"project-runtime-issue",reason:c});}(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((a,l)=>a+ee(l).blockingFindings,0),r=t.reduce((a,l)=>a+ee(l).advisoryFindings,0),c=e.filter(a=>a.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:c>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-system-error-gate",reason:c>0?`${c} 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:r>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:r>0?`${r} advisory warning(s) detected.`:"No advisory warnings detected."});}return n}async function nn(e$1,t$2=true,i=Nt({}),n=false){let o=u.basename(e$1),s=await a$2(e$1);if(typeof s?.name=="string"&&s.name.trim().length>0)o=s.name;else try{for(let h of t(e$1,"workspace.json")){if(!await m.pathExists(h))continue;let w=await m.readJSON(h);o=w.workspace_name||w.name||o;break}}catch{}let[r,c]=await Promise.all([un(e$1),qr(e$1)]),a={workspacePath:e$1,workspaceName:o,python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,cliResolution:r.cliResolution,projects:[],policyProfile:i};e.debug(`Workspace scan found ${c.length} project(s)`);let l=await Vr(e$1,c),d=u.join(e$1,t$1.doctorWorkspaceCache),p=t$2&&!n?await zr(d,l):null;if(p){a.projects=p.projects;for(let h of a.projects)qi(h),$t(h,p.generatedAt);a.projectScanCached=true,e.debug(`Workspace project health cache hit: ${d}`);}else try{let h=new Date().toISOString(),w=await Ur(c,P=>Mt(P,{allowNonRapidkit:true,freshAudit:n}));for(let P of w)$t(P,h);a.projects=w,a.projectScanCached=false,await Jr(e$1,{schemaVersion:Ti,signature:l,generatedAt:h,projects:w}),e.debug(`Workspace project health cache refreshed: ${d}`);}catch(h){e.debug(`Failed to scan workspace projects: ${h}`);}a.projectScanSignature=l,a.projectScanCachePath=d;let y=Mi({python:a.python,poetry:a.poetry,pipx:a.pipx,go:a.go,rapidkitCore:a.rapidkitCore,cliResolution:a.cliResolution},a.projects);a.python=y.python,a.poetry=y.poetry,a.pipx=y.pipx,a.go=y.go,a.rapidkitCore=y.rapidkitCore,a.cliResolution=y.cliResolution,await Promise.all(a.projects.map(async h=>{h.graphDiagnosis=await tn({workspacePath:e$1,projectPath:h.path,projectName:h.name,probes:Oi(h),issues:h.issues}),_i(h);}));let b=[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore,a.cliResolution];if(a.healthScore=mn(b,a.projects),a.scoreBreakdown=Vi([{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},{id:"system-cli-resolution",label:"CLI resolution",result:a.cliResolution}],a.projects,{includeWorkspaceAggregateRules:true}),a.scopeProvenance=Wi(a.scoreBreakdown),a.evidenceFreshness=dn(a.projects,new Date().toISOString()),a.rapidkitCore.status==="ok"){let h=a.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);h&&(a.coreVersion=h[1]);}let v=await g(e$1,sn),C=v?await Gi(v,"workspace"):null;return a.driftDelta=$r(C,a),a.evidencePath=await Yr(e$1,a,p?d:null),a.receiptPath=await Ui(e$1,Ji({scopeKind:"workspace",scopeRoot:e$1,scopeName:a.workspaceName,workspacePath:e$1,projects:a.projects,healthScore:a.healthScore,freshness:a.evidenceFreshness,evidencePath:a.evidencePath,systemChecks:[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore,a.cliResolution]})),a}function Di(e){return {name:e.name,path:e.path,framework:e.framework,frameworkKey:e.frameworkKey,importStack:e.importStack,runtimeFamily:e.runtimeFamily,runtimeFamilies:e.runtimeFamilies,projectKind:e.projectKind,projectArchetype:e.projectArchetype,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,diagnosis:e.diagnosis}}function zi(e,t){let i=e?u.relative(e,t).split(u.sep).join("/"):u.resolve(t),n=u.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 ws(e,t){let i$1=e||t.projectPath,n=t$1.doctorProject,o=zi(e,t.projectPath),s=u.join(i$1,n);try{let r=[...t.project.issues,...(t.project.probes??[]).filter(d=>d.status==="fail").map(d=>d.reason)].filter(d=>typeof d=="string"&&d.trim().length>0).slice(0,12),c=ee(t.project),a=Ee([t.project],[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore,t.cliResolution]),l=f$1({schemaVersion:b$4,evidenceType:"project",contract:Ue(),policyProfile:t.policyProfile,workspacePath:e||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,cliResolution:t.cliResolution},project:t.project,driftDelta:t.driftDelta,summary:{counts:a,scopeProvenance:t.scopeProvenance,verdict:c.verdict,probeSummary:c,blockingFindings:c.blockingFindings,advisoryFindings:c.advisoryFindings},scoreBreakdown:t.scoreBreakdown??[]},{commandId:"projectDoctor",exitCode:ft(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:r,runId:e$1()});return d(l),e?await i(e,n,[{relativePath:n,payload:l},{relativePath:o,payload:l}]):await h(i$1,n,l),e&&u.resolve(e)!==u.resolve(t.projectPath)&&await h(t.projectPath,n,l),s}catch(r){throw r}}function Ji(e){let t=new Date().toISOString(),i=e.freshness??dn(e.projects,t),n=Ee(e.projects,e.systemChecks),o=e.projects.map(l=>{let d=ee(l);return {name:l.name,path:l.path,runtimeFamily:l.runtimeFamily??"unknown",framework:l.framework??"Unknown",verdict:d.verdict,blockingCauses:l.diagnosis?.coverage.blockingFindings??d.blockingFindings,advisoryFindings:l.diagnosis?.coverage.advisoryFindings??d.advisoryFindings,unknownFindings:l.diagnosis?.coverage.unknownFindings??0}}).filter(l=>l.blockingCauses>0||l.advisoryFindings>0||l.unknownFindings>0),s$1=e.projects.flatMap(l=>(l.diagnosis?.findings??[]).filter(d=>d.status==="blocking").map(d=>({id:d.id,projectName:l.name,projectPath:l.path,issueClass:d.issueClass,symptom:d.symptom,repairDisposition:d.repair.disposition,...d.repair.capabilityId?{capabilityId:d.repair.capabilityId}:{}}))),r=e.projects.reduce((l,d)=>l+(d.diagnosis?.findings??[]).filter(p=>p.status==="blocking"&&(p.repair.disposition==="automatic"||p.repair.disposition==="approval-required")).length,0),c=e.healthScore?.verdict??(n.blockingCauses>0?"blocked":n.advisoryFindings+n.unknownFindings>0?"attention":"passed"),a=i.status!=="fresh"?{action:"refresh",reason:"Doctor evidence is stale or has unknown freshness.",commands:[`npx workspai doctor ${e.scopeKind} --fresh --json=summary`]}:n.blockingCauses>0&&r>0?{action:"repair",reason:"At least one blocking cause has a typed repair capability.",commands:[`npx workspai doctor ${e.scopeKind} --plan --json=summary`]}:n.blockingCauses>0?{action:"review",reason:"Blocking causes remain, but no automatic typed repair covers every cause.",commands:[`npx workspai doctor ${e.scopeKind} --json`]}:c==="attention"?{action:"review",reason:"No blocker remains; advisory or unknown findings need policy review.",commands:[`npx workspai doctor ${e.scopeKind} --json=summary`]}:{action:"verify",reason:"Doctor is healthy; canonical Workspace Intelligence verification is next.",commands:["npx workspai workspace intelligence run --strict --json"]};return {schemaVersion:s.doctorReceipt.schemaVersion,generatedAt:t,scope:{kind:e.scopeKind,root:e.scopeRoot,name:e.scopeName,workspacePath:e.workspacePath??null,projectPath:e.projectPath??null},verdict:c,counts:n,freshness:i,affectedProjects:o,blockers:s$1,next:a,artifacts:{evidence:e.evidencePath??null,receipt:u.join(e.scopeRoot,t$1.doctorReceipt)}}}async function Ui(e,t,i=[]){a$6(t,"contracts/workspace-intelligence/doctor-receipt.v1.json",`Doctor receipt ${e}`),await h(e,t$1.doctorReceipt,t);for(let n of i)u.resolve(n)!==u.resolve(e)&&await h(n,t$1.doctorReceipt,t);return u.join(e,t$1.doctorReceipt)}async function an(e,t,i=[]){let n=u.join(e,t$1.doctorRemediationPlan);try{await h(e,t$1.doctorRemediationPlan,t);for(let o of i)u.resolve(o)!==u.resolve(e)&&await h(o,t$1.doctorRemediationPlan,t);return n}catch(o){if(o instanceof Error&&o.message.includes("violates contracts/"))throw o;return}}async function Ye(e,t,i=[]){let n=u.join(e,t$1.doctorFixResult);try{await h(e,t$1.doctorFixResult,t);for(let o of i)u.resolve(o)!==u.resolve(e)&&await h(o,t$1.doctorFixResult,t);return n}catch{return}}async function Ze(e,t,i){try{await j(e,g$1(t,i));}catch{}}async function Ri(e,t=Nt({}),i=false){let n=await mt(e),o=await un(n||e),s=await Mt(e,{allowNonRapidkit:true,freshAudit:i}),r=Mi(o,[s]);$t(s),s.graphDiagnosis=await tn({workspacePath:n||void 0,projectPath:e,projectName:s.name,probes:Oi(s),issues:s.issues}),_i(s);let c=mn([r.python,r.poetry,r.pipx,r.go,r.rapidkitCore,r.cliResolution],[s]),a={workspacePath:n||void 0,projectPath:e,projectName:u.basename(e),python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,cliResolution:r.cliResolution,project:s,healthScore:c,policyProfile:t};a.scoreBreakdown=Vi([{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},{id:"system-cli-resolution",label:"CLI resolution",result:a.cliResolution}],[a.project]),a.scopeProvenance=Wi(a.scoreBreakdown),a.evidenceFreshness=dn([a.project],new Date().toISOString());let l=await g(e,t$1.doctorProject),d=n?await g(n,zi(n,e)):null,p=l??d,y=p?await Gi(p,"project"):null;a.driftDelta=Ir(y,a),a.evidencePath=await ws(n||void 0,a);let b=n||e;return a.receiptPath=await Ui(b,Ji({scopeKind:"project",scopeRoot:b,scopeName:a.projectName,workspacePath:n||null,projectPath:e,projects:[a.project],healthScore:a.healthScore,freshness:a.evidenceFreshness,evidencePath:a.evidencePath,systemChecks:[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore,a.cliResolution]}),n&&u.resolve(n)!==u.resolve(e)?[e]:[]),a}function Se(e,t){let i=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",n=e.status==="ok"?f.green:e.status==="warn"?f.yellow:f.red;console.log(`${i} ${f.bold(t)}: ${n(e.message)}`),e.paths&&e.paths.length>0&&e.paths.forEach(o=>{let s=o.version?f.cyan(` -> ${o.version}`):"";console.log(` ${f.cyan("\u2022")} ${f.gray(o.location)}: ${f.dim(o.path)}${s}`);}),e.details&&console.log(` ${f.gray(e.details)}`);}function Et(e,t){let i=It(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).replace(/^npx\s+(?:--no-install\s+)?workspai\b/,"workspai")}`}function js(e,t){if(!t)return "$PROJECT";let i=u.relative(t,e).split(u.sep).join("/");return i&&!i.startsWith("../")&&i!==".."?i===""?"$WORKSPACE":`$WORKSPACE/${i}`:`external/${u.basename(e)}`}function Si(e,t,i={}){let n=ee(e),o=n.verdict==="blocked"?"\u274C":n.verdict==="attention"?"\u26A0\uFE0F":"\u2705",s=n.verdict==="blocked"?f.red:n.verdict==="attention"?f.yellow:f.green;if(console.log(`
|
|
23
|
-
${o} ${f.bold("Project")}: ${s(e.name)}`),e.framework){let a=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}",l=["C","C++","Python","Unknown"].includes(e.framework)?"Detected stack":"Framework";console.log(` ${a} ${l}: ${f.cyan(e.framework)}${e.kit?f.gray(` (${e.kit})`):""}`);let d=[];e.runtimeFamily&&d.push(`runtime: ${e.runtimeFamily}`),e.projectKind&&d.push(`kind: ${e.projectKind}`),e.projectArchetype&&d.push(`archetype: ${e.projectArchetype}`),e.supportTier&&d.push(`lifecycle support: ${e.supportTier}`),e.diagnosis?.capability.tier&&d.push(`diagnostic adapter: ${e.diagnosis.capability.tier}`),e.frameworkConfidence&&d.push(`confidence: ${e.frameworkConfidence}`),d.length>0&&console.log(` ${f.dim("\u21B3")} ${f.gray(d.join(" \u2022 "))}`);}if(console.log(` ${f.gray(`Boundary: ${js(e.path,i.workspacePath)}`)}`),!i.verbose){e.runtimeFamily==="python"&&!e.coreInstalled&&t?.status!=="ok"&&console.log(` ${f.dim("\u2139")} RapidKit Core: ${f.gray("Not detected locally or globally")}`),console.log(` ${f.green(`${n.passed} passed`)} ${f.gray("\xB7")} ${f.yellow(`${n.advisoryFindings} advisory`)} ${f.gray("\xB7")} ${f.red(`${n.blockingFindings} blocking`)}${e.diagnosis?.coverage.unknownFindings?` ${f.gray("\xB7")} ${e.diagnosis.coverage.unknownFindings} unknown`:""}`);let a=(e.diagnosis?.findings??[]).filter(l=>l.status==="blocking"||l.status==="unknown"||l.status==="advisory");for(let l of a.slice(0,4)){let d=l.status==="blocking"?"\u2716":l.status==="unknown"?"?":"!",p=l.status==="blocking"?f.red:f.yellow;console.log(` ${p(d)} ${l.label}: ${f.gray(l.symptom)}`);}if(a.length>4){let l=i.scope??"workspace";console.log(` ${f.dim(`\u2026 ${a.length-4} more finding(s); run workspai doctor ${l} --verbose`)}`);}return}if(e.runtimeFamily==="python"&&(e.venvActive?console.log(` \u2705 Virtual environment: ${f.green("Active")}`):console.log(` \u274C Virtual environment: ${f.red("Not found")}`),e.coreInstalled?console.log(` ${f.dim("\u2139")} RapidKit Core: ${f.gray(e.coreVersion||"In venv")} ${f.dim("(optional)")}`):t?.status==="ok"?console.log(` ${f.dim("\u2139")} RapidKit Core: ${f.gray("Using global installation")} ${f.dim("(recommended)")}`):console.log(` \u274C RapidKit Core: ${f.red("Not detected locally or globally")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${f.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${f.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${f.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${f.yellow(".env missing")}`)),e.modulesHealthy!==void 0){let a=e.projectKind==="frontend"?"Source tree":e.projectKind==="desktop"?"Application source":e.projectKind==="extension"?"Extension source":"Modules";e.modulesHealthy?console.log(` \u2705 ${a}: ${f.green("Healthy")}`):e.missingModules&&e.missingModules.length>0?console.log(` \u26A0\uFE0F ${a}: ${f.yellow(`Missing ${e.missingModules.length} init file(s)`)}`):(e.projectKind==="frontend"||e.projectKind==="desktop"||e.projectKind==="extension")&&console.log(` \u26A0\uFE0F ${a}: ${f.yellow("No application directories detected")}`);}if(e.stats){let a=[];e.stats.modules!==void 0&&a.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),a.length>0&&console.log(` \u{1F4CA} Stats: ${f.cyan(a.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${f.gray(e.lastModified)}`);let c=[];if(e.hasTests!==void 0&&c.push(e.hasTests?"\u2705 Tests":f.dim("\u2298 No tests")),e.hasDocker!==void 0&&c.push(e.hasDocker?"\u2705 Docker":f.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let a=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";c.push(e.hasCodeQuality?`\u2705 ${a}`:f.dim(`\u2298 No ${a}`));}if(c.length>0&&console.log(` ${c.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${f.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${f.bold("Issues:")}`),e.issues.forEach(a=>{console.log(` \u2022 ${f.yellow(a)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
|
|
24
|
-
${f.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(a=>{console.log(` ${f.white(Et(e,a))}`);}))),e.probes&&e.probes.length>0){console.log(` ${f.bold("Probe checks:")}`);for(let a of e.probes){let l=a.status==="pass"?"\u2705":a.status==="warn"?"\u26A0\uFE0F":"\u274C";console.log(` ${l} ${a.label}: ${f.gray(a.reason)}`),a.recommendation&&console.log(` ${f.dim("\u21B3")} ${f.gray(a.recommendation)}`);}}if(e.graphDiagnosis?.status==="available"){let a=e.graphDiagnosis.summary;console.log(` ${f.bold("Graph-aware diagnosis:")}`),console.log(` ${a.findingCount} finding(s) \u2022 ${a.affectedEntityCount} affected candidate(s) \u2022 ${a.verificationTargetCount} verification target(s) \u2022 ${a.proofPathCount} proof path(s)`),a.unknownCount>0&&console.log(` ${f.dim("\u21B3")} ${f.gray(`${a.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: ${f.yellow(e.graphDiagnosis.status)} ${f.dim("(refresh workspace model evidence)")}`);if(e.commandCapabilities){let a=e.commandCapabilities;if(console.log(` ${f.bold("Command support:")}`),console.log(` ${f.green("supported")} ${a.supportedCommands.length} \u2022 ${f.yellow("unsupported")} ${a.unsupportedCommands.length} \u2022 ${f.gray("global")} ${a.globalCommands.length}`),a.unsupportedCommands.length>0){let l=a.unsupportedCommands.slice(0,8).join(", "),d=a.unsupportedCommands.length>8?", ...":"";console.log(` ${f.dim("\u21B3")} ${f.gray(`Unsupported here: ${l}${d}`)}`);}}}async function Yi(){try{return (await execa("go",["version"],{timeout:a$9(),reject:false})).exitCode===0}catch{return false}}function _e(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 Tt(e){return _e(e,"cp\\s+\\.env\\.example\\s+\\.env")||_e(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function fn(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:"uv\\s+sync",command:"uv",args:["sync"]},{pattern:"(?:\\.\\/)?script\\/setup",command:"script/setup",args:[]},{pattern:"(?:\\.\\/)?scripts\\/setup",command:"scripts/setup",args:[]},{pattern:"(?:\\.\\/)?bin\\/setup",command:"bin/setup",args:[]},{pattern:"script[\\\\/]setup\\.cmd",command:"script/setup.cmd",args:[]},{pattern:"scripts[\\\\/]setup\\.cmd",command:"scripts/setup.cmd",args:[]},{pattern:"script[\\\\/]setup\\.ps1",command:"script/setup.ps1",args:[]},{pattern:"scripts[\\\\/]setup\\.ps1",command:"scripts/setup.ps1",args:[]},{pattern:"script\\\\setup\\.cmd",command:"script\\setup.cmd",args:[]},{pattern:"scripts\\\\setup\\.cmd",command:"scripts\\setup.cmd",args:[]},{pattern:"python3\\s+-m\\s+venv\\s+\\.venv",command:"python3",args:["-m","venv",".venv"]},{pattern:"python\\s+-m\\s+venv\\s+\\.venv",command:"python",args:["-m","venv",".venv"]},{pattern:"py\\s+-3\\s+-m\\s+venv\\s+\\.venv",command:"py",args:["-3","-m","venv",".venv"]},{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:"lein\\s+deps",command:"lein",args:["deps"]},{pattern:"sbt\\s+compile",command:"sbt",args:["compile"]},{pattern:"go\\s+mod\\s+tidy",command:"go",args:["mod","tidy"]},{pattern:"mvn\\s+-B\\s+-DskipTests\\s+-Dmaven\\.repo\\.local=\\.workspai/cache/java/m2\\s+dependency:go-offline",command:"mvn",args:["-B","-DskipTests","-Dmaven.repo.local=.workspai/cache/java/m2","dependency:go-offline"]},{pattern:"\\.\\/mvnw\\s+-B\\s+-DskipTests\\s+-Dmaven\\.repo\\.local=\\.workspai/cache/java/m2\\s+dependency:go-offline",command:"./mvnw",args:["-B","-DskipTests","-Dmaven.repo.local=.workspai/cache/java/m2","dependency:go-offline"]},{pattern:"\\.\\\\mvnw\\.cmd\\s+-B\\s+-DskipTests\\s+-Dmaven\\.repo\\.local=\\.workspai/cache/java/m2\\s+dependency:go-offline",command:".\\mvnw.cmd",args:["-B","-DskipTests","-Dmaven.repo.local=.workspai/cache/java/m2","dependency:go-offline"]},{pattern:"mvn\\s+-B\\s+-DskipTests\\s+dependency:go-offline",command:"mvn",args:["-B","-DskipTests","dependency:go-offline"]},{pattern:"\\.\\/mvnw\\s+-B\\s+-DskipTests\\s+dependency:go-offline",command:"./mvnw",args:["-B","-DskipTests","dependency:go-offline"]},{pattern:"\\.\\\\mvnw\\.cmd\\s+-B\\s+-DskipTests\\s+dependency:go-offline",command:".\\mvnw.cmd",args:["-B","-DskipTests","dependency:go-offline"]},{pattern:"gradle\\s+dependencies",command:"gradle",args:["dependencies"]},{pattern:"\\.\\/gradlew\\s+dependencies",command:"./gradlew",args:["dependencies"]},{pattern:"\\.\\\\gradlew\\.bat\\s+dependencies",command:".\\gradlew.bat",args:["dependencies"]},{pattern:"gradle\\s+--project-cache-dir\\s+\\.workspai/cache/java/gradle\\s+dependencies",command:"gradle",args:["--project-cache-dir",".workspai/cache/java/gradle","dependencies"]},{pattern:"\\.\\/gradlew\\s+--project-cache-dir\\s+\\.workspai/cache/java/gradle\\s+dependencies",command:"./gradlew",args:["--project-cache-dir",".workspai/cache/java/gradle","dependencies"]},{pattern:"\\.\\\\gradlew\\.bat\\s+--project-cache-dir\\s+\\.workspai/cache/java/gradle\\s+dependencies",command:".\\gradlew.bat",args:["--project-cache-dir",".workspai/cache/java/gradle","dependencies"]}];for(let i of t){let n=_e(e,i.pattern);if(n)return {projectPath:n.projectPath,command:i.command,args:i.args}}return null}function xs(e){let t=u.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:cmd|bat)$/i,"");return /(?:^|\/)(?:script\/setup|scripts\/setup|bin\/setup)(?:\.cmd|\.ps1)?$/iu.test(e.replaceAll("\\","/"))?{ecosystem:"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt",e.replaceAll("\\","/")]}:["npm","pnpm","yarn","bun"].includes(t)?{ecosystem:t,files:["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]}:["poetry","uv","pip","pip3","python","python3","py"].includes(t)?{ecosystem:t==="uv"?"uv":t==="poetry"?"poetry":"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt"]}:t==="go"?{ecosystem:"go",files:["go.mod","go.sum"]}:t==="cargo"?{ecosystem:"cargo",files:["Cargo.toml","Cargo.lock"]}:t==="composer"?{ecosystem:"composer",files:["composer.json","composer.lock"]}:t==="bundle"?{ecosystem:"bundler",files:["Gemfile","Gemfile.lock"]}:t==="mix"?{ecosystem:"mix",files:["mix.exs","mix.lock"]}:t==="dotnet"?{ecosystem:"dotnet",files:["Directory.Packages.props","packages.lock.json"]}:t==="clojure"||t==="lein"?{ecosystem:"clojure",files:["deps.edn","project.clj"]}:t==="sbt"?{ecosystem:"sbt",files:["build.sbt"]}:t==="mvn"||t==="mvnw"?{ecosystem:"maven",files:["pom.xml",".workspai/cache/java/m2"]}:t==="gradle"||t==="gradlew"?{ecosystem:"gradle",files:["build.gradle","build.gradle.kts","gradle.lockfile",".workspai/cache/java/gradle"]}:{ecosystem:t,files:[]}}function Cs(e){let t=(e.issues??[]).find(i=>/(?:dependencies? (?:are )?(?:not (?:installed|downloaded|resolved)|missing)|dependency cache not initialized|virtual environment (?:not created|exists but)|restore\/build artifacts not found|build artifacts missing|dependencies are not warmed)/i.test(i));for(let i of e.fixCommands??[]){let n=fn(i);if(!n||e.depsInstalled&&!t)continue;let o=xs(n.command),s=c$4({issueId:"runtime-dependency-materialization",title:`Install ${o.ecosystem} dependencies`,projectPath:n.projectPath,ecosystem:o.ecosystem,executable:n.command,args:n.args,files:o.files,command:i,reason:"The dependency definition exists, but its local runtime dependency tree is missing or incomplete.",limitations:["This transaction may update a lockfile when the package manager determines it is stale.","Source mutation is not required when the existing manifest and lockfile are already consistent."]}),r=e.probes?.find(c=>c.id==="runtime-dependency-materialization");if(r){Object.assign(r,ln({...r,repairCapability:s},new Date().toISOString()));continue}_(e,{id:"runtime-dependency-materialization",label:"Runtime dependency materialization",status:"fail",severity:"error",scope:"project-scoped",reason:t??"The dependency definition exists, but its local runtime dependency tree is missing or incomplete.",recommendation:"Run the typed dependency materialization transaction, then recheck the exact runtime postcondition.",repairCapability:s,issueClass:"dependency",operationalImpact:"release-risk"});}if(e.depsInstalled&&!(e.probes??[]).some(i=>i.id==="runtime-dependency-materialization")){let i=(e.probes??[]).some(c=>c.id==="composite-project-boundary"),n=e.runtimeFamily==="c"||e.runtimeFamily==="cpp",o=e.runtimeFamily==="deno",s=i||n||o,r=i?"Dependency materialization is evaluated at each registered runtime project boundary, not at this aggregate polyglot container.":n?"Native dependency materialization is build-system and organization specific; Doctor verified the build contract without claiming a universal local dependency tree.":o?"The detected runtime resolves dependencies without a project-local installation tree.":Ps(e.runtimeFamily);_(e,{id:"runtime-dependency-materialization",label:"Runtime dependency materialization",status:"pass",severity:"info",scope:"project-scoped",...s?{applicability:"not-applicable"}:{},reason:r,issueClass:"dependency",operationalImpact:"none"});}}function Ps(e){switch(e){case "rust":return "Cargo dependency resolution evidence is present. Doctor does not infer the state of a shared crate cache from Cargo.lock alone.";case "go":return "Go module resolution evidence is present. Doctor does not infer the state of the shared module cache from go.sum alone.";case "ruby":return "Bundler dependency evidence is present. Doctor does not infer a global gem installation from Gemfile.lock alone.";case "elixir":return "Mix dependency evidence is present. Doctor distinguishes authored lock state from the environment-specific dependency cache.";case "clojure":return "Clojure dependency evidence is present. Doctor does not infer the environment-specific artifact cache from the project manifest alone.";default:return "The runtime dependency tree is materialized for the detected project ecosystem."}}function Ds(){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 Ot(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 Xe(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);return a(n)}catch{return null}}function Rs(e){let t=e.operation?Ss(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 Ss(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(`
|
|
25
|
-
`)}`;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 Es(e,t){let i=u.resolve(e),n=u.isAbsolute(t)?u.resolve(t):u.resolve(i,t),o=u.relative(i,n);if(o.startsWith("..")||u.isAbsolute(o))throw new Error(`Repair target escapes project boundary: ${t}`);return n}async function Ae(e,t){if(!(await m.stat(e).catch(()=>{}))?.isDirectory())throw new Error(`Repair project boundary not found: ${e}`);let n=Es(e,t),o=await m.realpath(e).catch(()=>u.resolve(e)),s=n;for(;!await m.pathExists(s);){let a=u.dirname(s);if(a===s)throw new Error(`Repair target has no resolvable project ancestor: ${t}`);s=a;}let r=await m.realpath(s).catch(()=>u.resolve(s)),c=u.relative(o,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Repair target escapes project boundary through a symbolic link: ${t}`);return n}async function As(e){if(!/^[A-Za-z0-9:_-]+$/.test(e.scriptName))throw new Error(`Unsafe package script name: ${e.scriptName}`);let t=await Ae(e.projectPath,e.packageJsonPath??"package.json");if(!await m.pathExists(t))throw new Error(`package.json not found at ${t}`);let i=await m.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 m.writeJSON(t,i,{spaces:2}));}async function Fs(e){let t=await Ae(e.projectPath,e.operation.path);await m.pathExists(t)||(await m.ensureDir(u.dirname(t)),await m.writeFile(t,e.operation.content,"utf8"));}async function $s(e){let t=await Ae(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await _t(t),n=i.split(/\r?\n/),o=e.operation.lines.filter(r=>!n.includes(r));if(o.length===0)return;let s=i.length===0||i.endsWith(`
|
|
26
|
-
`)||!e.operation.ensureNewline?"":`
|
|
27
|
-
`;await m.appendFile(t,`${s}${o.join(`
|
|
28
|
-
`)}
|
|
29
|
-
`,"utf8");}async function Is(e){let t=await Ae(e.projectPath,e.operation.sourcePath),i=await Ae(e.projectPath,e.operation.path);if(!await m.pathExists(t))throw new Error(`Repair source file not found at ${t}`);await m.pathExists(i)||(await m.ensureDir(u.dirname(i)),await m.copy(t,i,{overwrite:e.operation.overwrite,errorOnExist:false}));}function Ns(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}async function Ms(e){let t=await Ae(e.projectPath,e.operation.path);if(!await m.pathExists(t))throw new Error(`JSON repair target not found at ${t}`);let i=await m.readJSON(t);for(let n of e.operation.edits){let o=n.pointer.split("/").slice(1).map(Ns);if(o.length===0||o.some(r=>r.length===0||r==="__proto__"||r==="prototype"||r==="constructor"))throw new Error(`Unsupported JSON pointer: ${n.pointer}`);let s=i;for(let r of o.slice(0,-1)){let c=s[r];(!c||typeof c!="object"||Array.isArray(c))&&(s[r]={}),s=s[r];}s[o[o.length-1]]=n.value;}await m.writeJSON(t,i,{spaces:2});}async function Ts(e){let t=await Ae(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await _t(t),n=new Set(i.split(/\r?\n/).map(r=>r.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)=/)?.[1]).filter(r=>!!r)),o=[];for(let r of e.operation.keys)n.has(r.name)||(r.comment&&o.push(`# ${r.comment}`),o.push(`${r.name}=${r.value}`));if(o.length===0)return;let s=i.length===0||i.endsWith(`
|
|
30
|
-
`)?"":`
|
|
31
|
-
`;await m.appendFile(t,`${s}${o.join(`
|
|
32
|
-
`)}
|
|
33
|
-
`,"utf8");}async function Os(e){let t=await Ae(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await _t(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(`
|
|
34
|
-
`)?"":`
|
|
35
|
-
`;await m.appendFile(t,`${s}${o.join(`
|
|
36
|
-
`)}
|
|
37
|
-
`,"utf8");}async function _t(e){try{return await m.pathExists(e)?await m.readFile(e,"utf8"):""}catch{return ""}}function _s(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(Tt(t))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"};if(Ot(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=Xe(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"}:_e(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"}:_e(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"}:fn(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:false,reason:"Untyped command retained as review guidance only; Doctor never executes generic shell remediation."}}function It(e,t){return e.repairCapabilities?.find(i=>i.command===t)}function on(e,t){if(t)return e.probes?.find(i=>i.repairCapability?.id===t.id)}function Bs(e){let{step:t,capability:i,operation:n}=e;if(n?.type==="file-create")return {title:i?.title??"Create file",summary:`Create ${u.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 ${u.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 ${u.basename(n.sourcePath)} to ${u.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 ${u.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 ${u.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 Gs(e,t){let i=t.endsWith(`
|
|
38
|
-
`)?t.slice(0,-1).split(`
|
|
39
|
-
`):t.split(`
|
|
40
|
-
`);return ["--- /dev/null",`+++ ${e}`,"@@",...i.map(n=>`+${n}`)]}function Ks(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:Gs(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 Ws(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 Hs(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 Ls(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 Ei(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 qs(e){return [...e].sort((i,n)=>{let o=Ei(i.phase)-Ei(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 Vs(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 zs(e,t,i){if(i.kind==="dependency-sync"||i.kind==="go-mod-tidy")return `${e.path}:dependency-baseline`;let n=Xe(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(r=>r.pointer).join(",")}`;if(n?.type==="env-key-add")return `${e.path}:env-key-add:${n.path}:${n.keys.map(r=>r.name).join(",")}`;if(n?.type==="makefile-target")return `${e.path}:makefile-target:${n.path}:${n.target}`;let o=Tt(t);if(o)return `${e.path}:file-copy:${u.join(o.projectPath,".env")}`;let s=Ot(t);return s?`${e.path}:package-json-script:${u.join(s.projectPath,"package.json")}:${s.scriptName}`:null}function Js(e,t){return It(e,t)?4:Xe(t)?3:Ot(t)?2:Tt(t)?1:0}async function cn(e,t="local"){let n=e.filter(h=>(h.fixCommands?.length??0)>0||(h.repairCapabilities??[]).some(w=>w.status==="manual")).flatMap(h=>{let w=(h.fixCommands??[]).map(R=>{let x=It(h,R);return {project:h,step:_s(h,R),command:R,capability:x,probe:on(h,x)}}),P=(h.repairCapabilities??[]).filter(R=>R.status==="manual").map(R=>({project:h,step:{projectName:h.name,projectPath:h.path,originalCommand:R.command??"",kind:"shell",risk:R.risk,executable:false,reason:R.reason},command:R.command??"",capability:R,probe:on(h,R)}));return [...w,...P]}),o=[],s$1=new Map;for(let h of n){let w=zs(h.project,h.command,h.step);if(!w){o.push(h);continue}let P=Js(h.project,h.command),R=s$1.get(w);if(!R){s$1.set(w,{index:o.length,priority:P}),o.push(h);continue}P>R.priority&&(o[R.index]=h,s$1.set(w,{index:R.index,priority:P}));}let r=o,c=null,a=new Map,l=[],d=0,p=0,y=0,b=0;for(let h of r){let{project:w,step:P,command:R}=h,x=P.executable,g,D=h.capability??It(w,R);if(x&&D?.invocation){let W=D.invocation.cwd,K=D.invocation.executable,T=`${W}\0${K}`,O=a.get(T);O===void 0&&(O=await a$3({executable:K,cwd:W}),a.set(T,O)),O||(x=false,g=`Required executable is unavailable: ${K}`);}else P.kind==="go-mod-tidy"&&(c===null&&(c=await Yi()),c||(x=false,g="Go toolchain not available"));let k=h.probe??on(w,D),A=k?w.diagnosis?.findings.find(W=>W.probeId===k.id):void 0,j=D?.operation??Xe(R)??void 0;x&&!j&&!D?.invocation?.executable&&(x=false,g="Executable remediation requires a typed operation or structured invocation."),x&&(d+=1,P.risk==="safe"&&(p+=1),P.risk==="guarded"&&(y+=1),P.risk==="invasive"&&(b+=1));let G=D?.files??(j&&"path"in j?[j.path]:[]),F=k?.repairIntent,V=Hs({step:P,capability:D,executableInCurrentEnvironment:x,blockedReason:g,policyProfile:t}),se=Ls({step:P,issueClass:k?.issueClass,repairIntent:F,operation:j});l.push({...P,id:Rs({projectName:w.name,kind:P.kind,command:R,operation:j,capabilityId:D?.id}),phase:se,order:0,dependsOn:[],...A?{diagnosisFindingId:A.id,causalKey:A.causalKey}:{},issueId:D?.issueId,findingStatus:k?.status==="fail"?"blocking":k?.status==="warn"?"advisory":k?.status==="pass"?"informational":"unknown",issueClass:k?.issueClass,operationalImpact:k?.operationalImpact,repairIntent:F,files:G,...j?{operation:j}:{},...D?.invocation?{invocation:{cwd:D.invocation.cwd,executable:D.invocation.executable,args:[...D.invocation.args]}}:{},...D?.strategy?{strategy:D.strategy.map(W=>structuredClone(W))}:{},...D?.transaction?{transaction:structuredClone(D.transaction)}:{},preview:Bs({step:P,capability:D,operation:j}),diffPreview:Ks({step:P,operation:j}),verifyCommand:D?.verifyCommand,refreshCommands:D?.refreshCommands??["npx workspai doctor project --json"],rollback:Ws(P),studioStatus:V,executableInCurrentEnvironment:x,blockedReason:g});}let v=Vs(qs(l)),C=new Set(v.map(h=>h.projectPath)).size;return {schemaVersion:s.doctorRemediationPlan.schemaVersion,generatedAt:new Date().toISOString(),policyProfile:t,fixableProjects:C,totalSteps:v.length,executableSteps:d,risk:{safe:p,guarded:y,invasive:b},steps:v}}function Ai(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 Us(e,t){let i=e.get(t);if(i)return i;let n=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=u.basename(t).replace(/[^a-zA-Z0-9._-]/g,"_"),s=u.join(t,".workspai","reports","fix-snapshots",`${o}-${n}`);await m.ensureDir(s);let r=[".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"],c=new Map;for(let l of r){let d=u.join(t,l);if(!await m.pathExists(d))continue;let p=u.join(s,l);await m.ensureDir(u.dirname(p)),await m.copy(d,p,{overwrite:true}),c.set(d,p);}let a={snapshotRoot:s,files:c,missingFiles:new Set};return e.set(t,a),a}async function ze(e,t){if(e.files.has(t)||e.missingFiles.has(t))return;if(!await m.pathExists(t)){e.missingFiles.add(t);return}let i=u.basename(t),n=u.join(e.snapshotRoot,"ad-hoc",`${Date.now()}-${Math.random().toString(36).slice(2,8)}-${i}`);await m.ensureDir(u.dirname(n)),await m.copy(t,n,{overwrite:true}),e.files.set(t,n);}async function Ys(e){for(let[t,i]of e.files.entries())await m.pathExists(i)&&(await m.ensureDir(u.dirname(t)),await m.copy(i,t,{overwrite:true}));for(let t of e.missingFiles)await m.pathExists(t)&&await m.remove(t);}async function Zs(e){let i=(await Mt(e,{allowNonRapidkit:true})).diagnosis?.findings.filter(n=>n.status==="blocking")??[];return {issues:i.length,healthy:i.length===0}}async function rn(e){let t=[];for(let i of e){let o=(await Mt(i.path,{allowNonRapidkit:true})).diagnosis?.findings.filter(s=>s.status==="blocking");for(let s of o??[])s.symptom.trim()&&t.push(`${i.name}: ${s.symptom.trim()}`);}return t.slice(0,24)}function Fi(e){let t=[];for(let i of e){let n=i.diagnosis?.findings.filter(o=>o.status==="blocking");if(n){for(let o of n)o.symptom.trim()&&t.push(`${i.name}: ${o.symptom.trim()}`);continue}for(let o of i.issues)typeof o=="string"&&o.trim()&&t.push(`${i.name}: ${o.trim()}`);}return t.slice(0,24)}async function Je(e,t=false,i={}){let n=await cn(e,i.policyProfile);i.artifactRoot&&(i.planOnly||t)&&await an(i.artifactRoot,n,i.artifactMirrorRoots);let o=e.filter(g=>g.fixCommands&&g.fixCommands.length>0),s=[],r=i.json===true,c=(...g)=>{r||console.log(...g);},a=null,l=n.steps.some(g=>g.kind==="go-mod-tidy"&&!g.executableInCurrentEnvironment),d=new Map;if(o.length===0){if(r||console.log(f.green(`
|
|
41
|
-
\u2705 No fixes needed - all projects are healthy!`)),t){let g=Me({appliedFixes:[],remainingBlockers:[],verifyRecommended:Ce});return i.artifactRoot&&(await Ye(i.artifactRoot,g,i.artifactMirrorRoots),await Ze(i.artifactRoot,g,i.historyScope??"project")),g}return}if(!r){console.log(f.bold.cyan(`
|
|
42
|
-
\u{1F527} Available Fixes:
|
|
43
|
-
`));for(let g of o){let D=g.fixCommands??[];console.log(f.bold(`Project: ${f.yellow(g.name)}`)),D.forEach((k,A)=>{console.log(` ${A+1}. ${f.cyan(Et(g,k))}`);}),console.log();}}if(i.planOnly){if(i.json){console.log(JSON.stringify(n,null,2));return}console.log(f.bold(`
|
|
44
|
-
\u{1F9ED} Remediation Plan
|
|
45
|
-
`)),console.log(f.gray(`Executable steps: ${n.executableSteps}/${n.totalSteps} | risk: safe=${n.risk.safe}, guarded=${n.risk.guarded}, invasive=${n.risk.invasive}`));for(let g of n.steps){let D=o.find(A=>A.path===g.projectPath),k=g.executableInCurrentEnvironment?f.green("ready"):f.yellow(`blocked${g.blockedReason?` (${g.blockedReason})`:""}`);console.log(` - ${f.cyan(g.projectName)} [${g.risk}] ${D?Et(D,g.originalCommand):g.preview.title} ${f.gray(`=> ${k}`)}`);}console.log(f.gray(`
|
|
46
|
-
Use --apply to execute this plan non-interactively, or --fix for interactive confirmation.`));return}let p=n.executableSteps,y=n.risk.safe,b$1=n.risk.guarded,v=n.risk.invasive;if(p===0){if(r||(console.log(f.gray("\u{1F4A1} No automatic fixes can be applied right now.")),l&&console.log(f.gray(" Install Go to enable go mod tidy fixes, then rerun `workspai doctor workspace --fix`."))),t){let g=Me({appliedFixes:[],remainingBlockers:await rn(e),verifyRecommended:Ce});return i.artifactRoot&&(await Ye(i.artifactRoot,g,i.artifactMirrorRoots),await Ze(i.artifactRoot,g,i.historyScope??"project")),g}return}if(!t){r||console.log(f.gray('\u{1F4A1} Run "npx workspai doctor workspace --fix" to apply fixes automatically'));return}if(r||console.log(f.gray(`Risk policy: safe=${y}, guarded=${b$1}, invasive=${v}. Guarded/invasive fixes use snapshot + rollback.`)),!i.skipConfirmation){let{confirm:g}=await b([{type:"confirm",name:"confirm",message:`Apply ${o.reduce((D,k)=>D+(k.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!g){r||console.log(f.yellow(`
|
|
47
|
-
\u26A0\uFE0F Fixes cancelled by user`));let D=Me({appliedFixes:[],remainingBlockers:await rn(e),verifyRecommended:Ce});return i.artifactRoot&&(await Ye(i.artifactRoot,D,i.artifactMirrorRoots),await Ze(i.artifactRoot,D,i.historyScope??"project")),D}}r||console.log(f.bold.cyan(`
|
|
48
|
-
\u{1F680} Applying fixes...
|
|
49
|
-
`));let C=new Set,h=new Map(o.map(g=>[g.path,g])),w=new Set,P=Ds(),R=process.env.RAPIDKIT_DOCTOR_FIX_ALLOW_GUARDED_COMMANDS==="1"||process.env.RAPIDKIT_DOCTOR_FIX_ALLOW_DEPENDENCY_SYNC==="1",x="";for(let g of n.steps){let D=h.get(g.projectPath);if(!D)continue;let k=g.originalCommand;r||x!==g.projectName&&(x=g.projectName,console.log(f.bold(`Fixing ${f.cyan(g.projectName)}...`)));let A=`${g.projectPath}::${k}`;if(!C.has(A)){C.add(A);try{if(c(f.gray(` ${Et(D,k)}`)),g.kind==="manual-url"){c(f.yellow(` \u2139 Manual action required: open ${k}`)),c(f.green(` \u2705 Recorded as guidance
|
|
50
|
-
`));continue}if(!g.executable||!g.executableInCurrentEnvironment){let oe=g.blockedReason?`: ${g.blockedReason}`:"";c(f.yellow(` \u26A0 Step is non-executable by policy${oe}`)),c(f.green(` \u2705 Recorded as guidance
|
|
51
|
-
`));continue}let j=Xe(k),F=g.risk!=="safe"||j?.type==="file-create"||j?.type==="file-append"||j?.type==="file-copy"||j?.type==="json-edit"||j?.type==="env-key-add"||j?.type==="makefile-target"?await Us(d,g.projectPath):null;F&&j?.type==="file-create"&&await ze(F,j.path),F&&j?.type==="file-append"&&await ze(F,j.path),F&&j?.type==="file-copy"&&await ze(F,j.path),F&&j?.type==="json-edit"&&await ze(F,j.path),F&&j?.type==="env-key-add"&&await ze(F,j.path),F&&j?.type==="makefile-target"&&await ze(F,j.path);let V=Tt(k);if(V){let oe=u.join(V.projectPath,".env.example"),re=u.join(V.projectPath,".env");if(!await m.pathExists(oe))throw new Error(`.env.example not found at ${oe}`);if(await m.pathExists(re)){c(f.green(` \u2705 .env already exists
|
|
52
|
-
`));continue}await m.copy(oe,re,{overwrite:false,errorOnExist:false}),w.add(g.projectPath),s.push({path:re,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
53
|
-
`));continue}if(j?.type==="file-copy"){await Is({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),s.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
54
|
-
`));continue}let se=Ot(k);if(se){await As(se),w.add(g.projectPath),s.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
55
|
-
`));continue}if(j?.type==="file-create"){await Fs({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),s.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
56
|
-
`));continue}if(j?.type==="file-append"){await $s({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),s.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
57
|
-
`));continue}if(j?.type==="json-edit"){await Ms({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),s.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
58
|
-
`));continue}if(j?.type==="env-key-add"){await Ts({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),s.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
59
|
-
`));continue}if(j?.type==="makefile-target"){await Os({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),s.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
60
|
-
`));continue}let W=_e(k,"(?:npx\\s+workspai|rapidkit)\\s+init");if(W){if(!R){c(f.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:g.projectPath,action:g.kind,outcome:"guidance",projectName:g.projectName,command:k,detail:"Guarded setup command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}await execa("rapidkit",["init"],{cwd:W.projectPath,shell:c$1(),stdio:r?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),w.add(g.projectPath),s.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
61
|
-
`));continue}let K=_e(k,"go\\s+mod\\s+tidy");if(K){if(a===null&&(a=await Yi()),!a){c(f.yellow(" \u26A0 Go toolchain is not installed \u2014 skipping go mod tidy; install Go to apply this fix.")),c(f.green(` \u2705 Recorded as guidance
|
|
62
|
-
`));continue}await execa("go",["mod","tidy"],{cwd:K.projectPath,shell:c$1(),stdio:r?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),w.add(g.projectPath),s.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
63
|
-
`));continue}let T=fn(k);if(T){if(!R&&new Set(["npm","pnpm","yarn","bun","poetry","pip","pip3","pipenv"]).has(T.command)){c(f.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:g.projectPath,action:g.kind,outcome:"guidance",projectName:g.projectName,command:k,detail:"Guarded dependency command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}let re=2,Be,z=T.command==="poetry"&&T.args[0]==="install"?{...process.env,POETRY_CACHE_DIR:u.join(T.projectPath,".workspai","cache","python","poetry")}:process.env;for(let Qe=1;Qe<=re;Qe+=1)try{await execa(T.command,T.args,{cwd:T.projectPath,env:z,shell:c$1(),stdio:r?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),Be=null;break}catch(gt){if(Be=gt,Qe<re&&Ai(gt)){c(f.yellow(` \u26A0 Retrying dependency sync (${Qe}/${re-1})...`));continue}throw gt}if(Be)throw Be;w.add(g.projectPath),s.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
|
|
64
|
-
`));continue}let O=g.kind==="shell"?2:1,me;for(let oe=1;oe<=O;oe+=1)try{await execa(k,{shell:true,stdio:r?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),me=null;break}catch(re){if(me=re,oe<O&&Ai(re)){c(f.yellow(` \u26A0 Retrying command (${oe}/${O-1})...`));continue}throw re}if(me)throw me;r||console.log(f.green(` \u2705 Success
|
|
65
|
-
`)),w.add(g.projectPath),s.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k});}catch(j){let G=Xe(k);if(g.risk!=="safe"||G?.type==="file-create"||G?.type==="file-append"||G?.type==="file-copy"||G?.type==="json-edit"||G?.type==="env-key-add"||G?.type==="makefile-target"){let F=d.get(g.projectPath);if(F)try{await Ys(F),r||console.log(f.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(V){r||console.log(f.red(` \u274C Rollback failed: ${V instanceof Error?V.message:String(V)}`));}}r||console.log(f.red(` \u274C Failed: ${j instanceof Error?j.message:String(j)}
|
|
66
|
-
`)),s.push({path:g.projectPath,action:g.kind,outcome:"failed",projectName:g.projectName,command:k,detail:j instanceof Error?j.message:String(j)});}}}for(let g of o)if(w.has(g.path))try{let D=await Zs(g.path);r||console.log(D.healthy?f.green(` \u2705 Post-fix verification passed for ${g.name}`):f.yellow(` \u26A0 Post-fix verification: ${D.issues} issue(s) remain for ${g.name}`));}catch(D){r||console.log(f.yellow(` \u26A0 Post-fix verification skipped: ${D instanceof Error?D.message:String(D)}`));}if(r||console.log(f.bold.green(`
|
|
67
|
-
\u2705 Fix process completed!`)),t){let g=Me({appliedFixes:s,remainingBlockers:await rn(e),verifyRecommended:Ce});return i.artifactRoot&&(await Ye(i.artifactRoot,g,i.artifactMirrorRoots),await Ze(i.artifactRoot,g,i.historyScope??"project")),g}}function ft(e,t){let i=Nt(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 $i(e,t,i){let n=ft(e,t);return i?.appliedFixes.some(s=>s.outcome==="failed")??false?Math.max(n,1):n}async function Xc(e$1={}){let t=(l,d,p)=>{c({blockId:l,status:d,message:p,component:"doctor"});},i=(l,d)=>{t("doctor.observe","succeeded",`${l} evidence collected`),t("doctor.diagnose","running",`Diagnosing ${l.toLowerCase()} health`);let p=Number(d?.errors??0)>0||Number(d?.warnings??0)>0;t("doctor.diagnose",p?"warned":"succeeded",p?`${l} diagnosis completed with findings`:`${l} diagnosis completed`);};t("doctor.observe","running","Collecting health evidence");let n=Nt({profile:e$1.profile,strict:e$1.strict,ci:e$1.ci}),o=!!(e$1.fix||e$1.plan||e$1.apply),s=typeof e$1.workspace=="string"&&e$1.workspace.trim().length>0?u.resolve(e$1.workspace):null,r=!s&&!e$1.workspace&&!e$1.project&&o?await mt(process.cwd()):null,c$1=!!e$1.workspace||!!r,a=!!e$1.project&&!c$1;if(e$1.json||console.log(f.bold.cyan(`
|
|
68
|
-
\u{1FA7A} Workspai Health Check
|
|
69
|
-
`)),c$1){let l=s??r??await mt(process.cwd());l||(e.error("No Workspai workspace found in current directory or parents"),e.info('Run this command from within a workspace, or use "workspai doctor" for system check'),process.exit(1)),e$1.json||(r&&console.log(f.gray("\u2139\uFE0F Detected workspace context; enabling workspace checks for --fix")),console.log(f.bold(`Workspace: ${f.cyan(u.basename(l))}`)),console.log(f.gray("Boundary: $WORKSPACE")));let d=!(e$1.plan||e$1.fix||e$1.apply),p=await nn(l,d,n,e$1.fresh===true);if(i("Workspace",p.healthScore),e$1.json||(p.projectScanCached&&console.log(f.gray(`\u2139\uFE0F Reused cached project scan${p.projectScanCachePath?` (${u.basename(p.projectScanCachePath)})`:""}`)),p.evidencePath&&console.log(f.gray(`\u2139\uFE0F Evidence saved: ${u.relative(l,p.evidencePath).split(u.sep).join("/")}`))),e$1.json){let k;(e$1.plan||e$1.fix||e$1.apply)&&t("doctor.plan","running","Building governed remediation plan");let A=e$1.plan||e$1.fix||e$1.apply?await cn(p.projects,n.name):void 0,j=A?await an(l,A):void 0;(e$1.plan||e$1.fix||e$1.apply)&&t("doctor.plan","succeeded","Governed remediation plan ready");let G;(e$1.fix||e$1.apply)&&!e$1.plan&&(k=await Je(p.projects,true,{skipConfirmation:e$1.apply===true||e$1.fix===true,json:true,policyProfile:n.name})??Me({appliedFixes:[],remainingBlockers:[],verifyRecommended:Ce}),t("doctor.verify","running","Verifying workspace after remediation"),p=await nn(l,false,n,true),t("doctor.verify","succeeded","Post-remediation workspace verification completed"),k={...k,remainingBlockers:Fi(p.projects)},G=await Ye(l,k),await Ze(l,k,"workspace"));let F=p.projects.map(ee),V=F.reduce((T,O)=>T+O.blockingFindings,0),se=F.reduce((T,O)=>T+O.advisoryFindings,0),W=Ee(p.projects,[p.python,p.poetry,p.pipx,p.go,p.rapidkitCore,p.cliResolution]),K={contract:Ue(),policyProfile:n,workspace:{name:p.workspaceName,path:l},cache:{projectScan:p.projectScanCached??false,projectScanPath:p.projectScanCachePath,evidencePath:p.evidencePath,receiptPath:p.receiptPath},healthScore:p.healthScore,evidenceFreshness:p.evidenceFreshness,system:{python:p.python,poetry:p.poetry,pipx:p.pipx,go:p.go,rapidkitCore:p.rapidkitCore,cliResolution:p.cliResolution,versions:{core:p.coreVersion,npm:p.npmVersion}},projects:p.projects.map(T=>Di(T)),summary:{counts:W,totalProjects:p.projects.length,totalIssues:p.projects.reduce((T,O)=>T+O.issues.length,0),verdict:p.healthScore?.verdict??"passed",blockingFindings:V,advisoryFindings:se,projectAdvisoryWarningProjects:F.filter(T=>T.advisoryFindings>0).length,projectAdvisoryWarnings:se,hasSystemErrors:[p.python,p.rapidkitCore].some(T=>T.status==="error"),scopeProvenance:p.scopeProvenance},driftDelta:p.driftDelta,scoreBreakdown:p.scoreBreakdown??[],...A?{remediationPlan:A,remediationPlanPath:j}:{},...k?{appliedFixes:k.appliedFixes,remainingBlockers:k.remainingBlockers,verifyRecommended:k.verifyRecommended,fixResult:k,fixResultPath:G}:{}};if(!e$1.quiet){let T=e$1.json==="summary"?{schemaVersion:St,generatedAt:p.evidenceFreshness?.generatedAt??new Date().toISOString(),scope:"workspace",workspace:K.workspace,verdict:p.healthScore?.verdict??"passed",counts:W,freshness:p.evidenceFreshness,affectedProjects:p.projects.map(O=>{let me=ee(O);return {name:O.name,path:O.path,runtimeFamily:O.runtimeFamily??"unknown",projectArchetype:O.projectArchetype??"unknown",verdict:me.verdict,blockingCauses:O.diagnosis?.coverage.blockingFindings??me.blockingFindings,advisoryFindings:O.diagnosis?.coverage.advisoryFindings??me.advisoryFindings,unknownFindings:O.diagnosis?.coverage.unknownFindings??0}}).filter(O=>O.blockingCauses>0||O.advisoryFindings>0||O.unknownFindings>0),artifacts:{evidence:p.evidencePath,receipt:p.receiptPath,...j?{remediationPlan:j}:{},...G?{fixResult:G}:{}}}:K;console.log(JSON.stringify(T,null,2));}return $i(p.healthScore,{profile:n.name},k)}let y=Ee(p.projects,[p.python,p.poetry,p.pipx,p.go,p.rapidkitCore,p.cliResolution]),b=p.healthScore?.verdict??"passed",v=b==="blocked"?"\u274C":b==="attention"?"\u26A0\uFE0F":"\u2705",C=b==="blocked"?f.red:b==="attention"?f.yellow:f.green;if(console.log(`
|
|
70
|
-
${v} ${C.bold(b.toUpperCase())} ${f.gray("\xB7")} ${p.projects.length} project(s) ${f.gray("\xB7")} ${y.projectsBlocked} blocked ${f.gray("\xB7")} ${y.projectsNeedingAttention} need attention`),console.log(` ${y.blockingCauses+y.systemErrors} blocking ${f.gray("\xB7")} ${y.advisoryFindings} advisory ${f.gray("\xB7")} ${y.unknownFindings} unknown ${f.gray("\xB7")} ${y.notApplicableChecks} not applicable`),p.healthScore){let k=p.healthScore;console.log(f.bold(`
|
|
71
|
-
\u{1F4CA} Diagnostic accounting:`)),console.log(` ${f.green(`${k.passed} passed`)} ${f.gray("|")} ${f.yellow(`${k.warnings} warnings`)} ${f.gray("|")} ${f.red(`${k.errors} errors`)} ${f.gray("|")} ${k.presentation.notApplicableChecks} N/A`),console.log(f.dim(` Diagnostic pass rate: ${k.presentation.diagnosticPassRatePercent??"n/a"}% (accounting only; verdict and blocking findings govern readiness)`));}let h=[[p.python,"Python"],[p.poetry,"Poetry"],[p.pipx,"pipx"],[p.go,"Go"],[p.rapidkitCore,"RapidKit Core"],[p.cliResolution,"CLI resolution"]],w=e$1.verbose?h:h.filter(([k])=>k.applicability!=="not-applicable");console.log(f.bold(`
|
|
72
|
-
|
|
73
|
-
System Tools:
|
|
74
|
-
`)),w.length===0?console.log(f.gray("No host prerequisites apply to the detected primary runtimes.")):w.forEach(([k,A])=>Se(k,A)),wr({coreVersion:p.coreVersion,npmVersion:p.npmVersion})&&(console.log(f.yellow(`
|
|
75
|
-
\u26A0\uFE0F Version mismatch: Core ${p.coreVersion} / CLI ${p.npmVersion}`)),console.log(f.gray(" Consider updating to compatible major versions."))),p.projects.length>0?(console.log(f.bold(`
|
|
76
|
-
\u{1F4E6} Projects (${p.projects.length}):`)),p.projects.forEach(k=>Si(k,p.rapidkitCore,{verbose:e$1.verbose,workspacePath:l,scope:"workspace"}))):(console.log(f.bold(`
|
|
77
|
-
\u{1F4E6} Projects:`)),console.log(f.gray(" No Workspai projects found in workspace")));let P=p.projects.map(ee),R=P.reduce((k,A)=>k+A.blockingFindings,0),x=P.reduce((k,A)=>k+A.advisoryFindings,0),g=P.reduce((k,A)=>k+A.unknownFindings+A.contradictionFindings,0),D=[p.python,p.rapidkitCore].some(k=>k.status==="error");if(D||R>0||x>0||g>0)if(console.log(f.bold.yellow(`
|
|
78
|
-
\u26A0\uFE0F Doctor verdict: ${p.healthScore?.verdict??"attention"} \xB7 ${R} blocking \xB7 ${x} advisory \xB7 ${g} trust gap(s)`)),D&&console.log(f.bold.red("\u274C System requirements not met")),e$1.plan)t("doctor.plan","running","Building governed remediation plan"),await Je(p.projects,false,{planOnly:true,json:e$1.json,policyProfile:n.name,artifactRoot:l,historyScope:"workspace"}),t("doctor.plan","succeeded","Governed remediation plan ready");else if(e$1.fix||e$1.apply){if(t("doctor.plan","running","Planning governed remediation"),await Je(p.projects,true,{skipConfirmation:e$1.apply===true,policyProfile:n.name,artifactRoot:l,historyScope:"workspace"}),t("doctor.plan","succeeded","Governed remediation executed"),!e$1.json){t("doctor.verify","running","Verifying workspace after remediation");let k=await nn(l,false,n,true);t("doctor.verify","succeeded","Post-remediation workspace verification completed");let A=k.projects.map(ee).reduce((G,F)=>G+F.blockingFindings,0),j=[k.python,k.rapidkitCore].some(G=>G.status==="error");j||A>0?(console.log(f.bold.yellow(`
|
|
79
|
-
\u26A0\uFE0F Post-fix verification found ${A} remaining issue(s)`)),j&&console.log(f.bold.red("\u274C System requirements still not met"))):console.log(f.bold.green(`
|
|
80
|
-
\u2705 Post-fix verification passed. Workspace is healthy.`)),k.projectScanCached&&console.log(f.gray(`\u2139\uFE0F Reused cached project scan${k.projectScanCachePath?` (${u.basename(k.projectScanCachePath)})`:""}`)),k.evidencePath&&console.log(f.gray(`\u2139\uFE0F Evidence refreshed: ${k.evidencePath}`));}}else R>0&&(console.log(f.bold.cyan(`
|
|
81
|
-
Next action:`)),console.log(" Review the governed remediation plan:"),console.log(f.white(" workspai doctor workspace --plan")),console.log(f.dim(" Apply only after review: workspai doctor workspace --apply")));else console.log(f.bold.green(`
|
|
82
|
-
\u2705 All checks passed! Workspace is healthy.`));return ft(p.healthScore,{profile:n.name})}else if(a){let l=await hs(process.cwd());if(!l){let x=await mt(process.cwd());if(e$1.json){let g={contract:Ue(),policyProfile:n,scope:"project",status:"error",generatedAt:new Date().toISOString(),workspace:x?{name:u.basename(x),path:x}:null,project:null,healthScore:{total:1,passed:0,warnings:0,errors:1,verdict:"blocked",presentation:{policy:"doctor-multi-axis-v1",diagnosticPassRatePercent:0,blockingFindings:1,advisoryFindings:0,unknownFindings:0,contradictionFindings:0,notApplicableChecks:0,label:"diagnostic-pass-rate"},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:x?"doctor.project.scope.not_found_in_workspace":"doctor.project.scope.not_found",message:x?"No project found in the current directory within this workspace.":"No Workspai project found in the current directory or parents.",recommendation:x?"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:x?["npx workspai doctor workspace --json","npx workspai workspace list --json"]:["npx workspai doctor workspace --json","npx workspai adopt --json"]}};return e$1.quiet||console.log(JSON.stringify(g,null,2)),1}x?(e.error("No backend project found in current directory within this workspace"),e.info("Run this command from inside a project directory in the workspace")):e.error("No Workspai project found in current directory or parents"),e.info('Run this command from within a project, or use "workspai doctor workspace" for workspace checks'),process.exit(1);}let d=await Ri(l,n,e$1.fresh===true);i("Project",d.healthScore);let p=d.workspacePath?Pi(d.workspacePath):null;if(e$1.json){let x;(e$1.plan||e$1.fix||e$1.apply)&&t("doctor.plan","running","Building governed remediation plan");let g=e$1.plan||e$1.fix||e$1.apply?await cn([d.project],n.name):void 0,D=l,k=[],A=g?await an(D,g,k):void 0;(e$1.plan||e$1.fix||e$1.apply)&&t("doctor.plan","succeeded","Governed remediation plan ready");let j;(e$1.fix||e$1.apply)&&!e$1.plan&&(x=await Je([d.project],true,{skipConfirmation:e$1.apply===true||e$1.fix===true,json:true,policyProfile:n.name})??Me({appliedFixes:[],remainingBlockers:[],verifyRecommended:Ce}),t("doctor.verify","running","Verifying project after remediation"),d=await Ri(l,n,true),t("doctor.verify","succeeded","Post-remediation project verification completed"),x={...x,remainingBlockers:Fi([d.project])},j=await Ye(D,x,k),await Ze(D,x,"project"));let G=Pi(d.project.path),F=ee(d.project),V=Ee([d.project],[d.python,d.poetry,d.pipx,d.go,d.rapidkitCore,d.cliResolution]),se={contract:Ue(),policyProfile:n,scope:"project",workspace:p?{name:u.basename(p),path:p}:null,project:{...Di(d.project),path:G},evidencePath:d.evidencePath,receiptPath:d.receiptPath,healthScore:d.healthScore,evidenceFreshness:d.evidenceFreshness,system:{python:d.python,poetry:d.poetry,pipx:d.pipx,go:d.go,rapidkitCore:d.rapidkitCore,cliResolution:d.cliResolution},summary:{counts:V,totalProjects:1,totalIssues:d.project.issues.length,verdict:F.verdict,probeSummary:F,blockingFindings:F.blockingFindings,advisoryFindings:F.advisoryFindings,projectAdvisoryWarningProjects:F.advisoryFindings>0?1:0,projectAdvisoryWarnings:F.advisoryFindings,hasSystemErrors:[d.python,d.rapidkitCore].some(W=>W.status==="error"),scopeProvenance:d.scopeProvenance},driftDelta:d.driftDelta,scoreBreakdown:d.scoreBreakdown??[],...g?{remediationPlan:g,remediationPlanPath:A}:{},...x?{appliedFixes:x.appliedFixes,remainingBlockers:x.remainingBlockers,verifyRecommended:x.verifyRecommended,fixResult:x,fixResultPath:j}:{}};if(!e$1.quiet){let W=e$1.json==="summary"?{schemaVersion:St,generatedAt:d.evidenceFreshness?.generatedAt??new Date().toISOString(),scope:"project",workspace:se.workspace,project:{name:d.project.name,path:G,runtimeFamily:d.project.runtimeFamily??"unknown",framework:d.project.framework??"Unknown",projectArchetype:d.project.projectArchetype??"unknown"},verdict:F.verdict,counts:V,freshness:d.evidenceFreshness,blockers:(d.project.diagnosis?.findings??[]).filter(K=>K.status==="blocking").map(K=>({id:K.id,issueClass:K.issueClass,symptom:K.symptom,repairDisposition:K.repair.disposition,...K.repair.capabilityId?{capabilityId:K.repair.capabilityId}:{}})),artifacts:{evidence:d.evidencePath,receipt:d.receiptPath,...A?{remediationPlan:A}:{},...j?{fixResult:j}:{}}}:se;console.log(JSON.stringify(W,null,2));}return $i(d.healthScore,{profile:n.name},x)}if(console.log(f.bold(`Project: ${f.cyan(u.basename(l))}`)),console.log(f.gray("Boundary: $PROJECT")),d.workspacePath&&console.log(f.gray(`Workspace: ${u.basename(d.workspacePath)}`)),d.evidencePath){let x=d.workspacePath??l;console.log(f.gray(`\u2139\uFE0F Evidence saved: ${u.relative(x,d.evidencePath).split(u.sep).join("/")}`));}let y=d.healthScore;console.log(f.bold(`
|
|
83
|
-
\u{1F4CA} Diagnostic accounting:`)),console.log(` ${f.green(`${y.passed} passed`)} ${f.gray("|")} ${f.yellow(`${y.warnings} warnings`)} ${f.gray("|")} ${f.red(`${y.errors} errors`)} ${f.gray("|")} ${y.presentation.notApplicableChecks} N/A`),console.log(f.dim(` Diagnostic pass rate: ${y.presentation.diagnosticPassRatePercent??"n/a"}% (accounting only; verdict and blockers govern readiness)`));let b=[[d.python,"Python"],[d.poetry,"Poetry"],[d.pipx,"pipx"],[d.go,"Go"],[d.rapidkitCore,"RapidKit Core"],[d.cliResolution,"CLI resolution"]],v=e$1.verbose?b:b.filter(([x])=>x.applicability!=="not-applicable");console.log(f.bold(`
|
|
84
|
-
|
|
85
|
-
System Tools:
|
|
86
|
-
`)),v.length===0?console.log(f.gray("No host prerequisites apply to the detected primary runtime.")):v.forEach(([x,g])=>Se(x,g)),console.log(f.bold(`
|
|
87
|
-
\u{1F4E6} Project (1):`)),Si(d.project,d.rapidkitCore,{verbose:e$1.verbose,workspacePath:d.workspacePath,scope:"project"});let C=[d.python,d.rapidkitCore].some(x=>x.status==="error"),h=ee(d.project),w=h.blockingFindings,P=h.advisoryFindings,R=h.unknownFindings+h.contradictionFindings;if(C||w>0||P>0||R>0)if(console.log(f.bold.yellow(`
|
|
88
|
-
\u26A0\uFE0F Doctor verdict: ${h.verdict} \xB7 ${w} blocking \xB7 ${P} advisory \xB7 ${R} trust gap(s)`)),C&&console.log(f.bold.red("\u274C System requirements not met")),e$1.plan){let x=d.workspacePath??l,g=d.workspacePath&&u.resolve(d.workspacePath)!==u.resolve(l)?[l]:[];t("doctor.plan","running","Building governed remediation plan"),await Je([d.project],false,{planOnly:true,json:e$1.json,policyProfile:n.name,artifactRoot:x,artifactMirrorRoots:g,historyScope:"project"}),t("doctor.plan","succeeded","Governed remediation plan ready");}else if(e$1.fix||e$1.apply){let x=d.workspacePath??l,g=d.workspacePath&&u.resolve(d.workspacePath)!==u.resolve(l)?[l]:[];t("doctor.plan","running","Planning governed remediation"),await Je([d.project],true,{skipConfirmation:e$1.apply===true,policyProfile:n.name,artifactRoot:x,artifactMirrorRoots:g,historyScope:"project"}),t("doctor.plan","succeeded","Governed remediation executed"),t("doctor.verify","running","Verifying project after remediation"),t("doctor.verify","succeeded","Post-remediation project verification completed");}else w>0&&(console.log(f.bold.cyan(`
|
|
89
|
-
Next action:`)),console.log(f.white(" workspai doctor project --plan")),console.log(f.dim(" Apply only after review: workspai doctor project --apply")));else console.log(f.bold.green(`
|
|
90
|
-
\u2705 All checks passed! Project is healthy.`));return ft(d.healthScore,{profile:n.name})}else {let l=await un(),d=l.python,p=l.poetry,y=l.pipx,b=l.go,v=l.rapidkitCore,C=l.cliResolution,h=[d,p,y,b,v,C],w=mn(h,[]);i("System",w);let P=[d,v].filter(x=>x.status==="error").length;if(e$1.json){let x=new Date().toISOString(),g=Ee([],h),D={contract:Ue(),policyProfile:n,scope:"system",status:P>0?"error":"ok",generatedAt:x,healthScore:w,system:{python:d,poetry:p,pipx:y,go:b,rapidkitCore:v,cliResolution:C},summary:{totalChecks:h.length,errors:P,warnings:h.filter(k=>k.status==="warn").length,recommendedScopes:["workspace","project"]},nextActions:["npx workspai doctor workspace --json","npx workspai doctor project --json"]};if(!e$1.quiet){let k=e$1.json==="summary"?{schemaVersion:St,generatedAt:x,scope:"system",verdict:w.verdict,counts:g,system:Object.fromEntries(Object.entries({python:d,poetry:p,pipx:y,go:b,rapidkitCore:v,cliResolution:C}).map(([A,j])=>[A,{status:j.status,message:j.message}])),nextActions:D.nextActions}:D;console.log(JSON.stringify(k,null,2));}return (e$1.strict||e$1.ci)&&P>0?1:0}return console.log(f.bold(`System Tools:
|
|
91
|
-
`)),Se(d,"Python"),Se(p,"Poetry"),Se(y,"pipx"),Se(b,"Go"),Se(v,"RapidKit Core"),C.applicability!=="not-applicable"&&Se(C,"CLI resolution"),[d,v].some(x=>x.status==="error")?(console.log(f.bold.red(`
|
|
92
|
-
\u274C Some required tools are missing`)),(e$1.fix||e$1.apply)&&console.log(f.gray(`
|
|
93
|
-
Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "workspai doctor workspace --fix"`)),console.log(f.gray(`
|
|
94
|
-
Tip: Run "workspai doctor workspace" for workspace-wide checks, or "workspai doctor project" for the current project`))):(console.log(f.bold.green(`
|
|
95
|
-
\u2705 All required tools are installed!`)),(e$1.fix||e$1.apply)&&console.log(f.gray(`
|
|
96
|
-
Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "workspai doctor workspace --fix"`)),console.log(f.gray(`
|
|
97
|
-
Tip: Run "workspai doctor workspace" for workspace-wide checks, or "workspai doctor project" for the current project`))),console.log(""),(e$1.strict||e$1.ci)&&P>0?1:0}}export{so as a,Qt as b,St as c,sn as d,Nt as e,Ot as f,Xe as g,Ss as h,Es as i,Ae as j,As as k,Fs as l,$s as m,Is as n,Ns as o,Ms as p,Ts as q,Os as r,ft as s,$i as t,Xc as u};
|