Skip to content
93 changes: 61 additions & 32 deletions planning/workflow/collaboration.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,61 @@
# Multi-Agent Collaboration Protocol

This document defines the 10 binding collaboration rules for orchestrators and worker subagents operating across parallel git worktrees.

## The 10 Collaboration Rules

1. **One Writer Per File**: Every document, concept file, outgoing note, and receipt has exactly one owning writer at a time. Wide shared files (`main.md`, `design.md`, `AGENTS.md`, `doc/README.md`, catalogs) must only be modified via pull requests under active mutex leases.
2. **Add-Only Records**: Cross-agent communication must use new files (`notes/`, `receipts/`, `decisions/`) or union-merged lines (`changes.md`). Never append directly to the end of a shared file owned by another agent.
3. **Worktree Boot Protocol**: Every parallel worker must execute in a dedicated worktree on a dedicated branch branched from the declared integration baseline.
- Sourcing the local git environment: `source /home/user/.local/share/plaza-tools/git-env.sh`.
- Disabling automatic garbage collection: `git config --worktree gc.auto 0`.
- Pushing an empty branch to origin immediately upon creation to reserve the ref: `git push -u origin <branch>`.
- Making the first commit and opening a PR before proceeding with extensive changes.
- Guardrails: strictly no `git stash` (use WIP commits), no `git reset --hard`, no rebase, no force-push, no `sudo git`, and stage explicit paths only (`git add -- <paths>`).
4. **Dead Branch on Merge**: Because repository settings automatically delete head branches upon merge, merged branches are immediately considered dead. Post-merge follow-up work must be performed on a newly branched ref (e.g. `<branch>-2`).
5. **Live Coordination & Atomic Leases**: Non-committed live coordination data lives in `$(git rev-parse --git-common-dir)/agent-work/<package>-<stage>/`:
- Mutex locks use atomic directories: `mkdir locks/<resource>.lock/` containing an `owner` file (`<name> <acquired> <expires> <purpose>`) with a 20-minute expiry and atomic rename-based takeover.
- Append-only heartbeat logs: `<name>.md` with lines `<name> <UTC> <kind>: <text>`, beginning with `start` and ending with `end`.
6. **Worker Completion Report**: Every worker subagent must terminate with a structured report containing:
- Branch name and open PR URL.
- Exact last pushed commit SHA (`git rev-parse HEAD`).
- Verified automated test commands and output.
- List of unverified assumptions or open questions.
7. **Orchestrator Merge Gate**: An orchestrator merges a worker's PR only when:
- The remote ref (`git ls-remote origin <branch>`) matches the open PR's head SHA and matches the worker's reported last SHA.
- The worker subagent is confirmed idle/finished.
- Required status checks are green.
- Merging uses a merge commit (`--no-ff`), followed by verification that the commit is an ancestor of the base (`git merge-base --is-ancestor`).
- Stalled workers (no heartbeat for 20 minutes, no active lease, no open PR) are restarted with their original brief on the same branch.
8. **Ready Frontier Dispatch**: A concept is ready to dispatch only when all of its hard prerequisites (`requires`) are fully merged, no active lease exists, and no open PR or remote branch is currently working on it. Maximum concurrency is capped by `max_parallel_writers` (default: 5).
9. **Context Pointers Over Pasted Summaries**: Orchestrators communicate with subagents using file paths, commit SHAs, and issue URLs. They avoid pasting large text transcripts or intermediate summaries into prompts.
10. **Green on Own Base**: Every PR must pass all required checks against its own base. CI checks validate only the packages modified by the PR; global whole-tree audits run on scheduled workflows.
# Collaboration

How parallel agents share one repository without losing work. The skills cite these rules by number ("collaboration rule 7") instead of restating them. File formats are in [records.md](records.md), values in [vocabulary.md](vocabulary.md), and the base branch, git environment and cap in the profile ([profile.md](profile.md)).

## The rules

