mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
devvm agent import wrote each settings file into the store as it read it, so a file that failed to read partway (changed since it was listed, or past the bounds) left the store half replaced. The import now reads and writes every agent's settings into a staging folder of the agent's store first (.devvm-import-<random>, beside the agent's folder, so no VM mounts it), and only once all of them are staged, and the run isn't interrupted, moves each file into place, prunes what the home folder no longer has and then saves the logins. A failure or an interrupt while staging leaves the store as it was: the staging folder goes, through discard, or through a cleanup for an interrupted run, which reaches it by a root of its own. A failure after that (a rename, a login) can still leave the store partly replaced, which internals/agents.md says. A killed import's leftover staging folder counts as nothing of the agent's (inStore), so it never makes the import ask, and the next import of that agent takes it out first (sweepStages). The import's bounds on an agent's own folder now match devvm agent save's: the walk counts every entry it meets, links, sockets and FIFOs included, not only the folders and files it keeps, and a file of more than 16 MiB, as listed or as read, fails the import as the 128 MiB does. Claude Code's plugin records are copied with the store's longer paths, and what the copy grows counts against the same bounds (hostAgent.grew), naming the folder, or the link a file came through, so the store never gets more than the import checked. The two handles on an agent's folder, the os.Root it lists through and the folder opened one folder at a time that it reads through, are checked to be one folder (sameFolder), failing the import otherwise. A VM state the import can't read is a warning (agent_import_states_unread), naming the file, rather than silently dropping that VM from the project-inside warnings and the link checks; the follower takes the VMs the import read at its start instead of reading them again. state.WriteFileIn and writeFileMode share one tail (finishTemp). clearKind takes the root the import opened once, rather than opening the store for every path, and pruneStore's walk is pruneIn, which the import calls on the same root. Cursor's changing verbs (proxy's cursorChanges), checked again against the 1,463 methods of DashboardService, AutomationsService and BackgroundComposerService in 2026.11.17-f532c45, read and not run. generate goes: it matched only GenerateGrokCollectionDescription, which only returns a draft, and GenerateTeamGrokBotScimIdpSigningKey, which cursorCredential refuses anyway; no other method changes between refused and passed. test stays, justified in its comment: it matches TestAutomationFilter, a dry run that only reads, but also TestTeamCustomerTelemetryDestinationConnection, which has Cursor's servers send a request with any headers to any address. park, hand, decline, replace and resend match only methods that cursorCredential refuses too (as rotate, link and invite do), and stay, justified in the comment, for the methods Cursor adds. Every cursorRoutes path the CLI's login goes to is checked against the proxy by agentlogin's TestCursorCapture (proxy can't import agentlogin, which imports it); TestCursorChangingVerbs now says so. devvm agent login on a terminal saves the terminal's state before the login (ui.Terminal, through vm.Env.Terminal, which now returns a restore) and puts it back once the login and endLogin are done, or in a UI cleanup if the run ends first, so an ssh that a signal killed in raw mode doesn't leave the host terminal raw. Tests that fail without their fix: TestAgentImportFailsWhole (a failed import leaves the store's own files and no staging folder), TestAgentImportTooMuch (rewritten: its dead want field gone; exactly 20,000 entries and 128 MiB list whole, one more entry or byte fails, a link and a FIFO count, a file of 16 MiB and a byte fails), TestAgentImportPluginsGrow, TestSameFolder (the helper, and the import with its folder swapped between the two opens), TestAgentImportStageLeftover, TestAgentImportInterrupted (the ctx check before apply, and the interrupt cleanup on its own), TestAgentImportProjectInside (beside a broken state), TestCursorChangingVerbs (GenerateGrokCollectionDescription passes), TestAgentLoginTerminal (put back once, after the login ended, interrupted included), TestTerminalRestores. Tests that pin what already held: TestNarrowNotesBesideBroken (devvm network's -g allowlists beside a VM state that can't be read), TestWriteFileIn (a failed rename leaves no temporary file), and TestCursorChangingVerbs' TestTeamCustomerTelemetryDestinationConnection. The finder now checks fst with found, so nilaway no longer reports fst's flow, and all of fst's lines in its baseline go. Docs: using/coding-agents.md, internals/agents.md, internals/network.md; CHANGELOG. Co-Authored-By: Claude Opus 5.5 <[email protected]>
183 lines
6.5 KiB
Go
183 lines
6.5 KiB
Go
// Package state reads and writes the files devvm keeps its state in: each
|
|
// VM's state (vm.json), image and tool image records, rebuild counters and
|
|
// the cached --from digests.
|
|
//
|
|
// All of them are JSON only devvm writes (json.go): fields a reader
|
|
// doesn't know are ignored. Every write replaces the whole file atomically
|
|
// (a temporary file, then a rename), so a reader never sees half a file
|
|
// and reads take no lock; a VM's state changes under its lock (VM.Update). Files are private to the user (0600, or
|
|
// 0700 for a program devvm runs: WriteFileMode), and so are the folders
|
|
// devvm creates for them (0700: PrivateDir). Every file devvm writes
|
|
// whole goes through WriteFile or WriteFileMode, but for those of the
|
|
// packages that are the standard library only: internal/proxy's
|
|
// writeAtomic, and internal/daemon's pid and status files. A log a
|
|
// process writes as it runs, and a download, stream into their files.
|
|
package state
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/paths"
|
|
)
|
|
|
|
// CorruptError is a state file devvm can't read: edited by hand, or damaged.
|
|
type CorruptError struct {
|
|
Path string
|
|
Line int // 1-based; 0 when the problem isn't on one line
|
|
Reason string
|
|
// Msg is the reason's message, after Reason, when a check gave one
|
|
// (a value's: size_not_gib); the zero message when none did. It isn't
|
|
// unwrapped, so a failure shows the file and line around it.
|
|
Msg msg.M
|
|
}
|
|
|
|
func (e *CorruptError) Error() string { return e.Shown(msg.M.Text) }
|
|
|
|
// Shown is the error with its message as text shows it: the UI's Text,
|
|
// so names mode shows the message's names.
|
|
func (e *CorruptError) Shown(text func(msg.M) string) string {
|
|
reason := e.Reason
|
|
if e.Msg.ID() != "" {
|
|
reason += text(e.Msg)
|
|
}
|
|
if e.Line == 0 {
|
|
return fmt.Sprintf("%s: %s", e.Path, reason)
|
|
}
|
|
return fmt.Sprintf("%s:%d: %s", e.Path, e.Line, reason)
|
|
}
|
|
|
|
// MakePrivate makes devvm's data and config folders, and makes both the
|
|
// user's alone (mode 700) whatever mode they had, so nothing beneath them
|
|
// is open to others. Unlike PrivateDir, it follows a link there: where
|
|
// these two folders live is the user's choice, a dotfiles repo's say.
|
|
func MakePrivate(d paths.Dirs) error {
|
|
for _, dir := range []string{d.Data, d.Config} {
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Chmod(dir, 0o700); err != nil { //nolint:gosec // a folder: owner-only with search
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// PrivateDir makes the folder path, with any folders above it that are
|
|
// missing, and makes it the user's alone (mode 700) whatever mode it had.
|
|
// Anything at path but a folder, a link to one included, is refused, so
|
|
// the mode is never set on what a link points to.
|
|
func PrivateDir(path string) error {
|
|
if err := os.MkdirAll(path, 0o700); err != nil {
|
|
return err
|
|
}
|
|
fi, err := os.Lstat(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !fi.IsDir() {
|
|
return fmt.Errorf("%s isn't a folder", path)
|
|
}
|
|
if fi.Mode().Perm() != 0o700 {
|
|
return os.Chmod(path, 0o700) //nolint:gosec // a folder: owner-only with search
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// WriteFile replaces path with data atomically, readable only by the
|
|
// user, creating its folder (0700) when it's missing.
|
|
func WriteFile(path string, data []byte) error { return writeFile(path, data) }
|
|
|
|
// WriteFileMode replaces path with data atomically, as WriteFile does, with
|
|
// mode's permissions: 0o700 for a program devvm runs.
|
|
func WriteFileMode(path string, data []byte, mode os.FileMode) error {
|
|
return writeFileMode(path, data, mode.Perm())
|
|
}
|
|
|
|
// WriteFileIn replaces name, a path in root, with data atomically, with
|
|
// mode's permissions, as WriteFileMode does, making the folders on its way
|
|
// that aren't there (0700). Every step goes through root, so no link
|
|
// leads it out of root's folder, and a link at name itself is replaced,
|
|
// never followed.
|
|
func WriteFileIn(root *os.Root, name string, data []byte, mode os.FileMode) error {
|
|
dir := filepath.Dir(name)
|
|
if err := root.MkdirAll(dir, 0o700); err != nil {
|
|
return fmt.Errorf("writing %s: %w", name, err)
|
|
}
|
|
tmp := filepath.Join(dir, "."+filepath.Base(name)+".tmp-"+rand.Text())
|
|
f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
|
if err != nil {
|
|
return fmt.Errorf("writing %s: %w", name, err)
|
|
}
|
|
return finishTemp(f, data, mode.Perm(), name, func() error { return root.Rename(tmp, name) }, func() error { return root.Remove(tmp) })
|
|
}
|
|
|
|
// finishTemp is the end of every whole-file write: it writes data to f, a
|
|
// new temporary file of mode 600, gives it perm, syncs and closes it, and
|
|
// puts it in place (rename). On any failure it takes the temporary file
|
|
// out (remove) and names the file it was writing, name.
|
|
func finishTemp(f *os.File, data []byte, perm os.FileMode, name string, rename, remove func() error) error {
|
|
_, err := f.Write(data)
|
|
if err == nil && perm != 0o600 {
|
|
err = f.Chmod(perm)
|
|
}
|
|
if err == nil {
|
|
err = f.Sync()
|
|
}
|
|
if cerr := f.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err == nil {
|
|
err = rename()
|
|
}
|
|
if err != nil {
|
|
_ = remove() // the write's own error is the one to name
|
|
return fmt.Errorf("writing %s: %w", name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// writeFile replaces path with data atomically, mode 600, creating its
|
|
// folder (0700) when it's missing.
|
|
func writeFile(path string, data []byte) error { return writeFileMode(path, data, 0o600) }
|
|
|
|
// writeFileMode replaces path with data atomically, mode perm, creating
|
|
// its folder when it's missing as PrivateDir does (0700). A folder there
|
|
// keeps its mode: some, ~/.ssh say, are the user's, or a link to one.
|
|
func writeFileMode(path string, data []byte, perm os.FileMode) error {
|
|
dir := filepath.Dir(path)
|
|
if _, err := os.Lstat(dir); errors.Is(err, fs.ErrNotExist) {
|
|
if err := PrivateDir(dir); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
f, err := os.CreateTemp(dir, "."+filepath.Base(path)+".tmp-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tmp := f.Name() // CreateTemp makes it 600
|
|
return finishTemp(f, data, perm, path, func() error { return os.Rename(tmp, path) }, func() error { return os.Remove(tmp) })
|
|
}
|
|
|
|
// removeFile deletes path; a missing file is not an error.
|
|
func removeFile(path string) error {
|
|
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkName refuses a VM name or image key that isn't a plain file name.
|
|
func checkName(what, name string) error {
|
|
if name == "" || strings.HasPrefix(name, ".") || strings.ContainsAny(name, `/\`) {
|
|
return fmt.Errorf("invalid %s %q", what, name)
|
|
}
|
|
return nil
|
|
}
|