跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

doctor.go

393 行 · 14.7 KB历史下载
1package cli
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "os"
9 "os/exec"
10 "runtime"
11 "slices"
12 "strconv"
13 "strings"
14 "time"
15
16 limaversion "github.com/lima-vm/lima/v2/pkg/version"
17
18 "github.com/sylvinus/agent-vm/internal/env"
19 "github.com/sylvinus/agent-vm/internal/gitguard"
20 "github.com/sylvinus/agent-vm/internal/guard"
21 "github.com/sylvinus/agent-vm/internal/host"
22 "github.com/sylvinus/agent-vm/internal/mounts"
23 "github.com/sylvinus/agent-vm/internal/netguard"
24 "github.com/sylvinus/agent-vm/internal/runscript"
25 "github.com/sylvinus/agent-vm/internal/state"
26 "github.com/sylvinus/agent-vm/internal/version"
27 "github.com/sylvinus/agent-vm/internal/vm"
28 "github.com/sylvinus/agent-vm/internal/vmname"
29)
30
31// doctor counts what it finds.
32type doctor struct {
33 e *app
34 warn, fail int
35}
36
37// line prints one finding: level ok, warn, fail or info, then hints.
38func (d *doctor) line(level, msg string, hints ...string) {
39 w := d.e.io.Stdout
40 switch level {
41 case "ok":
42 fmt.Fprintf(w, " ok %s\n", msg)
43 case "warn":
44 fmt.Fprintf(w, " warn %s\n", msg)
45 d.warn++
46 case "fail":
47 fmt.Fprintf(w, " FAIL %s\n", msg)
48 d.fail++
49 default:
50 fmt.Fprintf(w, " - %s\n", msg)
51 }
52 for _, h := range hints {
53 fmt.Fprintf(w, " %s\n", h)
54 }
55}
56
57func (d *doctor) section(name string) { fmt.Fprintf(d.e.io.Stdout, "\n%s\n", name) }
58
59// `doctor`: checks the host, Lima, the base template and the current
60// directory, and says what to do about each problem. Read-only: it never
61// creates, starts or stops a VM, so it is safe to run first and to paste
62// into an issue (names, no secret values). 1 when a check failed.
63func (e *app) doctorCmd(ctx context.Context, args []string) int {
64 if len(args) > 0 {
65 fmt.Fprintln(e.io.Stderr, "Usage: agent-vm doctor")
66 return 2
67 }
68 d := &doctor{e: e}
69 w := e.io.Stdout
70 fmt.Fprintln(w, "agent-vm doctor")
71 d.section("agent-vm")
72 exe, _ := os.Executable()
73 d.line("info", fmt.Sprintf("version %s, from %s", version.Version, exe))
74
75 d.section("Host")
76 d.line("info", runtime.GOOS+" "+runtime.GOARCH)
77 cpus, mem := host.CPUs(), host.MemGiB()
78 if cpus > 0 && mem > 0 {
79 div, bad, invalid := host.Divisor()
80 var discard bytes.Buffer
81 d.line("info", fmt.Sprintf("%d CPUs, %d GiB RAM; a VM gets at most %d CPUs and %d GiB (a 1/%d share)",
82 cpus, mem, host.Cap("cpus", cpus, &discard), host.Cap("memory", mem, &discard), div))
83 if invalid {
84 d.line("warn", fmt.Sprintf("AGENT_VM_HOST_SHARE='%s' is not a positive integer: 2 is used", bad))
85 }
86 } else {
87 d.line("warn", "could not read the host's CPU or RAM: --cpus and --memory are not clamped")
88 }
89 dir := LimaHome(e.state)
90 switch free, ok := host.FreeGiB(dir); {
91 case !ok:
92 d.line("warn", "could not read the free disk space")
93 case free < 10:
94 d.line("warn", fmt.Sprintf("%d GiB free for the VMs", free), "A default VM disk is 10 GiB (sparse).")
95 default:
96 d.line("ok", fmt.Sprintf("%d GiB free for the VMs", free))
97 }
98
99 d.section("Lima")
100 d.line("info", fmt.Sprintf("Lima %s, built in; its VMs in %s", strings.TrimPrefix(limaversion.Version, "v"), LimaHome(e.state)))
101 for _, f := range vm.LimaOverrides(LimaHome(e.state)) {
102 d.line("fail", f+" adds to every VM's config: agent-vm makes and starts no VM while it is there", "Move it out of the way.")
103 }
104 protects := !writableGitOptOut(false)
105 if cageWritableGit() {
106 d.line("info", "Cage projects allow Git writes within the shared directories")
107 } else if protects {
108 d.line("ok", "every .git is read-only for the VMs (sshfs.readonlyNames)")
109 } else {
110 d.line("warn", "AGENT_VM_UNSAFE_WRITABLE_GIT=1: the VMs can write .git, and git on this machine runs what .git/config and hooks name",
111 "Unset it to keep .git read-only.")
112 }
113 var prereqs bytes.Buffer
114 switch runtime.GOOS {
115 case "linux":
116 if host.LinuxPrereqs(&prereqs) {
117 d.line("ok", "QEMU and /dev/kvm are usable")
118 } else {
119 d.line("fail", "QEMU or KVM is not usable", strings.Split(strings.TrimSuffix(prereqs.String(), "\n"), "\n")...)
120 }
121 case "windows":
122 if host.WindowsPrereqs(&prereqs, &prereqs) {
123 d.line("ok", "QEMU is installed")
124 } else {
125 d.line("fail", "QEMU is not usable", strings.Split(strings.TrimSuffix(prereqs.String(), "\n"), "\n")...)
126 }
127 d.line("info", "QEMU also needs the 'Windows Hypervisor Platform' feature, which only an administrator can check or turn on",
128 "Without it, VMs fail to start with a WHPX error. An administrator runs, once, then reboots:", host.WHPXOn)
129 }
130
131 // A bare repository is not named .git, so the names do not cover one the
132 // VM plants in a project.
133 if st := gitguard.BareState(ctx); st != gitguard.BareNoGit {
134 d.section("Git on this machine")
135 switch st {
136 case gitguard.BareOK:
137 d.line("ok", "safe.bareRepository = explicit")
138 case gitguard.BareUnavailable:
139 d.line("warn", "host Git could not be checked; check the Git installation, then retry")
140 case gitguard.BareOld:
141 out, _ := exec.CommandContext(ctx, "git", "--version").Output()
142 d.line("warn", strings.TrimSpace(string(out))+" is older than 2.38: it would use a repository a VM creates under another name than .git, and run what its config names",
143 "Upgrade git, then: git config --global safe.bareRepository explicit")
144 default:
145 d.line("warn", "safe.bareRepository is not 'explicit': git would use a repository a VM creates under another name than .git, and run what its config names",
146 "git config --global safe.bareRepository explicit")
147 }
148 }
149
150 d.section("Base template")
151 b, berr := e.readOnlyBackend()
152 if vms, old := e.unmovedOld(); len(vms) > 0 {
153 d.line("info", fmt.Sprintf("%d VM(s) of agent-vm 0.2 in %s, not moved yet", len(vms), old),
154 "The next agent-vm command that starts or removes a VM offers to move them.")
155 }
156 getVM := func(name string) (*vm.Instance, error) {
157 if berr != nil {
158 return nil, berr
159 }
160 inst, err := b.Get(ctx, name)
161 if errors.Is(err, vm.ErrNotFound) {
162 return nil, nil
163 }
164 return inst, err
165 }
166 base, err := getVM(vmname.Template)
167 _, merr := os.Stat(e.state.Path(state.BaseVersion))
168 switch {
169 case err != nil:
170 d.line("warn", "could not query Lima")
171 case base != nil && merr == nil:
172 if built, perr := strconv.ParseInt(e.state.Read(state.BaseVersion), 10, 64); perr == nil {
173 d.line("ok", fmt.Sprintf("%s is ready, built %s", vmname.Template, time.Unix(built, 0).Format("2006-01-02")))
174 if time.Since(time.Unix(built, 0)) > 90*24*time.Hour {
175 d.line("warn", "the base template is over 90 days old", "Its agents and packages are as old. 'agent-vm setup' rebuilds it.")
176 }
177 } else {
178 d.line("ok", vmname.Template+" is ready")
179 }
180 if _, err := os.Stat(e.state.Path(state.BaseBuiltBy)); err != nil {
181 d.line("warn", "the base template was built by agent-vm 0.1.0, without what the shares that keep .git read-only need",
182 "'agent-vm setup' rebuilds it, then '--reset' the VMs made from it.")
183 }
184 case base != nil:
185 d.line("fail", vmname.Template+" exists but its setup did not complete", "Run 'agent-vm setup' again.")
186 default:
187 d.line("fail", "no base template yet", "Run 'agent-vm setup'.")
188 }
189
190 d.section(fmt.Sprintf("Settings (%s)", e.state))
191 if content, err := os.ReadFile(e.state.Path("env")); err == nil {
192 keys := len(unique(env.Names(string(content))))
193 fi, serr := os.Stat(e.state.Path("env"))
194 switch {
195 case runtime.GOOS == "windows":
196 // Permission bits mean little there: the file's ACL protects it.
197 d.line("info", fmt.Sprintf("env: %d key(s)", keys))
198 case serr == nil && fi.Mode().Perm()&0o077 == 0:
199 d.line("ok", fmt.Sprintf("env: %d key(s), private to you (mode %o)", keys, fi.Mode().Perm()))
200 case serr == nil:
201 d.line("warn", fmt.Sprintf("env is readable by other users on this machine (mode %o)", fi.Mode().Perm()), fmt.Sprintf("chmod 600 '%s'", e.state.Path("env")))
202 default:
203 d.line("warn", "env permissions could not be checked", fmt.Sprintf("chmod 600 '%s'", e.state.Path("env")))
204 }
205 } else {
206 d.line("info", "env: none (agent-vm env set KEY VALUE)")
207 }
208 for _, f := range []string{"volumes", "setup.sh", "runtime.sh", guard.FileName} {
209 if _, err := os.Stat(e.state.Path(f)); err == nil {
210 d.line("info", f+": present")
211 }
212 }
213 switch pol, err := netguard.Load(string(e.state)); {
214 case err != nil:
215 d.line("fail", err.Error(), "No VM starts until it is fixed.")
216 case pol.Open:
217 d.line("warn", "network isolation off (AGENT_VM_UNSAFE_OPEN_NETWORK=1): the VMs reach this machine and its networks")
218 case len(pol.Allow) > 0 || len(pol.Domains) > 0:
219 d.line("info", netguard.FileName+": present")
220 }
221
222 wd, _ := vmname.AbsDir("")
223 d.section(fmt.Sprintf("This directory (%s)", wd))
224 d.directory(ctx, wd, protects, getVM)
225
226 d.section("All VMs")
227 if vms, err := e.lookVMs(ctx); err == nil {
228 n, c, m := 0, 0, 0
229 for _, v := range vms {
230 if v.Status == vm.Running {
231 n, c, m = n+1, c+v.CPUs, m+int(v.Memory>>30)
232 }
233 }
234 switch {
235 case n == 0:
236 d.line("info", "none running")
237 case mem > 0 && m > mem:
238 d.line("warn", fmt.Sprintf("%d running, %d CPUs and %d GiB in total: more memory than the host has", n, c, m),
239 "'agent-vm list' lists them; 'agent-vm stop <name>' frees one.")
240 default:
241 d.line("info", fmt.Sprintf("%d running, %d CPUs and %d GiB in total", n, c, m))
242 }
243 }
244 dead, unknown := e.scratchLeftovers()
245 for _, left := range dead {
246 d.line("warn", "scratch VM "+left+" was left by a run that did not finish", "The next --scratch run deletes it, or: agent-vm rm "+left)
247 }
248 for _, left := range unknown {
249 d.line("warn", "scratch VM "+left+" has a record without a process number: not known whether a run still uses it", "agent-vm rm "+left+" deletes it.")
250 }
251
252 fmt.Fprintln(w)
253 if d.fail > 0 {
254 fmt.Fprintf(w, "%d problem(s), %d warning(s).\n", d.fail, d.warn)
255 return 1
256 }
257 fmt.Fprintf(w, "No problems found, %d warning(s).\n", d.warn)
258 return 0
259}
260
261func unique(s []string) []string {
262 var out []string
263 for _, x := range s {
264 if !slices.Contains(out, x) {
265 out = append(out, x)
266 }
267 }
268 return out
269}
270
271// directory checks the project dir: its path, its VM and what protects it,
272// the hooks and config git runs from its shares, its runtime and env files.
273func (d *doctor) directory(ctx context.Context, dir string, protects bool, getVM func(string) (*vm.Instance, error)) {
274 e := d.e
275 if why, bad := mounts.Unmountable(dir); bad {
276 d.line("fail", "the path "+why, "agent-vm refuses to mount it. Rename the directory.")
277 }
278 if why, bad := mounts.UnsafeProject(dir, e.refs()); bad {
279 d.line("fail", "this directory "+why, "agent-vm refuses to share it with a VM. Run it from a project directory.")
280 }
281 scan := &gitguard.Result{}
282 if !cageWritableGit() {
283 scan = e.scan(ctx, dir)
284 }
285 names := scan.Names()
286 name := e.instanceName(dir)
287 inst, err := getVM(name)
288 switch {
289 case err != nil:
290 d.line("warn", "could not query Lima")
291 case inst == nil:
292 d.line("info", name+" will be created on the first agent-vm command here")
293 case inst.ConfigErr != nil:
294 d.line("fail", "Lima cannot read the config of "+name, inst.ConfigErr.Error(), "'agent-vm --reset <command>' re-clones it.")
295 default:
296 if e.staleState(name) == "1" {
297 d.line("warn", name+" was cloned from an older base template", "'agent-vm --reset <command>' re-clones it.")
298 } else {
299 d.line("ok", name+" exists")
300 }
301 confined := vm.Confined(inst)
302 switch {
303 case inst.Status == vm.Running && confined == nil:
304 d.line("ok", "running; the project share is enforced on the host (--readonly works)")
305 case inst.Status == vm.Running:
306 d.line("warn", "running with a share the host does not confine: "+confined.Error(),
307 "The next start (after 'agent-vm stop') sets its shares back.")
308 case inst.Orphaned:
309 d.line("warn", "running without Lima's host agent, cut off", "'agent-vm stop' stops it, and so does the next agent-vm command here that starts a VM.")
310 case inst.Status == vm.Broken:
311 d.line("warn", "Broken: Lima cannot say whether it runs")
312 default:
313 d.line("info", "stopped")
314 }
315 protected := len(inst.Mounts) > 0 && unprotected(inst, nil) == ""
316 current := unprotected(inst, names) == ""
317 switch {
318 case cageWritableGit() && !protected:
319 d.line("info", "its shares allow Git writes in Cage projects")
320 case protected && !current:
321 d.line("warn", "its shares keep .git read-only, but not all of "+strings.Join(names, ", "),
322 "The next start (after 'agent-vm stop' if it runs) fixes that.")
323 case protected:
324 d.line("ok", "its shares keep every .git read-only")
325 case !protects:
326 d.line("warn", "its shares leave .git writable (AGENT_VM_UNSAFE_WRITABLE_GIT=1)")
327 default:
328 d.line("warn", "its shares leave .git writable", "The next start (after 'agent-vm stop' if it runs) fixes that.")
329 }
330 }
331 for _, h := range scan.Hooks {
332 rel, inRepo, _ := strings.Cut(h, "\t")
333 if rel == "" {
334 continue
335 }
336 what := "git runs hooks from " + rel + " (core.hooksPath)"
337 switch {
338 case rel == ".":
339 what = "git runs hooks from the project directory itself (core.hooksPath)"
340 case inRepo == ".":
341 what = "git runs hooks from " + rel + ", which no read-only name covers (core.hooksPath)"
342 }
343 hn, ok := gitguard.HooksName(inRepo)
344 current := false
345 if inst != nil {
346 current = unprotected(inst, names) == ""
347 }
348 switch {
349 case !ok:
350 d.line("warn", what+", which the VM can write",
351 "agent-vm can only keep a folder inside a share read-only, by a name without quotes or backslashes: point core.hooksPath to one.")
352 case !protects:
353 d.line("warn", what+", which the VM can write", "agent-vm keeps it read-only when it keeps .git read-only (see above).")
354 case inst == nil:
355 d.line("info", fmt.Sprintf("%s: every '%s' in the project will be read-only for the VM", what, hn))
356 case current:
357 d.line("ok", fmt.Sprintf("%s: every '%s' in the project is read-only for the VM", what, hn))
358 default:
359 d.line("warn", what+", which the VM can still write",
360 fmt.Sprintf("The next start (after 'agent-vm stop' if it runs) makes every '%s' in the project read-only.", hn))
361 }
362 }
363 if risks := scan.Risks(names); len(risks) > 0 {
364 d.line("warn", "git on this machine uses these, and the VM can write them:",
365 append(risks, "Move them out of the shared folders, or have them name commands outside them.")...)
366 }
367 rt := runscript.ProjectPath(dir)
368 if rel, ok := env.ProjectRel(dir, rt); ok {
369 // Not by its path: the VM can make it a symlink.
370 if b, err := env.ReadIn(dir, rel); err == nil {
371 d.line("info", fmt.Sprintf("project runtime: %s (%s)", rt, runscript.Interpreter(string(b))))
372 }
373 } else if b, err := os.ReadFile(rt); err == nil {
374 d.line("info", fmt.Sprintf("project runtime: %s (%s)", rt, runscript.Interpreter(string(b))))
375 }
376 pe := env.ProjectEnvFile(dir)
377 if _, err := os.Stat(pe); err == nil {
378 var warn bytes.Buffer
379 saved := e.io.Stderr
380 e.io.Stderr = &warn
381 e.warnUnignored(ctx, pe)
382 e.io.Stderr = saved
383 if warn.Len() > 0 {
384 var hints []string
385 for _, l := range strings.Split(strings.TrimSuffix(warn.String(), "\n"), "\n") {
386 hints = append(hints, strings.TrimLeft(l, " "))
387 }
388 d.line("warn", "project env: "+pe, hints...)
389 } else {
390 d.line("ok", "project env: "+pe)
391 }
392 }
393}