# Engagement Schema & Shared Contracts

The canonical contract for the **engagement** module — the data shapes,
conventions, and lifecycle rules that every phase of the engagement
system depends on. This is the source of truth: skills, the render
engine (`engagement.mjs`), and the pib-db adapter all conform to what
is written here.

> **Status:** Schema v6 (base) / v9 (engagement patch). Engagement V2
> ships column-based client-facing copy, visibility-gated messages,
> scoped notes, and consolidated `/collab-client` + `/collab-consultant`
> skills. V2.1 adds bidirectional API communication via the engagement
> server, object-oriented skill subcommands, and the context model for
> threaded conversations. If a contract here is wrong, fix it here
> first, then propagate.

---

## 1. The store: `engagement_events` (schema v5, visibility v8)

An **append-only** log, modeled on `trigger_checks`. One row per event.
The canonical DDL lives in `templates/engagement/sql-constants.mjs` —
the migration entry and idempotent CREATE reference it (drift-guard
tests enforce consistency).

| Column       | Type / constraint | Meaning |
| ------------ | ----------------- | ------- |
| `id`         | INTEGER PK AUTOINCREMENT | Stable event id. |
| `engagement` | TEXT NOT NULL → `projects(fid)` | The engagement. **FK enforced** (`foreign_keys = ON`): an event can never reference a non-existent engagement. The FK has no `ON DELETE` clause (defaults to `NO ACTION`), so a **hard** `DELETE` of a project that still has events fails — correct for an append-only audit log. **Soft**-delete (`projects.deleted_at`) is unaffected and is the intended way to retire an engagement. |
| `target_fid` | TEXT (nullable)   | The action this event is about (`act:*`), or NULL for engagement-level events. **No FK** — append-only audit must survive a later delete of the action. |
| `packet_id`  | TEXT (nullable)   | The packet this event relates to. |
| `kind`       | TEXT NOT NULL, CHECK enum | One of the seven kinds below. |
| `author`     | TEXT NOT NULL     | Who authored it. Allowlist-enforced at write time. |
| `verdict`    | TEXT (nullable), CHECK enum | `approve`/`object`/`comment`/`none`. Required & meaningful for some kinds. |
| `body`       | TEXT (nullable), CHECK ≤10000 | Free-text content. |
| `visibility` | TEXT NOT NULL DEFAULT 'internal', CHECK enum | `client` or `internal`. **Fail-closed:** events default to `internal` and never reach the client packet unless explicitly marked `client`. Added in schema v8. |
| `addressed`  | INTEGER NOT NULL DEFAULT 0 | 0/1 — has the consultant triaged it? |
| `created_at` | TEXT NOT NULL, CHECK ISO-8601 | `new Date().toISOString()`. |

### Event kinds

| Kind             | Meaning | Verdict | Default visibility |
| ---------------- | ------- | ------- | ------------------ |
| `client_feedback`| A recipient's response to a packet item. | **Required** (`approve`/`object`/`comment`). | `internal` |
| `approval`       | An explicit approval of an item. | **Required** (meaningful). | `internal` |
| `status_push`    | A consultant-authored status message to a recipient. | Optional. | Explicit `client` when intended for the recipient. |
| `delegation`     | An item delegated to a recipient. | Optional. | `internal` |
| `note`           | An internal or engagement-level note. | Optional. | `internal` by default; `/collab-consultant messages` sets `client`. |
| `packet_sent`    | Marker that a packet was delivered. `target_fid` NULL. | Optional. | `internal` |
| `packet_opened`  | **PLANNED, not yet a valid kind.** Reserved for a client-opened-packet marker. It is NOT in `ENGAGEMENT_EVENT_KINDS` (the JS write-gate) and was removed from the DDL CHECK — no write path can produce it today. Ship it as `ENGAGEMENT_EVENT_KINDS` + DDL CHECK + a v9 migration together (data-integrity-0002). | — | — |

The table CHECK enforces: `client_feedback` and `approval` rows must
carry a verdict in (`approve`,`object`,`comment`). The explicit
`verdict IS NOT NULL` guard in the CHECK is required because SQLite
treats a CHECK that evaluates to NULL as *passing* — without it a NULL
verdict would slip through for those kinds.

### Visibility gate

The messages feed in `renderPacket` filters events with
`.filter(e => e.visibility === 'client')` — strict equality, fail-closed.
Events with `visibility='internal'`, `null`, or any other value are
silently dropped. The adapter (`toEvents`) maps missing/null visibility
to `'internal'` (fail-closed fallback). All three DB definition sites
(sql-constants.mjs, pib-db-schema.sql, engagement-setup.js) default to
`'internal'`.

### Indexes

- `idx_engagement_events_eng` — `(engagement, created_at DESC)`: list an
  engagement's events newest-first.
- `idx_engagement_events_tgt` — `(target_fid, created_at DESC)`: list a
  single action's events.
- `idx_engagement_events_dedup` — `(packet_id, target_fid, verdict)`:
  speeds the dedup lookup. **Not UNIQUE** — see below.

### Dedup semantics

Dedup is an **application-layer advisory**, not a hard constraint.
`addEngagementEvent` runs a SELECT-before-insert only when `packet_id`,
`target_fid`, and `verdict` are **all non-null** (i.e. a real feedback
or approval response). Body is part of the key so that two responses
mapping to the same verdict but carrying distinct content (e.g. a
`[provided]` value and a `[credential]` envelope, both stored as
`verdict='comment'`) don't collapse — but identical re-feeds dedup.

