diff --git a/README.md b/README.md index fe106fa..c6fb470 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,33 @@ atlas-cli status # what was captured, what synced, what agents remember `atlas-cli settings` changes any of it later on one screen: account, capture and memory, each agent, background sync, the local model, updates. +### One folder, several repositories + +When a project is a folder of repositories, each with its own git: + +``` +acme-shop/ ← atlas-cli init here, once +├── frontend/ (git) +└── backend/ (git) +``` + +run `atlas-cli init --workspace` in `acme-shop/`. On a terminal, plain +`atlas-cli init` asks, with "This folder only" pre-selected; a folder already +bound alone becomes a workspace with `atlas-cli workspace on`. Agents started +in `frontend/` or `backend/` then record into the one Project and share one +memory, and the agent hooks are installed in every repository. A workspace is +never made by default: it captures every repository below it. A repository +cloned in later is part of the workspace at once; `atlas-cli workspace sync` +hooks it. A repository with its own `atlas-cli init` is split off as its own +Project. + +| command | does | +|---|---| +| `atlas-cli workspace` | lists the workspace's folders and which agents are hooked in each | +| `atlas-cli workspace sync` | hooks folders added since, with the agents the workspace folder uses | +| `atlas-cli workspace on` / `off` | turns an already bound folder into a workspace, or back | +| `atlas-cli workspace add ` / `remove ` | a folder without git (or a repository deeper down) joins or leaves | + ## Shared memory Every agent in the project reads and writes one memory, through the diff --git a/cmd/atlas-cli/agents_cmds.go b/cmd/atlas-cli/agents_cmds.go index d18b286..b3a520c 100644 --- a/cmd/atlas-cli/agents_cmds.go +++ b/cmd/atlas-cli/agents_cmds.go @@ -105,36 +105,54 @@ func runAgentsAdd(cmd *cobra.Command, args []string) error { } // installAgents writes the git hook, then each agent's hook and memory entry, -// one line per agent. +// one line per agent. In a workspace each member repository gets them too, so +// an agent started in any of them records into the workspace (ADR-0015). func installAgents(ctx context.Context, out io.Writer, root string, agents []hooks.Agent, force, noMem bool) error { - if changed, err := hooks.InstallGitHooks(ctx, root); err != nil { - return fmt.Errorf("git hooks: %w", err) - } else if changed { + targets := project.Targets(root) + gitChanged := false + for _, t := range targets { + changed, err := hooks.InstallGitHooks(ctx, t) + if err != nil { + return fmt.Errorf("git hooks in %s: %w", t, err) + } + gitChanged = gitChanged || changed + } + if gitChanged { fmt.Fprintln(out, "Installed the git post-commit hook (links sessions to commits).") } for _, a := range agents { - changed, err := a.Install(root, force) - if err != nil { - return fmt.Errorf("%s: %w", a.ID(), err) + changed, mchanged := false, false + w, hasMem := mcpconfig.For(a.ID()) + for _, t := range targets { + c, err := a.Install(t, force) + if err != nil { + return fmt.Errorf("%s in %s: %w", a.ID(), t, err) + } + changed = changed || c + if hasMem && !noMem { + mc, err := w.Write(t) + if err != nil { + return fmt.Errorf("%s memory config in %s: %w", a.ID(), t, err) + } + mchanged = mchanged || mc + } } what := "already installed" if changed { what = "installed" } line := fmt.Sprintf("%s: hook %s", a.Name(), what) - if w, ok := mcpconfig.For(a.ID()); ok && !noMem { - mchanged, err := w.Write(root) - if err != nil { - return fmt.Errorf("%s memory config: %w", a.ID(), err) - } - if mchanged { - line += ", memory server added to " + strings.TrimPrefix(w.Path(root), root+"/") - } else { - line += ", memory server present" - } - } else if !ok && !noMem { + switch { + case hasMem && !noMem && mchanged: + line += ", memory server added to " + strings.TrimPrefix(w.Path(root), root+"/") + case hasMem && !noMem: + line += ", memory server present" + case !noMem: line += " (no memory config writer for this agent yet)" } + if n := len(targets) - 1; n > 0 { + line += " (workspace folder and " + repos(n) + ")" + } fmt.Fprintln(out, line) if _, err := exec.LookPath(a.Binary()); err != nil { fmt.Fprintf(out, " note: %s is not on PATH here\n", a.Binary()) @@ -182,29 +200,39 @@ func agentLines(w io.Writer) io.Writer { } // removeAgents takes the Atlas entries out of each agent's config, and the -// git hook once no agent is left. +// git hook once no agent is left, in every member repository of a workspace. func removeAgents(ctx context.Context, out io.Writer, root string, agents []hooks.Agent) error { + targets := project.Targets(root) for _, a := range agents { - if err := a.Uninstall(root); err != nil { - return fmt.Errorf("%s: %w", a.ID(), err) - } - if w, ok := mcpconfig.For(a.ID()); ok { - if err := w.Remove(root); err != nil { - return fmt.Errorf("%s memory config: %w", a.ID(), err) + for _, t := range targets { + if err := a.Uninstall(t); err != nil { + return fmt.Errorf("%s in %s: %w", a.ID(), t, err) + } + if w, ok := mcpconfig.For(a.ID()); ok { + if err := w.Remove(t); err != nil { + return fmt.Errorf("%s memory config in %s: %w", a.ID(), t, err) + } } } fmt.Fprintf(out, "%s: Atlas hook and memory entry removed.\n", a.Name()) } - left := false - for _, a := range hooks.All() { - if a.State(root) != hooks.Absent { - left = true + removed := false + for _, t := range targets { + left := false + for _, a := range hooks.All() { + if a.State(t) != hooks.Absent { + left = true + } } - } - if !left { - if err := hooks.UninstallGitHooks(ctx, root); err != nil { + if left || hooks.GitHooksState(ctx, t) == hooks.Absent { + continue + } + if err := hooks.UninstallGitHooks(ctx, t); err != nil { return err } + removed = true + } + if removed { fmt.Fprintln(out, "No agent left: the git post-commit hook was removed too.") } return nil @@ -377,7 +405,7 @@ func printAgents(ctx context.Context, w io.Writer, root string) { return } fmt.Fprintf(w, "Agents: %s\n", strings.Join(on, ", ")) - if hooks.GitHooksState(ctx, root) != hooks.Current { + if project.InRepo(ctx, root) && hooks.GitHooksState(ctx, root) != hooks.Current { fmt.Fprintln(w, "Git hook: post-commit not installed (atlas-cli agents add installs it)") } if states, _ := hooks.ListStates(root, ""); len(states) > 0 { diff --git a/cmd/atlas-cli/commands.go b/cmd/atlas-cli/commands.go index 347e5f3..13277e3 100644 --- a/cmd/atlas-cli/commands.go +++ b/cmd/atlas-cli/commands.go @@ -52,6 +52,7 @@ func newRootCmd() *cobra.Command { newUninstallCmd(), withRun(leaf("status", "Show login, organisation, Project, gates, capture health and agent integrations", cobra.NoArgs), runStatus), newAgentsCmd(), + newWorkspaceCmd(), newHooksCmd(), newACPCmd(), newMCPBridgeCmd(), @@ -65,7 +66,7 @@ var splashGroups = []struct { cmds []string }{ {"Start", []string{"login", "init", "status", "settings"}}, - {"Agents", []string{"agents", "sync"}}, + {"Agents", []string{"agents", "workspace", "sync"}}, {"Memory and capture", []string{"memory", "capture"}}, {"Account", []string{"whoami", "org", "logout", "update", "uninstall"}}, } @@ -138,6 +139,7 @@ func newInitCmd() *cobra.Command { c.Flags().StringSlice("agents", nil, "hook these agents (comma-separated ids, atlas-cli agents list); skips the agent step") c.Flags().Bool("all-agents", false, "hook every agent detected on this machine; skips the agent step") c.Flags().String("sync", "", "background sync: on or off (atlas-cli sync); skips the sync step") + c.Flags().Bool("workspace", false, "bind this folder of repositories once: agents started in each repository record here (off unless given; asked on a terminal)") c.MarkFlagsMutuallyExclusive("agents", "all-agents") c.MarkFlagsMutuallyExclusive("project", "create") c.MarkFlagsMutuallyExclusive("local", "project") diff --git a/cmd/atlas-cli/init_wizard.go b/cmd/atlas-cli/init_wizard.go index 514f759..1761792 100644 --- a/cmd/atlas-cli/init_wizard.go +++ b/cmd/atlas-cli/init_wizard.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "os/exec" + "path/filepath" "strings" "github.com/spf13/cobra" @@ -54,7 +55,7 @@ func finishInit(cmd *cobra.Command, root string, local, guided bool, steps initS } } model := false - if guided && !embed.Available() && project.MemorySharing(project.ScopeRoot(cmd.Context(), root)) { + if guided && !embed.Available() && project.MemorySharing(project.MemoryRoot(cmd.Context(), root)) { i, err := chooseStep(steps.step("Memory search"), "Download the memory search model? Agents then find memories by meaning, not only by words.", []tui.Choice{ {Label: "Download", Detail: embed.Size + ", once; the same model the Atlas app uses"}, {Label: "Not now", Detail: "keyword search; atlas-cli memory index downloads it later"}, @@ -82,7 +83,7 @@ func finishInit(cmd *cobra.Command, root string, local, guided bool, steps initS // On a terminal the work runs under the progress bar, each line a step. if model { fmt.Fprintln(out) - scope := project.ScopeRoot(cmd.Context(), root) + scope := project.MemoryRoot(cmd.Context(), root) if err := tui.WorkProgress(out, "Setting up memory search", func(step tui.StepFunc, frac tui.FracFunc) (string, error) { return indexMemory(cmd.Context(), root, scope, true, step, frac) }); err != nil { @@ -223,3 +224,79 @@ func pickSync(cmd *cobra.Command, root string, guided bool, step tui.Step) (on, } return i == 0, true, nil } + +// pickWorkspace decides whether the launch dir is bound as a workspace, a +// folder of repositories bound once (ADR-0015). A workspace captures every +// repository below it, so it is opt-in: --workspace when given; else, for a +// folder outside git that holds repositories, asked on a terminal with "This +// folder only" pre-selected, and never without one (init names the +// repositories and how to capture them). A folder that is already a +// workspace stays one unless --workspace=false or the prompt says otherwise. +func pickWorkspace(cmd *cobra.Command, launch, scope string, guided bool) (bool, error) { + flags := cmd.Flags() + members := project.Members(launch) + names := memberNames(launch, members) + if flags.Changed("workspace") { + if on, _ := flags.GetBool("workspace"); !on { + return false, nil + } + if launch != scope { + return false, fmt.Errorf("%s is inside the repository %s; a workspace is the folder that holds the repositories", launch, scope) + } + if len(members) == 0 { + return false, fmt.Errorf("%s holds no git repository; a workspace is a folder of repositories", launch) + } + if !guided { + fmt.Fprintf(cmd.ErrOrStderr(), "Binding %s as a workspace of %s (%s).\n", launch, repos(len(members)), names) + } + return true, nil + } + current := project.IsWorkspace(launch) + if len(members) == 0 || (!current && project.InRepo(cmd.Context(), launch)) { + return current, nil + } + if !guided { + if !current { + fmt.Fprintf(cmd.ErrOrStderr(), "Note: %s holds %s (%s). Agents started in them are not captured; atlas-cli workspace on captures them here.\n", + launch, repos(len(members)), names) + } + return current, nil + } + initial := 0 + if current { + initial = 1 + } + i, err := chooseStep(tui.Step{Title: "Workspace"}, fmt.Sprintf("This folder holds %s: %s.", repos(len(members)), names), []tui.Choice{ + {Label: "This folder only", Detail: "agents started in those repositories are not captured here"}, + {Label: "Workspace", Detail: "agents started in any of them record here and share one memory"}, + }, initial) + if err != nil { + return false, err + } + return i == 1, nil +} + +// memberNames lists member repositories by folder name, at most five. +func memberNames(root string, members []string) string { + var names []string + for i, m := range members { + if i == 5 { + names = append(names, fmt.Sprintf("and %d more", len(members)-5)) + break + } + rel, err := filepath.Rel(root, m) + if err != nil { + rel = filepath.Base(m) + } + names = append(names, rel) + } + return strings.Join(names, ", ") +} + +// repos is "1 repository" or "n repositories". +func repos(n int) string { + if n == 1 { + return "1 repository" + } + return fmt.Sprintf("%d repositories", n) +} diff --git a/cmd/atlas-cli/main_test.go b/cmd/atlas-cli/main_test.go index 0a8be73..c7c6c42 100644 --- a/cmd/atlas-cli/main_test.go +++ b/cmd/atlas-cli/main_test.go @@ -24,6 +24,10 @@ func TestMain(m *testing.M) { state, _ := os.MkdirTemp("", "atlas-state-") // never the user's CLI state _ = os.Setenv("XDG_STATE_HOME", state) _ = os.Setenv("ATLAS_MODELS_DIR", state) // no embedding model: deterministic + // Never the user's Projects: a test that does not chdir must not find a + // binding (or a workspace) above the source tree. + cwd, _ := os.MkdirTemp("", "atlas-cwd-") + _ = os.Chdir(cwd) os.Exit(m.Run()) } @@ -73,6 +77,12 @@ var wantCommands = []string{ "uninstall", "update", "whoami", + "workspace", + "workspace add", + "workspace off", + "workspace on", + "workspace remove", + "workspace sync", } // allCommands is wantCommands plus one hooks entry point per registered @@ -118,6 +128,7 @@ var implemented = map[string]bool{ "settings": true, "sync": true, "update": true, "uninstall": true, "memory index": true, "memory compute": true, "agents add": true, "agents list": true, "agents remove": true, "agents sessions": true, "hooks extract": true, "hooks git post-commit": true, + "workspace": true, "workspace on": true, "workspace off": true, "workspace sync": true, "workspace add": true, "workspace remove": true, } func TestStubsReportNotImplemented(t *testing.T) { diff --git a/cmd/atlas-cli/memory_cmds.go b/cmd/atlas-cli/memory_cmds.go index 7fbe078..789ada9 100644 --- a/cmd/atlas-cli/memory_cmds.go +++ b/cmd/atlas-cli/memory_cmds.go @@ -18,13 +18,14 @@ import ( "github.com/tryatlas/cli/internal/tui/memview" ) -// openRecord opens the shared-memory record of the repository around the cwd. +// openRecord opens the shared-memory record of the repository (or workspace) +// around the cwd. func openRecord(cmd *cobra.Command, create bool) (*record.Store, error) { cwd, err := os.Getwd() if err != nil { return nil, err } - scope := project.ScopeRoot(cmd.Context(), cwd) + scope := project.MemoryRoot(cmd.Context(), cwd) st, err := record.Open(scope, create) if errors.Is(err, record.ErrNoRecord) { return nil, fmt.Errorf("no shared memory yet for %s", scope) @@ -117,15 +118,22 @@ func runMCPBridge(cmd *cobra.Command, args []string) error { } root = cwd } + cwd := root + if c, err := project.Canonical(root); err == nil { + cwd, root = c, c + } if p, err := project.Discover(cmd.Context(), root); err == nil { root = p.Root - } else if c, err := project.Canonical(root); err == nil { - root = c + if !p.Workspace { + cwd = root + } + // In a workspace the agent works in one member repository: its + // relative paths resolve there, not in the workspace folder. } if agentID == "" { agentID = "unknown" } - g := server.Grant{Agent: agentID, Cwd: root, SessionID: hooks.CurrentSession(root, agentID)} + g := server.Grant{Agent: agentID, Cwd: cwd, SessionID: hooks.CurrentSession(root, agentID)} if rf := listener.ReadRunFile(root); rf != nil { return server.RunBridge(cmd.Context(), cmd.InOrStdin(), cmd.OutOrStdout(), server.NewUnixForwarder(rf.Socket, g)) } diff --git a/cmd/atlas-cli/project_cmds.go b/cmd/atlas-cli/project_cmds.go index a0c32f7..7310d07 100644 --- a/cmd/atlas-cli/project_cmds.go +++ b/cmd/atlas-cli/project_cmds.go @@ -60,13 +60,26 @@ func runInit(cmd *cobra.Command, _ []string) error { }) } - if launch != scope { + workspace, err := pickWorkspace(cmd, launch, scope, guided) + if err != nil { + return err + } + if workspace { + scope = launch // a workspace keeps its own memory, shared by its repositories + } else if launch != scope { fmt.Fprintf(errOut, "Note: %s is inside the repository %s.\n"+ "Capture is recorded for this folder only; shared memory is shared with the whole repository.\n", launch, scope) if err := confirm(cmd, yes, "Bind this subfolder as its own Project?"); err != nil { return err } } + if p, err := project.Discover(ctx, launch); err == nil && p.Workspace && p.Root != launch { + fmt.Fprintf(errOut, "Note: %s is part of the workspace %s.\n"+ + "Binding it splits it off: its sessions and memory stop going to the workspace.\n", launch, p.Root) + if err := confirm(cmd, yes, "Bind this folder as its own Project?"); err != nil { + return err + } + } // The session file is needed for a cloud binding, not for a local one. var a *auth.Auth @@ -102,6 +115,9 @@ func runInit(cmd *cobra.Command, _ []string) error { if err := bindFolder(cmd, a, sess, local, launch, scope, steps); err != nil { return err } + if err := project.SetWorkspace(launch, workspace); err != nil { + return err + } ensureMemoryRecord(scope) return finishInit(cmd, launch, local, guided, steps) } @@ -557,6 +573,9 @@ func statusLines(cmd *cobra.Command, w io.Writer) error { if errors.Is(err, project.ErrNotInitialised) { fmt.Fprintln(w, "Project: not initialised here (atlas-cli init)") dir, _ := project.Canonical(cwd) + if parent := project.PlainProjectAbove(ctx, dir); parent != "" { + fmt.Fprintf(w, "Hint: %s is an Atlas Project but not a workspace; atlas-cli init --workspace there records this repository too\n", parent) + } printGates(w, dir, nil) return nil } @@ -574,7 +593,9 @@ func statusLines(cmd *cobra.Command, w io.Writer) error { } fmt.Fprintf(w, "Project: %s\n", p.Root) fmt.Fprintf(w, "Binding: %s\n", describeBinding(b, sess)) - if p.ScopeRoot != p.Root { + if p.Workspace { + fmt.Fprintf(w, "Workspace: %s (each shares this Project's sessions and memory)\n", workspaceRepos(p.Root)) + } else if p.ScopeRoot != p.Root { fmt.Fprintf(w, "Memory at: %s (shared with the whole repository)\n", p.ScopeRoot) } printGates(w, p.Root, b) @@ -677,3 +698,12 @@ func printGates(w io.Writer, dir string, b *store.Binding) { fmt.Fprintln(w, "Capture: paused") } } + +// workspaceRepos names a workspace's member repositories for status lines. +func workspaceRepos(root string) string { + m := project.Members(root) + if len(m) == 0 { + return "no repositories yet" + } + return repos(len(m)) + ": " + memberNames(root, m) +} diff --git a/cmd/atlas-cli/project_cmds_test.go b/cmd/atlas-cli/project_cmds_test.go index 6184839..9f8e07f 100644 --- a/cmd/atlas-cli/project_cmds_test.go +++ b/cmd/atlas-cli/project_cmds_test.go @@ -14,6 +14,7 @@ import ( "testing" "github.com/tryatlas/cli/internal/capture/store" + "github.com/tryatlas/cli/internal/hooks" "github.com/tryatlas/cli/internal/project" ) @@ -233,3 +234,200 @@ func TestGatesAndStatus(t *testing.T) { } } } + +// workspaceDir is acme-shop/ outside git with the repositories frontend/ and +// backend/; the test runs in acme-shop/. +func workspaceDir(t *testing.T) (mother, frontend, backend string) { + t.Helper() + base, _ := project.Canonical(t.TempDir()) + mother = filepath.Join(base, "acme-shop") + frontend, backend = filepath.Join(mother, "frontend"), filepath.Join(mother, "backend") + for _, d := range []string{frontend, backend} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + c := exec.Command("git", "-C", d, "init", "-q") + c.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null") + if out, err := c.CombinedOutput(); err != nil { + t.Fatalf("git init: %v %s", err, out) + } + } + t.Chdir(mother) + return mother, frontend, backend +} + +func TestInitWorkspace(t *testing.T) { + mother, frontend, backend := workspaceDir(t) + code, _, e := runCmd(t, "init", "--local", "--workspace", "--agents", "claude-code") + if code != 0 { + t.Fatalf("exit %d: %s", code, e) + } + if !strings.Contains(e, "Binding "+mother+" as a workspace of 2 repositories (backend, frontend).") { + t.Fatalf("no workspace note: %s", e) + } + if b := binding(t, mother); b.Root != mother || b.RootCommitSHA != nil { + t.Fatalf("%+v", b) + } + if !project.IsWorkspace(mother) { + t.Fatal("marker not written") + } + // The agent's hook and memory entry are in every member repository. + for _, d := range []string{mother, frontend, backend} { + for _, f := range []string{".claude/settings.local.json", ".mcp.json"} { + if _, err := os.Stat(filepath.Join(d, f)); err != nil { + t.Errorf("%s: %v", d, err) + } + } + } + // From a member, status names the workspace Project. + t.Chdir(backend) + code, out, e := runCmd(t, "status") + if code != 0 || !strings.Contains(out, "Project: "+mother) || !strings.Contains(out, "2 repositories: backend, frontend") { + t.Fatalf("status %d: %s %s", code, out, e) + } + // Removing the agent cleans the members too. + if code, _, e := runCmd(t, "agents", "remove", "claude-code"); code != 0 { + t.Fatalf("remove: %s", e) + } + for _, d := range []string{mother, frontend, backend} { + if a, _ := hooks.Get("claude-code"); a.State(d) != hooks.Absent { + t.Errorf("%s still hooked", d) + } + } + + // Init again without the flag (another cloud Project, say) keeps it a workspace. + t.Chdir(mother) + if code, _, e := runCmd(t, "init", "--local", "--yes"); code != 0 || !project.IsWorkspace(mother) || strings.Contains(e, "not captured") { + t.Fatalf("re-init dropped the workspace: exit %d: %s", code, e) + } + + // --workspace=false binds the folder alone and drops the marker. + t.Chdir(mother) + if code, _, e := runCmd(t, "init", "--local", "--yes", "--workspace=false"); code != 0 { + t.Fatalf("exit %d: %s", code, e) + } + if project.IsWorkspace(mother) { + t.Fatal("marker kept") + } +} + +func TestInitWorkspaceRefusesAFolderWithoutRepositories(t *testing.T) { + dir, _ := project.Canonical(t.TempDir()) + t.Chdir(dir) + code, _, e := runCmd(t, "init", "--local", "--workspace") + if code == 0 || !strings.Contains(e, "holds no git repository") { + t.Fatalf("exit %d: %s", code, e) + } + // Without the flag a plain folder is a plain Project. + if code, _, e := runCmd(t, "init", "--local"); code != 0 || project.IsWorkspace(dir) { + t.Fatalf("exit %d: %s", code, e) + } +} + +func hooked(dir string) bool { + a, _ := hooks.Get("claude-code") + return a.State(dir) == hooks.Current +} + +// The cli-test case: the folder was bound before any repository existed in +// it. workspace on converts it, sync hooks a repository added later, and +// add/remove handle a folder without git. +func TestWorkspaceCommand(t *testing.T) { + mother, _ := project.Canonical(t.TempDir()) + t.Chdir(mother) + if code, _, e := runCmd(t, "init", "--local", "--agents", "claude-code"); code != 0 { + t.Fatalf("init: %s", e) + } + newRepo := func(name string) string { + d := filepath.Join(mother, name) + _ = os.MkdirAll(d, 0o755) + c := exec.Command("git", "-C", d, "init", "-q") + c.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null") + if out, err := c.CombinedOutput(); err != nil { + t.Fatalf("git init: %v %s", err, out) + } + return d + } + frontend := newRepo("frontend") + + // Not a workspace yet: the repository is on its own, and status says why. + if code, _, e := runCmd(t, "workspace", "sync"); code == 0 || !strings.Contains(e, "not a workspace") { + t.Fatalf("sync before on: %d %s", code, e) + } + t.Chdir(frontend) + if _, out, _ := runCmd(t, "status"); !strings.Contains(out, "atlas-cli init --workspace") { + t.Fatalf("no hint: %s", out) + } + + t.Chdir(mother) + code, out, e := runCmd(t, "workspace", "on") + if code != 0 || !strings.Contains(out, "is now a workspace (1 repository: frontend)") || !hooked(frontend) { + t.Fatalf("on: %d %s %s", code, out, e) + } + + // A repository added later: shown as not hooked, then synced. From a member. + backend := newRepo("backend") + t.Chdir(frontend) + if _, out, _ := runCmd(t, "workspace"); !strings.Contains(out, "not hooked: claude-code") || !strings.Contains(out, "atlas-cli workspace sync") { + t.Fatalf("show: %s", out) + } + if code, _, e := runCmd(t, "workspace", "sync"); code != 0 || !hooked(backend) { + t.Fatalf("sync: %d %s", code, e) + } + if _, out, _ := runCmd(t, "workspace"); strings.Contains(out, "not hooked") { + t.Fatalf("show after sync: %s", out) + } + + // A folder without git joins by hand, and status inside it finds the workspace. + docs := filepath.Join(mother, "docs") + _ = os.Mkdir(docs, 0o755) + t.Chdir(mother) + if code, _, e := runCmd(t, "workspace", "add", "docs"); code != 0 || !hooked(docs) { + t.Fatalf("add: %d %s", code, e) + } + if code, _, e := runCmd(t, "workspace", "add", t.TempDir()); code == 0 || !strings.Contains(e, "not inside the workspace") { + t.Fatalf("add outside: %d %s", code, e) + } + if code, _, e := runCmd(t, "workspace", "remove", "frontend"); code == 0 || !strings.Contains(e, "not added by hand") { + t.Fatalf("remove a repository: %d %s", code, e) + } + if code, _, e := runCmd(t, "workspace", "remove", "docs"); code != 0 || hooked(docs) { + t.Fatalf("remove: %d %s", code, e) + } + + // off unhooks the members and keeps the workspace folder's own hook. + if code, _, e := runCmd(t, "workspace", "off"); code != 0 { + t.Fatalf("off: %s", e) + } + if project.IsWorkspace(mother) || hooked(frontend) || hooked(backend) || !hooked(mother) { + t.Fatalf("off left: ws=%v fe=%v be=%v root=%v", project.IsWorkspace(mother), hooked(frontend), hooked(backend), hooked(mother)) + } +} + +// A workspace is opt-in: without --workspace and without a terminal, init in +// a folder of repositories binds the folder alone and says how to capture them. +func TestInitWithoutTheWorkspaceFlagLeavesTheRepositoriesAlone(t *testing.T) { + mother, frontend, backend := workspaceDir(t) + code, _, e := runCmd(t, "init", "--local", "--agents", "claude-code") + if code != 0 { + t.Fatalf("exit %d: %s", code, e) + } + if project.IsWorkspace(mother) { + t.Fatal("became a workspace without --workspace") + } + if !strings.Contains(e, mother+" holds 2 repositories (backend, frontend). Agents started in them are not captured; atlas-cli workspace on captures them here.") { + t.Fatalf("no hint: %s", e) + } + for _, d := range []string{frontend, backend} { + if hooked(d) { + t.Fatalf("%s hooked without a workspace", d) + } + } + if !hooked(mother) { + t.Fatal("the folder itself was not hooked") + } + // The hint's command turns it into a workspace. + if code, out, e := runCmd(t, "workspace", "on"); code != 0 || !project.IsWorkspace(mother) || !hooked(frontend) || !hooked(backend) { + t.Fatalf("workspace on: exit %d: %s %s", code, out, e) + } +} diff --git a/cmd/atlas-cli/settings_cmds.go b/cmd/atlas-cli/settings_cmds.go index 4511536..99e3afd 100644 --- a/cmd/atlas-cli/settings_cmds.go +++ b/cmd/atlas-cli/settings_cmds.go @@ -153,7 +153,10 @@ func (b *settingsBackend) projectSection(ctx context.Context, p *project.Project sec.Items = append(sec.Items, settings.Item{Label: "Bound to", Value: describeBinding(bind, sess), Detail: "atlas-cli init binds the folder again (another organisation or Project)."}) } - if p.ScopeRoot != p.Root { + if p.Workspace { + sec.Items = append(sec.Items, settings.Item{Label: "Workspace", Value: workspaceRepos(p.Root), + Detail: "Agents started in any of these repositories record here and share one memory."}) + } else if p.ScopeRoot != p.Root { sec.Items = append(sec.Items, settings.Item{Label: "Memory lives at", Value: p.ScopeRoot}) } } diff --git a/cmd/atlas-cli/uninstall_cmds.go b/cmd/atlas-cli/uninstall_cmds.go index af06e10..040cfb7 100644 --- a/cmd/atlas-cli/uninstall_cmds.go +++ b/cmd/atlas-cli/uninstall_cmds.go @@ -116,7 +116,8 @@ func uninstallRoots(ctx context.Context) []string { } // cleanProject stops a Project's background listener and takes Atlas's -// entries out of every agent config and the git hooks. +// entries out of every agent config and the git hooks, in each member +// repository too when the Project is a workspace. func cleanProject(ctx context.Context, out io.Writer, root string) error { var errs []error if pid, err := haltListener(root); err != nil { @@ -124,33 +125,43 @@ func cleanProject(ctx context.Context, out io.Writer, root string) error { } else if pid != 0 { fmt.Fprintf(out, "Stopped the listener for %s (pid %d).\n", root, pid) } + for _, t := range project.Targets(root) { + errs = append(errs, unhookFolder(ctx, out, t)...) + } + return errors.Join(errs...) +} + +// unhookFolder takes Atlas's entries out of every agent config and the git +// hooks of one folder. +func unhookFolder(ctx context.Context, out io.Writer, t string) []error { + var errs []error for _, a := range hooks.All() { mw, hasMem := mcpconfig.For(a.ID()) - hooked := a.State(root) != hooks.Absent - mem := hasMem && mw.State(root) != hooks.Absent + hooked := a.State(t) != hooks.Absent + mem := hasMem && mw.State(t) != hooks.Absent if !hooked && !mem { continue } if hooked { - if err := a.Uninstall(root); err != nil { + if err := a.Uninstall(t); err != nil { errs = append(errs, fmt.Errorf("%s: %w", a.ID(), err)) continue } } if mem { - if err := mw.Remove(root); err != nil { + if err := mw.Remove(t); err != nil { errs = append(errs, fmt.Errorf("%s memory config: %w", a.ID(), err)) continue } } - fmt.Fprintf(out, "%s: Atlas hook and memory entry removed from %s.\n", a.Name(), root) + fmt.Fprintf(out, "%s: Atlas hook and memory entry removed from %s.\n", a.Name(), t) } - if hooks.GitHooksState(ctx, root) != hooks.Absent { - if err := hooks.UninstallGitHooks(ctx, root); err != nil { + if hooks.GitHooksState(ctx, t) != hooks.Absent { + if err := hooks.UninstallGitHooks(ctx, t); err != nil { errs = append(errs, fmt.Errorf("git hooks: %w", err)) } else { - fmt.Fprintf(out, "Removed the git post-commit hook from %s.\n", root) + fmt.Fprintf(out, "Removed the git post-commit hook from %s.\n", t) } } - return errors.Join(errs...) + return errs } diff --git a/cmd/atlas-cli/workspace_cmds.go b/cmd/atlas-cli/workspace_cmds.go new file mode 100644 index 0000000..d008bb4 --- /dev/null +++ b/cmd/atlas-cli/workspace_cmds.go @@ -0,0 +1,225 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" + + "github.com/tryatlas/cli/internal/hooks" + "github.com/tryatlas/cli/internal/hooks/mcpconfig" + "github.com/tryatlas/cli/internal/project" +) + +// atlas-cli workspace: one Project for a folder of repositories (ADR-0015). + +func newWorkspaceCmd() *cobra.Command { + c := group("workspace", "One Project for a folder of repositories: show its folders, hook new ones", + withRun(leaf("on", "Make this Project a workspace: agents started in its repositories record here", cobra.NoArgs), runWorkspaceOn), + withRun(leaf("off", "Make this Project a single folder again and unhook its repositories", cobra.NoArgs), runWorkspaceOff), + withRun(leaf("sync", "Hook folders added since: every member gets the agents hooked in the workspace folder", cobra.NoArgs), runWorkspaceSync), + withRun(leaf("add ", "Add a folder without git (or a repository deeper down) to the workspace and hook it", cobra.ExactArgs(1)), runWorkspaceAdd), + withRun(leaf("remove ", "Take a folder added by hand out of the workspace and unhook it", cobra.ExactArgs(1)), runWorkspaceRemove), + ) + c.RunE = runWorkspaceShow + return c +} + +var errNotWorkspace = errors.New("this Project is not a workspace; atlas-cli workspace on (in the folder that holds the repositories) makes it one") + +// workspaceHere is the workspace around the cwd. +func workspaceHere(ctx context.Context) (*project.Project, error) { + p, err := agentRoot(ctx) + if err != nil { + return nil, err + } + if !p.Workspace { + return nil, errNotWorkspace + } + return p, nil +} + +// hookedAgents are the agents hooked in root. +func hookedAgents(root string) []hooks.Agent { + var out []hooks.Agent + for _, a := range hooks.All() { + if a.State(root) != hooks.Absent { + out = append(out, a) + } + } + return out +} + +// syncWorkspace gives every member the agents hooked in the workspace +// folder, each with a memory entry when the workspace folder has one. +func syncWorkspace(ctx context.Context, out io.Writer, root string) error { + agents := hookedAgents(root) + if len(agents) == 0 { + fmt.Fprintln(out, "No agent is hooked in the workspace folder yet: atlas-cli agents add hooks it and every member.") + return nil + } + for _, a := range agents { + noMem := false + if mw, ok := mcpconfig.For(a.ID()); ok { + noMem = mw.State(root) == hooks.Absent + } + if err := installAgents(ctx, out, root, []hooks.Agent{a}, false, noMem); err != nil { + return err + } + } + return nil +} + +func runWorkspaceShow(cmd *cobra.Command, _ []string) error { + out := cmd.OutOrStdout() + p, err := agentRoot(cmd.Context()) + if err != nil { + return err + } + if !p.Workspace { + fmt.Fprintf(out, "%s is a single-folder Project, not a workspace (atlas-cli workspace on).\n", p.Root) + return nil + } + agents := hookedAgents(p.Root) + fmt.Fprintf(out, "Workspace: %s\n", p.Root) + w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0) + fmt.Fprintln(w, "FOLDER\tKIND\tAGENTS") + missing := false + for _, t := range project.Targets(p.Root) { + name, kind := ".", "workspace folder" + if t != p.Root { + name, _ = filepath.Rel(p.Root, t) + kind = "folder" + if _, err := os.Stat(filepath.Join(t, ".git")); err == nil { + kind = "repository" + } + } + var on, off []string + for _, a := range agents { + if a.State(t) == hooks.Current { + on = append(on, a.ID()) + } else { + off = append(off, a.ID()) + } + } + state := strings.Join(on, ", ") + if len(off) > 0 { + missing = true + state = strings.TrimPrefix(state+" · not hooked: "+strings.Join(off, ", "), " · ") + } + if state == "" { + state = "-" + } + fmt.Fprintf(w, "%s\t%s\t%s\n", name, kind, state) + } + if err := w.Flush(); err != nil { + return err + } + switch { + case len(agents) == 0: + fmt.Fprintln(out, "No agent is hooked yet: atlas-cli agents add .") + case missing: + fmt.Fprintln(out, "Some folders are not hooked: atlas-cli workspace sync.") + } + return nil +} + +func runWorkspaceOn(cmd *cobra.Command, _ []string) error { + ctx, out := cmd.Context(), cmd.OutOrStdout() + p, err := agentRoot(ctx) + if err != nil { + return err + } + if p.Workspace { + fmt.Fprintf(out, "%s is already a workspace.\n", p.Root) + return syncWorkspace(ctx, out, p.Root) + } + if p.Cwd != p.Root { + return fmt.Errorf("run this in the Project folder, %s", p.Root) + } + if project.InRepo(ctx, p.Root) { + return fmt.Errorf("%s is inside a git repository; a workspace is the folder that holds the repositories", p.Root) + } + if err := project.SetWorkspace(p.Root, true); err != nil { + return err + } + fmt.Fprintf(out, "%s is now a workspace (%s).\n", p.Root, workspaceRepos(p.Root)) + return syncWorkspace(ctx, out, p.Root) +} + +func runWorkspaceOff(cmd *cobra.Command, _ []string) error { + ctx, out := cmd.Context(), cmd.OutOrStdout() + p, err := workspaceHere(ctx) + if err != nil { + return err + } + var errs []error + for _, m := range project.Members(p.Root) { + errs = append(errs, unhookFolder(ctx, out, m)...) + } + if err := errors.Join(errs...); err != nil { + return err + } + if err := project.SetWorkspace(p.Root, false); err != nil { + return err + } + fmt.Fprintf(out, "%s is a single-folder Project again. What was recorded stays.\n", p.Root) + return nil +} + +func runWorkspaceSync(cmd *cobra.Command, _ []string) error { + p, err := workspaceHere(cmd.Context()) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Workspace %s: %s.\n", p.Root, workspaceRepos(p.Root)) + return syncWorkspace(cmd.Context(), cmd.OutOrStdout(), p.Root) +} + +func runWorkspaceAdd(cmd *cobra.Command, args []string) error { + ctx, out := cmd.Context(), cmd.OutOrStdout() + p, err := workspaceHere(ctx) + if err != nil { + return err + } + added, err := project.AddFolder(p.Root, args[0]) + if err != nil { + return err + } + if added { + fmt.Fprintf(out, "Added %s to the workspace.\n", args[0]) + } else { + fmt.Fprintf(out, "%s is already in the workspace.\n", args[0]) + } + return syncWorkspace(ctx, out, p.Root) +} + +func runWorkspaceRemove(cmd *cobra.Command, args []string) error { + ctx, out := cmd.Context(), cmd.OutOrStdout() + p, err := workspaceHere(ctx) + if err != nil { + return err + } + removed, err := project.RemoveFolder(p.Root, args[0]) + if err != nil { + return err + } + if !removed { + return fmt.Errorf("%s was not added by hand; a repository directly in the workspace is a member by itself (its own atlas-cli init splits it off)", args[0]) + } + c, err := project.Canonical(args[0]) + if err != nil { + return err + } + if err := errors.Join(unhookFolder(ctx, out, c)...); err != nil { + return err + } + fmt.Fprintf(out, "Removed %s from the workspace.\n", args[0]) + return nil +} diff --git a/docs/adr/0015-a-workspace-binds-a-folder-of-repositories.md b/docs/adr/0015-a-workspace-binds-a-folder-of-repositories.md new file mode 100644 index 0000000..374bace --- /dev/null +++ b/docs/adr/0015-a-workspace-binds-a-folder-of-repositories.md @@ -0,0 +1,67 @@ +# ADR-0015: A workspace binds a folder of repositories once + +**Status:** Accepted (2026-11-23, at the user's request for enterprise +layouts: "they create 1 main folder with the project name, under it +frontend, backend etc., each with its own git; they want to init atlas 1 time +in the mother folder and run agents under frontend, backend"). Amends +ADR-0007. + +## Context + +ADR-0007 stops Project discovery at the scope root, the git repository that +owns the cwd. In the layout above the mother folder is not a git repository +and each child is, so an agent started in `acme-shop/backend` never finds a +binding in `acme-shop/` and reports "not initialised". Walking past the +scope root for every binding is not safe: a stray `.atlas/` in a parent +folder (the home directory, say) would capture unrelated repositories. + +The capture store is the desktop's schema v10 byte for byte +(`internal/capture/store/store.go`), so the binding row cannot take a new +column. + +## Decision + +1. **A workspace is an explicit, opt-in kind of Project.** `atlas init + --workspace` binds a folder of repositories once (it refuses a folder + without repositories or inside one). On a terminal, plain `atlas init` in + a folder that is not inside git and has child folders holding `.git` asks, + with "This folder only" pre-selected; without a terminal it binds the + folder alone and prints the repositories and `atlas-cli workspace on`. + Re-running init keeps a workspace a workspace unless `--workspace=false` + or the prompt says otherwise. It is never a global default or a setting: + the first build made a workspace by default, and one init in a folder of + unrelated projects pulled ten repositories into one cloud Project. +2. **The marker is a sidecar,** `.atlas/workspace.json` `{"workspace": true}`, + like `memory-sharing.json`. The binding row is unchanged. +3. **Discovery** walks to the scope root as before. Only when nothing is + bound there does it keep walking up, and then it accepts only a bound + folder carrying the marker. Nested bindings still win: a member + repository with its own `atlas init` is split off as its own Project. +4. **Members are read, not stored:** the direct child folders holding a + `.git` directory or file, each time. A repository cloned in later is a + member without re-running init. +5. **One memory for the workspace.** Memory lives in the workspace folder + (`project.MemoryRoot`), so the frontend agent sees what the backend agent + decided. Citations are spelled from the workspace folder + (`backend/src/x.go`). +6. **Agent and git hooks go into the workspace folder and every member** + (`project.Targets`), because each agent reads its config from the folder + it starts in. `agents remove` and `uninstall` clean them all. + +## Consequences + +- A workspace has no git fingerprint; a cloud workspace binds by name, as a + folder outside git does today. +- Git capture (shell changes, commit links) still runs in the Project root, + which is outside git for a workspace: sessions in members record prompts, + replies, tool calls and the files tools report, but not yet shell changes + or commit links. Running git per member repository is the next step. +- A repository cloned in later has no agent hooks until + `atlas-cli workspace sync` runs. `atlas-cli workspace` shows which folders + are hooked; `on`/`off` convert a bound folder; `add`/`remove` list a folder + without git (or a deeper repository) in the marker's `folders`. +- A member with its own binding is not a member: workspace commands never + hook or unhook it. +- The desktop app does not read the marker: opening a member alone in it + creates a separate store. +- A mother folder inside a git repository cannot be a workspace. diff --git a/docs/progress.md b/docs/progress.md index ce59543..59580ec 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1655,3 +1655,68 @@ Not verified: - Not run on Linux: cgroup limits and the per-thread renice are covered by unit tests on fixture files only; CI's Linux runners compile and test it. - `TestMatchesTheAppsVectors` needs an app-written record and was skipped. + +## v0.7.0: workspaces, one Project for a folder of repositories (ADR-0015) + +A layout asked for by enterprise users: one folder per product, each part +(`frontend/`, `backend/`, …) its own git repository. Discovery stopped at +the repository, so an agent started in `backend/` found no Project. + +Built: + +- `internal/project`: the `.atlas/workspace.json` marker (a sidecar, so + `sessions.db` stays the app's schema), `Members` (child folders holding + `.git` and no binding of their own, plus folders added by hand), + `Targets`, `MemoryRoot`, `PlainProjectAbove`. `Discover` walks past the + scope root only to a bound workspace; a plain binding above a repository + is still never found. +- Memory: the server, extraction, the `memory` commands and init resolve + `MemoryRoot`, so a workspace has one record; `mcp-bridge` keeps the member + as the session's cwd, so relative paths resolve there and citations are + spelled from the workspace (`backend/src/x.go`); `project.json` goes to the + workspace folder, never into a member. +- `init --workspace`, opt-in: asked on a terminal with "This folder only" + pre-selected, never made without one (init names the repositories and + `atlas-cli workspace on`); a re-run keeps a workspace. `agents add`, + `agents remove` and `uninstall` act on every member; `status` and + `settings` list the members; `status` in a repository under a plain + Project points at `atlas-cli init --workspace`. +- `atlas-cli workspace` (`on`, `off`, `sync`, `add `, + `remove `). +- Command tests start in a temporary directory: two of them had found a + real Project above the source tree and unhooked it. + +Verified in a sandbox (Docker, a clean copy of the sources, no network but +for the model download): gofmt, vet, `go test` and `-race` on 34 packages; +62 end-to-end workspace checks (init, sessions from three repositories and a +folder without git landing in one store, a memory remembered in one +repository found from another, a repository added later, a split-off +repository, off and on, opt-in and safety, the init wizard on a pty, +uninstall), of which the v0.6.1 binary fails 42 of the first 56; the 27 +earlier end-to-end checks (20 offline, 7 online). Cross-builds for the four +targets, lint and `go mod tidy -diff` clean, `make release-check`, +`make snapshot`, and install.sh against the snapshot. + +Verified live: sessions started in a member repository of a cloud-bound +workspace reached the cloud Project. + +Fixed before release: + +- The first build made a workspace without asking when init ran without a + terminal, and pre-selected it on one. One init in a folder of unrelated + projects pulled ten repositories into one cloud Project. A workspace is + opt-in now. +- Taking Atlas's hooks or memory entry out of a config file that held + nothing else left it as `{}`: after `workspace off` every member + repository had an untracked `.mcp.json`. Such a file is removed now + (`hooks.SaveOrRemoveJSON`), as the Codex, Copilot and OpenCode writers + already did with theirs. + +Not verified: + +- Shell changes and commit links in member repositories: git still runs in + the workspace folder, which is outside git. Not built yet. +- The acceptance checklists A–D of `RELEASE.md` were not run. Only Claude + Code was exercised in a workspace; no Mac run. +- The desktop app does not read the marker: a member opened on its own in + the app gets a separate store. diff --git a/internal/hooks/antigravity/antigravity.go b/internal/hooks/antigravity/antigravity.go index 0134007..1602e86 100644 --- a/internal/hooks/antigravity/antigravity.go +++ b/internal/hooks/antigravity/antigravity.go @@ -154,7 +154,7 @@ func (Agent) Uninstall(root string) error { return nil } delete(file, Key) - return hooks.SaveJSON(path, file, 0o644) + return hooks.SaveOrRemoveJSON(path, file, 0o644) } // State compares the "atlas" entry with what Install writes. diff --git a/internal/hooks/codex/codex_test.go b/internal/hooks/codex/codex_test.go index c1710aa..99506dd 100644 --- a/internal/hooks/codex/codex_test.go +++ b/internal/hooks/codex/codex_test.go @@ -74,9 +74,9 @@ func TestInstallIntoEmptyDir(t *testing.T) { if err := a.Uninstall(root); err != nil { t.Fatal(err) } - _, top := readHooks(t, root) - if _, ok := top["hooks"]; ok { - t.Fatalf("hooks left after uninstall: %s", top["hooks"]) + // Atlas's hooks were all the file held: it goes, not left as "{}". + if _, err := os.Stat(HooksPath(root)); !os.IsNotExist(err) { + t.Fatalf("hooks.json left after uninstall: %v", err) } if a.State(root) != hooks.Absent { t.Fatal("expected absent after uninstall") diff --git a/internal/hooks/jsonfile.go b/internal/hooks/jsonfile.go index 8c3306d..eb00633 100644 --- a/internal/hooks/jsonfile.go +++ b/internal/hooks/jsonfile.go @@ -57,6 +57,20 @@ func SaveJSON(path string, v any, mode fs.FileMode) error { return os.Rename(tmp, path) } +// SaveOrRemoveJSON writes obj after Atlas's entries were taken out of it, +// or removes the file when they were all it held: an empty object configures +// nothing, and a "{}" left behind is an untracked file in every repository +// an agent was hooked in (a workspace hooks many). +func SaveOrRemoveJSON(path string, obj map[string]json.RawMessage, mode fs.FileMode) error { + if len(obj) > 0 { + return SaveJSON(path, obj, mode) + } + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + return nil +} + // Raw marshals v to a RawMessage without HTML escaping (hook commands hold // > and &). func Raw(v any) json.RawMessage { @@ -212,7 +226,7 @@ func (c ClaudeShaped) Uninstall() error { if mode == 0 { mode = 0o600 } - return SaveJSON(c.Path, root, mode) + return SaveOrRemoveJSON(c.Path, root, mode) } // State compares the file with what Install would write. diff --git a/internal/hooks/mcpconfig/claude.go b/internal/hooks/mcpconfig/claude.go index 2a30b8f..af902c9 100644 --- a/internal/hooks/mcpconfig/claude.go +++ b/internal/hooks/mcpconfig/claude.go @@ -84,5 +84,5 @@ func unapproveClaude(root string) error { } else { obj["enabledMcpjsonServers"] = hooks.Raw(keep) } - return hooks.SaveJSON(claudeLocalSettings(root), obj, 0o600) + return hooks.SaveOrRemoveJSON(claudeLocalSettings(root), obj, 0o600) } diff --git a/internal/hooks/mcpconfig/mcpconfig.go b/internal/hooks/mcpconfig/mcpconfig.go index e09fb0c..f06ebdf 100644 --- a/internal/hooks/mcpconfig/mcpconfig.go +++ b/internal/hooks/mcpconfig/mcpconfig.go @@ -139,7 +139,7 @@ func (j JSONServers) Remove(root string) error { } else { obj[j.Key] = hooks.Raw(servers) } - return hooks.SaveJSON(j.Path(root), obj, 0o644) + return hooks.SaveOrRemoveJSON(j.Path(root), obj, 0o644) } // State compares the entry with what Write would put there. diff --git a/internal/hooks/mcpconfig/remove_test.go b/internal/hooks/mcpconfig/remove_test.go new file mode 100644 index 0000000..2219fd0 --- /dev/null +++ b/internal/hooks/mcpconfig/remove_test.go @@ -0,0 +1,40 @@ +package mcpconfig + +import ( + "os" + "path/filepath" + "testing" +) + +// Removing the entry from files that held nothing else removes the files: +// "{}" left behind would be an untracked .mcp.json in every repository an +// agent was hooked in. +func TestRemoveLeavesNoEmptyFiles(t *testing.T) { + root := t.TempDir() + w, ok := For(claudeID) + if !ok { + t.Fatal("no Claude Code writer") + } + if _, err := w.Write(root); err != nil { + t.Fatal(err) + } + mcp, local := filepath.Join(root, ".mcp.json"), filepath.Join(root, ".claude", "settings.local.json") + for _, p := range []string{mcp, local} { + if _, err := os.Stat(p); err != nil { + t.Fatalf("not written: %v", err) + } + } + if err := w.Remove(root); err != nil { + t.Fatal(err) + } + for _, p := range []string{mcp, local} { + if _, err := os.Stat(p); !os.IsNotExist(err) { + b, _ := os.ReadFile(p) + t.Fatalf("%s left behind: %q", p, b) + } + } + // Removing again is a no-op, not an error. + if err := w.Remove(root); err != nil { + t.Fatal(err) + } +} diff --git a/internal/memory/extract/extract.go b/internal/memory/extract/extract.go index 1fb3983..8946e72 100644 --- a/internal/memory/extract/extract.go +++ b/internal/memory/extract/extract.go @@ -154,7 +154,7 @@ func Run(ctx context.Context, o Options) (int, error) { return 0, ErrSkipped } defer unlock() - scope := project.ScopeRoot(ctx, o.Root) + scope := project.MemoryRoot(ctx, o.Root) st := loadState(scope, o.Root, o.Session) excerpt, last, tools, err := conversation(ctx, o.Root, o.Session, st.LastTurn) if errors.Is(err, sql.ErrNoRows) { diff --git a/internal/memory/server/server.go b/internal/memory/server/server.go index 762b364..9b2ed8e 100644 --- a/internal/memory/server/server.go +++ b/internal/memory/server/server.go @@ -81,9 +81,10 @@ func (s *Server) Close() { func (s *Server) now() int64 { return s.Now().UnixMilli() } -// store resolves cwd → scope root → the record, opened once per scope. +// store resolves cwd → memory root (the scope root, or the workspace folder) +// → the record, opened once per root. func (s *Server) store(ctx context.Context, cwd string) (*record.Store, error) { - scope := project.ScopeRoot(ctx, cwd) + scope := project.MemoryRoot(ctx, cwd) s.mu.Lock() defer s.mu.Unlock() if st, ok := s.stores[scope]; ok { @@ -132,7 +133,7 @@ func (s *Server) Fold(ctx context.Context, g Grant, ev record.Event) error { if err != nil { return err } - writeProjectJSON(g.Cwd) + writeProjectJSON(labelDir(ctx, g.Cwd)) ev.Agent, ev.Session = g.Agent, g.SessionID if ev.At == 0 { ev.At = s.now() @@ -155,7 +156,7 @@ func (s *Server) SessionEnded(ctx context.Context, g Grant) { _ = st.SessionEnd(ctx, g.SessionID, g.Agent, now) // The handoff note the next session's briefing shows, as the // desktop's lifecycle writes it. - _ = st.WriteHandoff(ctx, g.SessionID, g.Agent, project.ScopeRoot(ctx, g.Cwd), now) + _ = st.WriteHandoff(ctx, g.SessionID, g.Agent, project.MemoryRoot(ctx, g.Cwd), now) } } @@ -170,6 +171,16 @@ func (s *Server) Capture(ctx context.Context, g Grant, reply string) { } } +// labelDir is where project.json goes: the workspace folder for a session in +// one of its repositories (an .atlas/ there would show up in that repository's +// git status), else the cwd as before. +func labelDir(ctx context.Context, cwd string) string { + if p, err := project.Discover(ctx, cwd); err == nil && p.Workspace { + return p.Root + } + return cwd +} + // writeProjectJSON writes /.atlas/project.json on the first // record write if it is absent: {"projectId":"<12 hex of sha256(cwd)>"}. func writeProjectJSON(cwd string) { @@ -337,7 +348,7 @@ func (s *Server) call(ctx context.Context, g Grant, name string, args json.RawMe case "memory_remember": out, err = t.remember(args) if err == nil { - writeProjectJSON(g.Cwd) + writeProjectJSON(labelDir(ctx, g.Cwd)) } case "memory_feedback": out, err = t.feedback(args) diff --git a/internal/memory/server/workspace_test.go b/internal/memory/server/workspace_test.go new file mode 100644 index 0000000..6fb8d3b --- /dev/null +++ b/internal/memory/server/workspace_test.go @@ -0,0 +1,59 @@ +package server + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/tryatlas/cli/internal/capture/store" + "github.com/tryatlas/cli/internal/memory/record" + "github.com/tryatlas/cli/internal/project" +) + +// A session in a member repository of a workspace remembers into the +// workspace's one memory, and leaves no .atlas/ in the repository (ADR-0015). +func TestWorkspaceMemberSharesTheWorkspaceMemory(t *testing.T) { + base, _ := project.Canonical(t.TempDir()) + mother := filepath.Join(base, "acme-shop") + backend := filepath.Join(mother, "backend") + _ = os.MkdirAll(filepath.Join(backend, "src"), 0o755) + if out, err := exec.Command("git", "-C", backend, "init", "-q").CombinedOutput(); err != nil { + t.Fatalf("%v %s", err, out) + } + _ = os.WriteFile(filepath.Join(backend, "src", "ttl.go"), []byte("package src\n\n// TTL is fifteen minutes.\nconst TTL = 15\n"), 0o644) + st, err := store.Open(mother, true) + if err != nil { + t.Fatal(err) + } + if err := st.PutBinding(context.Background(), store.Binding{WorkspaceID: mother, Root: mother, Mode: store.ModeLocal, Enabled: true}, time.Now()); err != nil { + t.Fatal(err) + } + _ = st.Close() + if err := project.SetWorkspace(mother, true); err != nil { + t.Fatal(err) + } + + srv := newServer() + defer srv.Close() + c := startBridge(t, NewLocalForwarder(srv, Grant{SessionID: "s-b", Agent: "claude-code", Cwd: backend})) + handshake(c) + out, errText := c.tool("memory_remember", map[string]any{"kind": "decision", "key": "ttl", "content": "Access tokens live 15 minutes", + "evidence": []any{map[string]any{"path": "src/ttl.go", "lines": "3-4", "symbol": "TTL"}}}) + if errText != "" || out["outcome"] != "inserted" { + t.Fatalf("remember: %v %s", out, errText) + } + if _, err := os.Stat(record.Path(mother)); err != nil { + t.Fatalf("no record in the workspace: %v", err) + } + if _, err := os.Stat(filepath.Join(backend, ".atlas")); err == nil { + t.Fatal("an .atlas/ was created in the member repository") + } + // The citation is spelled from the workspace folder. + got, _ := c.tool("memory_why", map[string]any{"path": "src/ttl.go"}) + if target, _ := got["target"].(map[string]any); target["path"] != "backend/src/ttl.go" { + t.Fatalf("why target: %v", got) + } +} diff --git a/internal/project/project.go b/internal/project/project.go index 9c50ca5..f6221c7 100644 --- a/internal/project/project.go +++ b/internal/project/project.go @@ -20,8 +20,9 @@ var ErrNotInitialised = errors.New("this folder is not an Atlas Project; run atl // Project is a bound folder as seen from a working directory. type Project struct { Root string // canonical launch dir holding .atlas/sessions.db (capture's key) - ScopeRoot string // canonical repository root (shared memory's key) + ScopeRoot string // canonical repository root (shared memory's key); the workspace folder in a workspace Cwd string // canonical directory the lookup started from + Workspace bool // Root is a folder of repositories bound once (ADR-0015) } // Canonical spells a path the one way the desktop does: absolute, symlinks @@ -90,7 +91,9 @@ func ScopeRoot(ctx context.Context, dir string) string { // Discover finds the Project for cwd: the nearest directory from cwd upward // that holds .atlas/sessions.db with a binding row, stopping at the scope -// root (ADR-0007). Nested bindings resolve to the nearest. +// root (ADR-0007). Nested bindings resolve to the nearest. Past the scope +// root only a workspace binding counts (ADR-0015): a stray binding in a +// parent folder never captures an unrelated repository. func Discover(ctx context.Context, cwd string) (*Project, error) { start, err := Canonical(cwd) if err != nil { @@ -99,12 +102,19 @@ func Discover(ctx context.Context, cwd string) (*Project, error) { scope := ScopeRoot(ctx, start) for dir := start; ; dir = filepath.Dir(dir) { if bound(ctx, dir) { + if IsWorkspace(dir) { + return &Project{Root: dir, ScopeRoot: dir, Cwd: start, Workspace: true}, nil + } return &Project{Root: dir, ScopeRoot: scope, Cwd: start}, nil } if dir == scope || dir == filepath.Dir(dir) || !within(dir, scope) { - return nil, ErrNotInitialised + break } } + if ws, ok := workspaceAbove(ctx, scope); ok { + return &Project{Root: ws, ScopeRoot: ws, Cwd: start, Workspace: true}, nil + } + return nil, ErrNotInitialised } // within reports whether dir is scope or below it. diff --git a/internal/project/workspace.go b/internal/project/workspace.go new file mode 100644 index 0000000..d60d673 --- /dev/null +++ b/internal/project/workspace.go @@ -0,0 +1,223 @@ +package project + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "github.com/tryatlas/cli/internal/capture/store" +) + +// A workspace is a folder of repositories bound once (ADR-0015): a mother +// folder such as acme-shop/ holding frontend/ and backend/, each its own git +// repository. Agents started in any of them record into the mother folder's +// store and share its memory. The marker is a sidecar file, not a binding +// column, so sessions.db stays the desktop's schema. + +const workspaceFile = "workspace.json" + +// marker is .atlas/workspace.json. +type marker struct { + Workspace bool `json:"workspace"` + // Folders are members named by hand (atlas-cli workspace add): folders + // without git, or repositories deeper than one level, relative to the + // workspace folder. + Folders []string `json:"folders,omitempty"` +} + +func readMarker(dir string) marker { + var m marker + b, err := os.ReadFile(filepath.Join(dir, store.DirName, workspaceFile)) //nolint:gosec // G304: the Project's own marker + if err != nil || json.Unmarshal(b, &m) != nil { + return marker{} + } + return m +} + +func writeMarker(dir string, m marker) error { + path := filepath.Join(dir, store.DirName, workspaceFile) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + body, _ := json.MarshalIndent(m, "", " ") + tmp := path + ".tmp" + if err := os.WriteFile(tmp, body, 0o644); err != nil { //nolint:gosec // G306: a flag, not a secret + return err + } + return os.Rename(tmp, path) +} + +// IsWorkspace reports whether dir carries the workspace marker. +func IsWorkspace(dir string) bool { return readMarker(dir).Workspace } + +// SetWorkspace writes or removes the marker in dir/.atlas/. Turning it on +// again keeps the folders added by hand. +func SetWorkspace(dir string, on bool) error { + if !on { + err := os.Remove(filepath.Join(dir, store.DirName, workspaceFile)) + if err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + m := readMarker(dir) + m.Workspace = true + return writeMarker(dir, m) +} + +// ErrNotMember means a folder is not below the workspace folder. +var ErrNotMember = errors.New("the folder is not inside the workspace") + +// relMember spells folder relative to the workspace dir; it must be a +// directory strictly below it. +func relMember(dir, folder string) (string, error) { + c, err := Canonical(folder) + if err != nil { + return "", err + } + if fi, err := os.Stat(c); err != nil || !fi.IsDir() { + return "", fmt.Errorf("%s is not a folder", folder) + } + rel, err := filepath.Rel(dir, c) + if err != nil || rel == "." || !within(c, dir) || strings.HasPrefix(rel, store.DirName) { + return "", ErrNotMember + } + return filepath.ToSlash(rel), nil +} + +// AddFolder names folder a member of the workspace dir by hand. It reports +// false when it already was one. +func AddFolder(dir, folder string) (bool, error) { + rel, err := relMember(dir, folder) + if err != nil { + return false, err + } + if slices.Contains(Members(dir), filepath.Join(dir, filepath.FromSlash(rel))) { + return false, nil + } + m := readMarker(dir) + m.Folders = append(m.Folders, rel) + sort.Strings(m.Folders) + return true, writeMarker(dir, m) +} + +// RemoveFolder takes a folder added by hand out of the workspace dir. It +// reports false when it was not listed (a repository directly below the +// workspace is a member by itself and cannot be removed). +func RemoveFolder(dir, folder string) (bool, error) { + rel, err := relMember(dir, folder) + if err != nil { + return false, err + } + m := readMarker(dir) + i := slices.Index(m.Folders, rel) + if i < 0 { + return false, nil + } + m.Folders = slices.Delete(m.Folders, i, i+1) + return true, writeMarker(dir, m) +} + +// Members are a workspace folder's members, as absolute paths, sorted: its +// child folders holding a .git directory or file (a linked worktree or +// submodule) and no binding of their own, read each time so a repository +// cloned in later is a member without re-running init, and the folders added +// by hand that still exist. +func Members(dir string) []string { + var out []string + entries, _ := os.ReadDir(dir) + for _, e := range entries { + if !e.IsDir() || e.Name() == store.DirName { + continue + } + child := filepath.Join(dir, e.Name()) + if _, err := os.Stat(filepath.Join(child, ".git")); err == nil && !bound(context.Background(), child) { + out = append(out, child) // one with its own binding is split off: its own Project + } + } + for _, rel := range readMarker(dir).Folders { + p := filepath.Join(dir, filepath.FromSlash(rel)) + if fi, err := os.Stat(p); err == nil && fi.IsDir() { + out = append(out, p) + } + } + sort.Strings(out) + return slices.Compact(out) +} + +// Targets are the folders that take agent and git hooks for a Project: its +// root, and each member repository when it is a workspace. +func Targets(root string) []string { + if !IsWorkspace(root) { + return []string{root} + } + return append([]string{root}, Members(root)...) +} + +// InRepo reports whether dir is inside a git work tree or git dir. +func InRepo(ctx context.Context, dir string) bool { + _, err := gitOut(ctx, dir, "rev-parse", "--git-dir") + return err == nil +} + +// workspaceAbove finds the nearest bound workspace strictly above dir. +func workspaceAbove(ctx context.Context, dir string) (string, bool) { + for d := filepath.Dir(dir); ; d = filepath.Dir(d) { + if IsWorkspace(d) && bound(ctx, d) { + return d, true + } + if d == filepath.Dir(d) { + return "", false + } + } +} + +// markerAt reports a workspace marker in dir or any ancestor: a cheap stat +// walk that spares the common case a store open. +func markerAt(dir string) bool { + for d := dir; ; d = filepath.Dir(d) { + if IsWorkspace(d) { + return true + } + if d == filepath.Dir(d) { + return false + } + } +} + +// MemoryRoot is where shared memory lives for cwd: the workspace folder when +// cwd belongs to a workspace, else the repository's scope root (ADR-0007). +func MemoryRoot(ctx context.Context, cwd string) string { + scope := ScopeRoot(ctx, cwd) + start, err := Canonical(cwd) + if err != nil || !markerAt(start) { + return scope + } + if p, err := Discover(ctx, start); err == nil { + return p.ScopeRoot + } + return scope +} + +// PlainProjectAbove is the nearest bound folder above dir's scope root that +// is not a workspace, or "": the Project a repository created inside an +// already bound folder would join once that folder is made a workspace. +func PlainProjectAbove(ctx context.Context, dir string) string { + for d := filepath.Dir(ScopeRoot(ctx, dir)); ; d = filepath.Dir(d) { + if bound(ctx, d) { + if IsWorkspace(d) { + return "" + } + return d + } + if d == filepath.Dir(d) { + return "" + } + } +} diff --git a/internal/project/workspace_test.go b/internal/project/workspace_test.go new file mode 100644 index 0000000..a14647b --- /dev/null +++ b/internal/project/workspace_test.go @@ -0,0 +1,134 @@ +package project + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" +) + +// newWorkspace is acme-shop/ (outside git) holding the repositories frontend/ +// and backend/, a plain folder docs/, and nothing bound. +func newWorkspace(t *testing.T) (mother, frontend, backend string) { + t.Helper() + mother = filepath.Join(t.TempDir(), "acme-shop") + frontend, backend = filepath.Join(mother, "frontend"), filepath.Join(mother, "backend") + for _, d := range []string{filepath.Join(frontend, "src"), filepath.Join(backend, "api"), filepath.Join(mother, "docs")} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + git(t, frontend, "init", "-q") + git(t, backend, "init", "-q") + return mother, frontend, backend +} + +func TestMembersAreTheChildRepositories(t *testing.T) { + mother, frontend, backend := newWorkspace(t) + // A linked worktree's .git is a file; it counts too. + if err := os.MkdirAll(filepath.Join(mother, "wt"), 0o755); err != nil { + t.Fatal(err) + } + _ = os.WriteFile(filepath.Join(mother, "wt", ".git"), []byte("gitdir: elsewhere\n"), 0o644) + bind(t, mother) // its .atlas/ is not a member + + got := Members(mother) + want := []string{backend, frontend, filepath.Join(mother, "wt")} + if len(got) != len(want) { + t.Fatalf("members %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("members %v, want %v", got, want) + } + } +} + +func TestWorkspaceMarker(t *testing.T) { + dir := t.TempDir() + if IsWorkspace(dir) { + t.Fatal("no marker must mean no workspace") + } + if err := SetWorkspace(dir, true); err != nil { + t.Fatal(err) + } + if !IsWorkspace(dir) { + t.Fatal("marker not read back") + } + if got := Targets(dir); len(got) != 1 || got[0] != dir { + t.Fatalf("targets of an empty workspace: %v", got) + } + if err := SetWorkspace(dir, false); err != nil { + t.Fatal(err) + } + if IsWorkspace(dir) { + t.Fatal("marker not removed") + } + if err := SetWorkspace(dir, false); err != nil { + t.Fatalf("removing an absent marker: %v", err) + } +} + +func TestDiscoverFindsTheWorkspaceFromAMemberRepository(t *testing.T) { + ctx := context.Background() + mother, frontend, backend := newWorkspace(t) + m := canon(t, mother) + + // A plain binding above a repository is still not found (ADR-0007). + bind(t, mother) + if _, err := Discover(ctx, backend); !errors.Is(err, ErrNotInitialised) { + t.Fatalf("plain binding crossed the scope root: %v", err) + } + if got := PlainProjectAbove(ctx, backend); got != m { + t.Fatalf("plain Project above: %q, want %q", got, m) + } + if got := MemoryRoot(ctx, backend); got != canon(t, backend) { + t.Fatalf("memory without a workspace: %q", got) + } + + if err := SetWorkspace(mother, true); err != nil { + t.Fatal(err) + } + for _, dir := range []string{filepath.Join(backend, "api"), frontend, filepath.Join(mother, "docs"), mother} { + p, err := Discover(ctx, dir) + if err != nil { + t.Fatalf("%s: %v", dir, err) + } + if p.Root != m || p.ScopeRoot != m || !p.Workspace || p.Cwd != canon(t, dir) { + t.Fatalf("%s: %+v", dir, p) + } + if got := MemoryRoot(ctx, dir); got != m { + t.Fatalf("%s: memory at %q, want %q", dir, got, m) + } + } + if got := PlainProjectAbove(ctx, backend); got != "" { + t.Fatalf("a workspace is not a plain Project above: %q", got) + } + if got := Targets(m); len(got) != 3 || got[0] != m || got[1] != canon(t, backend) || got[2] != canon(t, frontend) { + t.Fatalf("targets %v", got) + } + + // A member bound on its own is split off: its own Project and memory. + bind(t, backend) + p, err := Discover(ctx, filepath.Join(backend, "api")) + if err != nil { + t.Fatal(err) + } + if p.Root != canon(t, backend) || p.Workspace || p.ScopeRoot != canon(t, backend) { + t.Fatalf("split-off member: %+v", p) + } + if got := MemoryRoot(ctx, backend); got != canon(t, backend) { + t.Fatalf("split-off member memory: %q", got) + } +} + +func TestAWorkspaceMarkerWithoutABindingIsIgnored(t *testing.T) { + mother, _, backend := newWorkspace(t) + if err := SetWorkspace(mother, true); err != nil { + t.Fatal(err) + } + if _, err := Discover(context.Background(), backend); !errors.Is(err, ErrNotInitialised) { + t.Fatalf("unbound workspace: %v", err) + } +}