# Waymarq REST API (v1)

This API lets an external agent — typically an AI coding assistant in its own session — populate
and maintain a project in Waymarq directly, without a human re-typing anything by hand. That covers
both halves of a project's life: turning a spec document into a plan, and then working against that
plan as it's built. An agent joining a project that's **already** planned should start at
[Joining an existing project](#joining-an-existing-project) rather than the creation workflow.
Waymarq does **not** do any of its own reasoning for this flow: the
calling agent reads the spec, decides on phases/tasks/estimates/sub-specs, and writes fully-formed
data to these endpoints. (Waymarq's separate AI-provider integration — Settings → AI — is a
different feature: that one calls out to an LLM *from inside* Waymarq to generate a breakdown.
This API is the reverse direction.)

## Authentication

Every request needs a Bearer token, generated from **Settings → API tokens** in the Waymarq UI.
A token acts as the user who created it, and can never do more than that user can already do —
the same tenant scoping and the same read-only viewer restriction apply. On top of that, each
token carries **abilities** that narrow it further.

```
Authorization: Bearer <token>
Accept: application/json
```

Tokens are shown once at creation time and can be revoked at any time from the same settings page.

### Abilities

| Ability | Covers |
|---|---|
| `read` | Every `GET`. |
| `write` | `POST`, `PATCH`, `PUT` — creating and updating. |
| `delete` | `DELETE`. Separate from `write` because it is the one that loses data: deleting a phase takes every task in it, with their comments, checklists, time logs and history. |
| `commercial` | **Additionally** required for anything about money — quotes, opportunities, work orders, statements, payment terms, and the pipeline, profitability and time-log reports. |

The two axes multiply rather than nest. Reading a statement needs `read` **and** `commercial`;
issuing one needs `write` **and** `commercial`. A token holding `read` and `write` but not
`commercial` can plan and run a project and cannot see what it is worth.

**A token without `commercial` also gets a filtered project payload** — `pricing_model`,
`fixed_fee_amount`, `hourly_rate` and `payment_terms` are absent from `GET /projects` and
`GET /projects/{project}`. A project is its own pricing record, so gating only the budget
endpoints would have handed the fee over with the plan.

**Abilities are fixed when a token is created.** Widening one silently would defeat the point, and
narrowing one would break whatever is already using it; issue a new token and revoke the old.

Missing one gets `403` naming what was needed, rather than a bare "forbidden" that leaves you
guessing between a permissions problem, a role problem and a wrong-organisation problem:

```json
{
  "message": "Your API token does not have the \"commercial\" ability. ...",
  "missing_ability": "commercial",
  "required_abilities": ["read", "commercial"]
}
```

### Personal or organisation tokens

A token from **Settings → API tokens** belongs to you: it acts as you, and it is deleted with your
account. Right for a script you run; wrong for anything a team depends on, which would stop working
the day you left.

**Organisation tokens** (Organisation settings → API, owner/admin only) belong to the organisation
instead. They survive any individual leaving, which is what you want for a CI job, an MCP
connection, or an accounting sync. They act as the organisation rather than as a person, so activity
shows against it by name.

There is deliberately no full-access organisation token. A personal one holding it can do no more
than you already could; an organisation one would be a permanent admin credential with nobody's name
against it.

**If you are setting up a coding agent, `read` + `write` is the right choice** — it can plan work,
move tasks, comment and log time, and it cannot delete a project or read a client's billing.
Tokens issued before abilities existed hold Sanctum's wildcard and are unaffected.

### Which organisation a token acts on

A token is bound to the organisation it was created in, and stays there. It does **not** follow
whichever organisation its owner happens to be viewing in the browser — switching organisation on
the website has no effect on what a token can see.

If you belong to more than one organisation and want a single token to reach another, name it
explicitly:

```
X-Waymarq-Organisation: 3
```

The header only selects between organisations the token's owner is a member of; anything else
returns `403`. Organisation ids are on `GET /projects` responses, or in the URL when you view an
organisation's settings.

One exception: tokens created before this binding existed have no recorded organisation, and fall
back to the owner's current one — the old behaviour. Send the header, or issue a fresh token, to
pin them down.

## Base URL

```
https://<your-domain>/api/v1
```

## Two ways in

**Straight to a project** (the original flow — you already know the work is happening): start at
step 1 below.

**Through the CRM** (the work is still a pitch): create a client, add an opportunity, quote it, and
send the quote. When the client accepts the no-login link — or you move the opportunity to `won`
yourself — the project is **created for you**, prefilled from the opportunity, and you carry on
from step 2 below. See [Clients](#clients), [Opportunities](#opportunities) and [Quotes](#quotes).

**Through the support desk** (the work is a client request rather than a plan): tickets arrive on
their own through a public intake link, and accepting one creates a task on a backlog phase. See
[Support desk](#support-desk).

**Joining work that's already planned** (the phases and tasks exist — written by Waymarq's own AI,
by an earlier agent session, or by a human): don't start at step 1. Read
[Joining an existing project](#joining-an-existing-project) below, then live at step 7.

## Binding a repository to a project

A token tells you *who* you are. It doesn't tell you *which project this checkout is*, and that is
the thing most likely to be missing when you arrive: the project id was in a prompt somebody pasted
into a session that has since ended.

The answer is a `.waymarq.json` committed to the repository root:

```json
{
  "version": 1,
  "project_id": 6,
  "api_base": "https://waymarq.co.uk/api/v1",
  "task_prefix": "W"
}
```

| Field | |
|---|---|
| `version` | Format version. `1` today; a reader should refuse a version it doesn't know rather than guess. |
| `project_id` | The project this repository's work belongs to. |
| `api_base` | Where to send requests. Present so a self-hosted or staging instance needs no other configuration. |
| `task_prefix` | The project's task-code prefix (`W` → `W-127`, and `PH-W-1` for phases). Lets a git hook or CLI check a branch name locally, with no network call. |

**The token is deliberately not in this file.** The file is committed; a credential must not be.
Read it from the `WAYMARQ_API_TOKEN` environment variable — one name, so a tool cannot be pointed
at the wrong one.

**Resolution order** for anything reading this: an explicit flag or argument, then `.waymarq.json`
walking up from the working directory, then the environment. Nearest wins, so a subdirectory can
override the repository it sits in — a monorepo holding two projects is a real case.

**If the file isn't there and you just created the project, write it and commit it.** You can
download the exact file for an existing project from the app (Organisation settings → API → Import
guide), build it from the `POST /projects` response (which carries both `id` and `task_prefix`), or
run `npx @waymarq/cli init`.

### Telling the next agent

`.waymarq.json` says *which* project. Two more files say *how to work with it*, so the next session
— or the next person's agent — doesn't start from nothing:

- **`AGENTS.md`** in the repository root, read by Codex, Cursor, Zed, Amp and Copilot.
- **`.claude/skills/waymarq/SKILL.md`**, which Claude Code loads only when the work is actually
  about Waymarq rather than carrying it in every session.

Both are generated from the project, so they stay right as the ways of connecting change — a
hand-written copy would still be describing whatever existed when it was written.

**`GET /projects/{project}/agent-files`** returns all three, each with the path it belongs at:

```json
{ "files": [ { "path": "AGENTS.md", "contents": "# Working in this repository\n..." } ] }
```

Write them verbatim rather than composing your own. `npx @waymarq/cli init` does exactly this.
Neither file contains a token, and neither should: they are committed.

### Other ways in

This document is the REST API. There are three siblings, and one of them may suit you better:

- **[MCP server](https://waymarq.co.uk/mcp-docs)** — Waymarq as a tool your AI assistant uses
  directly. Nine tools, a URL and a token, nothing to install. Best when a person is talking to an
  assistant and wants it to know about their work.
- **The CLI**, below — a command, for anything with a shell.
- **[Webhooks](https://waymarq.co.uk/webhook-docs)** — Waymarq telling you when something happens,
  rather than you asking.

They compose, and they all go through the same services, so they agree with each other.

### The CLI

`@waymarq/cli` is a thin wrapper over these endpoints, for when shelling out is easier than making
HTTP calls — and for CI, git hooks and people at a terminal. No dependencies, Node 18.17+.

```bash
npx @waymarq/cli init            # write .waymarq.json
npx @waymarq/cli next            # what to pick up
npx @waymarq/cli start W-127
npx @waymarq/cli log W-127 "1h 30m" --note "Middleware and tests"
npx @waymarq/cli done W-127
```

`--json` works on every command and is what a script should parse; the human output is free to
change. Failures exit non-zero with the message from here on stderr. The CLI holds no rules of its
own — everything it knows it asked this API for.

Keep it small. Everything else — the project's name, its client, its status — the API will answer
for you, and a committed copy of server state is a copy that goes stale and then gets believed.

## Joining an existing project

Most of this document is about turning a spec into a project. This section is the other case: the
plan already exists and you're picking up work against it. It is a different job, and following the
creation workflow here would have you write a second breakdown on top of the first.

1. **Read the whole project in one call.** `GET /projects/{project}` returns the project with its
   phases in order and, under each, every task with its status, dates, dependencies, size estimate
   and full `markdown_spec`. That last field is the point — it holds the detail the plan was built
   from, so you should not need the original spec document to start working.
   **Subtasks come back in the same flat list as their parents**, distinguished by a non-null
   `parent_task_id`. Filter on it before you count anything, or you'll double-count.
   **`context_entries` comes back at the top — read it first.** It is the project's decision log:
   the cross-cutting decisions and standing constraints behind the plan ("auth is Sanctum, don't
   re-open", "the client descoped reporting"), the things you should not re-decide. A task spec
   tells you *what* to build; the context tells you the *why* and the rules that span every task.
2. **Report what you found before changing anything.** The phases, the task count by status, what's
   in progress, what's blocked on an unfinished prerequisite, and anything with no estimate or no
   dates. If the plan disagrees with the actual state of the code — work already done but still
   marked `not_started`, a task describing something that got built differently — say so rather
   than silently reconciling it. The plan is what a project manager is showing their client, and a
   quiet correction is worse than a flagged discrepancy.
3. **Then work step 7 below**, which is the maintenance vocabulary: status transitions, comments,
   time logs, and general field updates. When you make a decision that spans the project rather than
   one task — a stack choice, a changed constraint, something descoped — record it with `POST
   /projects/{project}/context` so the next session inherits it instead of re-deciding it. A note
   about one specific task is a comment on that task, not a context entry.
4. **If genuinely new work appears**, add it the same way the plan was built — `POST
   /phases/{phase}/tasks` (or `POST /tasks/{task}/subtasks`) with a real `markdown_spec` and
   `estimated_minutes` — then call `POST /projects/{project}/schedule` so the new tasks get dates.
   **Preview with `?dry_run=1` first.** That endpoint rebuilds the dates for the *whole* project
   from estimates, not just the tasks you added — there is no undo, and the Gantt it rewrites is
   something clients get shown. Any date set by hand (a fixed meeting, a deadline someone typed in)
   is re-derived along with everything else, so check the response's `moved` count and each task's
   `previous_start_date`/`previous_due_date` before committing, and flag anything that jumped. Don't
   absorb unplanned work into an unrelated task, and don't skip it.

Three things need a human's agreement rather than your judgement: changing the **project's** status
(`PATCH /projects/{project}/status`), deleting or restructuring existing phases and tasks, and
inventing an estimate you can't actually justify — `null` is a real answer and a confident guess is
worse than a gap.

## The intended workflow

0. **Ask your questions first.** Before writing a single record, read the spec and go back to the
   person with your clarifying questions — unstated scope boundaries, which integrations are
   actually in play, who the users are, what "done" means for the vague parts. Then show them the
   phase list you propose and get agreement. Five questions answered now beats forty tasks
   corrected later, and a plan built on a guess is worse than no plan, because it looks decided.
   If something is still unresolved after asking, say so in the task's `markdown_spec` rather than
   inventing an answer. Nothing in this API is a substitute for that conversation.

1. **Create the project.** `POST /projects` with basics (name, dates, client). The project is
   automatically flagged `imported_via_api: true`, which shows a small "API-imported" badge on the
   project overview in the UI.
   Check `GET /clients` and link the right one with `client_id` — and if the client doesn't exist
   yet, ask before creating it rather than guessing a company into existence.
   **Leave `status` alone.** It defaults to `planning`, which is where an imported project should
   stay until a human has looked at it — see step 7.
   *(Skip this if you came via the CRM — winning an opportunity already created it.)*
2. **Create phases.** `POST /projects/{project}/phases`, one call per phase, in the order they
   should appear.
3. **Create tasks under each phase.** `POST /phases/{phase}/tasks`. For each task, in addition to
   the usual fields (title, dates, assignee), send:
   - `markdown_spec` — the **full specification** for this task: the sub-spec chunk from the
     original document, detailed enough that a developer never needs to go back to the source
     spec. This renders as a prominent "Full specification" section in the task view (a few
     paragraphs for a small task, a few pages for a large one — whatever the task actually needs).
   - `llm_test_plan` — a set of concrete, checkable instructions an AI agent can run against the
     finished code to verify the task meets spec. This is separate from the human checklist
     test-plan feature already in Waymarq; it shows as its own "Test plan (for AI)" section.
   - `estimated_tokens` — your anticipated token cost for the task, an integer. Shown next to the
     existing size estimate field, for planning/tracking purposes only (no billing/budget math is
     built on it yet).
   - `size_estimate` — a rough t-shirt size, free text but `"XS"`/`"S"`/`"M"`/`"L"`/`"XL"` is what
     the UI expects and what makes a board scannable at a glance. Cheap to send and easy to skip;
     send it anyway. It answers "how big is this" for a human in a way `estimated_minutes` doesn't —
     a two-day task can be trivial or fiddly.
   - `estimated_minutes` — **how the schedule gets built.** Effort in MINUTES, not days: a working day is 480, so a six-hour job is `360`. Minutes because a whole number of days could not say "half a day", so every small task rounded up to one and plans came out roughly three times too long.
     Waymarq derives start and due dates from these estimates plus the dependency order, honouring
     the organisation's working week and holidays, so you should normally send `estimated_minutes`
     and let it work out the calendar rather than sending dates yourself. A task with no estimate
     is deliberately left undated rather than given invented dates. If you genuinely cannot judge
     a task, send `null` — that is a real answer, and a project manager can fill the gap in later.
   - `depends_on_task_ids` — an array of task IDs already created in this project, if this task is
     blocked on others. Set it only for a genuine, *immediate* prerequisite — the one thing that
     directly has to finish first — not everything this task is eventually built on. A task near
     the end of a project can trace back to nearly everything before it if you follow the chain far
     enough; naming that whole chain explicitly (rather than just the task right before it) is what
     turns the Gantt chart and roadmap into a mess of lines crossing the whole project. Waymarq
     already drops a genuinely redundant edge (A→C, when A→B and B→C already exist), but it can't
     invent a shorter path you never declared — if a task only makes sense after some foundational
     work from several phases back, depend on whatever comes directly before it in that same chain
     (which already reaches the foundation transitively) rather than wiring the two together
     directly. **A dependency that turns out to already be implied by another one in the same
     request is dropped rather than kept** — and reported back in the response's
     `pruned_dependencies` array (`{id, code, title, reason}` per dropped id), so a shorter
     `dependencies` list than you sent reads as intentional rather than a bug. This applies to
     `POST /phases/{phase}/tasks`, `POST /tasks/{task}/subtasks`, and `PATCH /tasks/{task}`.

     Note the field names differ by direction: you **write** `depends_on_task_ids` (an array of
     ints) and **read** `dependencies` (an array of objects, each with `id`, `title` and `status`).
     Reading `depends_on_task_ids` off a `GET` returns nothing — that isn't a failed write.

   To reach the **same depth the in-app AI breakdown produces**, also attach a **test plan** —
   `POST /tasks/{task}/checklists` with `kind: "test_plan"` and an array of concrete, checkable
   verification steps. This is the human-facing checklist test plan (shown in the task modal and
   rolled into progress), distinct from the `llm_test_plan` string above. A `general` checklist is
   available the same way for ordinary sub-steps.

   Checklists are worth more than they look on a **large** task, and are routinely skipped on
   exactly the tasks that need them. A big task with no checklist sits at 0% for a week and tells
   nobody anything; the same task with six ticked steps shows real movement, and gives a human
   something to hand over mid-flight. Add one wherever a task is genuinely a sequence of steps.

   If a task genuinely contains several independently-trackable units of work — different
   assignees, different completion states — create it as a parent with subtasks instead of one
   task carrying all the detail (`POST /tasks/{task}/subtasks`, see below). A task that's just
   larger in scope but still one continuous piece of work should stay a single task with a longer
   `markdown_spec`; don't split for the sake of splitting.
4. **Upload the source spec file.** `POST /projects/{project}/files` (multipart). It's
   automatically tagged as a `spec`-type file and gets an auto-posted comment noting it was used
   as the source for the breakdown — so a human opening the Files page later can see exactly where
   the plan came from, and the goal is that they never need to re-read the original document.
5. **Build the schedule.** `POST /projects/{project}/schedule`, once, after every phase and task
   exists. This is the step that turns your `estimated_minutes` plus the dependency order into real
   start and due dates, honouring the organisation's working week and holidays. **Until you call
   it, an imported project has no dates at all and nothing appears on the Gantt chart** — the
   in-app AI breakdown gets this for free from its batch-completion hook, but an external agent
   has no equivalent and has to say when it's finished writing. The response reports `scheduled`
   and `unestimated` counts; pass both back to the person, since the second is the list of things
   nobody has sized yet.
6. **Hand back and ask before activating.** Summarise what you created, what you were unsure of,
   and anything you couldn't estimate. Then **ask whether to activate the project** rather than
   doing it yourself — activating turns provisional dates into commitments and starts schedule
   tracking, which is a project manager's call, not an importer's. If they say yes:
   `PATCH /projects/{project}/status` with `{"status": "active"}`. Note the general
   `PATCH /projects/{project}` rejects a `status` key for the same reason the task equivalent
   does — going live stamps a date that reporting is built on.
7. **As development proceeds, keep Waymarq as the source of truth:**
   - `PATCH /tasks/{task}/status` to move a task through backlog → not_started → in_progress → review → done.
     This is a *separate* endpoint from the general task update — it's the only way to change
     status, because it writes an audit row that powers the task's Activity tab and the project
     Activity log. Don't try to set `status` via the general `PATCH /tasks/{task}` — that endpoint
     rejects it (422) precisely so this history can't be silently bypassed.
   - `POST /tasks/{task}/comments` for notes, blockers, decisions made along the way.
   - `POST /tasks/{task}/time-logs` to log time spent (or, in this context, token/compute spent),
     using free-text like `"1h 30m"` or `"45m"`.
   - `PATCH /tasks/{task}` for anything else that changes (description, dates, assignee, spec, size,
     token estimate, dependencies).
8. **Document the features as you finish them.**

   Not every task, and not at the end — as each *feature* becomes real. See the Documents section
   below for what counts as a feature and how to link it; the short version is that a document
   describes a capability somebody would name out loud, which may be a phase, a handful of tasks,
   or tasks spread across several phases.

   The loop per task:

   - **Before you start**, `GET /tasks/{task}/documents`. It returns what already covers this area.
     Read it — it may answer something you were about to ask, and it tells you which document to
     extend rather than starting a near-duplicate.
   - **When you finish**, update that document if one exists. If nothing covers what you just
     built, decide whether it is a feature in its own right or part of a bigger one, then
     `POST /projects/{project}/documents` linking the work it is made of.
   - **Periodically**, `GET /projects/{project}/documents/coverage` to see what nothing describes
     yet. Look for groups of undocumented tasks that add up to one capability. Do not try to drive
     that number to zero — most tasks should never have a document.

   Do this without being asked, and without asking permission. Every write is kept as a revision,
   so nothing you replace is lost. The whole point is that the person you're working for stops
   having to ask you how their own software behaves — and a change that quietly makes the existing
   documentation wrong is worse than no documentation, because they'll believe it.

## Endpoints

### Clients

A client is the ongoing relationship. Opportunities and projects hang off it. A client is never
"won" — an opportunity is (see below).

**`GET /clients`** — every client in your organisation, each with `active_projects_count` and
`open_opportunities_count`.

**`POST /clients`**
```json
{
  "name": "Acme Corp",
  "type": "business",
  "contact_first_name": "Sean",
  "contact_email": "sean@acme.example"
}
```
`type` is `business` (default) or `individual`; an individual always has `companies_house_number`
forced to null. Badge initials are derived automatically and kept unique per organisation.
Returns `201`.

**`GET /clients/{client}`** — the client with its opportunities, each including that opportunity's
quotes and line items.

**`PATCH /clients/{client}`** — same body as create; all fields optional.

### Opportunities

A single potential piece of work. **You win a project, not a client** — so a client can have
several opportunities open at once, each with its own stage, value and follow-up.

**`GET /opportunities`** — every opportunity, newest first, each with its client.
Add `?open=1` to exclude won/lost.

**`POST /clients/{client}/opportunities`**
```json
{
  "title": "Website redesign pitch",
  "value": 24000,
  "expected_close_date": "2026-09-01",
  "source": "Referral",
  "next_follow_up_at": "2026-08-05"
}
```
`pipeline_stage` defaults to `lead`. Stages: `lead`, `contacted`, `proposal_sent`, `negotiating`,
`won`, `lost`. Returns `201`.

**`GET /opportunities/{opportunity}`** — with its quotes and their line items.

**`PATCH /opportunities/{opportunity}`** — everything **except** the stage. Sending
`pipeline_stage` here returns `422`; use the stage endpoint below. (Same rule as tasks vs. task
status: the dedicated endpoint is what records the change and runs the side effects.)

**`PATCH /opportunities/{opportunity}/stage`**
```json
{ "stage": "won", "note": "Client confirmed on the call" }
```
The only way to move an opportunity through the pipeline. It:
- logs the change on the client's activity timeline (with your optional `note`),
- clears `next_follow_up_at` on a terminal stage,
- and on `won`, **automatically creates the linked project**, prefilled from the opportunity's
  title, client and value (as a fixed fee).

Returns `{ "opportunity": {...}, "created_project": {...} | null }` — `created_project` is only
present when that call caused the win. Winning an already-won opportunity never creates a second
project.

### Quotes

A priced proposal against one opportunity. An accepted quote wins its opportunity, which in turn
creates the project — so quoting is the natural way to start work through this API.

**`POST /opportunities/{opportunity}/quotes`**
```json
{
  "expiry_date": "2026-09-01",
  "notes": "Fixed fee. 50% deposit to start.",
  "line_items": [
    { "description": "Secure client portal", "quantity": 1, "unit_price": 14000 },
    { "description": "Data migration", "quantity": 1, "unit_price": 2000 }
  ]
}
```
Line items are the whole quote — `subtotal`, `tax` (snapshotted from your organisation's VAT rate
at creation) and `total` are computed from them, never sent. The quote is created as a `draft` and
numbered automatically (`Q-0001`, `Q-0002`, …). Returns `201`.

**`GET /quotes/{quote}`** — with line items, computed totals, and `public_url` once sent.

**`PATCH /quotes/{quote}`** — same body; **replaces** all line items with what you send. Only a
`draft` can be edited — a sent/accepted/declined quote returns `422`, since it's a record of what
the client was actually shown.

**`POST /quotes/{quote}/send`** — locks the quote and mints `public_url`: a no-login link you give
the client. Them accepting it wins the opportunity and creates the project, with no further API
call from you. Requires at least one line item.

**Acceptance is attributed.** When a client accepts through the public link they type their full
name (and optionally an email), and we record it with their IP address and the timestamp. Those
come back on the quote as `accepted_by_name`, `accepted_by_email`, `accepted_ip` and `accepted_at`
— worth reading if you're syncing agreements anywhere, since it's the only record of *who*
committed.

### Payments

The payment schedule models what's owed and when; these endpoints add whether it arrived. Together
they're the seam an accounting integration reconciles against — Waymarq stops at "here's what
should be invoiced and whether it's settled", and the invoice document itself belongs in your
accounting package. Commercial data, so viewer-role tokens get `403`.

**`GET /projects/{project}/payment-terms`** — every term with its resolved money amount, whether
it's paid, and the project totals: `received_total`, `outstanding_total`, `overdue_total`.

**`PATCH /payment-terms/{paymentTerm}/payment`**
```json
{ "paid": true, "amount_received": 5000, "paid_at": "2026-07-19", "payment_reference": "BACS 4471" }
```
`amount_received` is stored rather than assumed equal to the scheduled amount, so a part payment is
representable. `{"paid": false}` clears the record entirely — amount and reference included, rather
than leaving a stale figure on a term that's unpaid again. Recording a payment fires the
`payment.received` webhook.

### Projects

**`GET /projects`** — list every project in your tenant.

**`POST /projects`**
```json
{
  "name": "Website Redesign",
  "client_id": 4,
  "status": "planning",
  "description": "...",
  "start_date": "2026-07-20",
  "deadline": "2026-09-01",
  "default_billable_status": "billable"
}
```
`status` defaults to `planning` if omitted. `start_date` is required; `deadline` is optional.
Returns `201` with the created project.

**`default_billable_status`** is what tasks on this project are billed as unless told otherwise —
`billable`, `internal` or `non_billable`. Set `internal` or `non_billable` for anything nobody is
invoiced for. It is inherited at task creation, so setting it once here beats remembering it forty
times, and getting it wrong means a plan that looks chargeable and an error that only shows up in
a report about money.

Pass **`template_id`** as well and the project is created from that saved shape: the template's
stages and tasks are laid out from `start_date`, one piece at a time, each starting the working day
after the last finishes and skipping the organisation's non-working days. It produces exactly what
a person would get from the same template, because it runs the same code.

**`GET /project-templates`** — the organisation's saved project shapes, each with its stages, the
tasks inside them, and how long each task takes in working days. Use this to find a `template_id`,
and prefer it over inventing a process the organisation has already described:

```json
[
  {
    "id": 3,
    "name": "Report design — standard",
    "phase_count": 3,
    "task_count": 9,
    "total_working_days": 24,
    "phases": [
      { "name": "Preparation", "tasks": [{ "title": "Briefing meeting", "length_days": 2, "waiting_on": null }] }
    ]
  }
]
```

**`GET /projects/{project}`** — the project with its `context_entries` (the decision log, at the
top), client, phases, and tasks (including each task's dependencies).

**`PATCH /projects/{project}`** — update `name`, `client_id`, `description`, `start_date`,
`deadline` or `scheduling_concurrency`. Every field optional; only send what changed.

`scheduling_concurrency` is how many tasks may run at once when the schedule is built, and it is
worth setting **before** you call the schedule endpoint. Dependencies say what *can't* overlap; this
says what *doesn't*, despite being allowed to — one person cannot work five unrelated tasks at once,
so a correctly-sparse dependency graph will otherwise start everything on day one and report a
delivery date nobody could hit. Send `1` for a sole trader, or `null` to inherit the organisation
default.

Sending `status` here returns `422` pointing at the endpoint below — the same guard the task
equivalent has, and for the same reason: the transition stamps dates that reporting is built on,
so a general field write must not be able to trigger it silently.

**`PATCH /projects/{project}/status`**
```json
{ "status": "active" }
```
One of `planning`, `active`, `on_hold`, `completed`, `cancelled`, `archived`. Records when the
project first went live and when it completed (and clears the completion stamp if it reopens).

**Ask the person before activating a project you have just imported.** It turns provisional dates
into commitments and starts schedule tracking — their decision, not yours.

**`cancelled` means the work is not going ahead** — quoted or planned and then dropped, as opposed
to `completed` (delivered) or `archived` (filed away, whatever the outcome). Send a
`cancellation_reason` with it: recording *why* is the entire reason this is a status rather than an
archive, since the pattern across cancellations is what tells someone how much planned work never
happens and what kills it. Nothing is deleted, the project stops being chased, and reviving it
clears both the stamp and the reason.

```json
{ "status": "cancelled", "cancellation_reason": "Client went with another supplier on price." }
```

Only `active` projects are chased. A project in `planning` has proposals rather than commitments,
and `on_hold`, `completed` and `cancelled` are all deliberately off the chase — so none of them
report overdue tasks or appear as behind schedule.

**`POST /projects/{project}/schedule`**
```json
{
  "dry_run": false,
  "scheduled": 31,
  "unestimated": 4,
  "moved": 27,
  "tasks": [
    {
      "id": 412, "code": "WR-3", "title": "Wireframes",
      "previous_start_date": "2026-07-18", "previous_due_date": "2026-07-22",
      "start_date": "2026-07-20", "due_date": "2026-07-24"
    }
  ]
}
```
Turns `estimated_minutes` plus the dependency order into real start and due dates, honouring the
organisation's working week and observed holidays, then rolls each phase's span up from its tasks.
No body. Call it **once, after all phases and tasks exist** — not per task; it plans the whole
project, and running it mid-import just recomputes an incomplete graph.

`moved` is how many tasks had a date changed, and every task carries its `previous_start_date`/
`previous_due_date` alongside the new ones. This is your blast radius: the endpoint re-derives
*every* date from estimates, so comparing previous against new is how you catch one that jumped
rather than finding out on the Gantt.

**Pin the dates that are commitments rather than calculations.** Set `"dates_locked": true` on a
task and this endpoint works *around* it instead of re-deriving it: its dates are never rewritten,
it never appears in `moved`, it still consumes capacity on the days it occupies, and dependents are
scheduled after it. That is what a client deadline, a contractual milestone, a site visit, or a
meeting recorded as a task needs — those are facts, not estimates. Pin sparingly: every pinned date
is one the scheduler can no longer help you with, and pinning a whole plan produces a chart that
cannot respond to anything changing. A pinned task is exempt from the "no estimate means no dates"
rule below, since the things worth pinning usually have no estimate at all.

**Preview it first with `?dry_run=1`.** That computes the identical plan and returns it in `tasks`
without writing anything. A real run rewrites every date in the project, there is no undo, and the
Gantt chart it rewrites is something clients get shown — so look before you commit, and check the
concurrency setting above if the finish date surprises you.

**A project that is not in `planning` refuses the call with `422`** unless you also send
`force=true`. A planning project's dates are proposals; once work is underway they are commitments
somebody has logged time against and a client has been shown, so rebuilding all of them is rarely
what was meant. `dry_run` is always allowed whatever the status — looking is safe. If you get the
422, preview with `dry_run`, look at `moved` and the per-task diff, and only then decide whether to
force. Often the better answer is to pin the handful of dates that matter and leave the rest alone.

Tasks with no `estimated_minutes` are deliberately left undated rather than given invented dates, and
come back in the `unestimated` count. Report that number to the person: it's precisely the list of
work nobody has sized.

### Project context

The project's decision log: cross-cutting decisions and standing constraints that aren't about one
task. It is the *why* behind the plan — the things a later session should read before planning or
building, and should not re-decide. It is included at the top of `GET /projects/{project}` as
`context_entries` (newest first); these endpoints read, write and retract it directly.

**`GET /projects/{project}/context`** — the entries, newest first, each with its author.

**`POST /projects/{project}/context`**
```json
{ "body": "Auth is Sanctum, not Passport — decided 12 Aug after the OAuth spike; do not re-open." }
```
Records a decision or constraint, posted as the token's user. Returns `201`. Keep each entry short
and self-contained — this is a record people read, not a running log. Put task-specific notes on the
task with `POST /tasks/{task}/comments` instead; the context log is for what spans the project.

**`DELETE /projects/{project}/context/{entry}`** — retract a mistaken or superseded entry (`204`).
The log is otherwise append-only: entries are never edited in place, so what it records having been
said stays trustworthy.

### Phases

**`POST /projects/{project}/phases`**
```json
{ "name": "Discovery", "description": "...", "start_date": "2026-07-20", "due_date": "2026-07-27" }
```
Phases are appended in call order (position is assigned automatically). Returns `201`.

Phases carry no scheduled/backlog flag. Whether a phase appears on the Gantt timeline is derived: it does once it holds tasks with dates. To park open-ended work — ideas, a running to-do list, anything with no real deadline — give the *tasks* `"status": "backlog"` (see Tasks below). A project can freely mix committed and backlog work in the same phase, or be all one or the other; there's no "project mode" to set.

**`PATCH /phases/{phase}`**
```json
{ "name": "Discovery", "position": 0, "depends_on_phase_ids": [12] }
```
Every field optional. `position` is the 0-based sort order within the project, so this is also how
you reorder. `depends_on_phase_ids` **replaces** the phase's prerequisites rather than adding to
them — ids outside the project are dropped, an edge already implied by another is pruned, and
anything that would form a cycle returns `422`.

Sequencing phases is what stops the scheduler running them concurrently: without it, "Testing after
Build" is a label rather than a constraint, and both phases get planned from the same start date.

**`DELETE /phases/{phase}`** — returns `204`.

**Destructive and not recoverable:** every task in the phase goes with it, along with their
comments, checklists, time logs and history. If you only meant to drop the grouping, move the tasks
to another phase first.

### Tasks

**`POST /phases/{phase}/tasks`**
```json
{
  "title": "Build the auth middleware",
  "description": "Short one-line summary",
  "markdown_spec": "## Full specification\n\n...as much detail as the task needs...",
  "llm_test_plan": "1. Run `php artisan test --filter=Auth`\n2. Confirm...\n3. ...",
  "size_estimate": "M",
  "estimated_tokens": 15000,
  "estimated_minutes": 360,
  "complexity": "standard",
  "priority": "normal",
  "billable_status": "billable",
  "status": "not_started",
  "assignee_id": 3,
  "depends_on_task_ids": [12, 13],
  "position": 0,
  "branch": "feature/auth-middleware",
  "commit_sha": "a1b2c3d4e5f6",
  "pull_request_url": "https://github.com/acme/app/pull/12"
}
```
Only `title` is required. Returns `201` with the created task (dependencies loaded).

**`POST /phases/{phase}/tasks/bulk`** — a whole phase in one call.
```json
{
  "tasks": [
    { "title": "Model the data", "estimated_minutes": 240 },
    { "title": "Build the API", "estimated_minutes": 480, "depends_on_task_ids": ["#0"] },
    { "title": "Build the UI", "estimated_minutes": 480, "depends_on_task_ids": ["#1"] }
  ]
}
```
Each entry takes the same fields as a single create. **Use this whenever you are writing more than
one task.** One at a time costs a round trip each, and issuing those in parallel loses the order —
`position` is otherwise assigned from whichever write lands last, so a plan arrives shuffled.

`position` comes from the array order and does not need setting. An entry may depend on one created
earlier in the same call, written as `"#0"`, `"#1"` — the id does not exist yet when the entry
naming it is written, so an index is the only way to express it. A real id or code still works for
a task that already exists.

All or nothing, up to 100 tasks: one invalid entry rejects the lot with `422` and writes nothing,
so a half-written plan is never left behind. Returns `201` with the tasks in the order given.

`start_date`, `due_date` and `duration_days` are still accepted, but you rarely want them: dates
are derived from `estimated_minutes` and the dependency order, so anything you set by hand is liable
to be recalculated. Send an estimate and let the scheduler place the work.

`dates_locked` (defaults to `false`) is the exception to that. Set it, with real dates, when the
date is a **commitment rather than a calculation** — a client deadline, a contractual milestone, a
site visit, a meeting recorded as a task because there is no meeting entity. The scheduler then
treats the task as a fixed anchor: it works other tasks around it and never rewrites it. Pin
sparingly; see `POST /projects/{project}/schedule` above.

`branch`, `commit_sha` and `pull_request_url` are where the work actually happened, and are shown
on the task page. Set `branch` when you pick the task up and the rest as they exist — they are what
lets somebody read a task and find the code, or read a commit and find what it was for. Plain text
rather than a git integration, so they work with any host and need nothing set up. (If the project
has a repository connected, observed commits appear alongside these; they do not replace each
other.)

`billable_status` defaults to whatever the project's `default_billable_status` says, and to
`"billable"` when the project says nothing. Set the project default rather than every task: on an
internal or personal project, a forty-task plan otherwise arrives looking invoiceable and the
mistake only surfaces in a report about money.

`status` defaults to `"not_started"`. Set `"backlog"` for work that exists but hasn't been
committed to — an idea, a request, something you're capturing rather than planning. Backlog tasks
appear on the board (leftmost column) and the task list, but are excluded from progress percentages,
overdue lists, workload and the client share view, and never appear on the Gantt or roadmap. Prefer
it over inventing a "someday" phase: it's a property of the item, so promoting one later doesn't
force it to move phase.

`complexity` (`"quick"` or `"standard"`, defaults to `null`/standard) is a UI hint only — it
doesn't change how the task is stored or synced, it just tells the app to show a shorter task
modal (no checklists, subtasks, or size/token fields) for genuinely small items.

`priority` (`"low"`, `"normal"`, `"high"` or `"urgent"`, defaults to `"normal"`) is how urgent the
work is — separate from `status`, which is where it has got to, and from being overdue, which is
derived from the due date rather than set. The board only colours `"urgent"` and `"high"`, so
reserve them for work that genuinely is: marking everything is the same as marking nothing. If
you're importing a plan and have no real signal either way, leave it alone — `"normal"` is the
honest answer and the default.

`waiting_on` (`null`, `"client"` or `"third_party"`, with `waiting_on_name` for the latter) marks a
task whose time is somebody else's: the client reviewing a proof, a printer turning a job round. It
stays in the plan — it has dates and can be a prerequisite, so "amends" can follow "client
feedback" — but it is not the organisation's effort: it is left out of the effort and workload
figures, it sits in the Review column while active (asking for `in_progress` lands it in `review`),
and on the client's own page it reads "with you". Use it for the gaps between your own tasks
rather than leaving them as unexplained space in the schedule.

`billable_status`
(`"billable"`, `"internal"`, or `"non_billable"`, defaults to `"billable"`) records what invoicing
should do with the task's logged time — `internal` is your own time (bugs, admin), `non_billable`
is client work you've chosen not to charge (warranty, goodwill). `source` is set to `"api"` for
everything created through this API and isn't settable — `"manual"` means a person typed it into
the UI and `"ai"` means Waymarq's own in-app generation wrote it. It exists so the activity log
can credit the origin honestly: a task you import is shown as coming from the API rather than
attributed to whoever owns the token, which is technically true but hides how the work arrived.

**`GET /tasks/{task}`** — a single task with its dependencies, assignee, (if it's a parent
task) its subtasks, and every checklist with its items in full. Also includes
`subtasks_total`/`subtasks_done` and
`checklist_items_total`/`checklist_items_done`/`test_plan_items_total`/`test_plan_items_done` —
read-only rollup counts the app uses for progress indicators; these aren't part of the write
payload.

The checklist **items** matter here, not just the counts: an item's id is otherwise only ever
returned by the call that created it, so this is how you find what to tick off when you come back to
a task later. See Checklists below.

Also read-only: `created_at`, `completed_at` (set the moment a task is marked `done`, cleared if it's
reopened — not derived from `updated_at`, which moves on any edit) and `age_days` (whole days from
`created_at` to `completed_at`, or to now if it's still open). None of these are part of the write
payload.

**`PATCH /tasks/{task}`** — update any field except `status` (see below). Same shape as create,
all fields optional.

**`PATCH /tasks/{task}/status`**
```json
{ "status": "in_progress", "note": "Optional note about why" }
```
The only way to change status — writes an audit row for the Activity tab/log.

**`PATCH /tasks/{task}/archive`**
```json
{ "archived": true }
```
Archiving puts a task aside without losing it. It leaves every board, list, progress count and
schedule, but stays readable at `GET /tasks/{task}`, stays in search, and keeps whatever time was
already logged against it. Cascades to subtasks. Send `false` to restore.

Its own endpoint rather than a field on `PATCH /tasks/{task}` — the same reason status has one, and
a stronger one here: it cascades, so a general field write must not be able to trigger it. Sending
`archived_at` to the general update returns `422`.

**Use this rather than DELETE for work that simply will not be done.** It's the honest record: the
task existed, it was considered, it was dropped.

**`DELETE /tasks/{task}`** — returns `204`.

**Genuinely destroys it.** Comments, checklists, watchers, attachments, the status history, subtasks
and time logs all go with it, and none of it is recoverable.

Refused with `422` when the task holds time logged against an issued statement — deleting it would
destroy the source of a line a client has already been asked to pay for. Archive those instead.

Note that `GET /projects/{project}` omits archived tasks (it describes the plan, and they're
deliberately not in it), while `GET /tasks/{task}` still returns one directly.

### Subtasks

**`POST /tasks/{task}/subtasks`**
```json
{
  "title": "Add the password-reset endpoint",
  "description": "Short one-line summary",
  "markdown_spec": "...",
  "status": "not_started",
  "assignee_id": 3,
  "start_date": "2026-07-20",
  "due_date": "2026-07-22",
  "depends_on_task_ids": [12]
}
```
Same shape as creating a task, minus phase selection — a subtask always inherits its parent's
phase. Only `title` is required. Returns `201` with the created subtask.

One level of nesting only: `{task}` must itself be a top-level task, not another subtask — calling
this on a subtask returns `422`. Subtasks appear nested under their parent in the task detail view
(not as their own Kanban card or Gantt bar) and roll up into a "N/M subtasks" progress indicator on
the parent, the same way checklists do.

### Files

**`POST /projects/{project}/files`** (multipart/form-data)
```
file: <binary>          # .docx, .pdf, or .txt, max 10MB
version: "v1"            # optional
```
Uploads and tags the file as the project's spec, with an auto-posted comment. Returns `201`.

### Documents

Living documentation — how the delivered thing **behaves**, as opposed to Files, which record what
was **asked for**. A document outlives the tasks that produced it and is meant to be edited.

This is the antidote to being asked the same question repeatedly. If you change how something
works, update the document that describes it in the same session, and the next person — or the next
run of you — reads it instead of asking.

#### What deserves a document

**Document features, not tasks.** This is the single most important thing to get right here, and
the easiest to get wrong: a document per task produces a library nobody can navigate, full of
entries called "Add rate limiting middleware" that no reader would ever search for.

A **feature** is a capability somebody would name out loud — "signing in with a one-time code",
"the client share link", "how invoicing works". It maps onto the work however it happens to map:

| A feature might be… | Link |
|---|---|
| a whole phase, when the phase *is* one coherent capability | `phase_ids: [7]` |
| several tasks inside a phase, when the phase holds three unrelated things | `task_ids: [41, 42, 47]` |
| tasks spread across phases, when a capability was built in stages | `task_ids: [12, 44, 89]` |
| one substantial task, when it genuinely stands alone | `task_ids: [63]` |
| the whole project, for a "how this system fits together" overview | every `phase_ids` |

**What you link is also the level.** There is no separate depth setting: link one task and you have
written about one thing; link every phase and you have written an overview. Choose the linking that
matches the document you actually wrote.

Good tests for whether something deserves its own document:

- Would somebody ask "how does X work?" using those words? If not, it is probably part of a bigger
  feature, not a feature.
- Could you write three useful paragraphs that are not just the task's spec reworded? If the answer
  is no, extend an existing document instead.
- Is it internal plumbing — a refactor, a config change, a dependency bump, a bug fix? Then no.
  It changes how the code is built, not how the product behaves.

When in doubt, **extend rather than create**. One document covering sign-in that mentions SMS codes
beats two documents, one of which the reader will never find.

#### Who it is for

`audience` is who the document is written **for**, and it genuinely changes what belongs in it:

- `user_guide` — someone using the thing. What it does, how to do it, in the words that appear in
  the interface. No file names, no table names, no implementation detail.
- `technical` — someone maintaining it. How the pieces fit, what was decided and why, what would
  surprise a newcomer.
- `reference` — a lookup, not a narrative. Options, fields, values, limits. Tables over prose.

A feature can warrant both a user guide and technical notes. That is two documents linked to the
same work, not one document trying to serve both readers — they want near-opposite things.

Omit `audience` and the project's own default is used.

#### Finding what to write

**`GET /projects/{project}/documents/coverage`** — the project's work with coverage against it.

```json
{
  "summary": { "documents": 3, "tasks_total": 41, "tasks_covered": 22, "tasks_undocumented": 19 },
  "phases": [
    {
      "id": 7, "reference": "PH-WR-3", "name": "Build",
      "documents": [{ "id": 2, "title": "Signing in with a one-time code", "audience": "user_guide" }],
      "undocumented_tasks": [
        { "id": 51, "reference": "WR-19", "title": "Password reset by email", "status": "done" }
      ]
    }
  ]
}
```

A task counts as covered when a document links it, or links its phase. Read `undocumented_tasks`
looking for **groups that add up to a feature**, not as a checklist to clear — most of those tasks
should never get a document, and driving this number to zero would produce exactly the unusable
library described above.

**`GET /tasks/{task}/documents`** — every document covering this task, directly or via its phase.

Start here when you pick up a task. It tells you what already documents this area, so you extend
the right document rather than starting a near-duplicate beside it.

**`GET /projects/{project}/documents`** — the library. Optional `?audience=` filter. Bodies are
omitted; fetch one to read it.

#### Reading and writing

**`GET /documents/{document}`** — the full document, with its markdown `body` and the phases and
tasks it was written from.

`is_stale` is `true` when the linked work has changed since the document was last brought into line
with it. Treat it as "check whether this is still true", not as an instruction to rewrite.

**`POST /projects/{project}/documents`**
```json
{
  "title": "Signing in with a one-time code",
  "body": "## Asking for a code\n\nEnter your email and a six-digit code arrives...",
  "summary": "The passwordless sign-in flow",
  "audience": "user_guide",
  "task_ids": [41, 42, 47],
  "phase_ids": []
}
```

Link the work the feature is made of. That is what lets the document show what produced it, and
what lets Waymarq flag it later when that work moves. Ids outside the project are ignored rather
than rejected.

Do not open `body` with a top-level `#` heading — the title carries it. Write in the present tense
about how the thing works. A document that reads like a progress report ("we implemented…", "this
task added…") is one nobody comes back to.

**`PATCH /documents/{document}`** — replaces whichever fields you send, leaves the rest alone.
Sending `task_ids`/`phase_ids` re-syncs the links, so a feature that grew can pick up the new work.

**Write directly. Do not ask first.** The previous version is kept as a revision automatically,
attributed to the API, so nothing you replace is lost and a human can restore it in one click. Set
`note` to say why you changed it — that shows in the document's history, and it is how someone
reading it later understands what prompted the edit.

**`DELETE /documents/{document}`** — removes the document and its history. The work it describes is
untouched.

### Comments & time logs

**`GET /tasks/{task}/comments`** — every comment on the task, oldest first, each with its author.

Comments are where decisions get recorded, so this is how a later session finds out what was already
settled and why. If you are resuming work someone (or some earlier run) started, read these before
changing anything.

**`POST /tasks/{task}/comments`**
```json
{ "body": "Blocked on the payments provider sandbox credentials." }
```

**`POST /tasks/{task}/time-logs`**
```json
{ "time": "1h 30m", "note": "Implemented the middleware, wrote tests", "logged_at": "2026-07-21" }
```
`time` accepts free text like `"1d 2h 15m"`, `"5.5h"`, or `"45m"` (a day = 8 working hours).
`logged_at` defaults to today if omitted.

### Attachments

Files on a task — a screenshot of the bug, the log, the document it came from.

**`POST /tasks/{task}/attachments`** — `multipart/form-data`, one `file` per request. Images, video,
PDFs, documents, logs and zips, up to 20MB each.

```bash
curl -X POST https://waymarq.co.uk/api/v1/tasks/128/attachments \
  -H "Authorization: Bearer $WAYMARQ_API_TOKEN" \
  -F "file=@checkout-error.png"
```

Several files means several calls. That is deliberate rather than a limitation: a partial failure
then means "the first two landed", which you can see and retry, instead of an unpredictable subset
of one batch.

There is no way to create a task and attach files in one request. Create it, then attach — the CLI's
`waymarq attach` does exactly that and reads as one action.

**`GET /tasks/{task}/attachments`** — metadata only, each with a `download_url`.

**`GET /tasks/{task}/attachments/{attachment}/download`** — the bytes, with
`Content-Disposition: attachment`. Send the same bearer token.

**`DELETE /tasks/{task}/attachments/{attachment}`** — removes the record and the file. Not
recoverable.

`uploaded_by` names whoever sent it, and `uploaded_by_user_id` is `null` when that person has no
account here — a client who attached a screenshot to a support request keeps their name on the file
after the ticket became a task, rather than borrowing the account of whoever accepted it.

### Checklists & test plans

**`POST /tasks/{task}/checklists`**
```json
{
  "kind": "test_plan",
  "title": "Test plan",
  "items": [
    "Submitting the form with an invalid email shows an inline error.",
    "A valid submission redirects to the dashboard and shows a success toast."
  ]
}
```
Creates a checklist and its items in one call. `kind` is `"test_plan"` (the checkable test plan
the in-app AI produces — shown in the task modal, rolled into task progress) or `"general"`
(default; an ordinary to-do list). `items` is a non-empty array of strings. Returns `201` with the
full checklist, including each item's id — this is what lets an external agent set a project up to
the same depth as the in-app AI breakdown, and what you need to reach an individual item afterward.

Lost the response, or picking up a task someone else set up? `GET /tasks/{task}` returns every
checklist on the task with its items and their ids.

**`DELETE /checklists/{checklist}`** removes the checklist and every item on it.

**`POST /checklists/{checklist}/items`**
```json
{ "description": "A cancelled subscription still shows historical invoices." }
```
Adds a single item to an existing checklist — for growing a checklist after the fact (a plan
changed, a question got answered, a new edge case surfaced), rather than replacing the whole thing.
Returns `201` with the item.

**`PATCH /checklists/{checklist}/items/{item}`**
```json
{ "description": "Corrected wording", "is_checked": true }
```
Send `description` to edit the text, `is_checked` to check/uncheck it, or both — at least one is
required. This is the fix for a checklist that's gone stale (a question dropped, a step no longer
applies): edit or remove the item directly, rather than leaving it and posting a comment saying to
disregard it. Checking an item records who did it and when (shown in the app as "completed by …"
under the item); unchecking clears that record rather than leaving a stale name on an item that's
open again.

**`DELETE /checklists/{checklist}/items/{item}`** removes a single item.

### Client requests

What a client asked for on a project, separated into asks, each decided one at a time. The
object between "a message arrived" and "a task exists" — nothing in it is part of the plan until an
ask is acted on. Gated like everything commercial-adjacent: `403` for a viewer.

**There is no endpoint for a client to send a request.** Intake is their own page behind a share
token (`/p/{token}`), which takes no bearer token because they have no account. `POST` here is the
PM's paste-in — logging a message they sent by some other route, attributed to them.

**`GET /projects/{project}/client-requests`** — newest first, each with its `items` (the asks) and
`attachments`. `?open=true` returns only requests with an ask still `proposed`. An item's `kind`
is what the AI digest (or a person) decided it is; `unsorted` means nobody has yet. `matched_task_id`
is only ever a task the digest was actually offered — a hallucinated code is dropped, never stored.

**`POST /projects/{project}/client-requests`** — `{"body": "…", "from_name": "Dave"}`. Returns
`201`. If AI is on for the project, the message is separated into asks out of band; poll the list.

**`POST …/items/{item}/attach`** — `{"task_id": 12, "body": null}` puts the client's words on the
task as a client note in their name, flagged for review, and copies any files they sent. Add
`"reopen": true` for a finished task (reopened through the audited status path) or `"park": true`
for one underway (note on the task, plus a follow-up work-order draft — needs `commercial`).

**`POST …/items/{item}/work-order`** — an unpriced work-order draft from the ask, so the charge
decision is made where it already lives. Needs `commercial`.

**`POST …/items/{item}/resolve`** — `{"action": "noted" | "dismiss" | "reply" | "ask" | "split", …}`
for the decisions that create nothing: `reply` (words the client sees), `dismiss` (silent unless a
`reply` is given, which the client sees as "not going ahead"), `ask` (a `question`; the ask waits on
the client and reopens with `client_answer` set), `split` (`asks`: one string per ask — the manual
equivalent of the digest).

Every action refuses (`422`) an ask that has already been decided — a second call does nothing.

### Support desk

Optional per organisation. **Every endpoint here returns `404` when the desk is switched off** —
an off feature is absent rather than empty, so an empty list always means "no tickets", never "you
don't have this".

Requests come in through a **per-client intake link**: a public, no-login page whose URL carries a
64-character token. That's why there is **no endpoint for creating a ticket** — intake is the
tokened form at `/r/{token}`, which deliberately takes no bearer token, and a request that arrived
there is guaranteed to have come from the named client. Letting an authenticated agent post tickets
too would give the same record two provenances and quietly break that guarantee.

**`GET /support/links`** — every intake link, each with `url`, `expires_at` and
`open_tickets_count`. **Treat `url`/`token` as a credential**: anyone holding it can file against
that client.

**`POST /support/links`** — `{"client_id": 7, "expires_at": "2026-12-31"}`. `expires_at` is optional
(omit for a link that never expires) and must be in the future. Returns `201` with the link.

**`DELETE /support/links/{supportLink}`** — revokes it; the URL stops working immediately. Tickets
already received are kept — they record what the client asked for, not which link they used.

**`GET /support/tickets`** — the inbox, newest first. Optional `?status=` (`new`, `accepted`,
`declined`, `resolved`) and `?client_id=`.

**`GET /support/tickets/{supportTicket}`** — one ticket, including any AI triage suggestion
(`ai_suggested_project_id`, `ai_suggested_priority`, `ai_suggested_size`, `ai_summary`). Those are
**advisory only** — nothing is ever applied automatically, and they're null for organisations with
no AI configured, since triage simply doesn't run there.

**`POST /support/tickets/{supportTicket}/accept`**
```json
{ "project_id": 12, "title": "Fix checkout validation on mobile Safari" }
```
Turns the ticket into a task. Both fields are optional: without `project_id` it lands on the
client's standing support project (created on first use), and without `title` it uses the ticket's
subject — usually worth rewriting, since a reporter's framing rarely reads as a task. The task is
created on a **backlog phase**, which is excluded from the Gantt timeline, so an ad-hoc request
never distorts a schedule someone is using to communicate dates. It goes through the normal task
service, so it gets a real reference code, board position, creation audit row and auto-watching —
indistinguishable from a task created any other way. Returns `201` with `{"ticket": ..., "task": ...}`.
Accepting an already-accepted ticket returns `422` rather than creating a second task.

**`PATCH /support/tickets/{supportTicket}/status`** — `{"status": "resolved"}`. Use this to decline
or resolve. Passing `"accepted"` here is rejected with `422` pointing at the accept endpoint: like
task status, accepting has real side effects, and a caller flipping the field directly would record
the decision without doing any of the work it implies. Moving to `resolved`/`declined` stamps the
resolved time; moving back to `new` clears it.

### Work orders

An agreed, priced piece of work **inside a live project** — a change request on a fixed-fee build,
or simply the next job on an ongoing account. The distinction that keeps this from overlapping with
phases: **a phase is *when*, a work order is *why***. A work order's tasks can be scattered across
several phases, so they are different axes rather than competing groupings. Commercial data, so
viewer-role tokens get `403` on writes.

**`GET /projects/{project}/work-orders`** · **`GET /work-orders/{workOrder}`**

**`POST /projects/{project}/work-orders`**
```json
{
  "title": "Single sign-on for the staff portal",
  "description": "Agreed on a call. Outside the original spec.",
  "origin": "change_request",
  "billing": "billable",
  "price_type": "estimate",
  "price_unit": "hours",
  "estimate_min": 6,
  "estimate_max": 8
}
```

Three things about pricing are deliberate and worth knowing before you build on it:

- **Omit the price entirely if you can't quote it yet.** The order starts in `scoping`, which is a
  real state ("needs a day of research first"), not an unfinished form.
- **An estimate keeps its range.** "6–8 hours" is what people actually say, and storing `7` throws
  away the honest part. `value` resolves an estimate to the **top** of its range, since quoting
  yourself the optimistic end is how a project ends up short.
- **`value` is `null`, never `0`,** when it can't be known — unpriced, absorbed, or priced in hours
  on a project with no rate. Zero would read as "this is free" when the truth is "not decided", and
  a total built on that understates what the client owes.

`origin` and `billing` are separate axes on purpose. Work you *absorb* is still recorded, with what
it would have been worth — an absorbed change request is the most useful line in a post-mortem, and
folding it into "not billable" is exactly what loses it.

**`PATCH /work-orders/{workOrder}`** — changing the price records a revision automatically, keeping
what the client was originally told. Send `price_note` to say why it moved. **A `status` key here is
rejected with `422`**: status changes have consequences (agreeing an order creates its tasks), so
they go through the endpoints that actually do that work.

**`POST /work-orders/{workOrder}/draft-tasks`** — what the work involves, while it's still being
discussed. Draft tasks are deliberately **not tasks**: un-agreed work is a quote, not work, and it
must never show on a board as though it were scheduled.

**`POST /work-orders/{workOrder}/agree`**
```json
{ "placements": { "14": 3, "15": 4 }, "agreed_by_name": "Priya at the client" }
```
Marks it agreed and turns each draft into a real task through the same service the app uses — proper
reference, board position, activity row, watcher. `placements` maps draft task id to the phase it
lands in; a draft with no placement is skipped rather than guessed at. Agreeing twice creates
nothing the second time.

Agreement is **implicit** — nothing is sent to anyone, and `agreed_by_name` is just a note of who
said yes. If the order is `absorbed`, its tasks are created `non_billable`, so the hours still get
logged and still count against the effective rate; somebody did the work either way.

**`PATCH /work-orders/{workOrder}/status`** — for orders with no drafts to convert.

### Statements

What has been billed on a project and what is still owed. **Not invoices** — the invoice document is
issued by your accounting system. This answers the question an accounting system can't, because it
has never heard of a work order, a time log or a payment-schedule instalment.

**`GET /projects/{project}/unbilled`** — the "what should be invoiced" question, ready to read:
completed work orders, billable time, incurred expenses, and payment-schedule instalments, with a
total. What's deliberately excluded is as important as what's in:

- **Work orders only once complete** — derived from their tasks all being done. Billing for work
  that isn't finished is a decision, not a default.
- **Time only on hourly projects.** On a fixed fee the hours are already covered by the fee, so
  listing them too is charging twice for the same work.
- **Non-billable time never appears**, so absorbed work can't reach a client.
- **Expenses only once incurred.** Billing for money you haven't spent is how trust goes.

**`POST /projects/{project}/statements`** — drafts a statement from everything unbilled. Leave the
period empty to bill everything outstanding, which is what you want for a one-off such as a single
finished feature.

**Nothing is marked billed at this point.** A draft is a proposal that can be deleted freely,
because consuming its sources here would mean an abandoned draft silently swallowed a month of
billable work.

**`POST /statements/{statement}/issue`** — freezes the lines and marks everything on it billed. This
is the single moment anything is consumed, and the natural hook for an accounting integration.
Issuing twice returns `422` rather than doing nothing quietly, since a silent no-op would leave you
believing it had re-sent.

Lines are **frozen copies**, not a live view: once a client has been told what they owe, editing a
work order's price cannot rewrite what they were told. `source_type`/`source_id` are for tracing
back, never for recalculating.

**`POST /statements/{statement}/payment`**
```json
{ "amount_received": 5000, "payment_reference": "BACS 4471" }
```
Omit `amount_received` for payment in full. A smaller figure makes `display_status` read `part_paid`
rather than `paid` — a statement headed PAID beside an outstanding balance is a claim a client will
rightly query. `{"clear": true}` undoes a recorded payment entirely.

**`POST /statements/{statement}/void`** — releases everything back to be billed again. The statement
is kept rather than deleted; it was sent to someone, and "issued then withdrawn" reads better than a
gap in the numbering.

### Reports

Read-only account-wide summaries — for a local agent pulling status without walking every project.
All are scoped to the token user's visible projects; the commercial ones (time log, AI usage) are
off-limits to viewer-role tokens (`403`).

**`GET /reports/workload`** — open tasks per person (not started / in progress / review / overdue /
total). Optional `?client_id=`.

**`GET /reports/time-log`** — logged time across projects. Optional `?from=YYYY-MM-DD&to=YYYY-MM-DD`
(defaults to the current month), `?client_id=`, `?user_id=`.

**`GET /reports/ai-usage`** — per-project AI token usage and approximate USD cost (estimates from
published per-model pricing, not a bill). Optional `?project_id=`.

**`GET /reports/pipeline`** — sales performance: win rate, open pipeline by stage, why deals were
lost, forecast by expected close month, average deal size and average days to win. Optional
`?client_id=`, `?from=`, `?to=` (the dates filter *decided* deals by decision date).

Two definitions worth knowing before you build on the numbers. **Win rate counts only decided
deals** — including still-open opportunities in the denominator would make a healthy pipeline read
as a failing one, since everything starts undecided. And **average deal size uses won deals only**,
because averaging in lost or speculative values measures optimism rather than revenue. `win_rate`
is `null` rather than `0` when nothing has been decided yet.

**`GET /projects/{project}/profitability`** — what the project earned per hour of work, once
unbilled time and real costs are counted. Owner/admin only, and `404` unless the project has the
profitability feature switched on.

This is an **effective rate, not a margin**, deliberately: a margin needs a cost for your own time,
and a sole trader does not pay themselves a salary, so any figure for it would be invented and the
answer would inherit that invention. Revenue minus money that actually left the account, over the
hours it took. Every hour counts, billable or not — unbilled time is precisely why an effective
rate falls below the headline rate. `effective_rate` is `null` below an hour of logged time or when
the project has no pricing, rather than a number derived from a few minutes that looks precise and
means nothing.

**`GET /projects/{project}/estimates`** — estimated effort against what the work actually took.
`404` unless the estimate-accuracy feature is on for that project.

Returns two buckets that are **never blended**. `logged` covers tasks with time recorded against
them: a measured effort, and the figure to trust. `calendar` covers tasks with no logged time,
where the only evidence is working days between start and due — that is how long a task was *open*,
not how long it took, so treat it as a ceiling. Only finished, estimated tasks count, and a
subtask's time rolls into its parent. The ratio is weighted by size rather than averaged per task,
because a ten-day task 20% over matters more than a one-day task 200% over. `has_signal` is `false`
until there are enough measured tasks to call it a pattern; the figures are still returned, but
don't present them as a trend. A day is `working_day_hours`, the organisation's configured working
day.

Estimates are compared against the **original** value a task was given rather than its current one
— revising a three-day task to seven while it overruns would otherwise read as accurate.
`revised_count` reports how many were changed after being set, so a corrected typo is at least
visible as something distinct from a moved goalpost.

Example prompts a person might give a local agent driving this API:
- *"Pull the workload report and tell me who has more than 8 open tasks."*
- *"Summarise this month's time log grouped by client."*
- *"How much has AI cost across all projects this quarter?"* → `GET /reports/ai-usage`.
- *"What's my win rate this year, and why are we losing?"* → `GET /reports/pipeline`.
- *"Did we make money on the Acme rebuild?"* → `GET /projects/12/profitability`.
- *"Do we consistently under-estimate for this client?"* → `GET /projects/12/estimates`.

## Errors

Standard Laravel shapes:
- `401` — missing/invalid token.
- `403` — the token's user doesn't have permission (e.g. a viewer-role user attempting a write).
- `404` — the resource doesn't exist, or belongs to a different tenant (cross-tenant IDs 404
  rather than 403, so their existence isn't leaked).
- `422` — validation failure, body shaped `{"message": "...", "errors": {"field": ["..."]}}`.