### Library API (`scripts/pib-db-lib.mjs`)

The lib is **config-agnostic** — it never reads `engagement.yaml`. The
caller (`/collab-consultant sync`) reads config and passes
`allowedAuthors` down. CLI and MCP both route through these functions;
there is no raw-INSERT path.

- **`addEngagementEvent(db, payload, allowedAuthors)`** — validates the
  engagement exists, `target_fid` format (if present), `kind`/`verdict`
  enums, verdict-required kinds, body length, `visibility` enum, and the
  author allowlist (**fail-closed**: empty or omitted `allowedAuthors`
  rejects all). Applies advisory dedup. Returns `{ id, ... }` or
  `{ id, deduped: true }`.
- **`listEngagementEvents(db, { engagement, target_fid, unaddressedOnly, excludeSoftDeleted })`**
  — newest-first. Returns `visibility` field. `excludeSoftDeleted` LEFT
  JOINs `actions` and keeps engagement-level events plus events whose
  target action is not soft-deleted.
- **`markEventAddressed(db, { id })`** — sets `addressed = 1`.

---

## 2. Action tag conventions

Engagement metadata rides on the existing `actions.tags` TEXT column —
**no schema change**. Tags are a comma-separated free-text convention,
validated at render time (`validateTags`), not by the DB.

| Tag               | Meaning |
| ----------------- | ------- |
| `client-visible`  | Opt-in. **Absence means internal** — an untagged action appears in no packet. |
| `audience:<id>`   | Which recipient(s) may see this item. `<id>` resolves to a `recipients[].id`. |
| `scope:<scope>`   | A topical scope (e.g. `scope:marketing`) used for filtering/visibility. |
| `assignee:<id>`   | **Sole basis** for inclusion in a delegate's email. `<id>` is a recipient id. |
| `needs:decision`  | This item requires a client decision (drives `needs_you`). |
| `needs:credential`| This item requires a credential capture (runs the encrypt pipeline). |

Priority is expressed through the existing `flagged` / `status` columns,
not a tag. Unrecognized or case-drifted tags produce **warnings**, not
hard failures.

**Projects can also carry tags** — same comma-separated format as
actions. A project tagged `client-visible` renders as a rolled-up item
in the client packet (see §2.5).

---

## 2.5. Project roll-ups

A project tagged `client-visible` appears in the engagement packet as a
**roll-up** — a single line showing the project's aggregated status.

### Rendering rules

- **Display-only.** Roll-up items carry `feedbackable: false` and have no
  `ref` or `_refmap` entry.
- **Status derivation.** Derived from the project's client-visible,
  non-deleted child actions **that have client copy populated** (4C
  roll-up purity — actions without copy are not yet client-ready and
  don't influence roll-up status). Priority order: `blocked` >
  `in-progress` > `deferred` > `open` > `done`. Zero copy-bearing
  children → the project's own status label (safe default `'In progress'`
  for unknown statuses — never the raw enum).
- **Visibility.** Principals see roll-ups. Delegates do NOT.
- **Client-facing copy required.** A `client-visible` project must have
  client copy (`parseClientCopy(project) !== null`). Without it, the
  project is not client-ready and is excluded.
- **Drill-down opt-in.** A project being `client-visible` does NOT
  automatically expose its child actions.

---

## 3. Client-facing copy (column-first)

Client-facing copy is stored in **dedicated columns** on both `actions`
and `projects` tables (schema v6 base / v7 patch):

| Column | Type | Meaning |
| ------ | ---- | ------- |
| `client_title` | TEXT (nullable) | One-line title shown in packets. |
| `client_body` | TEXT (nullable) | "Why this matters" explanation. |
| `client_generated_at` | TEXT (nullable) | ISO timestamp of last generation. |
| `client_generated_status` | TEXT (nullable) | Status at generation time (staleness detection). |

**NULL = no copy written.** Empty string is invalid — writes normalize
`'' → NULL` (the `updateAction`/`updateProject` dynamic SET builders
enforce this). The not-client-ready gate is `parseClientCopy(item) === null`.

### `parseClientCopy(item)`

Reads columns first; falls back to notes-based extraction when columns
are NULL (transition period for pre-V2 data):
1. If `item.client_title != null` → return `{ client_title, client_why: item.client_body }` (column path).
2. Else parse `<!-- client-facing\n...\n-->` from `item.notes` (legacy fallback).
3. Return `null` if neither source has copy.

Status suffixes (e.g. "— complete", "— shipped") are stripped from
titles at render time by `STATUS_SUFFIX_RE` — the stored `client_title`
is preserved as-is. New status values MUST be added to `STATUS_LABELS`
before use to prevent raw enum leaks.

### `detectStaleness(item, currentStatus)`

Checks whether copy was generated for a different status:
1. Column path: reads `item.client_generated_status`.
2. Notes fallback: parses `<!-- cc-generated:<ts> status:<status> -->`.
3. Returns `{ stale: true, reason }` or `{ stale: false }`.

### Options extraction (two functions)

- **`extractClientOptions(item)`** — reads from `item.client_body`.
  Used by `renderPacket` for packet construction (client-facing).
- **`extractOptions(item)`** — reads from `item.notes`. Used by
  `buildGenerationSource` for copy generation (internal).

These are intentionally different sources. Options declared in notes
but not in `client_body` never reach the client packet (the copy gate).

