πŸ“– Stories Maker V4 β€” Kitchen Pipeline

Multi-genre content engine with deterministic quality gates β€” 11 phases, 17 gates, 7 genres, 71 tests

System Overview

╔══════════════════════════════════════════════════════════════════════╗ β•‘ AVA v2 STORY ORCHESTRATOR β•‘ β•‘ β•‘ β•‘ source_data ───▢ ORCHESTRATOR FSM (main.py) β•‘ β•‘ β•‘ β•‘ Phase 0 ──G0──▢ Phase 1 ──G1──▢ Phase 2 ──G2──▢ Phase 3 β•‘ β•‘ [IDEATION] [RESEARCH] [BIBLE_DRAFT] [BIBLE_LOCK] πŸ”’ β•‘ β•‘ G3 (HUMAN βœ‹) β•‘ β•‘ β”‚ β•‘ β•‘ Phase 4 β—€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β•‘ [OUTLINE] G3.5 + G4A/B/C β•‘ β•‘ β”‚ β•‘ β•‘ Phase 5 [SCENE_LOOP] ← Core production loop β•‘ β•‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β•‘ β•‘ β”‚ for each scene_spec: β”‚ β•‘ β•‘ β”‚ Writer β†’ 6 Auditors β”‚ β•‘ β•‘ β”‚ β†’ Gate5 Tier1+Tier2 β”‚ β•‘ β•‘ β”‚ β†’ G5 token or REWRITE β”‚ β•‘ β•‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β•‘ β”‚ β•‘ β•‘ Phase 6 [ASSEMBLY] G6 + G7 β•‘ β•‘ Phase 7 [OUTPUT] G8 (HUMAN βœ‹) β•‘ β•‘ Phase 8 [THUMB/SEO] G8.5 β•‘ β•‘ Phase 9 [UPLOAD] G9 + G9.5 β•‘ β•‘ Phase 10 [MONITOR] G10 β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Design Pillars

DeterminismSHA-256 gate tokens β€” identical inputs = identical decisions
Sequential_PHASE_ORDER list β€” no skipping allowed
SeparationAuditors evaluate β†’ Arbiter decides β†’ Gates enforce β†’ Writer creates
ImmutabilityBible locked after G3 β€” tokens append-only JSONL
Fail-safePolicy violation β†’ immediate ABORT
Cost-consciousHard cost limits per mode β€” escalations abort, not loop

βš™οΈ 11 Pipeline Phases (0-10)

🚦 Gate System β€” 17 Gates

Mα»—i gate issue mα»™t GateToken (SHA-256 checksum, append-only JSONL). bypass_allowed structurally = False. Self-pass prevention: Writer khΓ΄ng thể issue token cho chΓ­nh mΓ¬nh.

GatePhaseTypeIssuerDescription
G00 β€” IdeationAutoArbiterPolicy bundle loaded
G11 β€” ResearchAutoArbiterSource quality β‰₯ 0.7
G22 β€” Bible DraftAutoArbiterOriginality score β‰₯ 0.85
G33 β€” Bible Lockβœ‹ HumanHumanBible approved by Rio
G3.54 β€” OutlineAutoArbiterScene spec JSON schema valid
G4A4 β€” OutlineAutoArbiterCanon consistency
G4B4 β€” OutlineAutoArbiterTimeline causality
G4C4 β€” OutlineAutoArbiterOriginality pre-screen
G44 β€” OutlineAutoArbiterCombined G4A+B+C summary
G55 β€” Scene LoopAutoArbiterPer-scene quality (Γ—N scenes)
G66 β€” AssemblyAutoArbiterCross-scene batch audit
G76 β€” AssemblyAutoArbiterAssembly word-count + structure
G87 β€” Outputβœ‹ HumanHumanFinal QA approved by Rio
G8.58 β€” Thumb/SEOAutoArbiterSEO package generated
G99 β€” UploadAutoArbiterOutput package complete
G9.59 β€” UploadAutoArbiterUpload confirmed
G1010 β€” MonitorAutoArbiterPost-publish analytics started

Gate 5 β€” Two-Tier Decision System

Tier 1 β€” Binary Decision (6 dimensions)

