# Chapter Workflow — Behaviour Graph v0

**Status:** Locked — Task 6 of Behaviour Graph v0 prep plan.
**Scope:** Defines the full per-chapter processing cycle, from pre-flight hydration
through lock. Follow every phase in order. Do not merge or skip phases.

**Reference docs:**
- `protocols/extraction.md` — 2-stage gap-driven extraction, node-type rules, IP-clean rule
- `protocols/edge-cheatsheet.md` — 10 edge types, coverage sanity check
- `protocols/adversarial-reviewer.md` — independent subagent brief
- `voice/kai-voice-persona.md` — voice register for every `kai_voice_draft`
- `templates/_chapter.md` — fillable chapter skeleton

---

### Phase 1: Pre-flight

**Goal:** Hydrate working memory with everything prior chapters established before
touching the new chapter source.

**Actions:**
1. Read every locked chapter artifact: `chapters/00-intro.md` through
   `chapters/(N-1)-*.md` (skip if no prior chapters — as in the ch.0 dry-run).
2. From each, extract and note: all node ids and titles, all `corrects` pairs
   (principle id ↔ anti-pattern id), all canonical `user_state` ids, any
   `forward-reference` gap-list entries that point to this chapter.
3. Pull MemPalace drawers tagged with prior chapter ids (wing: `pivot_salepoint`,
   room: `kai_coach_kb`) for any artifact body you may need to cross-reference.
