
Doc Coauthoring
- 1 installs
- 21 repo stars
- Updated August 5, 2026
- joaquimscosta/arkhe-claude-plugins
Guides structured collaborative documentation creation through context gathering, section-by-section refinement, and reader testing.
About
Runs a three-stage collaborative workflow, context gathering, refinement, and reader testing, to co-author READMEs, specs, proposals, RFCs, and API docs. A developer uses it when writing substantial documentation that must work for its readers.
- Full and streamlined variants for different doc types
- Stage 3 reader-testing with a fresh Claude to catch blind spots
Doc Coauthoring by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,366 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/joaquimscosta/arkhe-claude-plugins --skill doc-coauthoringAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 21 |
| Last updated | August 5, 2026 |
| Repository | joaquimscosta/arkhe-claude-plugins ↗ |
What it does
Guides structured collaborative documentation creation through context gathering, section-by-section refinement, and reader testing.
Files
Doc Co-Authoring Workflow
Collaborative workflow for creating documentation that works for readers.
When to Offer This Workflow
Trigger conditions:
- Writing documentation: "write a doc", "draft a proposal", "create a spec", "write up"
- Code documentation: "write README", "create API docs", "document this code", "architecture docs"
- Specific doc types: "PRD", "design doc", "decision doc", "RFC", "technical spec"
- User starting any substantial writing task
Workflow Variants
| Variant | Stages | Use For |
|---|---|---|
| Full Collaborative | Context Gathering → Refinement → Reader Testing | Proposals, specs, decisions, RFCs |
| Streamlined Collaborative | Context Gathering → Refinement | READMEs, API docs, architecture guides |
Both variants use collaborative principles (clarifying questions, iterative refinement). Streamlined skips Reader Testing since code docs have different validation (working examples, API accuracy).
Three Stages Overview
Stage 1: Context Gathering
Close the gap between what the user knows and what Claude knows. Ask about doc type, audience, desired impact, and template. Encourage info dumping. Ask clarifying questions until understanding is sufficient.
Stage 2: Refinement & Structure
Build the document section by section. For each section: ask clarifying questions, brainstorm options, let user curate, draft, and refine through surgical edits. Use code documentation patterns as scaffolds for READMEs, APIs, etc.
Stage 3: Reader Testing (Full Collaborative only)
Test the document with a fresh Claude (no context bleed) to verify it works for readers. If sub-agents available, test directly. Otherwise, guide user through manual testing.
Initial Offer Template
When triggered, offer the workflow:
I can help you write that [doc type]. I use a structured workflow that helps
ensure the doc works well when others read it:
1. **Context Gathering**: You share relevant context while I ask clarifying questions
2. **Refinement & Structure**: We build each section through brainstorming and iteration
3. **Reader Testing**: We test the doc with a fresh Claude to catch blind spots
(or skip for code docs like READMEs)
Would you like to try this workflow, or prefer to work freeform?Code Documentation Patterns
For code docs, select the appropriate pattern as the starting scaffold:
| Doc Type | Pattern |
|---|---|
| README | Features, Installation, Quick Start, Config, API, Contributing |
| API Docs | OpenAPI spec with paths, schemas, examples |
| Architecture | Overview, Component Diagram, Components table, Data Flow |
| Configuration | Required/Optional vars table, example config |
| Module | Purpose, Architecture diagram, Components, Methods table |
See WORKFLOW.md for complete patterns.
Resources
- WORKFLOW.md - Full stage procedures and code patterns
- EXAMPLES.md - Complete templates for proposals, specs, READMEs
- TROUBLESHOOTING.md - Common issues and solutions
Tips
- Be direct and procedural - explain rationale briefly when it affects user behavior
- Give user agency - always allow them to skip stages or work freeform
- Track context - address gaps as they come up, don't let them accumulate
- Use surgical edits - never reprint entire doc, use str_replace
- Quality over speed - each iteration should make meaningful improvements
- For code docs - verify examples work, check API signatures against actual code
Doc Co-Authoring Examples
Complete templates and examples for different documentation types.
Table of Contents
1. Human Documentation Examples
2. Code Documentation Examples
- Complete README
- OpenAPI Specification
- Module Documentation
- Configuration Reference
- Function Documentation
---
Human Documentation Examples
Example 1: Technical Proposal
# Proposal: Migrate Authentication to OAuth2
**Author**: Jane Smith
**Date**: 2025-01-15
**Status**: Draft
## Executive Summary
We propose migrating from our custom JWT-based authentication to OAuth2 with
support for external identity providers (Google, GitHub). This enables SSO
for enterprise customers while reducing our authentication maintenance burden.
## Problem Statement
Our current authentication system has several limitations:
- No SSO support - enterprise customers must create separate credentials
- Custom JWT implementation requires ongoing security maintenance
- Password reset flows create support burden (~50 tickets/month)
- No support for MFA without building it ourselves
## Proposed Solution
Implement OAuth2 authorization server with:
- External IdP support (Google, GitHub, SAML)
- Backward compatibility with existing sessions for 6-month transition
- Self-service MFA enrollment
### Technical Approach
graph LR User --> Gateway[API Gateway] Gateway --> Auth[Auth Service] Auth --> IdP[External IdP] Auth --> DB[(User DB)]
## Alternatives Considered
| Option | Pros | Cons | Verdict |
|--------|------|------|---------|
| Auth0 | Managed, fast | Cost at scale (~$50k/yr) | Too expensive |
| Keycloak | Self-hosted, free | Operational burden | Considered |
| Custom OAuth2 | Full control | Implementation time | **Selected** |
## Implementation Plan
1. **Phase 1 (4 weeks)**: OAuth2 core implementation
2. **Phase 2 (2 weeks)**: Google/GitHub integration
3. **Phase 3 (3 weeks)**: Migration tooling and dual-auth period
4. **Phase 4 (ongoing)**: User migration with deprecation of old system
## Risks and Mitigations
| Risk | Impact | Mitigation |
|------|--------|------------|
| User confusion during migration | Medium | In-app guidance, support documentation |
| Token compatibility issues | High | 6-month dual-auth period |
| External IdP outages | Medium | Fallback to email/password |
## Success Metrics
- 80% of enterprise users on SSO within 6 months
- 50% reduction in auth-related support tickets
- Zero security incidents during migration
## Appendix
- [A. Current Auth Architecture](link)
- [B. OAuth2 RFC Reference](link)---
Example 2: Decision Document
# Decision: Use PostgreSQL for Analytics Data Store
**Decision Date**: 2025-01-10
**Decision Makers**: Data Team, Platform Team
**Status**: Approved
## Context
Our analytics pipeline needs a data store for aggregated metrics. Current
options under consideration: PostgreSQL, ClickHouse, and TimescaleDB.
## Decision
We will use **PostgreSQL with TimescaleDB extension** for analytics data.
## Rationale
### Requirements
1. Store 6 months of aggregated metrics (~500GB)
2. Support time-series queries with <100ms p95 latency
3. Integrate with existing PostgreSQL tooling
4. Handle 10K writes/second during peak
### Evaluation
| Requirement | PostgreSQL | ClickHouse | TimescaleDB |
|-------------|------------|------------|-------------|
| Storage capacity | Yes | Yes | Yes |
| Query latency | Marginal | Yes | Yes |
| Existing tooling | Yes | No | Yes |
| Write throughput | No | Yes | Yes |
### Why TimescaleDB
- Maintains PostgreSQL compatibility (migrations, tooling, team expertise)
- Handles time-series workloads efficiently with hypertables
- Compression reduces storage costs by ~80%
- Single system to maintain vs. separate OLAP cluster
### Why Not ClickHouse
Despite superior raw performance:
- Requires new operational expertise
- Separate system to maintain
- Team would need training
- Our scale doesn't justify the complexity
## Consequences
**Positive:**
- Team can use existing PostgreSQL knowledge
- Single database technology to maintain
- Straightforward backup and recovery
**Negative:**
- May need to revisit if we 10x our data volume
- Some ClickHouse-specific features unavailable
## Implementation Notes
- Enable TimescaleDB extension on analytics database
- Create hypertables for time-series data
- Set up compression policy for data >7 days old
- Configure retention policy for 6-month window---
Example 3: Technical Spec
# Technical Spec: Real-Time Notification System
**Author**: Alex Chen
**Reviewers**: Platform Team
**Status**: In Review
## Overview
Design a real-time notification system supporting push notifications,
email, and in-app messages with guaranteed delivery and user preferences.
## Goals
- Deliver notifications within 5 seconds (p95) for real-time channels
- Support 100K concurrent WebSocket connections
- Respect user notification preferences
- Ensure at-least-once delivery for critical notifications
## Non-Goals
- SMS notifications (future phase)
- Notification analytics dashboard (separate project)
- Message scheduling beyond 24 hours
## System Design
### Architecture
graph TB subgraph Producers API[API Services] Workers[Background Workers] end
subgraph Core Queue[Message Queue] Router[Notification Router] Prefs[Preference Service] end
subgraph Delivery Push[Push Gateway] Email[Email Service] WS[WebSocket Server] end
API --> Queue Workers --> Queue Queue --> Router Router --> Prefs Router --> Push Router --> Email Router --> WS
### Components
#### Message Queue (Redis Streams)
- Durable message storage
- Consumer groups for scaling
- Dead letter queue for failures
#### Notification Router
- Reads from queue
- Checks user preferences
- Routes to appropriate channel(s)
- Handles retry logic
#### WebSocket Server
- Maintains persistent connections
- Horizontal scaling with Redis pub/sub
- Heartbeat for connection health
### Data Model
-- Notifications CREATE TABLE notifications ( id UUID PRIMARY KEY, user_id UUID NOT NULL, type VARCHAR(50) NOT NULL, payload JSONB NOT NULL, channel VARCHAR(20)[] NOT NULL, created_at TIMESTAMP DEFAULT NOW(), delivered_at TIMESTAMP, read_at TIMESTAMP );
-- User Preferences CREATE TABLE notification_preferences ( user_id UUID PRIMARY KEY, email_enabled BOOLEAN DEFAULT true, push_enabled BOOLEAN DEFAULT true, quiet_hours_start TIME, quiet_hours_end TIME, preferences JSONB DEFAULT '{}' );
### API Endpoints
POST /notifications
- Send notification to user(s)
- Body: { user_ids, type, payload, priority }
GET /notifications
- List notifications for current user
- Query: ?unread=true&limit=50
PATCH /notifications/:id/read
- Mark notification as read
GET /notifications/preferences PUT /notifications/preferences
- Get/update user preferences
## Failure Handling
| Failure Mode | Detection | Response |
|--------------|-----------|----------|
| WebSocket disconnect | Heartbeat timeout | Queue messages, retry on reconnect |
| Push delivery failure | Provider callback | Retry 3x, then fallback to email |
| Email bounce | Webhook | Mark channel failed, alert user |
| Queue unavailable | Health check | Circuit breaker, buffer in memory |
## Security Considerations
- WebSocket connections authenticated via JWT
- Notification payload sanitized before display
- User can only access their own notifications
- Rate limiting: 100 notifications/user/hour
## Testing Plan
1. Unit tests for router logic and preference matching
2. Integration tests for each delivery channel
3. Load test: 10K concurrent connections, 1K messages/second
4. Chaos testing: Network partitions, service failures
## Rollout Plan
1. **Week 1**: Deploy to staging, internal testing
2. **Week 2**: 5% of users (opt-in beta)
3. **Week 3**: 25% rollout with monitoring
4. **Week 4**: 100% rollout
## Open Questions
- [ ] Should we support notification batching for high-volume users?
- [ ] What's the retention period for notification history?---
Code Documentation Examples
Example 4: Complete README
# DataProcessor
Fast, type-safe data transformation library for Node.js.
[](https://www.npmjs.com/package/data-processor)
[](https://opensource.org/licenses/MIT)
## Features
- Type-safe transformations with TypeScript support
- Streaming support for large datasets
- Built-in validation and error handling
- Extensible plugin architecture
- Zero dependencies
## Installation
npm install data-processor
## Quick Start
import { DataProcessor } from 'data-processor';
const processor = new DataProcessor();
const result = await processor .load('data.csv') .transform(row => ({ ...row, total: row.price * row.quantity })) .filter(row => row.total > 100) .save('output.json');
console.log(Processed ${result.count} records);
## Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `chunkSize` | number | 1000 | Records per batch |
| `validateSchema` | boolean | true | Enable schema validation |
| `onError` | 'skip' \| 'throw' | 'throw' | Error handling mode |
const processor = new DataProcessor({ chunkSize: 5000, validateSchema: true, onError: 'skip' });
## API Reference
### `DataProcessor`
#### `load(source: string | Stream): DataProcessor`
Load data from file path or stream.
#### `transform(fn: (row: T) => U): DataProcessor`
Apply transformation to each row.
#### `filter(predicate: (row: T) => boolean): DataProcessor`
Filter rows based on predicate.
#### `save(destination: string): Promise<Result>`
Save processed data to file.
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
MIT License - see [LICENSE](LICENSE) for details.---
Example 5: OpenAPI Specification
openapi: 3.0.3
info:
title: User Management API
description: RESTful API for managing users and authentication
version: 1.0.0
contact:
email: api@example.com
servers:
- url: https://api.example.com/v1
description: Production
- url: https://staging-api.example.com/v1
description: Staging
security:
- bearerAuth: []
paths:
/users:
get:
summary: List all users
operationId: listUsers
tags:
- Users
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: limit
in: query
schema:
type: integer
default: 20
maximum: 100
- name: status
in: query
schema:
type: string
enum: [active, inactive, pending]
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
pagination:
$ref: '#/components/schemas/Pagination'
'401':
$ref: '#/components/responses/Unauthorized'
post:
summary: Create a new user
operationId: createUser
tags:
- Users
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: User created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
$ref: '#/components/responses/BadRequest'
/users/{id}:
get:
summary: Get user by ID
operationId: getUser
tags:
- Users
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
$ref: '#/components/responses/NotFound'
components:
schemas:
User:
type: object
required:
- id
- email
- createdAt
properties:
id:
type: string
format: uuid
email:
type: string
format: email
name:
type: string
status:
type: string
enum: [active, inactive, pending]
createdAt:
type: string
format: date-time
CreateUserRequest:
type: object
required:
- email
properties:
email:
type: string
format: email
name:
type: string
password:
type: string
minLength: 8
Pagination:
type: object
properties:
page:
type: integer
limit:
type: integer
total:
type: integer
totalPages:
type: integer
responses:
Unauthorized:
description: Authentication required
content:
application/json:
schema:
type: object
properties:
error:
type: string
example: "Authentication required"
BadRequest:
description: Invalid request
content:
application/json:
schema:
type: object
properties:
error:
type: string
details:
type: array
items:
type: string
NotFound:
description: Resource not found
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT---
Example 6: Module Documentation
# Authentication Module
Handles user authentication, session management, and authorization.
## Overview
The authentication module provides:
- JWT-based authentication
- Role-based access control (RBAC)
- Session management with Redis
- OAuth2 integration (Google, GitHub)
## Architecture
graph LR Client --> AuthController AuthController --> AuthService AuthService --> UserRepository AuthService --> TokenService AuthService --> SessionStore SessionStore --> Redis UserRepository --> PostgreSQL
## Components
### AuthService
Core authentication logic.
**Methods**:
| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `login` | email, password | TokenPair | Authenticate user |
| `logout` | refreshToken | void | Invalidate session |
| `refresh` | refreshToken | TokenPair | Refresh access token |
| `verify` | accessToken | UserPayload | Verify and decode token |
**Example**:
const authService = new AuthService(userRepo, tokenService, sessionStore);
// Login const { accessToken, refreshToken } = await authService.login( 'user@example.com', 'password123' );
// Verify token const user = await authService.verify(accessToken);
### TokenService
JWT token generation and validation.
**Configuration**:
const tokenService = new TokenService({ accessTokenSecret: process.env.ACCESS_TOKEN_SECRET, refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET, accessTokenExpiry: '15m', refreshTokenExpiry: '7d' });
### SessionStore
Redis-backed session management.
**Operations**:
- `create(userId, metadata)` - Create new session
- `get(sessionId)` - Retrieve session
- `invalidate(sessionId)` - End session
- `invalidateAll(userId)` - End all user sessions
## Configuration
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `JWT_SECRET` | Yes | - | Secret for signing tokens |
| `JWT_EXPIRY` | No | 15m | Access token expiry |
| `REDIS_URL` | Yes | - | Redis connection URL |
| `SESSION_TTL` | No | 7d | Session time-to-live |
## Error Handling
| Error | Code | Description |
|-------|------|-------------|
| `InvalidCredentials` | 401 | Wrong email or password |
| `TokenExpired` | 401 | Access token expired |
| `TokenInvalid` | 401 | Malformed or tampered token |
| `SessionNotFound` | 401 | Session invalidated |
| `InsufficientPermissions` | 403 | Missing required role |
## Security Considerations
- Tokens stored in httpOnly cookies
- Refresh tokens rotated on use
- Rate limiting on login endpoint (5/min)
- Passwords hashed with bcrypt (cost=12)---
Example 7: Configuration Reference
# Configuration Reference
Complete configuration options for the application.
## Environment Variables
### Required
| Variable | Type | Description |
|----------|------|-------------|
| `DATABASE_URL` | string | PostgreSQL connection string |
| `REDIS_URL` | string | Redis connection string |
| `JWT_SECRET` | string | Secret for signing JWTs (min 32 chars) |
### Optional
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `PORT` | number | 3000 | Server port |
| `NODE_ENV` | enum | development | Environment (development, staging, production) |
| `LOG_LEVEL` | enum | info | Logging level (debug, info, warn, error) |
| `CORS_ORIGINS` | string | * | Allowed CORS origins (comma-separated) |
## Configuration File
Create `config.yaml` in the project root:
server: port: 3000 host: 0.0.0.0
database: pool: min: 2 max: 10 timeout: 30000
cache: ttl: 3600 prefix: "app:"
features: enableMetrics: true enableTracing: false
## Example .env File
Database
DATABASE_URL=postgresql://user:pass@localhost:5432/myapp
Redis
REDIS_URL=redis://localhost:6379
Security
JWT_SECRET=your-very-long-secret-key-min-32-chars
Server
PORT=3000 NODE_ENV=development LOG_LEVEL=debug
Features
ENABLE_METRICS=true
## Validation
Configuration is validated at startup. Invalid configuration will prevent the application from starting.
// Validation schema const configSchema = z.object({ DATABASE_URL: z.string().url(), REDIS_URL: z.string().url(), JWT_SECRET: z.string().min(32), PORT: z.number().default(3000), NODE_ENV: z.enum(['development', 'staging', 'production']).default('development'), });
---
Example 8: Function Documentation
Python (Google Style)
def process_transactions(
transactions: List[Transaction],
config: ProcessingConfig,
*,
dry_run: bool = False,
batch_size: int = 100
) -> ProcessingResult:
"""Process a list of transactions according to configuration.
Validates each transaction, applies business rules, and persists
results to the database. Supports batch processing for large datasets.
Args:
transactions: List of transactions to process. Each transaction
must have valid account_id and amount fields.
config: Processing configuration including validation rules
and persistence settings.
dry_run: If True, validate without persisting. Defaults to False.
batch_size: Number of transactions per batch. Defaults to 100.
Returns:
ProcessingResult containing:
- processed_count: Number of successfully processed transactions
- failed_count: Number of failed transactions
- errors: List of error details for failed transactions
Raises:
ValidationError: If transactions list is empty or config is invalid.
DatabaseError: If persistence fails (only when dry_run=False).
Example:
>>> config = ProcessingConfig(validate_amounts=True)
>>> transactions = [Transaction(account_id=1, amount=100.00)]
>>> result = process_transactions(transactions, config)
>>> print(f"Processed: {result.processed_count}")
Processed: 1
Note:
For transactions over 10,000 items, consider using
process_transactions_async() for better performance.
"""TypeScript (TSDoc)
/**
* Process a list of transactions according to configuration.
*
* Validates each transaction, applies business rules, and persists
* results to the database. Supports batch processing for large datasets.
*
* @param transactions - List of transactions to process
* @param config - Processing configuration
* @param options - Optional processing options
* @param options.dryRun - If true, validate without persisting (default: false)
* @param options.batchSize - Number of transactions per batch (default: 100)
*
* @returns Processing result with counts and error details
*
* @throws {ValidationError} If transactions list is empty
* @throws {DatabaseError} If persistence fails (when dryRun=false)
*
* @example
* ```typescript
* const result = await processTransactions(transactions, config);
* console.log(`Processed: ${result.processedCount}`);
* ```
*
* @see {@link processTransactionsAsync} for large datasets
*/
async function processTransactions(
transactions: Transaction[],
config: ProcessingConfig,
options?: { dryRun?: boolean; batchSize?: number }
): Promise<ProcessingResult>---
Conversation Examples
Workflow Offer Example
User: I need to write a design doc for a new caching layer.
Claude: I can help you write that design doc. I use a structured workflow that helps ensure the doc works well when others read it:
1. Context Gathering: You share all the relevant context while I ask clarifying questions 2. Refinement & Structure: We build each section through brainstorming and iterative editing 3. Reader Testing: We test the doc with a fresh Claude (no context) to catch blind spots
Would you like to try this workflow, or prefer to work freeform?
Context Gathering Example
Claude: Let's start with some quick questions:
1. Who's the primary audience for this design doc? 2. What's the desired impact - what should readers take away? 3. Do you have a template or specific format to follow? 4. Any constraints I should know about (timeline, tech stack, etc.)?
Feel free to answer in shorthand.
Brainstorming Example
Claude: For the "Technical Approach" section, here are some points we might include:
1. Cache invalidation strategy (TTL vs. event-based) 2. Data structures for cache keys 3. Memory limits and eviction policy 4. Cache warming on startup 5. Metrics and monitoring hooks 6. Fallback behavior when cache is unavailable 7. Serialization format (JSON, Protocol Buffers) 8. Distributed cache vs. local cache trade-offs 9. Cache penetration protection 10. Hot key handling
Which of these should we keep? Any to remove or combine? Anything important I missed?
Doc Co-Authoring Troubleshooting
Common issues and solutions for the doc-coauthoring workflow.
Workflow Issues
User Wants to Skip Stages
Problem: User is impatient and wants to skip Context Gathering or Reader Testing.
Solution: Offer to work freeform while explaining the trade-off.
"We can absolutely skip this stage. Just know that [stage purpose].
Want to proceed freeform, or would a shorter version of this stage work?"For Reader Testing specifically: The Streamlined Collaborative workflow skips this stage by design for code documentation.
---
User Provides Too Little Context
Problem: User gives one-sentence answers and won't elaborate.
Solution: Ask more specific questions:
- Instead of "Tell me about the project" → "What problem does this solve?"
- Instead of "Who's the audience?" → "Will technical or non-technical people read this?"
- Offer multiple choice: "Is this for (a) internal team, (b) external stakeholders, or (c) public documentation?"
---
User Provides Too Much Context
Problem: User info-dumps extensively, making it hard to synthesize.
Solution: Summarize and confirm:
"Based on what you've shared, here's what I understand:
- Key goal: X
- Main audience: Y
- Constraints: Z
Is this accurate? Anything critical I'm missing?"---
User Wants to Edit Doc Directly
Problem: User makes changes directly instead of asking for edits.
Solution: Accept it gracefully:
"I see you've made changes. I'll incorporate your edits and keep your style
in mind for the remaining sections."Read the document to learn their preferences and apply them going forward.
---
Brainstorming Produces Too Many Options
Problem: 20 options overwhelms the user.
Solution: Pre-group or prioritize:
"Here are the options grouped by theme:
**Core functionality** (pick 2-3):
1. ...
2. ...
**Nice to have** (pick 0-2):
3. ...
4. ...
Which categories matter most for your audience?"---
User Struggles with Curation
Problem: User says "looks good" without specific selections.
Solution: Ask targeted follow-up:
"Great! To make sure I capture your intent:
- Are there any points you definitely want included?
- Any that feel redundant or off-topic?
- Anything important that's missing?"---
Code Documentation Issues
Missing Package Manifest
Problem: No package.json, pyproject.toml, or similar file exists.
Solution: Ask user for key project info:
- Project name and description
- Main dependencies
- Entry points
- Target audience (beginner/advanced developers)
---
Code Examples Don't Work
Problem: Generated examples have syntax errors or don't match actual API.
Solution: 1. Read the actual source code to verify API signatures 2. Test examples mentally against the codebase 3. Include imports and setup code 4. Ask user to verify examples work
---
API Spec Doesn't Match Implementation
Problem: OpenAPI spec has endpoints that don't exist or wrong parameters.
Solution: 1. Scan actual route definitions in code 2. Extract parameters from function signatures 3. Check for type hints/annotations 4. Cross-reference with any existing documentation
---
Architecture Diagram Too Complex
Problem: System has too many components to diagram clearly.
Solution: Create layered diagrams:
1. High-level system overview (3-5 boxes) 2. Detailed diagrams per subsystem 3. Data flow diagrams for specific use cases
Ask user which level of detail they need.
---
Reader Testing Issues
No Sub-Agent Access
Problem: Testing in claude.ai web interface without sub-agent capability.
Solution: Guide user through manual testing:
1. Provide specific questions to ask 2. Explain how to open a fresh Claude conversation 3. Tell them what to look for in responses 4. Have them report back issues found
---
Reader Claude Answers Correctly but Verbosely
Problem: Fresh Claude understands the doc but provides long-winded answers.
Solution: This is fine - it means the doc works. Focus on cases where:
- Claude misunderstands key concepts
- Claude makes incorrect assumptions
- Claude can't answer from the doc alone
---
Testing Reveals Major Gaps
Problem: Reader Testing surfaces fundamental problems, not just minor tweaks.
Solution: Loop back to Stage 2 for affected sections:
"Reader Claude struggled with [section]. Let's revisit it:
1. What key information was missing?
2. What assumptions did we make that aren't stated?
I'll draft a revised version addressing these gaps."---
General Issues
Conversation Running Long
Problem: Too many iterations, user losing patience.
Solution: Offer shortcuts:
"We've been through several iterations. Options:
1. Move forward with current version (good enough)
2. One more focused pass on [specific section]
3. Skip to final review
What works best for you?"---
User Wants Different Format
Problem: User wants output in format not covered by patterns (e.g., Wiki, Notion).
Solution: Adapt the patterns:
1. Ask for an example of their preferred format 2. Map the standard sections to their format 3. Maintain the collaborative process with their format as output
---
Document Needs Visuals
Problem: Doc would benefit from diagrams, but user hasn't provided any.
Solution: Offer to create Mermaid diagrams:
"This section might benefit from a diagram. I can create a Mermaid diagram
showing [proposed visual]. Would that help?"Use the diagramming skill if available.
---
Conflicting Requirements
Problem: User states requirements that contradict each other.
Solution: Surface the conflict explicitly:
"I notice a potential tension:
- You mentioned [requirement A]
- But also [requirement B]
These might conflict because [reason]. How would you like to resolve this?"---
Quick Reference
| Issue | Quick Fix |
|---|---|
| User impatient | Offer to streamline or skip |
| Too little context | Ask specific questions |
| Too much context | Summarize and confirm |
| User edits directly | Accept and learn from their style |
| Too many options | Group and prioritize |
| Examples broken | Verify against actual code |
| Testing reveals gaps | Loop back to refinement |
| Long conversation | Offer exit ramps |
| Format mismatch | Adapt patterns to their format |
| Needs visuals | Offer Mermaid diagrams |
Doc Co-Authoring Workflow
Detailed procedures for all workflow stages and variants.
Table of Contents
1. Stage 1: Context Gathering 2. Stage 2: Refinement & Structure 3. Stage 3: Reader Testing 4. Streamlined Workflow 5. Code Documentation Patterns 6. Quality Checklists
---
Stage 1: Context Gathering
Goal: Close the gap between what the user knows and what Claude knows, enabling smart guidance later.
Initial Questions
Start by asking the user for meta-context about the document:
1. What type of document is this? (e.g., technical spec, decision doc, proposal, README, API docs) 2. Who's the primary audience? 3. What's the desired impact when someone reads this? 4. Is there a template or specific format to follow? 5. Any other constraints or context to know?
Inform them they can answer in shorthand or dump information however works best for them.
Handling Templates and Existing Docs
If user provides a template or mentions a doc type:
- Ask if they have a template document to share
- If they provide a link to a shared document, use the appropriate integration to fetch it
- If they provide a file, read it
If user mentions editing an existing shared document:
- Use the appropriate integration to read the current state
- Check for images without alt-text
- If images exist without alt-text, explain that when others use Claude to understand the doc, Claude won't be able to see them. Ask if they want alt-text generated.
Info Dumping
Once initial questions are answered, encourage the user to dump all the context they have. Request information such as:
- Background on the project/problem
- Related team discussions or shared documents
- Why alternative solutions aren't being used
- Organizational context (team dynamics, past incidents, politics)
- Timeline pressures or constraints
- Technical architecture or dependencies
- Stakeholder concerns
Advise them not to worry about organizing it - just get it all out. Offer multiple ways to provide context:
- Info dump stream-of-consciousness
- Point to team channels or threads to read
- Link to shared documents
If integrations are available (e.g., Slack, Teams, Google Drive, SharePoint, or other MCP servers), mention that these can be used to pull in context directly.
If no integrations are detected and in Claude.ai or Claude app: Suggest they can enable connectors in their Claude settings to allow pulling context from messaging apps and document storage directly.
During Context Gathering
- If user mentions team channels or shared documents:
- If integrations available: Inform them the content will be read now, then use the appropriate integration
- If integrations not available: Explain lack of access. Suggest they enable connectors in Claude settings, or paste the relevant content directly.
- If user mentions entities/projects that are unknown:
- Ask if connected tools should be searched to learn more
- Wait for user confirmation before searching
- As user provides context, track what's being learned and what's still unclear
Asking Clarifying Questions
When user signals they've done their initial dump (or after substantial context provided), ask clarifying questions to ensure understanding:
Generate 5-10 numbered questions based on gaps in the context.
Inform them they can use shorthand to answer (e.g., "1: yes, 2: see #channel, 3: no because backwards compat"), link to more docs, point to channels to read, or just keep info-dumping. Whatever's most efficient for them.
Exit Condition
Sufficient context has been gathered when questions show understanding - when edge cases and trade-offs can be asked about without needing basics explained.
Transition
Ask if there's any more context they want to provide at this stage, or if it's time to move on to drafting the document.
If user wants to add more, let them. When ready, proceed to Stage 2.
---
Stage 2: Refinement & Structure
Goal: Build the document section by section through brainstorming, curation, and iterative refinement.
Instructions to User
Explain that the document will be built section by section. For each section: 1. Clarifying questions will be asked about what to include 2. 5-20 options will be brainstormed 3. User will indicate what to keep/remove/combine 4. The section will be drafted 5. It will be refined through surgical edits
Start with whichever section has the most unknowns (usually the core decision/proposal), then work through the rest.
Section Ordering
If the document structure is clear: Ask which section they'd like to start with.
Suggest starting with whichever section has the most unknowns. For decision docs, that's usually the core proposal. For specs, it's typically the technical approach. Summary sections are best left for last.
If user doesn't know what sections they need: Based on the type of document and template, suggest 3-5 sections appropriate for the doc type.
Ask if this structure works, or if they want to adjust it.
Creating Initial Structure
Once structure is agreed:
Create the initial document structure with placeholder text for all sections.
If access to artifacts is available: Use create_file to create an artifact. This gives both Claude and the user a scaffold to work from.
Inform them that the initial structure with placeholders for all sections will be created.
Create artifact with all section headers and brief placeholder text like "[To be written]" or "[Content here]".
Provide the scaffold link and indicate it's time to fill in each section.
If no access to artifacts: Create a markdown file in the working directory. Name it appropriately (e.g., decision-doc.md, technical-spec.md).
Inform them that the initial structure with placeholders for all sections will be created.
Create file with all section headers and placeholder text.
Confirm the filename has been created and indicate it's time to fill in each section.
For Each Section
Step 1: Clarifying Questions
Announce work will begin on the [SECTION NAME] section. Ask 5-10 clarifying questions about what should be included:
Generate 5-10 specific questions based on context and section purpose.
Inform them they can answer in shorthand or just indicate what's important to cover.
Step 2: Brainstorming
For the [SECTION NAME] section, brainstorm [5-20] things that might be included, depending on the section's complexity. Look for:
- Context shared that might have been forgotten
- Angles or considerations not yet mentioned
Generate 5-20 numbered options based on section complexity. At the end, offer to brainstorm more if they want additional options.
Step 3: Curation
Ask which points should be kept, removed, or combined. Request brief justifications to help learn priorities for the next sections.
Provide examples:
- "Keep 1,4,7,9"
- "Remove 3 (duplicates 1)"
- "Remove 6 (audience already knows this)"
- "Combine 11 and 12"
If user gives freeform feedback (e.g., "looks good" or "I like most of it but...") instead of numbered selections, extract their preferences and proceed. Parse what they want kept/removed/changed and apply it.
Step 4: Gap Check
Based on what they've selected, ask if there's anything important missing for the [SECTION NAME] section.
Step 5: Drafting
Use str_replace to replace the placeholder text for this section with the actual drafted content.
Announce the [SECTION NAME] section will be drafted now based on what they've selected.
If using artifacts: After drafting, provide a link to the artifact.
Ask them to read through it and indicate what to change. Note that being specific helps learning for the next sections.
If using a file (no artifacts): After drafting, confirm completion.
Inform them the [SECTION NAME] section has been drafted in [filename]. Ask them to read through it and indicate what to change. Note that being specific helps learning for the next sections.
Key instruction for user (include when drafting the first section): Provide a note: Instead of editing the doc directly, ask them to indicate what to change. This helps learning of their style for future sections. For example: "Remove the X bullet - already covered by Y" or "Make the third paragraph more concise".
Step 6: Iterative Refinement
As user provides feedback:
- Use
str_replaceto make edits (never reprint the whole doc) - If using artifacts: Provide link to artifact after each edit
- If using files: Just confirm edits are complete
- If user edits doc directly and asks to read it: mentally note the changes they made and keep them in mind for future sections (this shows their preferences)
Continue iterating until user is satisfied with the section.
Quality Checking
After 3 consecutive iterations with no substantial changes, ask if anything can be removed without losing important information.
When section is done, confirm [SECTION NAME] is complete. Ask if ready to move to the next section.
Repeat for all sections.
Near Completion
As approaching completion (80%+ of sections done), announce intention to re-read the entire document and check for:
- Flow and consistency across sections
- Redundancy or contradictions
- Anything that feels like "slop" or generic filler
- Whether every sentence carries weight
Read entire document and provide feedback.
When all sections are drafted and refined: Announce all sections are drafted. Indicate intention to review the complete document one more time.
Review for overall coherence, flow, completeness.
Provide any final suggestions.
Ask if ready to move to Reader Testing (for full collaborative workflow) or if they want to refine anything else.
---
Stage 3: Reader Testing
Goal: Test the document with a fresh Claude (no context bleed) to verify it works for readers.
Note: This stage is used in the Full Collaborative workflow. Skip for Streamlined Collaborative workflow (code docs like READMEs, API docs).
Instructions to User
Explain that testing will now occur to see if the document actually works for readers. This catches blind spots - things that make sense to the authors but might confuse others.
With Sub-Agent Access (e.g., Claude Code)
Perform the testing directly without user involvement.
Step 1: Predict Reader Questions
Announce intention to predict what questions readers might ask when trying to discover this document.
Generate 5-10 questions that readers would realistically ask.
Step 2: Test with Sub-Agent
Announce that these questions will be tested with a fresh Claude instance (no context from this conversation).
For each question, invoke a sub-agent with just the document content and the question.
Summarize what Reader Claude got right/wrong for each question.
Step 3: Run Additional Checks
Announce additional checks will be performed.
Invoke sub-agent to check for ambiguity, false assumptions, contradictions.
Summarize any issues found.
Step 4: Report and Fix
If issues found: Report that Reader Claude struggled with specific issues.
List the specific issues.
Indicate intention to fix these gaps.
Loop back to refinement for problematic sections.
Without Sub-Agent Access (e.g., claude.ai web interface)
The user will need to do the testing manually.
Step 1: Predict Reader Questions
Ask what questions people might ask when trying to discover this document. What would they type into Claude.ai?
Generate 5-10 questions that readers would realistically ask.
Step 2: Setup Testing
Provide testing instructions: 1. Open a fresh Claude conversation: https://claude.ai 2. Paste or share the document content (if using a shared doc platform with connectors enabled, provide the link) 3. Ask Reader Claude the generated questions
For each question, instruct Reader Claude to provide:
- The answer
- Whether anything was ambiguous or unclear
- What knowledge/context the doc assumes is already known
Check if Reader Claude gives correct answers or misinterprets anything.
Step 3: Additional Checks
Also ask Reader Claude:
- "What in this doc might be ambiguous or unclear to readers?"
- "What knowledge or context does this doc assume readers already have?"
- "Are there any internal contradictions or inconsistencies?"
Step 4: Iterate Based on Results
Ask what Reader Claude got wrong or struggled with. Indicate intention to fix those gaps.
Loop back to refinement for any problematic sections.
Exit Condition
When Reader Claude consistently answers questions correctly and doesn't surface new gaps or ambiguities, the doc is ready.
Final Review
When Reader Testing passes: Announce the doc has passed Reader Claude testing. Before completion:
1. Recommend they do a final read-through themselves - they own this document and are responsible for its quality 2. Suggest double-checking any facts, links, or technical details 3. Ask them to verify it achieves the impact they wanted
Ask if they want one more review, or if the work is done.
If user wants final review, provide it. Otherwise: Announce document completion. Provide a few final tips:
- Consider linking this conversation in an appendix so readers can see how the doc was developed
- Use appendices to provide depth without bloating the main doc
- Update the doc as feedback is received from real readers
---
Streamlined Workflow
For code documentation (READMEs, API docs, architecture guides), use this 2-stage variant that maintains collaborative principles while skipping Reader Testing.
When to Use Streamlined
- README files
- API documentation
- Architecture guides
- Configuration references
- Module documentation
- Technical references
Streamlined Process
Stage 1: Context Gathering (abbreviated) 1. Ask about doc type and audience 2. Gather relevant code context 3. Identify existing documentation 4. Ask 3-5 clarifying questions
Stage 2: Refinement & Structure 1. Choose appropriate pattern from Code Documentation Patterns 2. Create scaffold with sections 3. For each section:
- Draft based on code analysis
- Ask for user feedback
- Refine through iteration
4. Run quality checklist 5. Deliver final document
Streamlined Checklist
- [ ] Doc type and audience identified
- [ ] Code analyzed for relevant content
- [ ] Appropriate pattern selected
- [ ] All sections drafted
- [ ] User reviewed each section
- [ ] Working examples included
- [ ] Quality checklist passed
---
Code Documentation Patterns
Use these patterns as starting scaffolds in Stage 2 when creating code documentation.
README Generation
Pattern:
# Project Name
Brief description (1-2 sentences)
## Features
- Feature 1
- Feature 2
## Installation
[Installation steps]
## Quick Start
[Minimal working example]
## Configuration
[Key configuration options]
## API Reference
[Link or inline reference]
## Contributing
[Contribution guidelines]
## License
[License type]Process: 1. Read package.json / pyproject.toml / Cargo.toml 2. Identify main entry points 3. List key dependencies 4. Check for existing documentation 5. Draft each section with user input
API Documentation (OpenAPI)
Pattern:
openapi: 3.0.0
info:
title: API Name
version: 1.0.0
paths:
/resource:
get:
summary: Get resources
responses:
'200':
description: SuccessProcess: 1. Scan for REST endpoints (@app.route, router.get, etc.) 2. Extract parameters, types, descriptions 3. Generate OpenAPI spec 4. Add request/response examples
Component Documentation
Pattern:
## ComponentName
**Purpose**: What it does (1 sentence)
**Props/Parameters**:
| Name | Type | Required | Description |
|------|------|----------|-------------|
**Usage**:
[Code example]
**Notes**:
- Important behavior
- Edge casesFunction Documentation
Pattern:
## functionName
**Purpose**: What it does
**Parameters**:
- `param1` (Type): Description
- `param2` (Type): Description
**Returns**: Type - Description
**Example**:
[Code example]
**Throws**: ErrorType - When conditionArchitecture Documentation
Pattern:
# System Architecture
## Overview
[High-level description]
## Component Diagram
[Mermaid diagram]
## Components
| Component | Purpose | Tech Stack | Dependencies |
|-----------|---------|------------|--------------|
## Data Flow
[Description or diagram]
## Security Considerations
[Key security aspects]Process: 1. Identify services/modules 2. Map data stores and integrations 3. Create component diagram 4. Document each component 5. Describe data flow
Configuration Documentation
Pattern:
# Configuration Reference
## Environment Variables
### Required
| Variable | Type | Description |
|----------|------|-------------|
### Optional
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
## Configuration File
[Example config]
## Validation
[Validation rules]Process: 1. Scan config sources (.env, config files, CLI args) 2. Identify required vs optional 3. Document defaults and validation 4. Provide example configurations
---
Quality Checklists
Full Collaborative Workflow
Stage 1: Context Gathering
- [ ] Doc type identified
- [ ] Audience defined
- [ ] Desired impact stated
- [ ] Template reviewed (if provided)
- [ ] Info dump completed
- [ ] Clarifying questions asked
- [ ] No major gaps remain
Stage 2: Refinement & Structure
- [ ] Structure agreed with user
- [ ] Scaffold created
- [ ] Each section:
- [ ] Clarifying questions asked
- [ ] Options brainstormed
- [ ] User curated options
- [ ] Gap check performed
- [ ] Draft created
- [ ] Iteratively refined
- [ ] Full document reviewed for coherence
- [ ] No "slop" or filler content
Stage 3: Reader Testing
- [ ] Reader questions predicted
- [ ] Fresh Claude tested each question
- [ ] Additional checks run
- [ ] All issues addressed
- [ ] Exit criteria met
- [ ] Final review offered
Streamlined Collaborative Workflow
Context Gathering
- [ ] Doc type identified
- [ ] Audience defined
- [ ] Code context gathered
- [ ] Existing docs reviewed
- [ ] Clarifying questions asked
Refinement & Structure
- [ ] Pattern selected
- [ ] Scaffold created
- [ ] Each section drafted and refined
- [ ] User approved each section
- [ ] Code examples tested
- [ ] Quality checklist passed
Code Documentation Quality
- [ ] Purpose clear in first sentence
- [ ] Installation/setup complete
- [ ] Working examples included
- [ ] Edge cases documented
- [ ] API contracts specified
- [ ] Configuration options listed
- [ ] No jargon without explanation
---
Tips for Effective Guidance
Tone:
- Be direct and procedural
- Explain rationale briefly when it affects user behavior
- Don't try to "sell" the approach - just execute it
Handling Deviations:
- If user wants to skip a stage: Ask if they want to skip this and write freeform
- If user seems frustrated: Acknowledge this is taking longer than expected. Suggest ways to move faster
- Always give user agency to adjust the process
Context Management:
- Throughout, if context is missing on something mentioned, proactively ask
- Don't let gaps accumulate - address them as they come up
Artifact Management:
- Use
create_filefor drafting full sections - Use
str_replacefor all edits - Provide artifact link after every change
- Never use artifacts for brainstorming lists - that's just conversation
Quality over Speed:
- Don't rush through stages
- Each iteration should make meaningful improvements
- The goal is a document that actually works for readers