RuleConditionDecision
1Policy = FAILABORT (no recovery)
2All 6 = PASS→ Advance to Tier 2
31-2 non-policy FAILs, attempt < maxREWRITE
43+ non-policy FAILsESCALATE
5Any FAIL, attempt β‰₯ maxESCALATE (Guided) / ABORT (Auto)

Tier 2 β€” Quality Score Thresholds

DimensionMinimum
Consistency9.0
Originality8.5
Hook8.5
Cliffhanger8.0
Emotional8.5
TTS9.0

Any score below minimum β†’ REWRITE (even if all Tier-1 passed). All scores β‰₯ minimum β†’ PASS β†’ G5 token issued.

🎭 Genre Registry β€” 7 Genres (V4)

GenreLabelDefault ArchetypeVillain LayersBackstoryThesis
revengeFamily Revenge / Betrayalbetrayed_victim1front_loadednarrator
healingHealing / Recoverywounded_survivor1front_loadednarrator
redemptionRedemption / Invisible Goodinvisible_giver1wovenenvironmental
hidden_identityHidden Identity / Competence Revealsuppressed_identity2earnedcharacter_spoken
injusticeInjustice / Wrongful Accusationwrongly_accused2revelationprotagonist_earned
transformationTransformation / Underdog Riseunderdog1wovenenvironmental
defaultDefault (Legacy)betrayed_victim1front_loadednarrator

Required Beats per Genre

πŸ—‘οΈ Revenge

betrayal β†’ discovery β†’ confrontation β†’ resolution

πŸ’š Healing

wound β†’ breakdown β†’ turning_point β†’ acceptance

πŸ•ŠοΈ Redemption

selfless_act β†’ unrewarded_stretch β†’ unfair_opponent_rise β†’ opponent_fall β†’ quiet_payoff

🎭 Hidden Identity

hidden_state β†’ crisis_trigger β†’ competence_reveal β†’ backstory_earn β†’ villain_layer2_exposed β†’ identity_restored

βš–οΈ Injustice

accusation β†’ isolation β†’ ally_appears β†’ evidence_found β†’ true_villain_exposed β†’ vindication

πŸ¦‹ Transformation

low_point β†’ catalyst β†’ first_win β†’ setback β†’ mastery β†’ proving_moment

πŸ‘€ Archetype Registry β€” 7 Protagonist Types

ArchetypeLabelTraitsCompatible Genres
betrayed_victimVictim of BetrayalTrusting β†’ discovers betrayal β†’ fights backrevenge, healing
wounded_survivorWounded SurvivorDeep wound β†’ survival mode β†’ healing journeyhealing, transformation
invisible_giverInvisible GiverGives without expectation β†’ unrewarded β†’ quiet payoffredemption
suppressed_identitySuppressed IdentityHides true self β†’ crisis forces reveal β†’ identity restoredhidden_identity, transformation
wrongly_accusedWrongly AccusedFalsely blamed β†’ fights system β†’ truth emergesinjustice
underdogUnderdogOverlooked β†’ catalyst event β†’ rises through efforttransformation, redemption
hidden_competenceHidden CompetenceAppears ordinary β†’ forced to act β†’ reveals expertisehidden_identity

πŸ“œ Backstory Delivery Modes β€” 4 Modes

πŸ“– Front-loaded

Backstory told in Act 1, action follows.

Window: First 25% of story (0.0 – 0.25)
revenge healing

πŸ† Earned

Protagonist acts first β†’ audience earns backstory later.

Window: Middle 40-70% (0.4 – 0.7)
Rule: Protagonist MUST demonstrate competence BEFORE backstory revealed
hidden_identity

🧡 Woven

Backstory fragments woven throughout, building incrementally.

Window: Distributed 10-80% (0.1 – 0.8)
Fragments: 3-5 flashback moments
redemption transformation

πŸ’₯ Revelation

True backstory only revealed near climax β€” reframes everything.

Window: Late 70-90% (0.7 – 0.9)
Rule: Early scenes MUST work WITHOUT backstory context
injustice hidden_identity

πŸ’‘ Thesis Delivery Modes β€” 4 Modes

ModeDescriptionStrengthCompatible Genres
narratorNarrator directly delivers moral/themeClear but can feel preachyrevenge, healing
character_spokenSupporting character delivers core truthFeels earned β€” from within storyhidden_identity
protagonist_earnedProtagonist realizes truth through experienceMost powerful β€” earned through actioninjustice, transformation
environmentalNo one states thesis β€” shown through contrasting actionsMost subtle β€” audience concludesredemption