### Data migration

`migrateClientCopy(db)` extracts `<!-- client-facing -->` blocks and
`<!-- cc-generated -->` markers from `notes` into columns. Idempotent:
gates on `client_title IS NULL AND client_body IS NULL AND
client_generated_at IS NULL`. Notes content is left unchanged (the
HTML comments become inert legacy). Runs at postInstall after
`migrate()`.

### Legacy notes-based copy

The `<!-- client-facing\n...\n-->` format in notes is legacy. New copy
MUST be written to columns via `pib_update_action({ fid, client_title,
client_body, client_generated_at, client_generated_status })`.
`spliceClientCopy` is deprecated — do not use for new writes.

---

## 4. `engagement.yaml` v2

Extends `handoff.yaml` v1 — **v1 files stay valid**. New blocks:

```yaml
engagement:
  slug: maginnis
  title: "Maginnis Howard — Marketing & Platform"
  project_fid: prj:abc12345
  consultant: "Oren Magid"
  public_key: "./keys/consultant.pub.jwk"

billing:
  enabled: true
  timelog: "./timelog.md"
  rate: 190
  currency: USD
  period: since-last-sync          # engagement | month | since-last-sync

invoicing:                         # optional — see §8.1
  mode: consolidated               # consolidated | itemized
  scope_label: "Consulting services"
  terms_days: 30

recipients:
  - id: ed
    name: "Ed Maginnis"
    org: "Maginnis Howard"         # optional — shown in the invoice bill-to
    email: "ed@example.com"
    role: principal
    scopes: [all]
    has_claude_code: true
  - id: sydney
    name: "Sydney"
    email: "sydney@example.com"
    role: delegate
    scopes: [marketing]
    has_claude_code: false

roles:
  principal: { sees: all,      billing: true  }
  delegate:  { sees: assigned, billing: false }

transport:
  type: email                          # email | mcp | file | api
  consultant: "oren@example.com"

# API transport (engagement-server):
# transport:
#   type: api
#   endpoint: https://my-server.up.railway.app
#   token: env:ENGAGEMENT_TOKEN        # env:VAR_NAME or literal
#   notification_email: client@example.com  # optional nudge email

staleness_days: 7                  # per-user quiet detection threshold

engagement_notes:
  - "All email logic is built and tested on staging."

scoped_notes:                      # tag-scoped caveats (4A)
  - tag: "scope:email"
    note: "All email items are tested on staging."
  - tag: "scope:auth"
    note: "Authentication uses test credentials."
```

**`has_claude_code` vs transport.** `has_claude_code` (per recipient)
determines the *experience*: `true` → interactive `/collab-client`
packet + notification email; `false` → content email only via
`buildDelegateEmail`. `transport` (engagement-wide) is the *channel*.

**API transport** (`type: api`): Routes through the engagement server
(Phase 2). `engagement-transport.mjs` builds instruction objects via
`buildApiSendInstruction()` / `buildApiReceiveInstruction()` — the
skill executes the actual `fetch()`. Token resolution supports `env:`
prefix (reads from process environment) or literal strings. Falls back
to file transport if `endpoint` is missing.

**`scoped_notes`** (4A): tag-scoped caveats rendered below matching
items as `context_notes`. Tags matching zero actions produce an advisory
warning during sync hygiene.

---

## 5. Packet schema & lifecycle

A **packet** is a per-recipient projection of engagement state:

```
engagement, packet_id, recipient, role, generated_at,
needs_you: [ { ref, title, why, kind, options, context_notes? } ],
in_flight: [ { ref, title, why, status, context_notes? } ],
shipped: [ { ref, title, status } ],
delegated: [ { ref, title, status, context_notes? } ],
billing,              # present ONLY if roles[role].billing === true
messages,             # only visibility='client' events
new_since_last,
generated_label,
engagement_notes,     # persistent consultant-authored notes
checklist_summary     # [ { type, count } ] when config has sections
```

- The client **never** sees `action_fid` — items are referenced by an
  opaque `ref`. Status enums are pre-translated via `STATUS_LABELS`
  (unknown statuses render as `'In progress'`, never the raw enum).
- **`context_notes`** (4A): present on items matching `scoped_notes` tags.
  Array of strings, only present when non-empty.
- **`_refmap` stays consultant-side.** Written only to
  `<recipient>-sent.json`, **never** in the delivered packet.
- **`assertPacketInvariants`** is a HARD GATE: throws on `_refmap`,
  `action_fid`, `fid`, `project_fid`, `text`, `internal_text`, `name`,
  `notes`, `tags`, `client_title`, `client_body`, `client_generated_at`,
  `client_generated_status` on any item. Also throws on billing for
  non-billing roles and undefined roles.

### Lifecycle

1. **Render** → `<recipient>-draft.json` (full packet + `_refmap`).
2. **Deliver** packet minus `_refmap` via channel.
3. On confirmed send → rename to `-sent.json`, log `packet_sent` event.
4. Transport failure → keep draft, no event; rerun re-sends.

---

## 5.1. Decision items — the structured options & decision-type contract

The single shared contract that the engine synthesis (`renderPacket`),
the fail-closed validator (`assertPacketInvariants`), the client
renderer (`/collab-client`), and the consultant inbox
(`/collab-consultant`) all conform to. P1.1–P1.4 of the engagement
upstream-fix program depend on this — pin it here, build to it.

### Where a decision is authored (once)

