workspai 0.77.0 → 0.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/contracts/create-planner-capabilities.v1.json +27 -3
  2. package/contracts/runtime-command-surface.v1.json +2 -0
  3. package/contracts/workspace-intelligence-architecture.v1.json +2 -0
  4. package/dist/analyze-SKOIUD6F.js +1 -0
  5. package/dist/autopilot-release-MDMVMU67.js +1 -0
  6. package/dist/{chunk-UP3UWAJV.js → chunk-2ZVE7VE2.js} +1 -1
  7. package/dist/{chunk-47UR6ZH4.js → chunk-3O344BX3.js} +1 -1
  8. package/dist/{chunk-IDETNYCF.js → chunk-4H3VNKOJ.js} +1 -1
  9. package/dist/{chunk-LUPKDFQ3.js → chunk-7EMG3C3H.js} +2 -2
  10. package/dist/{chunk-O3TVVQ6X.js → chunk-7HV4U2OV.js} +1 -1
  11. package/dist/{chunk-DWKCFHHL.js → chunk-7MIOAM4A.js} +1 -1
  12. package/dist/{chunk-E7WJ2QX7.js → chunk-7SN4V3RC.js} +1 -1
  13. package/dist/{chunk-X5XFT5UZ.js → chunk-BGUCDG5N.js} +1 -1
  14. package/dist/{chunk-IAXRGH4Q.js → chunk-CJBDYDVC.js} +1 -1
  15. package/dist/{chunk-UTIK3K3M.js → chunk-EPFEUMYF.js} +1 -1
  16. package/dist/{chunk-4CXV3PPV.js → chunk-ETTZXKAS.js} +1 -1
  17. package/dist/{chunk-V6HVDVKJ.js → chunk-FVG5FBA4.js} +5 -5
  18. package/dist/{chunk-J2MPBSQJ.js → chunk-GUCZOQUS.js} +1 -1
  19. package/dist/{chunk-SC43A6LH.js → chunk-H24MEOML.js} +50 -50
  20. package/dist/{chunk-ZIWWE4BQ.js → chunk-HXTNPR3M.js} +1 -1
  21. package/dist/chunk-ICPL4WNK.js +2 -0
  22. package/dist/{chunk-475GQJ2D.js → chunk-KRTVIBPC.js} +1 -1
  23. package/dist/{chunk-GLBFY7AB.js → chunk-KTOKU6HQ.js} +2 -2
  24. package/dist/{chunk-QCX6BO2M.js → chunk-MNZAJ6PP.js} +1 -1
  25. package/dist/chunk-O4TZKLEC.js +1 -0
  26. package/dist/{chunk-HRVHQBTA.js → chunk-R7R5FX4B.js} +1 -1
  27. package/dist/chunk-RQXZF7BZ.js +1 -0
  28. package/dist/{chunk-UNEK3VVR.js → chunk-RRZQPFFR.js} +2171 -109
  29. package/dist/{chunk-3EPR3D5Q.js → chunk-SKHRUHXO.js} +1 -1
  30. package/dist/{chunk-WC2K5QFI.js → chunk-SV7X5LJW.js} +1 -1
  31. package/dist/{chunk-TGNPMOM6.js → chunk-TQW2SZHH.js} +1 -1
  32. package/dist/{chunk-JVZA35OL.js → chunk-U5WP4HDH.js} +1 -1
  33. package/dist/{chunk-223SWPTL.js → chunk-VT4WPXTO.js} +1 -1
  34. package/dist/chunk-WU5M6UP7.js +2 -0
  35. package/dist/{chunk-3EMAC3MF.js → chunk-ZDLF77IS.js} +1 -1
  36. package/dist/{chunk-3SQIV3F4.js → chunk-ZONAHZBG.js} +1 -1
  37. package/dist/{create-YPAZJYCE.js → create-M3TWRHV6.js} +1 -1
  38. package/dist/{doctor-W5PXJ5FL.js → doctor-FF3WLJSP.js} +1 -1
  39. package/dist/{goal-lifecycle-5R55CA7H.js → goal-lifecycle-O4MYYTRU.js} +1 -1
  40. package/dist/{goal-pack-IS6GGJPH.js → goal-pack-NUDKANPM.js} +1 -1
  41. package/dist/index.js +92 -91
  42. package/dist/{pipeline-LW3SW2WT.js → pipeline-V5P2FX2P.js} +1 -1
  43. package/dist/{project-agent-entry-5TYKK5IV.js → project-agent-entry-6O7FKWSL.js} +1 -1
  44. package/dist/{project-intelligence-lens-TEOSTKNU.js → project-intelligence-lens-OQTZ4K7L.js} +1 -1
  45. package/dist/{project-test-coverage-T4TIWGKN.js → project-test-coverage-EJ3MBSZ3.js} +1 -1
  46. package/dist/{proof-carrying-change-2TKRADCW.js → proof-carrying-change-GV37YLDQ.js} +1 -1
  47. package/dist/{verified-goal-RN4TOV34.js → verified-goal-VB7IOTNO.js} +1 -1
  48. package/dist/{workspace-A33YMF2N.js → workspace-AXU6ODER.js} +1 -1
  49. package/dist/{workspace-agent-sync-VCA4G4DT.js → workspace-agent-sync-6427FNME.js} +1 -1
  50. package/dist/{workspace-context-YBWLSKR6.js → workspace-context-VVZARI5K.js} +1 -1
  51. package/dist/{workspace-contract-3QUZDBMM.js → workspace-contract-N2BJCAJ7.js} +1 -1
  52. package/dist/{workspace-explain-NXYRAQFI.js → workspace-explain-5WKK6ENK.js} +1 -1
  53. package/dist/{workspace-foundation-DZ52PECX.js → workspace-foundation-GYL3D7TW.js} +1 -1
  54. package/dist/{workspace-graph-stream-4VT46HZ7.js → workspace-graph-stream-26ME2JJS.js} +1 -1
  55. package/dist/{workspace-intelligence-FKYQQDJ6.js → workspace-intelligence-ZTET7JHS.js} +1 -1
  56. package/dist/{workspace-intelligence-runner-3K2JZH6Q.js → workspace-intelligence-runner-2EJ7GXG5.js} +1 -1
  57. package/dist/{workspace-knowledge-graph-CPBKNXQI.js → workspace-knowledge-graph-4RSZTEFJ.js} +1 -1
  58. package/dist/workspace-knowledge-graph-snapshot-UTJHALST.js +1 -0
  59. package/dist/{workspace-mcp-serve-UXPKX7K6.js → workspace-mcp-serve-BSA6Q4EB.js} +1 -1
  60. package/dist/{workspace-model-POCPMNRT.js → workspace-model-LBICKRVI.js} +1 -1
  61. package/dist/{workspace-onboarding-KLG3GG7S.js → workspace-onboarding-NH4WFJ5N.js} +1 -1
  62. package/dist/{workspace-registry-summary-M4WMFDQ4.js → workspace-registry-summary-3PXZENLC.js} +1 -1
  63. package/dist/{workspace-repair-engine-2VGN42QD.js → workspace-repair-engine-ODTFFM6O.js} +1 -1
  64. package/dist/workspace-run-VDQ6BYLS.js +1 -0
  65. package/dist/{workspace-verify-PLAKTF3J.js → workspace-verify-UQWAFGNQ.js} +1 -1
  66. package/dist/{workspace-watch-VNU4KVYN.js → workspace-watch-BKIZQ2SM.js} +1 -1
  67. package/docs/agent-framework-adapters.md +88 -32
  68. package/docs/ci-workflows.md +10 -7
  69. package/docs/commands-reference.md +13 -9
  70. package/docs/create-planner-capabilities.md +1 -1
  71. package/docs/creating-workspaces-and-projects.md +24 -20
  72. package/docs/doctor-command.md +5 -3
  73. package/docs/model-gateways.md +23 -23
  74. package/docs/native-kit-baselines.md +2 -2
  75. package/package.json +4 -1
  76. package/scripts/enterprise-package-smoke.mjs +50 -0
  77. package/dist/analyze-TJM66CPF.js +0 -1
  78. package/dist/autopilot-release-C7Q4OTPY.js +0 -1
  79. package/dist/chunk-5KXOV7W4.js +0 -1
  80. package/dist/chunk-IHWS3ALP.js +0 -2
  81. package/dist/chunk-N7DOKE7V.js +0 -2
  82. package/dist/chunk-SEZTSMRR.js +0 -1
  83. package/dist/workspace-knowledge-graph-snapshot-67XDXUOT.js +0 -1
  84. package/dist/workspace-run-5YQR7GEZ.js +0 -1
@@ -1,97 +1,97 @@
1
- import {b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$3}from'./chunk-7Q7X4X5I.js';import {f as f$1,e as e$1,g as g$2,h as h$1}from'./chunk-XF65LQ6M.js';import {j,g as g$1}from'./chunk-RU3UT7GJ.js';import {e as e$2}from'./chunk-5HNQIMGW.js';import {a as a$a}from'./chunk-4ZUBPFSO.js';import {c as c$3,a as a$8,d as d$1,b as b$5}from'./chunk-N4B2M44I.js';import {a,c as c$4,h as h$2,g as g$3,k as k$1,f as f$2,d as d$3,e as e$4,i as i$1,j as j$3}from'./chunk-AO2ZI42U.js';import {a as a$1,b as b$2}from'./chunk-SVO2GGTV.js';import {c as c$2}from'./chunk-QCX6BO2M.js';import {a as a$7,b as b$3}from'./chunk-HRVHQBTA.js';import {b as b$4}from'./chunk-5KXOV7W4.js';import {a as a$5}from'./chunk-NMXGSVMD.js';import {a as a$4}from'./chunk-IHWS3ALP.js';import {D,y}from'./chunk-O3TVVQ6X.js';import {d}from'./chunk-ROOPODG6.js';import {j as j$2,l,m as m$1,d as d$2,e as e$3,b as b$7,a as a$d}from'./chunk-LUPKDFQ3.js';import {a as a$c}from'./chunk-GR6442P7.js';import {g,h,i}from'./chunk-BLEIUQL6.js';import {a as a$6}from'./chunk-AFIFZTOY.js';import {b,a as a$2}from'./chunk-252EKOR6.js';import {c as c$1,j as j$1,b as b$6,z,t as t$2,v,m as m$2}from'./chunk-6BO4QHKA.js';import {e}from'./chunk-EFHSRPW7.js';import {a as a$b}from'./chunk-TQEMLBAG.js';import {a as a$9}from'./chunk-2FIX2MDC.js';import {c}from'./chunk-25AWHAB5.js';import {t,k,u as u$1}from'./chunk-VQZ5PI5J.js';import {s,p,t as t$1}from'./chunk-ODK4LCEL.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 ro=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],so=["tests","test","src/test","__tests__","e2e","playwright","cypress"],ao=["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"],co=["src","app","pages"],lo=["dev","build","test","lint"];function si(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 ai(e,t){for(let o of ro)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 ci(e,t){for(let o of so)if(await m.pathExists(u.join(e,o)))return true;for(let o of ao)if(await m.pathExists(u.join(e,o)))return true;let i=si(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 po(e)}async function po(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 r of t){let s=u.join(e,r);if(!await m.pathExists(s))continue;let c=[{dir:s,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 Qt(e){for(let t of co){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 uo(e){let t=e.key;return b$7(t).key}function mo(e,t,i){return a$d(t,i).some(o=>!!e[o])}async function li(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=uo(i),r=b$7(o),s=si(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=r.fileHints.length>0&&r.fileHints.some(v=>existsSync(u.join(t,v)));c.push({id:"frontend-framework-config",label:`${r.displayName} config surface`,status:y?"pass":"warn",severity:"warn",scope:"project-scoped",reason:y?`${r.displayName} configuration artifacts detected.`:`No ${r.displayName} config markers detected (${r.fileHints.join(", ")||"n/a"}).`,recommendation:y?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let v of lo){let C=mo(s,o,v),h=v==="dev"||v==="build",w=!C&&v==="test"?h$2({projectPath:t,frameworkDisplayName:r.displayName,scriptName:v,scriptValue:g$3(s)}):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 ${r.displayName}.`:`No ${v} script detected for ${r.displayName}.`,recommendation:C?void 0:`Add a "${a$d(o,v)[0]??v}" script to package.json.`,repairCapability:w});}let b=await Qt(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 fo=s.doctorFixResult.schemaVersion,De="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function Oe(e){return {schemaVersion:fo,generatedAt:new Date().toISOString(),appliedFixes:e.appliedFixes,remainingBlockers:e.remainingBlockers,verifyRecommended:e.verifyRecommended??De}}var go=["python","node","go","java","rust","elixir","clojure","deno","bun","php","ruby","dotnet","scala","kotlin","c","cpp","unknown"],Dt={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:[]},Rt={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:[]},yo=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
1
+ import {b as b$1}from'./chunk-B6FJ6RG6.js';import {a as a$3}from'./chunk-7Q7X4X5I.js';import {f as f$1,e as e$1,g as g$2,h as h$1}from'./chunk-XF65LQ6M.js';import {j,g as g$1}from'./chunk-RU3UT7GJ.js';import {e as e$2}from'./chunk-5HNQIMGW.js';import {a as a$a}from'./chunk-4ZUBPFSO.js';import {c as c$3,a as a$8,d as d$1,b as b$5}from'./chunk-N4B2M44I.js';import {a,c as c$4,h as h$2,g as g$3,k as k$1,f as f$2,d as d$3,e as e$4,i as i$1,j as j$3}from'./chunk-AO2ZI42U.js';import {a as a$1,b as b$2}from'./chunk-SVO2GGTV.js';import {c as c$2}from'./chunk-MNZAJ6PP.js';import {a as a$7,b as b$3}from'./chunk-R7R5FX4B.js';import {b as b$4}from'./chunk-RQXZF7BZ.js';import {a as a$5}from'./chunk-NMXGSVMD.js';import {a as a$4}from'./chunk-WU5M6UP7.js';import {D,y}from'./chunk-7HV4U2OV.js';import {d}from'./chunk-ROOPODG6.js';import {j as j$2,l,m as m$1,d as d$2,e as e$3,b as b$7,a as a$d}from'./chunk-7EMG3C3H.js';import {a as a$c}from'./chunk-GR6442P7.js';import {g,h,i}from'./chunk-BLEIUQL6.js';import {a as a$6}from'./chunk-AFIFZTOY.js';import {b,a as a$2}from'./chunk-252EKOR6.js';import {c as c$1,j as j$1,b as b$6,z,t as t$2,v,m as m$2}from'./chunk-6BO4QHKA.js';import {e}from'./chunk-EFHSRPW7.js';import {a as a$b}from'./chunk-TQEMLBAG.js';import {a as a$9}from'./chunk-2FIX2MDC.js';import {c}from'./chunk-25AWHAB5.js';import {t,k,u as u$1}from'./chunk-VQZ5PI5J.js';import {s,p,t as t$1}from'./chunk-ODK4LCEL.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 ro=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],so=["tests","test","src/test","__tests__","e2e","playwright","cypress"],ao=["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"],co=["src","app","pages"],lo=["dev","build","test","lint"];function si(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 ai(e,t){for(let o of ro)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 ci(e,t){for(let o of so)if(await m.pathExists(u.join(e,o)))return true;for(let o of ao)if(await m.pathExists(u.join(e,o)))return true;let i=si(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 po(e)}async function po(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 r of t){let s=u.join(e,r);if(!await m.pathExists(s))continue;let c=[{dir:s,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 Qt(e){for(let t of co){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 uo(e){let t=e.key;return b$7(t).key}function mo(e,t,i){return a$d(t,i).some(o=>!!e[o])}async function li(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=uo(i),r=b$7(o),s=si(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=r.fileHints.length>0&&r.fileHints.some(v=>existsSync(u.join(t,v)));c.push({id:"frontend-framework-config",label:`${r.displayName} config surface`,status:y?"pass":"warn",severity:"warn",scope:"project-scoped",reason:y?`${r.displayName} configuration artifacts detected.`:`No ${r.displayName} config markers detected (${r.fileHints.join(", ")||"n/a"}).`,recommendation:y?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let v of lo){let C=mo(s,o,v),h=v==="dev"||v==="build",w=!C&&v==="test"?h$2({projectPath:t,frameworkDisplayName:r.displayName,scriptName:v,scriptValue:g$3(s)}):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 ${r.displayName}.`:`No ${v} script detected for ${r.displayName}.`,recommendation:C?void 0:`Add a "${a$d(o,v)[0]??v}" script to package.json.`,repairCapability:w});}let k=await Qt(t);return c.push({id:"frontend-source-tree",label:"Frontend source tree",status:k?"pass":"warn",severity:"warn",scope:"project-scoped",reason:k?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:k?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),c}var fo=s.doctorFixResult.schemaVersion,De="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function Oe(e){return {schemaVersion:fo,generatedAt:new Date().toISOString(),appliedFixes:e.appliedFixes,remainingBlockers:e.remainingBlockers,verifyRecommended:e.verifyRecommended??De}}var go=["python","node","go","java","rust","elixir","clojure","deno","bun","php","ruby","dotnet","scala","kotlin","c","cpp","unknown"],Dt={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:[]},Rt={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:[]},yo=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
2
2
  `),tn=[".env",".env.*","!.env.example"];function He(e){return e&&go.includes(e)?e:"unknown"}async function Re(e,t){for(let i of t){if(i.includes("*")){let n=i.replace("*","");if(await di(e,n,2))return true;continue}if(await m.pathExists(u.join(e,i)))return true}return false}async function di(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 r=n.shift();if(!r)break;let s=[];try{s=await m.readdir(r.dir,{withFileTypes:true});}catch{continue}for(let c of s){if(o.has(c.name))continue;let a=u.join(r.dir,c.name);if(c.isFile()&&c.name.endsWith(t))return true;c.isDirectory()&&r.depth<i&&!c.name.startsWith(".")&&n.push({dir:a,depth:r.depth+1});}}return false}async function nn(e,t=6){let i=await m.pathExists(u.join(e,"Dockerfile")),n=false,o=false,r=new Set(["docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml"]),s=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)s.has(d.name)||(d.isFile()?(a.depth>0&&d.name==="Dockerfile"&&(n=true),r.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 tt(e){try{return await m.pathExists(e)?await m.readFile(e,"utf8"):""}catch{return ""}}async function St(e,t){let i=[];for(let n of t){let o=await tt(u.join(e,n));o&&i.push(o);}return i.join(`
3
3
  `)}async function ho(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 r of i.filter(s=>s.isFile()&&/\.(?:ya?ml)$/i.test(s.name)).sort((s,c)=>s.name.localeCompare(c.name)).slice(0,64)){let s=u.join(t,r.name);try{let c=await m.stat(s);if(c.size>512*1024||o+c.size>1024*1024)continue;n.push(await m.readFile(s,"utf8")),o+=c.size;}catch{}}return n.join(`