4. Read `project_kai_blind_spot_register.md` in the memory directory
   (`C:\Users\Dokot\.claude\projects\c--Users-Dokot-github-wefi\memory\`) —
   apply any recovery rules from prior chapters before you begin.
5. Summarise into a 1-page working note `pre-flight-N.md` (working directory only,
   not committed): existing state spine, named principles, recurring anti-patterns,
   voice samples that worked, flagged forward-references from prior gap-lists.

**Output:** `pre-flight-N.md` working note. Deleted once the chapter locks (Phase 9).

**Gate to Phase 2:** No unresolved forward-reference flags from prior chapters have been silently skipped. (Prior canon summary should be scannable in ≤ 2 minutes; if it isn't, the summary is too long — that's a hint, not a gate condition.)

---

### Phase 2: Stage 1 Extraction

**Goal:** Emit all nodes and edges from the chapter source in one forward pass.

**Tool:** Read the chapter from the source PDF directly
(`.kiro/specs/pivot-salepoint/resources/go-pro-7-steps-to-becoming-a-network-marketing-professional-978-0-9886679-1-4.pdf`)
using the `Read` tool with the `pages:` parameter. Do NOT rely on existing
`.txt` re-chunks in `rag-corpus/` — re-read from the PDF.

**Fallback for PDF-read failures:** If `Read` cannot parse the PDF (e.g., complex layout, font issues), use Bash with `pdftotext -layout -f <start> -l <end> <pdf-path> -` to extract the page range as plain text. This was the working fallback identified during the ch.0 dry-run.

**Actions:**
1. Open a blank copy of `templates/_chapter.md` as `chapters/XX-<name>.md`.
   Fill in the frontmatter (id, title, source_pages, status: `draft`).
2. Read the chapter sequentially. For every paragraph (or tight group of related
   paragraphs) carrying substantive content, emit one or more artifact nodes.
   Apply the node-type decision rules from `protocols/extraction.md §2` — stop
   at first match.
3. For each emitted node, fill all required fields per spec §3.3 and the
   exemplar entries in `templates/_chapter.md`. Set `source_ref` on every node
   (format: `ch.XX p.NN para.N | "<≤30-word verbatim snippet>"`).
4. Write `kai_voice_draft` for every node in the voice register from
   `voice/kai-voice-persona.md`. Check against the negative vocab list (§4)
   before committing each draft.
5. Emit edges as you encounter them; record them in the node's `linked_*` fields.
   Consult `protocols/edge-cheatsheet.md` before emitting any non-obvious edge.
6. Prefer over-emission to under-emission at this stage. A node that survives
   Phase 3 unchanged is less expensive than a missed artifact discovered in Phase 4.

**Output:** `chapters/XX-<name>.md` with all node sections populated; `# gap_list`
section left empty for now.

**Gate to Phase 3:** Every paragraph in the chapter is either (a) emitted as a draft node citing it via `source_ref`, or (b) explicitly noted in your working session as a Stage 2 deferral. No paragraph is silently passed.

---

### Phase 3: Stage 2 Gap Audit

**Goal:** Make extraction coverage verifiable — every paragraph is accounted for.

**Tool:** Yourself, re-walking the chapter source alongside the Phase 2 draft.

**Actions:**
1. Re-read the chapter from the same PDF source, paragraph by paragraph.
2. For each paragraph: check whether it is cited in any node's `source_ref` field.
3. If yes — no gap-list entry needed; move on.
4. If no — assign one canonical reason tag from `protocols/extraction.md §5`:
   `restatement-of-<id>`, `anecdote`, `transitional`, `recap`, `meta-commentary`,
   or `forward-reference`.
5. If no canonical tag fits and the paragraph carries substantive content — stop.
   Return to Phase 2 and emit the missing artifact before continuing.
6. Append each tagged entry to the `# gap_list` section of the chapter file in the
   format: `- [ch.XX p.NN para.N] <reason-tag>: <one-sentence explanation if needed>`.

**Output:** Completed `# gap_list` section in `chapters/XX-<name>.md`. Every
paragraph is either an artifact or a tagged gap-list entry.

**Gate to Phase 4:** Stopping condition from `protocols/extraction.md §6` is met —
no paragraph left without an artifact id or a canonical gap-list tag.

---

### Phase 4: Adversarial Review

**Goal:** Independent review of the chapter draft by a fresh reviewer with no extractor context. **Dispatched by the main session controller**, NOT by the extractor subagent — the extractor's role ends after Stage 2 (Phase 3); the controller takes over for Phase 4.

**Actions:**

1. **Main session orchestration.** The controller (the session that produced this plan execution) dispatches a fresh Explore subagent for adversarial review. The extractor subagent does NOT attempt to dispatch sub-subagents — `Agent` tool may not be available from within a subagent context, and self-administered review breaks the independence guarantee.

2. **Subagent dispatch** (controller-side):

   ```
   Agent tool with subagent_type=Explore
   Prompt: contents of `protocols/adversarial-reviewer.md`, with the per-chapter inputs filled in:
     - Source PDF + page range (from chapter frontmatter `source_pages`, set in Phase 2 Step 1 — do not re-derive)
     - Extractor's draft: `chapters/XX-name.md`
     - Reference docs: `protocols/extraction.md`, `protocols/edge-cheatsheet.md`, `voice/kai-voice-persona.md`
   ```

3. **Result capture.** Subagent returns a markdown flag list per the adversarial-reviewer.md output format. Save the flag list to `protocols/adversarial-flags-ch.XX.md` for audit traceability.

4. **No silent passes.** If the subagent returns BLOCKED, NEEDS_CONTEXT, or zero flags with no rationale — surface to Dmitry rather than accept; an empty result is suspicious.

**Re-run rule:** If Phase 5 (resolution) modifies more than 20% of the chapter's
nodes — re-dispatch the adversarial subagent on the updated draft before proceeding
to Phase 6. A substantially-changed draft warrants a fresh independent read.

**Output:** `protocols/adversarial-flags-ch.XX.md` containing the flag list.
Zero flags is a valid result.

**Gate to Phase 5:** Subagent has returned a flag list (any length, including zero).
An empty or non-returned response is not acceptable — rerun if the subagent fails
to produce output.

---

### Phase 5: Resolution

**Goal:** Every flag from Phase 4 is either fixed or explicitly dispositioned.

**Tool:** Yourself, editing `chapters/XX-<name>.md` and annotating the flag log.

**Actions:**
1. For each flag in `protocols/adversarial-flags-ch.XX.md`:
   - **Fix path:** Edit the chapter draft — add the missed node, correct the
     paraphrase drift, fix the voice register violation, fill the gap-list entry.
     Mark the flag as `resolved-fix` in the flag log.
   - **Deliberate path:** If the flag reflects a legitimate editorial choice, add
     a one-sentence reason in the chapter's `# review_state` section and mark
     the flag as `resolved-deliberate: <reason>` in the flag log.
2. No flag may be silently ignored. Every flag line in the flag log receives one
   of: `resolved-fix`, `resolved-deliberate: <reason>`, or (if genuinely
   ambiguous) `escalate-to-dmitry`.
3. If you fix more than 20% of nodes — trigger the Phase 4 re-run rule before
   proceeding to Phase 6.

**Output:** Updated `chapters/XX-<name>.md`; `protocols/adversarial-flags-ch.XX.md`
with every flag dispositioned.

**Gate to Phase 6:** Zero unresolved flags. Every flag line has a disposition.
If re-run was triggered (>20% node change), the second adversarial pass also has
zero unresolved flags.

---

### Phase 6: Post-flight

**Goal:** Schema validation, global dedup, gap-list audit, and blind-spot register
update before the chapter goes to validators.

**Tool:** Yourself, running the checklist below against the chapter file.

**Actions:**

**Schema-validation checklist — all items must pass:**

1. **Every node has all required fields per spec §3.3.** The authoritative per-type field list lives in `templates/_chapter.md`. Use the template exemplar entry for each node type as the field-coverage checklist. If a node's required field is missing or empty — fail.
2. Every edge references two existing node ids — either within the chapter or via
   `# cross_chapter_links` citing a locked prior chapter's node.
3. Every artifact id is unique within the chapter AND globally across all locked
   chapters (cross-check against the pre-flight-N.md node-id list).
4. Every `kai_voice_draft` is within persona constraints — no negative-vocab phrase
   from `voice/kai-voice-persona.md §4`.
5. Gap-list has only the six canonical tags from `protocols/extraction.md §5`.
   No free-text tags, no unrecognised strings.
6. **Validation scenarios reference only existing node ids.** For each scenario in
   `# validation_scenarios`, parse the step text for node-id mentions (`S-*`,
   `L-*`, `P-*`, `AP-*`, `Sc-*`). Each must exist either in this chapter or in
   a prior locked chapter. Stale node-id references → flag.
7. Every `source_ref` verbatim snippet is ≤ 30 words. Count any near-boundary
   entries (approximately 28–32 words) and trim if needed.

**Dedup check:**
8. Cross-reference new node ids and titles against locked chapters. Flag any
   near-duplicate (same title or body substance appearing in a prior chapter)
   for human review. Do not auto-merge — surface to Dmitry with both node ids.

**Blind-spot register update:**
9. If Phase 5 resolution produced any new class of error not previously documented,
   append an entry to `project_kai_blind_spot_register.md` in the memory directory
   (`C:\Users\Dokot\.claude\projects\c--Users-Dokot-github-wefi\memory\`) using
   the schema: date/chapter, class of error, trigger, recovery rule.

**Output:** Post-flight checklist marked all-pass (inline in `# review_state`), OR
a specific list of failures with node ids. On failure — fix and re-run the checklist.

**Gate to Phase 7:** All checklist items pass (schema validation, dedup check, blind-spot register update). Any failure → return to Phase 5 (Resolution) before retrying Phase 6.

---

### Phase 7: FigJam Canvas Population

**Goal:** Render this chapter's artifacts onto a per-chapter FigJam canvas in the
spatial convention from spec §9.

**Tool:** Figma MCP (`mcp__claude_ai_Figma__use_figma`, `mcp__claude_ai_Figma__create_new_file`).
Load the `/figma-use` skill before calling `use_figma`. Canvas URLs are recorded
in `.kiro/specs/anakai-kai-coach/canvases.md` (created in Task 10).

**Actions:**

0. **Load required Figma skill.** Call `Skill skill=figma-use` before any other Figma MCP invocation. This is mandatory per the Figma MCP system instructions; skipping it will cause `use_figma` to fail.

1. Create (or duplicate) a per-chapter canvas:
   name it `Behaviour Graph v0 — Ch.XX <name>`.
2. Populate the canvas per the spatial convention (spec §9):
   - Header: chapter title, scope, gap-list link.
   - State-spine left-to-right: `user_state` nodes in journey order.
   - Loops beneath their triggering state; principles and scripts nested under loops;
     anti-patterns paired with their correcting principles.
   - Sidebar right: voice persona reminder, validation scenarios 1–N, gap-list link.
   - Voice-sample boxes tagged by brand pillar (Ambition / AI / Community).
3. Record the canvas URL in `canvases.md` under a new entry for this chapter.

**Plan-tier note (added 2026-06-09 per ch.0 dry-run):** Figma Starter plan limits MCP tool calls per session. Plan the canvas population as a *single* `use_figma` call containing all shapes + connectors + text — incremental calls each count against the quota. The ch.0 attempt followed this pattern; the failure was that the prior `create_new_file` call also counted against the quota and the populate hit the ceiling. If quota is exhausted mid-chapter, the canvas file exists but is empty; record this in `canvases.md` and surface to Dmitry rather than silently fail.

**Verification limitation.** `mcp__claude_ai_Figma__get_metadata` rejects FigJam-board URLs. Machine-verification of canvas content is not available; rely on visual inspection after the canvas is opened. Confirm by spot-loading the canvas URL in a browser, or accept the populate-call's success response as the canvas-write proof.

**Output:** Per-chapter FigJam canvas populated. Canvas URL recorded in `canvases.md`.

**Gate to Phase 8:** Canvas is visually inspectable:
- State-spine present and ordered.
- Loops, principles, scripts, anti-patterns nested correctly.
- Sidebar contains validation scenarios and persona reminder.
- Voice-sample boxes tagged by pillar.
- Canvas URL committed in `canvases.md`.

---

### Phase 7b: MemPalace + KG Population

**Goal:** File this chapter's artifacts into the MemPalace `kai_coach_kb` room and add the edge relationships as KG triples.

**Tool:** MemPalace MCP (`mcp__mempalace__mempalace_add_drawer`, `mcp__mempalace__mempalace_kg_add`, `mcp__mempalace__mempalace_list_drawers`, `mcp__mempalace__mempalace_kg_stats`).

**Actions:**

1. For each node in the chapter (states, loops, principles, anti-patterns, scripts), call `mempalace_add_drawer`:
   - `wing: pivot_salepoint`
   - `room: kai_coach_kb`
   - `source_file: .kiro/specs/anakai-kai-coach/chapters/XX-<name>.md`
   - `content`: first line = `artifact_id: <id> — <title>`, second line = `tags: [artifact_id:<id>, ch-X, <node_type>, draft]`, followed by full artifact content (title / body / source_ref / kai_voice_draft / voice_context_tags / linked_* / notes). See `protocols/mempalace-convention.md`.

2. For each edge in the chapter (within-chapter and cross-chapter outbound), call `mempalace_kg_add`:
   - `subject: <source artifact id>`
   - `predicate: <mapped predicate from protocols/kg-predicates.md>`
   - `object: <target artifact id>`
   - `valid_from: <today's date YYYY-MM-DD>`

3. **Verification (added 2026-06-09 per ch.0 dry-run lessons):**
   - Run `mempalace_list_drawers wing=pivot_salepoint room=kai_coach_kb limit=100` and confirm the count grew by the chapter's node count (existing baseline + N nodes).
   - Run `mempalace_kg_stats` and confirm the triple count grew by the chapter's edge count.
   - Any mismatch → identify which drawers / triples failed to write and re-attempt.

4. **Retroactive forward-reference triples.** If the chapter's `cross_chapter_links` includes any edge whose target id is a placeholder (e.g., `L-02-XX`, `L-XX-YY`) because the target chapter is not yet extracted: do NOT emit a KG triple. Instead, log the pending triple in this chapter's lessons-learned doc under "Retroactive triples pending". When the target chapter is extracted, its Phase 7b retroactively emits the pending triples from prior chapters. Source: ch.1 dry-run identified `L-01-05 precedes L-02-XX` as the first such case.

**Output:** N drawers + M triples in MemPalace, verified by count match.

**Gate to Phase 8:** Verification counts match. If the figma canvas was blocked (per Phase 7 plan-tier note), MemPalace + KG carry the chapter's structure for validator review fallback.

---

### Phase 8: Validator Handoff

**Goal:** Surface the chapter to Roma (operational truth) and Maks (brand/voice)
and record their signoff state.

**Tool:** Slack MCP (`mcp__slack__slack_post_message` or `slack_reply_to_thread`).
Channels: `#anakai` (C0ATP78D257) for Maks; Roma's direct channel per memory.
Slack user IDs available in the memory entry `reference_slack_anakai_channels.md`.

**Actions:**
1. Update the chapter frontmatter:
   - `validators_signoff.roma: pending`
   - `validators_signoff.maks: pending`
   Record today's date as the handoff date in `# review_state`.
2. Post to the relevant Slack channels with:
   - Chapter title and id.
   - FigJam canvas URL (from `canvases.md`).
   - Roma's ask: operational truth review (do the scripts + loops reflect how
     the business actually works?).
   - Maks's ask: brand/voice review (do the `kai_voice_draft` fields match
     the Anakai register?).
