### Usage example: start watching and handle events Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Shows how to start watching, subscribe to events, and process batches of BeanEvent. The channel receives batches after a 100 ms debounce; slow subscribers may have events dropped. ```go if err := core.StartWatching(); err != nil { log.Fatal(err) } defer core.Unwatch() eventCh, unsubscribe := core.Subscribe() defer unsubscribe() for events := range eventCh { for _, ev := range events { fmt.Println(ev.BeanID, ev.Type) } } ``` -------------------------------- ### Example: GetOrCreate and session usage Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/terminal.md Shows how to create or get a session, attach to it, write input, and read output. Uses `GetOrCreate` with a session ID, work directory, and dimensions, then attaches and writes a command. ```go mgr := terminal.NewManager(nil) sess, reconnected, err := mgr.GetOrCreate("__central__", projectRoot, 80, 24) scrollback, outputCh := sess.Attach() defer sess.Detach(outputCh) sess.Write([]byte("ls\n")) for data := range outputCh { fmt.Print(string(data)) } ``` -------------------------------- ### Example: creating a Manager with options Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Example of constructing a Manager with configuration values from a config object. ```go mgr := worktree.NewManager(repoRoot, worktreeRoot, cfg.GetWorktreeBaseRef(), cfg.GetWorktreeSetup(), worktree.WithFetchTimeout(cfg.GetWorktreeFetchTimeout()), ) ``` -------------------------------- ### Run the development server with npm run dev Source: https://github.com/hmans/beans/blob/main/frontend/README.md Start the development server after installing dependencies with npm install, pnpm install, or yarn. Add -- --open to automatically open the app in a new browser tab. ```sh npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Example: creating a worktree Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Example of creating a worktree and printing its branch and path. The branch becomes beans/ and the path is /. ```go wt, err := mgr.Create("beans-abc1") if err != nil { return err } fmt.Println(wt.Branch, wt.Path) // "beans/beans-abc1", ".../worktrees/beans-abc1" ``` -------------------------------- ### Usage example: detect forge and find PR Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/forge.md Shows how to use `forge.Detect` to get a provider, check for nil, and call `FindPR`. If the PR exists and `CanMerge()` is true, it prints a message. This example is from the package documentation. ```go provider := forge.Detect(projectRoot) if provider == nil { log.Println("no forge detected") return } pr, err := provider.FindPR(ctx, projectRoot, branch) if err != nil { return err } if pr != nil && pr.CanMerge() { fmt.Printf("PR #%d is ready to merge\n", pr.Number) } ``` -------------------------------- ### Manager instantiation example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/agent.md Example of creating a Manager with a context provider that returns a worktree-specific prompt, using the default mode from configuration. The manager is shut down with defer. ```go mgr := agent.NewManager(".beans", func(beanID string) string { return "You are working in worktree " + beanID }, agent.DefaultMode(cfg.GetDefaultMode())) defer mgr.Shutdown() ``` -------------------------------- ### SetOnSetupDone Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Sets a callback that is fired when a setup command finishes. On failure, success is false and trimmed output is provided as errMsg. ```APIDOC ## SetOnSetupDone ### Description Sets a callback that is fired when a setup command finishes. On failure, success is false and trimmed output is provided as errMsg. ### Signature `func (m *Manager) SetOnSetupDone(fn SetupDoneFunc)` ### Parameters - `fn` (SetupDoneFunc) - Required - The callback function. ``` -------------------------------- ### Install beans via Go Source: https://github.com/hmans/beans/blob/main/README.md Install the beans CLI tool directly using Go. Requires Go to be installed on your system. ```bash go install github.com/hmans/beans@latest ``` -------------------------------- ### Render usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/bean.md Example of calling b.Render() and writing the result to a file. It writes the content to the same file with permissions 0o644. ```go content, err := b.Render() if err != nil { return err } os.WriteFile(".beans/beans-abc1--login.md", content, 0o644) ``` -------------------------------- ### Install beans via Homebrew Source: https://github.com/hmans/beans/blob/main/README.md Install the beans CLI tool via Homebrew. Requires Homebrew to be installed on your system. ```bash brew install hmans/beans/beans ``` -------------------------------- ### CheckAllLinks usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Shows how to call CheckAllLinks and check for issues using HasIssues and TotalIssues. ```go result := core.CheckAllLinks() if result.HasIssues() { fmt.Printf("%d link issues\n", result.TotalIssues()) } ``` -------------------------------- ### Search usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/search.md Shows how to create an index, bulk-index beans, and search with a query string and limit. The comment notes that limit 0 uses DefaultSearchLimit. ```go idx, err := search.NewIndex() if err != nil { log.Fatal(err) } defer idx.Close() if err := idx.IndexBeans(core.All()); err != nil { return err } ids, err := idx.Search("auth*", 50) // limit 50; 0 uses DefaultSearchLimit if err != nil { return err } for _, id := range ids { fmt.Println(id) } ``` -------------------------------- ### Types: SetupStatus, Worktree, SetupDoneFunc, ManagerOption Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Defines the setup status enum, the Worktree struct with metadata fields, the setup completion callback, and the manager option function type. ```go type SetupStatus string const ( SetupNone SetupStatus = "" // no setup configured or already done SetupRunning SetupStatus = "running" SetupDone SetupStatus = "done" SetupFailed SetupStatus = "failed" ) type Worktree struct { ID string Branch string Path string Name string // Human-readable name Description string // Auto-generated summary BeanIDs []string // Bean IDs detected from changes vs base branch Setup SetupStatus // post-creation setup status (runtime only) SetupError string // error message if setup failed LastActiveAt time.Time // when an agent last completed a turn } type SetupDoneFunc func(worktreeID string, success bool, errMsg string) type ManagerOption func(*Manager) ``` -------------------------------- ### Using WithPersist and WithWorktreePath in Update calls Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Shows two usage examples: a runtime-only update (e.g. status flip when starting work on a bean) using WithPersist(false), and writing to a worktree's .beans dir instead of main using WithWorktreePath(wtPath). ```go // Runtime-only update (e.g. status flip when starting work on a bean): err := core.Update(b, nil, beancore.WithPersist(false)) if err != nil { return err } // Write to a worktree's .beans dir instead of main: err = core.Update(b, nil, beancore.WithWorktreePath(wtPath)) ``` -------------------------------- ### Usage example: NewID, BuildFilename, Slugify Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/bean.md Shows how to create a bean ID with a prefix, build a filename from a slug, and print the result. The example uses `bean.NewID("myproj-", 4)` and `bean.Slugify("Login bug")` to produce a filename like `myproj-a1b2--login-bug.md`. ```go id, err := bean.NewID("myproj-", 4) // e.g. "myproj-a1b2" if err != nil { log.Fatal(err) } filename := bean.BuildFilename(id, bean.Slugify("Login bug")) fmt.Println(filename) // e.g. "myproj-a1b2--login-bug.md" ``` -------------------------------- ### CreateBean usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beangraph.md Example of calling CreateBean with a sample input. The input sets Title, Type, Body, and Tags. The resolver returns the created bean and an error, which should be checked. ```go input := model.CreateBeanInput{ Title: "Fix login redirect", Type: ptr("bug"), Body: ptr("The /login route bounces back to /"), Tags: []string{"auth"}, } b, err := resolver.CreateBean(context.Background(), input) ``` -------------------------------- ### Loading config and using getters Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/config.md Example usage of loading config from the current directory, printing the default status and status names, and retrieving bean colors for a given status, type, and priority. ```go cfg = config.LoadFromDirectory(".") fmt.Println(cfg.GetDefaultStatus(), cfg.StatusNames()) colors := cfg.GetBeanColors("in-progress", "task", "high") ``` -------------------------------- ### Parse usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/bean.md Example of calling bean.Parse on a file. It opens a file, parses it, and prints the title, status, and body. On error, it logs a fatal message. ```go f, _ := os.Open(".beans/beans-abc1--login.md") defer f.Close() b, err := bean.Parse(f) if err != nil { log.Fatalf("parse: %v", err) } fmt.Println(b.Title, b.Status, b.Body) ``` -------------------------------- ### StartWatching Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Starts watching the .beans tree for changes. This is the preferred API to begin monitoring; use with Subscribe(). ```APIDOC ## StartWatching ### Description Preferred API — begins monitoring the .beans tree for changes. Use with Subscribe(). ### Method StartWatching ### Signature func (c *Core) StartWatching() error ### Parameters None ### Returns - **error** - Returns an error if starting the watcher fails. ### Example ```go if err := core.StartWatching(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### UpdateBean usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beangraph.md Example of calling UpdateBean with a sample input that sets Status and BodyMod. The BodyMod includes a Replace operation and an Append operation. The error is checked for ErrNotFound. ```go input := model.UpdateBeanInput{ Status: ptr("in-progress"), BodyMod: &model.BodyModification{ Replace: []*model.ReplaceOperation{{Old: "TODO", New: "DONE"}}, Append: ptr("## Notes\nSee tracking issue."), }, } b, err := resolver.UpdateBean(ctx, "beans-abc1", input) if errors.Is(err, beancore.ErrNotFound) { /* ... */ } ``` -------------------------------- ### Core watching and subscription methods Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Declares the Core methods for subscribing to events, starting and stopping file watching, and the deprecated Watch callback API. ```go func (c *Core) Subscribe() (<-chan []BeanEvent, func()) func (c *Core) StartWatching() error func (c *Core) Watch(onChange func()) error func (c *Core) Unwatch() error ``` -------------------------------- ### startRun Source: https://github.com/hmans/beans/blob/main/_autodocs/endpoints.md Starts the configured run command for a workspace in a dedicated session. Returns the port on which the run is available. Errors if no run command is configured or the work directory cannot be resolved. ```APIDOC ## startRun ### Description Starts the configured run command for a workspace in a dedicated session. ### Method Mutation ### Endpoint startRun(workspaceId: ID!) ### Parameters #### Arguments - **workspaceId** (ID!) - Required - The ID of the workspace. ### Returns - **Int!** - The port on which the run is available. ### Errors - `no run command configured` - `cannot resolve work directory for workspace %q` ``` -------------------------------- ### Create and Remove methods Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Create and Remove methods. Create runs git worktree add and optionally a setup command. Remove runs git worktree remove --force. ```go func (m *Manager) Create(name string) (*Worktree, error) func (m *Manager) Remove(id string) error ``` -------------------------------- ### Ask agent for next work recommendation Source: https://github.com/hmans/beans/blob/main/README.md Example natural language inquiry to ask your coding agent to recommend what to work on next when you already have some beans available. ```text What should we work on next? ``` -------------------------------- ### GET /playground Source: https://github.com/hmans/beans/blob/main/_autodocs/endpoints.md Serves the GraphQL Playground UI, configured to use the /api/graphql endpoint. ```APIDOC ## [GET] /playground ### Description Serves the GraphQL Playground UI for interactive exploration of the GraphQL API. ### Method GET ### Endpoint /playground ### Response #### Success Response (200) Returns the Playground HTML page. ``` -------------------------------- ### List Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Lists all beans-managed worktrees, enriched with metadata, detected bean IDs, and runtime setup status. Ordered by git's creation order (oldest first). ```APIDOC ## List ### Description Lists all beans-managed worktrees, enriched with metadata, detected bean IDs, and runtime setup status. Ordered by git's creation order (oldest first). ### Signature `func (m *Manager) List() ([]Worktree, error)` ### Returns - `[]Worktree` - The list of worktrees. - `error` - An error if listing fails. ``` -------------------------------- ### Create Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Creates a new worktree with the given name. The name doubles as the worktree ID. Runs fetch, git worktree add, persists metadata, and optionally runs a setup command asynchronously. ```APIDOC ## Create ### Description Creates a new worktree with the given name. The name doubles as the worktree ID. Runs fetch, git worktree add, persists metadata, and optionally runs a setup command asynchronously. ### Signature `func (m *Manager) Create(name string) (*Worktree, error)` ### Parameters - `name` (string) - Required - The worktree name/ID. Must be non-empty. ### Returns - `*Worktree` - The created worktree. - `error` - An error if creation fails. ### Behavior 1. The name doubles as the worktree ID (must be non-empty → error `worktree name must not be empty`). Branch becomes `beans/`, path `/`. 2. Fails with `worktree path already exists: %s` if the directory exists. 3. Runs `fetchBaseRef()` (bounded by `fetchTimeout`; skips when the remote doesn't exist; logs warnings on failure — a stale ref is preferable to refusing). 4. Runs `git worktree add -b [baseRef]`; error wraps the git output. 5. Persists metadata with `Name` and `LastActiveAt = now` (so new worktrees sort first). 6. If `setupCommand != ""`, runs `sh -c setupCommand` in the worktree asynchronously: status transitions `SetupRunning → SetupDone/SetupFailed`, then notifies subscribers and fires `onSetupDone`. ### Example ```go wt, err := mgr.Create("beans-abc1") if err != nil { return err } fmt.Println(wt.Branch, wt.Path) // "beans/beans-abc1", ".../worktrees/beans-abc1" ``` ``` -------------------------------- ### beans graphql usage examples Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/cli.md Three ways to run the `beans graphql` command: pass a query as an argument, pipe a query via stdin, or print the schema and exit with `--schema`. The query argument may be omitted when piping. ```bash beans graphql '{ beans(filter: { status: ["todo"] }) { id title } }' ``` ```bash echo '{ beans { id title } }' | beans graphql ``` ```bash beans graphql --schema ``` -------------------------------- ### Ask agent to create beans for tasks Source: https://github.com/hmans/beans/blob/main/README.md Example natural language inquiry to ask your coding agent to identify potential tasks and create beans for them after adding Beans to an existing project. ```text Are there any tasks we should be tracking for this project? If so, please create beans for them. ``` -------------------------------- ### .beans.yml reference configuration Source: https://github.com/hmans/beans/blob/main/_autodocs/configuration.md Reference layout from the repository's own .beans.yml. Shows all configuration keys: project.name, beans.path, beans.prefix, beans.id_length, beans.default_status, beans.default_type, worktree.base_ref, worktree.integrate, worktree.setup, worktree.run, agent.enabled, agent.default_mode, and server.port. Missing sections get defaults; statuses, types, and priorities are hardcoded. ```yaml # Beans configuration # See: https://github.com/hmans/beans project: # Human-readable project name (displayed in the UI) name: beans beans: # Directory where bean files are stored path: .beans # Prefix for bean IDs (e.g., "myproject-abc1") prefix: beans- # Length of the random ID suffix id_length: 4 # Default status for new beans default_status: todo # Default type for new beans default_type: task worktree: # Git ref to use as the base for new worktree branches (default: main) base_ref: origin/main integrate: pr # Shell command to run inside a worktree after creation (e.g. "pnpm install") setup: mise trust && mise setup # Shell command to run the project (adds a "Run" button to workspace toolbar) run: mise dev agent: # Enable agent functionality in the web UI (true, false) enabled: true # Default mode for agent sessions (act, plan) default_mode: act server: # Port for the web UI (used by `beans-serve`) port: 8080 ``` -------------------------------- ### SafeJoin usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/safepath.md Shows how to use safepath.SafeJoin to safely join a conversation directory with a bean ID to form a path. The function returns an error if the untrusted component escapes the root. ```go convDir := filepath.Join(beansDir, ".conversations") path, err := safepath.SafeJoin(convDir, "beans-abc1.jsonl") if err != nil { return "", fmt.Errorf("invalid conversation path: %w", err) } ``` -------------------------------- ### ValidateBeanID usage example Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/safepath.md Shows how to use safepath.ValidateBeanID to validate a bean ID before using it in a path. The function returns an error if the ID is empty or contains invalid characters. ```go if err := safepath.ValidateBeanID(beanID); err != nil { return fmt.Errorf("invalid bean ID for attachment: %w", err) } ``` -------------------------------- ### Allocator type and methods Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/auxiliary.md Declares the Allocator type and its methods. Allocate returns the existing port or the next free one (basePort + nextIndex*step, recycling freed ports LIFO). AllocateSpecific requests a specific port, returning the actual assignment; if taken by another workspace, a fresh port is allocated and nextIndex advances past the requested port. Free releases a port back to the pool. Get returns 0 and an error when unallocated. ```go type Allocator struct { ... } func New(basePort, step int) *Allocator func NewDefault() *Allocator func (a *Allocator) Allocate(workspaceID string) int func (a *Allocator) AllocateSpecific(workspaceID string, port int) int func (a *Allocator) Free(workspaceID string) func (a *Allocator) Get(workspaceID string) (int, error) ``` -------------------------------- ### Create and load a Core instance Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Shows how to construct a Core with a config loaded from the current directory, load it, and defer Close. The config may be nil, and Load or Init must be called before use. ```go cfg := config.LoadFromDirectory(".") core := beancore.New(cfg.ResolveBeansPath(), cfg) if err := core.Load(); err != nil { log.Fatal(err) } defer core.Close() ``` -------------------------------- ### Configure Claude Code hooks for Beans Source: https://github.com/hmans/beans/blob/main/README.md Manually add these hooks to your project's .claude/settings.json file to integrate Beans with Claude Code. The hooks run the beans prime command at session start and before compaction. ```json { "hooks": { "SessionStart": [ { "hooks": [{ "type": "command", "command": "beans prime" }] } ], "PreCompact": [ { "hooks": [{ "type": "command", "command": "beans prime" }] } ] } } ``` -------------------------------- ### Archive, Unarchive, and IsArchived method signatures Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Archive moves the file to .beans/archive/ (via os.Rename), updates Path, and emits an EventUpdated BeanEvent to subscribers. No-op if already archived. Unarchive moves the file back to the archive's parent (the main directory). IsArchived returns true when the bean's Path starts with archive/. ```go func (c *Core) Archive(id string) error func (c *Core) Unarchive(id string) error func (c *Core) IsArchived(id string) bool ``` -------------------------------- ### Ask agent to work on a specific bean Source: https://github.com/hmans/beans/blob/main/README.md Example natural language inquiry to ask your coding agent to start working on a particular bean, identified by its ID. ```text It's time to tackle myproj-123. ``` -------------------------------- ### Init, FullPath, and Close method signatures Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Init creates the root directory (os.MkdirAll(..., 0755)) and writes the .gitignore (method version — see also the standalone Init(dir)). FullPath returns the absolute path of a bean file: filepath.Join(c.root, b.Path). Close unwatches all worktrees, closes the search index if open, stops the main watcher, and closes all subscriber channels. ```go func (c *Core) Init() error func (c *Core) FullPath(b *bean.Bean) string func (c *Core) Close() error ``` -------------------------------- ### Allocating ports for workspaces Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/auxiliary.md Shows how to create a default allocator, allocate a port for the central workspace, request a specific port for a worktree, and print the results. ```go alloc := portalloc.NewDefault() port := alloc.Allocate("__central__") worktreePort := alloc.AllocateSpecific("wt-1", 44010) fmt.Println(port, worktreePort) ``` -------------------------------- ### New Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Constructor for creating a new Core instance. ```APIDOC ## Constructor: New ### Description Creates a new Core instance rooted at the given absolute path to the .beans directory with the provided configuration. The configuration may be nil, and callers must call Load() or Init() before use. ### Signature func New(root string, cfg *config.Config) *Core ### Parameters - **root** (string) - Required - Absolute path to the .beans directory. - **cfg** (*config.Config) - Optional - Configuration to use; may be nil. ### Returns - *Core - A new Core instance. ### Example ```go cfg := config.LoadFromDirectory(".") core := beancore.New(cfg.ResolveBeansPath(), cfg) if err := core.Load(); err != nil { log.Fatal(err) } defer core.Close() ``` ``` -------------------------------- ### Build the production version with npm run build Source: https://github.com/hmans/beans/blob/main/frontend/README.md Create a production version of the app. Preview the production build with npm run preview. ```sh npm run build ``` -------------------------------- ### Get Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Retrieves a bean by its ID, with prefix fallback. ```APIDOC ## Method: Get ### Description Performs an exact-ID lookup, retrying with a configured prefix if not found and the ID doesn't already carry it. Returns ErrNotFound when no match exists. ### Signature func (c *Core) Get(id string) (*bean.Bean, error) ### Parameters - **id** (string) - Required - Bean ID to look up. ### Returns - *bean.Bean - The found bean, or nil. - error - ErrNotFound if not found, otherwise nil. ### Example ```go bean, err := core.Get("abc1") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### GenerateDescription and GenerateQuickReplies signatures Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/agent.md GenerateDescription runs claude --print --model haiku --no-session-persistence --disable-slash-commands --strict-mcp-config --mcp-config {"mcpServers":{}} with the prompt on stdin (never argv) to summarize the first user message in 3-8 words, returning "" on error. GenerateQuickReplies uses the same invocation to suggest 3-4 follow-up replies (<10 words each) given the last assistant message and optional workspace context, returning nil on error. Output is capped at 4 and formatting artifacts (bullets, numbering, quotes) are stripped. ```go func GenerateDescription(message string) string func GenerateQuickReplies(message string, workspaceContext string) []string ``` -------------------------------- ### Init function creates .beans directory and .gitignore Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md The Init function creates /.beans and writes a .gitignore file with the given content. The .gitignore content is shown as a text block. ```text # Generated by beans init .conversations/ ``` -------------------------------- ### Show beans CLI help Source: https://github.com/hmans/beans/blob/main/README.md Display a list of available beans CLI commands. ```bash beans help ``` -------------------------------- ### LoadFromDirectoryWithin(startDir, rootDir string) Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/config.md Discovers and loads a config file anchored at a directory, stopping at rootDir. When no config file is found, returns Default() anchored at startDir. ```APIDOC ## LoadFromDirectoryWithin(startDir, rootDir string) ### Description Discovers and loads a config file anchored at a directory, stopping at rootDir. When no config file is found, returns Default() anchored at startDir. ### Signature ```go func LoadFromDirectoryWithin(startDir, rootDir string) (*Config, error) ``` ### Parameters - **startDir** (string) - Required - The directory to start discovery from. - **rootDir** (string) - Required - The directory to stop discovery at (inclusive; empty means filesystem root). ### Returns - **Config** (object) - The loaded Config, or Default() anchored at startDir if not found. - **error** - An error if discovery or loading fails. ``` -------------------------------- ### sendAgentMessage Source: https://github.com/hmans/beans/blob/main/_autodocs/endpoints.md Sends a message to an agent associated with a bean. Starts a session if needed. Images are base64-decoded and stored with size and format limits. ```APIDOC ## sendAgentMessage ### Description Sends a message to an agent associated with a bean. Starts a session if needed. ### Method Mutation ### Endpoint sendAgentMessage(beanId: ID!, message: String!, images: [ImageInput!], attachments: [FileAttachmentInput!]) ### Parameters #### Arguments - **beanId** (ID!) - Required - The ID of the bean. - **message** (String!) - Required - The message to send. - **images** ([ImageInput!]) - Optional - Images to include; base64-decoded and stored (5 MB / jpeg|png|gif|webp limits). - **attachments** ([FileAttachmentInput!]) - Optional - File attachments. ### Returns - **Boolean!** - True if the message was sent. ### Errors - `invalid base64 image data` ``` -------------------------------- ### ANY /api/graphql Source: https://github.com/hmans/beans/blob/main/_autodocs/endpoints.md GraphQL endpoint accepting GET, POST, and WebSocket upgrade requests. Supports queries, mutations, and subscriptions via the graphql-transport-ws protocol. ```APIDOC ## [ANY] /api/graphql ### Description GraphQL endpoint for executing queries, mutations, and subscriptions. Accepts GET, POST, and WebSocket upgrade requests. ### Method ANY (GET, POST, WebSocket) ### Endpoint /api/graphql ### Parameters #### Query Parameters (GET) - **query** (string) - Required - GraphQL query string - **variables** (object) - Optional - JSON-encoded variables for the query - **operationName** (string) - Optional - Name of the operation to execute #### Request Body (POST) - **query** (string) - Required - GraphQL query string - **variables** (object) - Optional - Variables for the query - **operationName** (string) - Optional - Name of the operation to execute ### Response #### Success Response (200) - **data** (object) - The result of the GraphQL operation - **errors** (array) - Optional - List of errors, each with a message ### Error Handling Validation errors are returned in the response body with HTTP 200, in the `errors[].message` field. ``` -------------------------------- ### Create a Svelte project with npx sv create Source: https://github.com/hmans/beans/blob/main/frontend/README.md Use the sv CLI to scaffold a new Svelte project. Run without arguments to create in the current directory, or pass a project name to create a subdirectory. ```sh # create a new project in the current directory npx sv create # create a new project in my-app npx sv create my-app ``` -------------------------------- ### Sentinel error ErrNotFound Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Sentinel error returned by Get, Delete, SaveBean, Archive/Unarchive, and findBeanLocked when a bean is not found. Compare with errors.Is(err, beancore.ErrNotFound). ```go var ErrNotFound = errors.New("bean not found") ``` -------------------------------- ### LoadFromDirectory(startDir string) Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/config.md Discovers and loads a config file anchored at a directory. When no config file is found, returns Default() anchored at startDir. ```APIDOC ## LoadFromDirectory(startDir string) ### Description Discovers and loads a config file anchored at a directory. When no config file is found, returns Default() anchored at startDir. ### Signature ```go func LoadFromDirectory(startDir string) (*Config, error) ``` ### Parameters - **startDir** (string) - Required - The directory to start discovery from. ### Returns - **Config** (object) - The loaded Config, or Default() anchored at startDir if not found. - **error** - An error if discovery or loading fails. ``` -------------------------------- ### GET /api/attachments/:beanId/:filename Source: https://github.com/hmans/beans/blob/main/_autodocs/endpoints.md Serves stored agent-chat image attachments. Resolves the file path from the bean ID and filename, with path-traversal protection. ```APIDOC ## [GET] /api/attachments/:beanId/:filename ### Description Serves stored agent-chat image attachments. The file is resolved from the bean ID and filename, with path-traversal protection. ### Method GET ### Endpoint /api/attachments/:beanId/:filename ### Parameters #### Path Parameters - **beanId** (string) - Required - The bean identifier - **filename** (string) - Required - The attachment filename ### Response #### Success Response (200) Returns the image file with `Content-Disposition: inline` and `X-Content-Type-Options: nosniff`. #### Error Responses - **400** - Unknown bean or session store - **404** - File not found ``` -------------------------------- ### NewManager Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Creates a new Manager instance with the given repository root, worktree root, base ref, and setup command. Options can be provided to customize behavior. ```APIDOC ## NewManager ### Description Creates a new Manager instance with the given repository root, worktree root, base ref, and setup command. Options can be provided to customize behavior. ### Signature `func NewManager(repoRoot, worktreeRoot, baseRef, setupCommand string, opts ...ManagerOption) *Manager` ### Parameters - `repoRoot` (string) - Required - Main repository root. - `worktreeRoot` (string) - Required - Directory where worktrees are created. - `baseRef` (string) - Required - Git ref to branch from (e.g. `main` or `origin/main`). - `setupCommand` (string) - Required - Optional shell command run inside a new worktree after creation. - `opts` (ManagerOption) - Optional - Variadic options to customize the manager. ### Example ```go mgr := worktree.NewManager(repoRoot, worktreeRoot, cfg.GetWorktreeBaseRef(), cfg.GetWorktreeSetup(), worktree.WithFetchTimeout(cfg.GetWorktreeFetchTimeout()), ) ``` ``` -------------------------------- ### beans init Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/cli.md Initializes a new Beans project by creating the `.beans` directory and configuration file. Supports JSON output and a custom beans path. ```APIDOC ## beans init ### Description Initializes a new Beans project by creating the `.beans` directory and `.beans.yml` configuration file. When `--beans-path` is provided, only the directory (plus `.gitignore`) is created, avoiding config file creation in unrelated parent directories. ### Method CLI Command ### Endpoint `beans init` ### Parameters #### Flags - `--json` (bool) - Optional - Output result as JSON. - `--beans-path` (string) - Optional - Overrides the beans directory path (lower precedence than `--beans-path` flag). ### Behavior - Without `--beans-path`: calls `beancore.Init(cwd)` and writes a config built by `config.DefaultWithPrefix(-)` with `Project.Name = `, auto-detecting the remote default branch as `worktree.base_ref` when in a git repo. - With `--beans-path`: only creates the directory and `.gitignore`. - JSON mode prints `SuccessInit(path)`; text mode prints `Initialized beans project`. ### Response #### Success Response - JSON mode: `SuccessInit(path)` - Text mode: `Initialized beans project` ``` -------------------------------- ### AttachmentPath method Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/agent.md Resolves the on-disk path for a stored image, served by GET /api/attachments/:beanId/:filename. Errors with 'no store configured' when no store is set. ```go func (m *Manager) AttachmentPath(beanID, imageID string) (string, error) ``` -------------------------------- ### Ask agent to reorganize beans into epics Source: https://github.com/hmans/beans/blob/main/README.md Example natural language inquiry to ask your coding agent to restructure tasks by reorganizing beans into epics and creating milestones. ```text Please inspect this project's beans and reorganize them into epics. Also please create 2-3 milestones to group these epics in a meaningful way. ``` -------------------------------- ### Using FileChanges and DiscardFileChange Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/gitutil.md Shows how to retrieve all file changes in a worktree using gitutil.FileChanges and print them with status, path, and addition/deletion counts. Then demonstrates discarding a change to a specific file with gitutil.DiscardFileChange, passing the worktree path, file path, and a staged flag (false here). ```go changes, err := gitutil.FileChanges(wt.Path) if err != nil { return err } for _, c := range changes { fmt.Printf("%s %s (+%d -%d)\n", c.Status, c.Path, c.Additions, c.Deletions) } if err := gitutil.DiscardFileChange(wt.Path, "src/broken.go", false); err != nil { return err } ``` -------------------------------- ### Subscription and running sessions methods Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/agent.md Subscription methods for per-session and global signal channels, plus ListRunningSessions to report in-memory sessions with RUNNING status. ```go func (m *Manager) Subscribe(beanID string) chan struct{} func (m *Manager) Unsubscribe(beanID string, ch chan struct{}) func (m *Manager) SubscribeGlobal() chan struct{} func (m *Manager) UnsubscribeGlobal(ch chan struct{}) func (m *Manager) ListRunningSessions() []ActiveAgent ``` -------------------------------- ### DefaultWithPrefix(prefix string) Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/config.md Returns a new Config with default values and a custom prefix. ```APIDOC ## DefaultWithPrefix(prefix string) ### Description Returns a new Config with default values and a custom prefix. ### Signature ```go func DefaultWithPrefix(prefix string) *Config ``` ### Parameters - **prefix** (string) - Required - The prefix to set for Beans.Prefix. ### Returns - **Config** (object) - A Config with default values, with `Beans.Prefix` set to the provided prefix. ``` -------------------------------- ### Create method signature Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Adds a new bean. Generates an ID from config (prefix, id_length, default length 4) if b.ID is empty; sets CreatedAt/UpdatedAt to now (UTC, truncated to seconds). With default options the bean is written to disk immediately; with WithPersist(false) it is only added to memory and marked dirty. The search index is updated best-effort (failures only warn). Errors wrap bean.NewID or disk write failures. ```go func (c *Core) Create(b *bean.Bean, opts ...UpdateOption) error ``` -------------------------------- ### GET /api/terminal (WebSocket) Source: https://github.com/hmans/beans/blob/main/_autodocs/endpoints.md WebSocket endpoint for PTY bridging, enabling embedded terminal sessions. Uses a JSON init frame followed by input and resize frames. ```APIDOC ## [GET] /api/terminal (WebSocket) ### Description WebSocket endpoint for PTY bridging, enabling embedded terminal sessions. The client sends an init frame, then input and resize frames. ### Method GET (WebSocket upgrade) ### Endpoint /api/terminal ### WebSocket Protocol #### Client → Server Frames - **init** (JSON) - Required first frame: `{"type": "init", "sessionId": "__central__", "cols": 80, "rows": 24}`. `sessionId` is `__central__` (project root) or a worktree ID; a `__run` suffix is stripped for directory lookup. - **input** (JSON) - `{"type": "input", "data": "..."}` - Write data to the PTY. - **resize** (JSON) - `{"type": "resize", "cols": N, "rows": N}` - Resize the PTY. #### Server → Client Frames - Binary frames with PTY output. - On reconnect, buffered scrollback (64 KB) is replayed first. - On shell exit, a close frame `CloseNormalClosure "shell exited"` is sent. ### Error Handling - Missing or bad init frame → close with `CloseProtocolError`. - Unknown session → `CloseProtocolError`. - PTY creation failure → `CloseInternalServerErr`. ``` -------------------------------- ### Add commit message instruction to AGENTS.md Source: https://github.com/hmans/beans/blob/main/README.md Example Beans-specific instruction to add to your AGENTS.md, CLAUDE.md, or equivalent file, telling the agent to include relevant bean IDs in commit messages. ```text When making a commit, include the relevant bean IDs in the commit message ``` -------------------------------- ### SetSystemPromptProvider Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/agent.md Sets a per-session system prompt provider. The returned string is appended via `--append-system-prompt` and persists across `--resume`. ```APIDOC ## SetSystemPromptProvider ### Description Sets a per-session system prompt provider. The returned string is appended via `--append-system-prompt` and persists across `--resume`. ### Method Configuration hook ### Signature ```go func (m *Manager) SetSystemPromptProvider(fn SystemPromptProvider) ``` ### Parameters - **fn** (SystemPromptProvider) - Required - Function that returns the system prompt string for a given bean ID. ``` -------------------------------- ### List and DetectBeanIDs methods Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Listing and detection methods. List shells out to git worktree list --porcelain and parses entries. DetectBeanIDs returns bean IDs from .beans/*.md files that differ from the base ref. ```go func (m *Manager) List() ([]Worktree, error) func (m *Manager) DetectBeanIDs(worktreePath string) []string ``` -------------------------------- ### Constants: DefaultFetchTimeout and branchPrefix Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/worktree.md Defines the default fetch timeout and the branch prefix for beans-managed worktrees. `List()` only reports worktrees whose branch starts with `beans/` or detached worktrees inside the configured root. ```go const DefaultFetchTimeout = 10 * time.Second const branchPrefix = "beans/" ``` -------------------------------- ### Tag validation and normalization functions Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/bean.md `ValidateTag` returns an error if the tag is empty or does not match `^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$` (lowercase, URL-safe, starts with a letter, hyphens not consecutive or trailing). `NormalizeTag` returns `strings.ToLower(strings.TrimSpace(tag))`. ```go func ValidateTag(tag string) error func NormalizeTag(tag string) string ``` -------------------------------- ### All Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beancore.md Returns all beans in the store. ```APIDOC ## Method: All ### Description Returns a slice of all beans in the store, unordered. ### Signature func (c *Core) All() []*bean.Bean ### Parameters None. ### Returns - []*bean.Bean - Slice of all beans. ### Example ```go beans := core.All() ``` ``` -------------------------------- ### Initialize Beans in project Source: https://github.com/hmans/beans/blob/main/README.md Initialize Beans in the root directory of your project. Creates a .beans/ directory and a .beans.yml configuration file at the project root, both meant to be tracked in version control. ```bash beans init ``` -------------------------------- ### Body content helpers: ReplaceOnce, UnescapeBody, AppendWithSeparator Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/bean.md Body content helpers from pkg/bean/content.go: ReplaceOnce replaces exactly one occurrence, UnescapeBody converts escape sequences, and AppendWithSeparator appends with a blank line separator. The usage example shows ReplaceOnce failing if the pattern appears twice and then appending a summary. ```go func ReplaceOnce(text, old, new string) (string, error) ``` ```go func UnescapeBody(s string) string ``` ```go func AppendWithSeparator(text, addition string) string ``` ```go body, err := bean.ReplaceOnce(b.Body, "TODO", "DONE") // fails if "TODO" appears twice if err != nil { return err } b.Body = bean.AppendWithSeparator(body, "## Summary of Changes\n...") ``` -------------------------------- ### Save(dir string) Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/config.md Writes the config as YAML (4-space indentation) to `.beans.yml` — in `c.configDir` when set, else `dir` — with inline `#` comments for each key. This is what `beans init` uses. ```APIDOC ## Save(dir string) ### Description Writes the config as YAML (4-space indentation) to `.beans.yml` — in `c.configDir` when set, else `dir` — with inline `#` comments for each key. This is what `beans init` uses. ### Signature ```go func (c *Config) Save(dir string) error ``` ### Parameters - **dir** (string) - Required - The directory to write the config file to, if `c.configDir` is not set. ### Returns - **error** - An error if writing fails. ``` -------------------------------- ### Instantiate CoreResolver and call Bean Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beangraph.md Instantiates a CoreResolver with a loaded core and calls the Bean method with a context and bean ID. The method returns a bean or error. ```go resolver := &beangraph.CoreResolver{Core: core} b, err := resolver.Bean(context.Background(), "abc1") ``` -------------------------------- ### SortByStatusPriorityAndType function signature and usage Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/bean.md The function signature and a usage example for the in-place sort used by the CLI, TUI, and GraphQL beans query. The sort prioritizes status order, then manual fractional order, then priority order (empty priority treated as "normal"), then type order, and finally case-insensitive title. Unrecognized statuses, priorities, and types sort last. ```go func SortByStatusPriorityAndType(beans []*Bean, statusNames, priorityNames, typeNames []string) ``` ```go beans := core.All() bean.SortByStatusPriorityAndType(beans, cfg.StatusNames(), cfg.PriorityNames(), cfg.TypeNames()) ``` -------------------------------- ### Launch Beans interactive TUI Source: https://github.com/hmans/beans/blob/main/README.md Run this command to launch the interactive TUI. ```bash beans tui ``` -------------------------------- ### FindConfigWithin(startDir, rootDir string) Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/config.md Searches upward from startDir for a `.beans.yml` file, stopping at rootDir (inclusive). ```APIDOC ## FindConfigWithin(startDir, rootDir string) ### Description Searches upward from startDir for a `.beans.yml` file, stopping at rootDir (inclusive). ### Signature ```go func FindConfigWithin(startDir, rootDir string) (string, error) ``` ### Parameters - **startDir** (string) - Required - The directory to start searching from. - **rootDir** (string) - Required - The directory to stop searching at (inclusive; empty means filesystem root). ### Returns - **string** - The absolute path to the config file, or `""` if not found. - **error** - An error if the search fails. ``` -------------------------------- ### ProjectName Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beangraph.md Returns the project name from the configuration. ```APIDOC ## [QUERY] ProjectName ### Description Returns cfg.GetProjectName() ("" when config is nil or unset). ### Method QUERY ### Endpoint ProjectName ### Parameters #### Arguments - **ctx** (context.Context) - Required - The context for the operation. ### Response #### Success Response - **string** (string) - The project name, or empty string if not set. #### Response Example ```json "my-project" ``` ``` -------------------------------- ### ProjectName query method signature Source: https://github.com/hmans/beans/blob/main/_autodocs/api-reference/beangraph.md Method signature for ProjectName query. Returns cfg.GetProjectName() ("" when config is nil or unset). ```go func (r *CoreResolver) ProjectName(ctx context.Context) (string, error) ``` -------------------------------- ### Add Beans instruction to AGENTS.md Source: https://github.com/hmans/beans/blob/main/README.md Add this instruction to your AGENTS.md, CLAUDE.md, or equivalent file to teach your agent about Beans. It tells the agent to run the beans prime command before doing anything else. ```text **IMPORTANT**: before you do anything else, run the `beans prime` command and heed its output. ```