---
phase: 10-user-guide-content
plan: 03
type: execute
wave: 2
depends_on:
  - 10-02
files_modified:
  - docs/agentic-workflows.md
  - docs/llms-full.txt
autonomous: true
requirements:
  - UGDE-04
  - UGDE-05

must_haves:
  truths:
    - "A reader can follow each of the 3 recipe walkthroughs (research-capture, review-triage, knowledge-synthesis) step-by-step with exact commands and expected output"
    - "A reader understands the human-driven session lifecycle: start → work → log entries → close with enrichment pipeline"
    - "A reader understands the agent-driven session lifecycle: MCP tool calls → structured context → automated enrichment"
    - "The session close enrichment pipeline (5 steps in exact order) is explained with what each step does and how to read the close result"
    - "llms-full.txt is regenerated to include plugins.md content from Plan 02"
  artifacts:
    - path: "docs/agentic-workflows.md"
      provides: "Expanded agentic workflows with recipe walkthroughs and session lifecycle guides"
      min_lines: 380
      contains:
        - "## Recipe Walkthroughs"
        - "research-capture"
        - "review-triage"
        - "knowledge-synthesis"
        - "## Human-Driven Session"
        - "## Agent-Driven Session"
        - "LOG CLOSE"
        - "CROSS-SESSION REWEAVE"
        - "ORPHAN SWEEP"
        - "INTEGRITY CHECK"
        - "GRAPH MATERIALIZATION"
    - path: "docs/llms-full.txt"
      provides: "Regenerated agent corpus including plugins.md"
      contains: "Built-in Plugins"
  key_links:
    - from: "docs/agentic-workflows.md recipe section"
      to: "ztlctl://recipes/research-capture"
      via: "URI reference in text"
      pattern: "ztlctl://recipes"
    - from: "docs/agentic-workflows.md session lifecycle"
      to: "session close enrichment pipeline"
      via: "step-by-step numbered list"
      pattern: "LOG CLOSE.*CROSS-SESSION REWEAVE.*ORPHAN SWEEP"
---

<objective>
Expand docs/agentic-workflows.md from its current 192 lines to 380+ lines by adding:
1. Three complete recipe walkthroughs (research-capture, review-triage, knowledge-synthesis) with step-by-step commands and expected output (UGDE-04)
2. Session lifecycle guides for both human-driven and agent-driven usage, with concrete examples and a detailed explanation of the 5-step close enrichment pipeline (UGDE-05)

Then regenerate docs/llms-full.txt to incorporate the new plugins.md page added in Plan 02.

Purpose: The current agentic-workflows.md describes features without telling a narrative story about how to use them together. The three MCP recipe resources are not mentioned at all. The session close enrichment pipeline is listed but not explained. Users — especially those using agents — cannot understand what a complete end-to-end workflow looks like from the docs alone.

Output: Expanded docs/agentic-workflows.md, regenerated docs/llms-full.txt.
</objective>

<execution_context>
@/Users/shparki/.claude/get-shit-done/workflows/execute-plan.md
@/Users/shparki/.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/phases/10-user-guide-content/10-CONTEXT.md
@.planning/phases/10-user-guide-content/10-RESEARCH.md
@.planning/phases/10-user-guide-content/10-02-SUMMARY.md
</context>

<interfaces>
<!-- Exact recipe step sequences from src/ztlctl/mcp/resources.py -->

Recipe 1 — research-capture:
  Description: "Capture research findings — search existing content, create synthesis notes, link evidence"
  Step 1: search(query={topic}, limit=10) — always
  Step 2: create_note(title={synthesis_title}, maturity=seed) — skip if step 1 already has note with identical title
  Step 3: reweave(content_id={step_2.content_id}) — always

  Human CLI equivalent:
    ztlctl query search "oauth security" --limit 10
    ztlctl create note "OAuth Security Patterns" --maturity seed
    ztlctl reweave --id ztl_<new_id>

