diff --git a/.github/workflows/docs-page-action.yml b/.github/workflows/docs-page-action.yml deleted file mode 100644 index b712948a0..000000000 --- a/.github/workflows/docs-page-action.yml +++ /dev/null @@ -1,2 +0,0 @@ -# This workflow is retired. Docs are now deployed to Cloudflare Pages via docs-deploy.yml. -# See docs-deploy.yml for the current deployment workflow targeting docs.protolabs.sh. diff --git a/.yamllint.yml b/.yamllint.yml index a98b6dbba..8b58b671d 100644 --- a/.yamllint.yml +++ b/.yamllint.yml @@ -73,7 +73,7 @@ rules: quoted-strings: quote-type: 'single' - required: true + required: false allow-quoted-quotes: true trailing-spaces: {} diff --git a/docs/beads-reference.md b/docs/beads-reference.md new file mode 100644 index 000000000..cc5f27d24 --- /dev/null +++ b/docs/beads-reference.md @@ -0,0 +1,879 @@ +# beads_rust (`br`) + proto Agent — Comprehensive Reference + +Generated: 2026-04-02 +`br` version: 0.1.23 +Tool path: `/home/josh/.cargo/bin/br` +Active workspace: `/home/josh/dev/labs/qwen-code/.beads/` + +--- + +## 1. What is beads_rust? + +`br` is an agent-first, per-project issue tracker backed by SQLite + JSONL. +Issues are stored in `.beads/beads.db` inside the working directory and are +flushed to JSONL for portability. The database auto-discovers itself by walking +up from the current directory, so all `br` commands work from any subdirectory +of the project. + +--- + +## 2. Global flags (apply to every subcommand) + +| Flag | Description | +| --------------------- | ----------------------------------------------------- | +| `--json` | Machine-readable JSON output | +| `--db ` | Override database path (auto-discovered by default) | +| `--actor ` | Actor name written to the audit trail | +| `--no-color` | Disable ANSI colour | +| `--quiet` / `-q` | Suppress all output except errors | +| `--verbose` / `-v` | Increase log verbosity (repeat for `-vv`) | +| `--allow-stale` | Skip freshness check warning | +| `--lock-timeout ` | SQLite busy timeout in ms | +| `--no-auto-flush` | Skip automatic JSONL export after write | +| `--no-auto-import` | Skip automatic JSONL import check on startup | +| `--no-db` | JSONL-only mode (no database connection) | +| `--no-daemon` | Force direct mode — no-op in v1 (already direct-only) | + +--- + +## 3. Full command reference + +### 3.1 Workspace management + +#### `br init` + +Initialize a `.beads/` workspace in the current directory. +Called automatically by the proto agent on first use. + +#### `br where` + +Print the path to the active `.beads/` directory. + +#### `br info` + +Show diagnostic metadata: database path, mode, daemon status, issue count, +prefix. + +#### `br config ` + +| Subcommand | Description | +| ------------------------ | ------------------------------------------------------------ | +| `list` | Print all config options (merged: defaults + project + user) | +| `get ` | Get a single value | +| `set ` | Persist a value | +| `delete ` / `unset` | Remove a value | +| `edit` | Open config file in `$EDITOR` | +| `path` | Show config file locations | + +Relevant config keys seen in this project's `config.yaml`: + +```yaml +issue_prefix: qwen-code # prefix for auto-generated IDs +default_priority: 2 # numeric (0=critical…4=backlog) +default_type: task +``` + +#### `br doctor` + +Run diagnostics and optionally repair issues (missing columns, schema drift, +etc.). + +#### `br upgrade` + +Upgrade `br` binary in-place to the latest release. + +--- + +### 3.2 Core CRUD + +#### `br create [TITLE] [OPTIONS]` + +Create a new issue. + +| Flag | Type | Description | +| ---------------------- | ------------------- | ------------------------------------------------------- | +| `TITLE` / `--title` | string | Issue title (1–500 chars) | +| `-t` / `--type` | string | `task` `bug` `feature` `epic` `chore` `docs` `question` | +| `-p` / `--priority` | 0–4 or P0–P4 | 0=critical, 1=high, 2=medium, 3=low, 4=backlog | +| `-d` / `--description` | string | Body / detailed description (alias `--body`) | +| `-a` / `--assignee` | string | Assign to a person | +| `--owner` | string | Set owner email | +| `-l` / `--labels` | comma-separated | Apply labels at creation | +| `--parent` | issue-id | Creates a parent-child dependency | +| `--deps` | `type:id,…` | Arbitrary dependency edges | +| `-e` / `--estimate` | minutes | Time estimate | +| `--due` | RFC3339 or relative | Due date | +| `--defer` | RFC3339 or relative | Defer until date | +| `--external-ref` | string | External reference (GitHub issue URL, etc.) | +| `-s` / `--status` | string | Initial status (default: `open`) | +| `--ephemeral` | flag | Not exported to JSONL | +| `--silent` | flag | Output only the new issue ID | +| `--dry-run` | flag | Preview without writing | +| `-f` / `--file` | path | Bulk-import from a Markdown file | + +Returns: full issue object (with `--json`). + +#### `br q [TITLE WORDS…] [OPTIONS]` + +Quick-capture — same as `create` but prints only the new ID. Useful for +scripting. Supports: `--priority`, `--type`, `--labels`, `--description`, +`--parent`, `--estimate`. + +#### `br show [IDS…] [OPTIONS]` + +Show full details of one or more issues. +Formats: `text` (default), `json`, `toon` (token-optimised). +Returns an **array** even for a single ID. + +#### `br update [IDS…] [OPTIONS]` + +Update one or more existing issues. + +| Flag | Description | +| ---------------------------------------- | ----------------------------------------------- | +| `--title` | New title | +| `--description` / `--body` | New description | +| `--design` | Technical design notes | +| `--acceptance-criteria` / `--acceptance` | Acceptance criteria | +| `--notes` | Additional notes | +| `-s` / `--status` | New status | +| `-p` / `--priority` | New priority | +| `-t` / `--type` | New issue type | +| `--assignee` | Assign (empty string clears) | +| `--owner` | Set owner (empty string clears) | +| `--claim` | Atomic: set assignee=actor + status=in_progress | +| `--due` | Set/clear due date | +| `--defer` | Set/clear defer date | +| `--estimate` | Time estimate in minutes | +| `--add-label` | Append label(s) | +| `--remove-label` | Remove label(s) | +| `--set-labels` | Replace all labels | +| `--parent` | Reparent (empty string removes parent) | +| `--external-ref` | Set external reference | +| `--session` | Set `closed_by_session` | +| `--force` | Update even if blocked | + +#### `br close [IDS…] [OPTIONS]` + +Close one or more issues. + +| Flag | Description | +| ----------------- | -------------------------------------------- | +| `-r` / `--reason` | Close reason (stored) | +| `-f` / `--force` | Close even if blocked by open dependencies | +| `--suggest-next` | After closing, return newly unblocked issues | +| `--session` | Session ID for tracking | +| `--robot` | Alias for `--json` | + +Uses "last-touched" issue if no IDs given. + +#### `br reopen [IDS…] [OPTIONS]` + +Reopen closed issues. +`-r` / `--reason` — stored as a comment. + +#### `br delete [IDS…]` + +Delete an issue (creates a tombstone record — soft delete, auditable). + +--- + +### 3.3 Listing and filtering + +#### `br list [OPTIONS]` + +List issues (open only by default). + +| Flag | Description | +| ------------------- | -------------------------------------------- | +| `-s` / `--status` | Filter by status (repeatable) | +| `-t` / `--type` | Filter by type (repeatable) | +| `--assignee` | Filter by assignee | +| `--unassigned` | Unassigned only | +| `--id` | Filter by specific IDs (repeatable) | +| `-l` / `--label` | AND label filter (repeatable) | +| `--label-any` | OR label filter (repeatable) | +| `-p` / `--priority` | Exact priority (repeatable) | +| `--priority-min` | Minimum priority (0=critical) | +| `--priority-max` | Maximum priority | +| `--title-contains` | Substring match on title | +| `--desc-contains` | Substring match on description | +| `--notes-contains` | Substring match on notes | +| `-a` / `--all` | Include closed issues | +| `--deferred` | Include deferred issues | +| `--overdue` | Only overdue issues | +| `--limit` | Max results (default 50, 0=unlimited) | +| `--sort` | `priority` `created_at` `updated_at` `title` | +| `-r` / `--reverse` | Reverse sort | +| `--long` | Long text format | +| `--pretty` | Tree/pretty format | +| `--format` | `text` `json` `csv` `toon` | +| `--fields` | CSV columns to include | + +Available CSV fields: `id`, `title`, `description`, `status`, `priority`, +`issue_type`, `assignee`, `owner`, `created_at`, `updated_at`, `closed_at`, +`due_at`, `defer_until`, `notes`, `external_ref`. + +#### `br search [OPTIONS]` + +Full-text search across title, description, and notes. Accepts the same +filters as `br list`. + +#### `br ready [OPTIONS]` + +List issues that are unblocked and not deferred (actionable now). + +| Flag | Description | +| -------------------- | --------------------------------------- | +| `--limit` | Max results (default 20) | +| `--assignee` | Filter by assignee | +| `--unassigned` | Unassigned only | +| `-l` / `--label` | AND label filter | +| `--label-any` | OR label filter | +| `-t` / `--type` | Type filter | +| `-p` / `--priority` | Priority filter | +| `--sort` | `hybrid` (default) `priority` `oldest` | +| `--include-deferred` | Include deferred | +| `--parent` | Children of a specific parent | +| `-r` / `--recursive` | Include all descendants with `--parent` | + +#### `br blocked [OPTIONS]` + +List issues blocked by open dependencies. +`--detailed` — include full blocker details in text output. + +#### `br stale [OPTIONS]` + +List issues not updated in N days. +`--days` — threshold (default 30). + +#### `br count [OPTIONS]` + +Count issues with optional grouping. +`--by ` or shorthand flags. + +#### `br stats [OPTIONS]` + +Summary statistics: totals by status, optional breakdowns by type / priority / +assignee / label. Returns a `summary` object in JSON mode. + +--- + +### 3.4 Dependencies + +#### `br dep add ` + +Add a dependency edge (ISSUE blocks on DEPENDS-ON). + +#### `br dep remove ` + +Remove a dependency edge. + +#### `br dep list ` + +List all dependencies of an issue. + +#### `br dep tree ` + +Render the full dependency tree rooted at an issue. + +#### `br dep cycles` + +Detect and report circular dependency cycles. + +#### `br graph [ISSUE] [OPTIONS]` + +Visualise the dependency graph. `--all` shows all connected components. +`--compact` — one line per issue. + +--- + +### 3.5 Comments + +#### `br comments [ID]` + +List comments on an issue. + +#### `br comments add ` + +Append a comment to an issue. This is how `task_output` stores its data in +the beads backend. + +--- + +### 3.6 Labels + +#### `br label add ` + +Add labels. Labels are plain strings; the proto agent uses two reserved +namespaces: `parent:` and `assignee:`. + +#### `br label remove ` + +Remove labels. + +#### `br label list [ID]` + +List labels on one issue or all unique labels across the workspace. + +#### `br label list-all` + +All unique labels with usage counts. + +#### `br label rename ` + +Rename a label across all issues. + +--- + +### 3.7 Workflow helpers + +#### `br defer [IDS…] --until ` + +Move issues to `deferred` status until a date/time (`+1h`, `tomorrow`, +`2025-01-15`, RFC3339). + +#### `br undefer [IDS…]` + +Remove deferral and return issues to `open`. + +#### `br orphans` + +List issues referenced in git commits that are still open. + +#### `br changelog` + +Generate a changelog from closed issues. + +#### `br lint` + +Check issues for missing template sections. + +#### `br epic status` + +Show progress and closure eligibility for all epics. + +#### `br epic close-eligible` + +Auto-close epics whose children are all closed. + +--- + +### 3.8 Agent/AI integration utilities + +#### `br audit record` + +Append an agent-interaction entry (JSONL append-only log). + +#### `br audit label` + +Append a label entry referencing an existing interaction. + +#### `br audit log ` + +View the audit log for a specific issue. + +#### `br audit summary` + +View aggregate audit summary. + +#### `br agents [OPTIONS]` + +Manage AGENTS.md workflow instructions injected into the project root. +`--add` injects beads workflow guidance; `--update` refreshes to the latest +version; `--remove` strips it. + +#### `br schema [TARGET]` + +Emit JSON Schemas for all `br` output types — useful for tooling integration. +Targets: `all` (default), `issue`, `issue-with-counts`, `issue-details`, +`ready-issue`, `stale-issue`, `blocked-issue`, `tree-node`, `statistics`, +`error`. + +--- + +### 3.9 History and sync + +#### `br history` + +Manage local history backups of the JSONL file. + +#### `br sync` + +Sync the database with the JSONL file (export or import). + +--- + +## 4. Issue schema (full field set) + +From `br schema issue --json`: + +| Field | Type | Description | +| --------------------- | -------------- | ---------------------------------------------- | +| `id` | string | Unique ID, e.g. `qwen-code-c43` | +| `title` | string | 1–500 chars | +| `description` | string? | Detailed body | +| `design` | string? | Technical design notes | +| `acceptance_criteria` | string? | Acceptance criteria text | +| `notes` | string? | Additional notes | +| `status` | Status enum | See below | +| `priority` | int 0–4 | 0=Critical, 1=High, 2=Medium, 3=Low, 4=Backlog | +| `issue_type` | IssueType enum | See below | +| `assignee` | string? | Assigned user | +| `owner` | string? | Owner email | +| `estimated_minutes` | int? | Effort estimate | +| `created_at` | datetime | Creation timestamp (RFC3339) | +| `created_by` | string? | Creator username | +| `updated_at` | datetime | Last update | +| `closed_at` | datetime? | When closed | +| `close_reason` | string? | Reason for closure | +| `closed_by_session` | string? | Session ID that closed it | +| `due_at` | datetime? | Due date | +| `defer_until` | datetime? | Deferred until | +| `external_ref` | string? | External reference (GitHub URL etc.) | +| `labels` | string[]? | Arbitrary labels | +| `source_repo` | string? | Git repo path | +| `dependency_count` | int | Number of outbound dependencies | +| `dependent_count` | int | Number of inbound dependents | +| `compaction_level` | int | JSONL compaction level | +| `comments` | Comment[]? | Present in `br show` output | + +**Status enum** values (br native): +`open` `in_progress` `blocked` `deferred` `draft` `closed` `tombstone` `pinned` + +**IssueType enum**: +`task` `bug` `feature` `epic` `chore` `docs` `question` + +**Dependency types**: +`blocks` `parent-child` `conditional-blocks` `waits-for` `related` +`discovered-from` `replies-to` `relates-to` `duplicates` `supersedes` +`caused-by` + +**Sample real issue** (from `br list --json`): + +```json +{ + "id": "qwen-code-c43", + "title": "Test beads task creation (IN PROGRESS)", + "description": "Creating a test task to verify beads_rust backend integration works correctly", + "status": "in_progress", + "priority": 2, + "issue_type": "task", + "created_at": "2026-04-01T03:03:04.031173943Z", + "created_by": "josh", + "updated_at": "2026-04-01T03:03:22.880996318Z", + "source_repo": ".", + "compaction_level": 0, + "dependency_count": 0, + "dependent_count": 0 +} +``` + +Comments appear only in `br show --json` output, not in `br list --json`. + +--- + +## 5. Proto agent tools — mapping to `br` commands + +The six agent tools are implemented in +`packages/core/src/tools/task-*.ts` and backed by +`packages/core/src/services/task-store.ts`. All `br` calls are made via +`execFileSync` with `--json` appended (or raw without `--json` for commands +that don't support it). + +### 5.1 Status and priority translation + +The proto agent uses its own vocabulary that is translated before hitting `br`: + +**Status mapping (proto → br)**: +| Proto `TaskStatus` | `br` status | +|---|---| +| `pending` | `open` | +| `in_progress` | `in_progress` | +| `completed` | `closed` (via `br close --reason done`) | +| `blocked` | `deferred` | +| `cancelled` | `closed` (via `br close --reason cancelled`) | + +**Reverse mapping (br → proto)**: +| `br` status | Proto `TaskStatus` | +|---|---| +| `open` | `pending` | +| `in_progress` | `in_progress` | +| `closed` | `completed` | +| `deferred` | `blocked` | +| anything else | `pending` (fallback) | + +Note: `br` statuses `draft`, `tombstone`, and `pinned` have no proto equivalent +and fall back to `pending`. + +**Priority mapping (proto → br numeric)**: +| Proto `TaskPriority` | `br` priority | +|---|---| +| `critical` | `0` | +| `high` | `1` | +| `medium` | `2` | +| `low` | `3` | + +br priority 4 (backlog) maps back to proto `low`. + +### 5.2 `task_create` + +**Agent parameters**: `title` (required), `description`, `parentTaskId`, +`priority` (`low` `medium` `high` `critical`). + +**What the store does**: + +1. Runs `br create --title --type task [--description …] [--priority N] --json` +2. If `parentTaskId` is set, runs `br label add <newId> parent:<parentTaskId>` (raw, no `--json`) +3. Fetches the created issue via `br show <id> --json` and returns it. + +**Note**: `br`'s native `--parent` flag is NOT used. Parent relationships are +encoded as the label `parent:<id>`. This means `br ready --parent <id>` and +`br dep` dependency edges are **not** used — parent lookup is done by scanning +all labels client-side. + +### 5.3 `task_get` + +**Agent parameters**: `taskId` (required). + +**What the store does**: + +1. Runs `br show <id> --json` — returns an array; takes `[0]`. +2. Enriches with `subtaskCount` (calls `list({ parentTaskId: id })`) and full + `subtasks` array. +3. Returns the combined object as JSON to the agent. + +### 5.4 `task_list` + +**Agent parameters**: `status` (`pending` `in_progress` `completed` `blocked` +`cancelled`), `parentTaskId`. + +**What the store does**: + +1. Runs `br list [--status <brStatus>] --json` — `br` does not support `--all` + by default so closed tasks require `--status closed` explicitly. +2. Filters by `parentTaskId` **client-side** by inspecting the `parent:` label + on each returned issue. +3. Sorts results by `created_at` ascending. + +**Note**: The `--all` flag (to include closed) is NOT passed; to see completed +tasks the agent must pass `status: "completed"` which maps to +`--status closed`. + +### 5.5 `task_update` + +**Agent parameters**: `taskId` (required), plus any of `status`, `title`, +`description`, `priority`. + +**What the store does**: + +- If `status === "completed"` → `br close <id> --reason done --json` +- If `status === "cancelled"` → `br close <id> --reason cancelled --json` +- If `status === "pending"` → `br reopen <id> --json` +- For all other status values (i.e. `in_progress`, `blocked`) or non-status + fields → `br update <id> [--title …] [--description …] [--priority N] +[--status <brStatus>] --json` +- Then fetches the updated task via `br show`. + +**Validation**: At least one of `status`, `title`, `description`, or +`priority` must be provided. The tool returns an error otherwise. + +### 5.6 `task_stop` + +**Agent parameters**: `taskId` (required), `reason` (optional). + +**What the store does**: + +1. Runs `br close <id> [--reason <reason>] --json`. +2. Recursively cancels all children by fetching `list({ parentTaskId: id })` + and calling `stop()` on each non-terminal child. +3. Returns the list of all cancelled tasks. + +### 5.7 `task_output` + +**Agent parameters**: `taskId` (required), `output` (required string). + +**What the store does**: + +1. Runs `br comments add <id> <output>` (**raw**, no `--json`). +2. Returns a task object with the `output` field set in-memory (not persisted + as a field — it lives in comments). + +**Critical gap**: `output` is stored as a comment in `br`, not as a native +field. When the task is later fetched via `br show --json`, the output appears +in the `comments` array, not as a top-level `output` field. The `brIssueToTask` +conversion does not read comments, so `task.output` will always be `undefined` +when re-fetching via `task_get`. The value is write-once from the agent's +perspective. + +--- + +## 6. Architecture notes + +### Fallback mode + +If `br` is not installed, `TaskStore` falls back to an in-memory +`Map<string, Task>` persisted to a session-scoped JSON file at +`<runtimeDir>/tasks/<sessionId>.json`. The fallback is feature-complete for +the six agent operations but does not persist across sessions and has no +`output` field persistence either. + +### Workspace initialisation + +On construction, `TaskStore` checks for `.beads/` in `cwd`. If missing it runs +`br init`. This means the agent can work in any project directory and will +auto-initialise beads storage. + +### ID format + +`br` generates IDs as `<prefix>-<hash>`, e.g. `qwen-code-c43`. The prefix +comes from `config.yaml:issue_prefix` which is set to the project name during +`br init`. Hashes are 3–8 chars (configurable via `min_hash_length` / +`max_hash_length`). + +### Concurrency + +All `execFileSync` calls use a 10-second timeout. `br` operates in direct mode +(no daemon in v1) so every call opens and closes the SQLite database. SQLite +WAL mode handles concurrent reads; writes are serialised by the busy timeout. + +--- + +## 7. Known gaps and limitations in the current integration + +### Gap 1: Parent-child via labels, not native `--parent` + +`br create --parent <id>` would register a proper `parent-child` dependency +edge, enabling `br ready --parent`, `br dep tree`, and `br epic` features. +The current implementation uses labels (`parent:<id>`) instead, which means: + +- `br ready --parent <id>` does NOT work for agent-created subtasks. +- `br epic` commands do not recognise the hierarchy. +- Dependency graphs (`br graph`, `br dep tree`) do not show parent-child edges. +- The `--parent` flag on `task_create` is cosmetic from `br`'s perspective. + +### Gap 2: `output` is not a first-class field + +`task_output` stores data as a comment (`br comments add`). Re-fetching via +`task_get` does not reconstruct `task.output` because `brIssueToTask` ignores +the `comments` array. To read back output the agent would need to call +`br show --json` and read `comments[*].text` directly — which is not exposed +through any agent tool. + +### Gap 3: `task_list` does not expose closed tasks by default + +`br list` excludes closed issues unless `--all` or `--status closed` is +passed. The agent must explicitly pass `status: "completed"` to see them. +There is no way to list ALL statuses at once via the current tool API. + +### Gap 4: No `br search` tool + +`br search <query>` is a powerful full-text command not exposed to the agent. +Finding tasks by description content requires shell access. + +### Gap 5: No `br ready` tool + +`br ready` is the most useful "what should I work on next?" command but is +not exposed to the agent. The agent must use `task_list` and filter manually. + +### Gap 6: No dependency management tools + +`br dep add/remove/list/tree` and `br blocked` are not exposed. The agent +cannot model blocking relationships, which limits multi-agent coordination. + +### Gap 7: No `br stats` / `br count` tool + +The agent cannot query aggregate statistics without running a shell command. + +### Gap 8: `cancelled` → `completed` collision in round-trips + +Both `completed` and `cancelled` map to `br` status `closed`. Once a task +is closed for either reason, fetching it back maps `closed` → `completed` +regardless of the original close reason. The `close_reason` field on the +`br` issue ("done" vs "cancelled") is ignored during translation. + +### Gap 9: `br` statuses `blocked` and `deferred` are swapped in meaning + +The proto agent status `blocked` maps to `br` status `deferred` (not to br's +own `blocked` status, which is a dependency-driven state). This means: + +- Issues the agent marks as `blocked` appear as `deferred` in the `br` UI. +- Genuine `br blocked` issues (from dependency edges) map to `pending` in + the proto agent view. + +### Gap 10: `--actor` not set + +The `br` calls do not pass `--actor`, so the audit trail records the system +default actor (`josh` in this workspace) rather than the agent's session ID. + +--- + +## 8. Best practices for long-horizon task management + +### 8.1 When to create tasks + +- Create a root task at the start of any multi-step operation that will span + more than ~3 tool calls or involve risk (file changes, API calls, etc.). +- Break epics/features into sub-tasks of 30–90 minutes of estimated effort. +- Use `parentTaskId` to nest: one epic → multiple features → multiple tasks. +- For exploratory work, create a task with `description` containing the + hypothesis and update it as you learn. + +### 8.2 Naming and typing + +- Use `issue_type: "epic"` for project-level goals. +- Use `issue_type: "feature"` for user-visible deliverables. +- Use `issue_type: "task"` for implementation work (default). +- Use `issue_type: "bug"` for defects. +- Keep titles to a single action-verb phrase: "Add JWT validation to login + endpoint", not "JWT stuff". + +### 8.3 Status discipline + +- Call `task_update { taskId, status: "in_progress" }` **before** starting + work, not after. This signals to other agents that the task is claimed. +- Use `task_update { status: "blocked", description: "Blocked on X" }` when + you cannot proceed rather than leaving a task as `in_progress` indefinitely. +- Call `task_update { status: "completed" }` immediately after finishing, + before starting the next task. +- Call `task_stop` only when a task is definitively abandoned (approach + changed, out-of-scope). It cascades to all subtasks. + +### 8.4 Recording output + +- Use `task_output` to attach findings, file paths, test results, or + summaries to a task before closing it. This is the only way to leave + a persistent artifact on the task. +- Keep outputs concise but complete enough to understand what was done + without re-reading the conversation. +- For large outputs (long diffs, full file contents), summarise rather than + dump raw content — `br comments add` has no enforced size limit but large + comments degrade readability. + +### 8.5 Hierarchy patterns + +**Single-agent linear work**: + +``` +root task (in_progress) + ├── step-1 subtask (completed) + ├── step-2 subtask (in_progress) + └── step-3 subtask (pending) +``` + +**Multi-phase feature**: + +``` +epic: "Ship auth v2" (open) + ├── feature: "JWT middleware" (in_progress) + │ ├── task: "Write validateToken()" (completed) + │ └── task: "Write refreshToken()" (in_progress) + └── feature: "Rate limiting" (pending) +``` + +**Note**: Due to Gap 1 above, use `parentTaskId` in `task_create` for +hierarchy even though it is stored as a label. Do NOT call `br dep add` +or `br create --parent` directly, as those will diverge from what the agent +tools can read. + +### 8.6 Claiming tasks in multi-agent scenarios + +The `claimTask` method in `TaskStore` exists (uses `br label add assignee:<id>` + +- `br update --status in_progress`) but is not exposed as an agent tool. + If you need multi-agent task claiming, use `br update --claim` via the + shell tool, or rely on status-checking via `task_list { status: "pending" }` + and `task_update { status: "in_progress" }` as a soft lock. + +### 8.7 Querying the board efficiently + +- `task_list` with no parameters returns all non-closed tasks (up to `br`'s + default limit of 50). +- Pass `status: "completed"` to see closed tasks. +- For subtask work: `task_get <parentId>` returns `subtasks` array inline — + prefer this over `task_list { parentTaskId }` for a single parent. +- For board-level visibility, call `br stats --json` via shell for aggregate + counts. + +### 8.8 Avoiding stale tasks + +- At the start of a session, run `task_list` to see what is `in_progress`. + Any tasks left `in_progress` from a prior session that you are resuming + are still valid — the beads backend persists across sessions. +- Close or reopen stale tasks explicitly; do not create duplicates. +- Run `br stale` (via shell) periodically to surface tasks untouched for + 30+ days. + +### 8.9 Using `br` directly for things the tools don't cover + +The agent has shell access. For operations not exposed through agent tools, +use the shell tool to call `br` directly: + +```bash +# Find what to work on next +br ready --json + +# See blocked tasks +br blocked --json + +# Full text search +br search "authentication" --json + +# Dependency management +br dep add <issue-id> <blocker-id> +br dep tree <issue-id> + +# Epic progress +br epic status --json + +# Board stats +br stats --json +``` + +Always pass `--json` for machine-readable output and `--no-color` if +parsing stdout. + +--- + +## 9. Quick reference card + +``` +# Create +br create "Fix login bug" -t bug -p 1 -d "Users get 403 on valid credentials" +br q "Quick note title" -p 3 # print ID only + +# Read +br list --json # open tasks +br list -s closed --json # closed tasks +br list -a --json # all tasks +br show <id> --json # full detail + comments +br ready --json # actionable now +br blocked --json # dependency-blocked + +# Update +br update <id> --status in_progress +br update <id> --title "New title" --description "More context" +br update <id> --claim # assignee=actor + in_progress + +# Close / reopen +br close <id> --reason "shipped" +br reopen <id> + +# Comments / output +br comments add <id> "Output text here" +br comments <id> --json + +# Hierarchy +br create "Subtask" --parent <parent-id> # native dep edge +br label add <id> "parent:<parent-id>" # label-based (current agent approach) + +# Dependencies +br dep add <issue> <blocker> +br dep tree <issue> +br graph <issue> + +# Stats +br stats --json +br count --by-status +br epic status --json +``` diff --git a/packages/cli/src/ui/components/views/__snapshots__/ToolsList.test.tsx.snap b/packages/cli/src/ui/components/views/__snapshots__/ToolsList.test.tsx.snap index d101710c0..356f2cd83 100644 --- a/packages/cli/src/ui/components/views/__snapshots__/ToolsList.test.tsx.snap +++ b/packages/cli/src/ui/components/views/__snapshots__/ToolsList.test.tsx.snap @@ -1,7 +1,7 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`<ToolsList /> > renders correctly with descriptions 1`] = ` -"Available Qwen Code CLI tools: +"Available proto CLI tools: - Test Tool One (test-tool-one) This is the first test tool. @@ -15,13 +15,13 @@ exports[`<ToolsList /> > renders correctly with descriptions 1`] = ` `; exports[`<ToolsList /> > renders correctly with no tools 1`] = ` -"Available Qwen Code CLI tools: +"Available proto CLI tools: No tools available" `; exports[`<ToolsList /> > renders correctly without descriptions 1`] = ` -"Available Qwen Code CLI tools: +"Available proto CLI tools: - Test Tool One - Test Tool Two diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index c85b4a7f1..58e8f5c13 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -64,6 +64,7 @@ import { TaskListTool } from '../tools/task-list.js'; import { TaskUpdateTool } from '../tools/task-update.js'; import { TaskStopTool } from '../tools/task-stop.js'; import { TaskOutputTool } from '../tools/task-output.js'; +import { TaskReadyTool } from '../tools/task-ready.js'; import { ToolRegistry } from '../tools/tool-registry.js'; import { WebFetchTool } from '../tools/web-fetch.js'; import { WebSearchTool } from '../tools/web-search/index.js'; @@ -2363,6 +2364,7 @@ export class Config { await registerCoreTool(TaskUpdateTool, this); await registerCoreTool(TaskStopTool, this); await registerCoreTool(TaskOutputTool, this); + await registerCoreTool(TaskReadyTool, this); await registerCoreTool(AskUserQuestionTool, this); !this.sdkMode && (await registerCoreTool(ExitPlanModeTool, this)); await registerCoreTool(WebFetchTool, this); diff --git a/packages/core/src/services/task-store.ts b/packages/core/src/services/task-store.ts index 594b55a68..e5e69d340 100644 --- a/packages/core/src/services/task-store.ts +++ b/packages/core/src/services/task-store.ts @@ -45,7 +45,7 @@ const STATUS_TO_BR: Record<TaskStatus, string> = { pending: 'open', in_progress: 'in_progress', completed: 'closed', - blocked: 'deferred', + blocked: 'blocked', cancelled: 'closed', }; @@ -53,7 +53,8 @@ const BR_TO_STATUS: Record<string, TaskStatus> = { open: 'pending', in_progress: 'in_progress', closed: 'completed', - deferred: 'blocked', + blocked: 'blocked', + deferred: 'blocked', // deferred = can't work on it now, treat same as blocked }; // Maps between our TaskPriority and beads_rust numeric priority (0=critical..4=low). @@ -72,6 +73,11 @@ const BR_PRIORITY_TO_OURS: Record<number, TaskPriority> = { 4: 'low', }; +interface BrComment { + text: string; + created_at?: string; +} + interface BrIssue { id: string; title: string; @@ -84,6 +90,8 @@ interface BrIssue { created_at?: string; updated_at?: string; closed_at?: string; + close_reason?: string; + comments?: BrComment[]; } /** @@ -170,11 +178,23 @@ export class TaskStore { } private brIssueToTask(issue: BrIssue): Task { + // Distinguish completed vs cancelled via close_reason + let status = BR_TO_STATUS[issue.status] ?? 'pending'; + if (issue.status === 'closed' && issue.close_reason === 'cancelled') { + status = 'cancelled'; + } + + // Reconstruct output from comments (most recent comment wins) + const output = + issue.comments && issue.comments.length > 0 + ? issue.comments[issue.comments.length - 1].text + : undefined; + return { id: issue.id, title: issue.title, description: issue.description, - status: BR_TO_STATUS[issue.status] ?? 'pending', + status, priority: BR_PRIORITY_TO_OURS[issue.priority] ?? 'medium', createdBy: issue.assignee ?? 'agent', // Assignee encoded as label: "assignee:<agentId>" @@ -192,6 +212,7 @@ export class TaskStore { parentTaskId: issue.labels ?.find((l) => l.startsWith('parent:')) ?.slice(7), + output, }; } @@ -211,6 +232,10 @@ export class TaskStore { if (params.priority) { args.push('--priority', String(PRIORITY_TO_BR[params.priority])); } + // Register native parent-child dep edge so br epic/dep tree/ready --parent work + if (params.parentTaskId) { + args.push('--parent', params.parentTaskId); + } // br create --json returns a flat issue object: {id, title, status, ...} const result = this.br(args) as BrIssue; @@ -220,7 +245,7 @@ export class TaskStore { throw new Error('Failed to create task: no ID returned'); } - // Encode parent relationship as a label + // Also encode parent as a label for client-side filtering in list() if (params.parentTaskId) { try { this.brRaw(['label', 'add', id, `parent:${params.parentTaskId}`]); diff --git a/packages/core/src/tools/task-ready.ts b/packages/core/src/tools/task-ready.ts new file mode 100644 index 000000000..aaf11e63a --- /dev/null +++ b/packages/core/src/tools/task-ready.ts @@ -0,0 +1,136 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { execFileSync } from 'node:child_process'; +import type { ToolInvocation, ToolResult } from './tools.js'; +import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; +import { ToolNames, ToolDisplayNames } from './tool-names.js'; +import type { Config } from '../config/config.js'; + +export interface TaskReadyParams { + limit?: number; + parentTaskId?: string; + priority?: string; +} + +class TaskReadyToolInvocation extends BaseToolInvocation< + TaskReadyParams, + ToolResult +> { + constructor( + private readonly config: Config, + params: TaskReadyParams, + ) { + super(params); + } + + getDescription(): string { + return 'List actionable tasks (unblocked, not deferred)'; + } + + async execute(_signal: AbortSignal): Promise<ToolResult> { + const cwd = this.config.getWorkingDir?.() ?? process.cwd(); + + const args = ['ready', '--json']; + if (this.params.limit != null) { + args.push('--limit', String(this.params.limit)); + } + if (this.params.parentTaskId) { + args.push('--parent', this.params.parentTaskId, '--recursive'); + } + if (this.params.priority) { + const priorityMap: Record<string, string> = { + critical: '0', + high: '1', + medium: '2', + low: '3', + }; + const p = priorityMap[this.params.priority]; + if (p) args.push('--priority', p); + } + + try { + const output = execFileSync('br', args, { + cwd, + stdio: ['pipe', 'pipe', 'pipe'], + timeout: 10000, + encoding: 'utf8', + env: { ...process.env, RUST_LOG: 'error', NO_COLOR: '1' }, + }); + + const issues = JSON.parse(output); + if (!Array.isArray(issues) || issues.length === 0) { + return { + llmContent: + 'No actionable tasks found. All tasks are either blocked, deferred, or completed.', + returnDisplay: 'No actionable tasks', + }; + } + + const tasksJson = JSON.stringify(issues, null, 2); + return { + llmContent: `Actionable tasks (unblocked, ordered by priority):\n\n${tasksJson}\n\n<system-reminder>\n${issues.length} task(s) ready to work on. Pick the highest priority one and call task_update to set it in_progress.\n</system-reminder>`, + returnDisplay: { + type: 'todo_list' as const, + todos: issues.map((t: { id: string; title: string }) => ({ + id: t.id, + content: t.title, + status: 'pending' as const, + })), + }, + }; + } catch { + return { + llmContent: + 'br ready is not available or failed. Use task_list to see pending tasks instead.', + returnDisplay: 'task_ready unavailable', + error: { message: 'br ready command failed' }, + }; + } + } +} + +export class TaskReadyTool extends BaseDeclarativeTool< + TaskReadyParams, + ToolResult +> { + static readonly Name: string = ToolNames.TASK_READY; + + constructor(private readonly config: Config) { + super( + TaskReadyTool.Name, + ToolDisplayNames.TASK_READY, + 'Returns tasks that are ready to work on right now — unblocked, not deferred, ordered by priority. Use this at the start of a session or after completing a task to decide what to do next.', + Kind.Think, + { + type: 'object', + properties: { + limit: { + type: 'number', + description: 'Maximum number of tasks to return (default 20).', + }, + parentTaskId: { + type: 'string', + description: + 'If set, restrict results to subtasks of this parent (recursive).', + }, + priority: { + type: 'string', + enum: ['critical', 'high', 'medium', 'low'], + description: 'Filter by exact priority level.', + }, + }, + $schema: 'http://json-schema.org/draft-07/schema#', + }, + ); + } + + protected createInvocation( + params: TaskReadyParams, + ): ToolInvocation<TaskReadyParams, ToolResult> { + return new TaskReadyToolInvocation(this.config, params); + } +} diff --git a/packages/core/src/tools/tool-names.ts b/packages/core/src/tools/tool-names.ts index c51465f3b..6534105d2 100644 --- a/packages/core/src/tools/tool-names.ts +++ b/packages/core/src/tools/tool-names.ts @@ -22,6 +22,7 @@ export const ToolNames = { TASK_UPDATE: 'task_update', TASK_STOP: 'task_stop', TASK_OUTPUT: 'task_output', + TASK_READY: 'task_ready', MEMORY: 'save_memory', AGENT: 'agent', SKILL: 'skill', @@ -54,6 +55,7 @@ export const ToolDisplayNames = { TASK_UPDATE: 'TaskUpdate', TASK_STOP: 'TaskStop', TASK_OUTPUT: 'TaskOutput', + TASK_READY: 'TaskReady', MEMORY: 'SaveMemory', AGENT: 'Agent', SKILL: 'Skill', diff --git a/tools/harbor_agent/proto_agent.py b/tools/harbor_agent/proto_agent.py index 1c73fe570..0bb0927d0 100644 --- a/tools/harbor_agent/proto_agent.py +++ b/tools/harbor_agent/proto_agent.py @@ -110,6 +110,18 @@ async def install(self, environment: BaseEnvironment) -> None: ")" ), ) + # Install beads_rust (br) — persistent SQLite-backed task tracking for proto. + # Version pinned to avoid GitHub API call overhead (saves ~2s during setup). + # Uses pre-built linux_amd64 binary; no Rust toolchain required. + await self.exec_as_root( + environment, + command=( + "BR_VERSION=v0.1.35 && " + "curl -fsSL https://github.com/Dicklesworthstone/beads_rust/releases/download/${BR_VERSION}/" + "br-${BR_VERSION}-linux_amd64.tar.gz | tar -xz -C /usr/local/bin && " + "chmod +x /usr/local/bin/br && br --version || echo 'beads_rust install failed (non-fatal)'" + ), + ) def _find_session_jsonl(self) -> Path | None: sessions_dir = self.logs_dir / "proto-sessions" @@ -322,8 +334,44 @@ async def run( # ANTHROPIC_API_KEY in its environment (which would otherwise bleed through and cause # Anthropic's API to 404 on gateway model names like "cli/claude-opus-4-6"). auth_flag = "" + setup_cmd = "" openai_base = env.get("OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL", "") - if not openai_base: + openai_key = env.get("OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY", "") + if openai_base: + # OpenAI-compat / gateway mode. Write ~/.proto/settings.json so proto registers + # the model against the correct base URL — more reliable than env vars alone. + import json as _json + import time as _time + settings = _json.dumps({ + "modelProviders": { + "openai": [{"id": model, "name": model, "baseUrl": openai_base, "envKey": "OPENAI_API_KEY"}] + }, + "security": {"auth": {"selectedType": "openai"}}, + "model": {"name": model}, + }) + now_ms = int(_time.time() * 1000) + # 3-member protoLabs team: explorer (read-only analysis) + implementer (coding) + + # verifier (test/validate). Written into the task working dir so proto can spawn + # them via the dispatching-parallel-agents skill. + team = _json.dumps({ + "name": "protolabs", + "createdAt": now_ms, + "updatedAt": now_ms, + "status": "active", + "members": [ + {"name": "explorer", "agentId": f"explorer-{now_ms}", "agentType": "Explore", "status": "idle"}, + {"name": "implementer", "agentId": f"implementer-{now_ms}", "agentType": "general-purpose", "status": "idle"}, + {"name": "verifier", "agentId": f"verifier-{now_ms}", "agentType": "general-purpose", "status": "idle"}, + ], + }) + safe_settings = settings.replace("'", "'\\''") + safe_team = team.replace("'", "'\\''") + setup_cmd = ( + f"mkdir -p ~/.proto && printf '%s' '{safe_settings}' > ~/.proto/settings.json && " + f"mkdir -p /app/.proto/teams/protolabs && printf '%s' '{safe_team}' > /app/.proto/teams/protolabs/config.json && " + ) + auth_flag = "--auth-type openai" + else: # No explicit gateway — fall back to direct Anthropic auth if key is available anthropic_key = env.get("ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY", "") if anthropic_key: @@ -342,6 +390,7 @@ async def run( environment, command=( ". ~/.nvm/nvm.sh; " + f"{setup_cmd}" f"proto --yolo {auth_flag} {model_flag} --prompt={escaped_instruction} " f"2>&1 | tee /logs/agent/proto.txt" ),