17 KiB
spec, created, status
| spec | created | status |
|---|---|---|
| docs/specs/office/requirements/automations-settings.md | 2026-07-30 | draft |
Implementation Plan: Multi-repository automation configuration
Overview
Replace the automation's singular repository_id with an ordered repository_ids
list, backed by a new automation_repositories join table (mirrors
task_repositories). The orchestrator resolves N repositories per trigger
firing the same way resolveExplicitRepository resolves one today. The editor
gates multi-select on the selected executor profile's capability by reusing
getMultiRepoExecutorDisabledReason from the task-creation dialog. Order:
backend data model + contract first (everything else depends on the wire
shape), then orchestrator resolution and frontend UI in parallel (disjoint
files, both consume the same contract), then E2E last.
Backend
Schema (apps/backend/internal/automation/store.go)
- Add to
createTablesSQL:CREATE TABLE IF NOT EXISTS automation_repositories ( id TEXT PRIMARY KEY, automation_id TEXT NOT NULL REFERENCES automations(id) ON DELETE CASCADE, repository_id TEXT NOT NULL, position INTEGER NOT NULL DEFAULT 0, created_at DATETIME NOT NULL, UNIQUE(automation_id, repository_id) ); CREATE INDEX IF NOT EXISTS idx_automation_repositories_automation ON automation_repositories(automation_id); - Drop
repository_idfrom the canonicalautomationsCREATE TABLE. - Replace the
migrateRepositoryIDSQLADD-COLUMN migration with a one-time recreate-and-backfill migration, following the exact pattern ofmigrateTaskRepositoriesAllowMultiBranchinapps/backend/internal/task/repository/sqlite/base_migrations.go(usesr.migrate.Apply/recreateTableNamed-equivalent helpers — automation'sStoredoesn't have that helper today; add a smallrecreateAutomationsTableDroppingRepositoryIDfollowing the same create-new/copy/drop/rename/reindex shape used there). Order of operations insideinitSchema:- Run
createTablesSQL(createsautomation_repositoriesfor fresh installs). - If the
automationstable still has arepository_idcolumn (detect viaPRAGMA table_info(automations)), backfill: for each automation row with non-emptyrepository_id,INSERT OR IGNORE INTO automation_repositories (id, automation_id, repository_id, position, created_at) VALUES (<uuid>, id, repository_id, 0, created_at). - Recreate
automationswithout therepository_idcolumn (new table, copy columns, drop old, rename, recreate indexes) — same shape as the task_repositories migration.
- Run
- This migration is idempotent: step 2 is skipped once the column check in
step 3 no longer finds
repository_idonautomations.
Model (apps/backend/internal/automation/models.go)
Automation: removeRepositoryID string db:"repository_id"; addRepositoryIDs []string json:"repository_ids" db:"-"(hydrated separately, likeTriggers).CreateAutomationRequest.RepositoryID string→RepositoryIDs []string json:"repository_ids".UpdateAutomationRequest.RepositoryID *string→RepositoryIDs []string json:"repository_ids,omitempty". Use the nil-vs-non-nil-slice convention already used bydto.TaskRepositoryInput/task_ws_handlers.go(req.Repositories != nilmeans "provided"): nil = untouched,[]= explicit clear, non-empty = replace.
Store (apps/backend/internal/automation/store.go)
CreateAutomation: after inserting theautomationsrow (column list dropsrepository_id), insert oneautomation_repositoriesrow per ID ina.RepositoryIDs(position = index) inside the same transaction.- New
hydrateRepositoryIDsbatch helper mirroringlistTriggersForAutomations:listRepositoryIDsForAutomations(ctx, automationIDs) (map[string][]string, error)—SELECT automation_id, repository_id FROM automation_repositories WHERE automation_id IN (?) ORDER BY automation_id, position. Wire intoGetAutomation,ListAutomations,ListAllEnabledthe same wayTriggersis hydrated today. UpdateAutomation: whenreq.RepositoryIDs != nil, replace the automation'sautomation_repositoriesrows transactionally:DELETE FROM automation_repositories WHERE automation_id = ?then re-insert the new ordered list, inside the sameTxas theUPDATE automationsstatement (do not rely solely onON DELETE CASCADE, which only fires on automation deletion, not on a repository-list replace for a still-live automation).applyAutomationUpdate: drop theRepositoryIDbranch (repositories are now handled directly by the store method above, not via the in-memory struct mutation, since they're a child table rather than a column).
Service (apps/backend/internal/automation/service.go)
CreateAutomation: before building*Automation, validatereq.RepositoryIDs— reject duplicates, and reject any ID that doesn't resolve to a repository belonging toreq.WorkspaceID. Needs arepoStore-shaped dependency capable ofGetRepository/listing by workspace; check what's already injected intoService(s.storeis the automation store only — repository lookups may need a new small interface injected via a setter, following theSetTaskDeleter/SetWorkspaceAuthorizerpattern). Confirm during implementation whether the automation package already has access to a repository lookup (it currently does not import the task/repository package) and add the minimal interface + setter needed; wire it fromapps/backend/cmd/.../main.go(or whereverautomation.NewServiceis constructed) the same waySetTaskDeleteris wired.UpdateAutomation: same validation before callings.store.UpdateAutomationwheneverreq.RepositoryIDs != nil.- Return a typed/sentinel error (e.g.
ErrRepositoryNotInWorkspace) so the WS handler can map it tows.ErrorCodeValidationinstead ofErrorCodeInternalError.
Orchestrator (apps/backend/internal/orchestrator/event_handlers_automation.go)
resolveAutomationRepository: replaceif a.RepositoryID != ""withif len(a.RepositoryIDs) > 0, calling a newresolveExplicitRepositories.- Add
resolveExplicitRepositories(ctx, repositoryIDs []string) []ReviewTaskRepository: loop overrepositoryIDs, reuse the existing per-ID resolution logic fromresolveExplicitRepository(load repo, default branch fallback toautomationDefaultBaseBranch), append oneReviewTaskRepositoryper ID, skip (with a warning log, not a hard failure) any ID that fails to load so one bad ID doesn't sink the whole firing. KeepresolveExplicitRepositoryonly if still referenced elsewhere after the change; otherwise delete it (check vialsp referencesbefore removing). - No other changes needed in
createAutomationTask— it already accepts[]ReviewTaskRepositoryand passes the full slice toCreateReviewTask.Repositories.
Frontend
Types (apps/web/lib/types/automation.ts)
Automation.repository_id: string→repository_ids: string[].CreateAutomationRequest/UpdateAutomationRequest(therepository_id?: stringfields around lines 125/144): →repository_ids?: string[].
apps/web/components/task-create-dialog-multi-repo-guard.ts
- No changes — import
getMultiRepoExecutorDisabledReasondirectly from this existing module (it's a pure function with zero task-creation-dialog dependencies). Do not duplicate the executor-type set.
apps/web/components/automations/config-section.tsx
RepositorySelectionretains its{kind:"none"}variant — still needed by the single-picker fallback branch below — but the repeatable multi-row picker never produces one (each row is always fully resolved the moment it's added).ConfigSectionProps:repositorySelection: RepositorySelection→repositorySelections: RepositorySelection[];onRepositoryChange→onRepositoriesChange: (selections: RepositorySelection[]) => void.dirtyFields.repositorySelection→dirtyFields.repositorySelections.- Compute
selectedExecutorProfile = allExecutorProfiles.find(p => p.id === executorProfileId)andmultiRepoDisabledReason = getMultiRepoExecutorDisabledReason(selectedExecutorProfile?.executor_type). - Executor Profile
SelectField: extend the localSelectFieldcomponent'sitemsshape toArray<{id, label, disabled?, disabledReason?}>(small, additive change — render<SelectItem disabled={item.disabled} title={item.disabledReason}>). Build executor items withdisabled: repositorySelections.length > 1 && getMultiRepoExecutorDisabledReason(p.executor_type) !== null. - Repository picker: branch on
multiRepoDisabledReason === null && conditionType !== "github_pr":- compatible (
nullreason, non-PR trigger): render a newAutomationRepositoryRowscomponent (new fileapps/web/components/automations/automation-repository-rows.tsx) that renders oneSelectFieldper entry inrepositorySelections(options built viabuildRepositoryItems, marking repos already chosen in another row analogous to the task-creation dialog's "Already added" marker) plus a trailing "Add repository" button. Each click appends a row pre-filled with the next not-yet-selected repository —onChange/addRowbail out onkind === "none"(an unreachable defensive guard here, sincepickSelectionFromOptionIdonly returns it for the"__none__"sentinel or a stale ID, neither offered by this picker), so every row is always fully resolved. The button disables once every known repo is already selected. Removing the last remaining row is allowed (falls back to an empty list, which the orchestrator resolves to the workspace's first repository — stated in helper text beside the control). - incompatible (single-repo executor, or a
github_prtrigger): render the existing singleSelectFieldbound torepositorySelections[0] ?? {kind:"none"},onChangereplaces the whole array with[]or[selection]. Forgithub_prspecifically, additionally disable the dropdown and show "PR triggers always use the PR's own repository." — the backend'sresolveAutomationRepository(orchestrator) checks the trigger type first and, forgithub_pr, resolves the repository from the PR's own trigger data unconditionally, never readingRepositoryIDs— so a stale multi-repo selection left over from before the trigger was switched togithub_prhas no effect. Covered byTestResolveAutomationRepository_GitHubPRIgnoresConfiguredRepositoryIDs.
- compatible (
pickSelectionFromOptionId/buildRepositoryItems/selectionToOptionId: unchanged signatures;RepositorySelectionkeeps its{kind:"none"}variant for the single-picker branch above.
apps/web/components/automations/automation-payload.ts
FormState.repositorySelection: RepositorySelection→repositorySelections: RepositorySelection[].resolveRepositoryId→resolveRepositoryIds(workspaceId, selections: RepositorySelection[]): Promise<string[]>— map each selection through the existing per-selection resolution logic (register discovered repos, pass through registered ids) viaPromise.all.buildCreatePayload/buildUpdatePayload:repository_id: repositoryId→repository_ids: repositoryIds.
apps/web/components/automations/automation-editor.tsx
defaultForm.repositorySelection→defaultForm.repositorySelections: [].formFromAutomation:a.repository_id ? {kind:"registered",id:...} : {kind:"none"}→a.repository_ids.map(id => ({kind:"registered", id})).useSaveHandler:resolveRepositoryId→resolveRepositoryIds; the discovered→registered promotion logic (currently checksform.repositorySelection.kind === "discovered") needs to promote each discovered row independently — mapform.repositorySelectionsagainst the resolvedrepositoryIdsarray by index, promoting only the discovered ones.
apps/web/components/automations/automation-editor-sections.tsx
repositorySelectionprop/dirty-field wiring (lines ~143-205) →repositorySelections.
Tests
apps/web/components/automations/config-section.test.tsx: update existing prop name; add cases per the Tests section below.apps/web/components/automations/automation-trigger-drafts.test.ts/ other automation tests referencingrepositorySelection: grep after the rename lands to confirm none were missed (lsp referenceson the removed export is not applicable across TS/Go, so usegrep -rnP '\brepositorySelection\b' apps/web/components/automationsas the completeness check).
Tests
-
What:
automation_repositoriesschema exists and CRUD round-trips an ordered multi-repo list. File:apps/backend/internal/automation/store_test.goHow:TestCreateAutomation_PersistsRepositoryIDsInOrder,TestUpdateAutomation_ReplacesRepositoryIDs,TestGetAutomation_HydratesRepositoryIDs,TestListAutomations_BatchHydratesRepositoryIDs. -
What: legacy
repository_idbackfills intoautomation_repositoriesand the column is dropped, exactly once, idempotently. File:apps/backend/internal/automation/store_test.goHow:TestInitSchema_BackfillsLegacyRepositoryID— seed a raw SQLite DB with the pre-migration schema + a row carryingrepository_id, runNewStore, assertautomation_repositorieshas the backfilled row andPRAGMA table_info(automations)no longer listsrepository_id. RuninitSchematwice against the same DB to prove idempotency. -
What:
CreateAutomation/UpdateAutomationreject repository IDs outside the automation's workspace, and reject duplicates. File:apps/backend/internal/automation/service_test.goHow:TestCreateAutomation_RejectsForeignRepositoryID,TestCreateAutomation_RejectsDuplicateRepositoryID,TestUpdateAutomation_RejectsForeignRepositoryID. -
What: orchestrator resolves N repositories for scheduled/webhook triggers, skips a single bad ID without failing the whole firing, and falls back to the workspace repository when the list is empty. File:
apps/backend/internal/orchestrator/event_handlers_automation_test.go(create if it doesn't exist; check first) How:TestResolveAutomationRepository_MultipleExplicitRepositories,TestResolveAutomationRepository_SkipsUnloadableID,TestResolveAutomationRepository_EmptyListFallsBackToWorkspace. -
What:
getMultiRepoExecutorDisabledReasonreuse is correct for the automation editor's executor-picker gate (the function itself is already covered bytask-create-dialog-multi-repo-guard.test.ts— no new unit test for the predicate itself, just for its wiring below). File:apps/web/components/automations/config-section.test.tsxHow:renders a repeatable repository list when the executor profile supports multi-reporenders a single dropdown when the executor profile does not support multi-repodisables incompatible executor profiles once two or more repositories are selectedkeeps a compatible executor profile enabled with two or more repositories selected
-
What: save flow resolves and promotes multiple discovered repositories independently. File:
apps/web/components/automations/automation-payload.test.ts(create if it doesn't exist; check first — no existing file was found for this module) How:resolveRepositoryIds resolves a mix of registered and discovered selections,buildUpdatePayload sends repository_ids in row order.
E2E Tests
-
Scenario: GIVEN the automation editor with a
worktreeexecutor profile selected, WHEN the user adds a second repository row and saves, THEN the saved automation shows two repository chips/rows on reload. File:apps/web/e2e/automations/multi-repository.spec.tsWhat to verify: "Add repository" button visible and enabled; second row appears; after save + reload, both repositories are pre-selected. -
Scenario: GIVEN the automation editor with a
localexecutor profile selected, WHEN the user opens the repository picker, THEN it is a single dropdown with no "Add repository" control. File:apps/web/e2e/automations/multi-repository.spec.tsWhat to verify:[data-testid="repository-selector"]renders as one select; no add-repository button in the DOM. -
Scenario: GIVEN two repositories already selected, WHEN the user opens the Executor Profile dropdown, THEN incompatible executor profiles are visibly disabled. File:
apps/web/e2e/automations/multi-repository.spec.tsWhat to verify: the incompatible option hasaria-disabled/disabledand is not selectable via click.
Implementation Waves And Parallel Candidates
Wave 1:
- [ ] [task-01-backend-data-model](task-01-backend-data-model.md)
Wave 2 (parallel candidates — user authorization required):
- [ ] [task-02-orchestrator-resolution](task-02-orchestrator-resolution.md)
- [ ] [task-03-frontend-multi-repo-picker](task-03-frontend-multi-repo-picker.md)
Wave 3:
- [ ] [task-04-e2e](task-04-e2e.md)
Open Questions
- Where exactly
automation.NewServiceis constructed and whether a repository-lookup dependency is already reachable there, or needs new plumbing — confirm during task-01 implementation (flagged in that task's Inputs).