Recipe 2 — review-triage:
  Description: "Triage the work queue — inspect items, update stale notes, archive completed or obsolete ones"
  Step 1: work_queue() — always — returns prioritized list of actionable items
  Step 2: get_document(content_id={step_1.items[N].id}) — repeat for each item in work queue
  Step 3: update(content_id={step_2.id}, changes={}) — skip if item needs no changes
  Step 4: archive(content_id={step_2.id}) — only if item is complete or stale beyond recovery

  Human CLI equivalent:
    ztlctl query work-queue
    ztlctl query get TASK-0001
    ztlctl update TASK-0001 --maturity budding
    ztlctl archive TASK-0001

Recipe 3 — knowledge-synthesis:
  Description: "Synthesize knowledge from existing content — search, find gaps, draft a synthesis note, reweave connections"
  Step 1: search(query={topic}, limit=20) — always
  Step 2: gaps(top=10) — always — finds structurally under-connected areas
  Step 3: draft_from_topic(topic={topic}, target=note) — skip if step 1 already returned a mature synthesis note
  Step 4: reweave(content_id={step_3.content_id}) — always

  Human CLI equivalent:
    ztlctl query search "distributed systems" --limit 20
    ztlctl graph gaps --top 10
    ztlctl query draft --topic "distributed-systems" --target note
    ztlctl reweave --id ztl_<draft_id>

Recipe URIs:
  ztlctl://recipes — index of all recipes
  ztlctl://recipes/research-capture
  ztlctl://recipes/review-triage
  ztlctl://recipes/knowledge-synthesis

<!-- Exact session close pipeline from src/ztlctl/services/session.py -->

Session close pipeline (in exact order):
  Step 1 — LOG CLOSE: Updates session node status="closed", inserts session_close log entry. All in one transaction.
  Step 2 — CROSS-SESSION REWEAVE (guarded by cfg.close_reweave): Queries all notes/references with session==session_id and archived==0. Runs ReweaveService.reweave() on each. Returns total links created.
  Step 3 — ORPHAN SWEEP (guarded by cfg.close_orphan_sweep): Finds ALL notes/references with zero outgoing edges (not just session notes). Runs reweave with min_score_override=settings.session.orphan_reweave_threshold (default 0.2). Lower threshold means orphans get links they wouldn't normally qualify for.
  Step 4 — INTEGRITY CHECK (guarded by cfg.close_integrity_check): Runs CheckService.check(). Counts error-severity issues. Appends warning if any found. Does NOT auto-fix — only reports.
  Step 5 — GRAPH MATERIALIZATION (always runs, no guard): Calls GraphService.materialize_metrics(). Updates PageRank, degree, betweenness centrality for all nodes.
  Step 6 — EVENT DISPATCH: Fires post_session_close event with stats payload. Drains event bus before returning.

Session close result JSON:
  {
    "session_id": "LOG-0001",
    "status": "closed",
    "reweave_count": 7,
    "orphan_count": 2,
    "integrity_issues": 0
  }

Session config fields:
  close_reweave = true
  close_orphan_sweep = true
  close_integrity_check = true
  orphan_reweave_threshold = 0.2
</interfaces>

<tasks>

<task type="auto">
  <name>Task 1: Add recipe walkthroughs and session lifecycle guides to agentic-workflows.md</name>
  <files>docs/agentic-workflows.md</files>

  <read_first>
    - docs/agentic-workflows.md — current 192-line content (keep all existing content, add new sections)
    - docs/tutorial.md — tone gold standard (sentence → code block → outcome note)
    - docs/plugins.md — cross-reference for reweave and session behavior
  </read_first>

  <action>
Expand docs/agentic-workflows.md from 192 lines to 380+ lines. All existing content must be preserved verbatim. Add the following new sections in this order:

**INSERT AFTER the existing "MCP Server Integration" section and BEFORE "Batch Operations":**

---

### NEW SECTION: ## Recipe Walkthroughs

Add this new top-level section (H2) after MCP Server Integration.

```markdown
## Recipe Walkthroughs

ztlctl exposes three structured workflow recipes via MCP. Each recipe is a sequence of tool calls that accomplishes a common knowledge-work task. Recipes are designed for agent-driven execution but every step has a human CLI equivalent.

Access recipes via MCP resource discovery:

```bash
# Discover available recipes
ztlctl://recipes
```

Or access individual recipe specs directly in your MCP client:
- `ztlctl://recipes/research-capture`
- `ztlctl://recipes/review-triage`
- `ztlctl://recipes/knowledge-synthesis`
```

Then add all three recipe subsections below.

**Recipe 1 subsection:**

```markdown
### Recipe 1: Research Capture