4
- `)}var bo=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"]),ko=[/\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],vo=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 wo(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 s=n.shift();if(!s)break;let c=[];try{c=await m.readdir(s.dir,{withFileTypes:true});}catch{continue}for(let a of c){if(i.has(a.name))continue;let l=u.join(s.dir,a.name);if(a.isDirectory()){s.depth<6&&!a.name.startsWith(".")&&n.push({dir:l,depth:s.depth+1});continue}if(!a.isFile()||!bo.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 ko){p.lastIndex=0;for(let y of d.matchAll(p)){let b=y.slice(1).find(v=>typeof v=="string"&&v.length>0);b&&!vo.has(b)&&t.add(b);}}}}let r=await tt(u.join(e,".env"));for(let s of r.split(/\r?\n/)){let c=s.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/);c?.[1]&&t.add(c[1]);}return [...t].sort((s,c)=>s.localeCompare(c))}async function jo(e){if(e.runtime==="node"){let t=typeof e.packageJsonData?.packageManager=="string"?e.packageJsonData.packageManager.split("@")[0]:null,i=e.projectKind==="agent"?" --prefix agents/primary":"";return {command:t==="pnpm"?"pnpm install":t==="yarn"?"yarn install":t==="bun"?"bun install":`npm install${i}`,title:e.projectKind==="agent"?"Generate nested Node agent dependency lockfile":"Generate Node dependency lockfile",files:e.projectKind==="agent"?["agents/primary/package.json","agents/primary/package-lock.json"]:["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 e.projectKind==="agent"?{command:"dotnet restore agents/primary/tests/Primary.Tests.csproj",title:".NET agent dependency restore",files:["agents/primary/Primary.csproj","agents/primary/tests/Primary.Tests.csproj","agents/primary/**/packages.lock.json"],limitations:["Review the generated NuGet lock files before committing."]}:{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=e.projectKind==="agent"?u.join(e.projectPath,"agents","primary","pyproject.toml"):u.join(e.projectPath,"pyproject.toml"),i=await tt(t);if(/\[tool\.poetry\]/.test(i))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(i))return {command:e.projectKind==="agent"?"uv lock --project agents/primary":"uv lock",title:"Generate uv lockfile",files:e.projectKind==="agent"?["agents/primary/pyproject.toml","agents/primary/uv.lock"]:["pyproject.toml","uv.lock"],limitations:["Review uv.lock changes before committing."]}}return null}function nt(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 xo(e){if(e.runtime==="node"){let i=nt(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=y(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 Co(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 on(e){let t=xo({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"))?Co({issueId:e.issueId,projectPath:e.projectPath,contract:t,reason:e.reason}):Se({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 Se(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}}async function en(e,t){let i=[...new Set(t.filter(o=>o&&!o.includes("*")))],n=[];for(let o of i)await m.pathExists(u.join(e,o))&&n.push(o);return n}function Po(e){return d$3({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${yo}
4
+ `)}var ko=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"]),bo=[/\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],vo=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 wo(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 s=n.shift();if(!s)break;let c=[];try{c=await m.readdir(s.dir,{withFileTypes:true});}catch{continue}for(let a of c){if(i.has(a.name))continue;let l=u.join(s.dir,a.name);if(a.isDirectory()){s.depth<6&&!a.name.startsWith(".")&&n.push({dir:l,depth:s.depth+1});continue}if(!a.isFile()||!ko.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 bo){p.lastIndex=0;for(let y of d.matchAll(p)){let k=y.slice(1).find(v=>typeof v=="string"&&v.length>0);k&&!vo.has(k)&&t.add(k);}}}}let r=await tt(u.join(e,".env"));for(let s of r.split(/\r?\n/)){let c=s.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/);c?.[1]&&t.add(c[1]);}return [...t].sort((s,c)=>s.localeCompare(c))}async function jo(e){if(e.runtime==="node"){let t=typeof e.packageJsonData?.packageManager=="string"?e.packageJsonData.packageManager.split("@")[0]:null,i=e.projectKind==="agent"?" --prefix agents/primary":"";return {command:t==="pnpm"?"pnpm install":t==="yarn"?"yarn install":t==="bun"?"bun install":`npm install${i}`,title:e.projectKind==="agent"?"Generate nested Node agent dependency lockfile":"Generate Node dependency lockfile",files:e.projectKind==="agent"?["agents/primary/package.json","agents/primary/package-lock.json"]:["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 e.projectKind==="agent"?{command:"dotnet restore agents/primary/tests/Primary.Tests.csproj",title:".NET agent dependency restore",files:["agents/primary/Primary.csproj","agents/primary/tests/Primary.Tests.csproj","agents/primary/**/packages.lock.json"],limitations:["Review the generated NuGet lock files before committing."]}:{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=e.projectKind==="agent"?u.join(e.projectPath,"agents","primary","pyproject.toml"):u.join(e.projectPath,"pyproject.toml"),i=await tt(t);if(/\[tool\.poetry\]/.test(i))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(i))return {command:e.projectKind==="agent"?"uv lock --project agents/primary":"uv lock",title:"Generate uv lockfile",files:e.projectKind==="agent"?["agents/primary/pyproject.toml","agents/primary/uv.lock"]:["pyproject.toml","uv.lock"],limitations:["Review uv.lock changes before committing."]}}return null}function nt(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 xo(e){if(e.runtime==="node"){let i=nt(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=y(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 Co(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 on(e){let t=xo({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"))?Co({issueId:e.issueId,projectPath:e.projectPath,contract:t,reason:e.reason}):Se({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 Se(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}}async function en(e,t){let i=[...new Set(t.filter(o=>o&&!o.includes("*")))],n=[];for(let o of i)await m.pathExists(u.join(e,o))&&n.push(o);return n}function Po(e){return d$3({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${yo}
5
5
  `,reason:"Create a Docker build ignore baseline to keep secrets, dependencies, and reports out of container contexts."})}async function Do(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:`${tn.join(`
6
6
  `)}
7
- `,reason:"Create a minimal ignore baseline so local env files are not committed accidentally."});let t=await tt(u.join(e,".gitignore")),i=tn.filter(n=>!t.split(/\r?\n/).includes(n));return e$4({issueId:"surface-security-hygiene",title:"Append .gitignore secret baseline",projectPath:e,relativePath:".gitignore",lines:i,reason:"Append missing env-file ignore rules so local secrets stay out of source control."})}async function Ro(e){let t=e.projectKind==="agent"?"agents/primary":null,i=[...Rt[e.runtime]??[],...t&&e.runtime==="python"?[`${t}/pyproject.toml`]:t&&e.runtime==="dotnet"?[`${t}/Primary.csproj`,`${t}/tests/Primary.Tests.csproj`]:t&&e.runtime==="node"?[`${t}/package.json`]:[]],n=[...Dt[e.runtime]??[],...t&&e.runtime==="python"?[`${t}/uv.lock`]:t&&e.runtime==="dotnet"?[`${t}/packages.lock.json`,`${t}/tests/packages.lock.json`,`${t}/Directory.Packages.props`]:t&&e.runtime==="node"?[`${t}/package-lock.json`]:[]];if(i.length===0&&n.length===0)return null;let o=(e.runtime==="c"||e.runtime==="cpp")&&e$3(e.projectPath)||await Re(e.projectPath,i),r=await Re(e.projectPath,n),s=e.runtime==="java"&&await m.pathExists(u.join(e.projectPath,"pom.xml"))&&!await Re(e.projectPath,["build.gradle","build.gradle.kts"]),c=o&&!r?await jo({projectPath:e.projectPath,runtime:e.runtime,projectKind:e.projectKind,packageJsonData:e.packageJsonData}):null;return {id:"surface-dependency-contract",label:"Dependency contract",status:!o||r?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?r?"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 (${n.join(", ")}).`:"No dependency manifest markers detected for this runtime.",recommendation:o&&!r?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:o&&!r&&c?k$1({issueId:"surface-dependency-contract",title:c.title,projectPath:e.projectPath,command:c.command,files:c.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:c.limitations}):void 0}}async function So(e){let t=await m.pathExists(u.join(e.projectPath,".env.example"))||await di(e.projectPath,".env.example",4),i=await Re(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")),r=await m.pathExists(u.join(e.projectPath,"config")),s=t||i||o||r,c=e.projectKind==="frontend",a=s?[]:await wo(e.projectPath),l=n||a.length>0,d=!s&&!l,p=n||e.projectKind==="backend"||e.projectKind==="gateway"||e.projectKind==="agent"||e.projectKind==="frontend"||e.projectKind==="fullstack",y=a.map(b=>`${b}=`).join(`
7
+ `,reason:"Create a minimal ignore baseline so local env files are not committed accidentally."});let t=await tt(u.join(e,".gitignore")),i=tn.filter(n=>!t.split(/\r?\n/).includes(n));return e$4({issueId:"surface-security-hygiene",title:"Append .gitignore secret baseline",projectPath:e,relativePath:".gitignore",lines:i,reason:"Append missing env-file ignore rules so local secrets stay out of source control."})}async function Ro(e){let t=e.projectKind==="agent"?"agents/primary":null,i=[...Rt[e.runtime]??[],...t&&e.runtime==="python"?[`${t}/pyproject.toml`]:t&&e.runtime==="dotnet"?[`${t}/Primary.csproj`,`${t}/tests/Primary.Tests.csproj`]:t&&e.runtime==="node"?[`${t}/package.json`]:[]],n=[...Dt[e.runtime]??[],...t&&e.runtime==="python"?[`${t}/uv.lock`]:t&&e.runtime==="dotnet"?[`${t}/packages.lock.json`,`${t}/tests/packages.lock.json`,`${t}/Directory.Packages.props`]:t&&e.runtime==="node"?[`${t}/package-lock.json`]:[]];if(i.length===0&&n.length===0)return null;let o=(e.runtime==="c"||e.runtime==="cpp")&&e$3(e.projectPath)||await Re(e.projectPath,i),r=await Re(e.projectPath,n),s=e.runtime==="java"&&await m.pathExists(u.join(e.projectPath,"pom.xml"))&&!await Re(e.projectPath,["build.gradle","build.gradle.kts"]),c=o&&!r?await jo({projectPath:e.projectPath,runtime:e.runtime,projectKind:e.projectKind,packageJsonData:e.packageJsonData}):null;return {id:"surface-dependency-contract",label:"Dependency contract",status:!o||r?"pass":"warn",severity:"warn",scope:"project-scoped",reason:o?r?"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 (${n.join(", ")}).`:"No dependency manifest markers detected for this runtime.",recommendation:o&&!r?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:o&&!r&&c?k$1({issueId:"surface-dependency-contract",title:c.title,projectPath:e.projectPath,command:c.command,files:c.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:c.limitations}):void 0}}async function So(e){let t=await m.pathExists(u.join(e.projectPath,".env.example"))||await di(e.projectPath,".env.example",4),i=await Re(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")),r=await m.pathExists(u.join(e.projectPath,"config")),s=t||i||o||r,c=e.projectKind==="frontend",a=s?[]:await wo(e.projectPath),l=n||a.length>0,d=!s&&!l,p=n||e.projectKind==="backend"||e.projectKind==="gateway"||e.projectKind==="agent"||e.projectKind==="frontend"||e.projectKind==="fullstack",y=a.map(k=>`${k}=`).join(`
8
8
  `);return {id:"surface-env-contract",label:"Environment/config contract",status:s||d?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:d?"not-applicable":"applicable",reason:s?"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:s||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:s?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."]}):Se({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 Eo(e){let t=await nn(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:Po(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 Ao(e){let t=["k8s","kubernetes","deploy","deployments","charts","helm","kustomization.yaml","kustomization.yml"];if(!await Re(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 Re(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 St(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),r=/resources:\s*[\s\S]*(limits:|requests:)/.test(n),s=o&&r;return {id:"surface-kubernetes-readiness",label:"Deployment readiness controls",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Deployment surface includes probe and resource-control markers.":"Deployment surface detected, but readiness/liveness probes or resource controls are incomplete.",recommendation:s?void 0:"Add readiness/liveness/startup probes and resource requests/limits to production deployment manifests.",repairCapability:s?void 0:Se({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 Fo(e){let t=await m.pathExists(u.join(e.projectPath,".gitignore")),n=(await tt(u.join(e.projectPath,".gitignore"))).split(/\r?\n/),o=t&&tn.every(j=>n.includes(j)),r=nt(e.packageJsonData),s=!!(r.audit||r["security:audit"]||r["audit:security"]||r["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=He(e.runtimeFamily),b=await m.pathExists(u.join(e.projectPath,"npm-shrinkwrap.json")),v=await en(e.projectPath,[...Rt[y]??[],...Dt[y]??[],...b?["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?Se({issueId:"surface-security-hygiene",title:`Establish ${c?.ecosystem??y} security audit evidence`,projectPath:e.projectPath,files:await en(e.projectPath,[...Rt[y]??[],...Dt[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?s?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??{...Se({issueId:"surface-security-hygiene",title:`Resolve ${c?.ecosystem??y} dependency vulnerabilities`,projectPath:e.projectPath,files:await en(e.projectPath,[...Rt[y]??[],...Dt[y]??[]]),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 Do(e.projectPath))}}async function $o(e){let t=He(e.runtimeFamily),i=e.hasTests===true,n=i?void 0:await on({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:Se({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 Io(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",r=No(i.target?.percent),s$1=i.metrics?.[o]?.percent,c=typeof s$1=="number"?`${s$1}%`:"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 ${r}% project target.`:i.status==="below-target"?`${o} coverage ${c} is below the ${r}% 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 ${r}%.`:"Repair the runtime-native coverage command or reporter and regenerate evidence.",repairCapability:i.status==="passed"?void 0:Se({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 No(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Mo(e){let t=nt(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 To(e){let t=He(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),r=await Re(e.projectPath,n)||o.runtimeFamilies.some(y=>y===t),s=nt(e.packageJsonData),c=Object.values(s).join(`
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."]}):Se({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 Eo(e){let t=await nn(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:Po(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 Ao(e){let t=["k8s","kubernetes","deploy","deployments","charts","helm","kustomization.yaml","kustomization.yml"];if(!await Re(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 Re(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 St(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),r=/resources:\s*[\s\S]*(limits:|requests:)/.test(n),s=o&&r;return {id:"surface-kubernetes-readiness",label:"Deployment readiness controls",status:s?"pass":"warn",severity:"warn",scope:"project-scoped",reason:s?"Deployment surface includes probe and resource-control markers.":"Deployment surface detected, but readiness/liveness probes or resource controls are incomplete.",recommendation:s?void 0:"Add readiness/liveness/startup probes and resource requests/limits to production deployment manifests.",repairCapability:s?void 0:Se({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 Fo(e){let t=await m.pathExists(u.join(e.projectPath,".gitignore")),n=(await tt(u.join(e.projectPath,".gitignore"))).split(/\r?\n/),o=t&&tn.every(j=>n.includes(j)),r=nt(e.packageJsonData),s=!!(r.audit||r["security:audit"]||r["audit:security"]||r["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=He(e.runtimeFamily),k=await m.pathExists(u.join(e.projectPath,"npm-shrinkwrap.json")),v=await en(e.projectPath,[...Rt[y]??[],...Dt[y]??[],...k?["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?Se({issueId:"surface-security-hygiene",title:`Establish ${c?.ecosystem??y} security audit evidence`,projectPath:e.projectPath,files:await en(e.projectPath,[...Rt[y]??[],...Dt[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,b=o&&d,A=c?.reason;return {id:"surface-security-hygiene",label:"Security hygiene surface",status:b?"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?s?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??{...Se({issueId:"surface-security-hygiene",title:`Resolve ${c?.ecosystem??y} dependency vulnerabilities`,projectPath:e.projectPath,files:await en(e.projectPath,[...Rt[y]??[],...Dt[y]??[]]),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 Do(e.projectPath))}}async function $o(e){let t=He(e.runtimeFamily),i=e.hasTests===true,n=i?void 0:await on({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:Se({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 Io(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",r=No(i.target?.percent),s$1=i.metrics?.[o]?.percent,c=typeof s$1=="number"?`${s$1}%`:"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 ${r}% project target.`:i.status==="below-target"?`${o} coverage ${c} is below the ${r}% 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 ${r}%.`:"Repair the runtime-native coverage command or reporter and regenerate evidence.",repairCapability:i.status==="passed"?void 0:Se({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 No(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Mo(e){let t=nt(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 To(e){let t=He(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),r=await Re(e.projectPath,n)||o.runtimeFamilies.some(y=>y===t),s=nt(e.packageJsonData),c=Object.values(s).join(`
10
10
  `),a=await St(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
11
  ${a}`)??false,p=r||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 Oo(e){let t=He(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 St(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"]),r=nt(e.packageJsonData),s=Object.entries(r).filter(([d])=>/lint|format|quality|check|typecheck|static/i.test(d)).map(([,d])=>d).join(`
12
12
  `),c=await Re(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
13
  ${s}`)||c,l=a?void 0:await on({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=He(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 St(e.projectPath,n),await ho(e.projectPath)].join(`
14
- `),r=/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),s=r?void 0:await on({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:r?"pass":"warn",severity:"warn",scope:"project-scoped",reason:r?"Runtime-native security audit tooling marker detected.":"No runtime-native security audit tooling marker detected.",recommendation:r?void 0:"Expose a runtime-native dependency/security audit command for CI and Studio verification.",repairCapability:r?void 0:s||Se({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 pi(e){let t=He(e.runtimeFamily),i=[],n=await Ro({projectPath:e.projectPath,runtime:t,projectKind:e.projectKind,packageJsonData:e.packageJsonData});n&&i.push(n),i.push(await So(e)),i.push(await Eo(e)),i.push(await Ao(e)),i.push(await Fo(e)),i.push(await $o(e)),i.push(await Io(e)),(t==="node"||t==="bun")&&i.push(Mo(e));let o=await Promise.all([To(e),Oo(e),_o(e)]);for(let r of o)r&&i.push(r);return i}var je={low:0,moderate:0,high:0,critical:0,unknown:0};function Go(e){let t=String(e??"unknown").toLowerCase();return t==="medium"?"moderate":t==="low"||t==="moderate"||t==="high"||t==="critical"?t:"unknown"}function we(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=>Go(i)))].sort()}:null}function ve(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 ui(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 _e=new Map,Wo=256,Ho=["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 Lo(){let e=Number(process.env.RAPIDKIT_DOCTOR_AUDIT_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.trunc(e):15e3}async function qo(e,t){let i=[];for(let n of Ho){let o=u.join(e,n);try{let r=await m.readFile(o);i.push(`${n}:${r.byteLength}:${createHash("sha256").update(r).digest("hex")}`);}catch{}}return `${u.resolve(e)}\0${t}\0${i.join("|")}`}function Ee(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 it(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function mi(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {low:it(t.low),moderate:it(t.moderate??t.medium),high:it(t.high),critical:it(t.critical),unknown:it(t.unknown)}}function ot(e){return e.low+e.moderate+e.high+e.critical+e.unknown}function Vo(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 zo(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[r,s]of Object.entries(o))typeof s=="string"&&s.trim()&&t.set(r.toLowerCase(),s.trim());}}catch{}return t}async function Jo(e,t){let i=Ee(t),n=i?.vulnerabilities&&typeof i.vulnerabilities=="object"&&!Array.isArray(i.vulnerabilities)?i.vulnerabilities:void 0;if(!n)return [];let[o,r]=await Promise.all([yi(e),zo(e)]),s=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=Vo(C),w=r.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"];s.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 [...s.values()].sort((c,a)=>c.packageName.localeCompare(a.packageName))}function qe(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 rt(e,t){if(Array.isArray(e)){for(let n of e)rt(n,t);return}if(!e||typeof e!="object")return;let i=e;t(i);for(let n of Object.values(i))rt(n,t);}function Uo(e,t){if(t===0)return {disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]};let i=false,n=false,o=false,r=[];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,r.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,r.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:r.sort((c,a)=>`${c.packageName}@${c.version??""}`.localeCompare(`${a.packageName}@${a.version??""}`))}}function Yo(e,t){let i=r=>{let s=r.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.+)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3]),s[4]??""]:null},n=i(e),o=i(t);if(!n||!o)return null;for(let r=0;r<3;r+=1)if(n[r]!==o[r])return Number(n[r])>Number(o[r])?1:-1;return n[3]===o[3]?0:n[3]?o[3]?n[3].localeCompare(o[3]):-1:1}async function yi(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[r,s]of Object.entries(n)){if(!r.startsWith("node_modules/"))continue;let c=r.replace(/^node_modules\//,"").split("/node_modules/").at(-1)?.trim()??"";if(!c)continue;let a=s&&typeof s=="object"?s:{};!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[r,s]of Object.entries(o)){if(t.has(r.toLowerCase()))continue;let c=s&&typeof s=="object"?s:{};typeof c.version=="string"&&c.version.trim()&&t.set(r.toLowerCase(),c.version.trim());}}catch{}return t}async function Zo(e,t){if(t.disposition==="not-needed")return t;let i=await yi(e),n=new Map;for(let a of t.candidates){let l=i.get(a.packageName.toLowerCase());if(a.version&&l){let y=Yo(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??""}`)),r=o.some(a=>!a.breaking),s=o.some(a=>a.breaking);return {disposition:r?s?"mixed":"compatible":s?"breaking-only":"none",compatibleFixAvailable:r,breakingFixAvailable:s,candidates:o}}function Xo(e){let t=Ee(e);if(!t){let l={...je},d=[],p=0,y=false;for(let b of e.split(/\r?\n/)){let v=Ee(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,qe(l,h.severity);let w=we({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=mi(C.vulnerabilities);if(ot(h)>=p)return {findingCount:ot(h),severityCounts:h,subjects:ve(d)}}}return p>0||y?{findingCount:p,severityCounts:l,subjects:ve(d)}:null}let i=t.metadata&&typeof t.metadata=="object"?t.metadata:null,n=mi(i?.vulnerabilities),o=t.vulnerabilities&&typeof t.vulnerabilities=="object"?Object.entries(t.vulnerabilities):[],r=ve(o.map(([l,d])=>{let p=d&&typeof d=="object"?d:{},y=Array.isArray(p.via)?p.via:[];return we({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(ot(n)>0||i?.vulnerabilities){let l=ot(n);return {findingCount:l,severityCounts:n,subjects:r,remediation:Uo(o,l)}}let s=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 s){let p=d&&typeof d=="object"?d:{};qe(n,p.severity);let y=we({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:s.length,severityCounts:n,subjects:ve([...r,...a])}}function Qo(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={...je},o=[],r=0;for(let s of i){let c=s&&typeof s=="object"?s:{},a=Array.isArray(c.vulns)?c.vulns:[];if(r+=a.length,n.unknown+=a.length,a.length>0){let l=we({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:r,severityCounts:n,subjects:ve(o)}}function er(e){if(!e.trim())return null;let t=new Set,i=new Map;for(let n of e.split(/\r?\n/)){let o=Ee(n),r=o?.osv&&typeof o.osv=="object"?o.osv:null;typeof r?.id=="string"&&t.add(r.id);let s=o?.finding&&typeof o.finding=="object"?o.finding:null;typeof s?.osv=="string"&&t.add(s.osv);let c=Array.isArray(s?.trace)?s.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 s?.osv=="string"&&p.advisoryIds.add(s.osv),i.set(d,p);}}return {findingCount:t.size,severityCounts:{...je,unknown:t.size},subjects:[...i.entries()].map(([n,o])=>we({name:n,version:o.version,advisoryIds:[...o.advisoryIds],severities:["unknown"]})).filter(n=>!!n)}}function tr(e){let t=Ee(e);if(!t)return null;let i=t.vulnerabilities&&typeof t.vulnerabilities=="object"?t.vulnerabilities:{},n=Array.isArray(i.list)?i.list:[],o={...je},r=[];for(let s of n){let c=s&&typeof s=="object"?s:{},a=c.advisory&&typeof c.advisory=="object"?c.advisory:{};qe(o,a.severity);let l=c.package&&typeof c.package=="object"?c.package:{},d=we({name:l.name,version:l.version,advisoryIds:[a.id,a.url],severities:[a.severity]});d&&r.push(d);}return {findingCount:n.length,severityCounts:o,subjects:ve(r)}}function nr(e){let t=Ee(e);if(!t)return null;let i=t.advisories&&typeof t.advisories=="object"?t.advisories:{},n={...je},o=0,r=[];for(let[s,c]of Object.entries(i)){let a=Array.isArray(c)?c:[c],l=we({name:s,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&&r.push(l);}return rt(i,s=>{(typeof s.advisoryId=="string"||typeof s.cve=="string")&&(o+=1,qe(n,s.severity));}),{findingCount:o,severityCounts:n,subjects:ve(r)}}function ir(e){let t=Ee(e);if(!t)return null;let i={...je},n=0,o=[];return rt(t,r=>{if(!Array.isArray(r.vulnerabilities))return;for(let c of r.vulnerabilities){let a=c&&typeof c=="object"?c:{};n+=1,qe(i,a.severity);}let s=we({name:r.id??r.name??r.packageId,version:r.resolvedVersion??r.version,direct:r.isTransitive===false,advisoryIds:r.vulnerabilities.flatMap(c=>{let a=c&&typeof c=="object"?c:{};return [a.advisoryurl,a.advisoryUrl,a.url]}),severities:r.vulnerabilities.map(c=>(c&&typeof c=="object"?c:{}).severity)});s&&o.push(s);}),{findingCount:n,severityCounts:i,subjects:ve(o)}}function or(e){let t=Ee(e);if(!t)return null;let i={...je},n=new Set,o=[];return rt(t,r=>{let s=r.id??r.cve??r.advisory??r.url;if(typeof s!="string")return;n.add(s),qe(i,r.severity??r.criticality);let c=r.gem&&typeof r.gem=="object"?r.gem:{},a=we({name:c.name??r.gemName??r.name,version:c.version??r.version,advisoryIds:[s],severities:[r.severity??r.criticality]});a&&o.push(a);}),{findingCount:n.size,severityCounts:n.size>0&&ot(i)===0?{...i,unknown:n.size}:i,subjects:ve(o)}}function fi(e,t){let i=`${e}
14
+ `),r=/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),s=r?void 0:await on({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:r?"pass":"warn",severity:"warn",scope:"project-scoped",reason:r?"Runtime-native security audit tooling marker detected.":"No runtime-native security audit tooling marker detected.",recommendation:r?void 0:"Expose a runtime-native dependency/security audit command for CI and Studio verification.",repairCapability:r?void 0:s||Se({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 pi(e){let t=He(e.runtimeFamily),i=[],n=await Ro({projectPath:e.projectPath,runtime:t,projectKind:e.projectKind,packageJsonData:e.packageJsonData});n&&i.push(n),i.push(await So(e)),i.push(await Eo(e)),i.push(await Ao(e)),i.push(await Fo(e)),i.push(await $o(e)),i.push(await Io(e)),(t==="node"||t==="bun")&&i.push(Mo(e));let o=await Promise.all([To(e),Oo(e),_o(e)]);for(let r of o)r&&i.push(r);return i}var je={low:0,moderate:0,high:0,critical:0,unknown:0};function Bo(e){let t=String(e??"unknown").toLowerCase();return t==="medium"?"moderate":t==="low"||t==="moderate"||t==="high"||t==="critical"?t:"unknown"}function we(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=>Bo(i)))].sort()}:null}function ve(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 ui(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 _e=new Map,Wo=256,Ho=["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 Lo(){let e=Number(process.env.RAPIDKIT_DOCTOR_AUDIT_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.trunc(e):15e3}async function qo(e,t){let i=[];for(let n of Ho){let o=u.join(e,n);try{let r=await m.readFile(o);i.push(`${n}:${r.byteLength}:${createHash("sha256").update(r).digest("hex")}`);}catch{}}return `${u.resolve(e)}\0${t}\0${i.join("|")}`}function Ee(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 it(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function mi(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {low:it(t.low),moderate:it(t.moderate??t.medium),high:it(t.high),critical:it(t.critical),unknown:it(t.unknown)}}function ot(e){return e.low+e.moderate+e.high+e.critical+e.unknown}function Vo(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 zo(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[r,s]of Object.entries(o))typeof s=="string"&&s.trim()&&t.set(r.toLowerCase(),s.trim());}}catch{}return t}async function Jo(e,t){let i=Ee(t),n=i?.vulnerabilities&&typeof i.vulnerabilities=="object"&&!Array.isArray(i.vulnerabilities)?i.vulnerabilities:void 0;if(!n)return [];let[o,r]=await Promise.all([yi(e),zo(e)]),s=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():[],k=Array.isArray(l.via)?l.via:[],v=[...new Set(k.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=Vo(C),w=r.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"];s.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 [...s.values()].sort((c,a)=>c.packageName.localeCompare(a.packageName))}function qe(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 rt(e,t){if(Array.isArray(e)){for(let n of e)rt(n,t);return}if(!e||typeof e!="object")return;let i=e;t(i);for(let n of Object.values(i))rt(n,t);}function Uo(e,t){if(t===0)return {disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]};let i=false,n=false,o=false,r=[];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,r.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,k=p.isSemVerMajor===true;n||=!k,o||=k,r.push({packageName:y,...typeof p.version=="string"&&p.version.trim()?{version:p.version.trim()}:{},breaking:k});}return {disposition:n?o?"mixed":"compatible":o?"breaking-only":i?"none":"unknown",compatibleFixAvailable:n,breakingFixAvailable:o,candidates:r.sort((c,a)=>`${c.packageName}@${c.version??""}`.localeCompare(`${a.packageName}@${a.version??""}`))}}function Yo(e,t){let i=r=>{let s=r.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.+)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3]),s[4]??""]:null},n=i(e),o=i(t);if(!n||!o)return null;for(let r=0;r<3;r+=1)if(n[r]!==o[r])return Number(n[r])>Number(o[r])?1:-1;return n[3]===o[3]?0:n[3]?o[3]?n[3].localeCompare(o[3]):-1:1}async function yi(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[r,s]of Object.entries(n)){if(!r.startsWith("node_modules/"))continue;let c=r.replace(/^node_modules\//,"").split("/node_modules/").at(-1)?.trim()??"";if(!c)continue;let a=s&&typeof s=="object"?s:{};!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[r,s]of Object.entries(o)){if(t.has(r.toLowerCase()))continue;let c=s&&typeof s=="object"?s:{};typeof c.version=="string"&&c.version.trim()&&t.set(r.toLowerCase(),c.version.trim());}}catch{}return t}async function Zo(e,t){if(t.disposition==="not-needed")return t;let i=await yi(e),n=new Map;for(let a of t.candidates){let l=i.get(a.packageName.toLowerCase());if(a.version&&l){let y=Yo(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??""}`)),r=o.some(a=>!a.breaking),s=o.some(a=>a.breaking);return {disposition:r?s?"mixed":"compatible":s?"breaking-only":"none",compatibleFixAvailable:r,breakingFixAvailable:s,candidates:o}}function Xo(e){let t=Ee(e);if(!t){let l={...je},d=[],p=0,y=false;for(let k of e.split(/\r?\n/)){let v=Ee(k);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,qe(l,h.severity);let w=we({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=mi(C.vulnerabilities);if(ot(h)>=p)return {findingCount:ot(h),severityCounts:h,subjects:ve(d)}}}return p>0||y?{findingCount:p,severityCounts:l,subjects:ve(d)}:null}let i=t.metadata&&typeof t.metadata=="object"?t.metadata:null,n=mi(i?.vulnerabilities),o=t.vulnerabilities&&typeof t.vulnerabilities=="object"?Object.entries(t.vulnerabilities):[],r=ve(o.map(([l,d])=>{let p=d&&typeof d=="object"?d:{},y=Array.isArray(p.via)?p.via:[];return we({name:p.name??l,direct:p.isDirect,advisoryIds:y.flatMap(k=>{let v=k&&typeof k=="object"?k:{};return [v.source,v.url]}),severities:[p.severity]})}));if(ot(n)>0||i?.vulnerabilities){let l=ot(n);return {findingCount:l,severityCounts:n,subjects:r,remediation:Uo(o,l)}}let s=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 s){let p=d&&typeof d=="object"?d:{};qe(n,p.severity);let y=we({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:s.length,severityCounts:n,subjects:ve([...r,...a])}}function Qo(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={...je},o=[],r=0;for(let s of i){let c=s&&typeof s=="object"?s:{},a=Array.isArray(c.vulns)?c.vulns:[];if(r+=a.length,n.unknown+=a.length,a.length>0){let l=we({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:r,severityCounts:n,subjects:ve(o)}}function er(e){if(!e.trim())return null;let t=new Set,i=new Map;for(let n of e.split(/\r?\n/)){let o=Ee(n),r=o?.osv&&typeof o.osv=="object"?o.osv:null;typeof r?.id=="string"&&t.add(r.id);let s=o?.finding&&typeof o.finding=="object"?o.finding:null;typeof s?.osv=="string"&&t.add(s.osv);let c=Array.isArray(s?.trace)?s.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 s?.osv=="string"&&p.advisoryIds.add(s.osv),i.set(d,p);}}return {findingCount:t.size,severityCounts:{...je,unknown:t.size},subjects:[...i.entries()].map(([n,o])=>we({name:n,version:o.version,advisoryIds:[...o.advisoryIds],severities:["unknown"]})).filter(n=>!!n)}}function tr(e){let t=Ee(e);if(!t)return null;let i=t.vulnerabilities&&typeof t.vulnerabilities=="object"?t.vulnerabilities:{},n=Array.isArray(i.list)?i.list:[],o={...je},r=[];for(let s of n){let c=s&&typeof s=="object"?s:{},a=c.advisory&&typeof c.advisory=="object"?c.advisory:{};qe(o,a.severity);let l=c.package&&typeof c.package=="object"?c.package:{},d=we({name:l.name,version:l.version,advisoryIds:[a.id,a.url],severities:[a.severity]});d&&r.push(d);}return {findingCount:n.length,severityCounts:o,subjects:ve(r)}}function nr(e){let t=Ee(e);if(!t)return null;let i=t.advisories&&typeof t.advisories=="object"?t.advisories:{},n={...je},o=0,r=[];for(let[s,c]of Object.entries(i)){let a=Array.isArray(c)?c:[c],l=we({name:s,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&&r.push(l);}return rt(i,s=>{(typeof s.advisoryId=="string"||typeof s.cve=="string")&&(o+=1,qe(n,s.severity));}),{findingCount:o,severityCounts:n,subjects:ve(r)}}function ir(e){let t=Ee(e);if(!t)return null;let i={...je},n=0,o=[];return rt(t,r=>{if(!Array.isArray(r.vulnerabilities))return;for(let c of r.vulnerabilities){let a=c&&typeof c=="object"?c:{};n+=1,qe(i,a.severity);}let s=we({name:r.id??r.name??r.packageId,version:r.resolvedVersion??r.version,direct:r.isTransitive===false,advisoryIds:r.vulnerabilities.flatMap(c=>{let a=c&&typeof c=="object"?c:{};return [a.advisoryurl,a.advisoryUrl,a.url]}),severities:r.vulnerabilities.map(c=>(c&&typeof c=="object"?c:{}).severity)});s&&o.push(s);}),{findingCount:n,severityCounts:i,subjects:ve(o)}}function or(e){let t=Ee(e);if(!t)return null;let i={...je},n=new Set,o=[];return rt(t,r=>{let s=r.id??r.cve??r.advisory??r.url;if(typeof s!="string")return;n.add(s),qe(i,r.severity??r.criticality);let c=r.gem&&typeof r.gem=="object"?r.gem:{},a=we({name:c.name??r.gemName??r.name,version:c.version??r.version,advisoryIds:[s],severities:[r.severity??r.criticality]});a&&o.push(a);}),{findingCount:n.size,severityCounts:n.size>0&&ot(i)===0?{...i,unknown:n.size}:i,subjects:ve(o)}}function fi(e,t){let i=`${e}
15
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 r=n?Number(n[1]):0;return {findingCount:r,severityCounts:{...je,unknown:r},subjects:[]}}function rr(e,t,i){return e==="node"||e==="bun"?Xo(t):e==="python"?Qo(t):e==="go"?er(t):e==="rust"?tr(t):e==="php"?nr(t):e==="dotnet"?ir(t):e==="ruby"?or(t)??fi(t,i):e==="deno"||e==="elixir"?fi(t,i):null}async function sr(e,t){return m.pathExists(u.join(e,t))}async function ar(e,t){if(t==="bun")return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(t==="node"){let i=y(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 sr(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 gi(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 cr(e){let t=new Date().toISOString(),i=await ar(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:{...je},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:Lo(),reject:false}),r=rr(e.runtime,o.stdout,o.stderr);if(!r){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
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(r.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")&&r.remediation&&(r.remediation=await Zo(e.projectPath,r.remediation),r.findingCount>0&&!r.remediation.compatibleFixAvailable)){let a=await Jo(e.projectPath,o.stdout);r.remediation.resolutionCandidates=a.length>0?a:ui(r.subjects);}let s=r.severityCounts.moderate+r.severityCounts.high+r.severityCounts.critical+r.severityCounts.unknown,c=r.remediation??(r.findingCount===0?{disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]}:{disposition:"unknown",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[],resolutionCandidates:ui(r.subjects)});return {...n,invocation:i.invocation,exitCode:o.exitCode,findingCount:r.findingCount,blockingFindingCount:s,severityCounts:r.severityCounts,subjects:r.subjects,remediation:c,status:r.findingCount>0?"vulnerable":"clean",reason:r.findingCount>0?`${i.tool} reported ${r.findingCount} known dependency vulnerability finding(s).`:`${i.tool} completed without known dependency vulnerability findings.`}}catch(o){return {...n,invocation:i.invocation,status:gi(o)?"tool-unavailable":"failed",reason:gi(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 hi(e){let t=await qo(e.projectPath,e.runtime);e.fresh&&_e.delete(t);let i=_e.get(t);if(i)return i;let n=cr(e);for(_e.set(t,n);_e.size>Wo;){let o=_e.keys().next().value;if(!o)break;_e.delete(o);}try{return await n}catch(o){throw _e.delete(t),o}}var rn="doctor-graph-diagnosis.v1";var wi="Graph paths identify evidence-backed structural reachability and verification candidates; they do not prove runtime causality or that every affected surface has been discovered.",bi={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"]},lr=new Set(["project","service","api","endpoint","schema","database","queue","container","deployment","pipeline","environment","document","decision","test-suite","owner"]),dr=new Set(["test-suite","pipeline"]),at=new Map;async function pr(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(":"),r=at.get(o);if(r)return r;at.size>=4&&at.clear();let s=(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:fr(l)}})();at.set(o,s);try{return await s}catch(c){throw at.delete(o),c}}function Et(e,t){if(!e)return ".";let i=u.relative(e,t).split(u.sep).join("/");return i&&!i.startsWith("../")?i:"."}function sn(e){return {id:e.id,kind:e.kind,label:e.label,...e.projectId?{projectId:e.projectId}:{}}}function Ve(e,t,i,n={artifact:a$7}){return {schemaVersion:rn,generatedAt:(e.now??new Date).toISOString(),status:t,claimBoundary:wi,graph:n,project:{name:e.projectName,path:Et(e.workspacePath,e.projectPath)},summary:{findingCount:0,rootEntityCount:0,affectedEntityCount:0,verificationTargetCount:0,proofPathCount:0,subjectCount:0,unresolvedSubjectCount:0,unknownCount:1},findings:[],diagnostics:[i]}}function ur(e,t){let i=Et(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(s=>typeof s=="string").map(s=>s.toLowerCase()).some(s=>n.has(s)||n.has(u.basename(s))))}function mr(e,t){let i=t.projectId??t.label,n=e.entities.filter(s=>s.id===t.id||s.projectId===i||s.projectId===t.projectId),o=new Set(n.map(s=>s.id)),r=new Set;for(let s of e.relations)o.has(s.from)&&r.add(s.to),o.has(s.to)&&r.add(s.from);return e.entities.filter(s=>o.has(s.id)||r.has(s.id))}function fr(e){let t=new Map,i=(n,o)=>{let r=t.get(n)??[];r.push(o),t.set(n,r);};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 gr(e,t,i){let n=new Set(t),o=t.map(r=>({id:r,depth:0}));for(let r=0;r<o.length;r+=1){let s=o[r];if(!(!s||s.depth>=i))for(let c of e.get(s.id)??[])n.has(c)||(n.add(c),o.push({id:c,depth:s.depth+1}));}return [...n]}function ki(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 vi(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function yr(e,t){let i=vi(e);return i?t.some(n=>{let o=vi(n.reason);return o===i||o.includes(i)||i.includes(o)}):true}function hr(e,t,i,n){let o=bi[i]??bi.unknown,r=[...new Set(n.map(c=>c.trim().toLowerCase()).filter(Boolean))];if(r.length>0){let c=t.filter(l=>o?.includes(l.kind)&&r.some(d=>ki(l).has(d))),a=new Set(r.filter(l=>c.some(d=>ki(d).has(l))));return {roots:c.length>0?c.slice(0,4):[e],unresolvedSubjects:n.filter(l=>!a.has(l.trim().toLowerCase()))}}let s=t.filter(c=>o?.includes(c.kind)).slice(0,4);return {roots:s.length>0?s:[e],unresolvedSubjects:[]}}function br(e,t,i,n){let o=n.issueClass??"unknown",r=[...new Set((n.subjects??[]).map(h=>h.trim()).filter(Boolean))],{roots:s,unresolvedSubjects:c}=hr(t,i.scoped,o,r),a=gr(i.edges,s.map(h=>h.id),3).map(h=>i.entitiesById.get(h)).filter(h=>!!h),l=a.filter(h=>i.scopedIds.has(h.id)&&!s.some(w=>w.id===h.id)&&lr.has(h.kind)).slice(0,6),d=a.filter(h=>i.scopedIds.has(h.id)&&dr.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=s.map(R=>e$2(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([...s.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:r,unresolvedSubjects:c,rootEntities:s.map(sn),affectedEntities:l.map(sn),verificationTargets:d.map(sn),proofPaths:y,sourceArtifacts:v,unknowns:C}}async function an(e){if(!e.workspacePath)return Ve(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 Ve(e,"graph-missing","Workspace knowledge graph is missing. Run workspace model before relying on graph-aware diagnosis.");if(!await m.pathExists(i))return Ve(e,"model-missing","Canonical workspace model is missing, so graph source binding cannot be verified.");let n,o,r,s;try{({graph:n,model:o,entitiesById:r,edges:s}=await pr(t,i));}catch(b){return Ve(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$3(n,o);}catch(b){return Ve(e,"stale",b instanceof Error?b.message:String(b),c)}let a=ur(n,e);if(!a)return Ve(e,"project-unresolved","The current project could not be resolved to one canonical project entity.",c);let l=mr(n,a),d={scoped:l,scopedIds:new Set(l.map(b=>b.id)),entitiesById:r,edges:s,projectRelativePath:Et(e.workspacePath,e.projectPath)},p$1=(e.probes??[]).filter(b=>b.status!=="pass"),y=[...p$1,...(e.issues??[]).filter(b=>!yr(b,p$1)).map((b,v)=>({id:`legacy-project-issue-${v+1}`,status:"fail",reason:b,issueClass:"runtime"}))].map(b=>br(n,a,d,b));return {schemaVersion:rn,generatedAt:(e.now??new Date).toISOString(),status:"available",claimBoundary:wi,graph:c,project:{name:e.projectName,path:Et(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 At="workspai.doctor-summary.v1";function xi(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 ji(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 kr(e,t){return t.replace(/\.\*$/u,"").split(".").map(n=>Number.parseInt(n,10)).every((n,o)=>e[o]===n)}function vr(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 wr(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=kr(e.parts,o);return n==="=="?c:!c}let r=xi(o);if(!r)return null;let s=ji(e.parts,r.parts);return n==="==="?e.raw===r.raw:n==="=="?s===0:n==="!="?s!==0:n===">="?s>=0:n==="<="?s<=0:n===">"?s>0:n==="<"?s<0:n==="~="?s>=0&&ji(e.parts,vr(r.parts))<0:null}function Ci(e,t){let i=xi(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 r=o.map(c=>({clause:c,result:wr(i,c)})),s=r.filter(c=>c.result===null).map(c=>c.clause);return {version:i.raw,specifier:n,satisfied:s.length>0?null:r.every(c=>c.result===true),unsupportedSpecifiers:s}}function Pi(e){return u.win32.normalize(e.trim()).replace(/\\/g,"/").toLowerCase()}function Di(e,t){return Pi(u.win32.dirname(e))===Pi(t)&&/^workspai(?:\.cmd|\.exe|\.ps1)?$/i.test(u.win32.basename(e))}async function jr(){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 xr(){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 Si(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??jr)(),(e.resolveNpmGlobalPrefix??xr)()]);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,r=n.status==="fulfilled"?n.value:void 0,s=[...new Set(o.map(d=>d.trim()).filter(Boolean))],c=s.map((d,p)=>({location:p===0?"Active PATH match":"Additional PATH match",path:d}));if(s.length===0)return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unresolved",candidates:s,...r?{npmGlobalPrefix:r}:{},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=s[0];if(!r)return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unverified",activePath:a,candidates:s,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=s.find(d=>Di(d,r));return Di(a,r)?{status:"ok",applicability:"applicable",command:"workspai",resolutionStatus:"canonical",activePath:a,npmGlobalPrefix:r,candidates:s,paths:c,message:"`workspai` resolves to the npm global shim.",...s.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:r,candidates:s,paths:c,message:"Another executable shadows the npm global `workspai` shim.",details:l?`Move ${r} before ${u.win32.dirname(a)} in PATH. Until then, use \`npx --yes workspai <command>\`.`:`Add ${r} to PATH before ${u.win32.dirname(a)}. Until then, use \`npx --yes workspai <command>\`.`}}var un=p.doctor;function Ki(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Ei(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Bi(){let e=z().map(n=>u.join(n,b$6()?"poetry.exe":"poetry")),t=b$6()?[u.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),u.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],i=b$6()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return Ki([...e,...t,...i])}function Cr(e,t=process.cwd()){let i=z().map(l=>({location:"Global (user-local)",path:u.join(l,b$6()?"rapidkit.exe":"rapidkit")})),n=[{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=t$2(u.join(t,".venv")),r=v(t),s=[{location:"Workspace (.venv)",path:o},...r.map(l=>({location:"Workspace (launcher)",path:l}))],c=[...i,...n,...s],a=new Set;return c.filter(l=>a.has(l.path)?false:(a.add(l.path),true))}function Pr(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,r=t.get(n.location)??Number.MAX_SAFE_INTEGER;return o!==r?o-r:i.path.localeCompare(n.path)})}function lt(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 Gi(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),r=t.find(c=>c.pythonRequirement?.satisfied===null),s=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}.`}:r?.pythonRequirement?{...e.python,status:e.python.status==="error"?"error":"warn",details:`Project ${r.name} declares requires-python ${r.pythonRequirement.specifier}, but compatibility could not be evaluated.`}:e.python;return {...e,python:i?s:lt(e.python,"Python is optional because this scope has no detected Python project."),poetry:i?e.poetry:lt(e.poetry,"Poetry is not applicable to this project scope."),pipx:i?e.pipx:lt(e.pipx,"pipx is not applicable to this project scope."),go:n?e.go:lt(e.go,"Go is not applicable to this project scope."),rapidkitCore:/not installed/i.test(e.rapidkitCore.message)||!i&&e.rapidkitCore.status!=="error"?lt(e.rapidkitCore,"RapidKit Core is an optional engine for Python-backed kits and modules; Workspai CLI diagnostics remain available without it."):e.rapidkitCore}}function Dr(e){let i=(e.probes??[]).filter(s=>s.status==="warn").length,n=e.issues.some(s=>s.toLowerCase().includes("environment file missing")),o=(e.probes??[]).some(s=>s.id==="surface-env-contract"),r=(e.probes??[]).some(s=>s.id==="surface-security-hygiene");return e.hasEnvFile===false&&!n&&!o&&(i+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&!r&&(i+=1),i}function Rr(e){let t=e.coreVersion?.split(".")[0],i=e.npmVersion?.split(".")[0];return !t||!i?false:t!==i}var Sr="doctor-project-scan-v2",Er="doctor-project-scan-policy-v5",Wi=s.doctorWorkspaceCache.schemaVersion,Ar=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v2",generatedBy:"workspai",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"}),dt=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 Ye(){return {...Ar}}function Tt(e){let t=e.profile?.trim();return t&&t in dt?{...dt[t]}:e.strict?{...dt.release}:e.ci?{...dt.ci}:{...dt.local}}function It(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function Fr(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 $r(e,t){let i=Fr(e),n=Date.parse(t),o=typeof i.ttlSeconds=="number"?i.ttlSeconds*1e3:null,r=o!==null&&Number.isFinite(n)?new Date(n+o).toISOString():void 0,s=!Number.isFinite(n)||o!==null&&!r?"unknown":o!==null&&Date.now()>n+o?"stale":"fresh";return {category:i.category,generatedAt:t,ttlSeconds:i.ttlSeconds,...r?{expiresAt:r}:{},status:s,verifyBeforeUse:i.category!=="structure"||s!=="fresh",reason:i.reason}}function Ir(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 Hi(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 Nr(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 Mr(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:Ei(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:Ei([...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 gn(e,t){let i=$r(e,e.freshness?.generatedAt??t),n=e.issueClass??Ir(e),o=e.operationalImpact??Nr(e,n),r=Mr({probe:e,freshness:i});return {...e,freshness:i,issueClass:n,operationalImpact:o,repairIntent:r}}function Tr(e,t){Array.isArray(e.probes)&&(e.probes=e.probes.map(i=>gn(i,t)));}function Or(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 Nt(e,t=new Date().toISOString()){Tr(e,t),Vr(e,e.path),Or(e);}function Li(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.`}],r=new Set(i.proofs.map(s=>`${s.kind}:${s.role}:${s.ref}`));for(let s of o){let c=`${s.kind}:${s.role}:${s.ref}`;r.has(c)||i.proofs.push(s);}}}function yn(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,r=i.filter(a=>a.category==="state").length,s=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:r,verifyBeforeUseProbeCount:s,...c?{oldestProbeGeneratedAt:c}:{}}}function qi(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Vi(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 zi(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 r=e.system?.[o.id]?.status;!r||r===o.current.status||n.push({id:o.id,from:r,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,qi(y.issues));}let r=0,s=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?(r+=v-b,c.add(y)):v<b&&(s+=b-v,a.add(y));}let d=It(e.healthScore),p=It(t.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:r,resolvedIssueCount:s,netIssueDelta:r-s,scoreDeltaPercent:d===null||p===null?null:p-d,systemStatusChanges:zi(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 Kr(e,t){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=qi(e.project?.issues),n=t.project.issues.length,o=Math.max(n-i,0),r=Math.max(i-n,0),s=It(e.healthScore),c=It(t.healthScore),a=t.project.path||t.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:r,netIssueDelta:o-r,scoreDeltaPercent:s===null||c===null?null:c-s,systemStatusChanges:zi(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,cliResolution:t.cliResolution}),regressedProjects:o>0?[a]:[],improvedProjects:r>0?[a]:[]}}function Ji(e){let t=e??[],i=0,n=0;for(let s of t){if(s.scope==="project-scoped"){i+=1;continue}(s.scope==="workspace-aggregate"||s.scope==="host-system")&&(n+=1);}let o=i>0&&n>0?1:0,r=o>0?"mixed":i>0?"scoped":n>0?"aggregated":"unknown";return {scopedCount:i,aggregatedCount:n,mixedCount:o,dominantScope:r}}function Q(e,t){return b$6()?`Set-Location -LiteralPath "${e.replace(/"/g,'`"')}"; ${t}`:`cd '${e.replace(/'/g,`'"'"'`)}' && ${t}`}function Br(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,e.uvProject?`uv sync --project ${e.uvProject}`:"uv sync"):Q(e.projectPath,b$6()?"py -3 -m venv .venv":"python3 -m venv .venv")}async function Gr(e){let t=b$6()?["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 Wr(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}),r=`${o.stdout??""}
18
- ${o.stderr??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(r)return r[1]}catch{}}function Hr(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 Lr(e){return e==="Microsoft Agent Framework"||e==="OpenAI Agents SDK"?"agent":e==="OpenRouter"?"gateway":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 qr(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 Vr(e,t){let i=D(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function pt(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=Hr(t),e.projectKind=Lr(t),e.runtimeFamily=qr(t);}function Ui(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 hn(e){switch(e.key){case "microsoft-agent-framework":return "Microsoft Agent Framework";case "openai-agents":return "OpenAI Agents SDK";case "openrouter":return "OpenRouter";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 zr(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 Jr(e,t){e.framework=hn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=Ui(t.runtime);}function U(e,t){e.framework=hn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind=t.key==="microsoft-agent-framework"||t.key==="openai-agents"?"agent":t.key==="openrouter"?"gateway":t.key==="tauri"||t.key==="electron"?"desktop":t.key==="vscode-extension"?"extension":zr(t)?"generic":"backend",e.runtimeFamily=Ui(t.runtime);}function Ur(e){let t=e.dependencies,i=e.scripts??{},n=(e.kitName??"").toLowerCase(),o=s=>!!t[s],r=Object.values(i).filter(s=>typeof s=="string").join(" ").toLowerCase();return o("next")||r.includes("next ")?{framework:"Next.js",confidence:"high"}:o("nuxt")||r.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:o("@nestjs/core")||n.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:o("@openai/agents")||n.startsWith("agent.openai.")?{framework:"OpenAI Agents SDK",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")||r.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 Yr(e,t){let i=m$1(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:hn(i),confidence:i.confidence}}async function Ai(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__"]),r=0,s=0,c=2e4,a=32*1024*1024;for(;n.length>0&&r<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(r+=1,i.update(`f:${b}:${v.size}:${v.mtimeMs}\0`),v.size<=262144&&s+v.size<=a){let C=await m.readFile(y).catch(()=>null);C&&(s+=C.length,i.update(C));}if(r>=c)break}}}return i.update(`files:${r}:bytes:${s}: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 Zr(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 mt(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 mt(e)&&i.add(e);let r=await c$2(e);for(let a of r.summary.projects){let l=d(e,a.relativePath);await o(l)&&(i.add(l),n.add(l));}let s=await a$4(e);for(let a of s){let l=d(e,a.relativePath||a.name,a.path?{absolutePath: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)?mt(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 xs(e,3,t)).forEach(l=>i.add(l)),i.size===0&&!await b$2(e)&&await o(e)&&i.add(e),Array.from(i).sort((a,l)=>a.localeCompare(l))}catch{return []}}async function Xr(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(Ai)),r=await Promise.all(t.map(async s=>{let c=await Promise.all(n.map(a=>Ai(u.join(s,a))));return `${s}::${c.join("|")}`}));return [Sr,Er,...o,...r].join("||")}async function Qr(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!==Wi)return null;let o=Date.parse(n.generatedAt),r=Number(process.env.WORKSPAI_DOCTOR_CACHE_MAX_AGE_SECONDS),s=Number.isFinite(r)&&r>=0?r:300;return !Number.isFinite(o)||Date.now()-o>s*1e3?null:n}catch{return null}}async function es(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 ts(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),r=0,s=Array.from({length:Math.min(n,e.length)},async()=>{for(;r<e.length;){let c=r;r+=1;let a=e[c];if(a===void 0)break;o[c]=await t(a);}});return await Promise.all(s),o}async function ns(e,t,i){let n=u.join(e,un);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 r=t.projects.map(ee),s=r.reduce((d,p)=>d+p.blockingFindings,0),c=r.reduce((d,p)=>d+p.advisoryFindings,0),a=Fe(t.projects,[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore,t.cliResolution]),l=f$1({schemaVersion:a$8,evidenceType:"workspace",contract:Ye(),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:s,advisoryFindings:c,projectAdvisoryWarningProjects:r.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:gt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:o.slice(0,12),runId:e$1()});return d$1(l),await h(e,un,l),n}catch(o){throw o}}async function bn(e=process.cwd()){let[t,i,n,o,r,s]=await Promise.all([is(),os(),rs(),ss(),as(e),Si()]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:r,cliResolution:s}}async function is(){let e=j$1(),t;for(let i of e)try{let n=i==="py"?["-3","--version"]:["--version"],{stdout:o,stderr:r}=await execa(i,n,{timeout:3e3,reject:false}),c=`${o??""}
19
- ${r??""}`.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 os(){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 Bi())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 rs(){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 ss(){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 as(e=process.cwd()){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],n=[],o=Cr(t,e);for(let{location:s,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:s,path:c,version:d[1]}):n.push({location:s,path:c,version:d[1],reason:ut(p.stderr||p.stdout)});}}}}catch(a){await m.pathExists(c)&&n.push({location:s,path:c,reason:ut(a instanceof Error?a.message:String(a))});continue}if(i.length>0){let s=i.filter(a=>a.location!=="Workspace (launcher)");if(s.length>0){let a=Pr(s),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:s,exitCode:c}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(c===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let a=s.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:ut(l.stderr||l.stdout)});}}}catch{}try{let{stdout:s,exitCode:c}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(c===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let a=s.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:ut(l.stderr||l.stdout)});}}}catch{}let r=j$1();for(let s of r)try{let c=s==="py"?["-3","-c","import rapidkit_core; print(rapidkit_core.__version__)"]:["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{stdout:a,exitCode:l}=await execa(s,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(s,s==="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 ${s} environment`};n.push({location:`${s} environment`,path:`${s} -m rapidkit`,version:d,reason:ut(y.stderr||y.stdout)});}}}catch{continue}if(n.length>0){let s=n[0];return {status:"error",message:s.version?`RapidKit Core ${s.version} installed but unusable`:"RapidKit Core installed but unusable",details:`${s.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 ut(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 nn(e);t.hasDocker=n.rootDockerfile||n.nestedDockerfile||n.compose;let o=u.join(e,"tests"),r=u.join(e,"test"),s=u.join(e,"src","test"),c=await m.pathExists(o)||await m.pathExists(r)||await m.pathExists(s),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 ci(e,i)),t.runtimeFamily==="python"&&!t.hasTests&&(t.hasTests=await ms(e)),t.runtimeFamily==="node"||t.runtimeFamily==="bun")t.hasCodeQuality=await ai(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 hi({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 cs(e){return Ki([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 ls(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}}function ds(e,t){let i=new Set(["pip","setuptools","wheel"]),n=t.split(".")[0].replaceAll("_","-").toLowerCase();return e?.some(o=>{if(typeof o.name!="string")return false;let r=o.name.replaceAll("_","-").toLowerCase();return n?r===n:!i.has(r)})??false}async function cn(e){for(let t of cs(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=ls(`${n.stdout??""}
20
- ${n.stderr??""}`),r=ds(o,e.frameworkImport);return {interpreter:t,coreVersion:i,dependenciesInstalled:r}}catch{return {interpreter:t,coreVersion:i,dependenciesInstalled:false}}}return {dependenciesInstalled:false}}async function ps(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]})),...Bi().map(o=>({executable:o,args:t}))],n=new Set;for(let o of i){let r=`${o.executable}\0${o.args.join("\0")}`;if(!n.has(r)&&(n.add(r),!(u.isAbsolute(o.executable)&&!await m.pathExists(o.executable))))try{let s=await execa(o.executable,o.args,{cwd:e,timeout:Math.max(a$9(),15e3),reject:false,shell:c$1()}),c=s.stdout.trim();if(s.exitCode===0&&c&&await m.pathExists(c))return c}catch{}}}async function us(e,t,i,n){let o=u.join(e,".venv");if(await m.pathExists(o))return {environmentPath:o,...await cn({environmentPath:o,frameworkImport:t})};if(n){let r=u.join(e,n,".venv");if(await m.pathExists(r))return {environmentPath:r,...await cn({environmentPath:r,frameworkImport:t})}}if(i){let r=await ps(e);if(r)return {environmentPath:r,...await cn({environmentPath:r,frameworkImport:t})}}return {dependenciesInstalled:false}}function _(e,t){e.probes||(e.probes=[]);let i=gn(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 xe(e,t){return (await Promise.all(t.map(i=>m.pathExists(u.join(e,i))))).some(Boolean)}async function Yi(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 ms(e){if(await xe(e,["pytest.ini","tox.ini","noxfile.py","conftest.py","tests","test"]))return true;let t=await Yi(e);return /\[tool\.pytest(?:\.|\])|\bpytest\b|\bunittest\b|\btox\b|\bnox\b/i.test(t)}async function de(e,t){let i=new Set(t.ignoreDirs??["node_modules",".git","bin","obj","dist"]),o=(t.under&&t.under.length>0?t.under:["."]).map(r=>u.join(e,r));for(;o.length>0;){let r=o.shift(),s;try{s=await m.readdir(r,{withFileTypes:true});}catch{continue}for(let c of s){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(r,c.name));}}return false}async function fs(e,t){let i=t.runtimeFamily||"unknown";if(!(t.projectKind==="backend"||t.projectKind==="generic"||t.projectKind==="gateway"||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 xe(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 xe(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 xe(e,["src/main/java/Application.java","src/main/kotlin/Application.kt"])||await de(e,{suffix:"Application.java",under:["src/main/java"]})||await de(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 xe(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 xe(e,["Program.cs","src/Program.cs"])||await de(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 r={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(!r)return;let s=(i==="c"||i==="cpp")&&e$3(e),c=s||await xe(e,r.dependencyMarkers);_(t,{id:`adapter-${i}-dependency-contract`,label:r.dependencyLabel,status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?s?`${r.dependencyLabel} detected across multiple native workspace components.`:`${r.dependencyLabel} detected.`:`${r.dependencyLabel} is missing.`,recommendation:c?void 0:`Add a runtime-native dependency/build contract: ${r.dependencyMarkers.join(", ")}.`,issueClass:"dependency",operationalImpact:"ci-risk"});let a=await xe(e,r.entrypointMarkers);!a&&i==="elixir"&&(a=await de(e,{name:"application.ex",under:["lib"]})),!a&&i==="scala"&&(a=await de(e,{name:"Main.scala",under:["src/main/scala"]})||await de(e,{name:"Application.scala",under:["src/main/scala"]})),!a&&i==="kotlin"&&(a=await de(e,{name:"Application.kt",under:["src/main/kotlin"]})||await de(e,{name:"Main.kt",under:["src/main/kotlin"]})),_(t,{id:`adapter-${i}-boot-entrypoint`,label:r.entrypointLabel,status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?`${r.entrypointLabel} detected.`:`${r.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 gs(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),r=Array.isArray(o?.checks)?o.checks:[];for(let s=0;s<r.length;s+=1){let c=r[s]||{},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-${s+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"||t.projectKind==="gateway"))return;let n=await xe(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"]},r=t.runtimeFamily||"unknown",s=o[r]||o.unknown,c=false;for(let y of s)if(await m.pathExists(u.join(e,y))){c=true;break}let a=await Yi(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=await h$1(e),p=d||/\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:d||!p?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:p?"applicable":"not-applicable",reason:d?"Health endpoint/config markers detected.":p?"No explicit runtime health endpoint markers detected.":"No HTTP service runtime intent was detected; an endpoint health surface is not currently applicable.",recommendation:d||!p?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await fs(e,t);}async function ys(e,t,i,n){let o=await li({projectPath:e,detection:n,packageJsonData:i});for(let r of o)_(t,r);}async function X(e,t,i){let n=await pi({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),r=Array.isArray(o?.probes)?o.probes:[];for(let s=0;s<r.length;s+=1){let c=r[s]||{},a=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`custom-probe-${s+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 gs(e,t);}async function hs(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 K of E.issues)n.issues.push(`${K.message} (${K.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 s=null;try{for(let S of u$1(e,"project.json")){if(!await m.pathExists(S))continue;s=await m.readJson(S);let E=typeof s?.name=="string"?s.name:typeof s?.slug=="string"?s.slug:void 0;E?.trim()&&(n.name=E.trim());let K=j$2(s)?void 0:s?.kit_name||s?.kit;K&&(n.kit=K);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),pe=Date.now()-E.mtime.getTime(),te=Math.floor(pe/(1e3*60*60*24));n.lastModified=te===0?"today":`${te} day${te>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),B=await m.pathExists(D),$=await m.pathExists(b),V=await m.pathExists(v),ce=await m.pathExists(C)||await m.pathExists(h),H=await m.pathExists(y),G=await m.pathExists(w)||await m.pathExists(P),T=k&&(await m.pathExists(R)||await m.pathExists(x)||typeof s?.packageManager=="string"&&(s?.packageManager).toLowerCase().startsWith("bun@")),ye=(await m.readdir(e).catch(()=>[])).some(S=>S.endsWith(".csproj")||S.endsWith(".sln")),oe=k||A||j||B||$||V||ce||H||G||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"))||ye||await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),re=oe?[]:l(e),Ge=!oe&&re.length>=2,he=m$1(e,s??null),z=he.runtime;if(Ge)return U(n,he),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(he.runtime==="c"||he.runtime==="cpp")return U(n,he),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"){U(n,m$1(e,s??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"){U(n,m$1(e,s??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 K=S?b$6()?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies";n.fixCommands?.push(Q(e,K));}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"){U(n,m$1(e,s??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")),K=await m.pathExists(u.join(e,"mvnw"))||await m.pathExists(u.join(e,"mvnw.cmd")),pe=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(!K)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&&!pe)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 te=u.join(e,"target"),le=u.join(e,"build","libs"),Ie=u.join(e,".workspai","cache","java","m2"),Ne=u.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await m.pathExists(te)||await m.pathExists(le)||await m.pathExists(Ie)||await m.pathExists(Ne),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let se=S?K?b$6()?".\\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":pe?b$6()?".\\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,se));}let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);let W=u.join(e,"src","main","resources","application.yml");if(await m.pathExists(W))try{let se=await m.readFile(W,"utf-8");/include:\s*[^\n]*health/i.test(se)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(se)||(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"){U(n,m$1(e,s??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 K=u.join(e,".env");return n.hasEnvFile=await m.pathExists(K),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="elixir"){U(n,m$1(e,s??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 K=u.join(e,".env");return n.hasEnvFile=await m.pathExists(K),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="clojure"){U(n,m$1(e,s??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,".cpcache"),E=u.join(e,"target"),K=await m.pathExists(C)||await m.pathExists(h);return n.depsInstalled=await m.pathExists(S)||await m.pathExists(E)||K,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"){U(n,m$1(e,s??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"){U(n,m$1(e,s??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??{}},K=S?.scripts??{},pe=typeof s?.kit_name=="string"?s.kit_name.toLowerCase():typeof s?.kit=="string"?s.kit.toLowerCase():"",te=d$2(e,s),le=Ur({dependencies:E,scripts:K,kitName:pe});if(T)pt(n,"Bun","high");else {let I=m$1(e,s??null);I.key==="nestjs"||I.key==="express"||I.key==="fastify"||I.key==="koa"||I.key==="tauri"||I.key==="electron"||I.key==="vscode-extension"?U(n,I):te.key!=="unknown"?Jr(n,te):I.key!=="unknown"&&I.key!=="node"?U(n,I):pt(n,le.framework,le.confidence);}n.venvActive=true;let Ie=n.projectKind==="agent"?"agents/primary":void 0,Ne=u.join(e,Ie??"","node_modules");if(await m.pathExists(Ne))try{let W=(await m.readdir(Ne)).filter(se=>!se.startsWith(".")&&!se.startsWith("_"));n.depsInstalled=W.length>0;}catch{n.depsInstalled=false;}if(!n.depsInstalled){n.issues.push("Dependencies not installed (node_modules empty or missing)");let I=typeof S?.packageManager=="string"?S.packageManager.split("@")[0]:void 0,W=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":Ie?`npm install --prefix ${Ie}`:"npm install";n.fixCommands?.push(Q(e,W));}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(se=>m.pathExists(u.join(e,se))))).some(Boolean))n.hasEnvFile=true;else {let se=u.join(e,".env.example");await m.pathExists(se)&&(n.hasEnvFile=false);}}else {let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);}if(n.projectKind==="frontend")n.modulesHealthy=await Qt(e),n.missingModules=[];else {let I=u.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(I))try{let W=await m.readdir(I);n.modulesHealthy=W.length>0;}catch{n.modulesHealthy=false;}}return await Y(e,n,S),await X(e,n,S),n.projectKind==="frontend"?await ys(e,n,S,te.key!=="unknown"?te:d$2(e,s)):await Z(e,n),await q(e,n),n}if(z==="python"){if(he.key==="microsoft-agent-framework"||he.key==="openai-agents"||he.key==="openrouter")U(n,he);else {let ae=await Yr(e,s);pt(n,ae.framework,ae.confidence);}let S="fastapi";n.framework==="Django"?S="django":n.framework==="Flask"?S="flask":n.framework==="Python"?S="":n.framework==="Microsoft Agent Framework"?S="agent-framework-core":n.framework==="OpenAI Agents SDK"?S="openai-agents":n.framework==="OpenRouter"&&(S="");let E=n.projectKind==="agent"?"agents/primary":void 0,K=E?u.join(e,E,"pyproject.toml"):a,pe=await Bt(K),te=/\[tool\.poetry\]/.test(pe),le=await Gr(e),Ie=le?"project-script":E?"uv":te?"poetry":await m.pathExists(u.join(e,"uv.lock"))?"uv":"venv",Ne=Br({projectPath:e,manager:Ie,...le?{projectScript:le}:{},...E?{uvProject:E}:{}}),I=await us(e,S,te,E);n.venvActive=!!I.environmentPath,n.depsInstalled=I.dependenciesInstalled,n.coreInstalled=!!I.coreVersion,n.coreVersion=I.coreVersion;let W=pe.match(/^\s*requires-python\s*=\s*["']([^"']+)["']/m)?.[1];if(W){let ae=await Wr(I.interpreter),ue=ae?Ci(ae,W):{version:"unknown",satisfied:null};if(n.pythonRequirement={specifier:W,...ae?{detectedVersion:ae}:{},satisfied:ue.satisfied},ue.satisfied===false){let We=`Python ${ue.version} does not satisfy requires-python ${W}`;n.issues.push(We),_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"fail",severity:"error",scope:"project-scoped",reason:We,recommendation:le?`Install a compatible Python interpreter, then run the repository-authored ${le} setup command.`:"Install a Python interpreter satisfying requires-python, then materialize the project environment.",issueClass:"runtime",operationalImpact:"release-risk"});}else ue.satisfied===null?_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"warn",severity:"warn",scope:"project-scoped",reason:ae?`Python ${ae} could not be evaluated against requires-python ${W}.`:`No executable Python version could be verified against requires-python ${W}.`,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 ${ue.version} satisfies requires-python ${W}.`,issueClass:"runtime",operationalImpact:"none"});}I.environmentPath?I.interpreter?n.depsInstalled||(n.issues.push("Dependencies not installed"),n.fixCommands?.push(Ne)):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Ne));let se=u.join(e,".env");n.hasEnvFile=await m.pathExists(se);let ht=u.join(e,"src"),Gt=u.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(ht)){let ae=u.join(ht,"__init__.py"),ue=await m.pathExists(ae),We=ue?false:await ws(ht);!ue&&!We&&(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await m.pathExists(Gt))try{let ae=await Xi(Gt);for(let ue of ae){let We=u.join(Gt,ue,"__init__.py");await m.pathExists(We)||(n.modulesHealthy=false,n.missingModules.push(`modules/${ue}/__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"){U(n,m$1(e,s??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"){U(n,m$1(e,s??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 K=u.join(e,".env");return n.hasEnvFile=await m.pathExists(K),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="dotnet"){U(n,m$1(e,s??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"obj"),E=u.join(e,"src","obj"),K=u.join(e,"agents","primary","obj"),pe=u.join(e,"agents","primary","tests","obj"),te=u.join(e,"packages.lock.json");n.depsInstalled=await m.pathExists(S)||await m.pathExists(E)||await m.pathExists(K)||await m.pathExists(pe)||await m.pathExists(te),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(Q(e,n.framework==="Microsoft Agent Framework"?"dotnet restore agents/primary/tests/Primary.Tests.csproj":"dotnet restore")));let le=u.join(e,".env");return n.hasEnvFile=await m.pathExists(le),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 de(e,{suffix:".cpp",under:["src","."]});return pt(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 pt(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 Zi(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 bs(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=[],r=(a,l)=>{l&&!o.includes(a)&&o.push(a);},s=await i("package.json");return r("bun",s&&(await i("bun.lock")||await i("bun.lockb"))),r("deno",await i("deno.json")||await i("deno.jsonc")),r("node",s&&!o.includes("bun")),r("python",await i("pyproject.toml")||await i("requirements.txt")),r("go",await i("go.mod")),r("kotlin",await i("build.gradle.kts")&&await de(e,{suffix:".kt",under:["src"]})),r("java",await i("pom.xml")||await i("build.gradle")||await i("build.gradle.kts")&&!o.includes("kotlin")),r("rust",await i("Cargo.toml")),r("elixir",await i("mix.exs")),r("clojure",await i("deps.edn")||await i("project.clj")),r("scala",await i("build.sbt")),r("php",await i("composer.json")),r("ruby",await i("Gemfile")),r("dotnet",n.some(a=>a.endsWith(".csproj"))||await i("global.json")),(await i("CMakeLists.txt")||await i("meson.build"))&&(r("cpp",await de(e,{suffix:".cpp",under:["src","."]})),r("c",await de(e,{suffix:".c",under:["src","."]})),!o.includes("c")&&!o.includes("cpp")&&r("cpp",true)),o.length>0?o:["unknown"]}async function ks(e,t){if(t.projectKind==="extension")return "plugin";if(t.projectKind==="agent")return "application";if(t.projectKind==="gateway")return "service";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")),r=await m.pathExists(u.join(e,"include")),s=(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&&s)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&&r?"library":t.projectKind==="backend"?"service":"unknown"}function vs(e){let t=e.probes??[],i=t.map((s,c)=>s.id==="config-surface"?c:-1).filter(s=>s>=0);t.some(s=>s.id==="surface-env-contract")&&(e.probes=t.filter((s,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(s=>{let c=s.id==="frontend-framework-config"||s.id==="frontend-source-tree"||s.id.startsWith("frontend-script-");return s.id==="migration-surface"||s.id==="runtime-health-surface"||s.id==="surface-kubernetes-readiness"||c||s.id.endsWith("-boot-entrypoint")||s.id==="runtime-security-tooling"&&e.probes?.some(l=>l.id==="surface-security-hygiene")||s.id==="surface-env-contract"&&s.status!=="pass"?(s.repairCapability?.command&&o.add(s.repairCapability.command),{...s,status:"pass",severity:"info",applicability:"not-applicable",reason:`${s.label} is not required for the detected ${e.projectArchetype} archetype.`,recommendation:void 0,repairCapability:void 0,repairIntent:void 0}):s});let r=new Set((e.probes??[]).map(s=>s.repairCapability?.id).filter(s=>!!s));e.repairCapabilities=(e.repairCapabilities??[]).filter(s=>r.has(s.id)),e.fixCommands=(e.fixCommands??[]).filter(s=>!o.has(s));}async function Ot(e,t={}){let i=Zi(await hs(e,t));delete i._freshDependencyAudit,Fs(i),i.runtimeFamilies=await bs(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$4(e);if(n==="gateway"?i.projectKind="gateway":n==="agent"?i.projectKind="agent":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 ks(e,i),i.projectArchetype==="platform"){let o=i.probes?.find(r=>r.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 vs(i),Nt(i),i}async function ws(e){for(let t of await Xi(e))if(!(t==="__pycache__"||t.startsWith("."))&&await m.pathExists(u.join(e,t,"__init__.py")))return true;return false}async function Xi(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 mt(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 js(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 xs(e,t,i){let n=new Set,o=[{dir:e,depth:0}];for(;o.length>0;){let r=o.shift();if(!r)break;try{let s=await m.readdir(r.dir);for(let c of s){if(js(c,i))continue;let a=u.join(r.dir,c),l;try{l=await m.stat(a);}catch{continue}if(l.isDirectory()){if(await mt(a)){n.add(a);continue}r.depth<t&&o.push({dir:a,depth:r.depth+1});}}}catch{continue}}return Array.from(n)}async function ft(e){let t=a$1(e);if(t)return t;let i=u.resolve(e),n=u.parse(i).root;for(;;){if(await Ds(i))return i;if(i===n)return null;i=u.dirname(i);}}async function Cs(e){let t=u.resolve(e),i=await ft(t),n=i??u.parse(t).root;for(;;){if(await mt(t)||await Ps(t)&&(!i||t!==i))return t;if(t===n)break;t=u.dirname(t);}return null}function Fi(e){let t=u.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function Ps(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 Ds(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 kn(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=Dr(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,r=i.warnings+n.warnings,s=i.errors+n.errors,c=Fe(t,e),a=i.total+n.total;return {total:a,passed:o,warnings:r,errors:s,verdict:s>0?"blocked":r>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,r=e.diagnosis?.coverage.blockingFindings??o+e.issues.length,s=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:r,advisoryFindings:s,unknownFindings:c,contradictionFindings:a,verdict:r>0?"blocked":s+c+a>0?"attention":"passed"}}function Fe(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,r)=>o+(r?.coverage.blockingFindings??0),0),advisoryFindings:i.reduce((o,r)=>o+(r?.coverage.advisoryFindings??0),0),unknownFindings:i.reduce((o,r)=>o+(r?.coverage.unknownFindings??0),0),contradictionFindings:i.reduce((o,r)=>o+(r?.coverage.contradictionCount??0),0),repairableFindings:i.reduce((o,r)=>o+(r?.coverage.repairableFindings??0),0),manualFindings:i.reduce((o,r)=>o+(r?.coverage.manualFindings??0),0),unsupportedFindings:i.reduce((o,r)=>o+(r?.coverage.unsupportedFindings??0),0),dependencyAdvisorySubjects:e.reduce((o,r)=>o+(r.dependencyAudit?.subjects.length??0),0),dependencyVulnerabilityFindings:e.reduce((o,r)=>o+(r.dependencyAudit?.findingCount??0),0),notApplicableChecks:e.reduce((o,r)=>o+(r.probes??[]).filter(s=>s.applicability==="not-applicable").length,0)+t.filter(o=>o.applicability==="not-applicable").length,systemErrors:t.filter(o=>o.status==="error").length}}function Rs(e){let t=ee(e);e.probeSummary=t,e.verdict=t.verdict;}function Qi(e,t,i={}){let n=[];for(let r of e)n.push({id:r.id,label:r.label,status:r.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:r.result.details||r.result.message});let o=[...t].sort((r,s)=>{let c=`${r.path||""}|${r.name||""}`.toLowerCase(),a=`${s.path||""}|${s.name||""}`.toLowerCase();return c.localeCompare(a)});for(let r of o){if(Rs(r),r.diagnosis){for(let s of (r.probes??[]).filter(c=>c.status==="pass"))n.push({id:`project:${r.name}:probe:${s.id}`,label:`${r.name} \xB7 ${s.label}`,status:"ok",scope:"project-scoped",policyRuleId:`project-probe-${s.id}`,reason:s.reason});for(let s of r.diagnosis.findings)n.push({id:`project:${r.name}:diagnosis:${s.id}`,label:`${r.name} \xB7 ${s.label}`,status:s.status==="blocking"?"error":"warn",scope:"project-scoped",policyRuleId:`project-diagnosis-${s.issueClass}`,reason:s.symptom});}else {for(let s of r.probes??[])n.push({id:`project:${r.name}:probe:${s.id}`,label:`${r.name} \xB7 ${s.label}`,status:s.status==="pass"?"ok":s.status==="warn"?"warn":"error",scope:"project-scoped",policyRuleId:`project-probe-${s.id}`,reason:s.reason});for(let[s,c]of r.issues.entries())n.push({id:`project:${r.name}:legacy:${s+1}`,label:`${r.name} \xB7 Runtime issue`,status:"error",scope:"project-scoped",policyRuleId:"project-runtime-issue",reason:c});}(r.probes?.length??0)===0&&r.issues.length===0&&n.push({id:`project:${r.name}`,label:`Project ${r.name}`,status:"ok",scope:"project-scoped",policyRuleId:"project-checks-passed",reason:"Project checks passed"});}if(i.includeWorkspaceAggregateRules){let r=t.reduce((a,l)=>a+ee(l).blockingFindings,0),s=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:r>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:r>0?`${r} blocking project issue(s) detected.`:"No blocking project issues detected."}),n.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:s>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:s>0?`${s} advisory warning(s) detected.`:"No advisory warnings detected."});}return n}async function ln(e$1,t$2=true,i=Tt({}),n=false){let o=u.basename(e$1),r=await a$2(e$1);if(typeof r?.name=="string"&&r.name.trim().length>0)o=r.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[s,c]=await Promise.all([bn(e$1),Zr(e$1)]),a={workspacePath:e$1,workspaceName:o,python:s.python,poetry:s.poetry,pipx:s.pipx,go:s.go,rapidkitCore:s.rapidkitCore,cliResolution:s.cliResolution,projects:[],policyProfile:i};e.debug(`Workspace scan found ${c.length} project(s)`);let l=await Xr(e$1,c),d=u.join(e$1,t$1.doctorWorkspaceCache),p=t$2&&!n?await Qr(d,l):null;if(p){a.projects=p.projects;for(let h of a.projects)Zi(h),Nt(h,p.generatedAt);a.projectScanCached=true,e.debug(`Workspace project health cache hit: ${d}`);}else try{let h=new Date().toISOString(),w=await ts(c,P=>Ot(P,{allowNonRapidkit:true,freshAudit:n}));for(let P of w)Nt(P,h);a.projects=w,a.projectScanCached=false,await es(e$1,{schemaVersion:Wi,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=Gi({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 an({workspacePath:e$1,projectPath:h.path,projectName:h.name,probes:Hi(h),issues:h.issues}),Li(h);}));let b=[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore,a.cliResolution];if(a.healthScore=kn(b,a.projects),a.scoreBreakdown=Qi([{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=Ji(a.scoreBreakdown),a.evidenceFreshness=yn(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,un),C=v?await Vi(v,"workspace"):null;return a.driftDelta=_r(C,a),a.evidencePath=await ns(e$1,a,p?d:null),a.receiptPath=await no(e$1,to({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 $i(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 eo(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 Ss(e,t){let i$1=e||t.projectPath,n=t$1.doctorProject,o=eo(e,t.projectPath),r=u.join(i$1,n);try{let s=[...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=Fe([t.project],[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore,t.cliResolution]),l=f$1({schemaVersion:b$5,evidenceType:"project",contract:Ye(),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:gt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:s,runId:e$1()});return d$1(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),r}catch(s){throw s}}function to(e){let t=new Date().toISOString(),i=e.freshness??yn(e.projects,t),n=Fe(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),r=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}:{}}))),s$1=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&&s$1>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:r,next:a,artifacts:{evidence:e.evidencePath??null,receipt:u.join(e.scopeRoot,t$1.doctorReceipt)}}}async function no(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 mn(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 Ze(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 Xe(e,t,i){try{await j(e,g$1(t,i));}catch{}}async function Ii(e,t=Tt({}),i=false){let n=await ft(e),o=await bn(n||e),r=await Ot(e,{allowNonRapidkit:true,freshAudit:i}),s=Gi(o,[r]);Nt(r),r.graphDiagnosis=await an({workspacePath:n||void 0,projectPath:e,projectName:r.name,probes:Hi(r),issues:r.issues}),Li(r);let c=kn([s.python,s.poetry,s.pipx,s.go,s.rapidkitCore,s.cliResolution],[r]),a={workspacePath:n||void 0,projectPath:e,projectName:u.basename(e),python:s.python,poetry:s.poetry,pipx:s.pipx,go:s.go,rapidkitCore:s.rapidkitCore,cliResolution:s.cliResolution,project:r,healthScore:c,policyProfile:t};a.scoreBreakdown=Qi([{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=Ji(a.scoreBreakdown),a.evidenceFreshness=yn([a.project],new Date().toISOString());let l=await g(e,t$1.doctorProject),d=n?await g(n,eo(n,e)):null,p=l??d,y=p?await Vi(p,"project"):null;a.driftDelta=Kr(y,a),a.evidencePath=await Ss(n||void 0,a);let b=n||e;return a.receiptPath=await no(b,to({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 Ae(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 r=o.version?f.cyan(` -> ${o.version}`):"";console.log(` ${f.cyan("\u2022")} ${f.gray(o.location)}: ${f.dim(o.path)}${r}`);}),e.details&&console.log(` ${f.gray(e.details)}`);}function Ft(e,t){let i=Mt(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 Es(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 Ni(e,t,i={}){let n=ee(e),o=n.verdict==="blocked"?"\u274C":n.verdict==="attention"?"\u26A0\uFE0F":"\u2705",r=n.verdict==="blocked"?f.red:n.verdict==="attention"?f.yellow:f.green;if(console.log(`
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(r.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")&&r.remediation&&(r.remediation=await Zo(e.projectPath,r.remediation),r.findingCount>0&&!r.remediation.compatibleFixAvailable)){let a=await Jo(e.projectPath,o.stdout);r.remediation.resolutionCandidates=a.length>0?a:ui(r.subjects);}let s=r.severityCounts.moderate+r.severityCounts.high+r.severityCounts.critical+r.severityCounts.unknown,c=r.remediation??(r.findingCount===0?{disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]}:{disposition:"unknown",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[],resolutionCandidates:ui(r.subjects)});return {...n,invocation:i.invocation,exitCode:o.exitCode,findingCount:r.findingCount,blockingFindingCount:s,severityCounts:r.severityCounts,subjects:r.subjects,remediation:c,status:r.findingCount>0?"vulnerable":"clean",reason:r.findingCount>0?`${i.tool} reported ${r.findingCount} known dependency vulnerability finding(s).`:`${i.tool} completed without known dependency vulnerability findings.`}}catch(o){return {...n,invocation:i.invocation,status:gi(o)?"tool-unavailable":"failed",reason:gi(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 hi(e){let t=await qo(e.projectPath,e.runtime);e.fresh&&_e.delete(t);let i=_e.get(t);if(i)return i;let n=cr(e);for(_e.set(t,n);_e.size>Wo;){let o=_e.keys().next().value;if(!o)break;_e.delete(o);}try{return await n}catch(o){throw _e.delete(t),o}}var rn="doctor-graph-diagnosis.v1";var wi="Graph paths identify evidence-backed structural reachability and verification candidates; they do not prove runtime causality or that every affected surface has been discovered.",ki={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"]},lr=new Set(["project","service","api","endpoint","schema","database","queue","container","deployment","pipeline","environment","document","decision","test-suite","owner"]),dr=new Set(["test-suite","pipeline"]),at=new Map;async function pr(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(":"),r=at.get(o);if(r)return r;at.size>=4&&at.clear();let s=(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:fr(l)}})();at.set(o,s);try{return await s}catch(c){throw at.delete(o),c}}function Et(e,t){if(!e)return ".";let i=u.relative(e,t).split(u.sep).join("/");return i&&!i.startsWith("../")?i:"."}function sn(e){return {id:e.id,kind:e.kind,label:e.label,...e.projectId?{projectId:e.projectId}:{}}}function Ve(e,t,i,n={artifact:a$7}){return {schemaVersion:rn,generatedAt:(e.now??new Date).toISOString(),status:t,claimBoundary:wi,graph:n,project:{name:e.projectName,path:Et(e.workspacePath,e.projectPath)},summary:{findingCount:0,rootEntityCount:0,affectedEntityCount:0,verificationTargetCount:0,proofPathCount:0,subjectCount:0,unresolvedSubjectCount:0,unknownCount:1},findings:[],diagnostics:[i]}}function ur(e,t){let i=Et(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(s=>typeof s=="string").map(s=>s.toLowerCase()).some(s=>n.has(s)||n.has(u.basename(s))))}function mr(e,t){let i=t.projectId??t.label,n=e.entities.filter(s=>s.id===t.id||s.projectId===i||s.projectId===t.projectId),o=new Set(n.map(s=>s.id)),r=new Set;for(let s of e.relations)o.has(s.from)&&r.add(s.to),o.has(s.to)&&r.add(s.from);return e.entities.filter(s=>o.has(s.id)||r.has(s.id))}function fr(e){let t=new Map,i=(n,o)=>{let r=t.get(n)??[];r.push(o),t.set(n,r);};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 gr(e,t,i){let n=new Set(t),o=t.map(r=>({id:r,depth:0}));for(let r=0;r<o.length;r+=1){let s=o[r];if(!(!s||s.depth>=i))for(let c of e.get(s.id)??[])n.has(c)||(n.add(c),o.push({id:c,depth:s.depth+1}));}return [...n]}function bi(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 vi(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function yr(e,t){let i=vi(e);return i?t.some(n=>{let o=vi(n.reason);return o===i||o.includes(i)||i.includes(o)}):true}function hr(e,t,i,n){let o=ki[i]??ki.unknown,r=[...new Set(n.map(c=>c.trim().toLowerCase()).filter(Boolean))];if(r.length>0){let c=t.filter(l=>o?.includes(l.kind)&&r.some(d=>bi(l).has(d))),a=new Set(r.filter(l=>c.some(d=>bi(d).has(l))));return {roots:c.length>0?c.slice(0,4):[e],unresolvedSubjects:n.filter(l=>!a.has(l.trim().toLowerCase()))}}let s=t.filter(c=>o?.includes(c.kind)).slice(0,4);return {roots:s.length>0?s:[e],unresolvedSubjects:[]}}function kr(e,t,i,n){let o=n.issueClass??"unknown",r=[...new Set((n.subjects??[]).map(h=>h.trim()).filter(Boolean))],{roots:s,unresolvedSubjects:c}=hr(t,i.scoped,o,r),a=gr(i.edges,s.map(h=>h.id),3).map(h=>i.entitiesById.get(h)).filter(h=>!!h),l=a.filter(h=>i.scopedIds.has(h.id)&&!s.some(w=>w.id===h.id)&&lr.has(h.kind)).slice(0,6),d=a.filter(h=>i.scopedIds.has(h.id)&&dr.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=s.map(R=>e$2(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)}]:[]}),k=new Set([...s.flatMap(h=>h.proofIds),...y.flatMap(h=>h.proofIds)]),v=e.proofs.filter(h=>k.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:r,unresolvedSubjects:c,rootEntities:s.map(sn),affectedEntities:l.map(sn),verificationTargets:d.map(sn),proofPaths:y,sourceArtifacts:v,unknowns:C}}async function an(e){if(!e.workspacePath)return Ve(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 Ve(e,"graph-missing","Workspace knowledge graph is missing. Run workspace model before relying on graph-aware diagnosis.");if(!await m.pathExists(i))return Ve(e,"model-missing","Canonical workspace model is missing, so graph source binding cannot be verified.");let n,o,r,s;try{({graph:n,model:o,entitiesById:r,edges:s}=await pr(t,i));}catch(k){return Ve(e,"invalid",`Graph-aware diagnosis rejected invalid evidence: ${k instanceof Error?k.message:String(k)}`)}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$3(n,o);}catch(k){return Ve(e,"stale",k instanceof Error?k.message:String(k),c)}let a=ur(n,e);if(!a)return Ve(e,"project-unresolved","The current project could not be resolved to one canonical project entity.",c);let l=mr(n,a),d={scoped:l,scopedIds:new Set(l.map(k=>k.id)),entitiesById:r,edges:s,projectRelativePath:Et(e.workspacePath,e.projectPath)},p$1=(e.probes??[]).filter(k=>k.status!=="pass"),y=[...p$1,...(e.issues??[]).filter(k=>!yr(k,p$1)).map((k,v)=>({id:`legacy-project-issue-${v+1}`,status:"fail",reason:k,issueClass:"runtime"}))].map(k=>kr(n,a,d,k));return {schemaVersion:rn,generatedAt:(e.now??new Date).toISOString(),status:"available",claimBoundary:wi,graph:c,project:{name:e.projectName,path:Et(e.workspacePath,e.projectPath),entityId:a.id},summary:{findingCount:y.length,rootEntityCount:new Set(y.flatMap(k=>k.rootEntities.map(v=>v.id))).size,affectedEntityCount:new Set(y.flatMap(k=>k.affectedEntities.map(v=>v.id))).size,verificationTargetCount:new Set(y.flatMap(k=>k.verificationTargets.map(v=>v.id))).size,proofPathCount:y.reduce((k,v)=>k+v.proofPaths.length,0),subjectCount:new Set(y.flatMap(k=>k.subjects)).size,unresolvedSubjectCount:new Set(y.flatMap(k=>k.unresolvedSubjects)).size,unknownCount:y.reduce((k,v)=>k+v.unknowns.length,0)},findings:y,diagnostics:[]}}var At="workspai.doctor-summary.v1";function xi(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 ji(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 br(e,t){return t.replace(/\.\*$/u,"").split(".").map(n=>Number.parseInt(n,10)).every((n,o)=>e[o]===n)}function vr(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 wr(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=br(e.parts,o);return n==="=="?c:!c}let r=xi(o);if(!r)return null;let s=ji(e.parts,r.parts);return n==="==="?e.raw===r.raw:n==="=="?s===0:n==="!="?s!==0:n===">="?s>=0:n==="<="?s<=0:n===">"?s>0:n==="<"?s<0:n==="~="?s>=0&&ji(e.parts,vr(r.parts))<0:null}function Ci(e,t){let i=xi(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 r=o.map(c=>({clause:c,result:wr(i,c)})),s=r.filter(c=>c.result===null).map(c=>c.clause);return {version:i.raw,specifier:n,satisfied:s.length>0?null:r.every(c=>c.result===true),unsupportedSpecifiers:s}}function Pi(e){return u.win32.normalize(e.trim()).replace(/\\/g,"/").toLowerCase()}function Di(e,t){return Pi(u.win32.dirname(e))===Pi(t)&&/^workspai(?:\.cmd|\.exe|\.ps1)?$/i.test(u.win32.basename(e))}async function jr(){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 xr(){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 Si(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??jr)(),(e.resolveNpmGlobalPrefix??xr)()]);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,r=n.status==="fulfilled"?n.value:void 0,s=[...new Set(o.map(d=>d.trim()).filter(Boolean))],c=s.map((d,p)=>({location:p===0?"Active PATH match":"Additional PATH match",path:d}));if(s.length===0)return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unresolved",candidates:s,...r?{npmGlobalPrefix:r}:{},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=s[0];if(!r)return {status:"warn",applicability:"applicable",command:"workspai",resolutionStatus:"unverified",activePath:a,candidates:s,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=s.find(d=>Di(d,r));return Di(a,r)?{status:"ok",applicability:"applicable",command:"workspai",resolutionStatus:"canonical",activePath:a,npmGlobalPrefix:r,candidates:s,paths:c,message:"`workspai` resolves to the npm global shim.",...s.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:r,candidates:s,paths:c,message:"Another executable shadows the npm global `workspai` shim.",details:l?`Move ${r} before ${u.win32.dirname(a)} in PATH. Until then, use \`npx --yes workspai <command>\`.`:`Add ${r} to PATH before ${u.win32.dirname(a)}. Until then, use \`npx --yes workspai <command>\`.`}}var un=p.doctor;function Ki(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Ei(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Gi(){let e=z().map(n=>u.join(n,b$6()?"poetry.exe":"poetry")),t=b$6()?[u.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),u.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],i=b$6()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return Ki([...e,...t,...i])}function Cr(e,t=process.cwd()){let i=z().map(l=>({location:"Global (user-local)",path:u.join(l,b$6()?"rapidkit.exe":"rapidkit")})),n=[{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=t$2(u.join(t,".venv")),r=v(t),s=[{location:"Workspace (.venv)",path:o},...r.map(l=>({location:"Workspace (launcher)",path:l}))],c=[...i,...n,...s],a=new Set;return c.filter(l=>a.has(l.path)?false:(a.add(l.path),true))}function Pr(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,r=t.get(n.location)??Number.MAX_SAFE_INTEGER;return o!==r?o-r:i.path.localeCompare(n.path)})}function lt(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 Bi(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),r=t.find(c=>c.pythonRequirement?.satisfied===null),s=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}.`}:r?.pythonRequirement?{...e.python,status:e.python.status==="error"?"error":"warn",details:`Project ${r.name} declares requires-python ${r.pythonRequirement.specifier}, but compatibility could not be evaluated.`}:e.python;return {...e,python:i?s:lt(e.python,"Python is optional because this scope has no detected Python project."),poetry:i?e.poetry:lt(e.poetry,"Poetry is not applicable to this project scope."),pipx:i?e.pipx:lt(e.pipx,"pipx is not applicable to this project scope."),go:n?e.go:lt(e.go,"Go is not applicable to this project scope."),rapidkitCore:/not installed/i.test(e.rapidkitCore.message)||!i&&e.rapidkitCore.status!=="error"?lt(e.rapidkitCore,"RapidKit Core is an optional engine for Python-backed kits and modules; Workspai CLI diagnostics remain available without it."):e.rapidkitCore}}function Dr(e){let i=(e.probes??[]).filter(s=>s.status==="warn").length,n=e.issues.some(s=>s.toLowerCase().includes("environment file missing")),o=(e.probes??[]).some(s=>s.id==="surface-env-contract"),r=(e.probes??[]).some(s=>s.id==="surface-security-hygiene");return e.hasEnvFile===false&&!n&&!o&&(i+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&!r&&(i+=1),i}function Rr(e){let t=e.coreVersion?.split(".")[0],i=e.npmVersion?.split(".")[0];return !t||!i?false:t!==i}var Sr="doctor-project-scan-v2",Er="doctor-project-scan-policy-v5",Wi=s.doctorWorkspaceCache.schemaVersion,Ar=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v2",generatedBy:"workspai",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"}),dt=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 Ye(){return {...Ar}}function Tt(e){let t=e.profile?.trim();return t&&t in dt?{...dt[t]}:e.strict?{...dt.release}:e.ci?{...dt.ci}:{...dt.local}}function It(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function Fr(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 $r(e,t){let i=Fr(e),n=Date.parse(t),o=typeof i.ttlSeconds=="number"?i.ttlSeconds*1e3:null,r=o!==null&&Number.isFinite(n)?new Date(n+o).toISOString():void 0,s=!Number.isFinite(n)||o!==null&&!r?"unknown":o!==null&&Date.now()>n+o?"stale":"fresh";return {category:i.category,generatedAt:t,ttlSeconds:i.ttlSeconds,...r?{expiresAt:r}:{},status:s,verifyBeforeUse:i.category!=="structure"||s!=="fresh",reason:i.reason}}function Ir(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 Hi(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 Nr(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 Mr(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:Ei(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:Ei([...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 gn(e,t){let i=$r(e,e.freshness?.generatedAt??t),n=e.issueClass??Ir(e),o=e.operationalImpact??Nr(e,n),r=Mr({probe:e,freshness:i});return {...e,freshness:i,issueClass:n,operationalImpact:o,repairIntent:r}}function Tr(e,t){Array.isArray(e.probes)&&(e.probes=e.probes.map(i=>gn(i,t)));}function Or(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 Nt(e,t=new Date().toISOString()){Tr(e,t),Vr(e,e.path),Or(e);}function Li(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.`}],r=new Set(i.proofs.map(s=>`${s.kind}:${s.role}:${s.ref}`));for(let s of o){let c=`${s.kind}:${s.role}:${s.ref}`;r.has(c)||i.proofs.push(s);}}}function yn(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,r=i.filter(a=>a.category==="state").length,s=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:r,verifyBeforeUseProbeCount:s,...c?{oldestProbeGeneratedAt:c}:{}}}function qi(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Vi(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 zi(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 r=e.system?.[o.id]?.status;!r||r===o.current.status||n.push({id:o.id,from:r,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 k=y.path||y.name;k&&o.set(k,qi(y.issues));}let r=0,s=0,c=new Set,a=new Set,l=new Set([...Array.from(o.keys()),...Array.from(i.keys())]);for(let y of l){let k=o.get(y)??0,v=i.get(y)??0;v>k?(r+=v-k,c.add(y)):v<k&&(s+=k-v,a.add(y));}let d=It(e.healthScore),p=It(t.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:r,resolvedIssueCount:s,netIssueDelta:r-s,scoreDeltaPercent:d===null||p===null?null:p-d,systemStatusChanges:zi(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 Kr(e,t){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=qi(e.project?.issues),n=t.project.issues.length,o=Math.max(n-i,0),r=Math.max(i-n,0),s=It(e.healthScore),c=It(t.healthScore),a=t.project.path||t.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:r,netIssueDelta:o-r,scoreDeltaPercent:s===null||c===null?null:c-s,systemStatusChanges:zi(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,cliResolution:t.cliResolution}),regressedProjects:o>0?[a]:[],improvedProjects:r>0?[a]:[]}}function Ji(e){let t=e??[],i=0,n=0;for(let s of t){if(s.scope==="project-scoped"){i+=1;continue}(s.scope==="workspace-aggregate"||s.scope==="host-system")&&(n+=1);}let o=i>0&&n>0?1:0,r=o>0?"mixed":i>0?"scoped":n>0?"aggregated":"unknown";return {scopedCount:i,aggregatedCount:n,mixedCount:o,dominantScope:r}}function Q(e,t){return b$6()?`Set-Location -LiteralPath "${e.replace(/"/g,'`"')}"; ${t}`:`cd '${e.replace(/'/g,`'"'"'`)}' && ${t}`}function Gr(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,e.uvProject?`uv sync --project ${e.uvProject}`:"uv sync"):Q(e.projectPath,b$6()?"py -3 -m venv .venv":"python3 -m venv .venv")}async function Br(e){let t=b$6()?["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 Wr(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}),r=`${o.stdout??""}
18
+ ${o.stderr??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(r)return r[1]}catch{}}function Hr(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 Lr(e){return e==="Microsoft Agent Framework"||e==="OpenAI Agents SDK"||e==="Google Agent Development Kit"?"agent":e==="OpenRouter"?"gateway":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 qr(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 Vr(e,t){let i=D(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function pt(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=Hr(t),e.projectKind=Lr(t),e.runtimeFamily=qr(t);}function Ui(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 hn(e){switch(e.key){case "microsoft-agent-framework":return "Microsoft Agent Framework";case "openai-agents":return "OpenAI Agents SDK";case "google-adk":return "Google Agent Development Kit";case "openrouter":return "OpenRouter";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 zr(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 Jr(e,t){e.framework=hn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=Ui(t.runtime);}function U(e,t){e.framework=hn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind=t.key==="microsoft-agent-framework"||t.key==="openai-agents"||t.key==="google-adk"?"agent":t.key==="openrouter"?"gateway":t.key==="tauri"||t.key==="electron"?"desktop":t.key==="vscode-extension"?"extension":zr(t)?"generic":"backend",e.runtimeFamily=Ui(t.runtime);}function Ur(e){let t=e.dependencies,i=e.scripts??{},n=(e.kitName??"").toLowerCase(),o=s=>!!t[s],r=Object.values(i).filter(s=>typeof s=="string").join(" ").toLowerCase();return o("next")||r.includes("next ")?{framework:"Next.js",confidence:"high"}:o("nuxt")||r.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:o("@nestjs/core")||n.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:o("@openai/agents")||n.startsWith("agent.openai.")?{framework:"OpenAI Agents SDK",confidence:"high"}:o("@google/adk")||n.startsWith("agent.google-adk.")||n.startsWith("agent.google.")?{framework:"Google Agent Development Kit",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")||r.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 Yr(e,t){let i=m$1(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:hn(i),confidence:i.confidence}}async function Ai(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__"]),r=0,s=0,c=2e4,a=32*1024*1024;for(;n.length>0&&r<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),k=u.relative(e,y).split(u.sep).join("/");if(p.isDirectory()){i.update(`d:${k}\0`),n.push(y);continue}if(!p.isFile())continue;let v=await m.stat(y).catch(()=>null);if(v){if(r+=1,i.update(`f:${k}:${v.size}:${v.mtimeMs}\0`),v.size<=262144&&s+v.size<=a){let C=await m.readFile(y).catch(()=>null);C&&(s+=C.length,i.update(C));}if(r>=c)break}}}return i.update(`files:${r}:bytes:${s}: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 Zr(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 mt(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 mt(e)&&i.add(e);let r=await c$2(e);for(let a of r.summary.projects){let l=d(e,a.relativePath);await o(l)&&(i.add(l),n.add(l));}let s=await a$4(e);for(let a of s){let l=d(e,a.relativePath||a.name,a.path?{absolutePath: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)?mt(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 xs(e,3,t)).forEach(l=>i.add(l)),i.size===0&&!await b$2(e)&&await o(e)&&i.add(e),Array.from(i).sort((a,l)=>a.localeCompare(l))}catch{return []}}async function Xr(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(Ai)),r=await Promise.all(t.map(async s=>{let c=await Promise.all(n.map(a=>Ai(u.join(s,a))));return `${s}::${c.join("|")}`}));return [Sr,Er,...o,...r].join("||")}async function Qr(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!==Wi)return null;let o=Date.parse(n.generatedAt),r=Number(process.env.WORKSPAI_DOCTOR_CACHE_MAX_AGE_SECONDS),s=Number.isFinite(r)&&r>=0?r:300;return !Number.isFinite(o)||Date.now()-o>s*1e3?null:n}catch{return null}}async function es(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 ts(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),r=0,s=Array.from({length:Math.min(n,e.length)},async()=>{for(;r<e.length;){let c=r;r+=1;let a=e[c];if(a===void 0)break;o[c]=await t(a);}});return await Promise.all(s),o}async function ns(e,t,i){let n=u.join(e,un);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 r=t.projects.map(ee),s=r.reduce((d,p)=>d+p.blockingFindings,0),c=r.reduce((d,p)=>d+p.advisoryFindings,0),a=Fe(t.projects,[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore,t.cliResolution]),l=f$1({schemaVersion:a$8,evidenceType:"workspace",contract:Ye(),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:s,advisoryFindings:c,projectAdvisoryWarningProjects:r.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:gt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:o.slice(0,12),runId:e$1()});return d$1(l),await h(e,un,l),n}catch(o){throw o}}async function kn(e=process.cwd()){let[t,i,n,o,r,s]=await Promise.all([is(),os(),rs(),ss(),as(e),Si()]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:r,cliResolution:s}}async function is(){let e=j$1(),t;for(let i of e)try{let n=i==="py"?["-3","--version"]:["--version"],{stdout:o,stderr:r}=await execa(i,n,{timeout:3e3,reject:false}),c=`${o??""}
19
+ ${r??""}`.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 os(){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 Gi())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 rs(){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 ss(){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 as(e=process.cwd()){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],n=[],o=Cr(t,e);for(let{location:s,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:s,path:c,version:d[1]}):n.push({location:s,path:c,version:d[1],reason:ut(p.stderr||p.stdout)});}}}}catch(a){await m.pathExists(c)&&n.push({location:s,path:c,reason:ut(a instanceof Error?a.message:String(a))});continue}if(i.length>0){let s=i.filter(a=>a.location!=="Workspace (launcher)");if(s.length>0){let a=Pr(s),l=a[0].version,d=a.some(k=>k.location==="Workspace (.venv)"),p=a.some(k=>k.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(k=>({location:k.location,path:k.path,version:k.version}))}}return {status:"ok",message:`RapidKit Core ${i[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:s,exitCode:c}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(c===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let a=s.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:ut(l.stderr||l.stdout)});}}}catch{}try{let{stdout:s,exitCode:c}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(c===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let a=s.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:ut(l.stderr||l.stdout)});}}}catch{}let r=j$1();for(let s of r)try{let c=s==="py"?["-3","-c","import rapidkit_core; print(rapidkit_core.__version__)"]:["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{stdout:a,exitCode:l}=await execa(s,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(s,s==="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 ${s} environment`};n.push({location:`${s} environment`,path:`${s} -m rapidkit`,version:d,reason:ut(y.stderr||y.stdout)});}}}catch{continue}if(n.length>0){let s=n[0];return {status:"error",message:s.version?`RapidKit Core ${s.version} installed but unusable`:"RapidKit Core installed but unusable",details:`${s.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 ut(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 nn(e);t.hasDocker=n.rootDockerfile||n.nestedDockerfile||n.compose;let o=u.join(e,"tests"),r=u.join(e,"test"),s=u.join(e,"src","test"),c=await m.pathExists(o)||await m.pathExists(r)||await m.pathExists(s),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 k=d.shift();if(!k)break;let v=[];try{v=await m.readdir(k.dir);}catch{continue}for(let C of v){let h=u.join(k.dir,C),w;try{w=await m.stat(h);}catch{continue}if(w.isFile()&&C.endsWith("_test.go")){a=true;break}w.isDirectory()&&k.depth<p&&!y.has(C)&&!C.startsWith(".")&&d.push({dir:h,depth:k.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 ci(e,i)),t.runtimeFamily==="python"&&!t.hasTests&&(t.hasTests=await ms(e)),t.runtimeFamily==="node"||t.runtimeFamily==="bun")t.hasCodeQuality=await ai(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"),k=await m.pathExists(y)&&(await m.readFile(y,"utf8")).includes("golangci-lint");t.hasCodeQuality=await m.pathExists(d)||await m.pathExists(p)||k;}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 hi({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 cs(e){return Ki([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 ls(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}}function ds(e,t){let i=new Set(["pip","setuptools","wheel"]),n=t.split(".")[0].replaceAll("_","-").toLowerCase();return e?.some(o=>{if(typeof o.name!="string")return false;let r=o.name.replaceAll("_","-").toLowerCase();return n?r===n:!i.has(r)})??false}async function cn(e){for(let t of cs(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=ls(`${n.stdout??""}
20
+ ${n.stderr??""}`),r=ds(o,e.frameworkImport);return {interpreter:t,coreVersion:i,dependenciesInstalled:r}}catch{return {interpreter:t,coreVersion:i,dependenciesInstalled:false}}}return {dependenciesInstalled:false}}async function ps(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]})),...Gi().map(o=>({executable:o,args:t}))],n=new Set;for(let o of i){let r=`${o.executable}\0${o.args.join("\0")}`;if(!n.has(r)&&(n.add(r),!(u.isAbsolute(o.executable)&&!await m.pathExists(o.executable))))try{let s=await execa(o.executable,o.args,{cwd:e,timeout:Math.max(a$9(),15e3),reject:false,shell:c$1()}),c=s.stdout.trim();if(s.exitCode===0&&c&&await m.pathExists(c))return c}catch{}}}async function us(e,t,i,n){let o=u.join(e,".venv");if(await m.pathExists(o))return {environmentPath:o,...await cn({environmentPath:o,frameworkImport:t})};if(n){let r=u.join(e,n,".venv");if(await m.pathExists(r))return {environmentPath:r,...await cn({environmentPath:r,frameworkImport:t})}}if(i){let r=await ps(e);if(r)return {environmentPath:r,...await cn({environmentPath:r,frameworkImport:t})}}return {dependenciesInstalled:false}}function _(e,t){e.probes||(e.probes=[]);let i=gn(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 xe(e,t){return (await Promise.all(t.map(i=>m.pathExists(u.join(e,i))))).some(Boolean)}async function Yi(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 ms(e){if(await xe(e,["pytest.ini","tox.ini","noxfile.py","conftest.py","tests","test"]))return true;let t=await Yi(e);return /\[tool\.pytest(?:\.|\])|\bpytest\b|\bunittest\b|\btox\b|\bnox\b/i.test(t)}async function de(e,t){let i=new Set(t.ignoreDirs??["node_modules",".git","bin","obj","dist"]),o=(t.under&&t.under.length>0?t.under:["."]).map(r=>u.join(e,r));for(;o.length>0;){let r=o.shift(),s;try{s=await m.readdir(r,{withFileTypes:true});}catch{continue}for(let c of s){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(r,c.name));}}return false}async function fs(e,t){let i=t.runtimeFamily||"unknown";if(!(t.projectKind==="backend"||t.projectKind==="generic"||t.projectKind==="gateway"||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 xe(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(()=>""),k=/\[(?:project\.scripts|tool\.poetry\.scripts)\]/i.test(p)||await xe(e,d);_(t,{id:"adapter-python-boot-entrypoint",label:"Python adapter boot entrypoint",status:k?"pass":"warn",severity:"warn",scope:"project-scoped",reason:k?"Python application or command entrypoint markers detected.":"No Python application or command entrypoint markers detected.",recommendation:k?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 xe(e,["src/main/java/Application.java","src/main/kotlin/Application.kt"])||await de(e,{suffix:"Application.java",under:["src/main/java"]})||await de(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 xe(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 xe(e,["Program.cs","src/Program.cs"])||await de(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 r={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(!r)return;let s=(i==="c"||i==="cpp")&&e$3(e),c=s||await xe(e,r.dependencyMarkers);_(t,{id:`adapter-${i}-dependency-contract`,label:r.dependencyLabel,status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?s?`${r.dependencyLabel} detected across multiple native workspace components.`:`${r.dependencyLabel} detected.`:`${r.dependencyLabel} is missing.`,recommendation:c?void 0:`Add a runtime-native dependency/build contract: ${r.dependencyMarkers.join(", ")}.`,issueClass:"dependency",operationalImpact:"ci-risk"});let a=await xe(e,r.entrypointMarkers);!a&&i==="elixir"&&(a=await de(e,{name:"application.ex",under:["lib"]})),!a&&i==="scala"&&(a=await de(e,{name:"Main.scala",under:["src/main/scala"]})||await de(e,{name:"Application.scala",under:["src/main/scala"]})),!a&&i==="kotlin"&&(a=await de(e,{name:"Application.kt",under:["src/main/kotlin"]})||await de(e,{name:"Main.kt",under:["src/main/kotlin"]})),_(t,{id:`adapter-${i}-boot-entrypoint`,label:r.entrypointLabel,status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?`${r.entrypointLabel} detected.`:`${r.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 gs(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),r=Array.isArray(o?.checks)?o.checks:[];for(let s=0;s<r.length;s+=1){let c=r[s]||{},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-${s+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):[],k=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 k)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"||t.projectKind==="gateway"))return;let n=await xe(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"]},r=t.runtimeFamily||"unknown",s=o[r]||o.unknown,c=false;for(let y of s)if(await m.pathExists(u.join(e,y))){c=true;break}let a=await Yi(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=await h$1(e),p=d||/\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:d||!p?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:p?"applicable":"not-applicable",reason:d?"Health endpoint/config markers detected.":p?"No explicit runtime health endpoint markers detected.":"No HTTP service runtime intent was detected; an endpoint health surface is not currently applicable.",recommendation:d||!p?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await fs(e,t);}async function ys(e,t,i,n){let o=await li({projectPath:e,detection:n,packageJsonData:i});for(let r of o)_(t,r);}async function X(e,t,i){let n=await pi({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),r=Array.isArray(o?.probes)?o.probes:[];for(let s=0;s<r.length;s+=1){let c=r[s]||{},a=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`custom-probe-${s+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):[],k=p.length===0;for(let h of p)if(await m.pathExists(u.join(e,h))){k=true;break}let v=true;for(let h of y)if(!await m.pathExists(u.join(e,h))){v=false;break}let C=k&&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 gs(e,t);}async function hs(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 K of E.issues)n.issues.push(`${K.message} (${K.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 s=null;try{for(let S of u$1(e,"project.json")){if(!await m.pathExists(S))continue;s=await m.readJson(S);let E=typeof s?.name=="string"?s.name:typeof s?.slug=="string"?s.slug:void 0;E?.trim()&&(n.name=E.trim());let K=j$2(s)?void 0:s?.kit_name||s?.kit;K&&(n.kit=K);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),ue=Date.now()-E.mtime.getTime(),te=Math.floor(ue/(1e3*60*60*24));n.lastModified=te===0?"today":`${te} day${te>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"),k=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"),b=await m.pathExists(c),A=await m.pathExists(a)||await m.pathExists(l$1),j=await m.pathExists(g),G=await m.pathExists(D),$=await m.pathExists(k),V=await m.pathExists(v),ce=await m.pathExists(C)||await m.pathExists(h),H=await m.pathExists(y),B=await m.pathExists(w)||await m.pathExists(P),T=b&&(await m.pathExists(R)||await m.pathExists(x)||typeof s?.packageManager=="string"&&(s?.packageManager).toLowerCase().startsWith("bun@")),he=(await m.readdir(e).catch(()=>[])).some(S=>S.endsWith(".csproj")||S.endsWith(".sln")),oe=b||A||j||G||$||V||ce||H||B||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"))||he||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,pe=m$1(e,s??null),z=pe.runtime;if(Be)return U(n,pe),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(pe.runtime==="c"||pe.runtime==="cpp")return U(n,pe),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"){U(n,m$1(e,s??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"){U(n,m$1(e,s??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 K=S?b$6()?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies";n.fixCommands?.push(Q(e,K));}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"){U(n,m$1(e,s??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")),K=await m.pathExists(u.join(e,"mvnw"))||await m.pathExists(u.join(e,"mvnw.cmd")),ue=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(!K)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&&!ue)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 te=u.join(e,"target"),le=u.join(e,"build","libs"),Ie=u.join(e,".workspai","cache","java","m2"),Ne=u.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await m.pathExists(te)||await m.pathExists(le)||await m.pathExists(Ie)||await m.pathExists(Ne),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let se=S?K?b$6()?".\\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":ue?b$6()?".\\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,se));}let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);let W=u.join(e,"src","main","resources","application.yml");if(await m.pathExists(W))try{let se=await m.readFile(W,"utf-8");/include:\s*[^\n]*health/i.test(se)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(se)||(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"){U(n,m$1(e,s??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 K=u.join(e,".env");return n.hasEnvFile=await m.pathExists(K),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="elixir"){U(n,m$1(e,s??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 K=u.join(e,".env");return n.hasEnvFile=await m.pathExists(K),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="clojure"){U(n,m$1(e,s??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,".cpcache"),E=u.join(e,"target"),K=await m.pathExists(C)||await m.pathExists(h);return n.depsInstalled=await m.pathExists(S)||await m.pathExists(E)||K,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"){U(n,m$1(e,s??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"){U(n,m$1(e,s??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??{}},K=S?.scripts??{},ue=typeof s?.kit_name=="string"?s.kit_name.toLowerCase():typeof s?.kit=="string"?s.kit.toLowerCase():"",te=d$2(e,s),le=Ur({dependencies:E,scripts:K,kitName:ue});if(T)pt(n,"Bun","high");else {let I=m$1(e,s??null);I.key==="nestjs"||I.key==="express"||I.key==="fastify"||I.key==="koa"||I.key==="tauri"||I.key==="electron"||I.key==="vscode-extension"?U(n,I):te.key!=="unknown"?Jr(n,te):I.key!=="unknown"&&I.key!=="node"?U(n,I):pt(n,le.framework,le.confidence);}n.venvActive=true;let Ie=n.projectKind==="agent"?"agents/primary":void 0,Ne=u.join(e,Ie??"","node_modules");if(await m.pathExists(Ne))try{let W=(await m.readdir(Ne)).filter(se=>!se.startsWith(".")&&!se.startsWith("_"));n.depsInstalled=W.length>0;}catch{n.depsInstalled=false;}if(!n.depsInstalled){n.issues.push("Dependencies not installed (node_modules empty or missing)");let I=typeof S?.packageManager=="string"?S.packageManager.split("@")[0]:void 0,W=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":Ie?`npm install --prefix ${Ie}`:"npm install";n.fixCommands?.push(Q(e,W));}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(se=>m.pathExists(u.join(e,se))))).some(Boolean))n.hasEnvFile=true;else {let se=u.join(e,".env.example");await m.pathExists(se)&&(n.hasEnvFile=false);}}else {let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);}if(n.projectKind==="frontend")n.modulesHealthy=await Qt(e),n.missingModules=[];else {let I=u.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(I))try{let W=await m.readdir(I);n.modulesHealthy=W.length>0;}catch{n.modulesHealthy=false;}}return await Y(e,n,S),await X(e,n,S),n.projectKind==="frontend"?await ys(e,n,S,te.key!=="unknown"?te:d$2(e,s)):await Z(e,n),await q(e,n),n}if(z==="python"){if(pe.key==="microsoft-agent-framework"||pe.key==="openai-agents"||pe.key==="google-adk"||pe.key==="openrouter")U(n,pe);else {let ae=await Yr(e,s);pt(n,ae.framework,ae.confidence);}let S="fastapi";n.framework==="Django"?S="django":n.framework==="Flask"?S="flask":n.framework==="Python"?S="":n.framework==="Microsoft Agent Framework"?S="agent-framework-core":n.framework==="OpenAI Agents SDK"?S="openai-agents":n.framework==="Google Agent Development Kit"?S="google-adk":n.framework==="OpenRouter"&&(S="");let E=n.projectKind==="agent"?"agents/primary":void 0,K=E?u.join(e,E,"pyproject.toml"):a,ue=await Gt(K),te=/\[tool\.poetry\]/.test(ue),le=await Br(e),Ie=le?"project-script":E?"uv":te?"poetry":await m.pathExists(u.join(e,"uv.lock"))?"uv":"venv",Ne=Gr({projectPath:e,manager:Ie,...le?{projectScript:le}:{},...E?{uvProject:E}:{}}),I=await us(e,S,te,E);n.venvActive=!!I.environmentPath,n.depsInstalled=I.dependenciesInstalled,n.coreInstalled=!!I.coreVersion,n.coreVersion=I.coreVersion;let W=ue.match(/^\s*requires-python\s*=\s*["']([^"']+)["']/m)?.[1];if(W){let ae=await Wr(I.interpreter),me=ae?Ci(ae,W):{version:"unknown",satisfied:null};if(n.pythonRequirement={specifier:W,...ae?{detectedVersion:ae}:{},satisfied:me.satisfied},me.satisfied===false){let We=`Python ${me.version} does not satisfy requires-python ${W}`;n.issues.push(We),_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"fail",severity:"error",scope:"project-scoped",reason:We,recommendation:le?`Install a compatible Python interpreter, then run the repository-authored ${le} setup command.`:"Install a Python interpreter satisfying requires-python, then materialize the project environment.",issueClass:"runtime",operationalImpact:"release-risk"});}else me.satisfied===null?_(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"warn",severity:"warn",scope:"project-scoped",reason:ae?`Python ${ae} could not be evaluated against requires-python ${W}.`:`No executable Python version could be verified against requires-python ${W}.`,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 ${me.version} satisfies requires-python ${W}.`,issueClass:"runtime",operationalImpact:"none"});}I.environmentPath?I.interpreter?n.depsInstalled||(n.issues.push("Dependencies not installed"),n.fixCommands?.push(Ne)):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Ne));let se=u.join(e,".env");n.hasEnvFile=await m.pathExists(se);let ht=u.join(e,"src"),Bt=u.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(ht)){let ae=u.join(ht,"__init__.py"),me=await m.pathExists(ae),We=me?false:await ws(ht);!me&&!We&&(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await m.pathExists(Bt))try{let ae=await Xi(Bt);for(let me of ae){let We=u.join(Bt,me,"__init__.py");await m.pathExists(We)||(n.modulesHealthy=false,n.missingModules.push(`modules/${me}/__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"){U(n,m$1(e,s??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"){U(n,m$1(e,s??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 K=u.join(e,".env");return n.hasEnvFile=await m.pathExists(K),await Y(e,n),await X(e,n),await Z(e,n),await q(e,n),n}if(z==="dotnet"){U(n,m$1(e,s??null)),n.venvActive=true,n.coreInstalled=false;let S=u.join(e,"obj"),E=u.join(e,"src","obj"),K=u.join(e,"agents","primary","obj"),ue=u.join(e,"agents","primary","tests","obj"),te=u.join(e,"packages.lock.json");n.depsInstalled=await m.pathExists(S)||await m.pathExists(E)||await m.pathExists(K)||await m.pathExists(ue)||await m.pathExists(te),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(Q(e,n.framework==="Microsoft Agent Framework"?"dotnet restore agents/primary/tests/Primary.Tests.csproj":"dotnet restore")));let le=u.join(e,".env");return n.hasEnvFile=await m.pathExists(le),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 de(e,{suffix:".cpp",under:["src","."]});return pt(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 pt(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 Zi(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 ks(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=[],r=(a,l)=>{l&&!o.includes(a)&&o.push(a);},s=await i("package.json");return r("bun",s&&(await i("bun.lock")||await i("bun.lockb"))),r("deno",await i("deno.json")||await i("deno.jsonc")),r("node",s&&!o.includes("bun")),r("python",await i("pyproject.toml")||await i("requirements.txt")),r("go",await i("go.mod")),r("kotlin",await i("build.gradle.kts")&&await de(e,{suffix:".kt",under:["src"]})),r("java",await i("pom.xml")||await i("build.gradle")||await i("build.gradle.kts")&&!o.includes("kotlin")),r("rust",await i("Cargo.toml")),r("elixir",await i("mix.exs")),r("clojure",await i("deps.edn")||await i("project.clj")),r("scala",await i("build.sbt")),r("php",await i("composer.json")),r("ruby",await i("Gemfile")),r("dotnet",n.some(a=>a.endsWith(".csproj"))||await i("global.json")),(await i("CMakeLists.txt")||await i("meson.build"))&&(r("cpp",await de(e,{suffix:".cpp",under:["src","."]})),r("c",await de(e,{suffix:".c",under:["src","."]})),!o.includes("c")&&!o.includes("cpp")&&r("cpp",true)),o.length>0?o:["unknown"]}async function bs(e,t){if(t.projectKind==="extension")return "plugin";if(t.projectKind==="agent")return "application";if(t.projectKind==="gateway")return "service";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")),r=await m.pathExists(u.join(e,"include")),s=(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&&s)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&&r?"library":t.projectKind==="backend"?"service":"unknown"}function vs(e){let t=e.probes??[],i=t.map((s,c)=>s.id==="config-surface"?c:-1).filter(s=>s>=0);t.some(s=>s.id==="surface-env-contract")&&(e.probes=t.filter((s,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(s=>{let c=s.id==="frontend-framework-config"||s.id==="frontend-source-tree"||s.id.startsWith("frontend-script-");return s.id==="migration-surface"||s.id==="runtime-health-surface"||s.id==="surface-kubernetes-readiness"||c||s.id.endsWith("-boot-entrypoint")||s.id==="runtime-security-tooling"&&e.probes?.some(l=>l.id==="surface-security-hygiene")||s.id==="surface-env-contract"&&s.status!=="pass"?(s.repairCapability?.command&&o.add(s.repairCapability.command),{...s,status:"pass",severity:"info",applicability:"not-applicable",reason:`${s.label} is not required for the detected ${e.projectArchetype} archetype.`,recommendation:void 0,repairCapability:void 0,repairIntent:void 0}):s});let r=new Set((e.probes??[]).map(s=>s.repairCapability?.id).filter(s=>!!s));e.repairCapabilities=(e.repairCapabilities??[]).filter(s=>r.has(s.id)),e.fixCommands=(e.fixCommands??[]).filter(s=>!o.has(s));}async function Ot(e,t={}){let i=Zi(await hs(e,t));delete i._freshDependencyAudit,Fs(i),i.runtimeFamilies=await ks(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$4(e);if(n==="gateway"?i.projectKind="gateway":n==="agent"?i.projectKind="agent":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 bs(e,i),i.projectArchetype==="platform"){let o=i.probes?.find(r=>r.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 vs(i),Nt(i),i}async function ws(e){for(let t of await Xi(e))if(!(t==="__pycache__"||t.startsWith("."))&&await m.pathExists(u.join(e,t,"__init__.py")))return true;return false}async function Xi(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 mt(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 js(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 xs(e,t,i){let n=new Set,o=[{dir:e,depth:0}];for(;o.length>0;){let r=o.shift();if(!r)break;try{let s=await m.readdir(r.dir);for(let c of s){if(js(c,i))continue;let a=u.join(r.dir,c),l;try{l=await m.stat(a);}catch{continue}if(l.isDirectory()){if(await mt(a)){n.add(a);continue}r.depth<t&&o.push({dir:a,depth:r.depth+1});}}}catch{continue}}return Array.from(n)}async function ft(e){let t=a$1(e);if(t)return t;let i=u.resolve(e),n=u.parse(i).root;for(;;){if(await Ds(i))return i;if(i===n)return null;i=u.dirname(i);}}async function Cs(e){let t=u.resolve(e),i=await ft(t),n=i??u.parse(t).root;for(;;){if(await mt(t)||await Ps(t)&&(!i||t!==i))return t;if(t===n)break;t=u.dirname(t);}return null}function Fi(e){let t=u.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function Ps(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 Ds(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 bn(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=Dr(l),k=l.isGoProject?l.issues.length===0&&l.depsInstalled:l.issues.length===0&&l.venvActive&&l.depsInstalled;l.issues.length>0||!k?n.errors+=1:y>0?n.warnings+=1:n.passed+=1;});let o=i.passed+n.passed,r=i.warnings+n.warnings,s=i.errors+n.errors,c=Fe(t,e),a=i.total+n.total;return {total:a,passed:o,warnings:r,errors:s,verdict:s>0?"blocked":r>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,r=e.diagnosis?.coverage.blockingFindings??o+e.issues.length,s=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:r,advisoryFindings:s,unknownFindings:c,contradictionFindings:a,verdict:r>0?"blocked":s+c+a>0?"attention":"passed"}}function Fe(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,r)=>o+(r?.coverage.blockingFindings??0),0),advisoryFindings:i.reduce((o,r)=>o+(r?.coverage.advisoryFindings??0),0),unknownFindings:i.reduce((o,r)=>o+(r?.coverage.unknownFindings??0),0),contradictionFindings:i.reduce((o,r)=>o+(r?.coverage.contradictionCount??0),0),repairableFindings:i.reduce((o,r)=>o+(r?.coverage.repairableFindings??0),0),manualFindings:i.reduce((o,r)=>o+(r?.coverage.manualFindings??0),0),unsupportedFindings:i.reduce((o,r)=>o+(r?.coverage.unsupportedFindings??0),0),dependencyAdvisorySubjects:e.reduce((o,r)=>o+(r.dependencyAudit?.subjects.length??0),0),dependencyVulnerabilityFindings:e.reduce((o,r)=>o+(r.dependencyAudit?.findingCount??0),0),notApplicableChecks:e.reduce((o,r)=>o+(r.probes??[]).filter(s=>s.applicability==="not-applicable").length,0)+t.filter(o=>o.applicability==="not-applicable").length,systemErrors:t.filter(o=>o.status==="error").length}}function Rs(e){let t=ee(e);e.probeSummary=t,e.verdict=t.verdict;}function Qi(e,t,i={}){let n=[];for(let r of e)n.push({id:r.id,label:r.label,status:r.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:r.result.details||r.result.message});let o=[...t].sort((r,s)=>{let c=`${r.path||""}|${r.name||""}`.toLowerCase(),a=`${s.path||""}|${s.name||""}`.toLowerCase();return c.localeCompare(a)});for(let r of o){if(Rs(r),r.diagnosis){for(let s of (r.probes??[]).filter(c=>c.status==="pass"))n.push({id:`project:${r.name}:probe:${s.id}`,label:`${r.name} \xB7 ${s.label}`,status:"ok",scope:"project-scoped",policyRuleId:`project-probe-${s.id}`,reason:s.reason});for(let s of r.diagnosis.findings)n.push({id:`project:${r.name}:diagnosis:${s.id}`,label:`${r.name} \xB7 ${s.label}`,status:s.status==="blocking"?"error":"warn",scope:"project-scoped",policyRuleId:`project-diagnosis-${s.issueClass}`,reason:s.symptom});}else {for(let s of r.probes??[])n.push({id:`project:${r.name}:probe:${s.id}`,label:`${r.name} \xB7 ${s.label}`,status:s.status==="pass"?"ok":s.status==="warn"?"warn":"error",scope:"project-scoped",policyRuleId:`project-probe-${s.id}`,reason:s.reason});for(let[s,c]of r.issues.entries())n.push({id:`project:${r.name}:legacy:${s+1}`,label:`${r.name} \xB7 Runtime issue`,status:"error",scope:"project-scoped",policyRuleId:"project-runtime-issue",reason:c});}(r.probes?.length??0)===0&&r.issues.length===0&&n.push({id:`project:${r.name}`,label:`Project ${r.name}`,status:"ok",scope:"project-scoped",policyRuleId:"project-checks-passed",reason:"Project checks passed"});}if(i.includeWorkspaceAggregateRules){let r=t.reduce((a,l)=>a+ee(l).blockingFindings,0),s=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:r>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:r>0?`${r} blocking project issue(s) detected.`:"No blocking project issues detected."}),n.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:s>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:s>0?`${s} advisory warning(s) detected.`:"No advisory warnings detected."});}return n}async function ln(e$1,t$2=true,i=Tt({}),n=false){let o=u.basename(e$1),r=await a$2(e$1);if(typeof r?.name=="string"&&r.name.trim().length>0)o=r.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[s,c]=await Promise.all([kn(e$1),Zr(e$1)]),a={workspacePath:e$1,workspaceName:o,python:s.python,poetry:s.poetry,pipx:s.pipx,go:s.go,rapidkitCore:s.rapidkitCore,cliResolution:s.cliResolution,projects:[],policyProfile:i};e.debug(`Workspace scan found ${c.length} project(s)`);let l=await Xr(e$1,c),d=u.join(e$1,t$1.doctorWorkspaceCache),p=t$2&&!n?await Qr(d,l):null;if(p){a.projects=p.projects;for(let h of a.projects)Zi(h),Nt(h,p.generatedAt);a.projectScanCached=true,e.debug(`Workspace project health cache hit: ${d}`);}else try{let h=new Date().toISOString(),w=await ts(c,P=>Ot(P,{allowNonRapidkit:true,freshAudit:n}));for(let P of w)Nt(P,h);a.projects=w,a.projectScanCached=false,await es(e$1,{schemaVersion:Wi,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=Bi({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 an({workspacePath:e$1,projectPath:h.path,projectName:h.name,probes:Hi(h),issues:h.issues}),Li(h);}));let k=[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore,a.cliResolution];if(a.healthScore=bn(k,a.projects),a.scoreBreakdown=Qi([{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=Ji(a.scoreBreakdown),a.evidenceFreshness=yn(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,un),C=v?await Vi(v,"workspace"):null;return a.driftDelta=_r(C,a),a.evidencePath=await ns(e$1,a,p?d:null),a.receiptPath=await no(e$1,to({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 $i(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 eo(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 Ss(e,t){let i$1=e||t.projectPath,n=t$1.doctorProject,o=eo(e,t.projectPath),r=u.join(i$1,n);try{let s=[...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=Fe([t.project],[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore,t.cliResolution]),l=f$1({schemaVersion:b$5,evidenceType:"project",contract:Ye(),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:gt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:s,runId:e$1()});return d$1(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),r}catch(s){throw s}}function to(e){let t=new Date().toISOString(),i=e.freshness??yn(e.projects,t),n=Fe(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),r=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}:{}}))),s$1=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&&s$1>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:r,next:a,artifacts:{evidence:e.evidencePath??null,receipt:u.join(e.scopeRoot,t$1.doctorReceipt)}}}async function no(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 mn(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 Ze(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 Xe(e,t,i){try{await j(e,g$1(t,i));}catch{}}async function Ii(e,t=Tt({}),i=false){let n=await ft(e),o=await kn(n||e),r=await Ot(e,{allowNonRapidkit:true,freshAudit:i}),s=Bi(o,[r]);Nt(r),r.graphDiagnosis=await an({workspacePath:n||void 0,projectPath:e,projectName:r.name,probes:Hi(r),issues:r.issues}),Li(r);let c=bn([s.python,s.poetry,s.pipx,s.go,s.rapidkitCore,s.cliResolution],[r]),a={workspacePath:n||void 0,projectPath:e,projectName:u.basename(e),python:s.python,poetry:s.poetry,pipx:s.pipx,go:s.go,rapidkitCore:s.rapidkitCore,cliResolution:s.cliResolution,project:r,healthScore:c,policyProfile:t};a.scoreBreakdown=Qi([{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=Ji(a.scoreBreakdown),a.evidenceFreshness=yn([a.project],new Date().toISOString());let l=await g(e,t$1.doctorProject),d=n?await g(n,eo(n,e)):null,p=l??d,y=p?await Vi(p,"project"):null;a.driftDelta=Kr(y,a),a.evidencePath=await Ss(n||void 0,a);let k=n||e;return a.receiptPath=await no(k,to({scopeKind:"project",scopeRoot:k,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 Ae(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 r=o.version?f.cyan(` -> ${o.version}`):"";console.log(` ${f.cyan("\u2022")} ${f.gray(o.location)}: ${f.dim(o.path)}${r}`);}),e.details&&console.log(` ${f.gray(e.details)}`);}function Ft(e,t){let i=Mt(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 Es(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 Ni(e,t,i={}){let n=ee(e),o=n.verdict==="blocked"?"\u274C":n.verdict==="attention"?"\u26A0\uFE0F":"\u2705",r=n.verdict==="blocked"?f.red:n.verdict==="attention"?f.yellow:f.green;if(console.log(`
23
23
  ${o} ${f.bold("Project")}: ${r(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: ${Es(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(Ft(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 io(){try{return (await execa("go",["version"],{timeout:a$9(),reject:false})).exitCode===0}catch{return false}}function Be(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 _t(e){return Be(e,"cp\\s+\\.env\\.example\\s+\\.env")||Be(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function vn(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\\s+--project\\s+agents/primary",command:"uv",args:["lock","--project","agents/primary"]},{pattern:"uv\\s+sync\\s+--project\\s+agents/primary",command:"uv",args:["sync","--project","agents/primary"]},{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\\s+agents/primary/tests/Primary\\.Tests\\.csproj\\s+--use-lock-file",command:"dotnet",args:["restore","agents/primary/tests/Primary.Tests.csproj","--use-lock-file"]},{pattern:"dotnet\\s+restore\\s+agents/primary/tests/Primary\\.Tests\\.csproj",command:"dotnet",args:["restore","agents/primary/tests/Primary.Tests.csproj"]},{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=Be(e,i.pattern);if(n)return {projectPath:n.projectPath,command:i.command,args:i.args}}return null}function As(e,t=[]){let i=u.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:cmd|bat)$/i,"");if(/(?:^|\/)(?:script\/setup|scripts\/setup|bin\/setup)(?:\.cmd|\.ps1)?$/iu.test(e.replaceAll("\\","/")))return {ecosystem:"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt",e.replaceAll("\\","/")]};if(["npm","pnpm","yarn","bun"].includes(i))return {ecosystem:i,files:["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]};if(["poetry","uv","pip","pip3","python","python3","py"].includes(i)){let n=t.indexOf("--project");if(i==="uv"&&n>=0&&t[n+1]){let o=t[n+1].replaceAll("\\","/").replace(/\/$/u,"");return {ecosystem:"uv",files:[`${o}/pyproject.toml`,`${o}/uv.lock`,`${o}/requirements.txt`]}}return {ecosystem:i==="uv"?"uv":i==="poetry"?"poetry":"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt"]}}if(i==="go")return {ecosystem:"go",files:["go.mod","go.sum"]};if(i==="cargo")return {ecosystem:"cargo",files:["Cargo.toml","Cargo.lock"]};if(i==="composer")return {ecosystem:"composer",files:["composer.json","composer.lock"]};if(i==="bundle")return {ecosystem:"bundler",files:["Gemfile","Gemfile.lock"]};if(i==="mix")return {ecosystem:"mix",files:["mix.exs","mix.lock"]};if(i==="dotnet"){let n=t.find(r=>/\.(?:cs|fs|vb)proj$/iu.test(r)),o=n?u.posix.dirname(n.replaceAll("\\","/")):null;return {ecosystem:"dotnet",files:o?[n,`${o}/Directory.Packages.props`,`${o}/packages.lock.json`]:["Directory.Packages.props","packages.lock.json"]}}return i==="clojure"||i==="lein"?{ecosystem:"clojure",files:["deps.edn","project.clj"]}:i==="sbt"?{ecosystem:"sbt",files:["build.sbt"]}:i==="mvn"||i==="mvnw"?{ecosystem:"maven",files:["pom.xml",".workspai/cache/java/m2"]}:i==="gradle"||i==="gradlew"?{ecosystem:"gradle",files:["build.gradle","build.gradle.kts","gradle.lockfile",".workspai/cache/java/gradle"]}:{ecosystem:i,files:[]}}function Fs(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=vn(i);if(!n||e.depsInstalled&&!t)continue;let o=As(n.command,n.args),r=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."]}),s=e.probes?.find(c=>c.id==="runtime-dependency-materialization");if(s){Object.assign(s,gn({...s,repairCapability:r},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:r,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",r=i||n||o,s=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.":$s(e.runtimeFamily);_(e,{id:"runtime-dependency-materialization",label:"Runtime dependency materialization",status:"pass",severity:"info",scope:"project-scoped",...r?{applicability:"not-applicable"}:{},reason:s,issueClass:"dependency",operationalImpact:"none"});}}function $s(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 Is(){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 Kt(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 Qe(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 Ns(e){let t=e.operation?Ms(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 Ms(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 Ts(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 $e(e,t){if(!(await m.stat(e).catch(()=>{}))?.isDirectory())throw new Error(`Repair project boundary not found: ${e}`);let n=Ts(e,t),o=await m.realpath(e).catch(()=>u.resolve(e)),r=n;for(;!await m.pathExists(r);){let a=u.dirname(r);if(a===r)throw new Error(`Repair target has no resolvable project ancestor: ${t}`);r=a;}let s=await m.realpath(r).catch(()=>u.resolve(r)),c=u.relative(o,s);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Repair target escapes project boundary through a symbolic link: ${t}`);return n}async function Os(e){if(!/^[A-Za-z0-9:_-]+$/.test(e.scriptName))throw new Error(`Unsafe package script name: ${e.scriptName}`);let t=await $e(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 _s(e){let t=await $e(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 Ks(e){let t=await $e(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Bt(t),n=i.split(/\r?\n/),o=e.operation.lines.filter(s=>!n.includes(s));if(o.length===0)return;let r=i.length===0||i.endsWith(`
24
+ ${f.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(a=>{console.log(` ${f.white(Ft(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 io(){try{return (await execa("go",["version"],{timeout:a$9(),reject:false})).exitCode===0}catch{return false}}function Ge(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 _t(e){return Ge(e,"cp\\s+\\.env\\.example\\s+\\.env")||Ge(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function vn(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\\s+--project\\s+agents/primary",command:"uv",args:["lock","--project","agents/primary"]},{pattern:"uv\\s+sync\\s+--project\\s+agents/primary",command:"uv",args:["sync","--project","agents/primary"]},{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\\s+agents/primary/tests/Primary\\.Tests\\.csproj\\s+--use-lock-file",command:"dotnet",args:["restore","agents/primary/tests/Primary.Tests.csproj","--use-lock-file"]},{pattern:"dotnet\\s+restore\\s+agents/primary/tests/Primary\\.Tests\\.csproj",command:"dotnet",args:["restore","agents/primary/tests/Primary.Tests.csproj"]},{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=Ge(e,i.pattern);if(n)return {projectPath:n.projectPath,command:i.command,args:i.args}}return null}function As(e,t=[]){let i=u.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:cmd|bat)$/i,"");if(/(?:^|\/)(?:script\/setup|scripts\/setup|bin\/setup)(?:\.cmd|\.ps1)?$/iu.test(e.replaceAll("\\","/")))return {ecosystem:"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt",e.replaceAll("\\","/")]};if(["npm","pnpm","yarn","bun"].includes(i))return {ecosystem:i,files:["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]};if(["poetry","uv","pip","pip3","python","python3","py"].includes(i)){let n=t.indexOf("--project");if(i==="uv"&&n>=0&&t[n+1]){let o=t[n+1].replaceAll("\\","/").replace(/\/$/u,"");return {ecosystem:"uv",files:[`${o}/pyproject.toml`,`${o}/uv.lock`,`${o}/requirements.txt`]}}return {ecosystem:i==="uv"?"uv":i==="poetry"?"poetry":"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt"]}}if(i==="go")return {ecosystem:"go",files:["go.mod","go.sum"]};if(i==="cargo")return {ecosystem:"cargo",files:["Cargo.toml","Cargo.lock"]};if(i==="composer")return {ecosystem:"composer",files:["composer.json","composer.lock"]};if(i==="bundle")return {ecosystem:"bundler",files:["Gemfile","Gemfile.lock"]};if(i==="mix")return {ecosystem:"mix",files:["mix.exs","mix.lock"]};if(i==="dotnet"){let n=t.find(r=>/\.(?:cs|fs|vb)proj$/iu.test(r)),o=n?u.posix.dirname(n.replaceAll("\\","/")):null;return {ecosystem:"dotnet",files:o?[n,`${o}/Directory.Packages.props`,`${o}/packages.lock.json`]:["Directory.Packages.props","packages.lock.json"]}}return i==="clojure"||i==="lein"?{ecosystem:"clojure",files:["deps.edn","project.clj"]}:i==="sbt"?{ecosystem:"sbt",files:["build.sbt"]}:i==="mvn"||i==="mvnw"?{ecosystem:"maven",files:["pom.xml",".workspai/cache/java/m2"]}:i==="gradle"||i==="gradlew"?{ecosystem:"gradle",files:["build.gradle","build.gradle.kts","gradle.lockfile",".workspai/cache/java/gradle"]}:{ecosystem:i,files:[]}}function Fs(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=vn(i);if(!n||e.depsInstalled&&!t)continue;let o=As(n.command,n.args),r=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."]}),s=e.probes?.find(c=>c.id==="runtime-dependency-materialization");if(s){Object.assign(s,gn({...s,repairCapability:r},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:r,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",r=i||n||o,s=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.":$s(e.runtimeFamily);_(e,{id:"runtime-dependency-materialization",label:"Runtime dependency materialization",status:"pass",severity:"info",scope:"project-scoped",...r?{applicability:"not-applicable"}:{},reason:s,issueClass:"dependency",operationalImpact:"none"});}}function $s(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 Is(){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 Kt(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 Qe(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 Ns(e){let t=e.operation?Ms(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 Ms(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 Ts(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 $e(e,t){if(!(await m.stat(e).catch(()=>{}))?.isDirectory())throw new Error(`Repair project boundary not found: ${e}`);let n=Ts(e,t),o=await m.realpath(e).catch(()=>u.resolve(e)),r=n;for(;!await m.pathExists(r);){let a=u.dirname(r);if(a===r)throw new Error(`Repair target has no resolvable project ancestor: ${t}`);r=a;}let s=await m.realpath(r).catch(()=>u.resolve(r)),c=u.relative(o,s);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Repair target escapes project boundary through a symbolic link: ${t}`);return n}async function Os(e){if(!/^[A-Za-z0-9:_-]+$/.test(e.scriptName))throw new Error(`Unsafe package script name: ${e.scriptName}`);let t=await $e(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 _s(e){let t=await $e(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 Ks(e){let t=await $e(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Gt(t),n=i.split(/\r?\n/),o=e.operation.lines.filter(s=>!n.includes(s));if(o.length===0)return;let r=i.length===0||i.endsWith(`
26
26
  `)||!e.operation.ensureNewline?"":`
27
27
  `;await m.appendFile(t,`${r}${o.join(`
28
28
  `)}
29
- `,"utf8");}async function Bs(e){let t=await $e(e.projectPath,e.operation.sourcePath),i=await $e(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 Gs(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}async function Ws(e){let t=await $e(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(Gs);if(o.length===0||o.some(s=>s.length===0||s==="__proto__"||s==="prototype"||s==="constructor"))throw new Error(`Unsupported JSON pointer: ${n.pointer}`);let r=i;for(let s of o.slice(0,-1)){let c=r[s];(!c||typeof c!="object"||Array.isArray(c))&&(r[s]={}),r=r[s];}r[o[o.length-1]]=n.value;}await m.writeJSON(t,i,{spaces:2});}async function Hs(e){let t=await $e(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Bt(t),n=new Set(i.split(/\r?\n/).map(s=>s.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)=/)?.[1]).filter(s=>!!s)),o=[];for(let s of e.operation.keys)n.has(s.name)||(s.comment&&o.push(`# ${s.comment}`),o.push(`${s.name}=${s.value}`));if(o.length===0)return;let r=i.length===0||i.endsWith(`
29
+ `,"utf8");}async function Gs(e){let t=await $e(e.projectPath,e.operation.sourcePath),i=await $e(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 Bs(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}async function Ws(e){let t=await $e(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(Bs);if(o.length===0||o.some(s=>s.length===0||s==="__proto__"||s==="prototype"||s==="constructor"))throw new Error(`Unsupported JSON pointer: ${n.pointer}`);let r=i;for(let s of o.slice(0,-1)){let c=r[s];(!c||typeof c!="object"||Array.isArray(c))&&(r[s]={}),r=r[s];}r[o[o.length-1]]=n.value;}await m.writeJSON(t,i,{spaces:2});}async function Hs(e){let t=await $e(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Gt(t),n=new Set(i.split(/\r?\n/).map(s=>s.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)=/)?.[1]).filter(s=>!!s)),o=[];for(let s of e.operation.keys)n.has(s.name)||(s.comment&&o.push(`# ${s.comment}`),o.push(`${s.name}=${s.value}`));if(o.length===0)return;let r=i.length===0||i.endsWith(`
30
30
  `)?"":`
31
31
  `;await m.appendFile(t,`${r}${o.join(`
32
32
  `)}
33
- `,"utf8");}async function Ls(e){let t=await $e(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Bt(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}`],r=i.length===0||i.endsWith(`
33
+ `,"utf8");}async function Ls(e){let t=await $e(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Gt(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}`],r=i.length===0||i.endsWith(`
34
34
  `)?"":`
35
35
  `;await m.appendFile(t,`${r}${o.join(`
36
36
  `)}
37
- `,"utf8");}async function Bt(e){try{return await m.pathExists(e)?await m.readFile(e,"utf8"):""}catch{return ""}}function qs(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(_t(t))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"};if(Kt(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=Qe(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"}:Be(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"}:Be(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"}:vn(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 Mt(e,t){return e.repairCapabilities?.find(i=>i.command===t)}function dn(e,t){if(t)return e.probes?.find(i=>i.repairCapability?.id===t.id)}function Vs(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 zs(e,t){let i=t.endsWith(`
37
+ `,"utf8");}async function Gt(e){try{return await m.pathExists(e)?await m.readFile(e,"utf8"):""}catch{return ""}}function qs(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(_t(t))return {projectName:e.name,projectPath:e.path,originalCommand:t,kind:"env-copy",risk:"safe",executable:true,reason:"Environment seed copy"};if(Kt(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=Qe(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"}:Ge(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"}:Ge(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"}:vn(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 Mt(e,t){return e.repairCapabilities?.find(i=>i.command===t)}function dn(e,t){if(t)return e.probes?.find(i=>i.repairCapability?.id===t.id)}function Vs(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 zs(e,t){let i=t.endsWith(`
38
38
  `)?t.slice(0,-1).split(`
39
39
  `):t.split(`
40
- `);return ["--- /dev/null",`+++ ${e}`,"@@",...i.map(n=>`+${n}`)]}function Js(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:zs(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 Us(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 Ys(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 Zs(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 Mi(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 Xs(e){return [...e].sort((i,n)=>{let o=Mi(i.phase)-Mi(n.phase);if(o!==0)return o;let r=i.projectName.localeCompare(n.projectName);return r!==0?r:i.id.localeCompare(n.id)}).map((i,n)=>({...i,order:n+1}))}function Qs(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 ea(e,t,i){if(i.kind==="dependency-sync"||i.kind==="go-mod-tidy")return `${e.path}:dependency-baseline`;let n=Qe(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(s=>s.pointer).join(",")}`;if(n?.type==="env-key-add")return `${e.path}:env-key-add:${n.path}:${n.keys.map(s=>s.name).join(",")}`;if(n?.type==="makefile-target")return `${e.path}:makefile-target:${n.path}:${n.target}`;let o=_t(t);if(o)return `${e.path}:file-copy:${u.join(o.projectPath,".env")}`;let r=Kt(t);return r?`${e.path}:package-json-script:${u.join(r.projectPath,"package.json")}:${r.scriptName}`:null}function ta(e,t){return Mt(e,t)?4:Qe(t)?3:Kt(t)?2:_t(t)?1:0}async function fn(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=Mt(h,R);return {project:h,step:qs(h,R),command:R,capability:x,probe:dn(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:dn(h,R)}));return [...w,...P]}),o=[],r=new Map;for(let h of n){let w=ea(h.project,h.command,h.step);if(!w){o.push(h);continue}let P=ta(h.project,h.command),R=r.get(w);if(!R){r.set(w,{index:o.length,priority:P}),o.push(h);continue}P>R.priority&&(o[R.index]=h,r.set(w,{index:R.index,priority:P}));}let s$1=o,c=null,a=new Map,l=[],d=0,p=0,y=0,b=0;for(let h of s$1){let{project:w,step:P,command:R}=h,x=P.executable,g,D=h.capability??Mt(w,R);if(x&&D?.invocation){let H=D.invocation.cwd,G=D.invocation.executable,T=`${H}\0${G}`,O=a.get(T);O===void 0&&(O=await a$3({executable:G,cwd:H}),a.set(T,O)),O||(x=false,g=`Required executable is unavailable: ${G}`);}else P.kind==="go-mod-tidy"&&(c===null&&(c=await io()),c||(x=false,g="Go toolchain not available"));let k=h.probe??dn(w,D),A=k?w.diagnosis?.findings.find(H=>H.probeId===k.id):void 0,j=D?.operation??Qe(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 B=D?.files??(j&&"path"in j?[j.path]:[]),$=k?.repairIntent,V=Ys({step:P,capability:D,executableInCurrentEnvironment:x,blockedReason:g,policyProfile:t}),ce=Zs({step:P,issueClass:k?.issueClass,repairIntent:$,operation:j});l.push({...P,id:Ns({projectName:w.name,kind:P.kind,command:R,operation:j,capabilityId:D?.id}),phase:ce,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:$,files:B,...j?{operation:j}:{},...D?.invocation?{invocation:{cwd:D.invocation.cwd,executable:D.invocation.executable,args:[...D.invocation.args]}}:{},...D?.strategy?{strategy:D.strategy.map(H=>structuredClone(H))}:{},...D?.transaction?{transaction:structuredClone(D.transaction)}:{},preview:Vs({step:P,capability:D,operation:j}),diffPreview:Js({step:P,operation:j}),verifyCommand:D?.verifyCommand,refreshCommands:D?.refreshCommands??["npx workspai doctor project --json"],rollback:Us(P),studioStatus:V,executableInCurrentEnvironment:x,blockedReason:g});}let v=Qs(Xs(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 Ti(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 na(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,"_"),r=u.join(t,".workspai","reports","fix-snapshots",`${o}-${n}`);await m.ensureDir(r);let s=[".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 s){let d=u.join(t,l);if(!await m.pathExists(d))continue;let p=u.join(r,l);await m.ensureDir(u.dirname(p)),await m.copy(d,p,{overwrite:true}),c.set(d,p);}let a={snapshotRoot:r,files:c,missingFiles:new Set};return e.set(t,a),a}async function Je(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 ia(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 oa(e){let i=(await Ot(e,{allowNonRapidkit:true})).diagnosis?.findings.filter(n=>n.status==="blocking")??[];return {issues:i.length,healthy:i.length===0}}async function pn(e){let t=[];for(let i of e){let o=(await Ot(i.path,{allowNonRapidkit:true})).diagnosis?.findings.filter(r=>r.status==="blocking");for(let r of o??[])r.symptom.trim()&&t.push(`${i.name}: ${r.symptom.trim()}`);}return t.slice(0,24)}function Oi(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 Ue(e,t=false,i={}){let n=await fn(e,i.policyProfile);i.artifactRoot&&(i.planOnly||t)&&await mn(i.artifactRoot,n,i.artifactMirrorRoots);let o=e.filter(g=>g.fixCommands&&g.fixCommands.length>0),r=[],s=i.json===true,c=(...g)=>{s||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(s||console.log(f.green(`
40
+ `);return ["--- /dev/null",`+++ ${e}`,"@@",...i.map(n=>`+${n}`)]}function Js(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:zs(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 Us(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 Ys(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 Zs(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 Mi(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 Xs(e){return [...e].sort((i,n)=>{let o=Mi(i.phase)-Mi(n.phase);if(o!==0)return o;let r=i.projectName.localeCompare(n.projectName);return r!==0?r:i.id.localeCompare(n.id)}).map((i,n)=>({...i,order:n+1}))}function Qs(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 ea(e,t,i){if(i.kind==="dependency-sync"||i.kind==="go-mod-tidy")return `${e.path}:dependency-baseline`;let n=Qe(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(s=>s.pointer).join(",")}`;if(n?.type==="env-key-add")return `${e.path}:env-key-add:${n.path}:${n.keys.map(s=>s.name).join(",")}`;if(n?.type==="makefile-target")return `${e.path}:makefile-target:${n.path}:${n.target}`;let o=_t(t);if(o)return `${e.path}:file-copy:${u.join(o.projectPath,".env")}`;let r=Kt(t);return r?`${e.path}:package-json-script:${u.join(r.projectPath,"package.json")}:${r.scriptName}`:null}function ta(e,t){return Mt(e,t)?4:Qe(t)?3:Kt(t)?2:_t(t)?1:0}async function fn(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=Mt(h,R);return {project:h,step:qs(h,R),command:R,capability:x,probe:dn(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:dn(h,R)}));return [...w,...P]}),o=[],r=new Map;for(let h of n){let w=ea(h.project,h.command,h.step);if(!w){o.push(h);continue}let P=ta(h.project,h.command),R=r.get(w);if(!R){r.set(w,{index:o.length,priority:P}),o.push(h);continue}P>R.priority&&(o[R.index]=h,r.set(w,{index:R.index,priority:P}));}let s$1=o,c=null,a=new Map,l=[],d=0,p=0,y=0,k=0;for(let h of s$1){let{project:w,step:P,command:R}=h,x=P.executable,g,D=h.capability??Mt(w,R);if(x&&D?.invocation){let H=D.invocation.cwd,B=D.invocation.executable,T=`${H}\0${B}`,O=a.get(T);O===void 0&&(O=await a$3({executable:B,cwd:H}),a.set(T,O)),O||(x=false,g=`Required executable is unavailable: ${B}`);}else P.kind==="go-mod-tidy"&&(c===null&&(c=await io()),c||(x=false,g="Go toolchain not available"));let b=h.probe??dn(w,D),A=b?w.diagnosis?.findings.find(H=>H.probeId===b.id):void 0,j=D?.operation??Qe(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"&&(k+=1));let G=D?.files??(j&&"path"in j?[j.path]:[]),$=b?.repairIntent,V=Ys({step:P,capability:D,executableInCurrentEnvironment:x,blockedReason:g,policyProfile:t}),ce=Zs({step:P,issueClass:b?.issueClass,repairIntent:$,operation:j});l.push({...P,id:Ns({projectName:w.name,kind:P.kind,command:R,operation:j,capabilityId:D?.id}),phase:ce,order:0,dependsOn:[],...A?{diagnosisFindingId:A.id,causalKey:A.causalKey}:{},issueId:D?.issueId,findingStatus:b?.status==="fail"?"blocking":b?.status==="warn"?"advisory":b?.status==="pass"?"informational":"unknown",issueClass:b?.issueClass,operationalImpact:b?.operationalImpact,repairIntent:$,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(H=>structuredClone(H))}:{},...D?.transaction?{transaction:structuredClone(D.transaction)}:{},preview:Vs({step:P,capability:D,operation:j}),diffPreview:Js({step:P,operation:j}),verifyCommand:D?.verifyCommand,refreshCommands:D?.refreshCommands??["npx workspai doctor project --json"],rollback:Us(P),studioStatus:V,executableInCurrentEnvironment:x,blockedReason:g});}let v=Qs(Xs(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:k},steps:v}}function Ti(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 na(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,"_"),r=u.join(t,".workspai","reports","fix-snapshots",`${o}-${n}`);await m.ensureDir(r);let s=[".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 s){let d=u.join(t,l);if(!await m.pathExists(d))continue;let p=u.join(r,l);await m.ensureDir(u.dirname(p)),await m.copy(d,p,{overwrite:true}),c.set(d,p);}let a={snapshotRoot:r,files:c,missingFiles:new Set};return e.set(t,a),a}async function Je(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 ia(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 oa(e){let i=(await Ot(e,{allowNonRapidkit:true})).diagnosis?.findings.filter(n=>n.status==="blocking")??[];return {issues:i.length,healthy:i.length===0}}async function pn(e){let t=[];for(let i of e){let o=(await Ot(i.path,{allowNonRapidkit:true})).diagnosis?.findings.filter(r=>r.status==="blocking");for(let r of o??[])r.symptom.trim()&&t.push(`${i.name}: ${r.symptom.trim()}`);}return t.slice(0,24)}function Oi(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 Ue(e,t=false,i={}){let n=await fn(e,i.policyProfile);i.artifactRoot&&(i.planOnly||t)&&await mn(i.artifactRoot,n,i.artifactMirrorRoots);let o=e.filter(g=>g.fixCommands&&g.fixCommands.length>0),r=[],s=i.json===true,c=(...g)=>{s||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(s||console.log(f.green(`
41
41
  \u2705 No fixes needed - all projects are healthy!`)),t){let g=Oe({appliedFixes:[],remainingBlockers:[],verifyRecommended:De});return i.artifactRoot&&(await Ze(i.artifactRoot,g,i.artifactMirrorRoots),await Xe(i.artifactRoot,g,i.historyScope??"project")),g}return}if(!s){console.log(f.bold.cyan(`
42
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(Ft(g,k))}`);}),console.log();}}if(i.planOnly){if(i.json){console.log(JSON.stringify(n,null,2));return}console.log(f.bold(`
43
+ `));for(let g of o){let D=g.fixCommands??[];console.log(f.bold(`Project: ${f.yellow(g.name)}`)),D.forEach((b,A)=>{console.log(` ${A+1}. ${f.cyan(Ft(g,b))}`);}),console.log();}}if(i.planOnly){if(i.json){console.log(JSON.stringify(n,null,2));return}console.log(f.bold(`
44
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?Ft(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=n.risk.guarded,v=n.risk.invasive;if(p===0){if(s||(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=Oe({appliedFixes:[],remainingBlockers:await pn(e),verifyRecommended:De});return i.artifactRoot&&(await Ze(i.artifactRoot,g,i.artifactMirrorRoots),await Xe(i.artifactRoot,g,i.historyScope??"project")),g}return}if(!t){s||console.log(f.gray('\u{1F4A1} Run "npx workspai doctor workspace --fix" to apply fixes automatically'));return}if(s||console.log(f.gray(`Risk policy: safe=${y}, guarded=${b}, invasive=${v}. Guarded/invasive fixes use snapshot + rollback.`)),!i.skipConfirmation){let{confirm:g}=await b$1([{type:"confirm",name:"confirm",message:`Apply ${o.reduce((D,k)=>D+(k.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!g){s||console.log(f.yellow(`
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),b=g.executableInCurrentEnvironment?f.green("ready"):f.yellow(`blocked${g.blockedReason?` (${g.blockedReason})`:""}`);console.log(` - ${f.cyan(g.projectName)} [${g.risk}] ${D?Ft(D,g.originalCommand):g.preview.title} ${f.gray(`=> ${b}`)}`);}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,k=n.risk.guarded,v=n.risk.invasive;if(p===0){if(s||(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=Oe({appliedFixes:[],remainingBlockers:await pn(e),verifyRecommended:De});return i.artifactRoot&&(await Ze(i.artifactRoot,g,i.artifactMirrorRoots),await Xe(i.artifactRoot,g,i.historyScope??"project")),g}return}if(!t){s||console.log(f.gray('\u{1F4A1} Run "npx workspai doctor workspace --fix" to apply fixes automatically'));return}if(s||console.log(f.gray(`Risk policy: safe=${y}, guarded=${k}, invasive=${v}. Guarded/invasive fixes use snapshot + rollback.`)),!i.skipConfirmation){let{confirm:g}=await b$1([{type:"confirm",name:"confirm",message:`Apply ${o.reduce((D,b)=>D+(b.fixCommands?.length??0),0)} fix(es)?`,default:false}]);if(!g){s||console.log(f.yellow(`
47
47
  \u26A0\uFE0F Fixes cancelled by user`));let D=Oe({appliedFixes:[],remainingBlockers:await pn(e),verifyRecommended:De});return i.artifactRoot&&(await Ze(i.artifactRoot,D,i.artifactMirrorRoots),await Xe(i.artifactRoot,D,i.historyScope??"project")),D}}s||console.log(f.bold.cyan(`
48
48
  \u{1F680} Applying fixes...
49
- `));let C=new Set,h=new Map(o.map(g=>[g.path,g])),w=new Set,P=Is(),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;s||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(` ${Ft(D,k)}`)),g.kind==="manual-url"){c(f.yellow(` \u2139 Manual action required: open ${k}`)),c(f.green(` \u2705 Recorded as guidance
49
+ `));let C=new Set,h=new Map(o.map(g=>[g.path,g])),w=new Set,P=Is(),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 b=g.originalCommand;s||x!==g.projectName&&(x=g.projectName,console.log(f.bold(`Fixing ${f.cyan(g.projectName)}...`)));let A=`${g.projectPath}::${b}`;if(!C.has(A)){C.add(A);try{if(c(f.gray(` ${Ft(D,b)}`)),g.kind==="manual-url"){c(f.yellow(` \u2139 Manual action required: open ${b}`)),c(f.green(` \u2705 Recorded as guidance
50
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=Qe(k),$=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 na(d,g.projectPath):null;$&&j?.type==="file-create"&&await Je($,j.path),$&&j?.type==="file-append"&&await Je($,j.path),$&&j?.type==="file-copy"&&await Je($,j.path),$&&j?.type==="json-edit"&&await Je($,j.path),$&&j?.type==="env-key-add"&&await Je($,j.path),$&&j?.type==="makefile-target"&&await Je($,j.path);let V=_t(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),r.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 Bs({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
54
- `));continue}let ce=Kt(k);if(ce){await Os(ce),w.add(g.projectPath),r.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 _s({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.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 Ks({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.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 Ws({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.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 Hs({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.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 Ls({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
60
- `));continue}let H=Be(k,"(?:npx\\s+workspai|rapidkit)\\s+init");if(H){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.")),r.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:H.projectPath,shell:c$1(),stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
61
- `));continue}let G=Be(k,"go\\s+mod\\s+tidy");if(G){if(a===null&&(a=await io()),!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:G.projectPath,shell:c$1(),stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k}),c(f.green(` \u2705 Success
63
- `));continue}let T=vn(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.")),r.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,Ge,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 et=1;et<=re;et+=1)try{await execa(T.command,T.args,{cwd:T.projectPath,env:z,shell:c$1(),stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),Ge=null;break}catch(yt){if(Ge=yt,et<re&&Ti(yt)){c(f.yellow(` \u26A0 Retrying dependency sync (${et}/${re-1})...`));continue}throw yt}if(Ge)throw Ge;w.add(g.projectPath),r.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,ye;for(let oe=1;oe<=O;oe+=1)try{await execa(k,{shell:true,stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),ye=null;break}catch(re){if(ye=re,oe<O&&Ti(re)){c(f.yellow(` \u26A0 Retrying command (${oe}/${O-1})...`));continue}throw re}if(ye)throw ye;s||console.log(f.green(` \u2705 Success
65
- `)),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:k});}catch(j){let B=Qe(k);if(g.risk!=="safe"||B?.type==="file-create"||B?.type==="file-append"||B?.type==="file-copy"||B?.type==="json-edit"||B?.type==="env-key-add"||B?.type==="makefile-target"){let $=d.get(g.projectPath);if($)try{await ia($),s||console.log(f.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(V){s||console.log(f.red(` \u274C Rollback failed: ${V instanceof Error?V.message:String(V)}`));}}s||console.log(f.red(` \u274C Failed: ${j instanceof Error?j.message:String(j)}
66
- `)),r.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 oa(g.path);s||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){s||console.log(f.yellow(` \u26A0 Post-fix verification skipped: ${D instanceof Error?D.message:String(D)}`));}if(s||console.log(f.bold.green(`
51
+ `));continue}let j=Qe(b),$=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 na(d,g.projectPath):null;$&&j?.type==="file-create"&&await Je($,j.path),$&&j?.type==="file-append"&&await Je($,j.path),$&&j?.type==="file-copy"&&await Je($,j.path),$&&j?.type==="json-edit"&&await Je($,j.path),$&&j?.type==="env-key-add"&&await Je($,j.path),$&&j?.type==="makefile-target"&&await Je($,j.path);let V=_t(b);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),r.push({path:re,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
53
+ `));continue}if(j?.type==="file-copy"){await Gs({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
54
+ `));continue}let ce=Kt(b);if(ce){await Os(ce),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
55
+ `));continue}if(j?.type==="file-create"){await _s({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
56
+ `));continue}if(j?.type==="file-append"){await Ks({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
57
+ `));continue}if(j?.type==="json-edit"){await Ws({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
58
+ `));continue}if(j?.type==="env-key-add"){await Hs({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
59
+ `));continue}if(j?.type==="makefile-target"){await Ls({projectPath:g.projectPath,operation:j}),w.add(g.projectPath),r.push({path:j.path,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
60
+ `));continue}let H=Ge(b,"(?:npx\\s+workspai|rapidkit)\\s+init");if(H){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.")),r.push({path:g.projectPath,action:g.kind,outcome:"guidance",projectName:g.projectName,command:b,detail:"Guarded setup command was not auto-executed by doctor --fix. Run it explicitly after review."});continue}await execa("rapidkit",["init"],{cwd:H.projectPath,shell:c$1(),stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
61
+ `));continue}let B=Ge(b,"go\\s+mod\\s+tidy");if(B){if(a===null&&(a=await io()),!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:B.projectPath,shell:c$1(),stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
63
+ `));continue}let T=vn(b);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.")),r.push({path:g.projectPath,action:g.kind,outcome:"guidance",projectName:g.projectName,command:b,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 et=1;et<=re;et+=1)try{await execa(T.command,T.args,{cwd:T.projectPath,env:z,shell:c$1(),stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),Be=null;break}catch(yt){if(Be=yt,et<re&&Ti(yt)){c(f.yellow(` \u26A0 Retrying dependency sync (${et}/${re-1})...`));continue}throw yt}if(Be)throw Be;w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:b}),c(f.green(` \u2705 Success
64
+ `));continue}let O=g.kind==="shell"?2:1,he;for(let oe=1;oe<=O;oe+=1)try{await execa(b,{shell:true,stdio:s?"pipe":"inherit",timeout:P,forceKillAfterDelay:1e3}),he=null;break}catch(re){if(he=re,oe<O&&Ti(re)){c(f.yellow(` \u26A0 Retrying command (${oe}/${O-1})...`));continue}throw re}if(he)throw he;s||console.log(f.green(` \u2705 Success
65
+ `)),w.add(g.projectPath),r.push({path:g.projectPath,action:g.kind,outcome:"applied",projectName:g.projectName,command:b});}catch(j){let G=Qe(b);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 $=d.get(g.projectPath);if($)try{await ia($),s||console.log(f.yellow(" \u21A9 Rolled back snapshot after failed fix"));}catch(V){s||console.log(f.red(` \u274C Rollback failed: ${V instanceof Error?V.message:String(V)}`));}}s||console.log(f.red(` \u274C Failed: ${j instanceof Error?j.message:String(j)}
66
+ `)),r.push({path:g.projectPath,action:g.kind,outcome:"failed",projectName:g.projectName,command:b,detail:j instanceof Error?j.message:String(j)});}}}for(let g of o)if(w.has(g.path))try{let D=await oa(g.path);s||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){s||console.log(f.yellow(` \u26A0 Post-fix verification skipped: ${D instanceof Error?D.message:String(D)}`));}if(s||console.log(f.bold.green(`
67
67
  \u2705 Fix process completed!`)),t){let g=Oe({appliedFixes:r,remainingBlockers:await pn(e),verifyRecommended:De});return i.artifactRoot&&(await Ze(i.artifactRoot,g,i.artifactMirrorRoots),await Xe(i.artifactRoot,g,i.historyScope??"project")),g}}function gt(e,t){let i=Tt(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=gt(e,t);return i?.appliedFixes.some(r=>r.outcome==="failed")??false?Math.max(n,1):n}async function al(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=Tt({profile:e$1.profile,strict:e$1.strict,ci:e$1.ci}),o=!!(e$1.fix||e$1.plan||e$1.apply),r=typeof e$1.workspace=="string"&&e$1.workspace.trim().length>0?u.resolve(e$1.workspace):null,s=!r&&!e$1.workspace&&!e$1.project&&o?await ft(process.cwd()):null,c$1=!!e$1.workspace||!!s,a=!!e$1.project&&!c$1;if(e$1.json||console.log(f.bold.cyan(`
68
68
  \u{1FA7A} Workspai Health Check
69
- `)),c$1){let l=r??s??await ft(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||(s&&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 ln(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 fn(p.projects,n.name):void 0,j=A?await mn(l,A):void 0;(e$1.plan||e$1.fix||e$1.apply)&&t("doctor.plan","succeeded","Governed remediation plan ready");let B;(e$1.fix||e$1.apply)&&!e$1.plan&&(k=await Ue(p.projects,true,{skipConfirmation:e$1.apply===true||e$1.fix===true,json:true,policyProfile:n.name})??Oe({appliedFixes:[],remainingBlockers:[],verifyRecommended:De}),t("doctor.verify","running","Verifying workspace after remediation"),p=await ln(l,false,n,true),t("doctor.verify","succeeded","Post-remediation workspace verification completed"),k={...k,remainingBlockers:Oi(p.projects)},B=await Ze(l,k),await Xe(l,k,"workspace"));let $=p.projects.map(ee),V=$.reduce((T,O)=>T+O.blockingFindings,0),ce=$.reduce((T,O)=>T+O.advisoryFindings,0),H=Fe(p.projects,[p.python,p.poetry,p.pipx,p.go,p.rapidkitCore,p.cliResolution]),G={contract:Ye(),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=>$i(T)),summary:{counts:H,totalProjects:p.projects.length,totalIssues:p.projects.reduce((T,O)=>T+O.issues.length,0),verdict:p.healthScore?.verdict??"passed",blockingFindings:V,advisoryFindings:ce,projectAdvisoryWarningProjects:$.filter(T=>T.advisoryFindings>0).length,projectAdvisoryWarnings:ce,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:B}:{}};if(!e$1.quiet){let T=e$1.json==="summary"?{schemaVersion:At,generatedAt:p.evidenceFreshness?.generatedAt??new Date().toISOString(),scope:"workspace",workspace:G.workspace,verdict:p.healthScore?.verdict??"passed",counts:H,freshness:p.evidenceFreshness,affectedProjects:p.projects.map(O=>{let ye=ee(O);return {name:O.name,path:O.path,runtimeFamily:O.runtimeFamily??"unknown",projectArchetype:O.projectArchetype??"unknown",verdict:ye.verdict,blockingCauses:O.diagnosis?.coverage.blockingFindings??ye.blockingFindings,advisoryFindings:O.diagnosis?.coverage.advisoryFindings??ye.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}:{},...B?{fixResult:B}:{}}}:G;console.log(JSON.stringify(T,null,2));}return _i(p.healthScore,{profile:n.name},k)}let y=Fe(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(`
69
+ `)),c$1){let l=r??s??await ft(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||(s&&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 ln(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 b;(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 fn(p.projects,n.name):void 0,j=A?await mn(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&&(b=await Ue(p.projects,true,{skipConfirmation:e$1.apply===true||e$1.fix===true,json:true,policyProfile:n.name})??Oe({appliedFixes:[],remainingBlockers:[],verifyRecommended:De}),t("doctor.verify","running","Verifying workspace after remediation"),p=await ln(l,false,n,true),t("doctor.verify","succeeded","Post-remediation workspace verification completed"),b={...b,remainingBlockers:Oi(p.projects)},G=await Ze(l,b),await Xe(l,b,"workspace"));let $=p.projects.map(ee),V=$.reduce((T,O)=>T+O.blockingFindings,0),ce=$.reduce((T,O)=>T+O.advisoryFindings,0),H=Fe(p.projects,[p.python,p.poetry,p.pipx,p.go,p.rapidkitCore,p.cliResolution]),B={contract:Ye(),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=>$i(T)),summary:{counts:H,totalProjects:p.projects.length,totalIssues:p.projects.reduce((T,O)=>T+O.issues.length,0),verdict:p.healthScore?.verdict??"passed",blockingFindings:V,advisoryFindings:ce,projectAdvisoryWarningProjects:$.filter(T=>T.advisoryFindings>0).length,projectAdvisoryWarnings:ce,hasSystemErrors:[p.python,p.rapidkitCore].some(T=>T.status==="error"),scopeProvenance:p.scopeProvenance},driftDelta:p.driftDelta,scoreBreakdown:p.scoreBreakdown??[],...A?{remediationPlan:A,remediationPlanPath:j}:{},...b?{appliedFixes:b.appliedFixes,remainingBlockers:b.remainingBlockers,verifyRecommended:b.verifyRecommended,fixResult:b,fixResultPath:G}:{}};if(!e$1.quiet){let T=e$1.json==="summary"?{schemaVersion:At,generatedAt:p.evidenceFreshness?.generatedAt??new Date().toISOString(),scope:"workspace",workspace:B.workspace,verdict:p.healthScore?.verdict??"passed",counts:H,freshness:p.evidenceFreshness,affectedProjects:p.projects.map(O=>{let he=ee(O);return {name:O.name,path:O.path,runtimeFamily:O.runtimeFamily??"unknown",projectArchetype:O.projectArchetype??"unknown",verdict:he.verdict,blockingCauses:O.diagnosis?.coverage.blockingFindings??he.blockingFindings,advisoryFindings:O.diagnosis?.coverage.advisoryFindings??he.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}:{}}}:B;console.log(JSON.stringify(T,null,2));}return _i(p.healthScore,{profile:n.name},b)}let y=Fe(p.projects,[p.python,p.poetry,p.pipx,p.go,p.rapidkitCore,p.cliResolution]),k=p.healthScore?.verdict??"passed",v=k==="blocked"?"\u274C":k==="attention"?"\u26A0\uFE0F":"\u2705",C=k==="blocked"?f.red:k==="attention"?f.yellow:f.green;if(console.log(`
70
+ ${v} ${C.bold(k.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 b=p.healthScore;console.log(f.bold(`
71
+ \u{1F4CA} Diagnostic accounting:`)),console.log(` ${f.green(`${b.passed} passed`)} ${f.gray("|")} ${f.yellow(`${b.warnings} warnings`)} ${f.gray("|")} ${f.red(`${b.errors} errors`)} ${f.gray("|")} ${b.presentation.notApplicableChecks} N/A`),console.log(f.dim(` Diagnostic pass rate: ${b.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(([b])=>b.applicability!=="not-applicable");console.log(f.bold(`
72
72
 
73
73
  System Tools:
74
- `)),w.length===0?console.log(f.gray("No host prerequisites apply to the detected primary runtimes.")):w.forEach(([k,A])=>Ae(k,A)),Rr({coreVersion:p.coreVersion,npmVersion:p.npmVersion})&&(console.log(f.yellow(`
74
+ `)),w.length===0?console.log(f.gray("No host prerequisites apply to the detected primary runtimes.")):w.forEach(([b,A])=>Ae(b,A)),Rr({coreVersion:p.coreVersion,npmVersion:p.npmVersion})&&(console.log(f.yellow(`
75
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=>Ni(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 Ue(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 Ue(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 ln(l,false,n,true);t("doctor.verify","succeeded","Post-remediation workspace verification completed");let A=k.projects.map(ee).reduce((B,$)=>B+$.blockingFindings,0),j=[k.python,k.rapidkitCore].some(B=>B.status==="error");j||A>0?(console.log(f.bold.yellow(`
76
+ \u{1F4E6} Projects (${p.projects.length}):`)),p.projects.forEach(b=>Ni(b,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((b,A)=>b+A.blockingFindings,0),x=P.reduce((b,A)=>b+A.advisoryFindings,0),g=P.reduce((b,A)=>b+A.unknownFindings+A.contradictionFindings,0),D=[p.python,p.rapidkitCore].some(b=>b.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 Ue(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 Ue(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 b=await ln(l,false,n,true);t("doctor.verify","succeeded","Post-remediation workspace verification completed");let A=b.projects.map(ee).reduce((G,$)=>G+$.blockingFindings,0),j=[b.python,b.rapidkitCore].some(G=>G.status==="error");j||A>0?(console.log(f.bold.yellow(`
79
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(`
80
+ \u2705 Post-fix verification passed. Workspace is healthy.`)),b.projectScanCached&&console.log(f.gray(`\u2139\uFE0F Reused cached project scan${b.projectScanCachePath?` (${u.basename(b.projectScanCachePath)})`:""}`)),b.evidencePath&&console.log(f.gray(`\u2139\uFE0F Evidence refreshed: ${b.evidencePath}`));}}else R>0&&(console.log(f.bold.cyan(`
81
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 gt(p.healthScore,{profile:n.name})}else if(a){let l=await Cs(process.cwd());if(!l){let x=await ft(process.cwd());if(e$1.json){let g={contract:Ye(),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 Ii(l,n,e$1.fresh===true);i("Project",d.healthScore);let p=d.workspacePath?Fi(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 fn([d.project],n.name):void 0,D=l,k=[],A=g?await mn(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 Ue([d.project],true,{skipConfirmation:e$1.apply===true||e$1.fix===true,json:true,policyProfile:n.name})??Oe({appliedFixes:[],remainingBlockers:[],verifyRecommended:De}),t("doctor.verify","running","Verifying project after remediation"),d=await Ii(l,n,true),t("doctor.verify","succeeded","Post-remediation project verification completed"),x={...x,remainingBlockers:Oi([d.project])},j=await Ze(D,x,k),await Xe(D,x,"project"));let B=Fi(d.project.path),$=ee(d.project),V=Fe([d.project],[d.python,d.poetry,d.pipx,d.go,d.rapidkitCore,d.cliResolution]),ce={contract:Ye(),policyProfile:n,scope:"project",workspace:p?{name:await b(p),path:p}:null,project:{...$i(d.project),path:B},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:$.verdict,probeSummary:$,blockingFindings:$.blockingFindings,advisoryFindings:$.advisoryFindings,projectAdvisoryWarningProjects:$.advisoryFindings>0?1:0,projectAdvisoryWarnings:$.advisoryFindings,hasSystemErrors:[d.python,d.rapidkitCore].some(H=>H.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 H=e$1.json==="summary"?{schemaVersion:At,generatedAt:d.evidenceFreshness?.generatedAt??new Date().toISOString(),scope:"project",workspace:ce.workspace,project:{name:d.project.name,path:B,runtimeFamily:d.project.runtimeFamily??"unknown",framework:d.project.framework??"Unknown",projectArchetype:d.project.projectArchetype??"unknown"},verdict:$.verdict,counts:V,freshness:d.evidenceFreshness,blockers:(d.project.diagnosis?.findings??[]).filter(G=>G.status==="blocking").map(G=>({id:G.id,issueClass:G.issueClass,symptom:G.symptom,repairDisposition:G.repair.disposition,...G.repair.capabilityId?{capabilityId:G.repair.capabilityId}:{}})),artifacts:{evidence:d.evidencePath,receipt:d.receiptPath,...A?{remediationPlan:A}:{},...j?{fixResult:j}:{}}}:ce;console.log(JSON.stringify(H,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$1=[[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$1:b$1.filter(([x])=>x.applicability!=="not-applicable");console.log(f.bold(`
82
+ \u2705 All checks passed! Workspace is healthy.`));return gt(p.healthScore,{profile:n.name})}else if(a){let l=await Cs(process.cwd());if(!l){let x=await ft(process.cwd());if(e$1.json){let g={contract:Ye(),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 Ii(l,n,e$1.fresh===true);i("Project",d.healthScore);let p=d.workspacePath?Fi(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 fn([d.project],n.name):void 0,D=l,b$1=[],A=g?await mn(D,g,b$1):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 Ue([d.project],true,{skipConfirmation:e$1.apply===true||e$1.fix===true,json:true,policyProfile:n.name})??Oe({appliedFixes:[],remainingBlockers:[],verifyRecommended:De}),t("doctor.verify","running","Verifying project after remediation"),d=await Ii(l,n,true),t("doctor.verify","succeeded","Post-remediation project verification completed"),x={...x,remainingBlockers:Oi([d.project])},j=await Ze(D,x,b$1),await Xe(D,x,"project"));let G=Fi(d.project.path),$=ee(d.project),V=Fe([d.project],[d.python,d.poetry,d.pipx,d.go,d.rapidkitCore,d.cliResolution]),ce={contract:Ye(),policyProfile:n,scope:"project",workspace:p?{name:await b(p),path:p}:null,project:{...$i(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:$.verdict,probeSummary:$,blockingFindings:$.blockingFindings,advisoryFindings:$.advisoryFindings,projectAdvisoryWarningProjects:$.advisoryFindings>0?1:0,projectAdvisoryWarnings:$.advisoryFindings,hasSystemErrors:[d.python,d.rapidkitCore].some(H=>H.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 H=e$1.json==="summary"?{schemaVersion:At,generatedAt:d.evidenceFreshness?.generatedAt??new Date().toISOString(),scope:"project",workspace:ce.workspace,project:{name:d.project.name,path:G,runtimeFamily:d.project.runtimeFamily??"unknown",framework:d.project.framework??"Unknown",projectArchetype:d.project.projectArchetype??"unknown"},verdict:$.verdict,counts:V,freshness:d.evidenceFreshness,blockers:(d.project.diagnosis?.findings??[]).filter(B=>B.status==="blocking").map(B=>({id:B.id,issueClass:B.issueClass,symptom:B.symptom,repairDisposition:B.repair.disposition,...B.repair.capabilityId?{capabilityId:B.repair.capabilityId}:{}})),artifacts:{evidence:d.evidencePath,receipt:d.receiptPath,...A?{remediationPlan:A}:{},...j?{fixResult:j}:{}}}:ce;console.log(JSON.stringify(H,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 k=[[d.python,"Python"],[d.poetry,"Poetry"],[d.pipx,"pipx"],[d.go,"Go"],[d.rapidkitCore,"RapidKit Core"],[d.cliResolution,"CLI resolution"]],v=e$1.verbose?k:k.filter(([x])=>x.applicability!=="not-applicable");console.log(f.bold(`
84
84
 
85
85
  System Tools:
86
86
  `)),v.length===0?console.log(f.gray("No host prerequisites apply to the detected primary runtime.")):v.forEach(([x,g])=>Ae(x,g)),console.log(f.bold(`
87
87
  \u{1F4E6} Project (1):`)),Ni(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
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 Ue([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 Ue([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
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 gt(d.healthScore,{profile:n.name})}else {let l=await bn(),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=kn(h,[]);i("System",w);let P=[d,v].filter(x=>x.status==="error").length;if(e$1.json){let x=new Date().toISOString(),g=Fe([],h),D={contract:Ye(),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:At,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
- `)),Ae(d,"Python"),Ae(p,"Poetry"),Ae(y,"pipx"),Ae(b,"Go"),Ae(v,"RapidKit Core"),C.applicability!=="not-applicable"&&Ae(C,"CLI resolution"),[d,v].some(x=>x.status==="error")?(console.log(f.bold.red(`
90
+ \u2705 All checks passed! Project is healthy.`));return gt(d.healthScore,{profile:n.name})}else {let l=await kn(),d=l.python,p=l.poetry,y=l.pipx,k=l.go,v=l.rapidkitCore,C=l.cliResolution,h=[d,p,y,k,v,C],w=bn(h,[]);i("System",w);let P=[d,v].filter(x=>x.status==="error").length;if(e$1.json){let x=new Date().toISOString(),g=Fe([],h),D={contract:Ye(),policyProfile:n,scope:"system",status:P>0?"error":"ok",generatedAt:x,healthScore:w,system:{python:d,poetry:p,pipx:y,go:k,rapidkitCore:v,cliResolution:C},summary:{totalChecks:h.length,errors:P,warnings:h.filter(b=>b.status==="warn").length,recommendedScopes:["workspace","project"]},nextActions:["npx workspai doctor workspace --json","npx workspai doctor project --json"]};if(!e$1.quiet){let b=e$1.json==="summary"?{schemaVersion:At,generatedAt:x,scope:"system",verdict:w.verdict,counts:g,system:Object.fromEntries(Object.entries({python:d,poetry:p,pipx:y,go:k,rapidkitCore:v,cliResolution:C}).map(([A,j])=>[A,{status:j.status,message:j.message}])),nextActions:D.nextActions}:D;console.log(JSON.stringify(b,null,2));}return (e$1.strict||e$1.ci)&&P>0?1:0}return console.log(f.bold(`System Tools:
91
+ `)),Ae(d,"Python"),Ae(p,"Poetry"),Ae(y,"pipx"),Ae(k,"Go"),Ae(v,"RapidKit Core"),C.applicability!=="not-applicable"&&Ae(C,"CLI resolution"),[d,v].some(x=>x.status==="error")?(console.log(f.bold.red(`
92
92
  \u274C Some required tools are missing`)),(e$1.fix||e$1.apply)&&console.log(f.gray(`
93
93
  Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "workspai doctor workspace --fix"`)),console.log(f.gray(`
94
94
  Tip: Run "workspai doctor workspace" for workspace-wide checks, or "workspai doctor project" for the current project`))):(console.log(f.bold.green(`
95
95
  \u2705 All required tools are installed!`)),(e$1.fix||e$1.apply)&&console.log(f.gray(`
96
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{fo as a,rn as b,At as c,un as d,Tt as e,ds as f,Kt as g,Qe as h,Ms as i,Ts as j,$e as k,Os as l,_s as m,Ks as n,Bs as o,Gs as p,Ws as q,Hs as r,Ls as s,gt as t,_i as u,al as v};
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{fo as a,rn as b,At as c,un as d,Tt as e,ds as f,Kt as g,Qe as h,Ms as i,Ts as j,$e as k,Os as l,_s as m,Ks as n,Gs as o,Bs as p,Ws as q,Hs as r,Ls as s,gt as t,_i as u,al as v};