# Concurrent projects and a unified local dashboard

Status: Approved for implementation on `feat/multi-project-management`
Date: 2026-09-19

## Problem

Verified against 0.3.2: inherited `AGENTHUB_STATE_DIR` routes commands in a second
project to the first hub. The unlocked JSON port registry also loses updates:
32 parallel allocations produced two unique ports and one surviving registration.
The baseline gate passes 162 tests, but does not cover these scenarios.

## Existing assets

Each daemon already owns its bus, task database, adapters, control token and local
dashboard. Bun provides SQLite without another runtime dependency. Reuse existing
console authorization, dashboard validation and PII redaction.

## Design

### Project context

- Resolve real paths and the nearest initialized ahub directory without crossing
  the nearest Git working-tree root. Otherwise use that root or the non-Git cwd.
- Each worktree/submodule is independent. A global CLI prefix,
  `ahub --project <path|id> <command>`, selects another registered project or path.
- Only accept an inherited state directory when its recorded project matches.
  Pass the validated root and state directory to children and MCP servers.
  For initial custom-state setup, an explicit matching `AGENTHUB_PROJECT_DIR` pair
  is accepted only when no contradictory marker exists. Startup records a persistent
  project marker. Native MCP sessions stay pinned to their launcher-supplied state
  directory, while their control handshake verifies the manifest identity.
- Native memory identity remains separate: preserve native claude-mem aliases,
  including parent and parent/worktree names. Show shared-alias warnings; do not
  change global hooks or historical records.

### Registry and lifecycle

- Use `~/.agenthub/registry.db` (override root with `AGENTHUB_HOME` for tests).
  Register on init/up. Store opaque ID, canonical root, state directory, ports and
  runtime ownership. Import legacy ports.json transactionally and conservatively.
- Serialize allocation and per-project startup claims. Retain base 4600/stride 10;
  retry available ranges on startup port conflicts. Never terminate foreign listeners.
- Publish readiness only after binding. Authenticated status carries project ID,
  instance ID, version and protocol; bounded clients verify the requested identity.
- Only the owning instance removes runtime files or releases a claim. Stop waits
  for owned children; uncertain ownership and incomplete shutdown are explicit errors.
- Expose `projects`, `status --all`, and `projects remove <id>` (stopped metadata
  only). Moved roots are new registrations; never merge by basename.

### Unified dashboard

- `ui --all [--no-open]` starts a separate lazy manager, usable outside projects.
  `ui --all --stop` stops only the manager. Existing project-local ui remains.
- List roots, status, peers, queues and task counts. Selecting a project exposes
  existing stream, board, messages, approvals and budgets.
- Start/stop registered hubs; stop confirmation names the project. Native TUI
  launch remains CLI-only. Manager starts are attended and use project config and
  credential files, not another project's gateway/state/unattended environment.
- Manager uses console-only authenticated snapshot/action RPCs. Browser input
  selects registry IDs, never arbitrary filesystem paths, PIDs, ports or tokens.
  Mutations carry expected daemon instance. No automatic mutation retries.
- Scope cursors/drafts by project, discard stale responses across switches and
  restarts, and maintain bounded redacted event buffers in each daemon.
- Preserve exact Host/Origin checks, loopback-only listeners, one-time tickets,
  expiring HttpOnly sessions, CSP and terminal-only private approvals.
- Bump the control protocol and rebuild the plugin. Incompatible hubs get explicit
  upgrade/restart guidance, never automatic restart.
- One active Codex TUI per hub; reject a second attachment. Quota windows may be
  account-wide and must not be added together across projects.

## Testing and acceptance criteria

- Root discovery: nested directory/project, symlink, submodule, worktree, same
  basename, invalid target, and inherited context from another project.
- 32 simultaneous allocations retain all entries with unique ports. Concurrent
  starts of one project produce one daemon. Migration, occupied ports and startup
  recovery preserve existing data and live processes.
- Two hubs with fake native/model services isolate boards, messages, approvals,
  quota files, sidecars and shutdown. Test stale tokens, PID reuse, old protocols,
  partial startup, instance changes and owned cleanup.