πŸ” Auditor System β€” 6 Dimensions

All 6 auditors run concurrently via asyncio.gather(). Each returns AuditResult with verdict (PASS/FAIL), error code, severity, quality scores.

AuditorDimensionError CodeWhat It Checks
CanonCharacter consistencyCANON_CONFLICTCharacters match bible traits, arcs, relationships
TimelineCausality + temporalTIMELINE_ERROREvent ordering, prerequisites, temporal logic
FactFactual verificationFACT_DRIFTClaims match fact ledger, no contradictions
OriginalityDuplicate detectionLOW_ORIGINALITYContent uniqueness, no plagiarism
PolicyContent compliancePOLICY_VIOLATIONNo dark psych, no celebrity images, ethical content
StyleVoice + toneSTYLE_DRIFTNarrator persona consistency, tone matching

Conflict Resolution Priority (highest β†’ lowest)

1. FACT β†’ 2. CANON β†’ 3. TIMELINE β†’ 4. ORIGINALITY β†’ 5. STYLE β†’ 6. POLICY (always ABORT)

When auditors disagree on same dimension: FAIL verdict wins (conservative).

✏️ Rewrite Engine

Scope Escalation Ladder

AttemptScopeDescriptionContext Loaded
1L1/L2Minimal fix (word/sentence)Target sentence or paragraph
2L3Paragraph rewriteScene section + bible cast summary
3L4Full scene rewrite (final attempt)Full bible, timeline, fact ledger, scene spec

Cost Containment

🎭 Villain Architecture β€” 2-Layer System

Layer 1 β€” Visible Antagonist

Always present. Direct opposition to protagonist.

Role: Executor
Arc: escalate β†’ overreach β†’ exposed
Example: "Tristan" (Hidden Identity)

Layer 2 β€” Hidden Architect

Optional (for hidden_identity, injustice). Creates "second twist".

Role: Architect
Arc: invisible β†’ hints β†’ full exposure Act 3
Reveal: Scene 60-90% of story
Example: "Ashford Sr." (Hidden Identity)

πŸ“₯ Intake Schema V2 β€” New Fields

# input_intake.yaml β€” V2 Schema
genre: "hidden_identity"           # 7 options tα»« GENRE_REGISTRY

protagonist:
  name: "Elena Vasquez"
  archetype: "suppressed_identity" # tα»« ARCHETYPE_REGISTRY
  visible_persona: "Quiet cleaning lady"
  hidden_truth: "Former international translator"

villain_architecture:
  layers: 2
  layer_1: { name: "Tristan", role: "executor" }
  layer_2: { name: "Ashford", role: "architect", reveal_timing: 0.75 }

backstory_mode: "earned"           # 4 modes
thesis:
  mode: "character_spoken"         # 4 modes
  core_message: "Identity isn't what they took..."
  speaker: "Elena's mother"

unfair_opponent:                   # Optional (redemption genre)
  name: "Jerome"
  philosophy: "Take everything, give nothing"

emotional_curve_override: null     # null = use genre default

Validation Rules

  1. Genre must be in GENRE_REGISTRY
  2. Archetype must be compatible with genre
  3. Villain layers must match genre default or be justified
  4. Backstory mode must be compatible with genre
  5. Thesis mode must be compatible with genre
  6. If unfair_opponent β†’ genre should be "redemption"
  7. If villain layers == 2 β†’ layer_2.reveal_timing must be 0.6-0.9

πŸ’Ύ State Management β€” 5 Persistent Objects

ObjectFileLifecycleKey Feature
Bible Lockstory_bible_lock.jsonCreated Phase 3 β†’ locked foreverSHA-256 checksum, immutable after G3
Fact Ledgerfact_ledger.jsonUpdated Phase 1-5FACT/INFERENCE/CREATIVE/UNKNOWN labels
Timeline Gridtimeline_grid.jsonUpdated Phase 1-5Causality validation via prerequisites
Scene Specscene_specs/{id}.jsonCreated Phase 4, read-only Phase 5Goal, beats, emotional turn, hooks
Scene Logscene_logs/{id}.jsonAppend-only Phase 5Version history, scores, rewrite tasks

πŸ”€ Guided vs Auto Mode