**What it accomplishes:** Search existing knowledge for a topic, create a synthesis note for new findings, and automatically connect it to related content via reweave.

**When to use:** When an agent (or you) has gathered research on a topic and wants to turn it into a durable knowledge artifact linked to existing context.

**Steps:**

| Step | Action | Condition |
|------|--------|-----------|
| 1 | Search existing content for the topic (limit 10) | Always |
| 2 | Create a seed note with the synthesis title | Skip if step 1 already has a note with the same title |
| 3 | Reweave the new note against existing content | Always |

**Human CLI walkthrough:**

```bash
# Step 1: Check if you already have related content
ztlctl query search "oauth security" --limit 10

# Expected output (if no related notes yet):
# No results for "oauth security"

# Step 2: Create a synthesis note
ztlctl create note "OAuth Security Patterns" --maturity seed --tags "auth/oauth,security"

# Expected output:
# ✓ Created note ZTL-0042: OAuth Security Patterns [seed]
# ✓ Reweave: 3 links created (auto-triggered by Reweave plugin)

# Step 3: Manual reweave if needed (already ran automatically above)
# ztlctl reweave --id ZTL-0042
```

!!! tip
    The Reweave plugin runs automatically after `create note`, so step 3 is already done for you. Run `ztlctl reweave --id {id}` manually only if you disabled auto-reweave or want to re-run after adding more related content. See [Built-in Plugins](plugins.md) for Reweave configuration.

**Agent MCP tool sequence:**
```
1. search(query="oauth security", limit=10)
2. create_note(title="OAuth Security Patterns", maturity="seed")
3. reweave(content_id=<step_2_id>)
```
```

**Recipe 2 subsection:**

```markdown
### Recipe 2: Review Triage

**What it accomplishes:** Surface the current work queue, inspect each actionable item, update stale notes, and archive completed or obsolete ones.

**When to use:** Periodic review — clearing the backlog, promoting mature notes, archiving abandoned tasks.

**Steps:**

| Step | Action | Condition |
|------|--------|-----------|
| 1 | Get the full work queue | Always |
| 2 | Fetch each item's full content | Repeat for each work queue item |
| 3 | Update items that need changes | Skip if item is already current |
| 4 | Archive items that are complete or irrecoverable | Only if item should not continue |

**Human CLI walkthrough:**

```bash
# Step 1: Get the prioritized work queue
ztlctl query work-queue

# Expected output (example):
# TASK-0001  "Follow up on OAuth threat model"   priority: high   maturity: seed   stale: 14 days
# TASK-0002  "Review Attention paper"             priority: medium maturity: seed   stale: 7 days
# ZTL-0035   "Token exchange trade-offs"          maturity: seed   no outgoing edges

# Step 2: Inspect a specific item
ztlctl query get TASK-0001

# Step 3: Update an item (promote maturity, add notes)
ztlctl update TASK-0001 --maturity budding

# Expected output:
# ✓ Updated TASK-0001: maturity seed → budding

# Step 4: Archive a completed item
ztlctl archive TASK-0001

# Expected output:
# ✓ Archived TASK-0001: "Follow up on OAuth threat model"
```

**Agent MCP tool sequence:**
```
1. work_queue()
2. get_document(content_id=<each_item_id>)  ← repeat per item
3. update(content_id=<id>, changes={maturity: "budding"})  ← skip if no changes needed
4. archive(content_id=<id>)  ← only if item is done or stale beyond recovery
```
```

**Recipe 3 subsection:**

```markdown
### Recipe 3: Knowledge Synthesis

**What it accomplishes:** Search a topic broadly, identify structural gaps in the knowledge graph, draft a synthesis note from the topic packet, and reweave it into the graph.

**When to use:** When you want to consolidate scattered knowledge on a topic into a single synthesis artifact that explicitly acknowledges gaps and invites future connection.

**Steps:**

