Execute writing tasks autonomously by loading pending tasks, running pre-write queries, checking consistency, writing grounded content, and storing results
Execute writing tasks autonomously to produce manuscript content grounded in the research corpus. This command loads pending writing tasks from the database, runs pre-write queries for context, checks consistency constraints, writes sections based on retrieved knowledge, and stores results in both database and files.
Write manuscript sections based on corpus knowledge without web access. This command operates in write mode where it strictly uses database content for writing. If knowledge gaps are discovered during writing, they are flagged for later research but never filled with web searches.
This command delegates the writing work to the writer agent, which operates in write mode with database-only access.
None. This command reads pending writing tasks from the database:
Query the database to retrieve pending writing tasks respecting dependencies:
# Query pending writing tasks
surreal sql --conn http://localhost:2665 \
--user root --pass root \
--ns bookstrap --db <database-name> \
--query "SELECT * FROM writing_task WHERE status = 'pending' AND blockedBy = [] ORDER BY priority DESC, sequence ASC;"
Filter and prioritize:
Execute writing tasks one at a time, committing progress after each completed section.
Each writing task specifies pre-write queries to gather context from the database. These queries use hybrid RAG combining semantic search, graph traversal, and timeline checks:
Semantic Search - Find similar content by theme:
SELECT * FROM section
WHERE embedding <|5|> $query_vector
ORDER BY vector::similarity(embedding, $query_vector) DESC;
Graph Traversal - Get relevant entities and relationships:
-- Character appearances and relationships
SELECT
->appears_in->section.content,
->knows->character.name,
->confronts->character.name
FROM character:anna;
-- Source support for concepts
SELECT
<-supports<-source.title,
<-supports<-source.reliability
FROM concept:wireless_protocols;
Timeline Queries - Establish what happened before this point:
-- Events before current sequence
SELECT * FROM event
WHERE sequence < $current_sequence
ORDER BY sequence DESC
LIMIT 10;
-- Previous sections in chapter
SELECT * FROM section
WHERE chapter = $chapter AND sequence < $section_sequence
ORDER BY sequence DESC;
Combined Hybrid Query:
-- Semantic + graph + timeline
SELECT * FROM section
WHERE embedding <|3|> $query_vector
AND ->appears_in->character:anna
AND sequence < 5
ORDER BY sequence;
Run all pre-write queries specified in task metadata and collect results for context.
Before writing, verify consistency constraints from task metadata:
-- Character state violations (can't appear if dead)
SELECT * FROM character:anna
WHERE status = 'dead'
AND death_sequence < $current_sequence;
-- Location not introduced yet
SELECT * FROM location:safehouse
WHERE introduced = false;
-- Timeline contradictions
SELECT * FROM event
WHERE sequence > $current_sequence
AND date < $current_section_date;
If any constraint fails:
Do NOT write if consistency checks fail.
Verify all required knowledge exists in the database:
-- Check required knowledge from task metadata
SELECT * FROM knowledge_gap
WHERE id IN $required_knowledge
AND resolved = false;
If gaps found:
CRITICAL: Write mode NEVER accesses web. Gaps are flagged, not filled.
With context gathered and constraints verified, write the section:
Writing Principles:
Output: Section content as markdown text
After writing, execute post-write operations specified in task metadata:
1. Generate Embedding:
python ./scripts/generate-embedding.py \
--text "$section_content" \
--provider <configured-provider> \
--model <configured-model>
2. Store Section in Database:
CREATE section SET
content = $content,
embedding = $embedding_vector,
chapter = $chapter_number,
sequence = $section_sequence,
word_count = $word_count,
status = 'draft',
created_at = time::now();
3. Extract Entities Mentioned:
python ./scripts/extract-entities.py \
--content "$section_content" \
--section-id <section-id> \
--mode writing
This extracts:
4. Create Relationships:
-- Link section to cited sources
RELATE section:<id>->cites->source:<source-id>;
-- Track character appearances
RELATE character:<id>->appears_in->section:<id>;
-- Location usage
RELATE section:<id>->located_in->location:<id>;
-- Event sequence
RELATE event:<new-id>->follows->event:<previous-id>;
5. Update Timeline:
-- Add events to timeline
CREATE event SET
name = $event_name,
description = $event_description,
sequence = $sequence_number,
date = $event_date,
section = section:<id>;
-- Link to previous events
RELATE event:<id>->precedes->event:<next-id>;
6. Write to Manuscript File:
# Create manuscript file using configured naming pattern
mkdir -p ./manuscript/chapter-$chapter_number/
cat > "./manuscript/chapter-$chapter_number/section-$section_sequence-$slug.md" <<EOF
# $section_title
$section_content
---
*Generated: $(date)*
*Word count: $word_count*
*Status: draft*
EOF
If writing reveals missing knowledge (character backstory, historical detail, technical specification):
CREATE knowledge_gap SET
question = $gap_question,
context = $gap_context,
discovered_during = 'writing',
discovered_in = section:<id>,
blocks_tasks = [task:<id>],
resolved = false,
created_at = time::now();
Log the gap for later research cycle.
After each successfully written section:
git add manuscript/ data/
git commit -m "[bookstrap] Write: Completed section '$section_title' (Chapter $chapter)
Section: chapter-$chapter-section-$sequence
Word count: $word_count
Entities extracted: $entity_count
Relationships created: $relationship_count
Citations: $citation_count
Gaps flagged: $gap_count
Co-Authored-By: Claude <[email protected]>"
Invoke the writer agent to perform the detailed writing work:
# Load writer agent with context
# Agent will:
# 1. Load next pending writing task
# 2. Run pre-write queries
# 3. Check consistency constraints
# 4. Verify required knowledge exists
# 5. Write section grounded in context
# 6. Generate embeddings
# 7. Extract entities and create relationships
# 8. Write to manuscript file
# 9. Flag any gaps discovered
# 10. Commit progress
# 11. Continue to next task or exit if blocked
The writer agent has read+write database access, NO web access, and uses the writing, surrealdb, outlining, and genre-specific skills.
The writer agent continues processing tasks until:
Report writing progress to the user:
WRITING EXECUTION
=================
Configuration:
- Embedding provider: Gemini (text-embedding-004)
- Database: bookstrap/my_book
- Manuscript dir: ./manuscript
- Auto-commit: enabled
TASK 1/32: Chapter 1, Section 2
--------------------------------
Title: "The Training Begins"
Sequence: chapter-1-section-2
Required knowledge: ✓ All available
Dependencies: ✓ None blocking
Pre-write queries:
→ Semantic search: 5 similar passages found
→ Graph query: character:anna relationships (3 connections)
→ Timeline: 2 previous events established
→ Sources: 4 relevant sources retrieved
Consistency checks:
✓ Characters: anna (status: alive, introduced: true)
✓ Location: beaulieu_training_facility (introduced: true)
✓ Timeline: sequence valid (no contradictions)
Writing section...
→ Content: 1,250 words written
→ Voice: matches BRD specifications
→ Citations: 3 sources cited
→ Genre conventions: thriller pacing maintained
Post-write storage:
→ Embedding generated (768 dimensions)
→ Section stored: section:ch1-sec2
→ Entities extracted: 2 new characters, 1 event
→ Relationships: 5 edges created
→ Manuscript file: ./manuscript/chapter-01/section-02-training-begins.md
Gaps flagged: 1
! "Specific wireless code protocols used in 1943" (flagged for research)
Committed: [def5678]
---
TASK 2/32: Chapter 1, Section 3
--------------------------------
Title: "First Transmission"
Sequence: chapter-1-section-3
Required knowledge: ✗ Gap blocking
Dependencies: ✓ Previous section complete
Consistency checks:
✓ All constraints pass
Knowledge gaps:
✗ Required: "Wireless code protocols 1943" (unresolved)
Task blocked by knowledge gap.
Skipping to next unblocked task...
---
TASK 3/32: Chapter 2, Section 1
--------------------------------
Title: "Arrival in Lyon"
[...]
---
PROGRESS SUMMARY
================
Tasks completed: 8/32
Tasks blocked by gaps: 3
Sections written: 8
Total word count: 9,850 / 80,000 target (12.3%)
Chapters started: 3/10
Entities extracted: 24
- Characters: 8
- Locations: 5
- Events: 11
- Concepts: 7
Relationships created: 47
Citations: 22 sources cited
Gaps flagged: 3
Commits: 8
Time elapsed: 24 minutes
NEXT STEPS
----------
Knowledge gaps blocking 3 tasks:
1. "Wireless code protocols 1943"
2. "Lyon Resistance safe house locations"
3. "German counter-intelligence procedures"
Recommended: /bookstrap-plan-research (generate research tasks for gaps)
Then: /bookstrap-research (fill gaps)
Then: /bookstrap-write (resume writing)
Continue writing unblocked tasks: /bookstrap-write
Check status: /bookstrap-status
Query content: /bookstrap-query "Show me all scenes with Anna"
This command operates in write mode:
Runs fully autonomously:
Prioritizes consistency:
Writing behavior configured in bookstrap.config.json:
{
"output": {
"manuscript_dir": "./manuscript",
"file_format": "markdown",
"naming": {
"chapter": "chapter-{{sequence}}-{{slug}}.md",
"section": "{{chapter}}/section-{{sequence}}-{{slug}}.md"
}
},
"git": {
"auto_commit": true,
"commit_after": "task",
"message_format": "[bookstrap] {{task_type}}: {{task_subject}}"
},
"writing": {
"min_sources_per_claim": 1,
"enforce_consistency": true,
"auto_flag_gaps": true,
"voice_check": true,
"genre_conventions": true
}
}
Settings:
manuscript_dir: Output directory for manuscript filesfile_format: Output format (markdown)naming: Filename templates for chapters and sectionsauto_commit: Commit after each section (recommended)min_sources_per_claim: Minimum citations for factual claimsenforce_consistency: Check constraints before writingauto_flag_gaps: Automatically detect and flag knowledge gapsvoice_check: Verify voice matches BRDgenre_conventions: Apply genre-specific patterns| Error | Recovery |
|---|---|
| Knowledge gap found | Flag gap, skip task, continue to next |
| Consistency check fails | Log violation, skip task, continue |
| Required knowledge missing | Mark task blocked, continue |
| Database write failure | Abort, report error, preserve uncommitted work |
| Embedding generation fails | Retry up to 3 times, then skip section |
| Manuscript file write fails | Abort, report error (database still has content) |
| Timeline contradiction | Flag inconsistency, skip task, recommend edit |
| Character state violation | Flag violation, skip task, recommend fix |
Before running /bookstrap-write:
/bookstrap-init must have been run/bookstrap-ingest and /bookstrap-research completed/bookstrap-plan-write must have created tasks/bookstrap-plan-write - Generate writing tasks (run this first)/bookstrap-research - Fill knowledge gaps (run when blocked)/bookstrap-edit - Review and polish written content (run after writing)/bookstrap-status - Monitor writing progress and gap status/bookstrap-query - Query written content and entities| Agent | Role |
|---|---|
writer | Executes writing tasks, enforces consistency, flags gaps |
| Skill | Purpose |
|---|---|
writing/ | Core writing workflow, voice consistency, citation integration |
surrealdb/ | Database query patterns for context retrieval and storage |
outlining/ | Story structure, chapter organization, pacing |
genres/* | Genre-specific conventions (thriller pacing, historical accuracy, etc.) |
| Script | Purpose |
|---|---|
generate-embedding.py | Generate embeddings via configured provider |
extract-entities.py | LLM-based entity extraction from written content |
# After generating writing tasks, execute writing
/bookstrap-plan-write
/bookstrap-write
# Writing interrupted? Resume where you left off
/bookstrap-write
# Check progress
/bookstrap-status
# If blocked by gaps, run research cycle
/bookstrap-plan-research
/bookstrap-research
/bookstrap-write
# Continue writing after gaps filled
/bookstrap-write
# Review written content
/bookstrap-edit
This command is part of the research-write cycle:
init → ingest → plan-research → research
↑ │
│ ▼
│ plan-write → write → edit
│ │
└──── gaps ────┘
When writing discovers knowledge gaps:
/bookstrap-plan-research to generate research tasks/bookstrap-research to fill gaps/bookstrap-write to resume writing (now unblocked)This separation ensures:
Calculate and report:
Detailed logging for transparency:
[2024-01-15 16:45:12] [WRITE] Task 1/32 started: Chapter 1, Section 2
[2024-01-15 16:45:13] [QUERY] Pre-write: semantic search (5 results)
[2024-01-15 16:45:14] [QUERY] Pre-write: graph traversal (3 relationships)
[2024-01-15 16:45:15] [QUERY] Pre-write: timeline check (2 events)
[2024-01-15 16:45:16] [CHECK] Consistency: All constraints pass
[2024-01-15 16:45:17] [CHECK] Knowledge: All required knowledge available
[2024-01-15 16:45:25] [WRITE] Section complete: 1,250 words
[2024-01-15 16:45:26] [EMBED] Embedding generated (768 dims)
[2024-01-15 16:45:27] [DB] Section stored: section:ch1-sec2
[2024-01-15 16:45:28] [EXTRACT] Entities: 2 characters, 1 event, 1 location
[2024-01-15 16:45:29] [GRAPH] Created 5 relationships
[2024-01-15 16:45:30] [FILE] Written: ./manuscript/chapter-01/section-02-training-begins.md
[2024-01-15 16:45:31] [GAP] Flagged: "Wireless code protocols 1943"
[2024-01-15 16:45:33] [GIT] Committed: def5678
[2024-01-15 16:45:34] [WRITE] Task 1/32 complete (22s)
This command is a thin wrapper that:
writer agentThe actual writing logic lives in the writer agent to keep concerns separated.
Re-running /bookstrap-write is safe:
Research mode vs. Write mode:
This command operates exclusively in write mode and never accesses the web. Writing discovers gaps but never fills them.
Verify each section matches BRD voice specifications:
Apply genre-specific patterns from loaded genre skills:
Maintain citation coverage:
Ensure chronological consistency:
Status: 32/32 tasks blocked by knowledge gaps
Action: Run research cycle
Solution:
/bookstrap-plan-research
/bookstrap-research
/bookstrap-write
Task: Chapter 3, Section 2
Error: Character 'anna' marked dead in previous chapter
Action: Task skipped, flagged for review
Possible solutions:
Error: Cannot connect to SurrealDB at localhost:2665
Action: Writing paused, no progress lost
Automatic recovery:
/bookstrap-write to resumeSection: Chapter 2, Section 5
Error: Embedding API rate limit exceeded
Action: Retrying in 60s (attempt 1/3)
Automatic recovery:
Write mode NEVER accesses web:
All factual claims must cite sources:
All writing committed to git:
Dual storage for safety:
Track writing quality: