workspai 0.69.0 → 0.70.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 (101) hide show
  1. package/contracts/workspace-intelligence/decision-event.v1.json +20 -0
  2. package/contracts/workspace-intelligence/proof-carrying-change-capsule.v1.json +1 -0
  3. package/dist/analyze-OGWDSPXQ.js +1 -0
  4. package/dist/{artifact-remediation-plan-JHHZ4L24.js → artifact-remediation-plan-URQL5MBN.js} +1 -1
  5. package/dist/autopilot-release-QQDFEPT7.js +1 -0
  6. package/dist/capabilities-command-NFGX42CH.js +1 -0
  7. package/dist/chunk-37SWTS2B.js +1 -0
  8. package/dist/{chunk-M37ALD4V.js → chunk-3S2U7WRM.js} +1 -1
  9. package/dist/{chunk-N2Q4MSSP.js → chunk-4R7STECB.js} +5 -5
  10. package/dist/{chunk-AD4ZY3RF.js → chunk-AGZWDYMF.js} +1 -1
  11. package/dist/{chunk-OU3BBWH5.js → chunk-DNZHKBQ3.js} +5 -5
  12. package/dist/chunk-EP6Q2QBU.js +1 -0
  13. package/dist/chunk-FE5R6EUV.js +2 -0
  14. package/dist/{chunk-V6TIT6M3.js → chunk-GED7JURY.js} +1 -1
  15. package/dist/{chunk-EBEAJIBI.js → chunk-GL3KLNIG.js} +1 -1
  16. package/dist/{chunk-37ZLNFV5.js → chunk-IET57ZKN.js} +2 -2
  17. package/dist/{chunk-EG6EZ7HW.js → chunk-IFHM2SI6.js} +1 -1
  18. package/dist/chunk-IHKG5C6G.js +1 -0
  19. package/dist/{chunk-A3MYO55A.js → chunk-IRLKWRLP.js} +2 -2
  20. package/dist/chunk-JK6XEF7K.js +6 -0
  21. package/dist/{chunk-MAWHHHU3.js → chunk-LE2I2E6R.js} +2 -2
  22. package/dist/{chunk-BM2F5C4J.js → chunk-LU6CYDLN.js} +1 -1
  23. package/dist/chunk-N6FJZ62B.js +2 -0
  24. package/dist/chunk-PTSEDZIV.js +2 -0
  25. package/dist/chunk-QNHKUSBH.js +1 -0
  26. package/dist/chunk-QZODGRAI.js +2 -0
  27. package/dist/chunk-S2TOSHQW.js +4 -0
  28. package/dist/chunk-S42KDOGG.js +1 -0
  29. package/dist/chunk-TEMFNVO2.js +2 -0
  30. package/dist/{chunk-WZ5V5U2K.js → chunk-TLMP2MGH.js} +1 -1
  31. package/dist/chunk-UT57IFS4.js +8 -0
  32. package/dist/chunk-WUXJCSYO.js +9 -0
  33. package/dist/{chunk-MHQHRMKU.js → chunk-XSSNM4F5.js} +2 -2
  34. package/dist/{chunk-YKY4JFCF.js → chunk-XVTN5DDV.js} +1 -1
  35. package/dist/{chunk-3G5FF2JZ.js → chunk-Z7JIUA6I.js} +1 -1
  36. package/dist/{chunk-ABMB6MJT.js → chunk-ZLCLGIM6.js} +1 -1
  37. package/dist/{chunk-XPGCFVGC.js → chunk-ZPOZ6MDX.js} +1 -1
  38. package/dist/{create-GWBQ74ZI.js → create-BBALBC3U.js} +1 -1
  39. package/dist/{doctor-OQAXSMEM.js → doctor-WWVY7NB6.js} +1 -1
  40. package/dist/{goal-lifecycle-YWBVQ2DF.js → goal-lifecycle-CEUTKUNV.js} +1 -1
  41. package/dist/{goal-pack-KUXPZVNO.js → goal-pack-JQL3YOKT.js} +1 -1
  42. package/dist/index.js +40 -40
  43. package/dist/pipeline-V46WWMP4.js +5 -0
  44. package/dist/{project-agent-entry-H3JAGNLS.js → project-agent-entry-MRAYG7QD.js} +1 -1
  45. package/dist/{project-intelligence-lens-7NMKHV5N.js → project-intelligence-lens-4BKPN4PE.js} +1 -1
  46. package/dist/{project-test-coverage-3DKZKLWY.js → project-test-coverage-4RRCHY5W.js} +1 -1
  47. package/dist/proof-carrying-change-B7ONTBYO.js +1 -0
  48. package/dist/{verified-goal-7XHRWYSE.js → verified-goal-YNSBL7L3.js} +1 -1
  49. package/dist/{workspace-TJHCETBV.js → workspace-FJ6JRYWA.js} +1 -1
  50. package/dist/{workspace-agent-sync-Z35NTXCB.js → workspace-agent-sync-V33UGII3.js} +1 -1
  51. package/dist/{workspace-context-KNJQUJWC.js → workspace-context-O6UBCBEA.js} +1 -1
  52. package/dist/{workspace-contract-VIUQT5SZ.js → workspace-contract-S2JYDA4K.js} +1 -1
  53. package/dist/{workspace-explain-HM6GMK26.js → workspace-explain-RP6VJ6QM.js} +1 -1
  54. package/dist/{workspace-feedback-YSPEGCON.js → workspace-feedback-D6HJLKBQ.js} +1 -1
  55. package/dist/{workspace-foundation-PLXFPI3J.js → workspace-foundation-7QXEJJKZ.js} +1 -1
  56. package/dist/{workspace-graph-stream-FNRQ2FTB.js → workspace-graph-stream-YY65R5EC.js} +1 -1
  57. package/dist/{workspace-history-HDDFG6LH.js → workspace-history-WWPS4U7H.js} +1 -1
  58. package/dist/{workspace-intelligence-QLSD5EEV.js → workspace-intelligence-LMR42ICR.js} +1 -1
  59. package/dist/{workspace-intelligence-runner-4EW4T2OW.js → workspace-intelligence-runner-FXFSTCHC.js} +1 -1
  60. package/dist/{workspace-knowledge-graph-EEOW5VAJ.js → workspace-knowledge-graph-3564KQXT.js} +1 -1
  61. package/dist/workspace-knowledge-graph-snapshot-P27RPMV5.js +1 -0
  62. package/dist/workspace-mcp-serve-ZK46EZUD.js +3 -0
  63. package/dist/{workspace-model-NCOOY5LC.js → workspace-model-6UMQAGUK.js} +1 -1
  64. package/dist/{workspace-onboarding-JNC7ZFMR.js → workspace-onboarding-C57OQ7XZ.js} +1 -1
  65. package/dist/{workspace-readme-OV2ADTLW.js → workspace-readme-HA6XLDME.js} +2 -2
  66. package/dist/{workspace-registry-summary-ONT4VOJX.js → workspace-registry-summary-GLQO4ZUF.js} +1 -1
  67. package/dist/workspace-repair-engine-5ZSSF3T5.js +3 -0
  68. package/dist/workspace-run-UGWGT3K2.js +1 -0
  69. package/dist/{workspace-verify-MLABQUWK.js → workspace-verify-LQHXBH2D.js} +1 -1
  70. package/dist/{workspace-watch-MJOG5AZ3.js → workspace-watch-Z32443UP.js} +1 -1
  71. package/docs/README.md +34 -32
  72. package/docs/ci-workflows.md +1 -1
  73. package/docs/commands-reference.md +4 -1
  74. package/docs/contracts/PROOF_CARRYING_CHANGE_CONTRACT_PLAN.md +6 -3
  75. package/docs/proof-carrying-change.implementation.v1.json +3 -2
  76. package/docs/proof-carrying-change.md +42 -8
  77. package/docs/real-world-qualification.md +8 -3
  78. package/package.json +1 -1
  79. package/dist/analyze-GPYPXXRT.js +0 -1
  80. package/dist/autopilot-release-FL47VMF7.js +0 -1
  81. package/dist/capabilities-command-MYSLJIYS.js +0 -1
  82. package/dist/chunk-2LZWBUJD.js +0 -1
  83. package/dist/chunk-3HFFKW4Q.js +0 -2
  84. package/dist/chunk-ERVWW5HX.js +0 -1
  85. package/dist/chunk-GSSJJS5M.js +0 -6
  86. package/dist/chunk-I3UCODXU.js +0 -1
  87. package/dist/chunk-MBICKDYP.js +0 -1
  88. package/dist/chunk-OZXCNVGW.js +0 -2
  89. package/dist/chunk-RVOW3BHQ.js +0 -2
  90. package/dist/chunk-UW4SESKD.js +0 -2
  91. package/dist/chunk-VNKAISFE.js +0 -8
  92. package/dist/chunk-W6WRT77T.js +0 -1
  93. package/dist/chunk-WHR5SL33.js +0 -4
  94. package/dist/chunk-YWZBGSFE.js +0 -9
  95. package/dist/chunk-YZL7ZY7J.js +0 -2
  96. package/dist/pipeline-PGB5TEV3.js +0 -5
  97. package/dist/proof-carrying-change-QFH7WI2E.js +0 -1
  98. package/dist/workspace-knowledge-graph-snapshot-X347REDB.js +0 -1
  99. package/dist/workspace-mcp-serve-NQ42PE2I.js +0 -3
  100. package/dist/workspace-repair-engine-WMJCYWO4.js +0 -3
  101. package/dist/workspace-run-3S35MDX6.js +0 -1