A decision is authored exactly once, in `engagement.yaml`, as a `decide`
item inside a `sections[]` block:

```yaml
sections:
  - key: go_live
    items:
      - key: arbitration_forum_model
        kind: decide
        tier: recommended            # optional priority hint (free text)
        audience: [ed]               # optional; default = all principals
        prompt: "Which forum model…" # the question  → client_title / title
        help:  "Tracking per-company…" # the explanation → client_body / why
        tradeoff: "Per-company is…"   # optional; appended to `why`
        options:                      # omit / empty ⇒ free-text decision
          - "A — forum per company, with an analysis notes field"
          - value: "B — one forum per theory"
            label: "One forum per theory"
        free_text: false              # optional; forces a free-text answer
```

`engagement.yaml` stays the **authoritative authoring source** for
decisions (Non-Goal: dropping it). The engine derives everything below
from it.

### The engine internalizes the projection (P1.1)

`renderPacket`, given the parsed config, **ensures a backing decision
per `decide` item and renders it into `needs_you` exactly as it renders
a `needs:decision` action** — preserving the `ref` / `refmap` /
`client_feedback` spine. The pure engine synthesizes the backing item
**in-memory** from the yaml (it imports nothing — no DB, no fs); a
pib-db row is materialized separately by `ensureDecisionActions` (below).

- **Deterministic backing fid.** Each decide item gets a stable fid
  `decisionFid(engagementSlug, sectionKey, itemKey)` → `act:<8 hex>`
  (FNV-1a). Deterministic so the `ref` is stable across renders
  (`new_since_last` stays a reliable diff) and so an inbound answer's
  `target_fid` always resolves to the same decision — even across a
  re-render (the cross-render gate). It **must satisfy the pib-db
  `FID_PATTERN` (`act:<8 lowercase hex>`)** so the answer's `target_fid`
  passes `addEngagementEvent`'s `validateFid` — the production ingest
  path the loop test's in-memory refmap never exercises (so the loop
  test alone would not catch a malformed fid; this is why the scheme is
  fixed at design time, not later). A collision with a real
  pib-db-generated fid is ~1e-6 and is hard-guarded in the synthesis (an
  unrelated live-fid match throws loudly rather than mis-attributing the
  answer).
- **Same spine as an action.** `ref = stableRef(fid)`,
  `refmap[ref] = fid`. The client answers `context_ref: <ref>`; the
  consultant inbox resolves `ref → fid` and writes `client_feedback`
  with `target_fid = fid`. A yaml section rendered *raw* (no fid) would
  break this — hence synthesis, not raw rendering (loop-test step D).
- **No row required to render or round-trip.** `target_fid` has no FK,
  so the answer stores even if no pib-db row exists. The row exists so
  the consultant can *apply* the answer against a real action — see
  `ensureDecisionActions`.

### Structural dedup (invariant #3)

The engine must **never** emit a decision twice — once natively from the
yaml and once from a surviving projected action. A backing/projected
action declares which decide item it covers via an
`engagement_key: <itemKey>` marker on its own line in `notes`. When
synthesizing, the engine **skips any decide item whose key appears in
the `engagement_key` marker of a live, visible `needs:decision`
action** — that action renders it instead. The marker is the single
dedup key, shared by the engine synthesis and `ensureDecisionActions`.
After the Phase-2 cutover (projected actions tag-neutralized), every
decide item renders natively.

### The packet decision item (the structured shape — P1.2)

Every decision `needs_you` item carries the fields below. **Note the
`kind` value is `'decision'`, not `'needs:decision'`** — `parseActionTags`
strips the `needs:` prefix, so the rendered item's `kind` is the
post-colon token (`'decision'` / `'credential'`). The TAG is
`needs:decision`; the item FIELD is `kind: 'decision'`.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `ref` | string | opaque stable ref (`refmap` resolves it to the fid) |
| `title` | string | the question (`prompt` / `client_title`) |
| `why` | string | the explanation (`help` / `client_body`, + `tradeoff`) |
| `kind` | `'decision'` | the needs token (the `needs:` prefix is stripped) |
| `decision_type` | `'choice'` \| `'free_text'` | how it is answered |
| `options` | `Array<{ value: string, label?: string }>` | the choices |

- **`options` is an array of objects, never a comma-joined string.** The
  `value` is the canonical, **comma-safe** answer text, round-tripped
  verbatim — there is no `split(',')` on a value anywhere. `label` is an
  optional short display string (defaults to `value`). This retires the
  lossy `Options: A, B, C` line: a value that itself contains a comma
  survives intact.
- **Normalization.** A yaml option given as a bare string `"X"`
  normalizes to `{ value: "X", label: "X" }`. An object option passes
  through; a missing `label` defaults to `value`. Whitespace-only / empty
  values are dropped.
- **`decision_type: 'free_text'`** — an open-ended written answer. Set
  when the decide item declares `free_text: true` OR has no `options`.
  `options` is `[]`. The client collects free text instead of choices.
- **`decision_type: 'choice'`** — pick from `options` (≥2 required).

### Fail-closed (P1.2)

`assertPacketInvariants` **throws** on any answerable `needs_you` item
(`kind === 'decision'` carrying a `ref`) with `decision_type === 'choice'`
and `options.length < 2`. An unanswerable choice decision can never ship —
the failure is loud at render time, not a confusing empty dialog for the
client. The gate is whole-packet (consistent with the leak gate): a
misconfigured decision holds the entire packet until fixed. Free-text
decisions legitimately carry zero options and are exempt. Display-only
roll-ups (`feedbackable: false`, no `ref`) are exempt. A real (projected)
action with exactly 1 option also trips this — fix by adding a second
option or dropping the `needs:decision` tag (an action author has no
`free_text` field).