1. **One writer per file.** A concept file, its outgoing notes, its receipts and a live log each have one writer at a time; [records.md](records.md#package-layout) says who. Wide files (`main.md`, `design.md`, `AGENTS.md`, `doc/README.md`, catalogs, roadmaps) change only through a PR from your own branch.
2. **Add-only records.** What several agents add to is a set of new files (notes, receipts, decisions) or one line each in the union-merged `changes.md`. Never append to the end of a shared file by hand.
3. **Worker boot.** Every writer starts in its own worktree and branch:

```sh
source /home/user/.local/share/plaza-tools/git-env.sh # commits fail without it
git fetch -q origin
git worktree add -b <branch> <worktree_root>/<name> origin/<base>
cd <worktree_root>/<name> && git push -u origin <branch>
```

- Push the empty branch before editing, so the name is taken. Open the PR after the first commit; GitHub refuses a PR with no diff.
- Never `git stash` (all worktrees share one stash; use a WIP commit), `gc` or `prune`, `sudo`, force push, rebase, or `git add .` (stage explicit paths). Merge commits only.
- Merge `origin/<base>` into your branch, and push, before opening the PR and again before it lands. Conflicts are then resolved in your worktree, and `changes.md` merges with git's union driver, which GitHub's merge button may skip.

4. **A merged branch is dead.** GitHub deletes it on merge. Follow-up work goes on a new branch (`-2`, `-3`) and a new PR. Never base a PR on a branch that will be deleted first: target the trunk, or an `integration/` branch that merges last.
5. **Live state stays outside git.** Leases, heartbeats and push SHAs go in the live directory ([Live coordination](#live-coordination)). Facts that must last (notes, receipts, decisions, history) go in git.
6. **Final message.** Every worker ends with its branch, PR URL, last pushed SHA, what it verified (commands and real output) and what it did not.
7. **Orchestrators only merge.** Workers write content. The orchestrator merges, files the decision records reviewers return, and keeps issues and state current. It never pushes to a worker's branch; it sends the worker back.
- Merge a worker PR only when the worker has finished (its log ends with `end`), the SHA triple check holds (`git ls-remote origin <branch>` = PR head = reported SHA), and the PR is mergeable, not a draft, based on the trunk, green, and inside the worker's owned paths. Afterwards confirm `git merge-base --is-ancestor <sha> origin/<trunk>`.
- Restart rule: a worker with no log line for 20 minutes, no live lease and no open PR is stalled. Restart it with its original brief on the same branch, merging what is there, never resetting.
- A branch with commits ahead of the trunk and no PR is an orphan. Restart its worker, or log it abandoned; never delete it.
- Commands: [merge-and-restart.md](../../.agents/skills/research-workflow/references/merge-and-restart.md).
8. **Dispatch only what is ready, within the cap.** A unit starts only when `ready` lists it: every `requires` target merged, no live lease, no open PR or pushed branch for it ([ordering.md](ordering.md#waves)). At most `max_parallel_writers` writers run at once (profile; 5). Read-only reviewers hold no worktree or lease and do not count. Each unit gets one fresh session; size it to fit one, and split it if it would not.
9. **Paths, not summaries.** Pass file paths, SHAs and issue and PR URLs between agents. Never paste a summary of something the receiver can read itself.
10. **Every PR is green on its own base.** A failure counts as pre-existing only if the base's latest run shows it. CI is meant to check only the packages a PR changes, with a scheduled job for the whole tree; today it checks the whole tree on every PR ([Tool status](records.md#tool-status)).

## Live coordination

Leases and heartbeats change every few minutes and every worktree must see them at once, so they live in the git common directory, which all worktrees of a clone share. Nothing here is committed and nothing here is the record.

- **Directory.** `$(git rev-parse --git-common-dir)/agent-work/<package>-<stage>/` per stage, `agent-work/<package>/` for package-wide locks, and `agent-work/<package>-router/` for the router. If the common directory is not writable, use the profile key `agent_work_dir`.
- **Locks.** `locks/<resource>.lock/`, created with `mkdir`, which fails when the directory exists, so exactly one writer gets it. It holds a file `owner` with one line `<name> <acquired> <expires> <purpose>`, times in UTC.
- A lease lasts 20 minutes. The holder renews it before then by rewriting `<expires>`, and removes the directory when done.
- Anyone may take over an expired lease: rename the directory to `<resource>.lock.stale-<UTC>` (only one rename succeeds), then create it again.
- Resources: `<C001>` for a concept at its stage, taken before the worker is dispatched; package-wide `ids` while allocating a concept or decision ID; package-wide `file-<path>` for a wide file, with each `/` written as `__`.
- Until `lease acquire|release|list` exists ([Tool status](records.md#tool-status)), make the directory and write `owner` by hand.
- **Heartbeat logs.** `<name>.md`, one per writer, appended only by that writer. Each line is `<name> <UTC> <kind>: <text>`.
- Worker kinds: `start` first, `heartbeat` at least every 10 minutes, `push <sha>` after every push, `end` last.
- Router kinds: `dispatch`, `merge`, `restart`, `abandoned`. The router keeps each worker's brief in its own directory as `<worker>.md`, so a restart can reuse it.

## Failure scenarios

Each was found in a review of the first version of this workflow; the prevention is the rule or mechanism above that stops it.

- **Every status change edits one shared state block, so parallel PRs always conflict.** Per-concept state blocks with one writer, generated views, and `changes.md` lines (rules 1, 2). The tool on `main` still uses one block ([Tool status](records.md#tool-status)).
- **`ready` lists concepts that are already running, so work is dispatched twice.** `ready` reads the trunk and skips leased and running units; dispatch takes the lease first (rule 8).
- **A worker commits after its PR merged, or reports done without pushing.** Final message with the last pushed SHA, the SHA triple check, dead merged branches, and the orphan sweep (rules 4, 6, 7).
- **Auto-delete strands PRs stacked on a branch that merges first.** Target the trunk or an `integration/` branch that merges last (rule 4).
- **Notes on unmerged branches are invisible, so reconcile reports everything resolved.** `check --remote-notes` scans every `origin/*` ref, note-only PRs merge fast, receipts record the scanned SHAs, and a later note reopens S3 ([records.md](records.md#receipts)).
- **Claims exist only in git, so two orchestrators take the same unit or file.** `mkdir` leases, including `file-<path>` locks for wide files (rule 5).
- **The shared stash, a missing git environment, or `gc` breaks worktree isolation.** The boot block and its prohibitions (rule 3).
- **Whole-tree validation couples unrelated workers, so red becomes normal.** Green on its own base, changed-package checks, and the pre-existing failure rule (rule 10).
- **Appends at the end of wide files conflict on every parallel PR.** Per-concept sections, one file per entry, and `merge=union` only for line lists (rules 1, 2).
- **No machine-readable stage or liveness, so the orchestrator stalls or starts implementing.** Enumerated run statuses derived from git and GitHub ([vocabulary.md](vocabulary.md#run-status)), heartbeats, the restart rule, and orchestrators that only merge (rules 5, 7).
96 changes: 32 additions & 64 deletions planning/workflow/decisions.md
Original file line number Diff line number Diff line change
@@ -1,79 +1,47 @@
# Decision Protocol & Human Review
# Decisions

This document defines how technical disagreements, trade-offs, and architecture decisions are evaluated, recorded, and escalated during research and design.
How a choice is recorded, who may confirm it, how disagreements are settled without stopping work, and what a human is asked. The record format is in [records.md](records.md#decisions) and the [decision template](templates/decision.md).

## 1. Decision Records (`decisions/D001-<slug>.md`)
## Source and status

Every architectural choice, technology selection, or contested trade-off is recorded as an explicit decision document:
Source says where a decision came from:

```markdown
# D001: Structured Storage Engine Selection
- `stated`: the transcript says it. Cite the segments: `stated (T051)`.
- `inferred`: it follows from what is stated or from the repository's existing rules. The rationale names what it follows from.
- `agent-preliminary`: an agent chose it so work could continue.
- `human-confirmed`: a human approved it. Cite the URL of their message.

- Status: preliminary | confirmed | reversed
- Source: stated | inferred | agent-preliminary | human-confirmed
- Date: 2026-10-19T06:09:02Z
- Affects: C001, C004
- Reversal cost: High (requires database migration)
Status says whether it is settled:

## Question
- `preliminary`: in force and open to change. `inferred` and `agent-preliminary` decisions start here.
- `confirmed`: settled. `stated` and `human-confirmed` decisions are confirmed.
- `reversed`: no longer in force. A dated line under Choice says what replaced it.

What storage backend should index world state events?
Only a human confirms an `agent-preliminary` decision. No agent, reviewer or later stage sets `human-confirmed`, however strong the evidence; an agent may record a human's confirmation or reversal by citing their message. Agents may change a preliminary choice (after the challenge pass, for example) by adding a dated line under Choice.

## Options Considered
## Coverage

### Option A: SQLite via Rusqlite
- Every decision has a stable ID, `D001`, `D002`, ..., taken from `ids` under the package's `ids` lease ([collaboration.md](collaboration.md#live-coordination)). An ID is never reused, even after a reversal.
- Every downstream artifact cites by ID the decisions it depends on: design sections, plan steps, issues and PR descriptions. The decision's `Affects` field lists the concepts and items it touches.
- A plan cites every `stated` or `human-confirmed` decision in at least one step ([S7](stages.md#s7-plan)).
- When a decision is reversed, `git grep -l D007` lists exactly what must be reworked. Rework is one issue per affected artifact, citing the reversal; nothing else is touched.

- Steelman: Zero-dependency, embedded, robust file locking, mature ecosystem.
- Downsides: Concurrency limits on multi-writer setups.
## Disagreement

### Option B: PostgreSQL / Neon
Two workers with conflicting results, or a `conflicts-with` pair in scope at S6, go through these steps. No one waits for a human.

- Steelman: Full network concurrency, branching support, scalable analytics.
- Downsides: External network dependency, operational overhead.
1. The orchestrator does not decide. It gives the merged material from both sides to three fresh, read-only subagents in parallel, using the prompts in [templates/prompts/](templates/prompts/): the [reviewer](templates/prompts/reviewer.md) checks the facts, the [critic](templates/prompts/critic.md) attacks each side's reasoning, and the [investigator](templates/prompts/investigator.md) looks for options nobody considered.
2. They decide everything the evidence settles, taking the option best practice would choose when in doubt, and list as toss-ups only choices that are genuinely balanced and costly to reverse.
3. The orchestrator files each decision as a record with `Source: agent-preliminary` and `Status: preliminary`. Work continues on the preliminary choice at once; toss-ups go to [human review](#human-review).
4. Challenge pass: before S6 closes, one fresh subagent with the [challenge-pass prompt](templates/prompts/challenge-pass.md) asks of every decision whether its options were too narrow. Each decision it flags is reopened with the investigator prompt, and the outcome is a dated line under Choice.

## Choice & Rationale
## Human review

Option A (SQLite). The platform requires self-contained offline execution; network DB introduces unnecessary latency for local nodes.
`human-review.md` ([template](templates/human-review.md)) is regenerated from the decision records whenever one changes.

## Consequential Human Review Items

None; standard embedded default.
```

## 2. Source Attribution & Promotion Rules

- **`stated`**: Explicitly commanded by the user in the transcript.
- **`inferred`**: Deduced logically from stated requirements or existing codebase patterns.
- **`agent-preliminary`**: Decided autonomously by a subagent or reviewer to avoid stalling progress.
- **`human-confirmed`**: Explicitly approved by the human maintainer.

**Promotion Invariant**: Downstream automated agents may never promote an `agent-preliminary` decision to `human-confirmed`. Only explicit human interaction updates this field.

## 3. Disagreement Protocol

When two concept researchers or subagents arrive at conflicting recommendations or mutually exclusive designs:

1. **Do Not Stall**: The orchestrator does not halt work waiting for user arbitration.
2. **Launch Reviewer & Critic Subagents**: The orchestrator dispatches read-only reviewer and critic subagents (using `planning/workflow/templates/prompts/reviewer.md` and `critic.md`), providing the full merged context from both workers.
3. **Analyze and Decide**: The critic identifies obvious decisions where one option clearly aligns with repository invariants. The orchestrator adopts the most standard, reversible option as `agent-preliminary`.
4. **Log Consequential Items**: If the decision represents an irreversible architectural fork with meaningful trade-offs, it is recorded in `human-review.md`. Work proceeds on the preliminary assumption.

## 4. The Challenge Pass

Before concluding Stage 6 (Design), the orchestrator launches a fresh-context investigator subagent to inspect all decisions. The investigator specifically checks:

- Were the options framed too narrowly?
- Was an obvious third alternative missed?
- Were the downsides of the chosen option understated?

If a decision is found to have been artificially constrained, it is reopened with an investigator subagent before final plan handoff.

## 5. Traceable Reversal

Because every decision record lists the concepts and files it affects (`Affects: C001, C004`), if a human maintainer reverses a decision (e.g. changing D001 from SQLite to PostgreSQL):

```sh
git grep -l "D001"
```

immediately identifies the exact set of documents, plans, and code files that require rework, avoiding uncoordinated drift.
- Minimal: list only preliminary decisions whose options are genuinely balanced and whose wrong choice would be costly to reverse. Obvious decisions are made and recorded, not listed. "None" is a valid list.
- Batched: one list for the package, never questions one at a time.
- Ranked by effect, most consequential first.
- Defaults: each item names the choice already in effect, the alternatives and the cost of reversing.
- Never re-ask what the transcript states or a `stated` or `human-confirmed` decision already answers.
- Nothing waits on the answers. A reversal starts rework scoped as in [Coverage](#coverage).
Loading
Loading