3. Monitor for responses. When Roma or Maks replies:
   - `signed` → update frontmatter `validators_signoff.<reviewer>: signed`.
   - `revisions-requested` → return to Phase 5 (Resolution) to address their notes. After Phase 5 closes, **re-run Phase 6 (Post-flight)** to verify schema integrity wasn't broken by the revisions. THEN re-notify the validator with the corrected canvas. Never re-notify without an intervening Phase 6 pass.

**Timeout rule (v0):** No formal SLA. If either reviewer has not responded within
7 days, escalate to Dmitry.

**Output:** Chapter frontmatter updated with both validators' current signoff state.
Slack notifications sent.

**Gate to Phase 9:** Both `validators_signoff.roma` and `validators_signoff.maks`
are `signed`. If either returns `revisions-requested` — resolve in Phase 5, then
re-run the post-flight checklist (Phase 6) before re-notifying the validator.

---

### Phase 9: Lock

**Goal:** Seal the chapter as a stable, non-editable artifact that feeds the next
chapter's pre-flight.

**Tool:** Git (commit). MemPalace MCP to update drawer tags.

**Actions:**
1. Confirm all Phase 8 gate conditions are met (both validators signed, all
   Phase 6 checklist items pass).
2. Set `locked: true` in the frontmatter AND in the `**Locked:**` line of
   `# review_state` (keep machine-readable and human-readable in sync).