### Two stability caveats

- **Decide keys must be unique across sections.** Dedup (and the legacy
  workaround) match a projected action's `engagement_key: <key>` marker —
  which carries no section — against a yaml decide key. If the same key
  appears in two sections and one projected action covers it, both
  sections' synthesis is suppressed and only one renders. Keep decide
  keys unique within an engagement.
- **A section/slug rename re-keys the ref.** The cross-render ref
  stability holds only while `engagement.slug`, the section key, and the
  item key are all unchanged (they seed `decisionFid`). Renaming any of
  them changes the fid → ref and orphans an in-flight answer keyed to the
  old ref. Don't rename a section or the slug while a decision packet is
  out and unanswered (the refmap-continuity invariant, #5).

### `ensureDecisionActions` — the persistent-row materialization (Phase-2 cutover)

**Phase 1 ships the render synthesis above; the persistent-row
materialization lands at the Phase-2 Maginnis cutover (P2.1), where it
replaces the project-local `project-engagement-decisions.mjs`.** The
synthesis alone closes the loop (render + refmap + answer round-trip;
`target_fid` has no FK, so the answer stores without a row). The
materialized row is what lets the consultant *apply* an answer against a
tracked action.

When built, it is the DB-side counterpart — living at the adapter/skill
boundary (NOT in the pure engine), called at sync time before render:
idempotently materializes one pib-db action per decide item, keyed to
the **same deterministic fid** and carrying the `engagement_key:
<itemKey>` marker, `client-visible,needs:decision` tags (+
`audience:<id>` when declared), and the structured copy. Because the row
carries the marker, the render's structural dedup skips re-synthesizing
that key and renders the row instead — so in production every decision
resolves to a real, ingest-valid fid, and the synthesis is the
no-row / loop-test fallback.

### Client render (P1.2 → `/collab-client`)

A `choice` decision maps each `options[i]` to one AskUserQuestion option
(`label: opt.label`, description from context); the chosen `value` is
the answer text submitted as the `client_feedback` message. A
`free_text` decision collects an open written answer (no option list).
The client never sees the `decision_type` enum or verdict jargon.

### Answer round-trip (unchanged spine)

The answer is a `client_feedback` event with
`target_fid = refmap[context_ref]` (§6). Because the backing fid is
deterministic, an answer keyed to a prior packet's ref resolves to the
same decision across re-renders.

---

## 6. `item_feedback` envelope

The contract for inbound client responses. **Keyed by `ref` only.**

```json
{
  "type": "item_feedback",
  "engagement": "prj:abc12345",
  "recipient": "ed",
  "packet_id": "pkt_2026-05-31",
  "responses": [
    { "ref": "r1", "verdict": "approve", "message": "yes" },
    { "ref": "r2", "verdict": "credential_sent", "envelope_id": "env_abc" },
    { "ref": "r3", "verdict": "delegate", "message": "Sydney" }
  ],
  "sent_at": "2026-05-31T00:00:00Z"
}
```

Response verdicts (`FEEDBACK_VERDICTS`):
`approve | object | comment | provided | credential_sent | delegate`

These are a **superset** of the `engagement_events.verdict` DB enum.
`mapResponseToEvent` maps each to a storable `client_feedback` event:

| Feedback verdict | Stored event | Body |
| --- | --- | --- |
| `approve` / `object` / `comment` | `client_feedback`, same verdict | the response `message` |
| `provided` | `client_feedback`, verdict `comment` | `[provided] <value>` |
| `credential_sent` | `client_feedback`, verdict `comment` | `[credential] envelope <envelope_id>` |
| `delegate` | `client_feedback`, verdict `comment` | `[delegate] <delegate name>` |

`provided`, `credential_sent`, and `delegate` all map to `comment`
with a body prefix — no DB schema change needed. The consultant
distinguishes them by the prefix. The dedup key
`(packet_id, target_fid, verdict)` includes body, so distinct prefixes
don't collapse.

### Ingestion (`/collab-consultant sync` step 13)

1. **Validate** (`validateFeedbackEnvelope`) — fail-closed trust boundary.
2. **Resolve** each `ref` via `<recipient>-sent.json`'s `_refmap`.
3. **Map + write** (`mapResponseToEvent` → `addEngagementEvent`).
4. **Apply — offer, never force.** Client input never auto-mutates pib-db.
5. **Neutral receipts — queue, never auto-send.**

---

## 7. Schema versioning (base/patch split model)

The engagement module overlays engagement-inclusive pib-db files over the
base work-tracking templates at install time (`lib/engagement-setup.js`).
Base and patch have different migration histories — the same physical
column can appear at different version numbers.

### Version allocation table

| Version | Base meaning | Patch meaning |
| ------- | ------------ | ------------- |
| v1 | actions.status CHECK | same |
| v2 | actions.tags | same |
| v3 | trigger_condition + trigger_checks | same |
| v4 | trigger_checks composite index | same |
| v5 | projects.tags | engagement_events + 3 indexes |
| v6 | client copy columns (4 each on actions + projects) | projects.tags |
| v7 | — | client copy columns (4 each) |
| v8 | — | engagement_events.visibility |
| v9 | — | _(deferred)_ engagement_events.kind += `packet_opened` — reverted from the CREATE-path constants until the write path ships; SCHEMA_VERSION stays 8 (data-integrity-0002) |

### Coordination rules

- The patch SCHEMA_VERSION must always be ≥ the base SCHEMA_VERSION.
- When base advances, the patch must advance in the same CC release.
- Migrations shared by both use column-existence checks or IF NOT EXISTS.
- The `try/catch` in `migrate()` swallows "duplicate column" — safe for
  the overlap where the same columns appear at different version numbers.

### Overlay logic (engagement-setup.js)

The overlay decision for `pib-db-lib.mjs` is **marker-aware**: it checks
whether the installed file contains engagement code (`engagement_events`
marker), not just the SCHEMA_VERSION number. Three cases:

1. Has engagement code + version ≥ patch → skip (already current).
2. Lacks engagement code + version ≤ patch → copy (normal first-add or upgrade).
3. Lacks engagement code + version > patch → **BASE AHEAD**: the base
   advanced without a coordinated patch bump. The overlay emits a loud
   warning and skips both file copy and schema-ensure to prevent
   mismatched lib/DB state.

---

## 8. Timelog & billing format

A Markdown table plus a running-total line:

```markdown
| Date       | Hours | Work                          |
| ---------- | ----- | ----------------------------- |
| 2026-05-20 | 2.5   | Platform setup                |
| 2026-05-22 | 1.75  | Campaign config               |

**Running total:** 23.25 hours
```

Default rate **$190/hr**. `renderBilling` sums the `Hours` column;
`period` selects which rows count. Billing appears only when
`roles[role].billing === true`.

---

## 8.1. Invoicing (`invoicing` block + the `invoices/` output)

`/collab-consultant invoice [YYYY-MM] [--itemized]` renders a clean,
print-friendly invoice **document** (`renderInvoiceDoc`) from a month's
tracked hours. It is local-only — no API, no pib-db mutation, no email.

### Why a document, not an API

The operator's bank (**Relay**) does the actual invoicing. Relay has no
API but accepts an uploaded PDF/PNG via **Create Invoice → Autofill from
document**. So the system's only job is to render the document; the
operator uploads, reviews, and sends in Relay. Validated against Relay's
autofill (live experiment):

- Line items are **Description / Quantity / Unit price / Amount** and
  Relay computes its own totals (Quantity = hours, Unit price = the rate).
- Relay assigns its own invoice number and pulls the sender (From /
  business name / address / email) from the operator's Relay account.
  **The document therefore carries NO invoice number and NO From / remit
  / bank / ACH block** — they are ignored or overridden.
- Relay autofills the customer (bill-to name + email) and the line items
  + total correctly.
- Relay does **not** read a net-30 due date — it defaults the due date to
  today. Terms only survive in Relay's free-text Memo, so they go in a
  memo-friendly footer line and the skill tells the operator to set the
  due date in Relay by hand.

### The `invoicing:` config block (optional)

| Field | Default | Meaning |
| ----- | ------- | ------- |
| `mode` | `consolidated` | `consolidated` (one line: scope label + month, Quantity = total hours) or `itemized` (one line per timelog row). `--itemized` on the command line overrides. |
| `scope_label` | `"Consulting services"` | The line description in consolidated mode (rendered as `<scope_label> — <Month YYYY>`). |
| `terms_days` | `30` | Net-N payment terms — `dueDate = invoiceDate + terms_days`, shown in the memo footer. |

`loadEngagement` normalizes these defaults (mirrors how `billing` /
`transport` defaults are filled), so downstream code can assume the
shape. **No bank / remit / From fields are needed** — see above.

The bill-to block reads `recipient.name`, optional `recipient.org`, and
`recipient.email` (org rides through `normalizeRecipient`).

### Output convention: `invoices/<YYYY-MM>.html` (+ best-effort `.pdf`)

The rendered HTML is written to `invoices/<YYYY-MM>.html` in the working
dir. The skill then attempts a best-effort PDF conversion using whatever
tool is already on the machine (weasyprint → headless Chrome →
wkhtmltopdf), **with no bundled dependency** — if none is available it
tells the operator to open the HTML and use Cmd-P → Save as PDF. Relay
needs a PDF or PNG, not HTML. The `invoices/` directory is local runtime
output (gitignore alongside `engagement-packets/`).

---

## 9. Scope model: multi-project engagements

An engagement operates at the scope of **one `pib.db`** — all
client-visible actions across **all projects** belong to the engagement.
`engagement.project_fid` is the home project (event logging default),
not a filter boundary.

---

## 10. Skills

Three primary skills, plus redirect stubs for backward compatibility.
Both `/collab-client` and `/collab-consultant` share the same **object
vocabulary** (`inbox`, `messages`, `input`, `requests`) — the skill
knows which side you're on from the engagement role.

| Skill | Side | Subcommands |
| ----- | ---- | ----------- |
| `/collab-client` | Client | (default) `inbox`, `updates`, `messages`, `input`, `requests`, `progress`, `delegate`, `help` |
| `/collab-consultant` | Consultant | (default) dashboard, `inbox`, `sync`, `messages`, `input`, `requests`, `create`, `add`, `edit`, `help` |
| `/setup-accounts` | Client | Interactive account-setup walkthrough with self/delegate/later modes |

The 9 old `/engagement-*` skills are redirect stubs pointing to `/collab-*`.

---

## 10.1. Context model (API communication)

When transport is `type: api`, messages flow through the engagement
server with a **context model** that structures conversations:

| `context_type` | `context_ref` | Meaning |
| -------------- | ------------- | ------- |
| `null` | `null` | About the engagement itself |
| `'item'` | opaque item `ref` | About a specific work item |
| `'message'` | message `id` (integer) | Reply to a previous message |

**Message types** (free-form, no server-side constraint):

| Type | Intent | Typical direction |
| ---- | ------ | ----------------- |
| `update` | Work status push (the packet) | consultant -> client |
| `message` | Freeform conversation | either |
| `input` | Bug report, idea, product feedback | client -> consultant |

Threads emerge from `context_type: 'message'` references. Work item
discussions group by `context_type: 'item'`. New types require zero
server changes — type is intent, context is structure.

**Acknowledgment pattern (planned):** When a client opens a packet, the
skill POSTs `type: 'update'` with `context_type: 'message'` and
`context_ref` set to the packet message ID, to record a `packet_opened`
event locally on the consultant side. This is not yet live — `packet_opened`
is a reserved-but-unshipped kind (see the events table above and
data-integrity-0002); the flow works once that kind ships.

---

## 11. App Guide convention

Client-facing projects benefit from a structured "here's how the app
works" document. The engagement module ships a template and a plugin
skill template for this purpose.

### What it is

A markdown document with four sections — Overview, Data Model, Workflows,
Page Reference — that gives the `/guide` skill a canonical vocabulary for
answering "how does this work?" questions. Without it, Claude improvises
from code and produces jargon.

### Where things live

| Artifact | Location | Owned by |
| -------- | -------- | -------- |
| Template (starter content) | `templates/engagement/app-guide-template.md` | CC upstream |
| Plugin skill template | `templates/skills/guide/SKILL.md` | CC upstream |
| Installed guide (runtime) | `guide/app-guide.md` (in the client plugin) or `.claude/cabinet/app-guide.md` | Project |

### How to use

1. Copy `app-guide-template.md` into your client plugin's `guide/`
   directory (or `.claude/cabinet/` for non-plugin projects).
2. Fill in the four sections using the client's domain vocabulary.
3. Copy `templates/skills/guide/SKILL.md` into the plugin's `skills/`
   directory so the client can run `/guide`.

### Staleness detection

The change-impact checklist's `knowledge-layer` dimension (in
`qa-dimensions-template.yaml`) fires when user-facing files change and
prompts a guide review. The debrief `checklist-feedback` phase proposes
adding checks when bugs slip through uncovered. Together these keep the
guide current without manual remembering.