| Step | Action | Condition |
|------|--------|-----------|
| 1 | Search existing content (limit 20) | Always |
| 2 | Find graph gaps — structurally isolated areas | Always |
| 3 | Draft a synthesis note from the topic packet | Skip if step 1 already has a mature (evergreen) synthesis note |
| 4 | Reweave the draft against existing content | Always |

**Human CLI walkthrough:**

```bash
# Step 1: Survey what exists on the topic
ztlctl query search "distributed systems" --limit 20

# Expected output (example):
# ZTL-0010  "CAP theorem trade-offs"        maturity: budding
# ZTL-0018  "Raft consensus algorithm"      maturity: seed
# REF-0003  "Designing Data-Intensive Apps"  maturity: evergreen

# Step 2: Find gaps — where the graph is thin
ztlctl graph gaps --top 10

# Expected output (example):
# Gap 1: "consensus" cluster — 3 notes, 1 bridge connection, no synthesis note
# Gap 2: "replication" cluster — isolated from "consistency" cluster

# Step 3: Draft a synthesis note from the topic
ztlctl query draft --topic "distributed-systems" --target note

# Expected output:
# ✓ Drafted ZTL-0055: "Distributed Systems Synthesis" [seed]
#   Sources: 8 notes, 2 references
#   Gaps surfaced: consensus ↔ replication bridge missing

# Step 4: Reweave (already ran automatically — manual run if re-running)
ztlctl reweave --id ZTL-0055
```

**Agent MCP tool sequence:**
```
1. search(query="distributed systems", limit=20)
2. gaps(top=10)
3. draft_from_topic(topic="distributed-systems", target="note")  ← skip if step 1 has mature synthesis
4. reweave(content_id=<step_3_id>)
```

!!! tip
    Recipes are starting points, not rigid scripts. An agent can modify steps based on what it finds — for example, skipping the draft step if a recent evergreen note already covers the topic.
```

---

**INSERT AFTER the new Recipe Walkthroughs section and BEFORE "Batch Operations":**

### NEW SECTION: ## Session Lifecycle

```markdown
## Session Lifecycle

Sessions are operational coordination units — they group a period of work so ztlctl can apply enrichment to everything created during that period when the session closes. Sessions are optional for human users and central to agent-driven workflows.
```

**Human-driven session subsection:**

```markdown
### Human-Driven Session

A typical 30-minute research session:

```bash
# Start a session with a topic focus
ztlctl agent session start "oauth security research"

# Expected output:
# ✓ Session started: LOG-0001 "oauth security research"
# Session is open. All notes and references created now are linked to LOG-0001.

# Capture sources as you find them
ztlctl ingest text "RFC 6749 key sections" --stdin --as reference --tags "auth/oauth"
ztlctl create note "Token exchange threat model" --tags "auth/oauth,security" --topic auth

# Log your reasoning as you go
ztlctl agent session log "Read RFC 6749 sections 4-6. Key risk: token replay via HTTP."
ztlctl agent session log "Drafted threat model. Needs peer review." --pin

# Check how much context you've accumulated (useful before asking an agent to continue)
ztlctl agent session cost --report 50000

# Close the session when done
ztlctl agent session close --summary "Mapped OAuth 2.0 attack surface"

# Expected output:
# ✓ Session closed: LOG-0001
# ✓ Cross-session reweave: 7 new links created
# ✓ Orphan sweep: 2 orphaned notes connected
# ✓ Integrity check: 0 issues
# ✓ Graph metrics updated (PageRank, degree, betweenness)
```

!!! note
    Only one session can be open at a time. If you already have an open session, `ztlctl agent session start` returns an error.
```

**Agent-driven session subsection:**

```markdown
### Agent-Driven Session

Agents use the same session commands via MCP tools. A literature review agent might:

```
# Agent starts session
agent_session_start(topic="attention mechanisms in transformers")

# Agent fetches topic context to understand what's already captured
agent_context(topic="transformers", budget=8000)

# Agent ingests retrieved sources
ingest_source(title="Attention Is All You Need", content=<paper_text>, as_type="reference")

# Agent creates synthesis notes as it reads
create_note(title="Multi-head attention intuition", maturity="seed", tags=["ml/transformers"])
create_note(title="Self-attention vs cross-attention", maturity="seed", tags=["ml/transformers"])

# Agent logs key decisions
agent_session_log("Core insight: Q/K/V projection sizes determine capacity vs. compute tradeoff", pin=True)

# Agent closes session when done
agent_session_close(summary="Surveyed attention mechanism architecture, 2 synthesis notes created")
```

