跳到主要内容

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

提交记录

Merge pull request #13 from aplainjane/fix/stale-running-record

fix: PID 被复用时不再把过期运行记录当成仍在运行 / Treat records with a reused PID as stale

作者
Shihao Li
时间
2026/11/09 23:45
提交
b581157
这个版本的全部文件

这是一个合并提交,下面是和第一个上一提交相比的改动。

新增internal/cage/process_start_darwin.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package cage
2新增:
3新增:import (
4新增: "fmt"
5新增:
6新增: "golang.org/x/sys/unix"
7新增:)
8新增:
9新增:func processStartToken(pid int) string {
10新增: if pid <= 0 {
11新增: return ""
12新增: }
13新增: p, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
14新增: if err != nil || p.Proc.P_pid != int32(pid) {
15新增: return ""
16新增: }
17新增: t := p.Proc.P_starttime
18新增: if t.Sec == 0 && t.Usec == 0 {
19新增: return ""
20新增: }
21新增: return fmt.Sprintf("%d.%06d", t.Sec, t.Usec)
22新增:}
新增internal/cage/process_start_linux.go+35 −0看文件
@@ -0,0 +1,35 @@
1新增:package cage
2新增:
3新增:import (
4新增: "bytes"
5新增: "os"
6新增: "strconv"
7新增: "strings"
8新增:)
9新增:
10新增:// Linux start times are clock ticks since boot, so the boot ID keeps a PID
11新增:// reused after a reboot from matching a record from the previous boot.
12新增:func processStartToken(pid int) string {
13新增: if pid <= 0 {
14新增: return ""
15新增: }
16新增: boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
17新增: if err != nil {
18新增: return ""
19新增: }
20新增: stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
21新增: if err != nil {
22新增: return ""
23新增: }
24新增: // The command name may contain spaces or parentheses; fields resume after
25新增: // the last ')'. starttime is field 22, the 20th after the name.
26新增: i := bytes.LastIndexByte(stat, ')')
27新增: if i < 0 {
28新增: return ""
29新增: }
30新增: fields := strings.Fields(string(stat[i+1:]))
31新增: if len(fields) < 20 {
32新增: return ""
33新增: }
34新增: return strings.TrimSpace(string(boot)) + ":" + fields[19]
35新增:}
新增internal/cage/process_start_other.go+5 −0看文件
@@ -0,0 +1,5 @@
1新增://go:build !windows && !linux && !darwin
2新增:
3新增:package cage
4新增:
5新增:func processStartToken(int) string { return "" }
修改internal/cage/process_windows.go+21 −1看文件
@@ -1,6 +1,10 @@
11package cage
22
3删除:import "golang.org/x/sys/windows"
3新增:import (
4新增: "strconv"
5新增:
6新增: "golang.org/x/sys/windows"
7新增:)
48
59func profileProcessAlive(pid int) bool {
610 h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
@@ -11,3 +15,19 @@ func profileProcessAlive(pid int) bool {
1115 var code uint32
1216 return windows.GetExitCodeProcess(h, &code) == nil && code == 259
1317}
18新增:
19新增:func processStartToken(pid int) string {
20新增: if pid <= 0 {
21新增: return ""
22新增: }
23新增: h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
24新增: if err != nil {
25新增: return ""
26新增: }
27新增: defer windows.CloseHandle(h)
28新增: var created, exited, kernel, user windows.Filetime
29新增: if windows.GetProcessTimes(h, &created, &exited, &kernel, &user) != nil {
30新增: return ""
31新增: }
32新增: return strconv.FormatInt(created.Nanoseconds(), 10)
33新增:}
修改internal/cage/profile.go+21 −6看文件
@@ -12,10 +12,28 @@ import (
1212
1313type runningProfile struct {
1414 PID int `json:"pid"`
15新增: Started string `json:"started,omitempty"`
1516 Fingerprint string `json:"fingerprint"`
1617 JobID string `json:"job_id,omitempty"`
1718}
1819
20新增:// ProcessStartMatches reports false only when pid now belongs to a process
21新增:// started at a different time than the record. After a reboot or crash the
22新增:// recorded PID can be reused by an unrelated process. Records from older
23新增:// versions carry no start time and an unreadable start time cannot prove
24新增:// reuse; both keep the previous PID-only behavior.
25新增:func ProcessStartMatches(pid int, started string) bool {
26新增: if started == "" {
27新增: return true
28新增: }
29新增: current := processStartToken(pid)
30新增: return current == "" || current == started
31新增:}
32新增:
33新增:func (r runningProfile) alive() bool {
34新增: return r.PID > 0 && profileProcessAlive(r.PID) && ProcessStartMatches(r.PID, r.Started)
35新增:}
36新增:
1937func (c Config) Fingerprint() string {
2038 c.ExitPolicy = c.ExitPolicy.Normalized()
2139 b, _ := json.Marshal(c)
@@ -34,7 +52,8 @@ func (c Config) RecordRunning(state, name string) error {
3452// RecordRunningAt records the network owner's identity in the runtime's real
3553// instance directory; container environments do not create Lima metadata.
3654func (c Config) RecordRunningAt(dir string) error {
37删除: b, _ := json.Marshal(runningProfile{PID: os.Getpid(), Fingerprint: c.Fingerprint(), JobID: os.Getenv(JobEnv)})
55新增: pid := os.Getpid()
56新增: b, _ := json.Marshal(runningProfile{PID: pid, Started: processStartToken(pid), Fingerprint: c.Fingerprint(), JobID: os.Getenv(JobEnv)})
3857 f, err := os.CreateTemp(dir, ".running-*")
3958 if err != nil {
4059 return err
@@ -71,11 +90,7 @@ func (c Config) CheckRunning(state string) error {
7190 if json.Unmarshal(b, &r) != nil {
7291 return errors.New("invalid running cage profile record")
7392 }
74删除: if r.PID < 1 {
75删除: continue
76删除: }
77删除: alive := profileProcessAlive(r.PID)
78删除: if alive && r.Fingerprint != c.Fingerprint() {
93新增: if r.alive() && r.Fingerprint != c.Fingerprint() {
7994 return fmt.Errorf("cage configuration changed while a VM is running; run cage stop before restarting")
8095 }
8196 }
修改internal/cage/profile_test.go+41 −0看文件
@@ -1,6 +1,7 @@
11package cage
22
33import (
4新增: "encoding/json"
45 "os"
56 "path/filepath"
67 "testing"
@@ -21,3 +22,43 @@ func TestConfigChangeRequiresStop(t *testing.T) {
2122 t.Fatal("running profile silently changed")
2223 }
2324}
25新增:
26新增:func TestRunningRecordRejectsReusedPID(t *testing.T) {
27新增: dir := t.TempDir()
28新增: instance := filepath.Join(dir, "lima", "test")
29新增: os.MkdirAll(instance, 0700)
30新增: c := DefaultConfig()
31新增: if err := c.RecordRunning(dir, "test"); err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: b, err := os.ReadFile(filepath.Join(instance, "cage-running.json"))
35新增: if err != nil {
36新增: t.Fatal(err)
37新增: }
38新增: var record runningProfile
39新增: if err := json.Unmarshal(b, &record); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: if record.Started == "" {
43新增: t.Skip("process start time is unavailable on this platform")
44新增: }
45新增: if !record.alive() {
46新增: t.Fatal("current owner was not recognized")
47新增: }
48新增: legacy := runningProfile{PID: record.PID}
49新增: if !legacy.alive() {
50新增: t.Fatal("legacy PID-only record was rejected")
51新增: }
52新增: reused := runningProfile{PID: record.PID, Started: record.Started + "0", Fingerprint: record.Fingerprint}
53新增: if reused.alive() {
54新增: t.Fatal("record from an earlier process with the same PID was treated as running")
55新增: }
56新增: b, _ = json.Marshal(reused)
57新增: if err := os.WriteFile(filepath.Join(instance, "cage-running.json"), b, 0600); err != nil {
58新增: t.Fatal(err)
59新增: }
60新增: c.Timezone = "Asia/Tokyo"
61新增: if err := c.CheckRunning(dir); err != nil {
62新增: t.Fatalf("stale record blocked a configuration change: %v", err)
63新增: }
64新增:}
修改internal/cage/storage.go+3 −2看文件
@@ -419,17 +419,18 @@ func stoppedStorage(source string) error {
419419 return err
420420 }
421421 var pid int
422新增: started := ""
422423 if name == "cage-running.json" {
423424 var record runningProfile
424425 err = json.Unmarshal(data, &record)
425删除: pid = record.PID
426新增: pid, started = record.PID, record.Started
426427 } else {
427428 pid, err = strconv.Atoi(strings.TrimSpace(string(data)))
428429 }
429430 if err != nil || pid < 1 {
430431 return fmt.Errorf("无法核验虚拟机进程记录 %s", name)
431432 }
432删除: if profileProcessAlive(pid) {
433新增: if profileProcessAlive(pid) && ProcessStartMatches(pid, started) {
433434 return fmt.Errorf("请先停止虚拟机 %s,再迁移环境", inst.Name())
434435 }
435436 }
修改internal/managedproxy/platform_windows.go+31 −2看文件
@@ -80,6 +80,11 @@ func stopWindowsCore(profile string) error {
8080 if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
8181 return os.Remove(path)
8282 }
83新增: if errors.Is(err, windows.ERROR_ACCESS_DENIED) && !recordedCoreRunning(record) {
84新增: // The core runs as the current user, so a PID that cannot be
85新增: // terminated now belongs to another account's process.
86新增: return removeStaleCore(profile, path)
87新增: }
8388 if err != nil {
8489 return err
8590 }
@@ -88,8 +93,10 @@ func stopWindowsCore(profile string) error {
8893 if err != nil {
8994 return err
9095 }
91删除: if !strings.EqualFold(filepath.Clean(image), filepath.Clean(record.Executable)) || created != record.Created {
92删除: return errors.New("代理进程身份已变化,未停止其他进程")
96新增: if !sameCore(record, image, created) {
97新增: // The recorded core exited and its PID was reused, typically after a
98新增: // reboot. Forget the stale record and leave the other process alone.
99新增: return removeStaleCore(profile, path)
93100 }
94101 var code uint32
95102 if err := windows.GetExitCodeProcess(handle, &code); err != nil {
@@ -111,6 +118,28 @@ func stopWindowsCore(profile string) error {
111118 return os.Remove(path)
112119}
113120
121新增:func sameCore(record windowsCoreRecord, image string, created int64) bool {
122新增: return strings.EqualFold(filepath.Clean(image), filepath.Clean(record.Executable)) && created == record.Created
123新增:}
124新增:
125新增:func recordedCoreRunning(record windowsCoreRecord) bool {
126新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, record.PID)
127新增: if err != nil {
128新增: return false
129新增: }
130新增: defer windows.CloseHandle(handle)
131新增: image, created, err := identifyCore(handle)
132新增: return err == nil && sameCore(record, image, created)
133新增:}
134新增:
135新增:func removeStaleCore(profile, path string) error {
136新增: _ = os.Remove(Socket(profile))
137新增: if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
138新增: return err
139新增: }
140新增: return nil
141新增:}
142新增:
114143func startWindowsCore(ctx context.Context, profile string, s Store) error {
115144 name, err := PhysicalInterface(ctx)
116145 if err != nil {
新增internal/managedproxy/platform_windows_test.go+36 −0看文件
@@ -0,0 +1,36 @@
1新增:package managedproxy
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "os"
6新增: "path/filepath"
7新增: "testing"
8新增:)
9新增:
10新增:// A PID reused after a reboot must neither be terminated nor block startup.
11新增:func TestStopWindowsCoreForgetsReusedPID(t *testing.T) {
12新增: exe, err := os.Executable()
13新增: if err != nil {
14新增: t.Fatal(err)
15新增: }
16新增: core := filepath.Join(filepath.Dir(exe), "mihomo.exe")
17新增: if err := os.WriteFile(core, []byte("placeholder"), 0700); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: t.Cleanup(func() { _ = os.Remove(core) })
21新增: for name, pid := range map[string]uint32{"same user": uint32(os.Getpid()), "system": 4} {
22新增: t.Run(name, func(t *testing.T) {
23新增: profile := t.TempDir()
24新增: b, _ := json.Marshal(windowsCoreRecord{PID: pid, Executable: core, Created: 1})
25新增: if err := Write(windowsCoreRecordPath(profile), b); err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: if err := stopWindowsCore(profile); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: if _, err := os.Lstat(windowsCoreRecordPath(profile)); !os.IsNotExist(err) {
32新增: t.Fatal("stale core record was kept")
33新增: }
34新增: })
35新增: }
36新增:}
修改internal/workbench/control_lifecycle.go+4 −2看文件
@@ -10,6 +10,7 @@ import (
1010 "path/filepath"
1111 "time"
1212
13新增: "github.com/sylvinus/agent-vm/internal/cage"
1314 "github.com/sylvinus/agent-vm/internal/containerenv"
1415 "github.com/sylvinus/agent-vm/internal/guestos"
1516 "github.com/sylvinus/agent-vm/internal/managedproxy"
@@ -170,12 +171,13 @@ func controllerVMOwners(profile string) ([]string, error) {
170171 return nil, err
171172 }
172173 var record struct {
173删除: PID int `json:"pid"`
174新增: PID int `json:"pid"`
175新增: Started string `json:"started"`
174176 }
175177 if json.Unmarshal(b, &record) != nil || record.PID <= 0 {
176178 return nil, errors.New("环境进程记录无效")
177179 }
178删除: if processExists(record.PID) {
180新增: if processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started) {
179181 owners = append(owners, fmt.Sprintf("%s/%d", filepath.Base(filepath.Dir(path)), record.PID))
180182 }
181183 }
修改internal/workbench/macos_guest.go+8 −2看文件
@@ -35,8 +35,14 @@ func macOSWorkbenchRoute(path string) bool {
3535
3636func macOSInstanceRunning(instanceDir string) bool {
3737 data, err := os.ReadFile(filepath.Join(instanceDir, "cage-running.json"))
38删除: var record struct{ PID int }
39删除: return err == nil && json.Unmarshal(data, &record) == nil && processExists(record.PID)
38新增: var record struct {
39新增: PID int `json:"pid"`
40新增: Started string `json:"started"`
41新增: }
42新增: if err != nil || json.Unmarshal(data, &record) != nil || record.PID < 1 {
43新增: return false
44新增: }
45新增: return processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started)
4046}
4147
4248func (s *Server) macOSSSHCommand(ctx context.Context, args ...string) *exec.Cmd {
新增internal/workbench/running_record_test.go+66 −0看文件
@@ -0,0 +1,66 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "os"
6新增: "path/filepath"
7新增: "testing"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/guestos"
10新增:)
11新增:
12新增:func TestVMRecordWithReusedPIDIsNotRunning(t *testing.T) {
13新增: for _, guest := range []string{"linux", "macos"} {
14新增: t.Run(guest, func(t *testing.T) {
15新增: s := testServer(t)
16新增: s.preferences.Workspace, _ = filepath.EvalSymlinks(t.TempDir())
17新增: if guest == "macos" {
18新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
19新增: }
20新增: dir := s.instanceDir()
21新增: if err := os.MkdirAll(dir, 0700); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: cfg, err := loadConfig(s.configPath)
25新增: if err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: if err := cfg.RecordRunningAt(dir); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: path := filepath.Join(dir, "cage-running.json")
32新增: var record map[string]any
33新增: b, _ := os.ReadFile(path)
34新增: if err := json.Unmarshal(b, &record); err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: started, _ := record["started"].(string)
38新增: if started == "" {
39新增: t.Skip("process start time is unavailable on this platform")
40新增: }
41新增: if !s.vmRunning() {
42新增: t.Fatal("current owner was not recognized")
43新增: }
44新增: if owners, err := controllerVMOwners(s.profile); err != nil || len(owners) != 1 {
45新增: t.Fatalf("owners = %v, %v", owners, err)
46新增: }
47新增: record["started"] = started + "0"
48新增: if err := writePrivate(path, record); err != nil {
49新增: t.Fatal(err)
50新增: }
51新增: if s.vmRunning() {
52新增: t.Fatal("record from an earlier process with the same PID was treated as running")
53新增: }
54新增: if owners, err := controllerVMOwners(s.profile); err != nil || len(owners) != 0 {
55新增: t.Fatalf("stale owners = %v, %v", owners, err)
56新增: }
57新增: delete(record, "started")
58新增: if err := writePrivate(path, record); err != nil {
59新增: t.Fatal(err)
60新增: }
61新增: if !s.vmRunning() {
62新增: t.Fatal("legacy PID-only record was rejected")
63新增: }
64新增: })
65新增: }
66新增:}
修改internal/workbench/runtime.go+3 −2看文件
@@ -697,12 +697,13 @@ func vmAlive(profile, workspace string) bool {
697697 return false
698698 }
699699 var record struct {
700删除: PID int `json:"pid"`
700新增: PID int `json:"pid"`
701新增: Started string `json:"started"`
701702 }
702703 if json.Unmarshal(b, &record) != nil || record.PID < 1 {
703704 return false
704705 }
705删除: return processExists(record.PID)
706新增: return processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started)
706707}
707708func (s *Server) vmRunning() bool {
708709 if s.windowsGuest != nil {