### Consultant-side management (planned)

A `/collab-consultant guide` subcommand for creating, editing, and
reviewing guide content is planned but not yet built. Until then,
edit the guide file directly.

---

## 12. Setup-walkthrough item fields

Checklist items in `engagement.yaml` sections support optional fields
used by the `/setup-accounts` skill for guided account-creation
walkthroughs. These fields extend the base item schema (key, prompt,
kind, help, options, visibility) — all are optional and the skill
degrades gracefully without them.

| Field | Type | Purpose |
| ----- | ---- | ------- |
| `signup_url` | string | Landing/signup page URL — opened in the client's default browser at item entry |
| `billing` | string or object | Cost context. String: `"$20/mo (your app server)"`. Object: `{ cost, payment_required, at_scale }` |
| `permissions` | string or object | Access scope. String: `"Member role"`. Object: `{ role, can, cannot, revoke }` |
| `time_estimate` | string | How long the setup takes — e.g., "10 minutes" |
| `screenshots` | string[] | URLs (typically Google Drive shareable links) to reference screenshots |
| `delegate_instructions` | string | Pre-written delegation email body text |
| `defer_consequence` | string | What won't work without this item — shown when client defers |
| `depends_on` | string | Flat dependency — item key that must be answered before this item appears |

`content_version` is an **engagement-level** field (under the
`engagement:` block), not a per-item field. Bumped when the content
changes materially; used as a sync guard between root and plugin copies.