The agent receives structured JSON at each step, including content IDs it can use in subsequent calls. No special agent-mode configuration is required — the same MCP tools work for both supervised and autonomous agents.
```

**Session close enrichment pipeline detailed explanation:**

```markdown
### Session Close Enrichment Pipeline

When you (or an agent) call `session close`, ztlctl runs a 5-step enrichment pipeline automatically:

```
LOG CLOSE → CROSS-SESSION REWEAVE → ORPHAN SWEEP → INTEGRITY CHECK → GRAPH MATERIALIZATION
```

**Step 1 — Log Close:** The session node is marked `status="closed"` and a `session_close` log entry is inserted. This is atomic — if it fails, no other steps run.

**Step 2 — Cross-Session Reweave** (toggle: `close_reweave`): Runs the reweave algorithm on every note and reference created during this session. New connections are discovered across the full vault — not just within the session. Returns the count of new links created.

**Step 3 — Orphan Sweep** (toggle: `close_orphan_sweep`): Finds every note and reference in the entire vault with zero outgoing edges — not just session notes. Runs reweave with a lower threshold (default: 0.2 instead of 0.6) so orphaned notes have a better chance of getting at least one connection.

**Step 4 — Integrity Check** (toggle: `close_integrity_check`): Runs the vault integrity checker. Counts error-severity issues and appends a warning to the close result. Does **not** auto-fix — only reports.

**Step 5 — Graph Materialization** (always runs): Updates PageRank, degree centrality, and betweenness centrality for all nodes in the graph. This powers rank-ordered search, bridge detection, and gap identification.

**Reading the close result with `--json`:**

```bash
ztlctl agent session close --summary "Research complete" --json
```

```json
{
  "session_id": "LOG-0001",
  "status": "closed",
  "reweave_count": 7,
  "orphan_count": 2,
  "integrity_issues": 0
}
```

- `reweave_count`: Total new graph edges created across all session notes
- `orphan_count`: Number of previously-isolated notes that received at least one connection via the orphan sweep
- `integrity_issues`: Count of error-severity integrity violations found (0 = healthy)

**Configuring the pipeline** in `ztlctl.toml`:

```toml
[session]
close_reweave = true
close_orphan_sweep = true
close_integrity_check = true
orphan_reweave_threshold = 0.2  # lower = more connections for orphans
```
```

**ALSO ADD at the very end of the file:**

```markdown
## Next Steps

