Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
13 KiB
Office — autonomous agent management
internal/office/ implements Office: workspaces of long-running agents that pick up tasks, coordinate via handoffs, and report through a dashboard. This file routes you to the specs and records local traps; it does not restate either.
Spec authority
docs/specs/office/ (15 files) is the authority for what Office is and why — it outranks any card, register, or comment. Where code and spec disagree, that is a defect in one of them; do not silently follow the code. A sixteenth office-tagged spec, per-agent + per-role tier selection, lives in a sibling directory, not under docs/specs/office/.
| Spec | Status | Covers |
|---|---|---|
overview.md |
draft | Why Office exists: autonomy layer on top of kandev's task system |
agents.md |
draft | Persistent Office agent identity vs. execution profiles |
tasks.md |
draft | Office task model: assignee, reviewers/approvers, blockers, subtasks, per-agent working memory |
scheduler.md |
draft | Autonomous wakeup pipeline: assignments/comments/approvals, routines, idle skip, retry/backoff |
runtime.md |
draft | Error-handling contract for the agent runtime; 2026-08-17 amendment: provider classification/recovery is superseded by ../platform/provider-error-recovery.md and ../agents/dynamic-agent-routing.md — read the amendment banner before the body |
routing.md |
archived | Provider routing; superseded by ../agents/dynamic-agent-routing.md — do not treat as current |
costs.md |
in-progress | Cost tracking and budget management |
dashboard.md |
draft | Workspace-health landing page: agents, run trends, recent activity, spend |
live-updates.md |
draft | Real-time refresh so concurrent agent fan-out is visible without a manual reload |
inbox.md |
draft | Centralized inbox, approvals, and activity log for actions needing human judgment |
assistant.md |
draft | Personal-assistant agent, external channels (Telegram/Slack/email), and agent memory |
automation-runs.md |
draft | Reading an automation's own output without opening its edit form |
automations-settings.md |
draft | Scheduling an automation (cron / PR event / webhook) from Settings, not the board |
testing.md |
shipped | E2E mock harness for task sessions/messages — Playwright can't launch real executors in CI |
unread-divider.md |
shipped | Slack-style unread divider for background-running task sessions |
office-agent-tier-routing/spec.md's own front matter still calls routing.md "authoritative" for tiers, provider order, execution profiles, provider health, and wake-reason policy — that predates routing.md's archival in docs/specs/INDEX.md and is now stale; trust the INDEX status over the sibling spec's own text.
Traps
- A run is not a task start. The
runstable carries provider routing (resolved_provider_id,logical_provider_order,requested_tier, plus theoffice_run_route_attemptsledger), the per-reasonassembled_prompt, theAppendRunEventtimeline, and retry/backoff/coalescing (retry_count,earliest_retry_at,coalesced_count,idempotency_keywith unique indexidx_run_idempotency).Service.QueueRun(service/run.go) andSchedulerService.QueueRun(scheduler/run.go) are the entry points that populate all of it;TaskStarter(theStartTaskseam office calls,service/service.go) runs only after. CallingStartTaskdirectly, or any ordinary kanban start path, skips all of the above. Seescheduler.md. heartbeatas a wake source is retired (scheduler.md: routines are "the only mechanism for periodic wakes";wakeup/payloads.gostates"heartbeat"is intentionally absent from theSourceenum) — but three literal"heartbeat"constants still exist in code (scheduler/run.go's andservice/run.go's duplicateRunReasonHeartbeat,routing/types.go'sWakeReasonHeartbeat, still listed inAllWakeReasonsand used to seed aTierPerReasonpolicy inonboarding/service.go).checkIdleSkip(service/scheduler_integration.go) delegates classification toshared.IsPeriodicTasklessWake(run.Reason), true only forRunReasonRoutineDispatchCronandRunReasonHeartbeat. The lightweight routine path (routines/service.go) sets the reason viashared.RoutineDispatchReason(source)— cron getsRunReasonRoutineDispatchCron(skippable), manual/webhook getsRunReasonRoutineDispatchEvent(never skippable). The legacyRunReasonRoutineDispatch("routine_dispatch") literal, written for all three triggers before the cron-only constant existed, is treated as non-skippable since a persisted run row can't say which trigger produced it. The wakeup dispatcher's claim-time coalesce (wakeup/dispatcher.go'scoalesceIntoInflightRun) promotes an in-flightqueuedrun's reason to the incoming request's (or itsSourcewhenReasonis empty — same fallback ascreateFreshRun) when the merge would otherwise let a periodic-classified run swallow an event-triggered one — promotion is monotonic (periodic → event only). Aclaimedinflight run is never promoted in place:processRun(service/scheduler_integration.go) evaluatescheckIdleSkipagainst the*models.Runit captured at claim time and never re-readsReason, so mutating the row afterward would race a decision already in flight. An event request that would otherwise coalesce into a claimed periodic run gets its own fresh run instead. Check the reason string (and whether it could have been promoted by a coalesce, or split into a second run because the inflight one was already claimed) before assuming an idle-skip gate fires for a given run.- Continuation summary scope must come from
summaryScopeForRun(service/event_subscribers.go), never a literal string. Its sole caller,refreshContinuationSummary, upserts under the same value it reads, so reader and writer can't drift. Two scope forms exist:routine:<id>andagent:<id>; the legacy"heartbeat"scope is retired. - Participant slate: one builder, not office's own. The AC-50 slate construction lives in
internal/workflow/engine—(*Engine).requiredSeats/requiredSeatsForWorkflow(workflow/engine/quorum.go) — andResolveParticipantRole(same file) reuses it so role resolution and slate membership can never disagree about who participates. Office reaches it throughengine_dispatcher.Dispatcher.ResolveParticipantRole, which forwards verbatim. Do not add an office-local "who are this task's reviewers" query; that is a fourth answer to a question that already has exactly one. - Lightweight vs. heavy routines fail differently. A routine with an empty
task_template(routines/service.go;CreateDefaultCoordinatorRoutinesetsTaskTemplate: "", cron*/5 * * * *) is lightweight. Its idle skip — firing with no actionable task, launching nothing — is specified behavior (scheduler.md, telemetrywakeup_idle_skipped), not a bug; don't "fix" it.checkIdleSkipfails open on a DB error. - A new Office HTTP route must declare how it is scoped. Office routes are keyed by a resource id far more often than by
:wsId, soofficeWorkspaceScopeMiddleware(internal/backendapp/office_scope.go) resolves the route's own ids to their owning workspace before dispatch — do not add a per-handler ownership check instead. A route naming a resource kind with no resolver is denied, andTestOfficeRouteScopeCompletenessturns that into a build failure. Adding a route means one of: register aWorkspaceIDFor...lookup inoffice/repository/sqlite/workspace_scope.goplus its<collection>/:<param>entry inofficeParamScopeResolvers; list a child param inofficeScopedSubResourceParams; or add it toofficeWorkspacelessRoutes/Prefixeswith the reason. :wsIddoes not excuse the other ids on the same route./workspaces/:wsId/labels/:idand/workspaces/:wsId/tasks/:taskId/...reach handlers that act on the sibling id alone (UpdateLabel(c.Param("id")),ListLabelsForTask(c.Param("taskId"))), ignoring the workspace they are mounted under — so a caller's own workspace id paired with a foreign label or task id was a cross-workspace read/mutation. The guard authorizes:wsIdand every other resolvable param; the completeness test enforces the same.- An agent JWT is only workspace-checked where you check it.
AgentAuthMiddlewarecomparesclaims.WorkspaceIDto:wsIdand nothing else, and the handlers' own agent-caller guards (agentCallerFromCtx+isAdminRole/caller.ID == target) are role and identity checks, never workspace. A CEO-role token minted in workspace A could therefore act on a workspace B agent.authorizeOfficeAgentCallerresolves by-ID routes for agent callers too and requires every resolved workspace to equal the token's. Do not reintroduce a blanketCallerFromContext(c) != nil { return nil }early-out. - Ids on one route must resolve to the SAME workspace. Authorizing each id on its own is not enough: a caller owning two workspaces passes the ownership check on both, so
/workspaces/<A2>/labels/<label in A1>satisfied every individual check and still crossed a boundary.officeRouteWorkspacesrefuses a route naming two workspaces; no Office route legitimately does (a task's reviewers, an agent's channels and runs, a workspace's labels are all intra-workspace). The quorum handler's hand-rolledtask.WorkspaceID != workspaceIDis the same rule patched per handler.TestOfficeMultiIDRoutesRejectMixedWorkspacesgenerates this check from the registered route table, so a new multi-id route is covered the day it is added. - Resolvers must fail closed. They deliberately do not reuse
GetTaskWorkspaceID/GetProjectWorkspaceID(repository/sqlite/tasks.go) — those return("", nil)for a missing row, andAuthorizeWorkspaceAccessreads""as "no scoping applies", i.e. allow everything. - Advancement has two signals. An explicit
step_complete_kandevMCP call (registeredmcp/server/server.go, ADR 0015) and the turn-end path (handleAgentReady,orchestrator/event_handlers_agent.go), reconciled for late signals inorchestrator/event_handlers_step_completion.go. The per-step toggleauto_advance_requires_signal(mcp/server/config_handlers.go) couples them — know which one a step relies on before changing either. - Config sync's mutual-exclusion guard is wired import-free.
configsync.Serviceis the single source of truth for whether a workspace has an active config-sync source (HasActiveSource), and it must refuseoffice/config'sApplyImport/ApplyIncoming/ApplyOutgoingandoffice/dashboard's git clone/pull while active. Neither consumer package importsconfigsync: each declares its own local, exportedActiveSourceCheckerinterface (HasActiveSource(ctx, workspaceID) (bool, error)), androutes.gois the sole composition root that satisfies it withsvcs.ConfigSync. Assign through an interface-typed local variable there (var guard config.ActiveSourceChecker; if svcs.ConfigSync != nil { guard = svcs.ConfigSync }) rather than passing the concrete*configsync.Servicepointer straight into the constructor — a nil concrete pointer assigned directly to an interface parameter produces a non-nil interface wrapping nil, which aguard == nilcheck inside the handler package would miss.
Package map
scheduler/— wakeup queueing, run dispatch, idle skip, retry/backoffservice/— core Office service: run lifecycle, event subscribers, continuation summariesconfigsync/— per-workspace config sync: pulls agent/skill/project/routine definitions from a GitHub or GitLab repository on a schedule (service.go,poller.go,provider.go), reconciles them against Office's tables (reconcile*.go), and exposes the HTTP config/force-sync routes (handlers.go,models.go). Modeled oninternal/workflowsyncbut shares no code with it.Servicealso satisfies theActiveSourceCheckerguard consumed byoffice/configandoffice/dashboard— see the trap above.routines/— routine (cron) definitions and dispatch, including the default coordinator routinewakeup/— wake payload/source/reason types and the dispatcher that turns them into runsrepository/sqlite/— Office's SQLite tables (runs, route-attempt ledger, etc.)routing/— provider routing types; spec archived, package still live — exactly the kind of code/spec mismatch the precedence rule above exists for; readers wanting current routing behavior should start from../agents/dynamic-agent-routing.mdengine_dispatcher/— office's bridge intointernal/workflow/engine(participant roles, transitions)engine_adapters/— concrete adapters office supplies to the workflow engine (CEO, child-task creation, workflow switching); consumed frominternal/backendappruntime/— Office agent runtime wiringsummary/— continuation summary storageconfigloader/— loads per-role agent instructions;configloader/instructions/{ceo,devops,qa,reviewer,security,worker}/AGENTS.mdare the role-specific system prompts fed to each Office agent type, not developer docs.ceo/additionally hasHEARTBEAT.md.agents/,approvals/,channels/,config/,costs/,dashboard/,infra/,labels/,models/,onboarding/,projects/,shared/,skills/,testharness/,tree_controls/,truncate/,workspaces/— one subpackage per dashboard/domain concept; names match the spec files above.