### `billing` field formats

**String (simple):**
```yaml
billing: "$20/mo Pro plan (includes 8GB RAM, covers expected traffic)"
```

**Object (structured):**
```yaml
billing:
  cost: "$20/month minimum (Pro plan)"
  payment_required: "Yes — credit card required at signup"
  at_scale: "Expect $20-35/month for typical traffic"
```

The skill renders string billing in the overview table directly. For
object billing, it uses `cost` in the overview table and shows
`payment_required` and `at_scale` in the per-item detail view.

### `permissions` field formats

**String (simple):**
```yaml
permissions: "Member role — can deploy and view logs, cannot delete the project"
```

**Object (structured):**
```yaml
permissions:
  role: "Member"
  can: "deploy, view logs, manage environment variables"
  cannot: "delete the project, manage billing"
  revoke: "Remove from People page after project handoff"
```

### `depends_on` field

Flat sequential dependency. The item is hidden from the walkthrough
until its dependency has an answer in state. Different from the nested
`visibility: { depends_on, value_in }` format — flat `depends_on`
gates on any answer (not a specific value).

```yaml
- key: railway_github_access
  prompt: "Connect GitHub to Railway"
  kind: confirm
  depends_on: railway_account
```

### `signup_url` field

The landing or signup page for the service being created. When present,
the `/setup-accounts` skill opens this URL in the client's **default
browser** (via the OS open command) at item entry — before the step
loop begins. This is a navigation aid only; the skill never types,
clicks, submits, or auto-fills in the browser.

