feat(workspaces): add repository branch policies (#2997)

This commit is contained in:
Carlos Florêncio
2026-08-26 11:09:00 +00:00
committed by GitHub
parent 469db8bc7d
commit fe0bda1e07
173 changed files with 8951 additions and 525 deletions
+3 -1
View File
@@ -12,7 +12,7 @@ owners:
## Purpose
The workspace system owns workspace lifecycle, repositories, worktrees,
branches, workspace secrets, and workspace-scoped execution context.
branches, branch policies, workspace secrets, and workspace-scoped execution context.
## Ownership
@@ -43,6 +43,7 @@ Git state.
- [Workspace Base-Branch Propagation](requirements/workspace-base-branch-propagation.md)
- [Worktree Base Refresh](requirements/worktree-base-refresh.md)
- [Worktree Branch Templates](requirements/worktree-branch-templates.md)
- [Branch Policies](requirements/branch-policies.md)
### System design
@@ -50,6 +51,7 @@ Git state.
- [Improve Kandev](system-design/improve-kandev.md)
- [Copy and Move Secrets Between Scopes](system-design/secret-scope-transfer.md)
- [Branch Policies](system-design/branch-policies.md)
- [Worktree Base Refresh](system-design/worktree-base-refresh.md)
## Migration record
@@ -0,0 +1,214 @@
---
status: draft
system: workspaces
created: 2026-08-24
owners:
- kandev
---
# Branch policies requirements
## Context
Kandev treats a local path as one repository identity. A team that uses Gitflow
therefore cannot represent `feature`, `bugfix`, `hotfix`, and `release` naming
rules by registering the same path several times. A repository currently has
one fallback worktree branch template, while task creation selects only a base
branch.
Branch policies let one repository expose named combinations of base branch,
new-branch template, and pull-request target. They are a task-creation aid, not
duplicate repositories and not a restriction on Git itself.
## Goals
- Let a repository define several understandable branch workflows.
- Keep repository settings compact and provide useful contextual guidance.
- Present policies and real branches in one task-create selector without making
a policy look like an existing branch.
- Make a selected policy deterministic for the lifetime of a task.
- Preserve all current behavior when no policy is selected.
## Non-goals
- Enforcing Gitflow or preventing users from selecting arbitrary branches.
- Automatically routing merges between release, production, and development
branches after a pull request is created.
- Adding the saved pull-request target to agent skills or shell environments.
- Adding policies to Quick Chat, Remote URL, Add Sources, or the post-creation
Add Branch flow in the first release.
- Reordering policies or choosing a repository-wide default policy.
- Converting the existing repository worktree template into a policy.
## Terminology
- **Branch policy**: a named repository configuration containing a base branch,
new-branch template, and pull-request target.
- **Raw branch**: an existing branch selected directly in the current task
creation flow.
- **Policy snapshot**: the effective policy values copied to a task-repository
record when the task is created.
- **Gitflow starter**: a guided action that creates the initial Feature,
Bugfix, Hotfix, and Release policies.
## Requirements
### REQ-WORKSPACES-BRANCH-POLICIES-001: Repository policy management
Each saved repository MUST support zero or more named branch policies. A policy
MUST contain a name, base branch, and branch template. Clients MAY omit the
pull-request target; the service MUST default it to the normalized base branch
before validation and persistence. A policy MAY contain a short description.
The repository editor MUST place policy management in a disclosure section that
is collapsed on each page load. The section header MUST show the policy count.
When expanded, the section MUST show a short visible explanation. Contextual
info controls MAY add detail but MUST NOT be the only explanation of the
setting.
Policy create, edit, and delete actions MUST persist independently of the
settings page save coordinator. The UI MUST require a new repository draft to
be saved before policies can be managed.
#### Acceptance criteria
- **AC-WORKSPACES-BRANCH-POLICIES-001.1:** A repository with no policies shows a collapsed `Branch
policies` section with count zero, and existing repository settings consume no
additional vertical space until the user expands it.
- **AC-WORKSPACES-BRANCH-POLICIES-001.2:** Expanding the section shows visible explanatory copy and
focusable info controls for policy fields. Help is available by hover and
keyboard focus on fine-pointer devices and by tap on touch devices.
- **AC-WORKSPACES-BRANCH-POLICIES-001.3:** A user can create, edit, and delete a policy without using the
settings route Save button. The list and count update only after the backend
confirms the mutation.
- **AC-WORKSPACES-BRANCH-POLICIES-001.4:** Policy names are trimmed, 1 to 100 characters, and unique within
a repository under case-insensitive comparison. Descriptions are optional and
no longer than 500 characters. Branch refs and rendered templates pass the
existing safe Git-ref validation.
- **AC-WORKSPACES-BRANCH-POLICIES-001.5:** Deleting a repository deletes its policies. Deleting or editing
a policy does not rewrite an existing task's policy snapshot.
- **AC-WORKSPACES-BRANCH-POLICIES-001.6:** Base and pull-request-target controls list distinct local and
remote branch refs in a searchable selector with an explicit refresh action.
Editing a policy whose saved ref is no longer listed keeps that saved value
visible until the user chooses a replacement.
### REQ-WORKSPACES-BRANCH-POLICIES-002: Guided Gitflow starter
An empty policy section MUST offer an `Add Gitflow policies` action. The action
MUST ask for a production branch and a development branch before it creates any
policies. It MUST create the complete starter set atomically.
#### Acceptance criteria
- **AC-WORKSPACES-BRANCH-POLICIES-002.1:** The production branch defaults to the repository default branch.
The development branch prefers `develop` when that branch is available. Both
values remain editable.
- **AC-WORKSPACES-BRANCH-POLICIES-002.2:** Production and development are required, valid existing branch
choices, and must differ.
- **AC-WORKSPACES-BRANCH-POLICIES-002.3:** Confirmation creates these editable policies in one transaction:
Feature uses development, `feature/{title}-{suffix}`, and development; Bugfix
uses development, `bugfix/{title}-{suffix}`, and development; Hotfix uses
production, `hotfix/{title}-{suffix}`, and production; Release uses
development, `release/{title}-{suffix}`, and production. Each tuple is base,
template, and pull-request target.
- **AC-WORKSPACES-BRANCH-POLICIES-002.4:** The starter is rejected without partial writes when the
repository already has a policy or another request creates one concurrently.
- **AC-WORKSPACES-BRANCH-POLICIES-002.5:** Starter policy names are persisted configuration values. Their
field guidance and built-in descriptions are localized presentation copy.
### REQ-WORKSPACES-BRANCH-POLICIES-003: Task-create policy selection
New Task and New Subtask MUST present configured policies and existing branches
through the current repository and base-branch selector. The selector MUST use
separate `Branch policies` and `Branches` groups and MUST keep policies visually
distinct from branches.
Selecting a policy means "start from this base branch and create a new branch
with this template." It MUST NOT be treated as the name of an existing branch.
#### Acceptance criteria
- **AC-WORKSPACES-BRANCH-POLICIES-003.1:** Policy options appear before raw branches and use a single-line
row with a localized `Policy` marker, policy name, and focusable information
control. The information control exposes the base branch, branch-template
preview, pull-request target, and unavailable-base guidance by hover, keyboard
focus, or tap.
- **AC-WORKSPACES-BRANCH-POLICIES-003.2:** A selected policy remains visibly identifiable as a policy in the
closed chip, including its base branch. Selection state uses a typed policy ID
and is never inferred from a label or branch string.
- **AC-WORKSPACES-BRANCH-POLICIES-003.3:** Selecting a policy explicitly turns on the existing `Fork a new
branch` mode for a local executor and keeps the state visible. Existing dirty
working-tree consent continues to apply.
- **AC-WORKSPACES-BRANCH-POLICIES-003.4:** Selecting a raw branch preserves current checkout and fallback
worktree-template behavior. Repositories with no policies preserve the current
selector behavior.
- **AC-WORKSPACES-BRANCH-POLICIES-003.5:** Policies are not offered for an unsaved local path, Remote URL,
Quick Chat, Add Sources, or post-creation Add Branch in the first release.
- **AC-WORKSPACES-BRANCH-POLICIES-003.6:** If a policy's base branch is known to be absent after a branch
refresh, the option is unavailable and explains how to repair the policy.
### REQ-WORKSPACES-BRANCH-POLICIES-004: Immutable task application
The backend MUST resolve a selected policy against the selected repository and
authorized workspace when it creates the task. It MUST snapshot the policy
identity, name, base branch, branch template, and pull-request target on the
task-repository record.
#### Acceptance criteria
- **AC-WORKSPACES-BRANCH-POLICIES-004.1:** The task-create request sends only the selected policy ID as new
policy input. The backend rejects a missing, deleted, cross-repository, or
unauthorized policy and creates no partial task.
- **AC-WORKSPACES-BRANCH-POLICIES-004.2:** Policy changes and deletion after task creation do not alter the
task's base, generated branch naming, title-triggered branch rename, or default
pull-request target.
- **AC-WORKSPACES-BRANCH-POLICIES-004.3:** Worktree creation, local fresh-branch creation, and generated-title
branch rename use the snapshot template. Older tasks and raw-branch tasks fall
back to the repository worktree template.
- **AC-WORKSPACES-BRANCH-POLICIES-004.4:** Desktop and mobile pull-request creation default to the snapshot
pull-request target and fall back to the task base branch when no target was
snapshotted.
- **AC-WORKSPACES-BRANCH-POLICIES-004.5:** A stale policy selected in an open dialog produces an actionable
error and refreshes available policies; Kandev does not silently substitute a
raw branch or another policy.
- **AC-WORKSPACES-BRANCH-POLICIES-004.6:** When Kandev starts or resets an agent for a policy-backed task,
the agent context identifies each repository's snapshotted pull-request
target. The context instructs the agent to pass that target explicitly to a
provider CLI. Passthrough agents receive the same instruction as plain text.
Raw-branch tasks receive no policy-target instruction.
### REQ-WORKSPACES-BRANCH-POLICIES-005: Responsive, accessible compatibility
Branch policy settings and selection MUST remain usable with keyboard, pointer,
and touch input and MUST preserve existing repository and task contracts.
#### Acceptance criteria
- **AC-WORKSPACES-BRANCH-POLICIES-005.1:** Desktop uses the compact repository disclosure and modal form.
Phone layouts use the same disclosure and a full-height drawer form with one
scroll owner, a fixed safe-area action region, and touch targets of at least
44 CSS pixels.
- **AC-WORKSPACES-BRANCH-POLICIES-005.2:** Help content has equivalent hover, focus, and tap access. A touch
user is never required to emulate hover.
- **AC-WORKSPACES-BRANCH-POLICIES-005.3:** Policy forms, grouped selectors, help triggers, errors, and
confirmations expose accessible names and keyboard behavior. All user-facing
copy is localized in the supported catalogs.
- **AC-WORKSPACES-BRANCH-POLICIES-005.4:** Existing repositories require no migration action, existing task
payloads remain valid, and tasks created without a policy continue to use the
current repository worktree template and task base branch.
## Operational requirements
- Mutations MUST emit structured logs with workspace, repository, policy, and
action identifiers. Task creation MUST log whether a policy was resolved or
fallback behavior was used.
- No new metrics are required for the first release.
- Policy API authorization MUST use the same workspace and repository membership
checks as repository settings. A cross-workspace policy identifier MUST not
disclose policy data.
## Traceability
- System design: [Branch policies](../system-design/branch-policies.md)
- Decision: [Snapshot task branch policies](../../../decisions/2026-08-24-task-snapshotted-branch-policies.md)
- Implementation plan: [Branch policies plan](../../../plans/branch-policies/plan.md)
@@ -30,6 +30,12 @@ Teams use repository-specific branch names for tickets and other local rules. Ka
## Migrated source detail
> This legacy specification is no longer the editable source for worktree branch
> policy behavior. See the migrated
> [branch policies requirements](requirements/branch-policies.md) and
> [system design](system-design/branch-policies.md). The repository-level
> template described below remains the compatibility fallback.
## Why
Teams use repository-specific branch names for tickets and other local rules.
@@ -0,0 +1,256 @@
---
status: draft
system: workspaces
created: 2026-08-24
owners:
- kandev
requirements:
- REQ-WORKSPACES-BRANCH-POLICIES-001
- REQ-WORKSPACES-BRANCH-POLICIES-002
- REQ-WORKSPACES-BRANCH-POLICIES-003
- REQ-WORKSPACES-BRANCH-POLICIES-004
- REQ-WORKSPACES-BRANCH-POLICIES-005
---
# Branch policies system design
## Summary
A branch policy is repository-owned configuration. Task creation sends a policy
ID, the backend resolves it, and the resulting task-repository row owns an
immutable snapshot. Repository settings manage policies through immediate CRUD,
while task creation shows policies and Git branches as typed option groups in
the existing selector.
This extends, rather than replaces, the repository
`worktree_branch_template`. That field remains the compatibility fallback for
raw branch selections and pre-policy tasks.
## Domain model
Add `repository_branch_policies`:
| Field | Contract |
| --- | --- |
| `id` | Stable UUID. |
| `repository_id` | Required repository owner; delete cascades from repository. |
| `name` | Trimmed display name, 1 to 100 characters. |
| `description` | Optional text, at most 500 characters. |
| `base_branch` | Safe Git ref used as task base. |
| `branch_template` | Template validated and rendered by `internal/worktree`. |
| `pull_request_target` | Safe Git ref; defaults to `base_branch` when omitted by a client. |
| `created_at`, `updated_at` | UTC timestamps. |
A unique index on `(repository_id, lower(name))` enforces name uniqueness. Lists
sort by case-folded name and stable ID. The table is part of both the SQLite
base schema and replayable SQLite/Postgres migrations.
Extend `task_repositories` with snapshot fields:
- `branch_policy_id`;
- `branch_policy_name`;
- `worktree_branch_template`;
- `pull_request_target`.
`base_branch` already stores the selected base. The policy ID is historical
provenance, not a foreign key. This keeps the complete snapshot after a policy
is deleted. Empty values identify raw-branch and legacy rows.
## Backend boundaries
### Repository policy service
The task repository interface gains list, get, create, update, delete, and
atomic Gitflow-starter operations. The service owns:
- workspace/repository authorization;
- normalized validation and case-insensitive conflicts;
- defaulting an omitted pull-request target to the normalized base branch;
- branch-template validation through the existing renderer;
- transactions and structured mutation logs.
The Gitflow starter accepts only production and development branch refs. It
checks that both refs are present in the current local or remote branch list,
checks that the repository has no policies inside the same transaction, and
inserts all four policies or none. The branch can still disappear after this
check, so task creation and later runtime operations retain their existing
missing-branch recovery behavior.
### API and events
Expose:
- `GET /api/v1/repositories/{repository_id}/branch-policies`;
- `POST /api/v1/repositories/{repository_id}/branch-policies`;
- `POST /api/v1/repositories/{repository_id}/branch-policies/gitflow`;
- `PATCH /api/v1/repository-branch-policies/{policy_id}`;
- `DELETE /api/v1/repository-branch-policies/{policy_id}`.
REST and WebSocket transports call the same service methods. Semantic
`repository_branch_policy.created`, `.updated`, and `.deleted` events keep
clients synchronized. The active-workspace boot payload includes policies
grouped by repository so task creation does not add a first-open request.
Conflicts return `409`; invalid refs, templates, or Gitflow pairs return a
validation error; an inaccessible or cross-repository policy is indistinguishable
from not found.
### Task creation and snapshot resolution
Add optional `branch_policy_id` to each task repository input. In the task-create
transaction, the service:
1. loads the selected repository under the authorized workspace;
2. loads the policy by ID and verifies repository ownership;
3. copies its name, base, template, and pull-request target to
`task_repositories`;
4. creates no task if any selected policy cannot be resolved.
The backend ignores any browser-derived policy template or target. A policy
selection supplies its base branch authoritatively, even though the UI also
shows that base for feedback.
Runtime worktree creation, local fresh-branch creation, and title-triggered
branch rename read the task snapshot first. They read the repository template
only when the snapshot template is empty. The web pull-request flow reads the
snapshot target first and then the task base branch.
The orchestrator also derives trusted agent context from policy-backed
task-repository snapshots. The context lists the repository, working branch,
and pull-request target. It tells agents to pass the target to the provider CLI
instead of inferring it from the base branch. First launches and agent-context
resets receive the context. Office agents receive the same trusted block.
Passthrough agents receive a compact plain-text instruction because they do not
receive hidden Kandev system blocks. Raw-branch tasks add no instruction.
Prompt construction reads only the task snapshot. It does not read the live
policy. Repeated record-and-launch wrapping replaces the same hidden target
block, so the agent receives one copy. Agent skills and shell environments do
not receive a separate target value.
## Frontend state and transport
Add a repository-policy API domain and a `repositoryBranchPolicies` store slice
keyed by repository ID. Boot hydration and semantic events update the same
slice. Store mutations occur only after API success.
Task repository draft rows add a tagged selection:
```ts
type TaskRepositoryBranchSelection =
| { kind: "branch"; branch: string }
| { kind: "policy"; policyId: string; baseBranch: string };
```
The submit adapter converts the tagged selection to `base_branch` plus optional
`branch_policy_id`. It never recognizes a policy by label. Last-used repository
and raw branch behavior stays backend-owned under ADR 0028; the first release
does not persist a last-used policy.
## Repository settings experience
Each saved repository editor contains a collapsed `Branch policies` disclosure
with a count. Expanded content has one visible explanatory sentence, the policy
list, Add policy, and, when empty, Add Gitflow policies. Policies use immediate
modal CRUD and a delete confirmation, so they do not register a dirty settings
contributor or add a local Save button.
The policy form contains name, optional description, base branch, branch
template, and pull-request target. Every technical field has concise visible
supporting text. Focusable info controls explain examples, template placeholders,
and how base differs from pull-request target. Base and target fields reuse the
task branch option model: local refs keep their short names, remote refs keep
their remote prefix, and badges distinguish their source. The shared selector
provides filtering and force-refresh. A saved ref that disappeared remains a
temporary option while the user edits the policy.
Desktop uses a dialog. At phone breakpoints the same form logic renders in a
full-height drawer with one scrolling body and a safe-area footer. Help uses a
tooltip/popover for fine pointers and the established touch drawer pattern for
coarse pointers. The disclosure and list remain inline in the repository
editor; list actions meet the 44 CSS pixel touch target.
The Gitflow starter is a separate guided dialog/drawer with production and
development branch selectors and a preview of the four resulting policies.
## Task-create experience
Extend the existing branch `Pill` selector to accept typed grouped options. It
shows `Branch policies` first and `Branches` second. A policy row keeps its name,
localized `Policy` badge, and information control on one line. Hover or keyboard
focus opens the base, template, target, and unavailable-base details on fine
pointers; tap opens the same details in a drawer on coarse pointers. The closed
chip renders a compact policy name plus base branch.
On a local executor, choosing a policy explicitly enables the existing `Fork a
new branch` state. It does not bypass dirty-tree consent. Choosing a raw branch
restores the existing semantics. A policy with a base branch known missing from
the latest branch list is disabled with repair guidance.
The shared New Task/New Subtask repository picker gets this behavior. Quick Chat,
Remote URL, unsaved-path discovery, Add Sources, and Add Branch do not.
On phone, the existing task selector remains a popover because it is already a
compact, viewport-contained selection surface. Policy rows keep one-line
identity and use a touch drawer for their detailed preview.
## Accessibility and localization
- Disclosure triggers expose expanded state and policy count.
- Group labels, badges, help triggers, field descriptions, errors, and
confirmations use translations.
- Help triggers are focusable, have accessible names, and expose equivalent
content by hover, focus, and tap.
- Dialog and drawer focus management uses existing shadcn primitives.
- English copy is added to all supported locale catalogs; Traditional Chinese
variants use the repository conversion workflow.
## Failure and recovery
- A stale/deleted policy at submit fails task creation atomically. The client
refreshes policies, keeps the dialog open, and asks the user to choose again.
- A policy base that disappeared after creation follows current worktree launch
recovery; Kandev does not rewrite the policy.
- A failed CRUD mutation leaves the confirmed list unchanged and shows the
backend error.
- Concurrent Gitflow starter calls are serialized by the empty-set check and
unique constraints.
## Security and observability
Policy reads and writes use repository membership authorization. IDs from other
workspaces do not reveal existence. Templates remain data for the safe renderer;
they are not shell fragments.
Structured logs cover policy mutations, Gitflow starter results, task policy
resolution, and compatibility fallback. Logs include identifiers, not policy
descriptions. No new production metric is introduced initially.
## Migration and rollout
The database migration is additive and replayable. Existing repositories gain
no policies automatically, and their fallback templates are unchanged. Existing
task requests and rows remain valid because all new fields are optional or
empty by default. No runtime feature flag is required because the no-policy path
is unchanged and policies are opt-in.
## Verification strategy
- Repository tests cover persistence, replay, normalization, conflicts,
authorization, cascade, and atomic Gitflow seeding in SQLite and Postgres.
- Service/runtime tests cover snapshot resolution, stale IDs, raw fallback,
local fresh branches, title rename, pull-request targets, and agent context.
- Frontend unit tests cover the settings CRUD state, responsive surface choice,
tagged selector options, local fork transition, and submit payload.
- Desktop and `mobile-chrome` Playwright tests cover collapsed settings, help
access, Gitflow seeding, policy selection, and visible post-selection state.
## Requirement traceability
| Requirement | Design areas |
| --- | --- |
| REQ-WORKSPACES-BRANCH-POLICIES-001 | Domain model, repository service, settings experience |
| REQ-WORKSPACES-BRANCH-POLICIES-002 | Repository service, Gitflow starter, failure recovery |
| REQ-WORKSPACES-BRANCH-POLICIES-003 | Frontend state, task-create experience |
| REQ-WORKSPACES-BRANCH-POLICIES-004 | Task snapshot resolution, runtime, agent context, migration |
| REQ-WORKSPACES-BRANCH-POLICIES-005 | Responsive UI, accessibility, localization, compatibility |