package main import ( "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "crypto/tls" "encoding/base64" "encoding/hex" "encoding/json" "errors" "flag" "fmt" "io" "log" "net" "net/http" "os" "os/exec" "os/signal" "path/filepath" "regexp" "runtime" "sort" "strconv" "strings" "sync" "syscall" "time" ) type File struct { Hash string `json:"hash"` TextHash string `json:"textHash,omitempty"` Data *string `json:"data,omitempty"` } type SyncRequest struct { Revision string `json:"revision"` Files map[string]File `json:"files"` Git *GitSnapshot `json:"git,omitempty"` } type Artifact struct { Name string `json:"name"` Hash string `json:"hash"` Size int64 `json:"size"` SourcePath string `json:"sourcePath,omitempty"` FileName string `json:"fileName,omitempty"` } type Build struct { JavaHome string `json:"javaHome,omitempty"` RequestID string `json:"clientRequestId,omitempty"` CreatedAt int64 `json:"createdAt"` Progress Progress `json:"progress"` Environment map[string]string `json:"environment,omitempty"` lastPersist time.Time ID string `json:"id"` Project string `json:"project"` Revision string `json:"revision"` Task string `json:"task"` Status string `json:"status"` Logs []string `json:"logs"` Artifacts []Artifact `json:"artifacts"` cmd *exec.Cmd cancelled bool } type Project struct { PrivateFiles map[string]File `json:"privateFiles,omitempty"` LegacyProject string `json:"legacyProject,omitempty"` Dedicated bool `json:"dedicated,omitempty"` Pending *PendingSync `json:"pending,omitempty"` WorkspacePath string `json:"workspacePath,omitempty"` Git *GitSnapshot `json:"git,omitempty"` Revision string `json:"revision"` Files map[string]File `json:"files"` Busy bool `json:"busy"` } type Server struct { mu sync.Mutex root, token string tasks map[string]bool projects map[string]*Project builds map[string]*Build workspaceRoot string workspaceRoots []string environmentFile string accessFile string accessLoaded bool } var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`) var safeTask = regexp.MustCompile(`^:?[A-Za-z0-9_]+(:[A-Za-z0-9_]+)*$`) func id() string { b := make([]byte, 16) if _, e := rand.Read(b); e != nil { panic(e) } return hex.EncodeToString(b) } func digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } func validPath(p string) bool { if p == "" || strings.ContainsAny(p, "\\:\x00<>\"|?*") || strings.HasPrefix(p, "/") { return false } for _, part := range strings.Split(p, "/") { if part == "" || part == "." || part == ".." || strings.TrimRight(part, ". ") != part { return false } base := strings.ToUpper(strings.Split(part, ".")[0]) if regexp.MustCompile(`^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$`).MatchString(base) { return false } } for _, part := range strings.Split(p, "/") { if reservedSource(part) { return false } } return true } func noLinks(root string) error { return filepath.WalkDir(root, func(p string, d os.DirEntry, e error) error { if e != nil { return e } if d.IsDir() && p != root && reservedSource(filepath.Base(p)) { return filepath.SkipDir } if d.Type()&os.ModeSymlink != 0 { return fmt.Errorf("symlink forbidden: %s", p) } return nil }) } func jsonOut(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(v) } func decode(w http.ResponseWriter, r *http.Request, v any) error { r.Body = http.MaxBytesReader(w, r.Body, 256<<20) d := json.NewDecoder(r.Body) d.DisallowUnknownFields() return d.Decode(v) } func (s *Server) work(p string) string { if pr := s.projects[p]; pr != nil && pr.WorkspacePath != "" && !pr.Dedicated { return pr.WorkspacePath } return filepath.Join(s.root, "projects", p, "work") } func (s *Server) save(p string) error { b, e := json.Marshal(s.projects[p]) if e != nil { return e } path := filepath.Join(s.root, "projects", p, "state.json") if e = os.WriteFile(path+".tmp", b, 0600); e != nil { return e } return os.Rename(path+".tmp", path) } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.token)) != 1 { http.Error(w, "unauthorized", 401) return } if r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs") { s.streamLogs(w, r) return } if strings.HasPrefix(r.URL.Path, "/api/v1/adb/") { s.serveADB(w, r) return } s.mu.Lock() defer s.mu.Unlock() if e := s.reloadAccessPolicy(); e != nil { http.Error(w, e.Error(), 503) return } parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") fail := func(e error) { http.Error(w, e.Error(), 400) } if r.URL.Path == "/api/v1/health" { jsonOut(w, map[string]any{"version": "0.7.0", "privateFileList": true, "remoteADB": true, "syncPreflight": true, "dedicatedGit": true, "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true}) return } if r.URL.Path == "/api/v1/environment" && r.Method == "GET" { cfg, e := s.buildEnvironment() if e != nil { fail(e) return } jsonOut(w, cfg.summary()) return } if r.URL.Path == "/api/v1/jdks" && r.Method == "GET" { s.jdks(w, r) return } if r.URL.Path == "/api/v1/private-files" { s.servePrivateFiles(w, r) return } if r.URL.Path == "/api/v1/directories" && r.Method == "GET" { s.browseDirectories(w, r) return } if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" { http.NotFound(w, r) return } if parts[2] == "projects" { if len(parts) == 4 && parts[3] == "check" && r.Method == "POST" { s.checkWorkspace(w, r) return } if len(parts) == 3 && r.Method == "POST" { s.createProject(w, r) return } if len(parts) != 5 || !safeID.MatchString(parts[3]) { http.NotFound(w, r) return } p := parts[3] pr := s.projects[p] if pr == nil { http.NotFound(w, r) return } if pr.WorkspacePath != "" && !(parts[4] == "builds" && r.Method == "GET") { if _, e := s.validateWorkspace(pr.WorkspacePath); e != nil { fail(e) return } } if parts[4] == "git" && r.Method == "POST" { s.importBundle(w, r, p) return } if parts[4] == "manifest" && r.Method == "GET" { jsonOut(w, s.manifest(p)) return } if parts[4] == "builds" && r.Method == "GET" { items := []*Build{} for _, b := range s.builds { if (b.Project == p || pr.LegacyProject != "" && b.Project == pr.LegacyProject) && (r.URL.Query().Get("clientRequestId") == "" || b.RequestID == r.URL.Query().Get("clientRequestId")) { items = append(items, b) } } sort.Slice(items, func(i, j int) bool { return items[i].CreatedAt > items[j].CreatedAt }) if len(items) > 50 { items = items[:50] } jsonOut(w, map[string]any{"builds": items}) return } if parts[4] == "sync" && r.Method == "POST" { if pr.Busy { http.Error(w, "workspace busy", 409) return } var req SyncRequest if e := decode(w, r, &req); e != nil { fail(e) return } if req.Revision == "" || req.Files == nil { fail(errors.New("revision and files required")) return } if pr.Dedicated { names, err := s.privateNames(p) if err != nil { fail(err) return } for _, name := range names { if privateConflict(req.Files, name) { fail(fmt.Errorf("私有文件与普通源码同步冲突:%s;请在本机忽略该文件", name)) return } } for name := range pr.PrivateFiles { if privateConflict(req.Files, name) { fail(fmt.Errorf("私有文件仍在工作区:%s;请先完成清单移除后的构建清理", name)) return } } } if e := s.checkGit(p, req.Git); e != nil { http.Error(w, e.Error(), 409) return } if e := noLinks(s.work(p)); e != nil { fail(e) return } staged := map[string][]byte{} seen := map[string]bool{} components := map[string]string{} for path, f := range req.Files { key := strings.ToLower(path) if !validPath(path) || seen[key] { fail(fmt.Errorf("invalid or colliding path: %s", path)) return } seen[key] = true segments := strings.Split(path, "/") for i := range segments { prefix := strings.Join(segments[:i+1], "/") lower := strings.ToLower(prefix) if previous, ok := components[lower]; ok && previous != prefix { fail(fmt.Errorf("inconsistent path casing: %s", path)) return } components[lower] = prefix } if f.Data != nil { b, e := base64.StdEncoding.DecodeString(*f.Data) if e != nil || digest(b) != f.Hash { fail(fmt.Errorf("hash mismatch: %s", path)) return } staged[path] = b } else { b, e := os.ReadFile(filepath.Join(s.work(p), filepath.FromSlash(path))) if e != nil || digest(b) != f.Hash { fail(fmt.Errorf("missing content: %s", path)) return } } } for path := range req.Files { segments := strings.Split(path, "/") for i := 1; i < len(segments); i++ { if seen[strings.ToLower(strings.Join(segments[:i], "/"))] { fail(fmt.Errorf("file/directory collision: %s", path)) return } } } previousFiles, baseErr := s.syncBase(p) if baseErr != nil { fail(baseErr) return } // Validate the entire request before touching the working tree. Invalidate first: // an interrupted commit must never permit building a mixed source revision. pr.Revision = "" if pr.Dedicated { journal := map[string]File{} for path, f := range req.Files { journal[path] = File{Hash: f.Hash} } pr.Pending = &PendingSync{Files: journal} } if e := s.save(p); e != nil { fail(e) return } if pr.Dedicated { if e := s.advanceDedicated(p, req.Git); e != nil { fail(e) return } } for path := range previousFiles { if _, ok := req.Files[path]; !ok && validPath(path) { if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) { fail(e) return } } } for path, b := range staged { dest := filepath.Join(s.work(p), filepath.FromSlash(path)) if e := os.MkdirAll(filepath.Dir(dest), 0700); e != nil { fail(e) return } if e := os.WriteFile(dest, b, 0600); e != nil { fail(e) return } } pr.Files = map[string]File{} for path, f := range req.Files { actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))) if e != nil || actual.Hash != f.Hash { fail(fmt.Errorf("source changed during sync: %s", path)) return } pr.Files[path] = actual } pr.Revision = req.Revision pr.Git = req.Git pr.Pending = nil if e := s.save(p); e != nil { pr.Revision = "" fail(e) return } jsonOut(w, pr) return } if parts[4] == "builds" && r.Method == "POST" { var req struct { Revision string `json:"revision"` Task string `json:"task"` RequestID string `json:"clientRequestId"` JavaHome string `json:"javaHome,omitempty"` } if e := decode(w, r, &req); e != nil { fail(e) return } if !safeTask.MatchString(req.Task) { fail(errors.New("任务名不合法:只允许单个 Gradle 任务,不允许命令行参数")) return } if !s.taskAllowed(req.Task) { fail(fmt.Errorf("task not allowed:服务端尚未允许任务 %s\n请在服务器本机以管理员权限执行:\n%s\n也可将精确任务名替换为限定模块的 :app:assemble* 规则;保存后无需重启", req.Task, s.adminCommand("task", req.Task))) return } if req.RequestID != "" { if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`).MatchString(req.RequestID) { fail(errors.New("invalid clientRequestId")) return } for _, old := range s.builds { if old.Project == p && old.RequestID == req.RequestID { if old.Task != req.Task || old.Revision != req.Revision || old.JavaHome != req.JavaHome { http.Error(w, "request ID already used with different parameters", 409) return } jsonOut(w, old) return } } } if pr.Busy || req.Revision == "" || pr.Revision != req.Revision { http.Error(w, "busy or revision mismatch", 409) return } if pr.WorkspacePath != "" { if e := s.checkGit(p, pr.Git); e != nil { http.Error(w, e.Error(), 409) return } var actual map[string]File var e error if pr.Dedicated { actual, e = s.projectInventory(p) } else { actual, e = sourceInventory(s.work(p)) } if e != nil { fail(e) return } if !sameSourceHashes(pr.Files, actual) { http.Error(w, "source changed after sync; sync again", 409) return } } javaHome, jdkErr := s.selectedJDK(req.JavaHome) if jdkErr != nil { fail(jdkErr) return } b := &Build{JavaHome: javaHome, ID: id(), Project: p, Revision: req.Revision, Task: req.Task, RequestID: req.RequestID, CreatedAt: time.Now().UnixMilli(), Status: "queued", Logs: []string{}, Artifacts: []Artifact{}} if e := s.persistBuild(b); e != nil { fail(e) return } if e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil { fail(e) return } s.builds[b.ID] = b pr.Busy = true go s.run(b) jsonOut(w, b) return } } if parts[2] == "builds" && len(parts) >= 4 { b := s.builds[parts[3]] if b == nil { http.NotFound(w, r) return } if len(parts) == 4 && r.Method == "GET" { jsonOut(w, b) return } if len(parts) == 4 && r.Method == "DELETE" { if b.Status == "queued" || b.Status == "running" { b.cancelled = true if b.cmd != nil && b.cmd.Process != nil { killTree(b.cmd) } } jsonOut(w, b) return } if len(parts) == 6 && parts[4] == "artifacts" && r.Method == "GET" { for _, a := range b.Artifacts { if a.Name == parts[5] { s.mu.Unlock() http.ServeFile(w, r, filepath.Join(s.root, "artifacts", b.ID, a.Name)) s.mu.Lock() return } } } } http.NotFound(w, r) } func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") if len(parts) != 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "builds" { http.NotFound(w, r) return } offset, _ := strconv.Atoi(r.Header.Get("Last-Event-ID")) if offset < 0 { offset = 0 } s.mu.Lock() b := s.builds[parts[3]] s.mu.Unlock() if b == nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") ticker := time.NewTicker(400 * time.Millisecond) defer ticker.Stop() for { s.mu.Lock() lines := append([]string{}, b.Logs...) terminal := b.Status != "queued" && b.Status != "running" s.mu.Unlock() for offset < len(lines) { if _, e := fmt.Fprintf(w, "id: %d\ndata: %s\n\n", offset+1, mustJSON(lines[offset])); e != nil { return } offset++ } if f, ok := w.(http.Flusher); ok { f.Flush() } if terminal { return } select { case <-r.Context().Done(): return case <-ticker.C: } } } func isOutputAPK(work, p string) bool { rel, e := filepath.Rel(work, p) if e != nil { return false } return strings.Contains("/"+filepath.ToSlash(rel), "/build/outputs/") && strings.HasSuffix(strings.ToLower(p), ".apk") } func mustJSON(v any) string { b, _ := json.Marshal(v); return string(b) } type buildWriter struct { s *Server b *Build } func (w buildWriter) Write(p []byte) (int, error) { w.s.mu.Lock() defer w.s.mu.Unlock() w.b.Logs = append(w.b.Logs, string(p)) if time.Since(w.b.lastPersist) > time.Second { _ = w.s.persistBuild(w.b) } return len(p), nil } func (s *Server) run(b *Build) { s.mu.Lock() if b.cancelled { b.Status = "cancelled" s.projects[b.Project].Busy = false _ = s.persistBuild(b) os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) s.mu.Unlock() return } b.Status = "running" source := s.projects[b.Project].WorkspacePath b.Progress = Progress{Phase: "preparing", Message: "正在检测工具版本、缓存及系统代理", Percent: -1} _ = s.persistBuild(b) s.mu.Unlock() work := s.work(b.Project) cfg, configErr := s.buildEnvironment() if configErr != nil { s.finishFailed(b, configErr) return } if b.JavaHome != "" { cfg.JavaHome = b.JavaHome } if e := s.prepareWorkspaceFiles(b.Project, cfg); e != nil { s.finishFailed(b, e) return } report := s.preflight(work, cfg) s.explainWrapper(&report, work, source, false) for _, item := range report.Items { buildWriter{s, b}.Write([]byte(fmt.Sprintf("环境检查 [%s] %s:%s [%s]\n", item.Status, item.Name, item.Message, item.Path))) } if checkErr := report.failure(); checkErr != nil { s.finishFailed(b, checkErr) return } // Remove old APKs only. Retain compilation caches and all other Gradle outputs. err := noLinks(work) if err == nil { err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error { if e != nil { return e } if !d.IsDir() && isOutputAPK(work, p) { return os.Remove(p) } return nil }) } if err == nil { cmd, info, prepErr := s.prepareCommand(work, b.Task, cfg) if prepErr != nil { s.finishFailed(b, prepErr) return } s.mu.Lock() b.Environment = info b.Progress = Progress{Phase: "building", Message: "执行项目 Wrapper,准备 Gradle 分发包", Path: info["distributionFile"], Percent: -1} if info["execution"] == "installed-gradle" { b.Progress.Message = "已复用 Gradle " + info["requestedGradleVersion"] + ";正在构建" b.Progress.Path = info["executable"] } _ = s.persistBuild(b) s.mu.Unlock() buildWriter{s, b}.Write([]byte("构建环境: " + mustJSON(info) + "\n")) cmd.Dir = work cmd.Env = cfg.environ() cmd.Stdout = buildWriter{s, b} cmd.Stderr = cmd.Stdout s.mu.Lock() b.cmd = cmd if b.cancelled { err = errors.New("cancelled") } else { err = cmd.Start() } s.mu.Unlock() if err == nil { stopProgress := make(chan struct{}) go s.monitorDistribution(b, work, cfg, stopProgress) done := make(chan error, 1) go func() { done <- cmd.Wait() }() select { case err = <-done: case <-time.After(30 * time.Minute): killTree(cmd) err = <-done if err == nil { err = errors.New("build timeout") } } close(stopProgress) } } artifacts := []Artifact{} if err == nil { err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error { if e != nil { return e } if d.IsDir() || !isOutputAPK(work, p) { return nil } data, e := os.ReadFile(p) if e != nil { return e } name := fmt.Sprintf("%d-%s", len(artifacts), filepath.Base(p)) dest := filepath.Join(s.root, "artifacts", b.ID) if e = os.MkdirAll(dest, 0700); e != nil { return e } if e = os.WriteFile(filepath.Join(dest, name), data, 0600); e != nil { return e } artifacts = append(artifacts, Artifact{Name: name, Hash: digest(data), Size: int64(len(data)), SourcePath: artifactSourcePath(work, p), FileName: filepath.Base(p)}) return nil }) } s.mu.Lock() defer s.mu.Unlock() b.cmd = nil b.Progress.Phase = "finished" b.Artifacts = artifacts b.Status = "success" if len(artifacts) == 0 && err == nil { err = errors.New("no APK produced") } if err != nil { b.Status = "failed" b.Logs = append(b.Logs, err.Error()) } if b.cancelled { b.Status = "cancelled" } s.projects[b.Project].Busy = false _ = s.persistBuild(b) os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) } func main() { if len(os.Args) > 1 && os.Args[1] == "admin" { if e := runAdmin(os.Args[2:], os.Stdout); e != nil && e != flag.ErrHelp { log.Fatal(e) } return } addr := flag.String("listen", "127.0.0.1:8765", "HTTP bind address; use HTTPS proxy or SSH tunnel remotely") root := flag.String("data", "./data", "service data directory") tasks := flag.String("tasks", ":app:assembleDebug", "comma separated allowed Gradle tasks") cert := flag.String("tls-cert", "", "PEM certificate path") key := flag.String("tls-key", "", "PEM private key path") initHost := flag.String("init-tls-host", "", "generate a local certificate for this IP/hostname and exit") tlsDir := flag.String("tls-dir", "./tls", "certificate output directory") var workspaceRoots workspaceRootFlags flag.Var(&workspaceRoots, "workspace-root", "allowed existing-project root; repeat for multiple roots; defaults to data/projects") environmentFile := flag.String("environment-file", "", "trusted build environment JSON; reloaded for each build") accessFile := flag.String("access-file", "", "runtime access policy; defaults to /access.json; CLI edits apply without restart") flag.Parse() if *initHost != "" { if e := initCertificate(*initHost, *tlsDir); e != nil { log.Fatal(e) } return } if (*cert == "") != (*key == "") { log.Fatal("tls-cert and tls-key must be provided together") } host, _, e := net.SplitHostPort(*addr) if e != nil { log.Fatal(e) } if *cert == "" && host != "localhost" && (net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback()) { log.Fatal("non-loopback listeners require TLS") } token := os.Getenv("REMOTE_BUILD_TOKEN") if len(token) < 24 { log.Fatal("REMOTE_BUILD_TOKEN must contain at least 24 characters") } abs, e := filepath.Abs(*root) if e != nil { log.Fatal(e) } s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}} s.environmentFile = *environmentFile s.workspaceRoots = []string(workspaceRoots) if len(s.workspaceRoots) > 0 { s.workspaceRoot = s.workspaceRoots[0] } else { s.workspaceRoot = filepath.Join(abs, "projects") } for _, t := range strings.Split(*tasks, ",") { if !safeTask.MatchString(t) { log.Fatal("invalid task") } s.tasks[t] = true } policyPath := *accessFile if policyPath == "" { policyPath = filepath.Join(abs, "access.json") } policyPath, e = filepath.Abs(policyPath) if e != nil { log.Fatal(e) } if e = s.initAccessPolicy(policyPath); e != nil { log.Fatal(e) } entries, _ := os.ReadDir(filepath.Join(abs, "projects")) for _, entry := range entries { if !safeID.MatchString(entry.Name()) { continue } data, e := os.ReadFile(filepath.Join(abs, "projects", entry.Name(), "state.json")) if e != nil { continue } var p Project if json.Unmarshal(data, &p) == nil { if p.WorkspacePath != "" { if _, e := s.validateWorkspace(p.WorkspacePath); e != nil { log.Printf("workspace %s unavailable under current root (history retained): %v", entry.Name(), e) } } s.projects[entry.Name()] = &p } } entries, _ = os.ReadDir(filepath.Join(abs, "artifacts")) for _, entry := range entries { data, e := os.ReadFile(filepath.Join(abs, "artifacts", entry.Name(), "build.json")) if e != nil { continue } var b Build if json.Unmarshal(data, &b) == nil { if b.CreatedAt == 0 { if info, e := os.Stat(filepath.Join(abs, "artifacts", entry.Name(), "build.json")); e == nil { b.CreatedAt = info.ModTime().UnixMilli() } } s.builds[b.ID] = &b } } s.recoverBuilds() log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS) srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second} srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt, syscall.SIGTERM) go func() { <-stop s.mu.Lock() for _, b := range s.builds { if b.Status == "running" || b.Status == "queued" { b.cancelled = true if b.cmd != nil { killTree(b.cmd) } } } s.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() srv.Shutdown(ctx) }() serve := srv.ListenAndServe if *cert != "" { serve = func() error { return srv.ListenAndServeTLS(*cert, *key) } } if e := serve(); e != nil && e != http.ErrServerClosed { log.Fatal(e) } // Let workers persist terminal state and clear their active markers. deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { s.mu.Lock() busy := false for _, p := range s.projects { busy = busy || p.Busy } s.mu.Unlock() if !busy { return } time.Sleep(50 * time.Millisecond) } } var _ io.Writer = buildWriter{}