```yaml
signup_url: "https://railway.com"
```

### `help` field formats

The `help` field doubles as step-by-step instructions. Two formats are
supported:

**String form (original):** A block scalar with numbered lines. The
skill parses numbered lines as individual walkthrough steps.

```yaml
help: |
  1. Go to railway.com (not railway.app)
  2. Click "Sign in" and enter your email
  3. Check your inbox for a 6-digit code
```

**Structured list form:** Each entry is a step object with required
`text` and optional `url`. Per-step `url` is opened in the client's
default browser when that step is presented.

```yaml
help:
  - text: "Click 'Sign in' (not 'Sign Up') and enter your email"
  - text: "Check your inbox for a 6-digit code and enter it"
  - text: "Accept the Terms of Service (two-step)"
  - text: "Go to People in the sidebar"
    url: "https://railway.com/project/settings/members"
  - text: "Click Invite → enter consultant email → set role to Member"
```

Per-step `url` works best for post-login destinations with stable
addressable pages (People/Invite, API-tokens, Billing settings). Steps
within a wizard flow (e.g. "enter the 6-digit code") typically have no
addressable URL and should omit `url`. Auth-gated deep-links may
redirect to login if the client hasn't signed in yet — this is expected
and the skill handles it gracefully (the client signs in, then arrives
at the target page).

### Browser navigation (optional)

URLs from `signup_url` and per-step `url` fields open in the client's
**default browser** via the OS open command (`open` on macOS,
`xdg-open` on Linux, `start ""` on Windows). This is never an
automation-controlled browser — the client uses their own browser with
their own cookies, fingerprint, and login state. No Playwright, no
MCP server, no Chromium download, no client-side dependency.

If the open command is unavailable or errors, the skill falls back to
displaying the URL as a clickable link — zero breakage.

The skill only opens pages. It never types, clicks, submits, or
auto-fills in the browser. The client performs every interaction. This
constraint is intentional: automation-controlled browsers on third-party
signup pages trigger anti-bot detection (Cloudflare Turnstile,
reCAPTCHA) and risk leaking on-screen secrets into the conversation
transcript via page snapshots.

### Full example

```yaml
- key: railway_account
  prompt: "Create a Railway hosting account"
  kind: credential
  signup_url: "https://railway.com"
  help:
    - text: "Click 'Sign in' (not 'Sign Up') and enter your email"
    - text: "Check your inbox for a 6-digit code and enter it"
    - text: "Accept the Terms of Service (two-step)"
    - text: "Go to People in the sidebar"
      url: "https://railway.com/project/settings/members"
    - text: "Click Invite → enter consultant email → set role to Member"
  billing:
    cost: "$20/month minimum (Pro plan)"
    payment_required: "Yes — credit card required at signup"
    at_scale: "Expect $20-35/month for typical traffic"
  permissions:
    role: "Member"
    can: "deploy, view logs, manage environment variables"
    cannot: "delete the project, manage billing"
  time_estimate: "10 minutes"
  screenshots:
    - "https://drive.google.com/file/d/abc123/view"
    - "https://drive.google.com/file/d/def456/view"
  delegate_instructions: |
    Create a Railway account at railway.com. Use your work email.
    After signup, go to People in the sidebar and invite
    oren.michael.magid@gmail.com as a Member.
    Give the API token to Ed directly — do not email it.
  defer_consequence: "The web application cannot be deployed without hosting."
```

---

## 13. Consultant dashboard data model

The `/collab-consultant` dashboard (default subcommand) computes three
views from engagement events — all derived from existing data, no new
tables.

### Response matrix (per-user)

Attributed to **individual users** (Ed, Sarah), not roles. Each row:

| Field | Source |
| ----- | ------ |
| Last seen | Most recent `packet_opened` or `client_feedback` event by this author |
| Items awaiting | Items in `needs_you` for this user's audience scope with no `client_feedback` |
| Response rate | (items with feedback / total items sent) across last 3 packets, excluding FYIs |
| Days quiet | Days since any event by this author |

### Credential progress

Cross-reference `needs:credential`-tagged actions with `client_feedback`
events whose body starts with `[credential]` or `[provided]`. Show
fulfilled (author + date) vs pending.

### Quiet engagement detection

Per-user staleness threshold: `engagement.yaml` key `staleness_days`
(default 7). When `days_quiet >= staleness_days` for any user, surface
a warning with last activity details. When ALL users exceed the
threshold, escalate the warning.

---

## Known limitations

- **Single machine, single session.** The engagement store is one local
  pib.db plus `engagement-packets/` (gitignored). Multi-machine use
  requires syncing both out-of-band.
- **v8 upgrade: pre-existing events become invisible.** The visibility
  column defaults to `'internal'`. Events created before v8 (e.g.,
  `status_push` notes intended for the client) will not appear in the
  messages feed after upgrade. If needed, manually update historical
  events: `UPDATE engagement_events SET visibility = 'client' WHERE
  kind IN ('status_push','note') AND created_at < '<upgrade-date>'`.

## See also

- `templates/engagement/sql-constants.mjs` — canonical engagement_events DDL.
- `scripts/pib-db-schema.sql`, `scripts/pib-db-lib.mjs` — the schema and
  library functions.
- `templates/cabinet/pib-db-access.md` — MCP/CLI access protocol.