- See [Built-in Plugins](plugins.md) for Git and Reweave plugin configuration
- See [Knowledge Paradigms](paradigms.md) for second-brain vs knowledge garden approach guidance
- See [Core Concepts](concepts.md) for the content type and maturity tier reference
- See [MCP Server](mcp.md) for the full MCP tool and resource reference
```

**Structural placement summary:**
- Keep all existing sections in their original order
- Insert "## Recipe Walkthroughs" after "## MCP Server Integration" and before "## Batch Operations"
- Insert "## Session Lifecycle" after "## Recipe Walkthroughs" and before "## Batch Operations"
- Add "## Next Steps" at the very end (after "## Scripting with JSON Output")
  </action>

  <verify>
    <automated>wc -l /Users/shparki/Documents/Workspace/thatdev/ztlctl/docs/agentic-workflows.md && grep -c "research-capture\|review-triage\|knowledge-synthesis\|LOG CLOSE\|CROSS-SESSION REWEAVE" /Users/shparki/Documents/Workspace/thatdev/ztlctl/docs/agentic-workflows.md</automated>
  </verify>

  <acceptance_criteria>
    - File is 380+ lines (up from 192)
    - Contains "## Recipe Walkthroughs" heading
    - Contains all three recipe subsections: "Research Capture", "Review Triage", "Knowledge Synthesis"
    - Each recipe has: description, steps table, human CLI walkthrough with expected output, agent MCP tool sequence
    - Contains "## Session Lifecycle" heading
    - Contains "### Human-Driven Session" subsection with 30-minute research session example
    - Contains "### Agent-Driven Session" subsection with MCP tool call sequence
    - Contains "### Session Close Enrichment Pipeline" with all 5 steps explained
    - Contains "LOG CLOSE → CROSS-SESSION REWEAVE → ORPHAN SWEEP → INTEGRITY CHECK → GRAPH MATERIALIZATION" pipeline string
    - Contains JSON example of session close result with reweave_count, orphan_count, integrity_issues
    - Contains session config toml block with orphan_reweave_threshold
    - All existing content from the original 192-line file is preserved
    - mkdocs build --strict passes
  </acceptance_criteria>

  <done>docs/agentic-workflows.md expanded to 380+ lines with Recipe Walkthroughs section (3 recipes with human CLI and agent MCP sequences), Session Lifecycle section (human-driven example, agent-driven example, 5-step close pipeline with JSON output), and Next Steps. All original content preserved. mkdocs build --strict passes.</done>
</task>

<task type="auto">
  <name>Task 2: Regenerate docs/llms-full.txt with plugins.md content</name>
  <files>docs/llms-full.txt</files>

  <read_first>
    - scripts/gen_llms_full_txt.py — generation script (NAV_ORDER was updated in Plan 02 to include plugins.md)
    - docs/plugins.md — verify the file exists before running regeneration
  </read_first>

  <action>
Run the generation script to rebuild docs/llms-full.txt. The NAV_ORDER in gen_llms_full_txt.py was updated in Plan 02 to include plugins.md, so this regeneration picks up the new Built-in Plugins content.

```bash
cd /path/to/vault-root
python scripts/gen_llms_full_txt.py
```

Verify the output:
1. Script completes without "WARNING: ... not found" messages
2. docs/llms-full.txt is larger than before (new plugins.md content was included)
3. docs/llms-full.txt contains "Built-in Plugins" (the title from plugins.md)

If the script prints a WARNING about plugins.md not being found, that means Plan 02's Task 2 was not completed successfully. Do not proceed — check that docs/plugins.md exists first.
  </action>

  <verify>
    <automated>python /Users/shparki/Documents/Workspace/thatdev/ztlctl/scripts/gen_llms_full_txt.py && grep "Built-in Plugins" /Users/shparki/Documents/Workspace/thatdev/ztlctl/docs/llms-full.txt</automated>
  </verify>

  <acceptance_criteria>
    - Script runs without any WARNING lines in output
    - docs/llms-full.txt contains "Built-in Plugins"
    - docs/llms-full.txt contains "batch_commits" (from plugins.md Git section)
    - docs/llms-full.txt contains "min_score_threshold" (from plugins.md Reweave section)
    - docs/llms-full.txt contains "Recipe Walkthroughs" (from expanded agentic-workflows.md — if Task 1 ran first)
  </acceptance_criteria>

  <done>docs/llms-full.txt regenerated. Contains Built-in Plugins, Git plugin, and Reweave plugin content from plugins.md. Script ran without warnings.</done>
</task>

</tasks>

<verification>
After all tasks complete:

```bash
# Line count check
wc -l docs/agentic-workflows.md

# Content marker checks
grep -c "Recipe Walkthroughs\|research-capture\|review-triage\|knowledge-synthesis\|LOG CLOSE\|Session Lifecycle" docs/agentic-workflows.md

# llms-full.txt content check
grep "Built-in Plugins\|batch_commits" docs/llms-full.txt | head -5

# Full build validation
mkdocs build --strict 2>&1 | tail -5
```
</verification>

<success_criteria>
- docs/agentic-workflows.md is 380+ lines with all 3 recipe walkthroughs (each with steps table, human CLI, agent MCP sequence) and session lifecycle guides (human-driven, agent-driven, 5-step close pipeline with JSON output)
- All original content in agentic-workflows.md is preserved
- docs/llms-full.txt regenerated and contains plugins.md content ("Built-in Plugins", "batch_commits", "min_score_threshold")
- `mkdocs build --strict` exits 0
</success_criteria>

<output>
After completion, create `.planning/phases/10-user-guide-content/10-03-SUMMARY.md`
</output>