@@ -1,11 +1,11 @@
1
- import {b}from'./chunk-B6FJ6RG6.js';import {a as a$d}from'./chunk-WCJU3CFG.js';import {j,g as g$1}from'./chunk-YKY4JFCF.js';import {d as d$1}from'./chunk-EZPLMAW2.js';import {a as a$9}from'./chunk-GSSJJS5M.js';import {c as c$3,a as a$7,d,b as b$4}from'./chunk-N4B2M44I.js';import {a,c as c$4,h as h$1,g as g$3,k as k$1,f as f$3,d as d$3,e as e$3,i,j as j$3}from'./chunk-AO2ZI42U.js';import {f as f$2,e as e$1,g as g$2}from'./chunk-NSH7TTSV.js';import {a as a$1,b as b$1}from'./chunk-MGL6DBOR.js';import {c as c$2}from'./chunk-I3UCODXU.js';import {a as a$6,b as b$2}from'./chunk-AD4ZY3RF.js';import {b as b$3}from'./chunk-V52R2W2Q.js';import {a as a$4}from'./chunk-NMXGSVMD.js';import {a as a$3}from'./chunk-UW4SESKD.js';import {z}from'./chunk-KFTJVVJR.js';import {j as j$2,l,m as m$1,d as d$2,e as e$2,b as b$6,a as a$c}from'./chunk-U5ENEDJA.js';import {a as a$b}from'./chunk-GR6442P7.js';import {f as f$1,g,h}from'./chunk-OZXCNVGW.js';import {a as a$5}from'./chunk-AFIFZTOY.js';import {a as a$2}from'./chunk-2LIVMG5C.js';import {s,p,t as t$1}from'./chunk-ODK4LCEL.js';import {e}from'./chunk-PKKSRXUS.js';import {a as a$a}from'./chunk-TQEMLBAG.js';import {c}from'./chunk-25AWHAB5.js';import {c as c$1,j as j$1,b as b$5,t as t$2,n,p as p$1,m as m$2}from'./chunk-RGNCL5OB.js';import {a as a$8}from'./chunk-2FIX2MDC.js';import {t,k,u as u$1}from'./chunk-VQZ5PI5J.js';import f from'chalk';import {createHash}from'crypto';import {execa}from'execa';import m from'fs-extra';import u from'path';import {existsSync}from'fs';var Vi=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],zi=["tests","test","src/test","__tests__","e2e","playwright","cypress"],Ji=["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"],Ui=["src","app","pages"],Yi=["dev","build","test","lint"];function Yn(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 Zn(e,t){for(let o of Vi)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 Xn(e,t){for(let o of zi)if(await m.pathExists(u.join(e,o)))return true;for(let o of Ji)if(await m.pathExists(u.join(e,o)))return true;let i=Yn(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 Zi(e)}async function Zi(e){let t=["src","app","pages","components"],i=/\.(test|spec)\.(tsx?|jsx?|vue|svelte)$/i,o=new Set(["node_modules",".git","dist","build",".next","coverage",".turbo"]);for(let s of t){let r=u.join(e,s);if(!await m.pathExists(r))continue;let c=[{dir:r,depth:0}];for(;c.length>0;){let a=c.shift();if(!a)break;let l=[];try{l=await m.readdir(a.dir);}catch{continue}for(let d of l){let p=u.join(a.dir,d);if(i.test(d))return true;if(!(a.depth>=3||o.has(d)||d.startsWith(".")))try{(await m.stat(p)).isDirectory()&&c.push({dir:p,depth:a.depth+1});}catch{continue}}}}return false}async function Jt(e){for(let t of Ui){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 Xi(e){let t=e.key;return b$6(t).key}function Qi(e,t,i){return a$c(t,i).some(o=>!!e[o])}async function Qn(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=Xi(i),s=b$6(o),r=Yn(n),c=[],a=await m.pathExists(u.join(t,"package-lock.json"))||await m.pathExists(u.join(t,"pnpm-lock.yaml"))||await m.pathExists(u.join(t,"yarn.lock"))||await m.pathExists(u.join(t,"bun.lockb"));c.push({id:"frontend-lockfile-integrity",label:"Frontend lockfile integrity",status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml/bun.lockb).",recommendation:a?void 0:"Commit a lockfile for deterministic installs and CI parity."});let l=await m.pathExists(u.join(t,"tsconfig.json")),d=await m.pathExists(u.join(t,"jsconfig.json")),p=l||d;c.push({id:"frontend-typescript-surface",label:"TypeScript project surface",status:p?"pass":"warn",severity:"warn",scope:"project-scoped",reason:p?l?"tsconfig.json detected.":"jsconfig.json detected.":"No tsconfig.json or jsconfig.json detected.",recommendation:p?void 0:"Add tsconfig.json (or jsconfig.json) for typed frontend builds and IDE parity."});let y=s.fileHints.length>0&&s.fileHints.some(k=>existsSync(u.join(t,k)));c.push({id:"frontend-framework-config",label:`${s.displayName} config surface`,status:y?"pass":"warn",severity:"warn",scope:"project-scoped",reason:y?`${s.displayName} configuration artifacts detected.`:`No ${s.displayName} config markers detected (${s.fileHints.join(", ")||"n/a"}).`,recommendation:y?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let k of Yi){let v=Qi(r,o,k),b=k==="dev"||k==="build",j=!v&&k==="test"?h$1({projectPath:t,frameworkDisplayName:s.displayName,scriptName:k,scriptValue:g$3(r)}):void 0;c.push({id:`frontend-script-${k}`,label:`${k} script surface`,status:v?"pass":b?"fail":"warn",severity:b?"error":"warn",scope:"project-scoped",reason:v?`package.json exposes a ${k} script for ${s.displayName}.`:`No ${k} script detected for ${s.displayName}.`,recommendation:v?void 0:`Add a "${a$c(o,k)[0]??k}" script to package.json.`,repairCapability:j});}let h=await Jt(t);return c.push({id:"frontend-source-tree",label:"Frontend source tree",status:h?"pass":"warn",severity:"warn",scope:"project-scoped",reason:h?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:h?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),c}var eo=s.doctorFixResult.schemaVersion,Ce="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function Ne(e){return {schemaVersion:eo,generatedAt:new Date().toISOString(),appliedFixes:e.appliedFixes,remainingBlockers:e.remainingBlockers,verifyRecommended:e.verifyRecommended??Ce}}var to=["python","node","go","java","rust","elixir","clojure","deno","bun","php","ruby","dotnet","scala","kotlin","c","cpp","unknown"],ei={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:[]},ti={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:[]},no=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
1
+ import {b}from'./chunk-B6FJ6RG6.js';import {a as a$d}from'./chunk-WCJU3CFG.js';import {j,g as g$1}from'./chunk-XVTN5DDV.js';import {d as d$1}from'./chunk-EZPLMAW2.js';import {a as a$9}from'./chunk-JK6XEF7K.js';import {c as c$3,a as a$7,d,b as b$4}from'./chunk-N4B2M44I.js';import {a,c as c$4,h as h$1,g as g$3,k as k$1,f as f$2,d as d$3,e as e$3,i as i$1,j as j$3}from'./chunk-AO2ZI42U.js';import {f as f$1,e as e$1,g as g$2}from'./chunk-NSH7TTSV.js';import {a as a$1,b as b$1}from'./chunk-MGL6DBOR.js';import {c as c$2}from'./chunk-EP6Q2QBU.js';import {a as a$6,b as b$2}from'./chunk-AGZWDYMF.js';import {b as b$3}from'./chunk-V52R2W2Q.js';import {a as a$4}from'./chunk-NMXGSVMD.js';import {a as a$3}from'./chunk-PTSEDZIV.js';import {z}from'./chunk-KFTJVVJR.js';import {j as j$2,l,m as m$1,d as d$2,e as e$2,b as b$6,a as a$c}from'./chunk-U5ENEDJA.js';import {a as a$b}from'./chunk-GR6442P7.js';import {g,h,i}from'./chunk-FE5R6EUV.js';import {a as a$5}from'./chunk-AFIFZTOY.js';import {a as a$2}from'./chunk-2LIVMG5C.js';import {s,p,t as t$1}from'./chunk-ODK4LCEL.js';import {e}from'./chunk-PKKSRXUS.js';import {a as a$a}from'./chunk-TQEMLBAG.js';import {c}from'./chunk-25AWHAB5.js';import {c as c$1,j as j$1,b as b$5,t as t$2,n,p as p$1,m as m$2}from'./chunk-RGNCL5OB.js';import {a as a$8}from'./chunk-2FIX2MDC.js';import {t,k,u as u$1}from'./chunk-VQZ5PI5J.js';import f from'chalk';import {createHash}from'crypto';import {execa}from'execa';import m from'fs-extra';import u from'path';import {existsSync}from'fs';var Vi=[".eslintrc.js",".eslintrc.cjs",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml","eslint.config.js","eslint.config.mjs","eslint.config.cjs"],zi=["tests","test","src/test","__tests__","e2e","playwright","cypress"],Ji=["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"],Ui=["src","app","pages"],Yi=["dev","build","test","lint"];function Yn(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 Zn(e,t){for(let o of Vi)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 Xn(e,t){for(let o of zi)if(await m.pathExists(u.join(e,o)))return true;for(let o of Ji)if(await m.pathExists(u.join(e,o)))return true;let i=Yn(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 Zi(e)}async function Zi(e){let t=["src","app","pages","components"],i=/\.(test|spec)\.(tsx?|jsx?|vue|svelte)$/i,o=new Set(["node_modules",".git","dist","build",".next","coverage",".turbo"]);for(let s of t){let r=u.join(e,s);if(!await m.pathExists(r))continue;let c=[{dir:r,depth:0}];for(;c.length>0;){let a=c.shift();if(!a)break;let l=[];try{l=await m.readdir(a.dir);}catch{continue}for(let d of l){let p=u.join(a.dir,d);if(i.test(d))return true;if(!(a.depth>=3||o.has(d)||d.startsWith(".")))try{(await m.stat(p)).isDirectory()&&c.push({dir:p,depth:a.depth+1});}catch{continue}}}}return false}async function Jt(e){for(let t of Ui){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 Xi(e){let t=e.key;return b$6(t).key}function Qi(e,t,i){return a$c(t,i).some(o=>!!e[o])}async function Qn(e){let{projectPath:t,detection:i,packageJsonData:n}=e,o=Xi(i),s=b$6(o),r=Yn(n),c=[],a=await m.pathExists(u.join(t,"package-lock.json"))||await m.pathExists(u.join(t,"pnpm-lock.yaml"))||await m.pathExists(u.join(t,"yarn.lock"))||await m.pathExists(u.join(t,"bun.lockb"));c.push({id:"frontend-lockfile-integrity",label:"Frontend lockfile integrity",status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml/bun.lockb).",recommendation:a?void 0:"Commit a lockfile for deterministic installs and CI parity."});let l=await m.pathExists(u.join(t,"tsconfig.json")),d=await m.pathExists(u.join(t,"jsconfig.json")),p=l||d;c.push({id:"frontend-typescript-surface",label:"TypeScript project surface",status:p?"pass":"warn",severity:"warn",scope:"project-scoped",reason:p?l?"tsconfig.json detected.":"jsconfig.json detected.":"No tsconfig.json or jsconfig.json detected.",recommendation:p?void 0:"Add tsconfig.json (or jsconfig.json) for typed frontend builds and IDE parity."});let y=s.fileHints.length>0&&s.fileHints.some(k=>existsSync(u.join(t,k)));c.push({id:"frontend-framework-config",label:`${s.displayName} config surface`,status:y?"pass":"warn",severity:"warn",scope:"project-scoped",reason:y?`${s.displayName} configuration artifacts detected.`:`No ${s.displayName} config markers detected (${s.fileHints.join(", ")||"n/a"}).`,recommendation:y?void 0:"Keep framework config files in-repo for reproducible dev/build behavior."});for(let k of Yi){let v=Qi(r,o,k),b=k==="dev"||k==="build",j=!v&&k==="test"?h$1({projectPath:t,frameworkDisplayName:s.displayName,scriptName:k,scriptValue:g$3(r)}):void 0;c.push({id:`frontend-script-${k}`,label:`${k} script surface`,status:v?"pass":b?"fail":"warn",severity:b?"error":"warn",scope:"project-scoped",reason:v?`package.json exposes a ${k} script for ${s.displayName}.`:`No ${k} script detected for ${s.displayName}.`,recommendation:v?void 0:`Add a "${a$c(o,k)[0]??k}" script to package.json.`,repairCapability:j});}let h=await Jt(t);return c.push({id:"frontend-source-tree",label:"Frontend source tree",status:h?"pass":"warn",severity:"warn",scope:"project-scoped",reason:h?"Application source directories detected (src/app/pages).":"No frontend source directories detected under src/, app/, or pages/.",recommendation:h?void 0:"Ensure the scaffolded application tree exists before running lifecycle commands."}),c}var eo=s.doctorFixResult.schemaVersion,Ce="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function Ne(e){return {schemaVersion:eo,generatedAt:new Date().toISOString(),appliedFixes:e.appliedFixes,remainingBlockers:e.remainingBlockers,verifyRecommended:e.verifyRecommended??Ce}}var to=["python","node","go","java","rust","elixir","clojure","deno","bun","php","ruby","dotnet","scala","kotlin","c","cpp","unknown"],ei={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:[]},ti={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:[]},no=["node_modules",".git",".workspai/reports",".venv","dist","build","coverage",".env",".env.*","!.env.example"].join(`
2
2
  `),Ut=[".env",".env.*","!.env.example"];function We(e){return e&&to.includes(e)?e:"unknown"}async function Pe(e,t){for(let i of t){if(i.includes("*")){let n=i.replace("*","");if(await io(e,n,2))return true;continue}if(await m.pathExists(u.join(e,i)))return true}return false}async function io(e,t,i){let n=[{dir:e,depth:0}],o=new Set(["node_modules",".git",".workspai",".rapidkit","dist","build","coverage"]);for(;n.length>0;){let s=n.shift();if(!s)break;let r=[];try{r=await m.readdir(s.dir,{withFileTypes:true});}catch{continue}for(let c of r){if(o.has(c.name))continue;let a=u.join(s.dir,c.name);if(c.isFile()&&c.name.endsWith(t))return true;c.isDirectory()&&s.depth<i&&!c.name.startsWith(".")&&n.push({dir:a,depth:s.depth+1});}}return false}async function Yt(e,t=6){let i=await m.pathExists(u.join(e,"Dockerfile")),n=false,o=false,s=new Set(["docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml"]),r=new Set(["node_modules",".git",".workspai",".rapidkit","dist","build","coverage","target","vendor"]),c=[{dir:e,depth:0}];for(;c.length>0&&(!n||!o);){let a=c.shift();if(!a)break;let l=[];try{l=await m.readdir(a.dir,{withFileTypes:true});}catch{continue}for(let d of l)r.has(d.name)||(d.isFile()?(a.depth>0&&d.name==="Dockerfile"&&(n=true),s.has(d.name)&&(o=true)):d.isDirectory()&&a.depth<t&&!d.name.startsWith(".")&&c.push({dir:u.join(a.dir,d.name),depth:a.depth+1}));}return {rootDockerfile:i,nestedDockerfile:n,compose:o}}async function et(e){try{return await m.pathExists(e)?await m.readFile(e,"utf8"):""}catch{return ""}}async function Pt(e,t){let i=[];for(let n of t){let o=await et(u.join(e,n));o&&i.push(o);}return i.join(`
3
3
  `)}async function oo(e){let t=u.join(e,".github","workflows"),i=[];try{i=await m.readdir(t,{withFileTypes:true});}catch{return ""}let n=[],o=0;for(let s of i.filter(r=>r.isFile()&&/\.(?:ya?ml)$/i.test(r.name)).sort((r,c)=>r.name.localeCompare(c.name)).slice(0,64)){let r=u.join(t,s.name);try{let c=await m.stat(r);if(c.size>512*1024||o+c.size>1024*1024)continue;n.push(await m.readFile(r,"utf8")),o+=c.size;}catch{}}return n.join(`
4
- `)}var ro=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"]),so=[/\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],ao=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 co(e){let t=new Set,i=new Set([".git",".next",".nuxt",".output",".rapidkit",".svelte-kit",".venv",".workspai","build","coverage","dist","node_modules","target","vendor"]),n=[{dir:e,depth:0}],o=0;for(;n.length>0&&o<300;){let r=n.shift();if(!r)break;let c=[];try{c=await m.readdir(r.dir,{withFileTypes:true});}catch{continue}for(let a of c){if(i.has(a.name))continue;let l=u.join(r.dir,a.name);if(a.isDirectory()){r.depth<6&&!a.name.startsWith(".")&&n.push({dir:l,depth:r.depth+1});continue}if(!a.isFile()||!ro.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 so){p.lastIndex=0;for(let y of d.matchAll(p)){let h=y.slice(1).find(k=>typeof k=="string"&&k.length>0);h&&!ao.has(h)&&t.add(h);}}}}let s=await et(u.join(e,".env"));for(let r of s.split(/\r?\n/)){let c=r.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/);c?.[1]&&t.add(c[1]);}return [...t].sort((r,c)=>r.localeCompare(c))}async function lo(e){if(e.runtime==="node"){let t=typeof e.packageJsonData?.packageManager=="string"?e.packageJsonData.packageManager.split("@")[0]:null;return {command:t==="pnpm"?"pnpm install":t==="yarn"?"yarn install":t==="bun"?"bun install":"npm install",title:"Generate Node dependency lockfile",files:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock"],limitations:["Review dependency and lockfile changes before committing."]}}if(e.runtime==="go"&&await m.pathExists(u.join(e.projectPath,"go.mod")))return {command:"go mod tidy",title:"Reconcile Go module graph",files:["go.mod","go.sum"],limitations:["Review go.mod/go.sum changes before committing."]};if(e.runtime==="java"){let t=await m.pathExists(u.join(e.projectPath,"pom.xml")),i=await m.pathExists(u.join(e.projectPath,"mvnw"))||await m.pathExists(u.join(e.projectPath,"mvnw.cmd")),n=await m.pathExists(u.join(e.projectPath,"gradlew"))||await m.pathExists(u.join(e.projectPath,"gradlew.bat")),o=t?i?process.platform==="win32"?".\\mvnw.cmd -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"./mvnw -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"mvn -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":n?process.platform==="win32"?".\\gradlew.bat --project-cache-dir .workspai/cache/java/gradle dependencies":"./gradlew --project-cache-dir .workspai/cache/java/gradle dependencies":"gradle --project-cache-dir .workspai/cache/java/gradle dependencies";return t?{command:o,title:"Warm Maven dependency graph",files:["pom.xml"],limitations:["Maven does not provide a native transitive lockfile; dependency:go-offline warms dependencies but does not create reproducibility evidence."]}:{command:o,title:"Prepare Gradle dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]}}if(e.runtime==="scala")return {command:"sbt update",title:"Prepare Scala dependency baseline",files:["build.sbt","project/build.properties","project/plugins.sbt"],limitations:["Review resolved dependency and plugin changes before committing."]};if(e.runtime==="kotlin")return {command:process.platform==="win32"?".\\gradlew.bat dependencies":"./gradlew dependencies",title:"Prepare Kotlin dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]};if(e.runtime==="rust")return {command:"cargo fetch",title:"Generate Rust dependency baseline",files:["Cargo.toml","Cargo.lock"],limitations:["Review Cargo.lock changes before committing."]};if(e.runtime==="php")return {command:"composer install",title:"Generate Composer lockfile",files:["composer.json","composer.lock"],limitations:["Review composer.lock changes before committing."]};if(e.runtime==="ruby")return {command:"bundle install",title:"Generate Bundler lockfile",files:["Gemfile","Gemfile.lock"],limitations:["Review Gemfile.lock changes before committing."]};if(e.runtime==="dotnet")return {command:"dotnet restore",title:".NET dependency restore",files:["*.sln","*.csproj","packages.lock.json","Directory.Packages.props"],limitations:["Enable NuGet lock files in the project when release policy requires deterministic restore."]};if(e.runtime==="elixir")return {command:"mix deps.get",title:"Generate Elixir dependency lockfile",files:["mix.exs","mix.lock"],limitations:["Review mix.lock changes before committing."]};if(e.runtime==="clojure")return {command:"clojure -P",title:"Prepare Clojure dependency baseline",files:["deps.edn","project.clj"],limitations:["Review dependency cache and CI restore policy before release."]};if(e.runtime==="python"){let t=await et(u.join(e.projectPath,"pyproject.toml"));if(/\[tool\.poetry\]/.test(t))return {command:"poetry install --no-root",title:"Install Poetry dependency baseline",files:["pyproject.toml","poetry.lock"],limitations:["Review poetry.lock changes before committing when Poetry resolves or updates the lockfile."]};if(/\[tool\.uv\]|\[project\]/.test(t))return {command:"uv lock",title:"Generate uv lockfile",files:["pyproject.toml","uv.lock"],limitations:["Review uv.lock changes before committing."]}}return null}function tt(e){let t=e?.scripts;if(!t||typeof t!="object"||Array.isArray(t))return {};let i={};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.trim().length>0&&(i[n]=o);return i}function po(e){if(e.runtime==="node"){let i=tt(e.packageJsonData);if(!e.packageJsonData)return null;if(e.kind==="test"){let n=i.lint?"npm run lint":i.build?"npm run build":null;return n?{command:n,title:"Define Node test script",targetName:"test",files:["package.json"],limitations:["Replace this fallback with real tests when product coverage is required."]}:null}if(e.kind==="security"){let n=a$d(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 uo(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 Zt(e){let t=po({runtime:e.runtime,kind:e.kind,projectPath:e.projectPath,packageJsonData:e.packageJsonData});if(t)return (e.runtime==="node"||e.runtime==="bun")&&e.packageJsonData?i({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"))?uo({issueId:e.issueId,projectPath:e.projectPath,contract:t,reason:e.reason}):De({issueId:e.issueId,title:t.title,projectPath:e.projectPath,files:t.files.filter(i=>i!=="Makefile"),reason:`${e.reason} The repository does not expose a Makefile, so Doctor will not invent a new command surface.`,limitations:t.limitations})}function De(e){return {id:`${e.issueId}.manual`,issueId:e.issueId,title:e.title,status:"manual",fixKind:"manual",risk:"guarded",canAutoFix:false,canEditFiles:false,requiresApproval:true,requiresReview:true,files:e.files.map(t=>u.join(e.projectPath,t)),refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function mo(e){return d$3({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${no}
4
+ `)}var ro=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"]),so=[/\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],ao=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 co(e){let t=new Set,i=new Set([".git",".next",".nuxt",".output",".rapidkit",".svelte-kit",".venv",".workspai","build","coverage","dist","node_modules","target","vendor"]),n=[{dir:e,depth:0}],o=0;for(;n.length>0&&o<300;){let r=n.shift();if(!r)break;let c=[];try{c=await m.readdir(r.dir,{withFileTypes:true});}catch{continue}for(let a of c){if(i.has(a.name))continue;let l=u.join(r.dir,a.name);if(a.isDirectory()){r.depth<6&&!a.name.startsWith(".")&&n.push({dir:l,depth:r.depth+1});continue}if(!a.isFile()||!ro.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 so){p.lastIndex=0;for(let y of d.matchAll(p)){let h=y.slice(1).find(k=>typeof k=="string"&&k.length>0);h&&!ao.has(h)&&t.add(h);}}}}let s=await et(u.join(e,".env"));for(let r of s.split(/\r?\n/)){let c=r.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/);c?.[1]&&t.add(c[1]);}return [...t].sort((r,c)=>r.localeCompare(c))}async function lo(e){if(e.runtime==="node"){let t=typeof e.packageJsonData?.packageManager=="string"?e.packageJsonData.packageManager.split("@")[0]:null;return {command:t==="pnpm"?"pnpm install":t==="yarn"?"yarn install":t==="bun"?"bun install":"npm install",title:"Generate Node dependency lockfile",files:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock"],limitations:["Review dependency and lockfile changes before committing."]}}if(e.runtime==="go"&&await m.pathExists(u.join(e.projectPath,"go.mod")))return {command:"go mod tidy",title:"Reconcile Go module graph",files:["go.mod","go.sum"],limitations:["Review go.mod/go.sum changes before committing."]};if(e.runtime==="java"){let t=await m.pathExists(u.join(e.projectPath,"pom.xml")),i=await m.pathExists(u.join(e.projectPath,"mvnw"))||await m.pathExists(u.join(e.projectPath,"mvnw.cmd")),n=await m.pathExists(u.join(e.projectPath,"gradlew"))||await m.pathExists(u.join(e.projectPath,"gradlew.bat")),o=t?i?process.platform==="win32"?".\\mvnw.cmd -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"./mvnw -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"mvn -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":n?process.platform==="win32"?".\\gradlew.bat --project-cache-dir .workspai/cache/java/gradle dependencies":"./gradlew --project-cache-dir .workspai/cache/java/gradle dependencies":"gradle --project-cache-dir .workspai/cache/java/gradle dependencies";return t?{command:o,title:"Warm Maven dependency graph",files:["pom.xml"],limitations:["Maven does not provide a native transitive lockfile; dependency:go-offline warms dependencies but does not create reproducibility evidence."]}:{command:o,title:"Prepare Gradle dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]}}if(e.runtime==="scala")return {command:"sbt update",title:"Prepare Scala dependency baseline",files:["build.sbt","project/build.properties","project/plugins.sbt"],limitations:["Review resolved dependency and plugin changes before committing."]};if(e.runtime==="kotlin")return {command:process.platform==="win32"?".\\gradlew.bat dependencies":"./gradlew dependencies",title:"Prepare Kotlin dependency baseline",files:["build.gradle","build.gradle.kts","gradle.lockfile"],limitations:["Review resolved dependency and lockfile changes before committing."]};if(e.runtime==="rust")return {command:"cargo fetch",title:"Generate Rust dependency baseline",files:["Cargo.toml","Cargo.lock"],limitations:["Review Cargo.lock changes before committing."]};if(e.runtime==="php")return {command:"composer install",title:"Generate Composer lockfile",files:["composer.json","composer.lock"],limitations:["Review composer.lock changes before committing."]};if(e.runtime==="ruby")return {command:"bundle install",title:"Generate Bundler lockfile",files:["Gemfile","Gemfile.lock"],limitations:["Review Gemfile.lock changes before committing."]};if(e.runtime==="dotnet")return {command:"dotnet restore",title:".NET dependency restore",files:["*.sln","*.csproj","packages.lock.json","Directory.Packages.props"],limitations:["Enable NuGet lock files in the project when release policy requires deterministic restore."]};if(e.runtime==="elixir")return {command:"mix deps.get",title:"Generate Elixir dependency lockfile",files:["mix.exs","mix.lock"],limitations:["Review mix.lock changes before committing."]};if(e.runtime==="clojure")return {command:"clojure -P",title:"Prepare Clojure dependency baseline",files:["deps.edn","project.clj"],limitations:["Review dependency cache and CI restore policy before release."]};if(e.runtime==="python"){let t=await et(u.join(e.projectPath,"pyproject.toml"));if(/\[tool\.poetry\]/.test(t))return {command:"poetry install --no-root",title:"Install Poetry dependency baseline",files:["pyproject.toml","poetry.lock"],limitations:["Review poetry.lock changes before committing when Poetry resolves or updates the lockfile."]};if(/\[tool\.uv\]|\[project\]/.test(t))return {command:"uv lock",title:"Generate uv lockfile",files:["pyproject.toml","uv.lock"],limitations:["Review uv.lock changes before committing."]}}return null}function tt(e){let t=e?.scripts;if(!t||typeof t!="object"||Array.isArray(t))return {};let i={};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.trim().length>0&&(i[n]=o);return i}function po(e){if(e.runtime==="node"){let i=tt(e.packageJsonData);if(!e.packageJsonData)return null;if(e.kind==="test"){let n=i.lint?"npm run lint":i.build?"npm run build":null;return n?{command:n,title:"Define Node test script",targetName:"test",files:["package.json"],limitations:["Replace this fallback with real tests when product coverage is required."]}:null}if(e.kind==="security"){let n=a$d(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 uo(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 Zt(e){let t=po({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"))?uo({issueId:e.issueId,projectPath:e.projectPath,contract:t,reason:e.reason}):De({issueId:e.issueId,title:t.title,projectPath:e.projectPath,files:t.files.filter(i=>i!=="Makefile"),reason:`${e.reason} The repository does not expose a Makefile, so Doctor will not invent a new command surface.`,limitations:t.limitations})}function De(e){return {id:`${e.issueId}.manual`,issueId:e.issueId,title:e.title,status:"manual",fixKind:"manual",risk:"guarded",canAutoFix:false,canEditFiles:false,requiresApproval:true,requiresReview:true,files:e.files.map(t=>u.join(e.projectPath,t)),refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function mo(e){return d$3({issueId:"surface-dockerignore",title:"Create .dockerignore",projectPath:e,relativePath:".dockerignore",content:`${no}
5
5
  `,reason:"Create a Docker build ignore baseline to keep secrets, dependencies, and reports out of container contexts."})}async function fo(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:`${Ut.join(`
6
6
  `)}
7
7
  `,reason:"Create a minimal ignore baseline so local env files are not committed accidentally."});let t=await et(u.join(e,".gitignore")),i=Ut.filter(n=>!t.split(/\r?\n/).includes(n));return e$3({issueId:"surface-security-hygiene",title:"Append .gitignore secret baseline",projectPath:e,relativePath:".gitignore",lines:i,reason:"Append missing env-file ignore rules so local secrets stay out of source control."})}async function go(e){let t=ti[e.runtime]??[],i=ei[e.runtime]??[];if(t.length===0&&i.length===0)return null;let n=(e.runtime==="c"||e.runtime==="cpp")&&e$2(e.projectPath)||await Pe(e.projectPath,t),o=await Pe(e.projectPath,i),s=e.runtime==="java"&&await m.pathExists(u.join(e.projectPath,"pom.xml"))&&!await Pe(e.projectPath,["build.gradle","build.gradle.kts"]),r=n&&!o?await lo({projectPath:e.projectPath,runtime:e.runtime,packageJsonData:e.packageJsonData}):null;return {id:"surface-dependency-contract",label:"Dependency contract",status:!n||o?"pass":"warn",severity:"warn",scope:"project-scoped",reason:n?o?"Dependency manifest and deterministic lock/baseline markers detected.":s?"Maven manifest detected. Maven has no native transitive lockfile, so reproducibility requires pinned dependency and plugin versions plus published resolved-dependency evidence.":`Dependency manifest detected, but no deterministic baseline found (${i.join(", ")}).`:"No dependency manifest markers detected for this runtime.",recommendation:n&&!o?s?"Pin dependency and plugin versions, then publish a resolved dependency tree or SBOM as release evidence.":"Generate and commit the runtime-native lockfile or package baseline before release.":void 0,repairCapability:n&&!o&&r?k$1({issueId:"surface-dependency-contract",title:r.title,projectPath:e.projectPath,command:r.command,files:r.files,fixKind:"dependency-sync",reason:s?"Warm the Maven dependency graph for inspection; reproducibility still requires pinned versions and published resolved-dependency evidence.":"Generate the runtime-native dependency baseline so CI, Doctor, and Studio share deterministic dependency evidence.",limitations:r.limitations}):void 0}}async function yo(e){let t=await m.pathExists(u.join(e.projectPath,".env.example")),i=await Pe(e.projectPath,[".env.sample",".env.template",".env.public"]),n=await m.pathExists(u.join(e.projectPath,".env")),o=await m.pathExists(u.join(e.projectPath,"docs","env.md"))||await m.pathExists(u.join(e.projectPath,"ENVIRONMENT.md")),s=await m.pathExists(u.join(e.projectPath,"config")),r=t||i||o||s,c=e.projectKind==="frontend",a=r?[]:await co(e.projectPath),l=n||a.length>0,d=!r&&!l,p=n||e.projectKind==="backend"||e.projectKind==="frontend"||e.projectKind==="fullstack",y=a.map(h=>`${h}=`).join(`
8
- `);return {id:"surface-env-contract",label:"Environment/config contract",status:r||d?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:d?"not-applicable":"applicable",reason:r?"Environment/config contract marker detected.":d?"No runtime environment-variable usage was detected; an environment contract is not currently applicable.":c?"No frontend environment contract marker detected.":"No environment/config contract marker detected.",recommendation:r||d?void 0:p?"Add .env.example, config schema, or environment documentation for deterministic setup.":"Document the governed build/runtime variables or declare an explicit configuration schema; do not infer a dotenv contract from host-tooling references alone.",repairCapability:r?t&&!n?f$3({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}
8
+ `);return {id:"surface-env-contract",label:"Environment/config contract",status:r||d?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:d?"not-applicable":"applicable",reason:r?"Environment/config contract marker detected.":d?"No runtime environment-variable usage was detected; an environment contract is not currently applicable.":c?"No frontend environment contract marker detected.":"No environment/config contract marker detected.",recommendation:r||d?void 0:p?"Add .env.example, config schema, or environment documentation for deterministic setup.":"Document the governed build/runtime variables or declare an explicit configuration schema; do not infer a dotenv contract from host-tooling references alone.",repairCapability:r?t&&!n?f$2({issueId:"surface-env-contract",title:"Create local .env from .env.example",projectPath:e.projectPath,sourceRelativePath:".env.example",targetRelativePath:".env",reason:"Seed the local environment file from the reviewed example without overwriting an existing .env."}):void 0:d?void 0:a.length>0&&p?d$3({issueId:"surface-env-contract",title:"Create environment contract skeleton",projectPath:e.projectPath,relativePath:".env.example",content:`${y}
9
9
  `,reason:"Create a secret-free .env.example from environment keys observed in source. Values remain empty for project-owner review.",limitations:["Only variable names are copied; secrets and local values are never read into the generated contract.","Review required and optional variables before committing the example."]}):De({issueId:"surface-env-contract",title:n?"Define environment contract":"Review environment/config contract",projectPath:e.projectPath,files:n?[".env.example"]:["ENVIRONMENT.md"],reason:n?"A local .env exists, but no safe variable names could be inferred. Review the required keys before publishing an example.":"Environment-variable references were observed, but this project kind does not prove a dotenv contract. Document the governed build/runtime variables or declare an explicit configuration schema before generating files."})}}async function ho(e){let t=await Yt(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:mo(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 bo(e){let t=["k8s","kubernetes","deploy","deployments","charts","helm","kustomization.yaml","kustomization.yml"];if(!await Pe(e.projectPath,t)){let c=["DEPLOYMENT.md","docs/deployment.md","docs/deploy.md","Procfile","fly.toml","render.yaml","railway.json","vercel.json","netlify.toml","serverless.yml","serverless.yaml","sst.config.ts","cdk.json","terraform","infra"],a=await Pe(e.projectPath,c);return {id:"surface-deploy-contract",label:"Deployment contract",status:"pass",severity:"warn",scope:"project-scoped",applicability:a?"applicable":"not-applicable",reason:a?"A documented or provider-managed non-Kubernetes deployment surface was detected.":"No deployment intent was detected; a deployment contract is not currently applicable."}}let n=await Pt(e.projectPath,["k8s/deployment.yaml","k8s/deployment.yml","kubernetes/deployment.yaml","deploy/deployment.yaml","deployment.yaml","deployment.yml","values.yaml","charts/values.yaml"]),o=/readinessProbe|livenessProbe|startupProbe/.test(n),s=/resources:\s*[\s\S]*(limits:|requests:)/.test(n),r=o&&s;return {id:"surface-kubernetes-readiness",label:"Deployment readiness controls",status:r?"pass":"warn",severity:"warn",scope:"project-scoped",reason:r?"Deployment surface includes probe and resource-control markers.":"Deployment surface detected, but readiness/liveness probes or resource controls are incomplete.",recommendation:r?void 0:"Add readiness/liveness/startup probes and resource requests/limits to production deployment manifests.",repairCapability:r?void 0:De({issueId:"surface-kubernetes-readiness",title:"Harden deployment readiness controls",projectPath:e.projectPath,files:["k8s/","helm/","deploy/"],reason:"Deployment manifests are environment-specific and should be reviewed before mutation."})}}async function ko(e){let t=await m.pathExists(u.join(e.projectPath,".gitignore")),n=(await et(u.join(e.projectPath,".gitignore"))).split(/\r?\n/),o=t&&Ut.every(C=>n.includes(C)),s=tt(e.packageJsonData),r=!!(s.audit||s["security:audit"]||s["audit:security"]||s["npm:audit"]),c=e.dependencyAudit,a=Number(c?.blockingFindingCount??c?.findingCount??e.vulnerabilities??0),l=a>0,d=c?.status==="clean",p=c?.status==="tool-unavailable"||c?.status==="unsupported"||c?.status==="failed",y=We(e.runtimeFamily),k=["package.json","package-lock.json",...await m.pathExists(u.join(e.projectPath,"npm-shrinkwrap.json"))?["npm-shrinkwrap.json"]:[]],v=c?.invocation,b=c?.remediation?.disposition,j=c?.remediation?.resolutionCandidates?.length??0,x=b==="compatible"||b==="mixed"||!c&&y==="node",D=l&&x&&(c?.tool==="npm audit"||!c&&y==="node")?{cwd:e.projectPath,executable:"npm",args:["audit","fix","--audit-level=moderate"]}:l&&x&&c?.tool==="bun audit"?{cwd:e.projectPath,executable:"bun",args:["update"]}:l&&x&&c?.tool==="deno audit"?{cwd:e.projectPath,executable:"deno",args:["audit","--fix"]}:void 0,P=l?[{id:"audit-live-state",kind:"diagnose",description:"Read the current advisory graph and classify direct, transitive, fixable, and breaking findings.",risk:"safe",invocation:v,continueWhen:"always"},...D?[{id:"apply-compatible-fixes",kind:"safe-fix",description:"Apply runtime-authored compatible dependency and lockfile updates without forcing breaking upgrades.",risk:"guarded",invocation:D,continueWhen:"previous-passed"}]:[],{id:"upgrade-owning-dependencies",kind:"targeted-upgrade",description:"Upgrade the smallest set of direct dependencies that own unresolved advisory paths, then run tests and build.",risk:"guarded",continueWhen:D?"blocker-remains":"always"},{id:"recheck-advisory-graph",kind:"verify",description:"Re-run the runtime-native audit and retain only unresolved advisory paths.",risk:"safe",invocation:v,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&&D?k$1({issueId:"surface-security-hygiene",title:`Apply compatible ${c?.ecosystem??y} vulnerability fixes`,projectPath:e.projectPath,command:[D.executable,...D.args].join(" "),invocation:{executable:D.executable,args:D.args},strategy:P,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:c?.ecosystem??D.executable??y,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}},files:k,reason:"Apply runtime-authored compatible vulnerability remediations, then regenerate Doctor and release-readiness evidence.",risk:"guarded",requiresReview:true,limitations:["Never add --force automatically; unresolved advisories require an evidence-backed dependency upgrade plan.","Review lockfile changes and rerun the complete Workspace Intelligence verification loop."]}):void 0,S=p?De({issueId:"surface-security-hygiene",title:`Establish ${c?.ecosystem??y} security audit evidence`,projectPath:e.projectPath,files:Array.from(new Set([...ti[y]??[],...ei[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,w=o&&d,E=c?.reason;return {id:"surface-security-hygiene",label:"Security hygiene surface",status:w?"pass":l?"fail":"warn",severity:l?"error":"warn",scope:"project-scoped",reason:l?`${a} moderate/high/critical dependency vulnerability(ies) reported.`:p?`${E} 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?j>0&&!x?`No direct automatic fix is currently authorized. Evaluate the ${j} structured dependency resolution candidate(s) through a guarded reconcile, audit, test, and build transaction before considering a breaking change.`:b==="breaking-only"||b==="none"?j>0?`No direct automatic fix is currently available. Evaluate the ${j} structured dependency resolution candidate(s) through a guarded install, audit, test, and build transaction before considering a breaking change.`:"No compatible automatic fix is currently available. Review an explicit replacement, a time-bounded exception, or wait for an upstream patch.":"Run the runtime-native audit fix path without force, review lockfile changes, then rerun Doctor.":p?"Install or declare the runtime-native audit tool, rerun Doctor, and keep the command available to CI and Studio.":o?r?void 0:"Consider adding a security audit script for CI parity.":"Add .gitignore entries for env files, build output, dependency directories, and local reports.",repairCapability:l?g??{...De({issueId:"surface-security-hygiene",title:`Resolve ${c?.ecosystem??y} dependency vulnerabilities`,projectPath:e.projectPath,files:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","Directory.Packages.props"],reason:b==="breaking-only"?j>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.":b==="none"?j>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:P,transaction:{schemaVersion:"workspai.doctor-dependency-repair-transaction.v1",kind:"dependency-security",state:"planned",projectPath:e.projectPath,ecosystem:c?.ecosystem??D?.executable??y,requiredStages:["reconcile","audit","test","build"],completion:{manifestLockConsistent:true,auditClean:true,declaredTestsPass:true,declaredBuildPass:true,canonicalVerificationRequired:true}}}:S||(o?void 0:await fo(e.projectPath))}}async function vo(e){let t=We(e.runtimeFamily),i=e.hasTests===true,n=i?void 0:await Zt({issueId:"surface-test-contract",projectPath:e.projectPath,runtime:t,kind:"test",packageJsonData:e.packageJsonData,reason:"Create a deterministic runtime-native test command contract so Doctor, CI, and Studio can verify changes consistently."});return {id:"surface-test-contract",label:"Test contract",status:i?"pass":"warn",severity:"warn",scope:"project-scoped",reason:i?"Test surface detected through scripts, config, directories, or test files.":"No test surface detected by Doctor.",recommendation:i?void 0:"Add at least one deterministic test command or test baseline before release.",repairCapability:n??(i?void 0:De({issueId:"surface-test-contract",title:"Define test contract",projectPath:e.projectPath,files:["package.json","pyproject.toml","go.mod","pom.xml"],reason:"Doctor can identify missing test surfaces, but the correct test runner depends on product intent."}))}}async function wo(e){let t=u.join(e.projectPath,".workspai","reports","project-test-coverage-last-run.json"),i=await m.readJson(t).catch(()=>null);if(!(i?.schemaVersion===s.projectTestCoverage.schemaVersion))return {id:"test-coverage-evidence",label:"Test coverage evidence",status:"warn",severity:"warn",scope:"project-scoped",reason:"No normalized project coverage evidence has been generated yet.",recommendation:"Run project coverage once to establish a measurable baseline before selecting a coverage goal.",repairCapability:k$1({issueId:"test-coverage-evidence",title:"Generate project coverage baseline",projectPath:e.projectPath,command:"npx workspai project coverage --run --json",invocation:{executable:"npx",args:["workspai","project","coverage","--run","--json"]},files:[t$1.projectTestCoverage],reason:"Run the runtime-native test coverage adapter and publish normalized evidence for Doctor, CI, Studio, and IDE consumers.",risk:"safe",requiresReview:false})};let o=i.target?.metric??"lines",s$1=jo(i.target?.percent),r=i.metrics?.[o]?.percent,c=typeof r=="number"?`${r}%`:"unavailable",a=i.status==="passed"?"pass":i.status==="below-target"||i.status==="failed"?"fail":"warn";return {id:"test-coverage-evidence",label:"Test coverage evidence",status:a,severity:a==="fail"?"error":"warn",scope:"project-scoped",reason:i.status==="passed"?`${o} coverage ${c} satisfies the ${s$1}% project target.`:i.status==="below-target"?`${o} coverage ${c} is below the ${s$1}% project target.`:i.status==="failed"?"The runtime-native coverage command failed; the target cannot be verified.":"Coverage evidence exists, but no supported metric could be normalized.",recommendation:i.status==="passed"?void 0:i.status==="below-target"?`Add targeted tests for the lowest-coverage source paths, then rerun project coverage with target ${s$1}%.`:"Repair the runtime-native coverage command or reporter and regenerate evidence.",repairCapability:i.status==="passed"?void 0:De({issueId:"test-coverage-evidence",title:"Reach the project coverage goal",projectPath:e.projectPath,files:[t$1.projectTestCoverage,...(i.lowCoverageFiles??[]).map(l=>l.path).filter(l=>typeof l=="string").slice(0,20)],reason:"Test creation requires source-aware assertions. Studio should use the normalized low-coverage paths, edit tests, and rerun the same target until verified.",limitations:["Do not lower thresholds, exclude difficult source files, remove assertions, or skip failing tests to satisfy the goal."]})}}function jo(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function xo(e){let t=tt(e.packageJsonData),i=!!(t.format||t["format:check"]||t.prettier);return {id:"surface-format-contract",label:"Format contract",status:i?"pass":"warn",severity:"warn",scope:"project-scoped",reason:i?"Format script detected in package.json.":"No explicit format script detected by Doctor.",recommendation:i?void 0:"Add a formatter command or document the formatting tool used by CI."}}async function Co(e){let t=We(e.runtimeFamily),n={node:["test","tests","__tests__","vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","jest.config.ts","jest.config.js","jest.config.cjs","jest.config.mjs","playwright.config.ts","playwright.config.js","cypress.config.ts","cypress.config.js","*.spec.ts","*.spec.js","*.test.ts","*.test.js"],deno:["deno.json","deno.jsonc"],bun:["bunfig.toml",".bunfig.toml","test","tests","vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","jest.config.ts","jest.config.js","playwright.config.ts","playwright.config.js","*.test.ts","*.spec.ts"],python:["pytest.ini","tox.ini","noxfile.py","tests","test","conftest.py","*_test.py"],go:["*_test.go"],java:["src/test","*Test.java","*Tests.java","*IT.java"],rust:["tests","*_test.rs"],elixir:["test","*_test.exs"],clojure:["test","*_test.clj","*_test.cljc"],php:["phpunit.xml","phpunit.xml.dist","tests"],ruby:["spec","test",".rspec"],dotnet:["*.Tests.csproj","*.Test.csproj","*Tests.cs"],scala:["src/test","*Spec.scala","*Suite.scala"],kotlin:["src/test","*Test.kt","*Tests.kt"],c:["test","tests","*_test.c","test_*.c"],cpp:["test","tests","*_test.cpp","test_*.cpp","*Test.cpp"],unknown:[]}[t]??[];if(n.length===0)return null;let o=await g$2(e.projectPath),s=await Pe(e.projectPath,n)||o.runtimeFamilies.some(y=>y===t),r=tt(e.packageJsonData),c=Object.values(r).join(`
10
10
  `),a=await Pt(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=s||d;return {id:"runtime-test-depth",label:"Runtime-native test depth",status:p?"pass":("warn"),severity:"warn",scope:"project-scoped",reason:p?"Runtime-native test markers detected.":e.hasTests?"Generic test surface detected, but runtime-native test markers are incomplete.":"No runtime-native test markers detected.",recommendation:p?void 0:"Add runtime-native tests/config so Doctor, CI, and Studio can verify changes deterministically."}}async function Po(e){let t=We(e.runtimeFamily),n={node:["eslint.config.js","eslint.config.cjs","eslint.config.mjs","eslint.config.ts","eslint.config.mts",".eslintrc",".eslintrc.js",".eslintrc.cjs",".eslintrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs",".prettierrc",".prettierrc.json","biome.json","biome.jsonc"],deno:["deno.json","deno.jsonc"],bun:["eslint.config.js","biome.json"],python:["ruff.toml",".flake8","mypy.ini"],go:[".golangci.yml",".golangci.yaml"],java:["checkstyle.xml"],rust:["rustfmt.toml","clippy.toml"],elixir:[".formatter.exs","credo.exs"],clojure:["cljfmt.edn",".clj-kondo"],php:["phpcs.xml","phpstan.neon","pint.json"],ruby:[".rubocop.yml"],dotnet:[".editorconfig"],scala:[".scalafmt.conf",".scalafix.conf"],kotlin:[".editorconfig","detekt.yml"],c:[".clang-format",".clang-tidy"],cpp:[".clang-format",".clang-tidy"],unknown:[]}[t]??[];if(n.length===0)return null;let o=await Pt(e.projectPath,[...n,"package.json","pyproject.toml","Makefile","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","mix.exs","deps.edn","project.clj","composer.json","Gemfile","Directory.Build.props"]),s=tt(e.packageJsonData),r=Object.entries(s).filter(([d])=>/lint|format|quality|check|typecheck|static/i.test(d)).map(([,d])=>d).join(`
@@ -15,11 +15,11 @@ ${r}`)||c,l=a?void 0:await Zt({issueId:"runtime-quality-tooling",projectPath:e.p
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 s=n?Number(n[1]):0;return {findingCount:s,severityCounts:{...ke,unknown:s},subjects:[]}}function zo(e,t,i){return e==="node"||e==="bun"?Go(t):e==="python"?Ko(t):e==="go"?Wo(t):e==="rust"?Ho(t):e==="php"?Lo(t):e==="dotnet"?qo(t):e==="ruby"?Vo(t)??ri(t,i):e==="deno"||e==="elixir"?ri(t,i):null}async function Jo(e,t){return m.pathExists(u.join(e,t))}async function Uo(e,t){if(t==="bun")return {ecosystem:"npm",tool:"bun audit",invocation:{cwd:e,executable:"bun",args:["audit","--json"]}};if(t==="node"){let i=a$d(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 Jo(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 si(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 Yo(e){let t=new Date().toISOString(),i=await Uo(e.projectPath,e.runtime),n={schemaVersion:"doctor-dependency-audit-v1",runtime:e.runtime,ecosystem:i.ecosystem,tool:i.tool,generatedAt:t,findingCount:null,blockingFindingCount:null,severityCounts:{...ke},subjects:[],limitations:["A clean result covers known advisories available to the selected runtime-native audit tool at execution time.","Doctor never treats a missing scanner, malformed output, registry failure, or timeout as a clean audit."]};if(!i.invocation)return {...n,status:"unsupported",reason:i.unsupportedReason??"No supported audit invocation is available."};try{let o=await execa(i.invocation.executable,i.invocation.args,{cwd:i.invocation.cwd,timeout:$o(),reject:false}),s=zo(e.runtime,o.stdout,o.stderr);if(!s){let a=String(o.code??"")==="ENOENT"||/not found|no such (?:command|subcommand)|script not found|no module named pip_audit|unknown command|unrecognized (?:command|option)/i.test(`${o.stdout}
16
16
  ${o.stderr}
17
17
  ${o.shortMessage??""}`);return {...n,invocation:i.invocation,exitCode:o.exitCode,status:a?"tool-unavailable":"failed",reason:a?`${i.tool} is not installed or not supported by the detected runtime version.`:`${i.tool} did not produce parseable vulnerability evidence.`}}if(s.findingCount===0&&o.exitCode!==0)return {...n,invocation:i.invocation,exitCode:o.exitCode,status:"failed",reason:`${i.tool} emitted a clean-looking payload but exited with ${o.exitCode}; Doctor refuses to treat contradictory audit execution as healthy.`};if((e.runtime==="node"||e.runtime==="bun")&&s.remediation&&(s.remediation=await Bo(e.projectPath,s.remediation),s.findingCount>0&&!s.remediation.compatibleFixAvailable)){let a=await To(e.projectPath,o.stdout);s.remediation.resolutionCandidates=a.length>0?a:ii(s.subjects);}let r=s.severityCounts.moderate+s.severityCounts.high+s.severityCounts.critical+s.severityCounts.unknown,c=s.remediation??(s.findingCount===0?{disposition:"not-needed",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[]}:{disposition:"unknown",compatibleFixAvailable:false,breakingFixAvailable:false,candidates:[],resolutionCandidates:ii(s.subjects)});return {...n,invocation:i.invocation,exitCode:o.exitCode,findingCount:s.findingCount,blockingFindingCount:r,severityCounts:s.severityCounts,subjects:s.subjects,remediation:c,status:s.findingCount>0?"vulnerable":"clean",reason:s.findingCount>0?`${i.tool} reported ${s.findingCount} known dependency vulnerability finding(s).`:`${i.tool} completed without known dependency vulnerability findings.`}}catch(o){return {...n,invocation:i.invocation,status:si(o)?"tool-unavailable":"failed",reason:si(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 ci(e){let t=await Io(e.projectPath,e.runtime);e.fresh&&Me.delete(t);let i=Me.get(t);if(i)return i;let n=Yo(e);for(Me.set(t,n);Me.size>Ao;){let o=Me.keys().next().value;if(!o)break;Me.delete(o);}try{return await n}catch(o){throw Me.delete(t),o}}var Xt="doctor-graph-diagnosis.v1";var ui="Graph paths identify evidence-backed structural reachability and verification candidates; they do not prove runtime causality or that every affected surface has been discovered.",li={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"]},Zo=new Set(["project","service","api","endpoint","schema","database","queue","container","deployment","pipeline","environment","document","decision","test-suite","owner"]),Xo=new Set(["test-suite","pipeline"]),st=new Map;async function Qo(e,t){let[i,n]=await Promise.all([m.stat(e),m.stat(t)]),o=[e,i.size,i.mtimeMs,t,n.size,n.mtimeMs].join(":"),s=st.get(o);if(s)return s;st.size>=4&&st.clear();let r=(async()=>{let[c,a]=await Promise.all([m.readJSON(e),m.readJSON(t)]);a$5(c,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Doctor graph diagnosis source"),a$5(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:nr(l)}})();st.set(o,r);try{return await r}catch(c){throw st.delete(o),c}}function Dt(e,t){if(!e)return ".";let i=u.relative(e,t).split(u.sep).join("/");return i&&!i.startsWith("../")?i:"."}function Qt(e){return {id:e.id,kind:e.kind,label:e.label,...e.projectId?{projectId:e.projectId}:{}}}function qe(e,t,i,n={artifact:a$6}){return {schemaVersion:Xt,generatedAt:(e.now??new Date).toISOString(),status:t,claimBoundary:ui,graph:n,project:{name:e.projectName,path:Dt(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 er(e,t){let i=Dt(t.workspacePath,t.projectPath).toLowerCase(),n=new Set([t.projectName,u.basename(t.projectPath),i].map(o=>o.trim().toLowerCase()).filter(Boolean));return e.entities.filter(o=>o.kind==="project").find(o=>[o.projectId,o.label,o.identity.key,...o.identity.aliases,typeof o.attributes.path=="string"?o.attributes.path:void 0].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>n.has(r)||n.has(u.basename(r))))}function tr(e,t){let i=t.projectId??t.label,n=e.entities.filter(r=>r.id===t.id||r.projectId===i||r.projectId===t.projectId),o=new Set(n.map(r=>r.id)),s=new Set;for(let r of e.relations)o.has(r.from)&&s.add(r.to),o.has(r.to)&&s.add(r.from);return e.entities.filter(r=>o.has(r.id)||s.has(r.id))}function nr(e){let t=new Map,i=(n,o)=>{let s=t.get(n)??[];s.push(o),t.set(n,s);};for(let n of e.relations)i(n.from,n.to),i(n.to,n.from);for(let n of t.values())n.sort();return t}function ir(e,t,i){let n=new Set(t),o=t.map(s=>({id:s,depth:0}));for(let s=0;s<o.length;s+=1){let r=o[s];if(!(!r||r.depth>=i))for(let c of e.get(r.id)??[])n.has(c)||(n.add(c),o.push({id:c,depth:r.depth+1}));}return [...n]}function di(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 pi(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function or(e,t){let i=pi(e);return i?t.some(n=>{let o=pi(n.reason);return o===i||o.includes(i)||i.includes(o)}):true}function rr(e,t,i,n){let o=li[i]??li.unknown,s=[...new Set(n.map(c=>c.trim().toLowerCase()).filter(Boolean))];if(s.length>0){let c=t.filter(l=>o?.includes(l.kind)&&s.some(d=>di(l).has(d))),a=new Set(s.filter(l=>c.some(d=>di(d).has(l))));return {roots:c.length>0?c.slice(0,4):[e],unresolvedSubjects:n.filter(l=>!a.has(l.trim().toLowerCase()))}}let r=t.filter(c=>o?.includes(c.kind)).slice(0,4);return {roots:r.length>0?r:[e],unresolvedSubjects:[]}}function sr(e,t,i,n){let o=n.issueClass??"unknown",s=[...new Set((n.subjects??[]).map(b=>b.trim()).filter(Boolean))],{roots:r,unresolvedSubjects:c}=rr(t,i.scoped,o,s),a=ir(i.edges,r.map(b=>b.id),3).map(b=>i.entitiesById.get(b)).filter(b=>!!b),l=a.filter(b=>i.scopedIds.has(b.id)&&!r.some(j=>j.id===b.id)&&Zo.has(b.kind)).slice(0,6),d=a.filter(b=>i.scopedIds.has(b.id)&&Xo.has(b.kind)).slice(0,2),y=[...l,...d].filter((b,j,x)=>x.findIndex(D=>D.id===b.id)===j).slice(0,3).flatMap(b=>{let x=r.map(D=>d$1(e,D.id,b.id)).filter(D=>D.found).sort((D,P)=>D.hops.length-P.hops.length)[0];return x?[{from:x.resolvedFrom??x.from,to:x.resolvedTo??x.to,entityPath:x.entityPath,hops:x.hops,proofIds:x.proofs.map(D=>D.id)}]:[]}),h=new Set([...r.flatMap(b=>b.proofIds),...y.flatMap(b=>b.proofIds)]),k=e.proofs.filter(b=>h.has(b.id)).map(b=>b.artifact).filter(b=>i.projectRelativePath==="."?true:b.split(u.sep).join("/").replace(/^\.\//,"").startsWith(`${i.projectRelativePath}/`)).filter((b,j,x)=>x.indexOf(b)===j).sort().slice(0,4),v=[];return l.length===0&&v.push("No affected surface is structurally reachable from the selected root evidence."),d.length===0&&v.push("No graph-connected test suite or pipeline is available as a verification target."),k.length===0&&v.push("The selected graph entities do not carry portable source evidence."),c.length>0&&v.push(`No canonical graph entity resolved for ${c.length} reported subject(s): ${c.join(", ")}.`),{issueId:n.id,issueClass:o,status:n.status==="fail"?"fail":"warn",reason:n.reason,scope:"structural-impact-candidates",subjects:s,unresolvedSubjects:c,rootEntities:r.map(Qt),affectedEntities:l.map(Qt),verificationTargets:d.map(Qt),proofPaths:y,sourceArtifacts:k,unknowns:v}}async function en(e){if(!e.workspacePath)return qe(e,"graph-missing","Project is not attached to a Workspai workspace; no workspace graph can be consulted.");let t=u.join(e.workspacePath,a$6),i=u.join(e.workspacePath,p.model);if(!await m.pathExists(t))return qe(e,"graph-missing","Workspace knowledge graph is missing. Run workspace model before relying on graph-aware diagnosis.");if(!await m.pathExists(i))return qe(e,"model-missing","Canonical workspace model is missing, so graph source binding cannot be verified.");let n,o,s,r;try{({graph:n,model:o,entitiesById:s,edges:r}=await Qo(t,i));}catch(h){return qe(e,"invalid",`Graph-aware diagnosis rejected invalid evidence: ${h instanceof Error?h.message:String(h)}`)}let c={artifact:a$6,schemaVersion:n.schemaVersion,sourceArtifact:n.source.artifact,sourceHash:n.source.hash,entityCount:n.entities.length,relationCount:n.relations.length,proofCount:n.proofs.length};try{b$2(n,o);}catch(h){return qe(e,"stale",h instanceof Error?h.message:String(h),c)}let a=er(n,e);if(!a)return qe(e,"project-unresolved","The current project could not be resolved to one canonical project entity.",c);let l=tr(n,a),d={scoped:l,scopedIds:new Set(l.map(h=>h.id)),entitiesById:s,edges:r,projectRelativePath:Dt(e.workspacePath,e.projectPath)},p$1=(e.probes??[]).filter(h=>h.status!=="pass"),y=[...p$1,...(e.issues??[]).filter(h=>!or(h,p$1)).map((h,k)=>({id:`legacy-project-issue-${k+1}`,status:"fail",reason:h,issueClass:"runtime"}))].map(h=>sr(n,a,d,h));return {schemaVersion:Xt,generatedAt:(e.now??new Date).toISOString(),status:"available",claimBoundary:ui,graph:c,project:{name:e.projectName,path:Dt(e.workspacePath,e.projectPath),entityId:a.id},summary:{findingCount:y.length,rootEntityCount:new Set(y.flatMap(h=>h.rootEntities.map(k=>k.id))).size,affectedEntityCount:new Set(y.flatMap(h=>h.affectedEntities.map(k=>k.id))).size,verificationTargetCount:new Set(y.flatMap(h=>h.verificationTargets.map(k=>k.id))).size,proofPathCount:y.reduce((h,k)=>h+k.proofPaths.length,0),subjectCount:new Set(y.flatMap(h=>h.subjects)).size,unresolvedSubjectCount:new Set(y.flatMap(h=>h.unresolvedSubjects)).size,unknownCount:y.reduce((h,k)=>h+k.unknowns.length,0)},findings:y,diagnostics:[]}}var Rt="workspai.doctor-summary.v1";function fi(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 mi(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 ar(e,t){return t.replace(/\.\*$/u,"").split(".").map(n=>Number.parseInt(n,10)).every((n,o)=>e[o]===n)}function cr(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 lr(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=ar(e.parts,o);return n==="=="?c:!c}let s=fi(o);if(!s)return null;let r=mi(e.parts,s.parts);return n==="==="?e.raw===s.raw:n==="=="?r===0:n==="!="?r!==0:n===">="?r>=0:n==="<="?r<=0:n===">"?r>0:n==="<"?r<0:n==="~="?r>=0&&mi(e.parts,cr(s.parts))<0:null}function gi(e,t){let i=fi(e),n=t.trim(),o=n.replace(/^\(|\)$/gu,"").split(",").map(c=>c.trim()).filter(Boolean);if(!i||o.length===0)return {version:i?.raw??e.trim(),specifier:n,satisfied:null,unsupportedSpecifiers:o.length===0?[n]:o};let s=o.map(c=>({clause:c,result:lr(i,c)})),r=s.filter(c=>c.result===null).map(c=>c.clause);return {version:i.raw,specifier:n,satisfied:r.length>0?null:s.every(c=>c.result===true),unsupportedSpecifiers:r}}var rn=p.doctor;function Ri(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function yi(e){return [...new Set(e.filter(t=>t&&t.trim().length>0))]}function Si(){let e=t$2().map(n=>u.join(n,b$5()?"poetry.exe":"poetry")),t=b$5()?[u.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),u.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],i=b$5()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return Ri([...e,...t,...i])}function dr(e,t=process.cwd()){let i=t$2().map(l=>({location:"Global (user-local)",path:u.join(l,b$5()?"rapidkit.exe":"rapidkit")})),n$1=[{location:"Global (pipx)",path:u.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:u.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:u.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],o=n(u.join(t,".venv")),s=p$1(t),r=[{location:"Workspace (.venv)",path:o},...s.map(l=>({location:"Workspace (launcher)",path:l}))],c=[...i,...n$1,...r],a=new Set;return c.filter(l=>a.has(l.path)?false:(a.add(l.path),true))}function 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,s=t.get(n.location)??Number.MAX_SAFE_INTEGER;return o!==s?o-s:i.path.localeCompare(n.path)})}function at(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 Ei(e,t){let i=t.some(c=>c.runtimeFamily==="python"),n=t.some(c=>c.runtimeFamily==="go"),o=t.find(c=>c.pythonRequirement?.satisfied===false),s=t.find(c=>c.pythonRequirement?.satisfied===null),r=o?.pythonRequirement?{...e.python,status:"error",message:`Python ${o.pythonRequirement.detectedVersion??"unknown"} does not satisfy ${o.pythonRequirement.specifier}`,details:`Project ${o.name} declares requires-python ${o.pythonRequirement.specifier}.`}:s?.pythonRequirement?{...e.python,status:e.python.status==="error"?"error":"warn",details:`Project ${s.name} declares requires-python ${s.pythonRequirement.specifier}, but compatibility could not be evaluated.`}:e.python;return {...e,python:i?r:at(e.python,"Python is optional because this scope has no detected Python project."),poetry:i?e.poetry:at(e.poetry,"Poetry is not applicable to this project scope."),pipx:i?e.pipx:at(e.pipx,"pipx is not applicable to this project scope."),go:n?e.go:at(e.go,"Go is not applicable to this project scope."),rapidkitCore:/not installed/i.test(e.rapidkitCore.message)||!i&&e.rapidkitCore.status!=="error"?at(e.rapidkitCore,"RapidKit Core is an optional engine for Python-backed kits and modules; Workspai CLI diagnostics remain available without it."):e.rapidkitCore}}function ur(e){let i=(e.probes??[]).filter(r=>r.status==="warn").length,n=e.issues.some(r=>r.toLowerCase().includes("environment file missing")),o=(e.probes??[]).some(r=>r.id==="surface-env-contract"),s=(e.probes??[]).some(r=>r.id==="surface-security-hygiene");return e.hasEnvFile===false&&!n&&!o&&(i+=1),typeof e.vulnerabilities=="number"&&e.vulnerabilities>0&&!s&&(i+=1),i}function mr(e){let t=e.coreVersion?.split(".")[0],i=e.npmVersion?.split(".")[0];return !t||!i?false:t!==i}var fr="doctor-project-scan-v2",gr="doctor-project-scan-policy-v4",Ai=s.doctorWorkspaceCache.schemaVersion,yr=Object.freeze({version:"doctor-evidence-v1",scoringPolicyVersion:"doctor-score-policy-v2",generatedBy:"workspai",deterministicScoreBreakdown:true,scopeModel:"workspace-aggregate-or-project-scoped"}),ct=Object.freeze({local:{name:"local",exitOnErrors:true,exitOnWarnings:false,warningExitCode:0,advisoryWarningsBlockRelease:false,description:"Local diagnostics: report warnings without blocking the developer loop."},ci:{name:"ci",exitOnErrors:true,exitOnWarnings:true,warningExitCode:2,advisoryWarningsBlockRelease:false,description:"CI diagnostics: errors fail, warnings return a distinct warning exit code."},release:{name:"release",exitOnErrors:true,exitOnWarnings:true,warningExitCode:1,advisoryWarningsBlockRelease:true,description:"Release gate: any warning/error blocks release readiness."},"enterprise-strict":{name:"enterprise-strict",exitOnErrors:true,exitOnWarnings:true,warningExitCode:1,advisoryWarningsBlockRelease:true,description:"Enterprise strict gate: all warnings/errors block release and must carry evidence or repair guidance."}});function Ue(){return {...yr}}function It(e){let t=e.profile?.trim();return t&&t in ct?{...ct[t]}:e.strict?{...ct.release}:e.ci?{...ct.ci}:{...ct.local}}function At(e){return !e||e.total<=0?null:Math.round(e.passed/e.total*100)}function hr(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 br(e,t){let i=hr(e),n=Date.parse(t),o=typeof i.ttlSeconds=="number"?i.ttlSeconds*1e3:null,s=o!==null&&Number.isFinite(n)?new Date(n+o).toISOString():void 0,r=!Number.isFinite(n)||o!==null&&!s?"unknown":o!==null&&Date.now()>n+o?"stale":"fresh";return {category:i.category,generatedAt:t,ttlSeconds:i.ttlSeconds,...s?{expiresAt:s}:{},status:r,verifyBeforeUse:i.category!=="structure"||r!=="fresh",reason:i.reason}}function kr(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 Fi(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 vr(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 wr(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:yi(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:yi([...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 cn(e,t){let i=br(e,e.freshness?.generatedAt??t),n=e.issueClass??kr(e),o=e.operationalImpact??vr(e,n),s=wr({probe:e,freshness:i});return {...e,freshness:i,issueClass:n,operationalImpact:o,repairIntent:s}}function jr(e,t){Array.isArray(e.probes)&&(e.probes=e.probes.map(i=>cn(i,t)));}function xr(e){e.diagnosis=a$9({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 Ft(e,t=new Date().toISOString()){jr(e,t),$r(e,e.path),xr(e);}function $i(e){if(!e.diagnosis||e.graphDiagnosis?.status!=="available")return;let t=new Map(e.graphDiagnosis.findings.map(i=>[i.issueId,i]));for(let i of e.diagnosis.findings){let n=t.get(i.probeId);if(!n)continue;let o=[{kind:"graph",role:"impact",ref:`doctor-graph:${e.name}:${n.issueId}`,claim:`Canonical graph diagnosis retained ${n.proofPaths.length} bounded proof path(s), ${n.affectedEntities.length} affected candidate(s), and ${n.verificationTargets.length} verification target(s); structural reachability is not runtime causality.`}],s=new Set(i.proofs.map(r=>`${r.kind}:${r.role}:${r.ref}`));for(let r of o){let c=`${r.kind}:${r.role}:${r.ref}`;s.has(c)||i.proofs.push(r);}}}function ln(e,t){let i=e.flatMap(a=>Array.isArray(a.probes)?a.probes.map(l=>l.freshness).filter(l=>!!l):[]),n=i.filter(a=>a.status==="stale").length,o=i.filter(a=>a.status==="unknown").length,s=i.filter(a=>a.category==="state").length,r=i.filter(a=>a.verifyBeforeUse).length,c=i.map(a=>a.generatedAt).filter(Boolean).sort()[0];return {generatedAt:t,status:n>0?"stale":o>0?"unknown":"fresh",staleProbeCount:n,unknownProbeCount:o,liveStateProbeCount:s,verifyBeforeUseProbeCount:r,...c?{oldestProbeGeneratedAt:c}:{}}}function Ii(e){return typeof e=="number"?e:Array.isArray(e)?e.length:0}async function Ni(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 Mi(e,t){if(!e?.system)return [];let i=[{id:"python",current:t.python},{id:"poetry",current:t.poetry},{id:"pipx",current:t.pipx},{id:"go",current:t.go},{id:"rapidkitCore",current:t.rapidkitCore}],n=[];for(let o of i){let s=e.system?.[o.id]?.status;!s||s===o.current.status||n.push({id:o.id,from:s,to:o.current.status});}return n}function Cr(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 h=y.path||y.name;h&&o.set(h,Ii(y.issues));}let s=0,r=0,c=new Set,a=new Set,l=new Set([...Array.from(o.keys()),...Array.from(i.keys())]);for(let y of l){let h=o.get(y)??0,k=i.get(y)??0;k>h?(s+=k-h,c.add(y)):k<h&&(r+=h-k,a.add(y));}let d=At(e.healthScore),p=At(t.healthScore);return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:s,resolvedIssueCount:r,netIssueDelta:s-r,scoreDeltaPercent:d===null||p===null?null:p-d,systemStatusChanges:Mi(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore}),regressedProjects:Array.from(c).sort(),improvedProjects:Array.from(a).sort()}}function Pr(e,t){if(!e)return {baselineAvailable:false,newIssueCount:0,resolvedIssueCount:0,netIssueDelta:0,scoreDeltaPercent:null,systemStatusChanges:[],regressedProjects:[],improvedProjects:[]};let i=Ii(e.project?.issues),n=t.project.issues.length,o=Math.max(n-i,0),s=Math.max(i-n,0),r=At(e.healthScore),c=At(t.healthScore),a=t.project.path||t.project.name;return {baselineAvailable:true,previousGeneratedAt:e.generatedAt,newIssueCount:o,resolvedIssueCount:s,netIssueDelta:o-s,scoreDeltaPercent:r===null||c===null?null:c-r,systemStatusChanges:Mi(e,{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore}),regressedProjects:o>0?[a]:[],improvedProjects:s>0?[a]:[]}}function Ti(e){let t=e??[],i=0,n=0;for(let r of t){if(r.scope==="project-scoped"){i+=1;continue}(r.scope==="workspace-aggregate"||r.scope==="host-system")&&(n+=1);}let o=i>0&&n>0?1:0,s=o>0?"mixed":i>0?"scoped":n>0?"aggregated":"unknown";return {scopedCount:i,aggregatedCount:n,mixedCount:o,dominantScope:s}}function X(e,t){return b$5()?`Set-Location -LiteralPath "${e.replace(/"/g,'`"')}"; ${t}`:`cd '${e.replace(/'/g,`'"'"'`)}' && ${t}`}function Dr(e){return e.manager==="project-script"&&e.projectScript?X(e.projectPath,e.projectScript):e.manager==="poetry"?X(e.projectPath,"poetry install --no-root"):e.manager==="uv"?X(e.projectPath,"uv sync"):X(e.projectPath,b$5()?"py -3 -m venv .venv":"python3 -m venv .venv")}async function Rr(e){let t=b$5()?["script/setup.cmd","script/setup.ps1","scripts/setup.cmd","scripts/setup.ps1","script/setup","scripts/setup","bin/setup"]:["script/setup","scripts/setup","bin/setup"];for(let i of t)if(await m.pathExists(u.join(e,i)))return i}async function Sr(e){let t=e?[e]:j$1();for(let i of t)try{let o=await execa(i,i==="py"?["-3","--version"]:["--version"],{timeout:3e3,reject:false}),s=`${o.stdout??""}
18
- ${o.stderr??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(s)return s[1]}catch{}}function Er(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 Ar(e){return e==="Tauri"||e==="Electron"?"desktop":e==="VS Code Extension"?"extension":e==="Next.js"||e==="Remix"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Svelte"||e==="Vite"||e==="Astro"||e==="Solid"?"frontend":e==="Unknown"||e==="Node.js"||e==="Python"||e==="Go"||e==="Java"||e==="Scala"||e==="Kotlin"||e==="C"||e==="C++"?"generic":"backend"}function Fr(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 $r(e,t){let i=z(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function lt(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=Er(t),e.projectKind=Ar(t),e.runtimeFamily=Fr(t);}function Oi(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 dn(e){switch(e.key){case "fastapi":return "FastAPI";case "django":return "Django";case "flask":return "Flask";case "python":return "Python";case "nestjs":return "NestJS";case "nextjs":return "Next.js";case "remix":return "Remix";case "nuxt":return "Nuxt";case "react":return "React";case "vite":return "Vite";case "vue":return "Vue";case "sveltekit":return "SvelteKit";case "svelte":return "Svelte";case "angular":return "Angular";case "astro":return "Astro";case "solid":return "Solid";case "express":return "Express";case "fastify":return "Fastify";case "koa":return "Koa";case "tauri":return "Tauri";case "electron":return "Electron";case "vscode-extension":return "VS Code Extension";case "node":return "Node.js";case "gofiber":return "Go/Fiber";case "gogin":return "Go/Gin";case "echo":return "Echo";case "go":return "Go";case "springboot":return "Spring Boot";case "java":return "Java";case "laravel":return "Laravel";case "php":return "PHP";case "rails":return "Ruby on Rails";case "ruby":return "Ruby";case "dotnet":return "ASP.NET";case "phoenix":return "Phoenix";case "elixir":return "Elixir";case "clojure":return "Clojure";case "scala":return "Scala";case "kotlin":return "Kotlin";case "deno":return "Deno";case "bun":return "Bun";case "actix":case "axum":case "rocket":case "rust":return "Rust";case "sinatra":case "symfony":return e.key==="sinatra"?"Ruby":"PHP";case "c":return "C";case "cpp":return "C++";case "unknown":return "Unknown";default:return "Unknown"}}function Ir(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 Nr(e,t){e.framework=dn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=Oi(t.runtime);}function ne(e,t){e.framework=dn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind=t.key==="tauri"||t.key==="electron"?"desktop":t.key==="vscode-extension"?"extension":Ir(t)?"generic":"backend",e.runtimeFamily=Oi(t.runtime);}function Mr(e){let t=e.dependencies,i=e.scripts??{},n=(e.kitName??"").toLowerCase(),o=r=>!!t[r],s=Object.values(i).filter(r=>typeof r=="string").join(" ").toLowerCase();return o("next")||s.includes("next ")?{framework:"Next.js",confidence:"high"}:o("nuxt")||s.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:o("@nestjs/core")||n.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:o("express")?{framework:"Express",confidence:"high"}:o("fastify")?{framework:"Fastify",confidence:"high"}:o("koa")?{framework:"Koa",confidence:"high"}:o("@angular/core")?{framework:"Angular",confidence:"high"}:o("@sveltejs/kit")||s.includes("svelte-kit")?{framework:"SvelteKit",confidence:"high"}:o("vue")?{framework:"Vue",confidence:"medium"}:o("react")&&o("react-dom")?{framework:"React",confidence:"medium"}:{framework:"Node.js",confidence:"low"}}async function Tr(e,t){let i=m$1(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:dn(i),confidence:i.confidence}}async function hi(e){try{let t=await m.stat(e);if(t.isFile()&&t.size<=1048576){let i=await m.readFile(e);return `${u.basename(e)}:f:${t.size}:${createHash("sha256").update(i).digest("hex")}`}if(t.isDirectory()){if(["node_modules",".venv"].includes(u.basename(e))){let l=await m.readdir(e).catch(()=>[]);return `${u.basename(e)}:materialized:${l.length}:${t.mtimeMs}`}let i=createHash("sha256"),n=[e],o=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","coverage","target","bin","obj","__pycache__"]),s=0,r=0,c=2e4,a=32*1024*1024;for(;n.length>0&&s<c;){let l=n.shift();if(!l)break;let d=await m.readdir(l,{withFileTypes:true}).catch(()=>[]);d.sort((p,y)=>p.name.localeCompare(y.name));for(let p of d){if(o.has(p.name))continue;let y=u.join(l,p.name),h=u.relative(e,y).split(u.sep).join("/");if(p.isDirectory()){i.update(`d:${h}\0`),n.push(y);continue}if(!p.isFile())continue;let k=await m.stat(y).catch(()=>null);if(k){if(s+=1,i.update(`f:${h}:${k.size}:${k.mtimeMs}\0`),k.size<=262144&&r+k.size<=a){let v=await m.readFile(y).catch(()=>null);v&&(r+=v.length,i.update(v));}if(s>=c)break}}}return i.update(`files:${s}:bytes:${r}:remaining:${n.length}`),`${u.basename(e)}:d:${i.digest("hex")}`}return `${u.basename(e)}:other:${t.size}:${t.mtimeMs}`}catch{return `${u.basename(e)}:missing`}}async function Or(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 pt(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 pt(e)&&i.add(e);let s=await c$2(e);for(let a of s.summary.projects){let l=u.resolve(e,a.relativePath);await o(l)&&(i.add(l),n.add(l));}let r=await a$3(e);for(let a of r){let l=u.isAbsolute(a.path)?a.path:u.join(e,a.path);if(await o(l)){let d=u.resolve(l);i.add(d),n.add(d);}}return (await a$4(e,{skipDirs:t,descendIntoMatchedProjects:true,isProjectDir:async(a,l)=>u.resolve(a)===u.resolve(l)?pt(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 cs(e,3,t)).forEach(l=>i.add(l)),i.size===0&&!await b$1(e)&&await o(e)&&i.add(e),Array.from(i).sort((a,l)=>a.localeCompare(l))}catch{return []}}async function _r(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(hi)),s=await Promise.all(t.map(async r=>{let c=await Promise.all(n.map(a=>hi(u.join(r,a))));return `${r}::${c.join("|")}`}));return [fr,gr,...o,...s].join("||")}async function Br(e,t){try{if(!await m.pathExists(e))return null;let i=await m.readJSON(e);a$5(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!==Ai)return null;let o=Date.parse(n.generatedAt),s=Number(process.env.WORKSPAI_DOCTOR_CACHE_MAX_AGE_SECONDS),r=Number.isFinite(s)&&s>=0?s:300;return !Number.isFinite(o)||Date.now()-o>r*1e3?null:n}catch{return null}}async function Gr(e,t){try{a$5(t,"contracts/doctor-workspace-cache.v2.json",`Doctor workspace cache ${e}`),await g(e,t$1.doctorWorkspaceCache,t);}catch{}}async function Kr(e,t){let i=Number.parseInt(process.env.RAPIDKIT_DOCTOR_SCAN_CONCURRENCY??"4",10),n=Number.isFinite(i)?Math.min(32,Math.max(1,i)):4,o=new Array(e.length),s=0,r=Array.from({length:Math.min(n,e.length)},async()=>{for(;s<e.length;){let c=s;s+=1;let a=e[c];if(a===void 0)break;o[c]=await t(a);}});return await Promise.all(r),o}async function Wr(e,t,i){let n=u.join(e,rn);try{let o=[];for(let d of t.projects)if(d.diagnosis)for(let p of d.diagnosis.findings)p.status==="blocking"&&p.symptom.trim()&&o.push(`${d.name}: ${p.symptom.trim()}`);else {for(let p of d.issues??[])typeof p=="string"&&p.trim()&&o.push(`${d.name}: ${p.trim()}`);for(let p of d.probes??[])p.status==="fail"&&p.reason.trim()&&o.push(`${d.name}: ${p.reason.trim()}`);}for(let[d,p]of [["python",t.python],["rapidkitCore",t.rapidkitCore]])if(p?.status==="error"){let y=typeof p.message=="string"?p.message:`${d} check failed`;o.push(`${d}: ${y}`);}let s=t.projects.map(Q),r=s.reduce((d,p)=>d+p.blockingFindings,0),c=s.reduce((d,p)=>d+p.advisoryFindings,0),a=Se(t.projects,[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore]),l=f$2({schemaVersion:a$7,evidenceType:"workspace",contract:Ue(),policyProfile:t.policyProfile,workspacePath:e,workspaceName:t.workspaceName,projectScanCached:t.projectScanCached??false,projectScanSignature:t.projectScanSignature,cachePath:i,healthScore:t.healthScore,evidenceFreshness:t.evidenceFreshness,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,versions:{core:t.coreVersion,npm:t.npmVersion}},projects:t.projects,summary:{counts:a,totalProjects:t.projects.length,totalIssues:t.projects.reduce((d,p)=>d+p.issues.length,0),verdict:t.healthScore?.verdict??"passed",blockingFindings:r,advisoryFindings:c,projectAdvisoryWarningProjects:s.filter(d=>d.advisoryFindings>0).length,projectAdvisoryWarnings:c,hasSystemErrors:[t.python,t.rapidkitCore].some(d=>d.status==="error"),scopeProvenance:t.scopeProvenance},driftDelta:t.driftDelta,scoreBreakdown:t.scoreBreakdown??[]},{commandId:"checkWorkspaceHealth",exitCode:mt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:o.slice(0,12),runId:e$1()});return d(l),await g(e,rn,l),n}catch(o){throw o}}async function pn(e=process.cwd()){let[t,i,n,o,s]=await Promise.all([Hr(),Lr(),qr(),Vr(),zr(e)]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:s}}async function Hr(){let e=j$1(),t;for(let i of e)try{let n=i==="py"?["-3","--version"]:["--version"],{stdout:o,stderr:s}=await execa(i,n,{timeout:3e3,reject:false}),c=`${o??""}
18
+ ${o.stderr??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(s)return s[1]}catch{}}function Er(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 Ar(e){return e==="Tauri"||e==="Electron"?"desktop":e==="VS Code Extension"?"extension":e==="Next.js"||e==="Remix"||e==="Nuxt"||e==="React"||e==="Vue"||e==="Angular"||e==="SvelteKit"||e==="Svelte"||e==="Vite"||e==="Astro"||e==="Solid"?"frontend":e==="Unknown"||e==="Node.js"||e==="Python"||e==="Go"||e==="Java"||e==="Scala"||e==="Kotlin"||e==="C"||e==="C++"?"generic":"backend"}function Fr(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 $r(e,t){let i=z(t);e.commandCapabilities=i,e.supportTier=i.frameworkSupportTier;}function lt(e,t,i,n){e.framework=t,e.frameworkConfidence=i,e.supportTier=Er(t),e.projectKind=Ar(t),e.runtimeFamily=Fr(t);}function Oi(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 dn(e){switch(e.key){case "fastapi":return "FastAPI";case "django":return "Django";case "flask":return "Flask";case "python":return "Python";case "nestjs":return "NestJS";case "nextjs":return "Next.js";case "remix":return "Remix";case "nuxt":return "Nuxt";case "react":return "React";case "vite":return "Vite";case "vue":return "Vue";case "sveltekit":return "SvelteKit";case "svelte":return "Svelte";case "angular":return "Angular";case "astro":return "Astro";case "solid":return "Solid";case "express":return "Express";case "fastify":return "Fastify";case "koa":return "Koa";case "tauri":return "Tauri";case "electron":return "Electron";case "vscode-extension":return "VS Code Extension";case "node":return "Node.js";case "gofiber":return "Go/Fiber";case "gogin":return "Go/Gin";case "echo":return "Echo";case "go":return "Go";case "springboot":return "Spring Boot";case "java":return "Java";case "laravel":return "Laravel";case "php":return "PHP";case "rails":return "Ruby on Rails";case "ruby":return "Ruby";case "dotnet":return "ASP.NET";case "phoenix":return "Phoenix";case "elixir":return "Elixir";case "clojure":return "Clojure";case "scala":return "Scala";case "kotlin":return "Kotlin";case "deno":return "Deno";case "bun":return "Bun";case "actix":case "axum":case "rocket":case "rust":return "Rust";case "sinatra":case "symfony":return e.key==="sinatra"?"Ruby":"PHP";case "c":return "C";case "cpp":return "C++";case "unknown":return "Unknown";default:return "Unknown"}}function Ir(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 Nr(e,t){e.framework=dn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind="frontend",e.runtimeFamily=Oi(t.runtime);}function ne(e,t){e.framework=dn(t),e.frameworkKey=t.key,e.importStack=t.importStack,e.frameworkConfidence=t.confidence,e.supportTier=t.supportTier,e.projectKind=t.key==="tauri"||t.key==="electron"?"desktop":t.key==="vscode-extension"?"extension":Ir(t)?"generic":"backend",e.runtimeFamily=Oi(t.runtime);}function Mr(e){let t=e.dependencies,i=e.scripts??{},n=(e.kitName??"").toLowerCase(),o=r=>!!t[r],s=Object.values(i).filter(r=>typeof r=="string").join(" ").toLowerCase();return o("next")||s.includes("next ")?{framework:"Next.js",confidence:"high"}:o("nuxt")||s.includes("nuxt ")?{framework:"Nuxt",confidence:"high"}:o("@nestjs/core")||n.startsWith("nestjs.")?{framework:"NestJS",confidence:"high"}:o("express")?{framework:"Express",confidence:"high"}:o("fastify")?{framework:"Fastify",confidence:"high"}:o("koa")?{framework:"Koa",confidence:"high"}:o("@angular/core")?{framework:"Angular",confidence:"high"}:o("@sveltejs/kit")||s.includes("svelte-kit")?{framework:"SvelteKit",confidence:"high"}:o("vue")?{framework:"Vue",confidence:"medium"}:o("react")&&o("react-dom")?{framework:"React",confidence:"medium"}:{framework:"Node.js",confidence:"low"}}async function Tr(e,t){let i=m$1(e,t??null);return i.runtime!=="python"?{framework:"Python",confidence:"low"}:{framework:dn(i),confidence:i.confidence}}async function hi(e){try{let t=await m.stat(e);if(t.isFile()&&t.size<=1048576){let i=await m.readFile(e);return `${u.basename(e)}:f:${t.size}:${createHash("sha256").update(i).digest("hex")}`}if(t.isDirectory()){if(["node_modules",".venv"].includes(u.basename(e))){let l=await m.readdir(e).catch(()=>[]);return `${u.basename(e)}:materialized:${l.length}:${t.mtimeMs}`}let i=createHash("sha256"),n=[e],o=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","coverage","target","bin","obj","__pycache__"]),s=0,r=0,c=2e4,a=32*1024*1024;for(;n.length>0&&s<c;){let l=n.shift();if(!l)break;let d=await m.readdir(l,{withFileTypes:true}).catch(()=>[]);d.sort((p,y)=>p.name.localeCompare(y.name));for(let p of d){if(o.has(p.name))continue;let y=u.join(l,p.name),h=u.relative(e,y).split(u.sep).join("/");if(p.isDirectory()){i.update(`d:${h}\0`),n.push(y);continue}if(!p.isFile())continue;let k=await m.stat(y).catch(()=>null);if(k){if(s+=1,i.update(`f:${h}:${k.size}:${k.mtimeMs}\0`),k.size<=262144&&r+k.size<=a){let v=await m.readFile(y).catch(()=>null);v&&(r+=v.length,i.update(v));}if(s>=c)break}}}return i.update(`files:${s}:bytes:${r}:remaining:${n.length}`),`${u.basename(e)}:d:${i.digest("hex")}`}return `${u.basename(e)}:other:${t.size}:${t.mtimeMs}`}catch{return `${u.basename(e)}:missing`}}async function Or(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 pt(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 pt(e)&&i.add(e);let s=await c$2(e);for(let a of s.summary.projects){let l=u.resolve(e,a.relativePath);await o(l)&&(i.add(l),n.add(l));}let r=await a$3(e);for(let a of r){let l=u.isAbsolute(a.path)?a.path:u.join(e,a.path);if(await o(l)){let d=u.resolve(l);i.add(d),n.add(d);}}return (await a$4(e,{skipDirs:t,descendIntoMatchedProjects:true,isProjectDir:async(a,l)=>u.resolve(a)===u.resolve(l)?pt(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 cs(e,3,t)).forEach(l=>i.add(l)),i.size===0&&!await b$1(e)&&await o(e)&&i.add(e),Array.from(i).sort((a,l)=>a.localeCompare(l))}catch{return []}}async function _r(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(hi)),s=await Promise.all(t.map(async r=>{let c=await Promise.all(n.map(a=>hi(u.join(r,a))));return `${r}::${c.join("|")}`}));return [fr,gr,...o,...s].join("||")}async function Br(e,t){try{if(!await m.pathExists(e))return null;let i=await m.readJSON(e);a$5(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!==Ai)return null;let o=Date.parse(n.generatedAt),s=Number(process.env.WORKSPAI_DOCTOR_CACHE_MAX_AGE_SECONDS),r=Number.isFinite(s)&&s>=0?s:300;return !Number.isFinite(o)||Date.now()-o>r*1e3?null:n}catch{return null}}async function Gr(e,t){try{a$5(t,"contracts/doctor-workspace-cache.v2.json",`Doctor workspace cache ${e}`),await h(e,t$1.doctorWorkspaceCache,t);}catch{}}async function Kr(e,t){let i=Number.parseInt(process.env.RAPIDKIT_DOCTOR_SCAN_CONCURRENCY??"4",10),n=Number.isFinite(i)?Math.min(32,Math.max(1,i)):4,o=new Array(e.length),s=0,r=Array.from({length:Math.min(n,e.length)},async()=>{for(;s<e.length;){let c=s;s+=1;let a=e[c];if(a===void 0)break;o[c]=await t(a);}});return await Promise.all(r),o}async function Wr(e,t,i){let n=u.join(e,rn);try{let o=[];for(let d of t.projects)if(d.diagnosis)for(let p of d.diagnosis.findings)p.status==="blocking"&&p.symptom.trim()&&o.push(`${d.name}: ${p.symptom.trim()}`);else {for(let p of d.issues??[])typeof p=="string"&&p.trim()&&o.push(`${d.name}: ${p.trim()}`);for(let p of d.probes??[])p.status==="fail"&&p.reason.trim()&&o.push(`${d.name}: ${p.reason.trim()}`);}for(let[d,p]of [["python",t.python],["rapidkitCore",t.rapidkitCore]])if(p?.status==="error"){let y=typeof p.message=="string"?p.message:`${d} check failed`;o.push(`${d}: ${y}`);}let s=t.projects.map(Q),r=s.reduce((d,p)=>d+p.blockingFindings,0),c=s.reduce((d,p)=>d+p.advisoryFindings,0),a=Se(t.projects,[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore]),l=f$1({schemaVersion:a$7,evidenceType:"workspace",contract:Ue(),policyProfile:t.policyProfile,workspacePath:e,workspaceName:t.workspaceName,projectScanCached:t.projectScanCached??false,projectScanSignature:t.projectScanSignature,cachePath:i,healthScore:t.healthScore,evidenceFreshness:t.evidenceFreshness,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore,versions:{core:t.coreVersion,npm:t.npmVersion}},projects:t.projects,summary:{counts:a,totalProjects:t.projects.length,totalIssues:t.projects.reduce((d,p)=>d+p.issues.length,0),verdict:t.healthScore?.verdict??"passed",blockingFindings:r,advisoryFindings:c,projectAdvisoryWarningProjects:s.filter(d=>d.advisoryFindings>0).length,projectAdvisoryWarnings:c,hasSystemErrors:[t.python,t.rapidkitCore].some(d=>d.status==="error"),scopeProvenance:t.scopeProvenance},driftDelta:t.driftDelta,scoreBreakdown:t.scoreBreakdown??[]},{commandId:"checkWorkspaceHealth",exitCode:mt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:o.slice(0,12),runId:e$1()});return d(l),await h(e,rn,l),n}catch(o){throw o}}async function pn(e=process.cwd()){let[t,i,n,o,s]=await Promise.all([Hr(),Lr(),qr(),Vr(),zr(e)]);return {python:t,poetry:i,pipx:n,go:o,rapidkitCore:s}}async function Hr(){let e=j$1(),t;for(let i of e)try{let n=i==="py"?["-3","--version"]:["--version"],{stdout:o,stderr:s}=await execa(i,n,{timeout:3e3,reject:false}),c=`${o??""}
19
19
  ${s??""}`.match(/Python\s+(\d+\.\d+(?:\.\d+)?)/i);if(c){let a=c[1],[l,d]=a.split(".").map(Number);if(l<3||l===3&&d<10){t??={version:a,command:[i,...n.slice(0,-1)].join(" ")};continue}return {status:"ok",message:`Python ${a}`,details:`Using ${[i,...n.slice(0,-1)].join(" ")}`}}}catch{continue}return t?{status:"warn",message:`Python ${t.version} (requires 3.10+)`,details:`${t.command} found but version is below minimum requirement`}:{status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Lr(){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 Si())try{if(!await m.pathExists(t))continue;let{stdout:i}=await execa(t,["--version"],{timeout:3e3,shell:c$1()}),n=i.match(/Poetry .*version ([\d.]+)/)||i.match(/([\d.]+)/);return {status:"ok",message:n?.[1]?`Poetry ${n[1]}`:"Poetry detected",details:`Available at ${t}`}}catch{continue}return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function qr(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{let e=j$1();for(let t of e)try{let i=t==="py"?["-3","-m","pipx","--version"]:["-m","pipx","--version"],{stdout:n}=await execa(t,i,{timeout:3e3,shell:c$1()});return {status:"ok",message:`pipx ${n.trim()}`,details:`Available via ${t} ${i.join(" ")}`}}catch{continue}return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Vr(){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 zr(e=process.cwd()){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],n=[],o=dr(t,e);for(let{location:r,path:c}of o)try{if(await m.pathExists(c)){let{stdout:a,exitCode:l}=await execa(c,["--version"],{timeout:3e3,reject:false});if(l===0&&(a.includes("RapidKit Version")||a.includes("RapidKit"))){let d=a.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(d){let p=await execa(c,["list","--json"],{timeout:5e3,reject:false});p.exitCode===0?i.push({location:r,path:c,version:d[1]}):n.push({location:r,path:c,version:d[1],reason:dt(p.stderr||p.stdout)});}}}}catch(a){await m.pathExists(c)&&n.push({location:r,path:c,reason:dt(a instanceof Error?a.message:String(a))});continue}if(i.length>0){let r=i.filter(a=>a.location!=="Workspace (launcher)");if(r.length>0){let a=pr(r),l=a[0].version,d=a.some(h=>h.location==="Workspace (.venv)"),p=a.some(h=>h.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(h=>({location:h.location,path:h.path,version:h.version}))}}return {status:"ok",message:`RapidKit Core ${i[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:r,exitCode:c}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(c===0&&(r.includes("RapidKit Version")||r.includes("RapidKit"))){let a=r.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a){let l=await execa("rapidkit",["list","--json"],{timeout:5e3,reject:false});if(l.exitCode===0)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via PATH"};n.push({location:"PATH",path:"rapidkit",version:a[1],reason:dt(l.stderr||l.stdout)});}}}catch{}try{let{stdout:r,exitCode:c}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(c===0&&(r.includes("RapidKit Version")||r.includes("RapidKit"))){let a=r.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a){let l=await execa("poetry",["run","rapidkit","list","--json"],{timeout:5e3,reject:false});if(l.exitCode===0)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via Poetry"};n.push({location:"Poetry",path:"poetry run rapidkit",version:a[1],reason:dt(l.stderr||l.stdout)});}}}catch{}let s=j$1();for(let r of s)try{let c=r==="py"?["-3","-c","import rapidkit_core; print(rapidkit_core.__version__)"]:["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{stdout:a,exitCode:l}=await execa(r,c,{timeout:3e3,reject:false});if(l===0&&a&&!a.includes("Traceback")&&!a.includes("ModuleNotFoundError")){let d=a.trim();if(d){let y=await execa(r,r==="py"?["-3","-m","rapidkit","list","--json"]:["-m","rapidkit","list","--json"],{timeout:5e3,reject:false});if(y.exitCode===0)return {status:"ok",message:`RapidKit Core ${d}`,details:`Available in ${r} environment`};n.push({location:`${r} environment`,path:`${r} -m rapidkit`,version:d,reason:dt(y.stderr||y.stdout)});}}}catch{continue}if(n.length>0){let r=n[0];return {status:"error",message:r.version?`RapidKit Core ${r.version} installed but unusable`:"RapidKit Core installed but unusable",details:`${r.reason} Reinstall or repair this Python environment before running Core-backed commands.`,paths:n.map(({location:c,path:a,version:l})=>({location:c,path:a,...l?{version:l}:{}}))}}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}function dt(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 U(e,t,i){let n=await Yt(e);t.hasDocker=n.rootDockerfile||n.nestedDockerfile||n.compose;let o=u.join(e,"tests"),s=u.join(e,"test"),r=u.join(e,"src","test"),c=await m.pathExists(o)||await m.pathExists(s)||await m.pathExists(r),a=false;if(t.framework==="Go/Fiber"||t.framework==="Go/Gin")try{let d=[{dir:e,depth:0}],p=4,y=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;d.length>0&&!a;){let h=d.shift();if(!h)break;let k=[];try{k=await m.readdir(h.dir);}catch{continue}for(let v of k){let b=u.join(h.dir,v),j;try{j=await m.stat(b);}catch{continue}if(j.isFile()&&v.endsWith("_test.go")){a=true;break}j.isDirectory()&&h.depth<p&&!y.has(v)&&!v.startsWith(".")&&d.push({dir:b,depth:h.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 Xn(e,i)),t.runtimeFamily==="python"&&!t.hasTests&&(t.hasTests=await Xr(e)),t.runtimeFamily==="node"||t.runtimeFamily==="bun")t.hasCodeQuality=await Zn(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"),h=await m.pathExists(y)&&(await m.readFile(y,"utf8")).includes("golangci-lint");t.hasCodeQuality=await m.pathExists(d)||await m.pathExists(p)||h;}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 ci({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 Jr(e){return Ri([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 Ur(e){let t=e.indexOf("["),i=e.lastIndexOf("]");if(t<0||i<t)return null;try{let n=JSON.parse(e.slice(t,i+1));return Array.isArray(n)?n:null}catch{return null}}async function bi(e){for(let t of Jr(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=Ur(`${n.stdout??""}
20
20
  ${n.stderr??""}`),s=new Set(["pip","setuptools","wheel"]),r=o?.some(c=>typeof c.name=="string"&&!s.has(c.name.toLowerCase()))??false;return {interpreter:t,coreVersion:i,dependenciesInstalled:r}}catch{return {interpreter:t,coreVersion:i,dependenciesInstalled:false}}}return {dependenciesInstalled:false}}async function Yr(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]})),...Si().map(o=>({executable:o,args:t}))],n=new Set;for(let o of i){let s=`${o.executable}\0${o.args.join("\0")}`;if(!n.has(s)&&(n.add(s),!(u.isAbsolute(o.executable)&&!await m.pathExists(o.executable))))try{let r=await execa(o.executable,o.args,{cwd:e,timeout:Math.max(a$8(),15e3),reject:false,shell:c$1()}),c=r.stdout.trim();if(r.exitCode===0&&c&&await m.pathExists(c))return c}catch{}}}async function Zr(e,t,i){let n=u.join(e,".venv");if(await m.pathExists(n))return {environmentPath:n,...await bi({environmentPath:n,frameworkImport:t})};if(i){let o=await Yr(e);if(o)return {environmentPath:o,...await bi({environmentPath:o,frameworkImport:t})}}return {dependenciesInstalled:false}}function T(e,t){e.probes||(e.probes=[]);let i=cn(t,new Date().toISOString()),n=i.status==="pass"&&i.repairCapability?{...i,repairCapability:void 0}:i;e.probes.push(n),n.repairCapability&&(e.repairCapabilities||(e.repairCapabilities=[]),e.repairCapabilities.push(n.repairCapability),n.status!=="pass"&&n.repairCapability.status==="available"&&n.repairCapability.canAutoFix&&n.repairCapability.command&&(e.fixCommands=e.fixCommands??[],e.fixCommands.includes(n.repairCapability.command)||e.fixCommands.push(n.repairCapability.command)));}async function ve(e,t){return (await Promise.all(t.map(i=>m.pathExists(u.join(e,i))))).some(Boolean)}async function _i(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
21
  `)}async function Xr(e){if(await ve(e,["pytest.ini","tox.ini","noxfile.py","conftest.py","tests","test"]))return true;let t=await _i(e);return /\[tool\.pytest(?:\.|\])|\bpytest\b|\bunittest\b|\btox\b|\bnox\b/i.test(t)}async function se(e,t){let i=new Set(t.ignoreDirs??["node_modules",".git","bin","obj","dist"]),o=(t.under&&t.under.length>0?t.under:["."]).map(s=>u.join(e,s));for(;o.length>0;){let s=o.shift(),r;try{r=await m.readdir(s,{withFileTypes:true});}catch{continue}for(let c of r){if(c.isFile()&&(t.name&&c.name===t.name||t.suffix&&c.name.endsWith(t.suffix)))return true;c.isDirectory()&&!i.has(c.name)&&o.push(u.join(s,c.name));}}return false}async function Qr(e,t){let i=t.runtimeFamily||"unknown";if(!(t.projectKind==="backend"||t.projectKind==="generic"||t.projectKind==="desktop"||t.projectKind==="extension"))return;if(i==="node"){let l=await m.pathExists(u.join(e,"package-lock.json"))||await m.pathExists(u.join(e,"pnpm-lock.yaml"))||await m.pathExists(u.join(e,"yarn.lock"));T(t,{id:"adapter-node-lockfile-integrity",label:"Node adapter lockfile integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Node lockfile detected for deterministic dependency restore.":"No Node lockfile detected (package-lock/yarn.lock/pnpm-lock.yaml).",recommendation:l?void 0:"Commit a lockfile for deterministic installs and CI parity."});let d=t.projectKind==="extension"?["src/extension.ts","src/extension.js","extension.ts","extension.js"]:t.projectKind==="desktop"?["src/main.ts","src/main.js","src/index.ts","src/index.js","src-tauri/src/main.rs"]:["src/main.ts","src/main.js","src/server.ts","src/server.js","server.ts","server.js","index.ts","index.js"],p=await ve(e,d);T(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(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(()=>""),h=/\[(?:project\.scripts|tool\.poetry\.scripts)\]/i.test(p)||await ve(e,d);T(t,{id:"adapter-python-boot-entrypoint",label:"Python adapter boot entrypoint",status:h?"pass":"warn",severity:"warn",scope:"project-scoped",reason:h?"Python application or command entrypoint markers detected.":"No Python application or command entrypoint markers detected.",recommendation:h?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(t,{id:"adapter-java-build-wrapper",label:"Java adapter build wrapper",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"Build wrapper detected (mvnw/gradlew).":"No Java build wrapper detected.",recommendation:l?void 0:"Commit mvnw or gradlew for reproducible enterprise pipelines."});let d=await ve(e,["src/main/java/Application.java","src/main/kotlin/Application.kt"])||await se(e,{suffix:"Application.java",under:["src/main/java"]})||await se(e,{suffix:"Application.kt",under:["src/main/kotlin"]});T(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(t,{id:"adapter-go-module-integrity",label:"Go adapter module integrity",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?"go.sum detected for deterministic module verification.":"go.sum missing; module integrity baseline is incomplete.",recommendation:l?void 0:"Generate and commit go.sum in the repository baseline."});let d=await ve(e,["cmd/server/main.go","cmd/api/main.go","main.go"]);T(t,{id:"adapter-go-boot-entrypoint",label:"Go adapter boot entrypoint",status:d?"pass":"warn",severity:"warn",scope:"project-scoped",reason:d?"Go application entrypoint markers detected.":"No Go application entrypoint markers detected.",recommendation:d?void 0:"Expose a Go main package entrypoint such as cmd/server/main.go."});return}if(i==="dotnet"){let l=await ve(e,["Program.cs","src/Program.cs"])||await se(e,{name:"Program.cs"});T(t,{id:"adapter-dotnet-boot-entrypoint",label:".NET adapter boot entrypoint",status:l?"pass":"warn",severity:"warn",scope:"project-scoped",reason:l?".NET application entrypoint markers detected.":"No .NET application entrypoint markers detected.",recommendation:l?void 0:"Expose Program.cs at the project root or under src for deterministic boot probes."});return}let s={rust:{dependencyMarkers:["Cargo.lock"],entrypointMarkers:["src/main.rs","src/lib.rs"],dependencyLabel:"Rust lockfile integrity",entrypointLabel:"Rust crate entrypoint"},php:{dependencyMarkers:["composer.lock"],entrypointMarkers:["public/index.php","artisan","index.php"],dependencyLabel:"Composer lockfile integrity",entrypointLabel:"PHP application entrypoint"},ruby:{dependencyMarkers:["Gemfile.lock"],entrypointMarkers:["config.ru","app.rb","config/application.rb"],dependencyLabel:"Bundler lockfile integrity",entrypointLabel:"Ruby application entrypoint"},elixir:{dependencyMarkers:["mix.lock"],entrypointMarkers:["lib/application.ex","lib/*/application.ex"],dependencyLabel:"Mix lockfile integrity",entrypointLabel:"Elixir application entrypoint"},clojure:{dependencyMarkers:["deps.edn","project.clj"],entrypointMarkers:["src/core.clj","src/main.clj"],dependencyLabel:"Clojure dependency contract",entrypointLabel:"Clojure application entrypoint"},deno:{dependencyMarkers:["deno.lock","deno.json","deno.jsonc"],entrypointMarkers:["main.ts","mod.ts","src/main.ts","src/mod.ts"],dependencyLabel:"Deno dependency contract",entrypointLabel:"Deno application entrypoint"},bun:{dependencyMarkers:["bun.lock","bun.lockb"],entrypointMarkers:["src/index.ts","src/main.ts","index.ts"],dependencyLabel:"Bun lockfile integrity",entrypointLabel:"Bun application entrypoint"},scala:{dependencyMarkers:["build.sbt","project/build.properties"],entrypointMarkers:["src/main/scala/Main.scala","src/main/scala/Application.scala"],dependencyLabel:"Scala build contract",entrypointLabel:"Scala application entrypoint"},kotlin:{dependencyMarkers:["build.gradle.kts","gradle.lockfile"],entrypointMarkers:["src/main/kotlin/Application.kt","src/main/kotlin/Main.kt"],dependencyLabel:"Kotlin build contract",entrypointLabel:"Kotlin application entrypoint"},c:{dependencyMarkers:["CMakeLists.txt","meson.build","Makefile"],entrypointMarkers:["src/main.c","main.c"],dependencyLabel:"C build contract",entrypointLabel:"C application entrypoint"},cpp:{dependencyMarkers:["CMakeLists.txt","meson.build","Makefile"],entrypointMarkers:["src/main.cpp","main.cpp","src/main.cc","main.cc"],dependencyLabel:"C++ build contract",entrypointLabel:"C++ application entrypoint"}}[i];if(!s)return;let r=(i==="c"||i==="cpp")&&e$2(e),c=r||await ve(e,s.dependencyMarkers);T(t,{id:`adapter-${i}-dependency-contract`,label:s.dependencyLabel,status:c?"pass":"warn",severity:"warn",scope:"project-scoped",reason:c?r?`${s.dependencyLabel} detected across multiple native workspace components.`:`${s.dependencyLabel} detected.`:`${s.dependencyLabel} is missing.`,recommendation:c?void 0:`Add a runtime-native dependency/build contract: ${s.dependencyMarkers.join(", ")}.`,issueClass:"dependency",operationalImpact:"ci-risk"});let a=await ve(e,s.entrypointMarkers);!a&&i==="elixir"&&(a=await se(e,{name:"application.ex",under:["lib"]})),!a&&i==="scala"&&(a=await se(e,{name:"Main.scala",under:["src/main/scala"]})||await se(e,{name:"Application.scala",under:["src/main/scala"]})),!a&&i==="kotlin"&&(a=await se(e,{name:"Application.kt",under:["src/main/kotlin"]})||await se(e,{name:"Main.kt",under:["src/main/kotlin"]})),T(t,{id:`adapter-${i}-boot-entrypoint`,label:s.entrypointLabel,status:a?"pass":"warn",severity:"warn",scope:"project-scoped",reason:a?`${s.entrypointLabel} detected.`:`${s.entrypointLabel} is not explicitly declared.`,recommendation:a?void 0:`Expose a conventional entrypoint or declare a custom Doctor adapter for this ${i} project.`,issueClass:"runtime",operationalImpact:"runtime-risk"});}async function es(e,t){let i=[u.join(e,".workspai","doctor.adapters.json"),u.join(e,".rapidkit","doctor.adapters.json"),u.join(e,"doctor.adapters.json")];for(let n of i)if(await m.pathExists(n))try{let o=await m.readJSON(n),s=Array.isArray(o?.checks)?o.checks:[];for(let r=0;r<s.length;r+=1){let c=s[r]||{},a=Array.isArray(c.runtimes)?c.runtimes:[];if(a.length>0&&!a.includes(t.runtimeFamily||"unknown"))continue;let l=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`adapter-check-${r+1}`,d=typeof c.label=="string"&&c.label.trim().length>0?c.label.trim():l,p=c.severity||"warn",y=Array.isArray(c.anyOfPaths)?c.anyOfPaths.filter(Boolean):[],h=Array.isArray(c.allOfPaths)?c.allOfPaths.filter(Boolean):[],k=y.length===0;for(let j of y)if(await m.pathExists(u.join(e,j))){k=true;break}let v=true;for(let j of h)if(!await m.pathExists(u.join(e,j))){v=false;break}let b=k&&v;T(t,{id:l,label:d,status:b?"pass":p==="error"?"fail":"warn",severity:p,scope:"project-scoped",reason:b?c.passReason||"Custom adapter contract satisfied.":c.failReason||`Custom adapter check failed from ${u.basename(n)}.`,recommendation:c.recommendation});}}catch{T(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 Y(e,t){if(!(t.projectKind==="backend"||t.projectKind==="generic"))return;let n=await ve(e,[".env",".env.example",".env.sample",".env.template",".env.public","config","docs/env.md","ENVIRONMENT.md"]);T(t,{id:"config-surface",label:"Configuration contract surface",status:n?"pass":"warn",severity:"warn",scope:"project-scoped",reason:n?"Configuration contract artifacts or documentation detected.":"No explicit configuration contract artifacts detected.",recommendation:n?void 0:"Add a secret-free environment example or explicit config contract documentation for deterministic setup."});let o={python:["alembic.ini","migrations","versions"],node:["prisma/schema.prisma","migrations","typeorm.config.ts","typeorm.config.js"],bun:["prisma/schema.prisma","migrations","typeorm.config.ts","typeorm.config.js"],go:["migrations","db/migrations"],java:["src/main/resources/db/migration","src/main/resources/liquibase"],rust:["migrations","sqlx-data.json"],elixir:["priv/repo/migrations"],clojure:["resources/migrations","migrations"],deno:["migrations"],php:["database/migrations","migrations"],ruby:["db/migrate"],dotnet:["Migrations","Data/Migrations"],scala:["src/main/resources/db/migration","conf/evolutions"],kotlin:["src/main/resources/db/migration","src/main/resources/liquibase"],c:["migrations","db/migrations"],cpp:["migrations","db/migrations"],unknown:["migrations"]},s=t.runtimeFamily||"unknown",r=o[s]||o.unknown,c=false;for(let h of r)if(await m.pathExists(u.join(e,h))){c=true;break}let a=await _i(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(t,{id:"migration-surface",label:"Migration/readiness surface",status:c||!l?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:l?"applicable":"not-applicable",reason:c?"Migration or schema evolution markers detected.":l?"No migration markers detected for this backend runtime.":"No relational persistence or schema-migration intent was detected; a migration surface is not currently applicable.",recommendation:c||!l?void 0:"Add migration tooling baseline (migrations dir or runtime-native migration config)."});let d=["src/health","src/healthcheck","src/main/resources/application.yml","src/main/resources/application.properties","app/health.py","routes/health.ts","routes/health.js"],p=false;for(let h of d)if(await m.pathExists(u.join(e,h))){p=true;break}let y=p||/\b(fastapi|flask|django|express|nestjs|spring[ -]?boot|axum|actix(?:-web)?|gin-gonic|gofiber|asp\.net|laravel|rails)\b/i.test(`${t.framework??""}
22
- ${a}`);T(t,{id:"runtime-health-surface",label:"Runtime health probe surface",status:p||!y?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:y?"applicable":"not-applicable",reason:p?"Health endpoint/config markers detected.":y?"No explicit runtime health endpoint markers detected.":"No HTTP service runtime intent was detected; an endpoint health surface is not currently applicable.",recommendation:p||!y?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await Qr(e,t);}async function ts(e,t,i,n){let o=await Qn({projectPath:e,detection:n,packageJsonData:i});for(let s of o)T(t,s);}async function Z(e,t,i){let n=await ni({projectPath:e,runtimeFamily:t.runtimeFamily,projectKind:t.projectKind,packageJsonData:i,hasTests:t.hasTests,vulnerabilities:t.vulnerabilities,dependencyAudit:t.dependencyAudit});for(let o of n)T(t,o);}async function H(e,t){let i=[u.join(e,".workspai","doctor.probes.json"),u.join(e,".rapidkit","doctor.probes.json"),u.join(e,"doctor.probes.json")];for(let n of i)if(await m.pathExists(n))try{let o=await m.readJSON(n),s=Array.isArray(o?.probes)?o.probes:[];for(let r=0;r<s.length;r+=1){let c=s[r]||{},a=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`custom-probe-${r+1}`,l=typeof c.label=="string"&&c.label.trim().length>0?c.label.trim():a,d=c.severity||"warn",p=Array.isArray(c.anyOfPaths)?c.anyOfPaths.filter(Boolean):[],y=Array.isArray(c.allOfPaths)?c.allOfPaths.filter(Boolean):[],h=p.length===0;for(let b of p)if(await m.pathExists(u.join(e,b))){h=true;break}let k=true;for(let b of y)if(!await m.pathExists(u.join(e,b))){k=false;break}let v=h&&k;T(t,{id:a,label:l,status:v?"pass":d==="error"?"fail":"warn",severity:d,scope:"project-scoped",reason:v?"Custom probe contract satisfied.":`Custom probe failed from ${u.basename(n)}.`,recommendation:c.recommendation});}}catch{T(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 es(e,t);}async function ns(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 R=u.join(e,"registry.json");if(await m.pathExists(R)){let A=await m.readJson(R);A.installed_modules&&(n.stats={modules:A.installed_modules.length});}}catch{}try{let{auditProjectModulePaths:R}=await import('./module-layout-NZ43RSC5.js'),A=await R(e);if(A.issues.length>0){for(let O of A.issues)n.issues.push(`${O.message} (${O.slug})`);n.fixCommands=n.fixCommands??[],n.fixCommands.push("npx workspai workspace contract verify --strict --json"),n.fixCommands.push("npx workspai add module <slug> # reinstall via Core-backed module install");}}catch{}let r=null;try{for(let R of u$1(e,"project.json")){if(!await m.pathExists(R))continue;r=await m.readJson(R);let A=typeof r?.name=="string"?r.name:typeof r?.slug=="string"?r.slug:void 0;A?.trim()&&(n.name=A.trim());let O=j$2(r)?void 0:r?.kit_name||r?.kit;O&&(n.kit=O);break}}catch{}try{let R=u.join(e,".git");if(await m.pathExists(R)){let{stdout:A}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false,env:a$a()});A&&(n.lastModified=A.trim());}else {let A=await m.stat(e),ce=Date.now()-A.mtime.getTime(),z=Math.floor(ce/(1e3*60*60*24));n.lastModified=z===0?"today":`${z} day${z>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"),h=u.join(e,"Cargo.toml"),k=u.join(e,"mix.exs"),v=u.join(e,"deps.edn"),b=u.join(e,"project.clj"),j=u.join(e,"deno.json"),x=u.join(e,"deno.jsonc"),D=u.join(e,"bun.lockb"),P=u.join(e,"bun.lock"),g=u.join(e,"composer.json"),S=u.join(e,"Gemfile"),w=await m.pathExists(c),E=await m.pathExists(a)||await m.pathExists(l$1),C=await m.pathExists(g),B=await m.pathExists(S),F=await m.pathExists(h),L=await m.pathExists(k),ie=await m.pathExists(v)||await m.pathExists(b),ae=await m.pathExists(y),q=await m.pathExists(j)||await m.pathExists(x),_=w&&(await m.pathExists(D)||await m.pathExists(P)||typeof r?.packageManager=="string"&&(r?.packageManager).toLowerCase().startsWith("bun@")),me=(await m.readdir(e).catch(()=>[])).some(R=>R.endsWith(".csproj")||R.endsWith(".sln")),oe=w||E||C||B||F||L||ie||ae||q||await m.pathExists(d)||await m.pathExists(p)||await m.pathExists(u.join(e,"build.gradle"))||await m.pathExists(u.join(e,"build.gradle.kts"))||me||await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),re=oe?[]:l(e),Be=!oe&&re.length>=2,Ge=m$1(e,r??null),V=Ge.runtime;if(Be)return ne(n,Ge),n.venvActive=true,n.depsInstalled=true,n.coreInstalled=false,T(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 H(e,n),n;if(Ge.runtime==="c"||Ge.runtime==="cpp")return ne(n,Ge),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true,n.modulesHealthy=true,n.missingModules=[],await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n;if(V==="go"){ne(n,m$1(e,r??null)),n.isGoProject=true,n.venvActive=true,n.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{n.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/");}let R=u.join(e,"go.sum");return await m.pathExists(R)?n.depsInstalled=true:(n.depsInstalled=false,n.issues.push("Go dependencies not downloaded (go.sum missing)"),n.fixCommands?.push(X(e,"go mod tidy"))),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="kotlin"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=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 O=R?b$5()?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies";n.fixCommands?.push(X(e,O));}let A=u.join(e,".env");return n.hasEnvFile=await m.pathExists(A),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="java"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=await m.pathExists(p),A=await m.pathExists(u.join(e,"build.gradle"))||await m.pathExists(u.join(e,"build.gradle.kts")),O=await m.pathExists(u.join(e,"mvnw"))||await m.pathExists(u.join(e,"mvnw.cmd")),ce=await m.pathExists(u.join(e,"gradlew"))||await m.pathExists(u.join(e,"gradlew.bat"));try{await execa("java",["-version"],{timeout:3e3,reject:false});}catch{n.issues.push("Java runtime not found \u2014 install JDK 21+ and ensure java is on PATH");}if(R){if(!O)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(A&&!ce)try{await execa("gradle",["--version"],{timeout:3e3,reject:false});}catch{n.issues.push("Gradle not found \u2014 install Gradle 8+ or add Gradle Wrapper");}let z=u.join(e,"target"),Ke=u.join(e,"build","libs"),Ae=u.join(e,".workspai","cache","java","m2"),I=u.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await m.pathExists(z)||await m.pathExists(Ke)||await m.pathExists(Ae)||await m.pathExists(I),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let Fe=R?O?b$5()?".\\mvnw.cmd -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"./mvnw -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"mvn -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":ce?b$5()?".\\gradlew.bat --project-cache-dir .workspai/cache/java/gradle dependencies":"./gradlew --project-cache-dir .workspai/cache/java/gradle dependencies":"gradle --project-cache-dir .workspai/cache/java/gradle dependencies";n.fixCommands?.push(X(e,Fe));}let K=u.join(e,".env");n.hasEnvFile=await m.pathExists(K);let le=u.join(e,"src","main","resources","application.yml");if(await m.pathExists(le))try{let Fe=await m.readFile(le,"utf-8");/include:\s*[^\n]*health/i.test(Fe)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(Fe)||(n.issues.push("Actuator health endpoint exposure is not clearly configured in application.yml"),n.fixCommands?.push(X(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 U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="rust"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"Cargo.lock"),A=u.join(e,"target");n.depsInstalled=await m.pathExists(R)||await m.pathExists(A),n.depsInstalled||(n.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),n.fixCommands?.push(X(e,"cargo fetch")));let O=u.join(e,".env");return n.hasEnvFile=await m.pathExists(O),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="elixir"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"mix.lock"),A=u.join(e,"deps");n.depsInstalled=await m.pathExists(R)||await m.pathExists(A),n.depsInstalled||(n.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),n.fixCommands?.push(X(e,"mix deps.get")));let O=u.join(e,".env");return n.hasEnvFile=await m.pathExists(O),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="clojure"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,".cpcache"),A=u.join(e,"target"),O=await m.pathExists(v)||await m.pathExists(b);return n.depsInstalled=await m.pathExists(R)||await m.pathExists(A)||O,n.depsInstalled||(n.issues.push("Clojure dependency cache not initialized"),n.fixCommands?.push(X(e,await m.pathExists(v)?"clojure -P":"lein deps"))),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="scala"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"target");n.depsInstalled=await m.pathExists(R),n.depsInstalled||(n.issues.push("Scala build artifacts missing (run dependency/build warmup)"),n.fixCommands?.push(X(e,"sbt compile")));let A=u.join(e,".env");return n.hasEnvFile=await m.pathExists(A),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="deno"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true;let R=u.join(e,".env");return n.hasEnvFile=await m.pathExists(R),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="node"||V==="bun"){let R=null;try{R=await m.readJson(c);}catch{R=null;}let A={...R?.dependencies??{},...R?.devDependencies??{}},O=R?.scripts??{},ce=typeof r?.kit_name=="string"?r.kit_name.toLowerCase():typeof r?.kit=="string"?r.kit.toLowerCase():"",z=d$2(e,r),Ke=Mr({dependencies:A,scripts:O,kitName:ce});if(_)lt(n,"Bun","high");else {let I=m$1(e,r??null);I.key==="nestjs"||I.key==="express"||I.key==="fastify"||I.key==="koa"||I.key==="tauri"||I.key==="electron"||I.key==="vscode-extension"?ne(n,I):z.key!=="unknown"?Nr(n,z):I.key!=="unknown"&&I.key!=="node"?ne(n,I):lt(n,Ke.framework,Ke.confidence);}n.venvActive=true;let Ae=u.join(e,"node_modules");if(await m.pathExists(Ae))try{let K=(await m.readdir(Ae)).filter(le=>!le.startsWith(".")&&!le.startsWith("_"));n.depsInstalled=K.length>0;}catch{n.depsInstalled=false;}if(!n.depsInstalled){n.issues.push("Dependencies not installed (node_modules empty or missing)");let I=typeof R?.packageManager=="string"?R.packageManager.split("@")[0]:void 0,K=_?"bun install":I==="pnpm"||await m.pathExists(u.join(e,"pnpm-lock.yaml"))?"pnpm install":I==="yarn"||await m.pathExists(u.join(e,"yarn.lock"))?"yarn install":"npm install";n.fixCommands?.push(X(e,K));}if(n.coreInstalled=false,n.projectKind==="frontend"){let I=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(I.map(le=>m.pathExists(u.join(e,le))))).some(Boolean))n.hasEnvFile=true;else {let le=u.join(e,".env.example");await m.pathExists(le)&&(n.hasEnvFile=false);}}else {let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);}if(n.projectKind==="frontend")n.modulesHealthy=await Jt(e),n.missingModules=[];else {let I=u.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(I))try{let K=await m.readdir(I);n.modulesHealthy=K.length>0;}catch{n.modulesHealthy=false;}}return await U(e,n,R),await Z(e,n,R),n.projectKind==="frontend"?await ts(e,n,R,z.key!=="unknown"?z:d$2(e,r)):await Y(e,n),await H(e,n),n}if(V==="python"){let R=await Tr(e,r);lt(n,R.framework,R.confidence);let A="fastapi";n.framework==="Django"?A="django":n.framework==="Flask"?A="flask":n.framework==="Python"&&(A="");let O=await Ot(a),ce=/\[tool\.poetry\]/.test(O),z=await Rr(e),Ke=z?"project-script":ce?"poetry":await m.pathExists(u.join(e,"uv.lock"))?"uv":"venv",Ae=Dr({projectPath:e,manager:Ke,...z?{projectScript:z}:{}}),I=await Zr(e,A,ce);n.venvActive=!!I.environmentPath,n.depsInstalled=I.dependenciesInstalled,n.coreInstalled=!!I.coreVersion,n.coreVersion=I.coreVersion;let K=O.match(/^\s*requires-python\s*=\s*["']([^"']+)["']/m)?.[1];if(K){let fe=await Sr(I.interpreter),we=fe?gi(fe,K):{version:"unknown",satisfied:null};if(n.pythonRequirement={specifier:K,...fe?{detectedVersion:fe}:{},satisfied:we.satisfied},we.satisfied===false){let yt=`Python ${we.version} does not satisfy requires-python ${K}`;n.issues.push(yt),T(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"fail",severity:"error",scope:"project-scoped",reason:yt,recommendation:z?`Install a compatible Python interpreter, then run the repository-authored ${z} setup command.`:"Install a Python interpreter satisfying requires-python, then materialize the project environment.",issueClass:"runtime",operationalImpact:"release-risk"});}else we.satisfied===null?T(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"warn",severity:"warn",scope:"project-scoped",reason:fe?`Python ${fe} could not be evaluated against requires-python ${K}.`:`No executable Python version could be verified against requires-python ${K}.`,recommendation:"Verify the selected project interpreter against the complete requires-python constraint before setup or release.",issueClass:"runtime",operationalImpact:"ci-risk"}):T(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"pass",severity:"info",scope:"project-scoped",reason:`Python ${we.version} satisfies requires-python ${K}.`,issueClass:"runtime",operationalImpact:"none"});}I.environmentPath?I.interpreter?n.depsInstalled||(n.issues.push("Dependencies not installed"),n.fixCommands?.push(Ae)):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Ae));let le=u.join(e,".env");n.hasEnvFile=await m.pathExists(le);let Fe=u.join(e,"src"),gt=u.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(Fe)){let fe=u.join(Fe,"__init__.py");await m.pathExists(fe)||(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await m.pathExists(gt))try{let fe=await ss(gt);for(let we of fe){let yt=u.join(gt,we,"__init__.py");await m.pathExists(yt)||(n.modulesHealthy=false,n.missingModules.push(`modules/${we}/__init__.py`));}}catch{}return !n.modulesHealthy&&n.missingModules.length>0&&n.issues.push(`Missing module init files: ${n.missingModules.join(", ")}`),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="php"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"vendor");n.depsInstalled=await m.pathExists(R),n.depsInstalled||(n.issues.push("PHP dependencies not installed (vendor missing)"),n.fixCommands?.push(X(e,"composer install")));let A=u.join(e,".env");return n.hasEnvFile=await m.pathExists(A),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="ruby"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=await m.pathExists(u.join(e,"Gemfile.lock")),A=await m.pathExists(u.join(e,"vendor","bundle"));n.depsInstalled=R||A,n.depsInstalled||(n.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),n.fixCommands?.push(X(e,"bundle install")));let O=u.join(e,".env");return n.hasEnvFile=await m.pathExists(O),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="dotnet"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"obj"),A=u.join(e,"src","obj"),O=u.join(e,"packages.lock.json");n.depsInstalled=await m.pathExists(R)||await m.pathExists(A)||await m.pathExists(O),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(X(e,"dotnet restore")));let ce=u.join(e,".env");return n.hasEnvFile=await m.pathExists(ce),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build"))){let R=await se(e,{suffix:".cpp",under:["src","."]});return lt(n,R?"C++":"C","medium"),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true,await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}return lt(n,"Unknown","low"),T(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 U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}function Bi(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 is(e){let t=l(e);if(t.length>0)return t;let i=async a=>m.pathExists(u.join(e,a)),n=await m.readdir(e).catch(()=>[]),o=[],s=(a,l)=>{l&&!o.includes(a)&&o.push(a);},r=await i("package.json");return s("bun",r&&(await i("bun.lock")||await i("bun.lockb"))),s("deno",await i("deno.json")||await i("deno.jsonc")),s("node",r&&!o.includes("bun")),s("python",await i("pyproject.toml")||await i("requirements.txt")),s("go",await i("go.mod")),s("kotlin",await i("build.gradle.kts")&&await se(e,{suffix:".kt",under:["src"]})),s("java",await i("pom.xml")||await i("build.gradle")||await i("build.gradle.kts")&&!o.includes("kotlin")),s("rust",await i("Cargo.toml")),s("elixir",await i("mix.exs")),s("clojure",await i("deps.edn")||await i("project.clj")),s("scala",await i("build.sbt")),s("php",await i("composer.json")),s("ruby",await i("Gemfile")),s("dotnet",n.some(a=>a.endsWith(".csproj"))||await i("global.json")),(await i("CMakeLists.txt")||await i("meson.build"))&&(s("cpp",await se(e,{suffix:".cpp",under:["src","."]})),s("c",await se(e,{suffix:".c",under:["src","."]})),!o.includes("c")&&!o.includes("cpp")&&s("cpp",true)),o.length>0?o:["unknown"]}async function os(e,t){if(t.projectKind==="extension")return "plugin";if(t.projectKind==="platform")return (await m.readJson(u.join(e,"package.json")).catch(()=>null))?.workspaces?"monorepo":"platform";if(t.projectKind==="library")return "library";if(t.projectKind==="frontend"||t.projectKind==="desktop"||t.projectKind==="fullstack")return "application";let i=await m.readJson(u.join(e,"package.json")).catch(()=>null),n=!!(i&&(Array.isArray(i.workspaces)||i.workspaces&&typeof i.workspaces=="object")),o=await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),s=await m.pathExists(u.join(e,"include")),r=(await Promise.all(["bindings","src/proto","proto","python","ruby","php","csharp","objective-c"].map(d=>m.pathExists(u.join(e,d))))).some(Boolean);if((t.runtimeFamilies?.length??0)>=3||(t.runtimeFamilies?.length??0)>=2&&o&&r)return "platform";if(n)return "monorepo";let c=i?.scripts&&typeof i.scripts=="object"?i.scripts:{},a=!!(i?.exports||i?.types||i?.main),l=!!(c.start||c.dev||c.serve);return a&&!l?/sdk|client/i.test(String(i?.name??t.name))?"sdk":"library":o&&s?"library":t.projectKind==="backend"?"service":"unknown"}function rs(e){let t=e.probes??[],i=t.map((r,c)=>r.id==="config-surface"?c:-1).filter(r=>r>=0);t.some(r=>r.id==="surface-env-contract")&&(e.probes=t.filter((r,c)=>!i.includes(c)));let n=new Set(["library","sdk","platform","plugin","monorepo"]);if(!e.projectArchetype||!n.has(e.projectArchetype))return;let o=new Set;e.probes=(e.probes??[]).map(r=>r.id==="migration-surface"||r.id==="runtime-health-surface"||r.id==="surface-kubernetes-readiness"||r.id.endsWith("-boot-entrypoint")||r.id==="runtime-security-tooling"&&e.probes?.some(a=>a.id==="surface-security-hygiene")||r.id==="surface-env-contract"&&r.status!=="pass"?(r.repairCapability?.command&&o.add(r.repairCapability.command),{...r,status:"pass",severity:"info",applicability:"not-applicable",reason:`${r.label} is not required for the detected ${e.projectArchetype} archetype.`,recommendation:void 0,repairCapability:void 0,repairIntent:void 0}):r);let s=new Set((e.probes??[]).map(r=>r.repairCapability?.id).filter(r=>!!r));e.repairCapabilities=(e.repairCapabilities??[]).filter(r=>s.has(r.id)),e.fixCommands=(e.fixCommands??[]).filter(r=>!o.has(r));}async function Nt(e,t={}){let i=Bi(await ns(e,t));delete i._freshDependencyAudit,ys(i),i.runtimeFamilies=await is(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&&T(i,{id:"runtime-composition",label:"Composite runtime coverage",status:"warn",severity:"warn",scope:"project-scoped",reason:`Multiple runtime families share one project boundary: ${i.runtimeFamilies.join(", ")}. Primary adapters evaluated ${i.runtimeFamily??"unknown"} only.`,recommendation:"Declare nested project boundaries or add doctor.adapters.json checks for every secondary runtime.",issueClass:"runtime",operationalImpact:"ci-risk"});let n=await b$3(e);if(n==="backend"||n==="service"||n==="worker"?i.projectKind="backend":n==="frontend"||n==="desktop"||n==="extension"||n==="platform"||n==="library"?i.projectKind=n:i.projectKind||(i.projectKind="generic"),i.projectArchetype=await os(e,i),i.projectArchetype==="platform"){let o=i.probes?.find(s=>s.id==="runtime-composition");o&&(o.reason=`Cross-language platform boundary detected: ${i.runtimeFamilies.join(", ")}. The primary ${i.runtimeFamily??"unknown"} adapter is combined with portable cross-runtime evidence.`,o.recommendation="Add explicit adapters only for runtime-specific checks that are not represented by the portable evidence contract.");}return rs(i),Ft(i),i}async function ss(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 pt(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 as(e,t){if(t.has(e)||a$b(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 cs(e,t,i){let n=new Set,o=[{dir:e,depth:0}];for(;o.length>0;){let s=o.shift();if(!s)break;try{let r=await m.readdir(s.dir);for(let c of r){if(as(c,i))continue;let a=u.join(s.dir,c),l;try{l=await m.stat(a);}catch{continue}if(l.isDirectory()){if(await pt(a)){n.add(a);continue}s.depth<t&&o.push({dir:a,depth:s.depth+1});}}}catch{continue}}return Array.from(n)}async function ut(e){let t=a$1(e);if(t)return t;let i=u.resolve(e),n=u.parse(i).root;for(;;){if(await ps(i))return i;if(i===n)return null;i=u.dirname(i);}}async function ls(e){let t=u.resolve(e),i=await ut(t),n=i??u.parse(t).root;for(;;){if(await pt(t)||await ds(t)&&(!i||t!==i))return t;if(t===n)break;t=u.dirname(t);}return null}function ki(e){let t=u.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function ds(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 ps(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 un(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 k=d.coverage.passingObservations,v=d.coverage.blockingFindings,b=d.coverage.advisoryFindings+d.coverage.unknownFindings+d.coverage.contradictionCount;n.passed+=k,n.warnings+=b,n.errors+=v,n.total+=k+b+v;return}let p=l.probes??[];if(p.length>0){for(let k of p)n.total+=1,k.status==="pass"?n.passed+=1:k.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=ur(l),h=l.isGoProject?l.issues.length===0&&l.depsInstalled:l.issues.length===0&&l.venvActive&&l.depsInstalled;l.issues.length>0||!h?n.errors+=1:y>0?n.warnings+=1:n.passed+=1;});let o=i.passed+n.passed,s=i.warnings+n.warnings,r=i.errors+n.errors,c=Se(t,e),a=i.total+n.total;return {total:a,passed:o,warnings:s,errors:r,verdict:r>0?"blocked":s>0?"attention":"passed",presentation:{policy:"doctor-multi-axis-v1",diagnosticPassRatePercent:a>0?Math.round(o/a*100):null,blockingFindings:c.blockingCauses+c.systemErrors,advisoryFindings:c.advisoryFindings,unknownFindings:c.unknownFindings,contradictionFindings:c.contradictionFindings,notApplicableChecks:c.notApplicableChecks,label:"diagnostic-pass-rate"},components:{host:i,projects:n}}}function Q(e){let t=(e.probes??[]).filter(l=>l.applicability!=="not-applicable"),i=t.filter(l=>l.status==="pass").length,n=t.filter(l=>l.status==="warn").length,o=t.filter(l=>l.status==="fail").length,s=e.diagnosis?.coverage.blockingFindings??o+e.issues.length,r=e.diagnosis?e.diagnosis.coverage.advisoryFindings:n,c=e.diagnosis?.coverage.unknownFindings??0,a=e.diagnosis?.coverage.contradictionCount??0;return {total:t.length,passed:i,warnings:n,failed:o,blockingFindings:s,advisoryFindings:r,unknownFindings:c,contradictionFindings:a,verdict:s>0?"blocked":r+c+a>0?"attention":"passed"}}function Se(e,t=[]){let i=e.map(o=>o.diagnosis).filter(Boolean),n=e.map(Q);return {projectsScanned:e.length,affectedProjects:n.filter(o=>o.verdict!=="passed").length,projectsBlocked:n.filter(o=>o.blockingFindings>0).length,projectsNeedingAttention:n.filter(o=>o.blockingFindings===0&&o.verdict==="attention").length,blockingCauses:i.reduce((o,s)=>o+(s?.coverage.blockingFindings??0),0),advisoryFindings:i.reduce((o,s)=>o+(s?.coverage.advisoryFindings??0),0),unknownFindings:i.reduce((o,s)=>o+(s?.coverage.unknownFindings??0),0),contradictionFindings:i.reduce((o,s)=>o+(s?.coverage.contradictionCount??0),0),repairableFindings:i.reduce((o,s)=>o+(s?.coverage.repairableFindings??0),0),manualFindings:i.reduce((o,s)=>o+(s?.coverage.manualFindings??0),0),unsupportedFindings:i.reduce((o,s)=>o+(s?.coverage.unsupportedFindings??0),0),dependencyAdvisorySubjects:e.reduce((o,s)=>o+(s.dependencyAudit?.subjects.length??0),0),dependencyVulnerabilityFindings:e.reduce((o,s)=>o+(s.dependencyAudit?.findingCount??0),0),notApplicableChecks:e.reduce((o,s)=>o+(s.probes??[]).filter(r=>r.applicability==="not-applicable").length,0)+t.filter(o=>o.applicability==="not-applicable").length,systemErrors:t.filter(o=>o.status==="error").length}}function us(e){let t=Q(e);e.probeSummary=t,e.verdict=t.verdict;}function Gi(e,t,i={}){let n=[];for(let s of e)n.push({id:s.id,label:s.label,status:s.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:s.result.details||s.result.message});let o=[...t].sort((s,r)=>{let c=`${s.path||""}|${s.name||""}`.toLowerCase(),a=`${r.path||""}|${r.name||""}`.toLowerCase();return c.localeCompare(a)});for(let s of o){if(us(s),s.diagnosis){for(let r of (s.probes??[]).filter(c=>c.status==="pass"))n.push({id:`project:${s.name}:probe:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:"ok",scope:"project-scoped",policyRuleId:`project-probe-${r.id}`,reason:r.reason});for(let r of s.diagnosis.findings)n.push({id:`project:${s.name}:diagnosis:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:r.status==="blocking"?"error":"warn",scope:"project-scoped",policyRuleId:`project-diagnosis-${r.issueClass}`,reason:r.symptom});}else {for(let r of s.probes??[])n.push({id:`project:${s.name}:probe:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:r.status==="pass"?"ok":r.status==="warn"?"warn":"error",scope:"project-scoped",policyRuleId:`project-probe-${r.id}`,reason:r.reason});for(let[r,c]of s.issues.entries())n.push({id:`project:${s.name}:legacy:${r+1}`,label:`${s.name} \xB7 Runtime issue`,status:"error",scope:"project-scoped",policyRuleId:"project-runtime-issue",reason:c});}(s.probes?.length??0)===0&&s.issues.length===0&&n.push({id:`project:${s.name}`,label:`Project ${s.name}`,status:"ok",scope:"project-scoped",policyRuleId:"project-checks-passed",reason:"Project checks passed"});}if(i.includeWorkspaceAggregateRules){let s=t.reduce((a,l)=>a+Q(l).blockingFindings,0),r=t.reduce((a,l)=>a+Q(l).advisoryFindings,0),c=e.filter(a=>a.result.status==="error").length;n.push({id:"workspace:projects-discovered",label:"Workspace projects discovered",status:t.length>0?"ok":"warn",scope:"workspace-aggregate",policyRuleId:"workspace-project-discovery",reason:t.length>0?`${t.length} project(s) discovered for workspace analysis.`:"No projects discovered for workspace analysis."}),n.push({id:"workspace:system-error-gate",label:"Workspace system error gate",status:c>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-system-error-gate",reason:c>0?`${c} system requirement gate(s) failed.`:"All system requirement gates passed."}),n.push({id:"workspace:blocking-issues-gate",label:"Workspace blocking issues gate",status:s>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:s>0?`${s} blocking project issue(s) detected.`:"No blocking project issues detected."}),n.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:r>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:r>0?`${r} advisory warning(s) detected.`:"No advisory warnings detected."});}return n}async function tn(e$1,t$2=true,i=It({}),n=false){let o=u.basename(e$1),s=await a$2(e$1);if(typeof s?.name=="string"&&s.name.trim().length>0)o=s.name;else try{for(let b of t(e$1,"workspace.json")){if(!await m.pathExists(b))continue;let j=await m.readJSON(b);o=j.workspace_name||j.name||o;break}}catch{}let[r,c]=await Promise.all([pn(e$1),Or(e$1)]),a={workspacePath:e$1,workspaceName:o,python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,projects:[],policyProfile:i};e.debug(`Workspace scan found ${c.length} project(s)`);let l=await _r(e$1,c),d=u.join(e$1,t$1.doctorWorkspaceCache),p=t$2&&!n?await Br(d,l):null;if(p){a.projects=p.projects;for(let b of a.projects)Bi(b),Ft(b,p.generatedAt);a.projectScanCached=true,e.debug(`Workspace project health cache hit: ${d}`);}else try{let b=new Date().toISOString(),j=await Kr(c,x=>Nt(x,{allowNonRapidkit:true,freshAudit:n}));for(let x of j)Ft(x,b);a.projects=j,a.projectScanCached=false,await Gr(e$1,{schemaVersion:Ai,signature:l,generatedAt:b,projects:j}),e.debug(`Workspace project health cache refreshed: ${d}`);}catch(b){e.debug(`Failed to scan workspace projects: ${b}`);}a.projectScanSignature=l,a.projectScanCachePath=d;let y=Ei({python:a.python,poetry:a.poetry,pipx:a.pipx,go:a.go,rapidkitCore:a.rapidkitCore},a.projects);a.python=y.python,a.poetry=y.poetry,a.pipx=y.pipx,a.go=y.go,a.rapidkitCore=y.rapidkitCore,await Promise.all(a.projects.map(async b=>{b.graphDiagnosis=await en({workspacePath:e$1,projectPath:b.path,projectName:b.name,probes:Fi(b),issues:b.issues}),$i(b);}));let h=[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore];if(a.healthScore=un(h,a.projects),a.scoreBreakdown=Gi([{id:"system-python",label:"Python",result:a.python},{id:"system-poetry",label:"Poetry",result:a.poetry},{id:"system-pipx",label:"pipx",result:a.pipx},{id:"system-go",label:"Go",result:a.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:a.rapidkitCore}],a.projects,{includeWorkspaceAggregateRules:true}),a.scopeProvenance=Ti(a.scoreBreakdown),a.evidenceFreshness=ln(a.projects,new Date().toISOString()),a.rapidkitCore.status==="ok"){let b=a.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);b&&(a.coreVersion=b[1]);}let k=await f$1(e$1,rn),v=k?await Ni(k,"workspace"):null;return a.driftDelta=Cr(v,a),a.evidencePath=await Wr(e$1,a,p?d:null),a.receiptPath=await Hi(e$1,Wi({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}function vi(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??Q(e).verdict,probeSummary:e.probeSummary??Q(e),repairCapabilities:e.repairCapabilities,commandCapabilities:e.commandCapabilities,graphDiagnosis:e.graphDiagnosis,diagnosis:e.diagnosis}}function Ki(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 ms(e,t){let i=e||t.projectPath,n=t$1.doctorProject,o=Ki(e,t.projectPath),s=u.join(i,n);try{let r=[...t.project.issues,...(t.project.probes??[]).filter(d=>d.status==="fail").map(d=>d.reason)].filter(d=>typeof d=="string"&&d.trim().length>0).slice(0,12),c=Q(t.project),a=Se([t.project],[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore]),l=f$2({schemaVersion:b$4,evidenceType:"project",contract:Ue(),policyProfile:t.policyProfile,workspacePath:e||null,projectPath:t.projectPath,projectName:t.projectName,healthScore:t.healthScore,evidenceFreshness:t.evidenceFreshness,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore},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:mt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:r,runId:e$1()});return d(l),e?await h(e,n,[{relativePath:n,payload:l},{relativePath:o,payload:l}]):await g(i,n,l),e&&u.resolve(e)!==u.resolve(t.projectPath)&&await g(t.projectPath,n,l),s}catch(r){throw r}}function Wi(e){let t=new Date().toISOString(),i=e.freshness??ln(e.projects,t),n=Se(e.projects,e.systemChecks),o=e.projects.map(l=>{let d=Q(l);return {name:l.name,path:l.path,runtimeFamily:l.runtimeFamily??"unknown",framework:l.framework??"Unknown",verdict:d.verdict,blockingCauses:l.diagnosis?.coverage.blockingFindings??d.blockingFindings,advisoryFindings:l.diagnosis?.coverage.advisoryFindings??d.advisoryFindings,unknownFindings:l.diagnosis?.coverage.unknownFindings??0}}).filter(l=>l.blockingCauses>0||l.advisoryFindings>0||l.unknownFindings>0),s$1=e.projects.flatMap(l=>(l.diagnosis?.findings??[]).filter(d=>d.status==="blocking").map(d=>({id:d.id,projectName:l.name,projectPath:l.path,issueClass:d.issueClass,symptom:d.symptom,repairDisposition:d.repair.disposition,...d.repair.capabilityId?{capabilityId:d.repair.capabilityId}:{}}))),r=e.projects.reduce((l,d)=>l+(d.diagnosis?.findings??[]).filter(p=>p.status==="blocking"&&(p.repair.disposition==="automatic"||p.repair.disposition==="approval-required")).length,0),c=e.healthScore?.verdict??(n.blockingCauses>0?"blocked":n.advisoryFindings+n.unknownFindings>0?"attention":"passed"),a=i.status!=="fresh"?{action:"refresh",reason:"Doctor evidence is stale or has unknown freshness.",commands:[`npx workspai doctor ${e.scopeKind} --fresh --json=summary`]}:n.blockingCauses>0&&r>0?{action:"repair",reason:"At least one blocking cause has a typed repair capability.",commands:[`npx workspai doctor ${e.scopeKind} --plan --json=summary`]}:n.blockingCauses>0?{action:"review",reason:"Blocking causes remain, but no automatic typed repair covers every cause.",commands:[`npx workspai doctor ${e.scopeKind} --json`]}:c==="attention"?{action:"review",reason:"No blocker remains; advisory or unknown findings need policy review.",commands:[`npx workspai doctor ${e.scopeKind} --json=summary`]}:{action:"verify",reason:"Doctor is healthy; canonical Workspace Intelligence verification is next.",commands:["npx workspai workspace intelligence run --strict --json"]};return {schemaVersion:s.doctorReceipt.schemaVersion,generatedAt:t,scope:{kind:e.scopeKind,root:e.scopeRoot,name:e.scopeName,workspacePath:e.workspacePath??null,projectPath:e.projectPath??null},verdict:c,counts:n,freshness:i,affectedProjects:o,blockers:s$1,next:a,artifacts:{evidence:e.evidencePath??null,receipt:u.join(e.scopeRoot,t$1.doctorReceipt)}}}async function Hi(e,t,i=[]){a$5(t,"contracts/workspace-intelligence/doctor-receipt.v1.json",`Doctor receipt ${e}`),await g(e,t$1.doctorReceipt,t);for(let n of i)u.resolve(n)!==u.resolve(e)&&await g(n,t$1.doctorReceipt,t);return u.join(e,t$1.doctorReceipt)}async function sn(e,t,i=[]){let n=u.join(e,t$1.doctorRemediationPlan);try{await g(e,t$1.doctorRemediationPlan,t);for(let o of i)u.resolve(o)!==u.resolve(e)&&await g(o,t$1.doctorRemediationPlan,t);return n}catch(o){if(o instanceof Error&&o.message.includes("violates contracts/"))throw o;return}}async function Ye(e,t,i=[]){let n=u.join(e,t$1.doctorFixResult);try{await g(e,t$1.doctorFixResult,t);for(let o of i)u.resolve(o)!==u.resolve(e)&&await g(o,t$1.doctorFixResult,t);return n}catch{return}}async function Ze(e,t,i){try{await j(e,g$1(t,i));}catch{}}async function wi(e,t=It({}),i=false){let n=await ut(e),o=await pn(n||e),s=await Nt(e,{allowNonRapidkit:true,freshAudit:i}),r=Ei(o,[s]);Ft(s),s.graphDiagnosis=await en({workspacePath:n||void 0,projectPath:e,projectName:s.name,probes:Fi(s),issues:s.issues}),$i(s);let c=un([r.python,r.poetry,r.pipx,r.go,r.rapidkitCore],[s]),a={workspacePath:n||void 0,projectPath:e,projectName:u.basename(e),python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,project:s,healthScore:c,policyProfile:t};a.scoreBreakdown=Gi([{id:"system-python",label:"Python",result:a.python},{id:"system-poetry",label:"Poetry",result:a.poetry},{id:"system-pipx",label:"pipx",result:a.pipx},{id:"system-go",label:"Go",result:a.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:a.rapidkitCore}],[a.project]),a.scopeProvenance=Ti(a.scoreBreakdown),a.evidenceFreshness=ln([a.project],new Date().toISOString());let l=await f$1(e,t$1.doctorProject),d=n?await f$1(n,Ki(n,e)):null,p=l??d,y=p?await Ni(p,"project"):null;a.driftDelta=Pr(y,a),a.evidencePath=await ms(n||void 0,a);let h=n||e;return a.receiptPath=await Hi(h,Wi({scopeKind:"project",scopeRoot:h,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]}),n&&u.resolve(n)!==u.resolve(e)?[e]:[]),a}function Oe(e,t){let i=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",n=e.status==="ok"?f.green:e.status==="warn"?f.yellow:f.red;console.log(`${i} ${f.bold(t)}: ${n(e.message)}`),e.paths&&e.paths.length>0&&e.paths.forEach(o=>{let s=o.version?f.cyan(` -> ${o.version}`):"";console.log(` ${f.cyan("\u2022")} ${f.gray(o.location)}: ${f.dim(o.path)}${s}`);}),e.details&&console.log(` ${f.gray(e.details)}`);}function St(e,t){let i=$t(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 fs(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 ji(e,t,i={}){let n=Q(e),o=n.verdict==="blocked"?"\u274C":n.verdict==="attention"?"\u26A0\uFE0F":"\u2705",s=n.verdict==="blocked"?f.red:n.verdict==="attention"?f.yellow:f.green;if(console.log(`
22
+ ${a}`);T(t,{id:"runtime-health-surface",label:"Runtime health probe surface",status:p||!y?"pass":"warn",severity:"warn",scope:"project-scoped",applicability:y?"applicable":"not-applicable",reason:p?"Health endpoint/config markers detected.":y?"No explicit runtime health endpoint markers detected.":"No HTTP service runtime intent was detected; an endpoint health surface is not currently applicable.",recommendation:p||!y?void 0:"Expose a deterministic health endpoint and keep it covered in verify pack."}),await Qr(e,t);}async function ts(e,t,i,n){let o=await Qn({projectPath:e,detection:n,packageJsonData:i});for(let s of o)T(t,s);}async function Z(e,t,i){let n=await ni({projectPath:e,runtimeFamily:t.runtimeFamily,projectKind:t.projectKind,packageJsonData:i,hasTests:t.hasTests,vulnerabilities:t.vulnerabilities,dependencyAudit:t.dependencyAudit});for(let o of n)T(t,o);}async function H(e,t){let i=[u.join(e,".workspai","doctor.probes.json"),u.join(e,".rapidkit","doctor.probes.json"),u.join(e,"doctor.probes.json")];for(let n of i)if(await m.pathExists(n))try{let o=await m.readJSON(n),s=Array.isArray(o?.probes)?o.probes:[];for(let r=0;r<s.length;r+=1){let c=s[r]||{},a=typeof c.id=="string"&&c.id.trim().length>0?c.id.trim():`custom-probe-${r+1}`,l=typeof c.label=="string"&&c.label.trim().length>0?c.label.trim():a,d=c.severity||"warn",p=Array.isArray(c.anyOfPaths)?c.anyOfPaths.filter(Boolean):[],y=Array.isArray(c.allOfPaths)?c.allOfPaths.filter(Boolean):[],h=p.length===0;for(let b of p)if(await m.pathExists(u.join(e,b))){h=true;break}let k=true;for(let b of y)if(!await m.pathExists(u.join(e,b))){k=false;break}let v=h&&k;T(t,{id:a,label:l,status:v?"pass":d==="error"?"fail":"warn",severity:d,scope:"project-scoped",reason:v?"Custom probe contract satisfied.":`Custom probe failed from ${u.basename(n)}.`,recommendation:c.recommendation});}}catch{T(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 es(e,t);}async function ns(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 R=u.join(e,"registry.json");if(await m.pathExists(R)){let A=await m.readJson(R);A.installed_modules&&(n.stats={modules:A.installed_modules.length});}}catch{}try{let{auditProjectModulePaths:R}=await import('./module-layout-NZ43RSC5.js'),A=await R(e);if(A.issues.length>0){for(let O of A.issues)n.issues.push(`${O.message} (${O.slug})`);n.fixCommands=n.fixCommands??[],n.fixCommands.push("npx workspai workspace contract verify --strict --json"),n.fixCommands.push("npx workspai add module <slug> # reinstall via Core-backed module install");}}catch{}let r=null;try{for(let R of u$1(e,"project.json")){if(!await m.pathExists(R))continue;r=await m.readJson(R);let A=typeof r?.name=="string"?r.name:typeof r?.slug=="string"?r.slug:void 0;A?.trim()&&(n.name=A.trim());let O=j$2(r)?void 0:r?.kit_name||r?.kit;O&&(n.kit=O);break}}catch{}try{let R=u.join(e,".git");if(await m.pathExists(R)){let{stdout:A}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false,env:a$a()});A&&(n.lastModified=A.trim());}else {let A=await m.stat(e),ce=Date.now()-A.mtime.getTime(),z=Math.floor(ce/(1e3*60*60*24));n.lastModified=z===0?"today":`${z} day${z>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"),h=u.join(e,"Cargo.toml"),k=u.join(e,"mix.exs"),v=u.join(e,"deps.edn"),b=u.join(e,"project.clj"),j=u.join(e,"deno.json"),x=u.join(e,"deno.jsonc"),D=u.join(e,"bun.lockb"),P=u.join(e,"bun.lock"),g=u.join(e,"composer.json"),S=u.join(e,"Gemfile"),w=await m.pathExists(c),E=await m.pathExists(a)||await m.pathExists(l$1),C=await m.pathExists(g),B=await m.pathExists(S),F=await m.pathExists(h),L=await m.pathExists(k),ie=await m.pathExists(v)||await m.pathExists(b),ae=await m.pathExists(y),q=await m.pathExists(j)||await m.pathExists(x),_=w&&(await m.pathExists(D)||await m.pathExists(P)||typeof r?.packageManager=="string"&&(r?.packageManager).toLowerCase().startsWith("bun@")),me=(await m.readdir(e).catch(()=>[])).some(R=>R.endsWith(".csproj")||R.endsWith(".sln")),oe=w||E||C||B||F||L||ie||ae||q||await m.pathExists(d)||await m.pathExists(p)||await m.pathExists(u.join(e,"build.gradle"))||await m.pathExists(u.join(e,"build.gradle.kts"))||me||await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),re=oe?[]:l(e),Be=!oe&&re.length>=2,Ge=m$1(e,r??null),V=Ge.runtime;if(Be)return ne(n,Ge),n.venvActive=true,n.depsInstalled=true,n.coreInstalled=false,T(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 H(e,n),n;if(Ge.runtime==="c"||Ge.runtime==="cpp")return ne(n,Ge),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true,n.modulesHealthy=true,n.missingModules=[],await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n;if(V==="go"){ne(n,m$1(e,r??null)),n.isGoProject=true,n.venvActive=true,n.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{n.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/");}let R=u.join(e,"go.sum");return await m.pathExists(R)?n.depsInstalled=true:(n.depsInstalled=false,n.issues.push("Go dependencies not downloaded (go.sum missing)"),n.fixCommands?.push(X(e,"go mod tidy"))),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="kotlin"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=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 O=R?b$5()?".\\gradlew.bat dependencies":"./gradlew dependencies":"gradle dependencies";n.fixCommands?.push(X(e,O));}let A=u.join(e,".env");return n.hasEnvFile=await m.pathExists(A),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="java"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=await m.pathExists(p),A=await m.pathExists(u.join(e,"build.gradle"))||await m.pathExists(u.join(e,"build.gradle.kts")),O=await m.pathExists(u.join(e,"mvnw"))||await m.pathExists(u.join(e,"mvnw.cmd")),ce=await m.pathExists(u.join(e,"gradlew"))||await m.pathExists(u.join(e,"gradlew.bat"));try{await execa("java",["-version"],{timeout:3e3,reject:false});}catch{n.issues.push("Java runtime not found \u2014 install JDK 21+ and ensure java is on PATH");}if(R){if(!O)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(A&&!ce)try{await execa("gradle",["--version"],{timeout:3e3,reject:false});}catch{n.issues.push("Gradle not found \u2014 install Gradle 8+ or add Gradle Wrapper");}let z=u.join(e,"target"),Ke=u.join(e,"build","libs"),Ae=u.join(e,".workspai","cache","java","m2"),I=u.join(e,".workspai","cache","java","gradle");if(n.depsInstalled=await m.pathExists(z)||await m.pathExists(Ke)||await m.pathExists(Ae)||await m.pathExists(I),!n.depsInstalled){n.issues.push("Java dependencies are not warmed or built yet");let Fe=R?O?b$5()?".\\mvnw.cmd -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"./mvnw -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":"mvn -B -DskipTests -Dmaven.repo.local=.workspai/cache/java/m2 dependency:go-offline":ce?b$5()?".\\gradlew.bat --project-cache-dir .workspai/cache/java/gradle dependencies":"./gradlew --project-cache-dir .workspai/cache/java/gradle dependencies":"gradle --project-cache-dir .workspai/cache/java/gradle dependencies";n.fixCommands?.push(X(e,Fe));}let K=u.join(e,".env");n.hasEnvFile=await m.pathExists(K);let le=u.join(e,"src","main","resources","application.yml");if(await m.pathExists(le))try{let Fe=await m.readFile(le,"utf-8");/include:\s*[^\n]*health/i.test(Fe)||/management:\s*[\s\S]*endpoint:\s*[\s\S]*health:/i.test(Fe)||(n.issues.push("Actuator health endpoint exposure is not clearly configured in application.yml"),n.fixCommands?.push(X(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 U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="rust"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"Cargo.lock"),A=u.join(e,"target");n.depsInstalled=await m.pathExists(R)||await m.pathExists(A),n.depsInstalled||(n.issues.push("Rust dependencies are not resolved yet (Cargo.lock/target missing)"),n.fixCommands?.push(X(e,"cargo fetch")));let O=u.join(e,".env");return n.hasEnvFile=await m.pathExists(O),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="elixir"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"mix.lock"),A=u.join(e,"deps");n.depsInstalled=await m.pathExists(R)||await m.pathExists(A),n.depsInstalled||(n.issues.push("Elixir dependencies not installed (mix.lock/deps missing)"),n.fixCommands?.push(X(e,"mix deps.get")));let O=u.join(e,".env");return n.hasEnvFile=await m.pathExists(O),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="clojure"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,".cpcache"),A=u.join(e,"target"),O=await m.pathExists(v)||await m.pathExists(b);return n.depsInstalled=await m.pathExists(R)||await m.pathExists(A)||O,n.depsInstalled||(n.issues.push("Clojure dependency cache not initialized"),n.fixCommands?.push(X(e,await m.pathExists(v)?"clojure -P":"lein deps"))),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="scala"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"target");n.depsInstalled=await m.pathExists(R),n.depsInstalled||(n.issues.push("Scala build artifacts missing (run dependency/build warmup)"),n.fixCommands?.push(X(e,"sbt compile")));let A=u.join(e,".env");return n.hasEnvFile=await m.pathExists(A),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="deno"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true;let R=u.join(e,".env");return n.hasEnvFile=await m.pathExists(R),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="node"||V==="bun"){let R=null;try{R=await m.readJson(c);}catch{R=null;}let A={...R?.dependencies??{},...R?.devDependencies??{}},O=R?.scripts??{},ce=typeof r?.kit_name=="string"?r.kit_name.toLowerCase():typeof r?.kit=="string"?r.kit.toLowerCase():"",z=d$2(e,r),Ke=Mr({dependencies:A,scripts:O,kitName:ce});if(_)lt(n,"Bun","high");else {let I=m$1(e,r??null);I.key==="nestjs"||I.key==="express"||I.key==="fastify"||I.key==="koa"||I.key==="tauri"||I.key==="electron"||I.key==="vscode-extension"?ne(n,I):z.key!=="unknown"?Nr(n,z):I.key!=="unknown"&&I.key!=="node"?ne(n,I):lt(n,Ke.framework,Ke.confidence);}n.venvActive=true;let Ae=u.join(e,"node_modules");if(await m.pathExists(Ae))try{let K=(await m.readdir(Ae)).filter(le=>!le.startsWith(".")&&!le.startsWith("_"));n.depsInstalled=K.length>0;}catch{n.depsInstalled=false;}if(!n.depsInstalled){n.issues.push("Dependencies not installed (node_modules empty or missing)");let I=typeof R?.packageManager=="string"?R.packageManager.split("@")[0]:void 0,K=_?"bun install":I==="pnpm"||await m.pathExists(u.join(e,"pnpm-lock.yaml"))?"pnpm install":I==="yarn"||await m.pathExists(u.join(e,"yarn.lock"))?"yarn install":"npm install";n.fixCommands?.push(X(e,K));}if(n.coreInstalled=false,n.projectKind==="frontend"){let I=[".env",".env.local",".env.development",".env.development.local",".env.production",".env.production.local"];if((await Promise.all(I.map(le=>m.pathExists(u.join(e,le))))).some(Boolean))n.hasEnvFile=true;else {let le=u.join(e,".env.example");await m.pathExists(le)&&(n.hasEnvFile=false);}}else {let I=u.join(e,".env");n.hasEnvFile=await m.pathExists(I);}if(n.projectKind==="frontend")n.modulesHealthy=await Jt(e),n.missingModules=[];else {let I=u.join(e,"src");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(I))try{let K=await m.readdir(I);n.modulesHealthy=K.length>0;}catch{n.modulesHealthy=false;}}return await U(e,n,R),await Z(e,n,R),n.projectKind==="frontend"?await ts(e,n,R,z.key!=="unknown"?z:d$2(e,r)):await Y(e,n),await H(e,n),n}if(V==="python"){let R=await Tr(e,r);lt(n,R.framework,R.confidence);let A="fastapi";n.framework==="Django"?A="django":n.framework==="Flask"?A="flask":n.framework==="Python"&&(A="");let O=await Ot(a),ce=/\[tool\.poetry\]/.test(O),z=await Rr(e),Ke=z?"project-script":ce?"poetry":await m.pathExists(u.join(e,"uv.lock"))?"uv":"venv",Ae=Dr({projectPath:e,manager:Ke,...z?{projectScript:z}:{}}),I=await Zr(e,A,ce);n.venvActive=!!I.environmentPath,n.depsInstalled=I.dependenciesInstalled,n.coreInstalled=!!I.coreVersion,n.coreVersion=I.coreVersion;let K=O.match(/^\s*requires-python\s*=\s*["']([^"']+)["']/m)?.[1];if(K){let fe=await Sr(I.interpreter),we=fe?gi(fe,K):{version:"unknown",satisfied:null};if(n.pythonRequirement={specifier:K,...fe?{detectedVersion:fe}:{},satisfied:we.satisfied},we.satisfied===false){let yt=`Python ${we.version} does not satisfy requires-python ${K}`;n.issues.push(yt),T(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"fail",severity:"error",scope:"project-scoped",reason:yt,recommendation:z?`Install a compatible Python interpreter, then run the repository-authored ${z} setup command.`:"Install a Python interpreter satisfying requires-python, then materialize the project environment.",issueClass:"runtime",operationalImpact:"release-risk"});}else we.satisfied===null?T(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"warn",severity:"warn",scope:"project-scoped",reason:fe?`Python ${fe} could not be evaluated against requires-python ${K}.`:`No executable Python version could be verified against requires-python ${K}.`,recommendation:"Verify the selected project interpreter against the complete requires-python constraint before setup or release.",issueClass:"runtime",operationalImpact:"ci-risk"}):T(n,{id:"runtime-python-version",label:"Python project version compatibility",status:"pass",severity:"info",scope:"project-scoped",reason:`Python ${we.version} satisfies requires-python ${K}.`,issueClass:"runtime",operationalImpact:"none"});}I.environmentPath?I.interpreter?n.depsInstalled||(n.issues.push("Dependencies not installed"),n.fixCommands?.push(Ae)):n.issues.push("Virtual environment exists but Python executable not found"):(n.issues.push("Virtual environment not created"),n.fixCommands?.push(Ae));let le=u.join(e,".env");n.hasEnvFile=await m.pathExists(le);let Fe=u.join(e,"src"),gt=u.join(e,"modules");if(n.modulesHealthy=true,n.missingModules=[],await m.pathExists(Fe)){let fe=u.join(Fe,"__init__.py");await m.pathExists(fe)||(n.modulesHealthy=false,n.missingModules.push("src/__init__.py"));}if(await m.pathExists(gt))try{let fe=await ss(gt);for(let we of fe){let yt=u.join(gt,we,"__init__.py");await m.pathExists(yt)||(n.modulesHealthy=false,n.missingModules.push(`modules/${we}/__init__.py`));}}catch{}return !n.modulesHealthy&&n.missingModules.length>0&&n.issues.push(`Missing module init files: ${n.missingModules.join(", ")}`),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="php"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"vendor");n.depsInstalled=await m.pathExists(R),n.depsInstalled||(n.issues.push("PHP dependencies not installed (vendor missing)"),n.fixCommands?.push(X(e,"composer install")));let A=u.join(e,".env");return n.hasEnvFile=await m.pathExists(A),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="ruby"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=await m.pathExists(u.join(e,"Gemfile.lock")),A=await m.pathExists(u.join(e,"vendor","bundle"));n.depsInstalled=R||A,n.depsInstalled||(n.issues.push("Ruby dependencies not installed (Gemfile.lock/vendor missing)"),n.fixCommands?.push(X(e,"bundle install")));let O=u.join(e,".env");return n.hasEnvFile=await m.pathExists(O),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(V==="dotnet"){ne(n,m$1(e,r??null)),n.venvActive=true,n.coreInstalled=false;let R=u.join(e,"obj"),A=u.join(e,"src","obj"),O=u.join(e,"packages.lock.json");n.depsInstalled=await m.pathExists(R)||await m.pathExists(A)||await m.pathExists(O),n.depsInstalled||(n.issues.push(".NET restore/build artifacts not found"),n.fixCommands?.push(X(e,"dotnet restore")));let ce=u.join(e,".env");return n.hasEnvFile=await m.pathExists(ce),await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}if(await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build"))){let R=await se(e,{suffix:".cpp",under:["src","."]});return lt(n,R?"C++":"C","medium"),n.venvActive=true,n.coreInstalled=false,n.depsInstalled=true,await U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}return lt(n,"Unknown","low"),T(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 U(e,n),await Z(e,n),await Y(e,n),await H(e,n),n}function Bi(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 is(e){let t=l(e);if(t.length>0)return t;let i=async a=>m.pathExists(u.join(e,a)),n=await m.readdir(e).catch(()=>[]),o=[],s=(a,l)=>{l&&!o.includes(a)&&o.push(a);},r=await i("package.json");return s("bun",r&&(await i("bun.lock")||await i("bun.lockb"))),s("deno",await i("deno.json")||await i("deno.jsonc")),s("node",r&&!o.includes("bun")),s("python",await i("pyproject.toml")||await i("requirements.txt")),s("go",await i("go.mod")),s("kotlin",await i("build.gradle.kts")&&await se(e,{suffix:".kt",under:["src"]})),s("java",await i("pom.xml")||await i("build.gradle")||await i("build.gradle.kts")&&!o.includes("kotlin")),s("rust",await i("Cargo.toml")),s("elixir",await i("mix.exs")),s("clojure",await i("deps.edn")||await i("project.clj")),s("scala",await i("build.sbt")),s("php",await i("composer.json")),s("ruby",await i("Gemfile")),s("dotnet",n.some(a=>a.endsWith(".csproj"))||await i("global.json")),(await i("CMakeLists.txt")||await i("meson.build"))&&(s("cpp",await se(e,{suffix:".cpp",under:["src","."]})),s("c",await se(e,{suffix:".c",under:["src","."]})),!o.includes("c")&&!o.includes("cpp")&&s("cpp",true)),o.length>0?o:["unknown"]}async function os(e,t){if(t.projectKind==="extension")return "plugin";if(t.projectKind==="platform")return (await m.readJson(u.join(e,"package.json")).catch(()=>null))?.workspaces?"monorepo":"platform";if(t.projectKind==="library")return "library";if(t.projectKind==="frontend"||t.projectKind==="desktop"||t.projectKind==="fullstack")return "application";let i=await m.readJson(u.join(e,"package.json")).catch(()=>null),n=!!(i&&(Array.isArray(i.workspaces)||i.workspaces&&typeof i.workspaces=="object")),o=await m.pathExists(u.join(e,"CMakeLists.txt"))||await m.pathExists(u.join(e,"meson.build")),s=await m.pathExists(u.join(e,"include")),r=(await Promise.all(["bindings","src/proto","proto","python","ruby","php","csharp","objective-c"].map(d=>m.pathExists(u.join(e,d))))).some(Boolean);if((t.runtimeFamilies?.length??0)>=3||(t.runtimeFamilies?.length??0)>=2&&o&&r)return "platform";if(n)return "monorepo";let c=i?.scripts&&typeof i.scripts=="object"?i.scripts:{},a=!!(i?.exports||i?.types||i?.main),l=!!(c.start||c.dev||c.serve);return a&&!l?/sdk|client/i.test(String(i?.name??t.name))?"sdk":"library":o&&s?"library":t.projectKind==="backend"?"service":"unknown"}function rs(e){let t=e.probes??[],i=t.map((r,c)=>r.id==="config-surface"?c:-1).filter(r=>r>=0);t.some(r=>r.id==="surface-env-contract")&&(e.probes=t.filter((r,c)=>!i.includes(c)));let n=new Set(["library","sdk","platform","plugin","monorepo"]);if(!e.projectArchetype||!n.has(e.projectArchetype))return;let o=new Set;e.probes=(e.probes??[]).map(r=>r.id==="migration-surface"||r.id==="runtime-health-surface"||r.id==="surface-kubernetes-readiness"||r.id.endsWith("-boot-entrypoint")||r.id==="runtime-security-tooling"&&e.probes?.some(a=>a.id==="surface-security-hygiene")||r.id==="surface-env-contract"&&r.status!=="pass"?(r.repairCapability?.command&&o.add(r.repairCapability.command),{...r,status:"pass",severity:"info",applicability:"not-applicable",reason:`${r.label} is not required for the detected ${e.projectArchetype} archetype.`,recommendation:void 0,repairCapability:void 0,repairIntent:void 0}):r);let s=new Set((e.probes??[]).map(r=>r.repairCapability?.id).filter(r=>!!r));e.repairCapabilities=(e.repairCapabilities??[]).filter(r=>s.has(r.id)),e.fixCommands=(e.fixCommands??[]).filter(r=>!o.has(r));}async function Nt(e,t={}){let i=Bi(await ns(e,t));delete i._freshDependencyAudit,ys(i),i.runtimeFamilies=await is(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&&T(i,{id:"runtime-composition",label:"Composite runtime coverage",status:"warn",severity:"warn",scope:"project-scoped",reason:`Multiple runtime families share one project boundary: ${i.runtimeFamilies.join(", ")}. Primary adapters evaluated ${i.runtimeFamily??"unknown"} only.`,recommendation:"Declare nested project boundaries or add doctor.adapters.json checks for every secondary runtime.",issueClass:"runtime",operationalImpact:"ci-risk"});let n=await b$3(e);if(n==="backend"||n==="service"||n==="worker"?i.projectKind="backend":n==="frontend"||n==="desktop"||n==="extension"||n==="platform"||n==="library"?i.projectKind=n:i.projectKind||(i.projectKind="generic"),i.projectArchetype=await os(e,i),i.projectArchetype==="platform"){let o=i.probes?.find(s=>s.id==="runtime-composition");o&&(o.reason=`Cross-language platform boundary detected: ${i.runtimeFamilies.join(", ")}. The primary ${i.runtimeFamily??"unknown"} adapter is combined with portable cross-runtime evidence.`,o.recommendation="Add explicit adapters only for runtime-specific checks that are not represented by the portable evidence contract.");}return rs(i),Ft(i),i}async function ss(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 pt(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 as(e,t){if(t.has(e)||a$b(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 cs(e,t,i){let n=new Set,o=[{dir:e,depth:0}];for(;o.length>0;){let s=o.shift();if(!s)break;try{let r=await m.readdir(s.dir);for(let c of r){if(as(c,i))continue;let a=u.join(s.dir,c),l;try{l=await m.stat(a);}catch{continue}if(l.isDirectory()){if(await pt(a)){n.add(a);continue}s.depth<t&&o.push({dir:a,depth:s.depth+1});}}}catch{continue}}return Array.from(n)}async function ut(e){let t=a$1(e);if(t)return t;let i=u.resolve(e),n=u.parse(i).root;for(;;){if(await ps(i))return i;if(i===n)return null;i=u.dirname(i);}}async function ls(e){let t=u.resolve(e),i=await ut(t),n=i??u.parse(t).root;for(;;){if(await pt(t)||await ds(t)&&(!i||t!==i))return t;if(t===n)break;t=u.dirname(t);}return null}function ki(e){let t=u.resolve(e);return process.platform==="darwin"?t.replace(/^\/private(?=\/var\/)/,""):t}async function ds(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 ps(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 un(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 k=d.coverage.passingObservations,v=d.coverage.blockingFindings,b=d.coverage.advisoryFindings+d.coverage.unknownFindings+d.coverage.contradictionCount;n.passed+=k,n.warnings+=b,n.errors+=v,n.total+=k+b+v;return}let p=l.probes??[];if(p.length>0){for(let k of p)n.total+=1,k.status==="pass"?n.passed+=1:k.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=ur(l),h=l.isGoProject?l.issues.length===0&&l.depsInstalled:l.issues.length===0&&l.venvActive&&l.depsInstalled;l.issues.length>0||!h?n.errors+=1:y>0?n.warnings+=1:n.passed+=1;});let o=i.passed+n.passed,s=i.warnings+n.warnings,r=i.errors+n.errors,c=Se(t,e),a=i.total+n.total;return {total:a,passed:o,warnings:s,errors:r,verdict:r>0?"blocked":s>0?"attention":"passed",presentation:{policy:"doctor-multi-axis-v1",diagnosticPassRatePercent:a>0?Math.round(o/a*100):null,blockingFindings:c.blockingCauses+c.systemErrors,advisoryFindings:c.advisoryFindings,unknownFindings:c.unknownFindings,contradictionFindings:c.contradictionFindings,notApplicableChecks:c.notApplicableChecks,label:"diagnostic-pass-rate"},components:{host:i,projects:n}}}function Q(e){let t=(e.probes??[]).filter(l=>l.applicability!=="not-applicable"),i=t.filter(l=>l.status==="pass").length,n=t.filter(l=>l.status==="warn").length,o=t.filter(l=>l.status==="fail").length,s=e.diagnosis?.coverage.blockingFindings??o+e.issues.length,r=e.diagnosis?e.diagnosis.coverage.advisoryFindings:n,c=e.diagnosis?.coverage.unknownFindings??0,a=e.diagnosis?.coverage.contradictionCount??0;return {total:t.length,passed:i,warnings:n,failed:o,blockingFindings:s,advisoryFindings:r,unknownFindings:c,contradictionFindings:a,verdict:s>0?"blocked":r+c+a>0?"attention":"passed"}}function Se(e,t=[]){let i=e.map(o=>o.diagnosis).filter(Boolean),n=e.map(Q);return {projectsScanned:e.length,affectedProjects:n.filter(o=>o.verdict!=="passed").length,projectsBlocked:n.filter(o=>o.blockingFindings>0).length,projectsNeedingAttention:n.filter(o=>o.blockingFindings===0&&o.verdict==="attention").length,blockingCauses:i.reduce((o,s)=>o+(s?.coverage.blockingFindings??0),0),advisoryFindings:i.reduce((o,s)=>o+(s?.coverage.advisoryFindings??0),0),unknownFindings:i.reduce((o,s)=>o+(s?.coverage.unknownFindings??0),0),contradictionFindings:i.reduce((o,s)=>o+(s?.coverage.contradictionCount??0),0),repairableFindings:i.reduce((o,s)=>o+(s?.coverage.repairableFindings??0),0),manualFindings:i.reduce((o,s)=>o+(s?.coverage.manualFindings??0),0),unsupportedFindings:i.reduce((o,s)=>o+(s?.coverage.unsupportedFindings??0),0),dependencyAdvisorySubjects:e.reduce((o,s)=>o+(s.dependencyAudit?.subjects.length??0),0),dependencyVulnerabilityFindings:e.reduce((o,s)=>o+(s.dependencyAudit?.findingCount??0),0),notApplicableChecks:e.reduce((o,s)=>o+(s.probes??[]).filter(r=>r.applicability==="not-applicable").length,0)+t.filter(o=>o.applicability==="not-applicable").length,systemErrors:t.filter(o=>o.status==="error").length}}function us(e){let t=Q(e);e.probeSummary=t,e.verdict=t.verdict;}function Gi(e,t,i={}){let n=[];for(let s of e)n.push({id:s.id,label:s.label,status:s.result.status,scope:"host-system",policyRuleId:"system-status-derived",reason:s.result.details||s.result.message});let o=[...t].sort((s,r)=>{let c=`${s.path||""}|${s.name||""}`.toLowerCase(),a=`${r.path||""}|${r.name||""}`.toLowerCase();return c.localeCompare(a)});for(let s of o){if(us(s),s.diagnosis){for(let r of (s.probes??[]).filter(c=>c.status==="pass"))n.push({id:`project:${s.name}:probe:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:"ok",scope:"project-scoped",policyRuleId:`project-probe-${r.id}`,reason:r.reason});for(let r of s.diagnosis.findings)n.push({id:`project:${s.name}:diagnosis:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:r.status==="blocking"?"error":"warn",scope:"project-scoped",policyRuleId:`project-diagnosis-${r.issueClass}`,reason:r.symptom});}else {for(let r of s.probes??[])n.push({id:`project:${s.name}:probe:${r.id}`,label:`${s.name} \xB7 ${r.label}`,status:r.status==="pass"?"ok":r.status==="warn"?"warn":"error",scope:"project-scoped",policyRuleId:`project-probe-${r.id}`,reason:r.reason});for(let[r,c]of s.issues.entries())n.push({id:`project:${s.name}:legacy:${r+1}`,label:`${s.name} \xB7 Runtime issue`,status:"error",scope:"project-scoped",policyRuleId:"project-runtime-issue",reason:c});}(s.probes?.length??0)===0&&s.issues.length===0&&n.push({id:`project:${s.name}`,label:`Project ${s.name}`,status:"ok",scope:"project-scoped",policyRuleId:"project-checks-passed",reason:"Project checks passed"});}if(i.includeWorkspaceAggregateRules){let s=t.reduce((a,l)=>a+Q(l).blockingFindings,0),r=t.reduce((a,l)=>a+Q(l).advisoryFindings,0),c=e.filter(a=>a.result.status==="error").length;n.push({id:"workspace:projects-discovered",label:"Workspace projects discovered",status:t.length>0?"ok":"warn",scope:"workspace-aggregate",policyRuleId:"workspace-project-discovery",reason:t.length>0?`${t.length} project(s) discovered for workspace analysis.`:"No projects discovered for workspace analysis."}),n.push({id:"workspace:system-error-gate",label:"Workspace system error gate",status:c>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-system-error-gate",reason:c>0?`${c} system requirement gate(s) failed.`:"All system requirement gates passed."}),n.push({id:"workspace:blocking-issues-gate",label:"Workspace blocking issues gate",status:s>0?"error":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-blocking-issues-gate",reason:s>0?`${s} blocking project issue(s) detected.`:"No blocking project issues detected."}),n.push({id:"workspace:advisory-warnings-gate",label:"Workspace advisory warnings gate",status:r>0?"warn":"ok",scope:"workspace-aggregate",policyRuleId:"workspace-advisory-warning-gate",reason:r>0?`${r} advisory warning(s) detected.`:"No advisory warnings detected."});}return n}async function tn(e$1,t$2=true,i=It({}),n=false){let o=u.basename(e$1),s=await a$2(e$1);if(typeof s?.name=="string"&&s.name.trim().length>0)o=s.name;else try{for(let b of t(e$1,"workspace.json")){if(!await m.pathExists(b))continue;let j=await m.readJSON(b);o=j.workspace_name||j.name||o;break}}catch{}let[r,c]=await Promise.all([pn(e$1),Or(e$1)]),a={workspacePath:e$1,workspaceName:o,python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,projects:[],policyProfile:i};e.debug(`Workspace scan found ${c.length} project(s)`);let l=await _r(e$1,c),d=u.join(e$1,t$1.doctorWorkspaceCache),p=t$2&&!n?await Br(d,l):null;if(p){a.projects=p.projects;for(let b of a.projects)Bi(b),Ft(b,p.generatedAt);a.projectScanCached=true,e.debug(`Workspace project health cache hit: ${d}`);}else try{let b=new Date().toISOString(),j=await Kr(c,x=>Nt(x,{allowNonRapidkit:true,freshAudit:n}));for(let x of j)Ft(x,b);a.projects=j,a.projectScanCached=false,await Gr(e$1,{schemaVersion:Ai,signature:l,generatedAt:b,projects:j}),e.debug(`Workspace project health cache refreshed: ${d}`);}catch(b){e.debug(`Failed to scan workspace projects: ${b}`);}a.projectScanSignature=l,a.projectScanCachePath=d;let y=Ei({python:a.python,poetry:a.poetry,pipx:a.pipx,go:a.go,rapidkitCore:a.rapidkitCore},a.projects);a.python=y.python,a.poetry=y.poetry,a.pipx=y.pipx,a.go=y.go,a.rapidkitCore=y.rapidkitCore,await Promise.all(a.projects.map(async b=>{b.graphDiagnosis=await en({workspacePath:e$1,projectPath:b.path,projectName:b.name,probes:Fi(b),issues:b.issues}),$i(b);}));let h=[a.python,a.poetry,a.pipx,a.go,a.rapidkitCore];if(a.healthScore=un(h,a.projects),a.scoreBreakdown=Gi([{id:"system-python",label:"Python",result:a.python},{id:"system-poetry",label:"Poetry",result:a.poetry},{id:"system-pipx",label:"pipx",result:a.pipx},{id:"system-go",label:"Go",result:a.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:a.rapidkitCore}],a.projects,{includeWorkspaceAggregateRules:true}),a.scopeProvenance=Ti(a.scoreBreakdown),a.evidenceFreshness=ln(a.projects,new Date().toISOString()),a.rapidkitCore.status==="ok"){let b=a.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);b&&(a.coreVersion=b[1]);}let k=await g(e$1,rn),v=k?await Ni(k,"workspace"):null;return a.driftDelta=Cr(v,a),a.evidencePath=await Wr(e$1,a,p?d:null),a.receiptPath=await Hi(e$1,Wi({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}function vi(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??Q(e).verdict,probeSummary:e.probeSummary??Q(e),repairCapabilities:e.repairCapabilities,commandCapabilities:e.commandCapabilities,graphDiagnosis:e.graphDiagnosis,diagnosis:e.diagnosis}}function Ki(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 ms(e,t){let i$1=e||t.projectPath,n=t$1.doctorProject,o=Ki(e,t.projectPath),s=u.join(i$1,n);try{let r=[...t.project.issues,...(t.project.probes??[]).filter(d=>d.status==="fail").map(d=>d.reason)].filter(d=>typeof d=="string"&&d.trim().length>0).slice(0,12),c=Q(t.project),a=Se([t.project],[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore]),l=f$1({schemaVersion:b$4,evidenceType:"project",contract:Ue(),policyProfile:t.policyProfile,workspacePath:e||null,projectPath:t.projectPath,projectName:t.projectName,healthScore:t.healthScore,evidenceFreshness:t.evidenceFreshness,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,go:t.go,rapidkitCore:t.rapidkitCore},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:mt(t.healthScore,{profile:t.policyProfile?.name}),generatedAt:new Date().toISOString(),blockers:r,runId:e$1()});return d(l),e?await i(e,n,[{relativePath:n,payload:l},{relativePath:o,payload:l}]):await h(i$1,n,l),e&&u.resolve(e)!==u.resolve(t.projectPath)&&await h(t.projectPath,n,l),s}catch(r){throw r}}function Wi(e){let t=new Date().toISOString(),i=e.freshness??ln(e.projects,t),n=Se(e.projects,e.systemChecks),o=e.projects.map(l=>{let d=Q(l);return {name:l.name,path:l.path,runtimeFamily:l.runtimeFamily??"unknown",framework:l.framework??"Unknown",verdict:d.verdict,blockingCauses:l.diagnosis?.coverage.blockingFindings??d.blockingFindings,advisoryFindings:l.diagnosis?.coverage.advisoryFindings??d.advisoryFindings,unknownFindings:l.diagnosis?.coverage.unknownFindings??0}}).filter(l=>l.blockingCauses>0||l.advisoryFindings>0||l.unknownFindings>0),s$1=e.projects.flatMap(l=>(l.diagnosis?.findings??[]).filter(d=>d.status==="blocking").map(d=>({id:d.id,projectName:l.name,projectPath:l.path,issueClass:d.issueClass,symptom:d.symptom,repairDisposition:d.repair.disposition,...d.repair.capabilityId?{capabilityId:d.repair.capabilityId}:{}}))),r=e.projects.reduce((l,d)=>l+(d.diagnosis?.findings??[]).filter(p=>p.status==="blocking"&&(p.repair.disposition==="automatic"||p.repair.disposition==="approval-required")).length,0),c=e.healthScore?.verdict??(n.blockingCauses>0?"blocked":n.advisoryFindings+n.unknownFindings>0?"attention":"passed"),a=i.status!=="fresh"?{action:"refresh",reason:"Doctor evidence is stale or has unknown freshness.",commands:[`npx workspai doctor ${e.scopeKind} --fresh --json=summary`]}:n.blockingCauses>0&&r>0?{action:"repair",reason:"At least one blocking cause has a typed repair capability.",commands:[`npx workspai doctor ${e.scopeKind} --plan --json=summary`]}:n.blockingCauses>0?{action:"review",reason:"Blocking causes remain, but no automatic typed repair covers every cause.",commands:[`npx workspai doctor ${e.scopeKind} --json`]}:c==="attention"?{action:"review",reason:"No blocker remains; advisory or unknown findings need policy review.",commands:[`npx workspai doctor ${e.scopeKind} --json=summary`]}:{action:"verify",reason:"Doctor is healthy; canonical Workspace Intelligence verification is next.",commands:["npx workspai workspace intelligence run --strict --json"]};return {schemaVersion:s.doctorReceipt.schemaVersion,generatedAt:t,scope:{kind:e.scopeKind,root:e.scopeRoot,name:e.scopeName,workspacePath:e.workspacePath??null,projectPath:e.projectPath??null},verdict:c,counts:n,freshness:i,affectedProjects:o,blockers:s$1,next:a,artifacts:{evidence:e.evidencePath??null,receipt:u.join(e.scopeRoot,t$1.doctorReceipt)}}}async function Hi(e,t,i=[]){a$5(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 sn(e,t,i=[]){let n=u.join(e,t$1.doctorRemediationPlan);try{await h(e,t$1.doctorRemediationPlan,t);for(let o of i)u.resolve(o)!==u.resolve(e)&&await h(o,t$1.doctorRemediationPlan,t);return n}catch(o){if(o instanceof Error&&o.message.includes("violates contracts/"))throw o;return}}async function Ye(e,t,i=[]){let n=u.join(e,t$1.doctorFixResult);try{await h(e,t$1.doctorFixResult,t);for(let o of i)u.resolve(o)!==u.resolve(e)&&await h(o,t$1.doctorFixResult,t);return n}catch{return}}async function Ze(e,t,i){try{await j(e,g$1(t,i));}catch{}}async function wi(e,t=It({}),i=false){let n=await ut(e),o=await pn(n||e),s=await Nt(e,{allowNonRapidkit:true,freshAudit:i}),r=Ei(o,[s]);Ft(s),s.graphDiagnosis=await en({workspacePath:n||void 0,projectPath:e,projectName:s.name,probes:Fi(s),issues:s.issues}),$i(s);let c=un([r.python,r.poetry,r.pipx,r.go,r.rapidkitCore],[s]),a={workspacePath:n||void 0,projectPath:e,projectName:u.basename(e),python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,project:s,healthScore:c,policyProfile:t};a.scoreBreakdown=Gi([{id:"system-python",label:"Python",result:a.python},{id:"system-poetry",label:"Poetry",result:a.poetry},{id:"system-pipx",label:"pipx",result:a.pipx},{id:"system-go",label:"Go",result:a.go},{id:"system-rapidkit-core",label:"RapidKit Core",result:a.rapidkitCore}],[a.project]),a.scopeProvenance=Ti(a.scoreBreakdown),a.evidenceFreshness=ln([a.project],new Date().toISOString());let l=await g(e,t$1.doctorProject),d=n?await g(n,Ki(n,e)):null,p=l??d,y=p?await Ni(p,"project"):null;a.driftDelta=Pr(y,a),a.evidencePath=await ms(n||void 0,a);let h=n||e;return a.receiptPath=await Hi(h,Wi({scopeKind:"project",scopeRoot:h,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]}),n&&u.resolve(n)!==u.resolve(e)?[e]:[]),a}function Oe(e,t){let i=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",n=e.status==="ok"?f.green:e.status==="warn"?f.yellow:f.red;console.log(`${i} ${f.bold(t)}: ${n(e.message)}`),e.paths&&e.paths.length>0&&e.paths.forEach(o=>{let s=o.version?f.cyan(` -> ${o.version}`):"";console.log(` ${f.cyan("\u2022")} ${f.gray(o.location)}: ${f.dim(o.path)}${s}`);}),e.details&&console.log(` ${f.gray(e.details)}`);}function St(e,t){let i=$t(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 fs(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 ji(e,t,i={}){let n=Q(e),o=n.verdict==="blocked"?"\u274C":n.verdict==="attention"?"\u26A0\uFE0F":"\u2705",s=n.verdict==="blocked"?f.red:n.verdict==="attention"?f.yellow:f.green;if(console.log(`
23
23
  ${o} ${f.bold("Project")}: ${s(e.name)}`),e.framework){let a=e.framework==="FastAPI"||e.framework==="Django"||e.framework==="Flask"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":e.framework==="Next.js"||e.framework==="Nuxt"||e.framework==="Remix"?"\u25B2":e.framework==="React"||e.framework==="Vite"?"\u269B\uFE0F":e.framework==="Vue"?"\u{1F7E2}":e.framework==="Angular"?"\u{1F170}\uFE0F":e.framework==="SvelteKit"?"\u{1F9E1}":e.framework==="Spring Boot"?"\u2615":e.framework==="Rust"?"\u{1F980}":e.framework==="Elixir"||e.framework==="Phoenix"?"\u{1F9EA}":e.framework==="Clojure"?"\u2699\uFE0F":e.framework==="Scala"?"\u{1F53A}":e.framework==="Kotlin"?"\u{1F7E3}":e.framework==="Deno"?"\u{1F995}":e.framework==="Bun"?"\u{1F956}":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"\u{1F439}":e.framework==="Laravel"||e.framework==="PHP"?"\u{1F418}":e.framework==="Ruby on Rails"||e.framework==="Ruby"?"\u{1F48E}":e.framework==="ASP.NET"?"\u{1F537}":"\u{1F4E6}",l=["C","C++","Python","Unknown"].includes(e.framework)?"Detected stack":"Framework";console.log(` ${a} ${l}: ${f.cyan(e.framework)}${e.kit?f.gray(` (${e.kit})`):""}`);let d=[];e.runtimeFamily&&d.push(`runtime: ${e.runtimeFamily}`),e.projectKind&&d.push(`kind: ${e.projectKind}`),e.projectArchetype&&d.push(`archetype: ${e.projectArchetype}`),e.supportTier&&d.push(`lifecycle support: ${e.supportTier}`),e.diagnosis?.capability.tier&&d.push(`diagnostic adapter: ${e.diagnosis.capability.tier}`),e.frameworkConfidence&&d.push(`confidence: ${e.frameworkConfidence}`),d.length>0&&console.log(` ${f.dim("\u21B3")} ${f.gray(d.join(" \u2022 "))}`);}if(console.log(` ${f.gray(`Boundary: ${fs(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
24
  ${f.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(a=>{console.log(` ${f.white(St(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 Li(){try{return (await execa("go",["version"],{timeout:a$8(),reject:false})).exitCode===0}catch{return false}}function _e(e,t){let i=[new RegExp(`^Set-Location\\s+-LiteralPath\\s+"([^"]+)"\\s*;\\s*${t}\\s*$`,"i"),new RegExp(`^cd\\s+"([^"]+)"\\s*(?:&&|;)\\s*${t}\\s*$`,"i"),new RegExp(`^cd\\s+'([^']+)'\\s*(?:&&|;)\\s*${t}\\s*$`,"i"),new RegExp(`^cd\\s+(.+?)\\s*(?:&&|;)\\s*${t}\\s*$`,"i")];for(let n of i){let o=e.match(n);if(o?.[1])return {projectPath:o[1].trim()}}return null}function Mt(e){return _e(e,"cp\\s+\\.env\\.example\\s+\\.env")||_e(e,"copy-item\\s+\\.env\\.example\\s+\\.env")}function mn(e){let t=[{pattern:"npm\\s+install",command:"npm",args:["install"]},{pattern:"npm\\s+ci",command:"npm",args:["ci"]},{pattern:"pnpm\\s+install",command:"pnpm",args:["install"]},{pattern:"yarn\\s+install",command:"yarn",args:["install"]},{pattern:"bun\\s+install",command:"bun",args:["install"]},{pattern:"poetry\\s+install",command:"poetry",args:["install"]},{pattern:"poetry\\s+install\\s+--no-root",command:"poetry",args:["install","--no-root"]},{pattern:"poetry\\s+lock",command:"poetry",args:["lock"]},{pattern:"uv\\s+lock",command:"uv",args:["lock"]},{pattern:"uv\\s+sync",command:"uv",args:["sync"]},{pattern:"(?:\\.\\/)?script\\/setup",command:"script/setup",args:[]},{pattern:"(?:\\.\\/)?scripts\\/setup",command:"scripts/setup",args:[]},{pattern:"(?:\\.\\/)?bin\\/setup",command:"bin/setup",args:[]},{pattern:"script[\\\\/]setup\\.cmd",command:"script/setup.cmd",args:[]},{pattern:"scripts[\\\\/]setup\\.cmd",command:"scripts/setup.cmd",args:[]},{pattern:"script[\\\\/]setup\\.ps1",command:"script/setup.ps1",args:[]},{pattern:"scripts[\\\\/]setup\\.ps1",command:"scripts/setup.ps1",args:[]},{pattern:"script\\\\setup\\.cmd",command:"script\\setup.cmd",args:[]},{pattern:"scripts\\\\setup\\.cmd",command:"scripts\\setup.cmd",args:[]},{pattern:"python3\\s+-m\\s+venv\\s+\\.venv",command:"python3",args:["-m","venv",".venv"]},{pattern:"python\\s+-m\\s+venv\\s+\\.venv",command:"python",args:["-m","venv",".venv"]},{pattern:"py\\s+-3\\s+-m\\s+venv\\s+\\.venv",command:"py",args:["-3","-m","venv",".venv"]},{pattern:"pip\\s+install\\s+-r\\s+requirements\\.txt",command:"pip",args:["install","-r","requirements.txt"]},{pattern:"composer\\s+install",command:"composer",args:["install"]},{pattern:"bundle\\s+install",command:"bundle",args:["install"]},{pattern:"dotnet\\s+restore",command:"dotnet",args:["restore"]},{pattern:"cargo\\s+fetch",command:"cargo",args:["fetch"]},{pattern:"mix\\s+deps\\.get",command:"mix",args:["deps.get"]},{pattern:"clojure\\s+-P",command:"clojure",args:["-P"]},{pattern:"lein\\s+deps",command:"lein",args:["deps"]},{pattern:"sbt\\s+compile",command:"sbt",args:["compile"]},{pattern:"go\\s+mod\\s+tidy",command:"go",args:["mod","tidy"]},{pattern:"mvn\\s+-B\\s+-DskipTests\\s+-Dmaven\\.repo\\.local=\\.workspai/cache/java/m2\\s+dependency:go-offline",command:"mvn",args:["-B","-DskipTests","-Dmaven.repo.local=.workspai/cache/java/m2","dependency:go-offline"]},{pattern:"\\.\\/mvnw\\s+-B\\s+-DskipTests\\s+-Dmaven\\.repo\\.local=\\.workspai/cache/java/m2\\s+dependency:go-offline",command:"./mvnw",args:["-B","-DskipTests","-Dmaven.repo.local=.workspai/cache/java/m2","dependency:go-offline"]},{pattern:"\\.\\\\mvnw\\.cmd\\s+-B\\s+-DskipTests\\s+-Dmaven\\.repo\\.local=\\.workspai/cache/java/m2\\s+dependency:go-offline",command:".\\mvnw.cmd",args:["-B","-DskipTests","-Dmaven.repo.local=.workspai/cache/java/m2","dependency:go-offline"]},{pattern:"mvn\\s+-B\\s+-DskipTests\\s+dependency:go-offline",command:"mvn",args:["-B","-DskipTests","dependency:go-offline"]},{pattern:"\\.\\/mvnw\\s+-B\\s+-DskipTests\\s+dependency:go-offline",command:"./mvnw",args:["-B","-DskipTests","dependency:go-offline"]},{pattern:"\\.\\\\mvnw\\.cmd\\s+-B\\s+-DskipTests\\s+dependency:go-offline",command:".\\mvnw.cmd",args:["-B","-DskipTests","dependency:go-offline"]},{pattern:"gradle\\s+dependencies",command:"gradle",args:["dependencies"]},{pattern:"\\.\\/gradlew\\s+dependencies",command:"./gradlew",args:["dependencies"]},{pattern:"\\.\\\\gradlew\\.bat\\s+dependencies",command:".\\gradlew.bat",args:["dependencies"]},{pattern:"gradle\\s+--project-cache-dir\\s+\\.workspai/cache/java/gradle\\s+dependencies",command:"gradle",args:["--project-cache-dir",".workspai/cache/java/gradle","dependencies"]},{pattern:"\\.\\/gradlew\\s+--project-cache-dir\\s+\\.workspai/cache/java/gradle\\s+dependencies",command:"./gradlew",args:["--project-cache-dir",".workspai/cache/java/gradle","dependencies"]},{pattern:"\\.\\\\gradlew\\.bat\\s+--project-cache-dir\\s+\\.workspai/cache/java/gradle\\s+dependencies",command:".\\gradlew.bat",args:["--project-cache-dir",".workspai/cache/java/gradle","dependencies"]}];for(let i of t){let n=_e(e,i.pattern);if(n)return {projectPath:n.projectPath,command:i.command,args:i.args}}return null}function gs(e){let t=u.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:cmd|bat)$/i,"");return /(?:^|\/)(?:script\/setup|scripts\/setup|bin\/setup)(?:\.cmd|\.ps1)?$/iu.test(e.replaceAll("\\","/"))?{ecosystem:"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt",e.replaceAll("\\","/")]}:["npm","pnpm","yarn","bun"].includes(t)?{ecosystem:t,files:["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]}:["poetry","uv","pip","pip3","python","python3","py"].includes(t)?{ecosystem:t==="uv"?"uv":t==="poetry"?"poetry":"python",files:["pyproject.toml","poetry.lock","uv.lock","requirements.txt"]}:t==="go"?{ecosystem:"go",files:["go.mod","go.sum"]}:t==="cargo"?{ecosystem:"cargo",files:["Cargo.toml","Cargo.lock"]}:t==="composer"?{ecosystem:"composer",files:["composer.json","composer.lock"]}:t==="bundle"?{ecosystem:"bundler",files:["Gemfile","Gemfile.lock"]}:t==="mix"?{ecosystem:"mix",files:["mix.exs","mix.lock"]}:t==="dotnet"?{ecosystem:"dotnet",files:["Directory.Packages.props","packages.lock.json"]}:t==="clojure"||t==="lein"?{ecosystem:"clojure",files:["deps.edn","project.clj"]}:t==="sbt"?{ecosystem:"sbt",files:["build.sbt"]}:t==="mvn"||t==="mvnw"?{ecosystem:"maven",files:["pom.xml",".workspai/cache/java/m2"]}:t==="gradle"||t==="gradlew"?{ecosystem:"gradle",files:["build.gradle","build.gradle.kts","gradle.lockfile",".workspai/cache/java/gradle"]}:{ecosystem:t,files:[]}}function ys(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=mn(i);if(!n||e.depsInstalled&&!t)continue;let o=gs(n.command),s=c$4({issueId:"runtime-dependency-materialization",title:`Install ${o.ecosystem} dependencies`,projectPath:n.projectPath,ecosystem:o.ecosystem,executable:n.command,args:n.args,files:o.files,command:i,reason:"The dependency definition exists, but its local runtime dependency tree is missing or incomplete.",limitations:["This transaction may update a lockfile when the package manager determines it is stale.","Source mutation is not required when the existing manifest and lockfile are already consistent."]}),r=e.probes?.find(c=>c.id==="runtime-dependency-materialization");if(r){Object.assign(r,cn({...r,repairCapability:s},new Date().toISOString()));continue}T(e,{id:"runtime-dependency-materialization",label:"Runtime dependency materialization",status:"fail",severity:"error",scope:"project-scoped",reason:t??"The dependency definition exists, but its local runtime dependency tree is missing or incomplete.",recommendation:"Run the typed dependency materialization transaction, then recheck the exact runtime postcondition.",repairCapability:s,issueClass:"dependency",operationalImpact:"release-risk"});}if(e.depsInstalled&&!(e.probes??[]).some(i=>i.id==="runtime-dependency-materialization")){let i=(e.probes??[]).some(c=>c.id==="composite-project-boundary"),n=e.runtimeFamily==="c"||e.runtimeFamily==="cpp",o=e.runtimeFamily==="deno",s=i||n||o,r=i?"Dependency materialization is evaluated at each registered runtime project boundary, not at this aggregate polyglot container.":n?"Native dependency materialization is build-system and organization specific; Doctor verified the build contract without claiming a universal local dependency tree.":o?"The detected runtime resolves dependencies without a project-local installation tree.":hs(e.runtimeFamily);T(e,{id:"runtime-dependency-materialization",label:"Runtime dependency materialization",status:"pass",severity:"info",scope:"project-scoped",...s?{applicability:"not-applicable"}:{},reason:r,issueClass:"dependency",operationalImpact:"none"});}}function hs(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 bs(){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 Tt(e){let t=[/^cd\s+"([^"]+)"\s*(?:&&|;)\s*npm\s+pkg\s+set\s+"scripts\.([^=]+)=([^"]+)"\s*$/i,/^cd\s+'([^']+)'\s*(?:&&|;)\s*npm\s+pkg\s+set\s+'scripts\.([^=]+)=([^']+)'\s*$/i,/^cd\s+(.+?)\s*(?:&&|;)\s*npm\s+pkg\s+set\s+scripts\.([^=\s]+)=(.+)\s*$/i];for(let i of t){let n=e.match(i);if(!(!n?.[1]||!n?.[2]||!n?.[3]))return {projectPath:n[1].trim(),scriptName:n[2].trim(),scriptValue:n[3].trim().replace(/\\"/g,'"').replace(/\\\\/g,"\\")}}return null}function Xe(e){let t=e.trim().match(/^(?:workspai|rapidkit):doctor:repair\s+([A-Za-z0-9_-]+)$/);if(!t?.[1])return null;try{let i=Buffer.from(t[1],"base64url").toString("utf8"),n=JSON.parse(i);return a(n)}catch{return null}}function ks(e){let t=e.operation?vs(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 vs(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
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 ws(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 Ee(e,t){if(!(await m.stat(e).catch(()=>{}))?.isDirectory())throw new Error(`Repair project boundary not found: ${e}`);let n=ws(e,t),o=await m.realpath(e).catch(()=>u.resolve(e)),s=n;for(;!await m.pathExists(s);){let a=u.dirname(s);if(a===s)throw new Error(`Repair target has no resolvable project ancestor: ${t}`);s=a;}let r=await m.realpath(s).catch(()=>u.resolve(s)),c=u.relative(o,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Repair target escapes project boundary through a symbolic link: ${t}`);return n}async function js(e){if(!/^[A-Za-z0-9:_-]+$/.test(e.scriptName))throw new Error(`Unsafe package script name: ${e.scriptName}`);let t=await Ee(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 xs(e){let t=await Ee(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 Cs(e){let t=await Ee(e.projectPath,e.operation.path);await m.ensureDir(u.dirname(t));let i=await Ot(t),n=i.split(/\r?\n/),o=e.operation.lines.filter(r=>!n.includes(r));if(o.length===0)return;let s=i.length===0||i.endsWith(`