3. Set `status: locked` in the frontmatter.
4. Update all MemPalace drawers for this chapter's nodes:
   change the `status` tag from `draft` or `reviewed` to `locked`
   (wing: `pivot_salepoint`, room: `kai_coach_kb`).
5. Commit the chapter file, flag log, and any updated `canvases.md`:
   ```bash
   git add .kiro/specs/anakai-kai-coach/chapters/XX-<name>.md \
           .kiro/specs/anakai-kai-coach/protocols/adversarial-flags-ch.XX.md \
           .kiro/specs/anakai-kai-coach/canvases.md
   git commit -m "Lock ch.XX <name> — all validators signed, post-flight clean"
   ```
6. Delete the working `pre-flight-N.md` note (it is no longer needed).
7. If MEMORY.md is stale with respect to this chapter's completion (e.g., a
   project state entry references it as in-progress), update it now.

**Output:** Chapter file with `locked: true` committed. MemPalace drawers tagged
`status: locked`. Pre-flight working note deleted.

**Gate:** This chapter no longer accepts edits without an explicit unlock decision
(requires Dmitry sign-off). It is now a stable input for the next chapter's Phase 1
pre-flight.

*Unlock process v0:* not formalised. If a locked chapter needs edits, surface to Dmitry; mechanics TBD.