BehaviourGuidedAuto
G3 (Bible Lock)Pauses β†’ PENDING_HUMANNo pause
G8 (Final QA)Pauses β†’ PENDING_HUMANNo pause
ESCALATE in scenePauses β†’ PENDING_HUMANReturns ABORTED
Model strategyclaude-opus-4.6 (all agents)Hybrid (haiku auditors, sonnet writer)
Cost limit (soft/hard)$200 / $300$100 / $150
Max rewrites15 per scene15 per scene

πŸ’° Cost Optimisation Strategy

Model Selection Matrix

Agent RoleGuided ModelAuto Model
Scene Writerclaude-opus-4.6claude-sonnet-4
Canon Auditorclaude-opus-4.6claude-haiku-3
Timeline Auditorclaude-opus-4.6claude-haiku-3
Fact Auditorclaude-opus-4.6claude-sonnet-4
Originality Auditorclaude-opus-4.6claude-haiku-3
Policy Auditorclaude-opus-4.6claude-haiku-3
Style Auditorclaude-opus-4.6claude-haiku-3

Budget Safeguards

Per-run cost flow:
  tokens_used (per scene version in SceneLog)
      ↓
  credits_used (accumulated)
      ↓
  soft_limit reached β†’ WARNING, continue
      ↓
  hard_limit reached β†’ ABORTED("Cost limit exceeded")

🧩 Component Map

orchestrator_v2/
β”œβ”€β”€ main.py              # Orchestrator FSM entry point
β”œβ”€β”€ config.py            # GENRE_REGISTRY, ARCHETYPE_REGISTRY, modes, thresholds
β”‚
β”œβ”€β”€ gates/               # Gate enforcement layer
β”‚   β”œβ”€β”€ token_engine.py  # GateToken + SHA-256 checksums
β”‚   β”œβ”€β”€ gate_5.py        # Tier-1 binary + Tier-2 numeric
β”‚   β”œβ”€β”€ gates_0_3.py     # G0, G1, G2, G3
β”‚   β”œβ”€β”€ gates_4.py       # G3.5, G4A, G4B, G4C
β”‚   └── gates_6_8.py     # G6, G7, G8
β”‚
β”œβ”€β”€ arbiter/             # Decision engine
β”‚   β”œβ”€β”€ decision_engine.py
β”‚   └── phase2_mode.py   # AUTO escalation handler
β”‚
β”œβ”€β”€ auditors/            # 6 quality auditors
β”‚   β”œβ”€β”€ canon_auditor.py
β”‚   β”œβ”€β”€ timeline_auditor.py
β”‚   β”œβ”€β”€ fact_auditor.py
β”‚   β”œβ”€β”€ originality_auditor.py
β”‚   β”œβ”€β”€ policy_auditor.py
β”‚   └── style_auditor.py
β”‚
β”œβ”€β”€ agents/              # Sub-agent integration
β”‚   β”œβ”€β”€ intake_validator.py   # V4 cross-validation
β”‚   β”œβ”€β”€ bible_builder.py      # Expanded character sheet
β”‚   β”œβ”€β”€ scene_builder.py      # Backstory placement, villain reveal
β”‚   β”œβ”€β”€ scene_writer.py
β”‚   β”œβ”€β”€ story_architect.py
β”‚   β”œβ”€β”€ renderer.py
β”‚   β”œβ”€β”€ thumbnail_generator.py
β”‚   └── youtube_uploader.py
β”‚
β”œβ”€β”€ state/               # Persistent state objects
β”‚   β”œβ”€β”€ bible_lock.py
β”‚   β”œβ”€β”€ fact_ledger.py
β”‚   β”œβ”€β”€ timeline_grid.py
β”‚   β”œβ”€β”€ scene_spec.py
β”‚   └── scene_log.py
β”‚
β”œβ”€β”€ rewrite/
β”‚   └── rewrite_engine.py
β”‚
β”œβ”€β”€ context/
β”‚   └── context_manager.py
β”‚
β”œβ”€β”€ dashboard/           # Dashboard connector
β”‚   └── dashboard_connector.py
β”‚
└── tests/               # 71 passing tests

AVA Stories Maker V4 β€” Kitchen Pipeline Documentation
Last updated: 2026-03-24 | Branch: dev | Commit: cc91ff2