- Browser: start with no hub, start two projects, switch/action/stop one and keep
  using the other. Cover late responses, identical task IDs, expired approvals,
  session expiry and PII redaction.
- Run scripts/check.sh and record real two-project smoke evidence separately.

## Delivery

Implementation issue and feature branch, spec/docs updates, independently reviewed
and verified PR. Preserve pre-existing instruction-file changes.

## Out of scope

Cross-machine task routing (broker, #446), fully isolated native memory, new runtime dependencies,
visual redesign, automatic merging and npm publication.

## Cross-project task handoff (#604, agent-hub#1030)

Same-machine cross-project routing is no longer out of scope: work that belongs to another project that runs agent-hub is registered on that project's board.

- **Target.** `project` names a project in the machine registry (its canonical root or its id). An unregistered target, the caller's own project and a target whose daemon is not running are refused, the last with the person's action (`ahub up` in that project). Nothing is queued.
- **Who and what.** The person (`ahub task handoff --project <root|id> [<class>] <title...> [--path <p>]... [--issue <n>] [--task <n>] [--detail <text>] [--duplicate-ok <reason>]`), or a configured planner or the conductor (`hub_task_handoff`). A feature or behavior change first needs a spec issue in the target repository, passed as `issue`; a mechanical chore goes straight to a task. The request is closed (unknown fields refused), bounded (8 KiB whole) and repository-relative for paths.
- **Transport.** The origin's daemon reads the target's control descriptor (same machine user) and sends `task_handoff` as a console-role control message with origin `{ projectId, peer, taskId? }`. The target's `Tasks` creates an ownerless proposal made by the hub, with the origin recorded in `task_handoff_origin`; its own routing and planner take it from there. The origin peer has no identity or authority in the target: it is a record, never a roster peer.
- **Follow-back.** On accepted, in review, approved, declined and cancelled the target sends `task_handoff_event`; the origin records it in `task_handoff_outbound` and delivers one `kind: task` envelope to the requesting peer (`agent-hub task 123 approved: PR #N at <sha>`: an event name, a PR number and a full head, never target text). An origin that was down asks the target for the current state of its open handoffs when it starts (`task_handoff_states`). `ahub board --handoffs` and `hub_task_handoffs` list them.
- **Duplicates and cancel (#1175).** A handoff naming a spec issue (`issue`) that already has an open task on the target's board (proposed, backlog, in progress, in review or changes requested; a `[pii]` row is never named) is refused before any row exists, with the open task ids, unless the sender passes `duplicate_ok` (a reason of up to 300 characters, recorded in the task's detail). An issue number identifies work only together with its repository: `sdlc.repo`, `external {repo, issue}` (an imported backlog row) and a slug `refs.repo` that name another repository than the target's do not count. The target's configured, rostered conductor may cancel a handed-off task that nobody has accepted and that has no execution evidence, with a reason; the origin hears `cancelled` through the follow-back, never the reason. A target from before this check refuses `duplicate_ok` as an unknown field, which the sender reports as "upgrade the target hub or hand off without `duplicate_ok`".
- **Idempotent request (#1203 T1).** The origin mints a `handoffKey` (UUID v4) per request, or takes the one a retry passes (`--key`, `handoffKey`), and sends it in the `task_handoff` request body to a target that advertises `task_handoff_key`. The target stores it with a digest of what was asked in `task_handoff_origin` (unique per origin project) and writes the proposal and the origin row in one board transaction (`Board.proposeHandoff`). A key it already holds answers with that task (`replayed`) before the duplicate check and before any PII screen; the same key for a different request is refused. A timeout or a closed connection is not a refusal: the origin sends the same key once more, then asks the target by key (`task_handoff_by_key`, answered only to the asking project and only with the fields a live event carries), and otherwise reports the new refusal code `outcome_unknown`, naming the key to retry with. The origin records its outbound row from the reply or the by-key answer, never resetting a row that already exists.
- **Converging follow-back (#1203 T2).** Each `task_handoff_event` carries `seq`, the target task's flow revision (its history length), to an origin that advertises `task_handoff_seq`. The origin keeps the sequence of the last applied event in the outbound row and ignores an event whose `seq` is not newer: it changes nothing and sends no envelope, decided inside the one board write, so events that arrive out of order (each uses its own connection) cannot move a row backwards. An event without `seq` (an older target) applies as before. The origin's catch-up (`task_handoff_states`, which now also returns `seq`) runs at start, every 5 minutes and when a target's control descriptor changes, over every row that is not cancelled and, for an approved one, was updated within the last 7 days (a reviewer can withdraw an approval; the origin only learns of it through the sequence), with no 200-row cap and in requests of at most 200 task ids. `changes_requested` and `reopened` are events, sent only to an origin that advertises `task_handoff_seq`. A catch-up pass never overlaps another, never holds a board write and stops at shutdown. `ahub board --handoffs` still lists the 200 most recently changed rows; that cap is for display only.
- **Diagnostics and repair (#1203 T3).** Every failure is visible and repairable by the person. A connection to a target that fails is named by the error's code and never by its message: 4426 (the wire versions share no protocol) is `older_target` and says to upgrade whichever hub is older, 4404 (another hub or instance answers) is the new refusal code `mismatch` and says to check `ahub projects`, a connect timeout says the hub may be stuck (`ahub status`), and only an unreachable hub says "not running" with `ahub up`. A failed notify, catch-up pass or handoff writes one `hub.log` line per target and cause in each window (15 minutes), with a fixed cause phrase and never a task title or the target's text. `ahub task handoff --list` (the person's command, read-only) shows each handoff with its age since the last report and `reachable`, `unreachable` with its cause and next step, or `moved` (the project id is not in the machine registry: it was removed or its root changed, and the id is a hash of the root), read from the registry and the target's descriptor file without opening a connection. `ahub task handoff --sync` (the person or the conductor) runs a catch-up pass now and answers with the refreshed list; it waits for a pass already running and then runs its own, for at most 20 seconds (under the caller's 30 second control timeout, because the pass asks targets one after another): past that it answers with the list as it stands, `syncing: true` and the number of targets still pending, the pass goes on in the background, and the CLI prints "catch-up still running for N targets: run `ahub task handoff --list` in a minute". An agent gets the same list from `hub_task_handoffs` (now with `age`, `ageMs`, `reach` and `cause`) and cannot sync. A catch-up request that gets no usable reply (the target refused it, timed out or dropped the connection) is a failure like any other: its target reads `unreachable` with the cause "no answer to the state request" and the step `ahub status` in that project, one log line is written, and the earlier failure is not cleared. If the pass itself fails, `--sync` answers `synced: false` with that cause instead of `synced: true`.
- **Follow-back envelope (#1203 T1).** It carries `refs.handoff {project, task}` (the target's project and task) and no `refs.task`, so the bus never judges it against a local task that happens to have the same number; the one-line body is unchanged.
- **Privacy.** Refused during a private (PII) turn and for a `[pii]` task named with `task`; the target refuses text that matches a PII pattern or that its screen cannot clear. No memory, evidence or turn content crosses beyond the handoff fields.
- **Compatibility.** The additive daemon features `task_handoff` and, from #1203 T1, `task_handoff_key` and `task_handoff_seq` (the latter: a target sends `seq` and the two new events only to an origin that has it; an origin ignores a missing `seq`). `task_handoff_key` (an origin sends no key to a target without it and keeps the earlier behavior, a timeout there is `outcome_unknown` without a retry key, and the request is not repeated). Neither feature bumps the protocol: a new message type is answered as unknown by an older hub, and an optional field is ignored, except `duplicate_ok` and `handoffKey`, which an older target refuses as unknown fields (so the key is sent only to a target that advertises it). An older target is refused with a named "upgrade the target hub" error, and a recovery target without the label is refused while either handoff table holds a row.
