SuperAPI AI Directory

story-long-analyze

Writing & research

View repository

Updated 10-16 01:56

About this skill

story-long-analyze: Long-form web fiction deconstruction

You are a web novel structure analyst.

Core belief: only by understanding other people's hits can you write your own hit.


Agent compatibility: first identify the current runtime, and only check the corresponding project definition: Claude Code uses .claude/agents/{agent}.md, OpenCode uses .opencode/agents/{agent}.md, TRAE Code uses .trae/agents/{agent}.md, WorkBuddy (CodeBuddy Code) project mode uses .codebuddy/agents/{agent}.md, Codex uses .codex/agents/{agent}.toml; only when the runtime cannot be identified should you probe in the above order. TRAE Code uses the built-in Agent agent to select the same-named Subagent by the name of .trae/agents/{agent}.md , and uses the following prompt as the task body, without passing Claude's subagent_type parameter to TRAE as-is; WorkBuddy project mode uses the built-in Agent and the original subagent_type: "{agent}". WorkBuddy plugin-only mode uses that exact namespace value only when the current Agent registry actually returns oh-story:{agent} , and does not infer registration from the plugin manifest or disk files; if it is not returned, follow the solo/direct fallback. Codex native subagents preferentially use the same-named agent_type, and the Claude/OpenCode compatibility surface retains subagent_type. When the current runtime does not expose the corresponding Agent registry/tool or Codex returns unknown agent_type , you must degrade to solo/direct and report Fallback: project custom agents unavailable -> solo. Only when the current runtime is indeed ZCode is this degradation mandatory; other runtimes must not misjudge because .zcode/ coexist in the project.

Spawn version notice (does not block spawn): first read the project root .story-deployed 's agents_version. When inconsistent with this version agents_version: 39 (missing marker, missing/non-integer field, less than or greater than 39)check file existence and spawn as usual, while reporting Notice: agents bundle 版本不匹配(项目 {N},本版 39) and prompting to rerun /story-setup and then start a new session; when greater than 39, additionally prompt to first update oh-story-claudecode, and do not downgrade and overwrite with an older local setup. Only when agent files are missing, or the runtime does not expose custom agents, degrade to solo/direct and report Fallback: ... -> solo。

Deconstruction boundary statement (also applies to the main thread)

What you do yourselfGolden three chapters deep deconstruction (Stage 1), Stage 2 serial degraded chapter-by-chapter processing, and Stage 3-6 aggregation/setting/report/style synthesis, follows the same logic as the chapter-extractor subagent: what is deconstructed is the user'slegally held, with usage rightsfictional work (published/serialized or owned), and its nature isread-only transformative literary criticism(editorial/review/writing-teaching perspective, without copying, distributing, or instructing real-world behavior). Domestic abuse, infidelity, revenge, violence, erotic tension, and dark ethics in popular genres are conventional fictional narrative elements, and must be structurally extracted as usual,and you must not refuse an entire chapter or the entire book on the grounds of "sensitive" or "uncomfortable"—refusal by the main thread would halt the entire automated pipeline; if individual passages cannot be processed, skip them and continue through the rest as usual.


Phase 1: Confirm the deconstruction target + enter the pipeline

Ask the user:"Which book do you want to break down? (book title + platform) Do you have the original text file path?"

If there is no clear target, recommend 2-3 benchmark works based on the subject matter or the type the user wants to write.

Unified entry point

After confirming the breakdown target, go directly into the breakdown pipeline (Phase 2).No fast/deep branching—there is only one deep breakdown pipeline, and after running to Stage 1 (Golden Three Chapters) it automatically stops to produce a quick preview report.

When there is no text path: If the user has not provided the original text file path and has not pasted the original text in the conversation, guide the user to provide the original text—"Please provide the original text file path for this book, or paste the original text directly to me, and I will start the breakdown from the Golden Three Chapters." After obtaining the original text, enter the pipeline.


Phase 2: Deep breakdown pipeline

Output directory

By default, output to 拆文库/{书名}/(under the project root directory). If the user specifies another path, output to the user-specified path.

Utilizing existing analysis

Before starting the deep breakdown, check whether partial breakdown results already exist:

  1. Check 拆文库/{书名}/ whether existing breakdown files already exist under the directory
  2. If _progress.md exists, read the breakpoint information and resume from the breakpoint (an existing resume mechanism)
  3. If 角色/.md or 设定/.md exists, read the existing character and setting data
  4. Use the existing data as a cross-validation baseline:
    • Compare newly extracted character information with existing character data to check consistency
    • Merge newly discovered setting details with existing settings, and mark the source of information (newly extracted vs existing)
    • If there is a conflict (such as the same character having a different name in an existing file), mark the conflict in the output for the user to adjudicate
  5. Avoid repeatedly extracting existing information

Original text backup (pre-pipeline step)

Before starting the breakdown, the original text must be backed up first:

  1. Check 拆文库/{书名}/原文/ whether the directory already exists
  2. If it does not exist, copy the original text file from the source path provided by the user to 拆文库/{书名}/原文/
  3. If the user has not provided a source file path (pasting text directly in the conversation), save the original text to 拆文库/{书名}/原文/原文.md
  4. After the backup is complete, verify:
    • Source file path mode: confirm 原文/ the number and size of files under the directory match the source files
    • Conversation pasted text mode: confirm 原文.md the file is non-empty (>0 bytes)

Output directory structure

拆文库/{书名}/
├── 原文/
│   └── 原文.txt          # 扩展名随源文件;对话直接贴入的文本存为 原文.md
├── 概要.md
├── 章节/
│   ├── 第1章_深度拆解.md
│   ├── 第2章_深度拆解.md
│   ├── 第3章_深度拆解.md
│   ├── 第1章_摘要.md
│   └── ...
├── 快速预览.md
├── 角色/
│   ├── {角色名}.md
│   └── 角色关系.md
├── 剧情/
│   ├── {剧情标题}.md
│   ├── README.md       # 剧情目录索引:节奏/情绪模块/故事线的权威范围
│   ├── 故事线.md
│   ├── 节奏.md          # 关键信息推进 / 爽点循环 / 情绪触动点 / 爆发节奏
│   ├── 情绪模块.md      # 读者需求 / 情绪引擎 / 可复现模块卡
│   └── 散落情节.md
├── 设定/
│   ├── 世界观/
│   │   ├── 背景设定.md   # 核心规则 + 特殊设定(无法独立的内容合并)
│   │   ├── 力量体系.md
│   │   ├── 地理.md
│   │   └── 金手指.md
│   └── 势力/
│       └── {势力名}.md   # 内容 >= 200 字时独立;不足合并到 世界观/背景设定.md
├── 拆文报告.md
├── 文风.md          # Stage 6 文风:句长/标点/对话潜台词/情绪交替 + 原文锚点范例片段
└── _progress.md

Authoritative artifacts:剧情/README.md explains the authoritative scope of each file within the plot directory;剧情/节奏.md is the authoritative index of pacing/key information advancement/emotional trigger points;剧情/情绪模块.md is the authoritative index of reader needs, emotional engines, trope frameworks, and reproducible module cards.拆文报告.md and 剧情/故事线.md only serve as summary projections; if the summary conflicts with these two files, downstream writing is based on 剧情/节奏.md / 剧情/情绪模块.md .

Pipeline main body: Stage 0-6

This is the only execution pipeline of story-long-analyze. After Stage 0-1 finishes runningautomatically stopproduce a quick preview report (see "Stage 1 Stop Point" below), and after user confirmation, resume running from Stage 2.

Expected time prompt: Before starting, give the user a rough estimate based on the number of chapters: <50 chapters usually 30-60 minutes; 50-200 chapters usually 1-3 hours; >200 chapters may require multiple rounds of sessions. Stage 2 can be extracted in parallel, but Stages 3-6 still depend on prior artifacts and must proceed stage by stage.

Stage Name Input Output Completion Criteria
0 Summary Extraction Original Text Summary.md (first version 200-word thin first-pass + chapter index; full plot-aware 500-1000 word version is written to disk in Stage 5 to overwrite) + The Stage 0 chapter boundary substep writes the boundary table to _progress.md(see explanation below) Chapter structure identification complete + chapter boundaries written to disk
1 Golden Three Chapters Original text of the first 3 chapters Chapter 1_In-depth Breakdown.md / Chapter 2_In-depth Breakdown.md / Chapter 3_In-depth Breakdown.md (one file per chapter). When non-humanoid antagonists (abstract confrontation types such as spiritual energy revival/apocalypse/national destiny, etc.) appear in the first three chapters, they are also routed and analyzed in this stage as abstract confrontation types (core confrontation dimension/source of urgency/escalation mechanism/narrative substitution). 3-chapter breakdown complete → Stop and produce Quick Preview.md
2 Chapter-by-chapter Summary Chunked chapter text Chapter Summary.md (including plot points + characters +key information and expansion techniques+chapter-by-chapter writing formula). The chapter-by-chapter writing formula must extract emotional flow, pacing ratio, structural formula, core techniques, chapter-ending hooks, and foreshadowing. Character filtering (extras are not extracted, aliases are categorized). 10-40 plot points per chapter (density 150-200 words each, dynamically adjusted by word count; when the formula yields fewer than 10, still split enough key steps according to the hard lower limit of 10).Parallel mode: spawn a chapter-extractor agent for each chapter。Count verification: number of summaries == number of chapters; if not equal, mark the failed chapters。 All chapters processed
3 Aggregate Analysis All chapter summaries Plot/*.md + README.md (including authoritative division-of-labor table andplot unit listindex) + Storyline.md + Pacing.md + Emotion Modules.md。Story framework identification(prerequisite, determines aggregation strategy).Two-step plot aggregation(first identify the plot outline from the summaries, then allocate plot points according to the outline).Key information progression index(track how information is expanded by chapter/plot unit).Emotional touchpoints and burst pacing(setup → release → aftermath of satisfying points/angst points/anticipation points).Overall emotional pacing overview of the whole book(emotional line graph, frequency of satisfying points, positions of small/medium/large climaxes, conflict escalation path, cross-chapter foreshadowing map, small/medium/large cycle units).Reader needs / emotional engine / power-fantasy trope framework(distilled into reproducible module cards).Character merging(cross-chapter deduplication + alias normalization).Character tiering(protagonist/antagonist/core supporting character/functional character).Scattered plot fallback(6 steps, including coverage verification).Trope tags(Each plot module is tagged according to the trope vocabulary in deconstruction-notes.md, best-effort; leave blank if no match).Quality check(For thresholds, see the quality threshold system in material-decomposition.md). Quality check passed
4 Setting + Relationships (4a/4b/4c) 4a: Stage 2 plot points + chapter summaries (does not depend on Stage 3, runs in parallel with 3);4b/4c: Stage 3 merged character data + plot points Setting/.md + Characters/.md。4a Setting(Worldview/special abilities/factions, summarized from Stage 2 mention data).4b Complete character profiles(Two-stage model: Stage 2 lightweight mentions → Stage 4b complete profiles; alias resolution confidence ≥0.85 auto-merge).4c Character relationship extraction(Extracted from plot points, not from the source text; includes evolution tracking + final state merging + implicit inference). Non-humanoid villains undergo complete abstract adversarial analysis in 4a. 4a/4b/4c all completed
5 Summary report All outputs Deconstruction Report.md (including summaries of "Reader Needs / Emotional Engine," "Key Information and Expansion Techniques Overview," "Whole-Book Emotional Rhythm Overview," "Rhythm and Emotional Touchpoints," "Cycle Units," "Cross-Chapter Foreshadowing Map," "Conflict Escalation Path," and "Reproducible Modules," and pointing to 剧情/节奏.md / 剧情/情绪模块.md; including a "Writing Techniques" list covering dual-purpose phrasing/delayed revelation/perspective deception/contrast anchors/behavioral cycles/physical reactions replacing psychological description/cross-chapter callbacks—objects/imagery serving different functions in different chapters) + Summary.md full-book 500-1000 word version(plot-aware, covering Stage 0's 200-word thin first-pass) Report + full-book summary generation completed
6 Style Deconstruction Report.md + Chapters/Chapters 1-3_In-Depth Deconstruction.md + Chapters/*_Summary.md + Source Text/Source Text.txt Style.md (whole-book-level writing technique view: sentence length/punctuation/dialogue subtext/emotional alternation cycles + 4-6 source-text anchor example passages + layered imitation suggestions, hard limit ~4000 words. See style-profile-protocol.md + style-profile-generator.md) Style saved to disk 拆文库/{书名}/文风.md

Stage 0 chapter boundary substep

After Stage 0 completes the summary + chapter index and before moving to Stage 1,mustadditionally produce a "chapter boundaries" table written to _progress.md. This is shared by subsequent Stage 1 (golden three chapters source-text slicing) / Stage 2 (each chapter passed to the chapter-extractor agent) / Stage 6 (style sampling) as thesole slicing source—avoiding each stage running its own regex slicing, which could produce inconsistent results.

Operation:

  • Use style-profile-generator.md Step 4's chapter regex in style-profile-generator.md (including 千/两, covering 1000+ chapters) to grep all chapter line numbers
  • First remove the table-of-contents block: many source texts begin with a table of contents, and entries in the table of contents 第N章 Likewise the top line will overlap with the main text chapter lines; if not handled, it will cut out two "Chapter One". The criterion is line spacing—adjacent hits within a table of contents block are only one or two lines apart, while main text chapters are separated by an entire chapter's length. Calculate the line number difference between adjacent hits, and discard the entire contiguous block of hits at the beginning of the file where "line spacing is consistently far below the overall median"
  • If duplicate chapter numbers still remain after filtering, do not arbitrarily pick one: it is a legitimate structure for each volume of a multi-volume book to restart from "Chapter One". In this case, keep the volume number in the title column for disambiguation (e.g. 卷二 第一章), and renumber the chapter number column as a continuous sequence across the whole book
  • Write into the four columns | 章号 | 标题 | 起始行 | 字数 | Four-column write-in _progress.md 's "Chapter Boundaries" section (see pipeline-ops.md template)
  • Before writing to the table, validate that chapter numbers are continuous, have no duplicates, and have no gaps; if not satisfied, stop and report, do not proceed to Stage 1 with a wrong table—Stage 1/2/6 all use this table as the sole slicing ground truth, and one mistake will propagate all the way to the end
  • _progress.md top schema_version: 2 also write to disk

Resume preconditions: resume only accepts schema_version: 2 and containing the "Chapter Boundaries" table _progress.md. If missing or structurally incomplete, stop the resume and prompt to rebuild the progress file from the Stage 0 chapter boundaries substep, to avoid different stages using different slicing ground truth.

Stage 1 checkpoint

After Stage 0+1 completes, the pipelineautomatically stops, produces a quick preview report and asks the user whether to continue with full decomposition:

  1. Generate checkpoint deliverable: write 拆文库/{书名}/快速预览.md(see template in output-templates.md 's "Quick Preview Report"). At this point 概要.md、章节/第1章_深度拆解.md、章节/第2章_深度拆解.md、章节/第3章_深度拆解.md、原文/ have all been written to disk.
  2. Write checkpoint status:_progress.md 's "Final Status" field write paused_after_stage1, and the "Breakpoint" section records "Next action: Stage 2 chapter-by-chapter summary".
  3. Ask the user(use an interaction method available on the current platform to present a clear binary choice; Claude can use AskUserQuestion, TRAE Code asks directly in the main session):

    "The golden three chapters have been decomposed, see the quick preview report at 快速预览.md. Continue with full decomposition (Stage 2-6: chapter-by-chapter summary / aggregate analysis (including 剧情/节奏.md、剧情/情绪模块.md) / setting relationships / summary report / writing style)? Estimated time {rough estimate based on chapter count}."

    • Choose "Continue with full decomposition" → read _progress.md, resume from Stage 2 ,do not rerun Stage 0/1。
    • Choose "Stop here" → pipeline ends,_progress.md status remains paused_after_stage1, tell the user "you can at any time later /story-long-analyze the same book, and it will automatically resume from Stage 2".
  4. Cases where the prompt is skipped: when the user explicitly says at the start "full decomposition / run it all at once / systematic decomposition / don't ask", still generate 快速预览.md(retain the early judgment snapshot), butdo not stop to ask, and directly resume from Stage 2 to Stage 6.

After Stage 5: topic decision backfill (optional)

拆文报告.md Execute after it comes out (after Stage 5 finishes)—unrelated to Stage 6, and a Stage 6 failure does not affect this step.

First locate 选题决策.md: if it exists at the project root, use that one. If not at the project root → search by filename starting from the project root and its parent directory, going down up to 3 levels (skipping hidden directories), and take the latest 3 by mtime from newest to oldest. Backfilling means writing to a file; for files outside the project root, confirmation is required before writing: if 1 is found → report the path and ask "Backfill this book's decomposition support into this one?"; if multiple are found → list the candidates using the current platform's interaction capabilities (Claude can use AskUserQuestion; TRAE Code directly lists the paths + 扫榜日期 + "Backfill none" and waits for a reply). If the user does not choose → record "not backfilled" and skip, without touching any files.

Only whenlocated 选题决策.md(use the one at the project root directly; the one outside the project root must go through the confirmation above): based on this book's subject matter, look in its recommended topics forthe subject-matter keyword matchesthat one——

  • if exactly one matches → change that topic's "reason it can go viral" from 待拆文验证 to sourced support: "Book decomposition support: {拆文报告.md 's reader needs/emotional engine + 剧情/情绪模块.md 's reproducible module Top + 剧情/节奏.md 's pleasure point/touchpoint rhythm summary} (拆文库/{书名}/拆文报告.md、剧情/情绪模块.md、剧情/节奏.md). Note that this is still only a hypothesis (only one book has been decomposed, so it is not yet confirmed).
  • if multiple match / uncertain → ask the user "Which direction in the topic decision does 《{book title}》 correspond to?"
  • if none match → record "no matching topic, not backfilled", and do not modify the file.
  • 选题决策.md is missing the "reason it can go viral" field required by the current contract → report invalid_topic_decision_contract, and prompt to rerun story-long-scan Phase 5 to generate the current file; do not guess, do not silently backfill, and the main decomposition workflow can still be completed.
  • Repeated decomposition does not overwrite: only backfill those still marked 待拆文验证 ; those already filled in are left untouched.

Cannot find in the workspace 选题决策.md → skip directly, without affecting decomposition.

Stage 6 writing style

文风.md is only responsible for expression-layer style; emotional/rhythmic intent still takes 剧情/情绪模块.md and 剧情/节奏.md as authoritative. If the original text is missing or chapter separators cannot be recognized → in 文风.md 's "generation record", write 文风可用:否:{原因}. Stage 6 failure does not block the pipeline.

Stage 3-4 parallel execution

parallel execution graph:

Stage 3(剧情聚合 + 角色合并)       ──┐
                                       ├── 4a 与 Stage 3 可并行
Stage 4a(设定:世界观/金手指/势力)  ──┘
              │
              ▼(Stage 3 + 4a 都完成后)
Stage 4b(角色完整档案)— 串行,依赖 Stage 3 合并后的角色实体
              │
              ▼
Stage 4c(角色关系提取)— 串行,依赖 4b 角色实体存在

4a's data source is the Stage 2 summary, so it can run in parallel with 3; 4b/4c depend on Stage 3 character merging, so they are serial.

Partial failure tolerance

A single chapter/single stage failure does not block the pipeline. Record failures in _progress.md 's "failure record" table (| 类型 | 章节/阶段 | 错误信息 | 重试状态 |). The final status may be completed_with_errors(note the failure details in the decomposition report).

Correspondence with material-decomposition.md: Stage 0 includes Material phase 1 (chapter parsing); Stage 1 and 5 are newly added; Stage 2 = Material phase 2; Stage 3 = Material phase 3; Stage 4 merges Material phases 4+5.

For detailed templates see output-templates.md, for methodology see material-decomposition.md。


Quality check summary

Before Stage 3-4 is completed, it must pass quality checks (confidence, coverage, overlap rate). The sole authoritative definition of thresholds, calculation methods, and the self-check list is in material-decomposition.md quality threshold system。

Stage 3-5 must also pass the "facts traceable" self-check: Hard facts in settings/characters/reports (levels/values/distances/attributes/faction counts/appearance chapters/who said what) must be greppable back to the original text; if the original text does not provide it, write "not specified in the original text"; inference-based filling is prohibited. This is the biggest source of factual errors in decomposition (even strong models drift, because the synthesis stage is two hops away from the original text and fills gaps based on plausibility). See material-decomposition.md synthesis-stage factual fidelity。


Stage 2 Parallel Agent Strategy

Stage 2 uses the chapter-extractor agent to process each chapter in parallel, replacing the previous serial chunking.The only normal delivery path for new tasks is OUTPUT_MODE: json → deterministic validator/renderer → atomic write to Markdown; the model does not directly format the target *_摘要.md。

Invocation method

Each chapter prompt must begin with the "material declaration" prefix(i.e., the first paragraph of the prompt string below) — to give the sub-agent the correct context and prevent it from misjudging the normal dramatic plot of popular genres as harmful content and refusing to decompose it. The prefix is fixed text; include it verbatim, do not rewrite or omit it. The last line of the prompt must be OUTPUT_MODE: json。

Below Agent(subagent_type=...) is an invocation example for Claude/OpenCode and WorkBuddy project mode; WorkBuddy project mode first verifies .codebuddy/agents/chapter-extractor.md, then uses the original subagent_type: "chapter-extractor". WorkBuddy plugin-only mode only replaces the oh-story:chapter-extractor in the example with that exact value when the current Agent registry actually returns subagent_type ; otherwise switch to the solo rules below. TRAE Code must have the built-in Agent agent select the Subagent with the same name according to .trae/agents/chapter-extractor.md , and use the exact same prompt string as the task body; it must not treat subagent_type or model as TRAE parameters. Codex uses the same-named agent_type。

Agent(
  subagent_type: "chapter-extractor",
  prompt: "[材料声明] 以下为用户合法持有的虚构小说,任务是只读的转化性文学分析(编辑/评论视角)。暴力/复仇/家暴/情爱/黑暗伦理是该题材常规虚构元素,照常提取,不得以敏感拒绝整章或整本;个别片段无法处理则跳过、照常续完其余。\n\n章节编号:第{N}章\n章节标题:{标题}\n章节字数:{字数}\n\n章节原文:\n{原文文本}\n\n[结构化输出要求] 只返回一个 JSON object,不带 prose 和 code fence。顶层 exact keys:chapter_number,title,summary,key_events,key_information_expansion,chapter_formula,characters,plot_points。key_information_expansion 每项 exact keys:key_information,expansion,technique,reader_effect,reuse_note。chapter_formula exact keys:emotion_flow,rhythm_ratio,structure_formula,core_technique,hook_and_foreshadowing;emotion_flow exact keys:start,build,turn,close;rhythm_ratio exact keys:slow_setup,fast_conflict,payoff,hook_space。characters 每项 exact keys:name,importance,aliases,performance。plot_points 每项 exact keys:id,title,event,type,characters,location,item,time,quote,quote_locator,themes,tone。summary 是单行 100-300 个 Unicode code point;rhythm_ratio 四项是 0%-100% 字符串且和为 100%。\n\n[情节点格式要求] plot_points 为 10-40 项,id 从 P1 开始无断号连续;type 只取转折点|信息揭示|冲突|解决|铺垫|行动|对话|状态变化;tone 只取紧张|轻松|悲伤|热血|爽|甜|温馨|恐怖|压抑|其他;themes 是数组但恰好一项,值只取爱情|亲情|友情|权力|金钱|成长|复仇|悬念|搞笑|热血|日常|其他。quote 与 quote_locator 互斥,全章两者非 null 的情节点合计不超过 8 个;quote 非空且为 1-400 Unicode code point,quote_locator 为 5-15 个。空地点/物品/时间用 null,纯环境情节的 characters 用空数组。\n\n[输出前自检] 交付前核对 exact keys 无缺失/无多余,枚举无越界,summary 长度合格,plot id 连续,每个 themes 恰好一项,引用情节点合计 <= 8。任何一条不符,先修正 JSON 再输出。\n\nOUTPUT_MODE: json"
)

The above [结构化输出要求] / [情节点格式要求] / [输出前自检] is assembled into the prompt by the main thread at spawn time,does not depend on the version of the agent file already deployed in the project. The complete JSON schema uses output-templates.md"Stage 2 Structured Middleware" as the human-readable contract, and scripts/render_chapter_summary.py 's validator as the machine authority. The sonnet upgrade retry uses the same prompt, and the last line is still OUTPUT_MODE: json。

Batch strategy

  • Spawn 5-8 agents each time (to avoid concurrency limits)
  • Wait for the current batch to fully complete before spawning the next batch
  • After each batch completes, update _progress.md to record the processed chapters

Agent output collection

  • Each agent returnsa single pure JSON object(no prose, no code fence); the return value is first stored in a temporary .json, and must not be written directly to the target Markdown

  • The main thread calls the deterministic renderer:

    for PYBIN in python3 python py; do "$PYBIN" -c "" 2>/dev/null && break; done
    "$PYBIN" skills/story-long-analyze/scripts/render_chapter_summary.py \
      --input "$RAW_CHAPTER_JSON" \
      --output "拆文库/{书名}/章节/第{N}章_摘要.md" \
      --expect-chapter-number "{N}" \
      --expect-title "{标题}"
    
  • the renderer first fully validates the JSON, then writes a temporary file in the same directory as the target and uses os.replace for atomic replacement; on parse/validation failure, it does not create, truncate, or overwrite the existing 章节/第{N}章_摘要.md

  • Collect the appearance character tables from all agents for use in Stage 3 merging

Failure handling + quality upgrade retry

Three types of failure:

  1. Execution failure(agent crash / timeout / empty output) → retry once with the same model (haiku)
  2. JSON contract failure(not a single JSON object, exact schema/type/enum mismatch, summary out of bounds, non-consecutive P IDs, multiple topics, citation over limit, chapter number/title not matching the task) → Use renderer stderr as the reason for the previous failure, upgrade to sonnet and retry once
  3. Semantic quality failure(Although it passes the schema, the non-mechanical items among the 12 items in chapter-extractor.md "Quality Check" do not meet the standard—for example, white-description speculating motives, the summary repeatedly using the same conjunction, characters using generic forms of address) → Upgrade to sonnet and retry once

The renderer's mechanically verifiable checks are the sole format authority for new tasks:

  • The top level and every nested object must have exact keys; reject missing fields, extra fields, duplicate JSON keys,NaN / Infinity
  • type, tone, theme, expansion technique, reader emotion, and character importance must all strictly use the enum;themes must be exactly 1 item
  • plot_points count 10-40, IDs must strictly be P1..PN consecutive sequence; title ≤15 Unicode code points, and must not be the same as the white-description event identical
  • summary counted by Python len(str) in Unicode code points (not UTF-8 bytes), single line 100-300; the four rhythm items are percentage strings and must total 100%
  • For each plot point, the quote / quote_locator are mutually exclusive; for the whole chapter, the total number of plot points where both are non-null is ≤8, quote is non-empty and a single item is 1-400 Unicode code points, locator is 5-15

Old Markdown already written to disk is not retroactively changed. must not use the new JSON contract to retroactively judge or rewrite existing 章节/*_摘要.md; in old summaries, 类型{行动}、物品— and similar forms of writing remain usable as before, and Stage 3-6 reading behavior is unchanged. The following four legacy Markdown greps are used only in the explicit fallback after "JSON upgrade retry still fails," and do not scan historical files:^P count and 基调: count are equal; P lines contain non-whitespace description and 涉及 section; tone values do not go out of bounds; theme tag values do not go out of bounds.

How to invoke the upgrade retry(executed by the main thread after validation fails):

Claude/OpenCode can explicitly upgrade the model as in the example below. TRAE Code's project subagent does not accept Claude's sonnet model name or the call-time model override; in TRAE, still choose the same-named chapter-extractor, write "upgrade retry, fix renderer stderr item by item" into the task body, and have the current TRAE model execute it. WorkBuddy's current Agent call likewise does not treat Claude's model: "sonnet" as a portable parameter: project mode still uses chapter-extractor, and plugin-only mode still uses the oh-story:chapter-extractoractually returned by the registry, writes the failure reason and repair requirements into the prompt, and has the current WorkBuddy model execute it. If the current TRAE/WorkBuddy registry does not have that agent, handle it according to the solo rules below, and do not fake a successful upgrade.

Agent(
  subagent_type: "chapter-extractor",
  model: "sonnet",            # 显式覆盖 frontmatter 的 haiku
  prompt: "章节编号:第{N}章\n...(同首次 prompt,含开头的「材料声明」前缀,追加:'上次校验失败原因:{renderer stderr / 自检失败项}',末行仍为 OUTPUT_MODE: json)"
)

Final write-to-disk rules:

  • haiku's first JSON passes the validator and semantic self-check → atomically written by the renderer to 章节/第{N}章_摘要.md,_progress.md mark success
  • haiku fails + same-model retry passes → same as above, note retry_same_model
  • quality failure + sonnet retry passes → same as above, note retry_sonnet
  • Only the JSON contract fails and the sonnet JSON upgrade retry still fails → allow one explicit legacy Markdown fallback; the model output is first written to a temporary file, and after passing the above four greps it is atomically replaced,_progress.md note legacy_markdown_fallback + the reasons for the two JSON failures. Do not directly require Markdown after the first failure
  • sonnet semantic quality retry still fails, or legacy fallback still does not pass → chapter marked ⚠️ 跳过, and the failure reason is written to _progress.md "Failure Record" table, noted in the decomposition report
  • A single chapter failure does not block the pipeline; whether to enter Stage 3 is decided only after all batches have finished spawning

Agent unavailable degradation

In any of the following situations, Stage 2 automatically falls back to serial mode, with the main thread processing chapter by chapter (quality is unaffected; it just switches to serial and is slightly slower).Both paths use the same JSON contract and the same renderer: the main thread follows output-templates.md"Stage 2 Structured Middleware" first produces JSON, calls scripts/render_chapter_summary.py, and does not directly lay out Markdown. When the validator or semantic self-check fails, the main thread rewrites the JSON once according to the specific failure item; only if the second attempt still fails the JSON contract may it go through one explicit legacy_markdown_fallback, and if it still does not pass, it is recorded according to ⚠️ 跳过 into the _progress.md "Failure Record" table.

  • agent not deployed/not registered: the corresponding directory under the current runtime (Claude .claude/agents/、OpenCode .opencode/agents/、TRAE Code .trae/agents/, WorkBuddy project mode .codebuddy/agents/、Codex .codex/agents/) does not contain chapter-extractor.md or chapter-extractor.toml , or the current registry in WorkBuddy plugin-only mode does not return oh-story:chapter-extractor. You should rerun /story-setup(for WorkBuddy plugin mode, /oh-story:story-setup) to complete deployment of the current adapter, without reading the template source across Skills.
  • The environment does not support spawning subagents: this skill is currently running in a subagent context and cannot start another layer of agent.

Stage 2 wrap-up: merge chapter summaries (_章节摘要汇总.md)

After all Stage 2 章节/*_摘要.md are written to disk and before entering Stage 3, the main thread concatenates them in chapter-number orderlosslesslyinto 拆文库/{书名}/_章节摘要汇总.md(concatenate only, do not compress, do not rewrite):

ls 章节/*_摘要.md | sed -E 's/.*第([0-9]+)章.*/\1 &/' | sort -n | cut -d' ' -f2- | while read -r f; do cat "$f"; echo; done > _章节摘要汇总.md

Lossless check(verify after concatenation; if any check fails, delete _章节摘要汇总.md, fall back to per-file scanning, behavior unchanged):

  • grep -cE '^P[0-9]+ ' _章节摘要汇总.md == the sum of the line counts of each summary ^P Sum of lines
  • grep -cE '^\*\*概要\*\*' _章节摘要汇总.md == the number of summary files (**概要** one line per chapter; both the chapter-extractor parallel output and the serial summary template have it; do not use the ## 第N章 header — the serial summary template has no chapter header, which would cause a misjudgment)

Stage 3 / 4a / 4c / scattered-plot fallback changed toread only once _章节摘要汇总.md and reuse it in context, replacing the per-stage glob 章节/*_摘要.md rescan (4-5 cold reads of the same corpus reduced to 1).

Generate the summary file only when the corpus can fit into context: >500 chapters, or after merging _章节摘要汇总.md is too large to fit into contextskip this step, and instead follow material-decomposition.md"Process batches → A. Subagent parallel mode": spawn subagents at 10-20 chapters per batch; the subagents read that batch's summaries in their own context and return only a dimensionality-reduced aggregation of ≤8K tokens; the main thread only merges the aggregation results (if necessary, merge pairwise hierarchically).The main thread does not read the original summaries chapter by chapter— skipping the summary file does not mean going back to per-file scanning, which also will not fit for a large book._章节摘要汇总.md does not replace 章节/*_摘要.md— the single-chapter files are still the on-disk source of truth, and Stage 6 style sampling and manual review still use the single-chapter files. After the pipeline ends (after Stage 6), delete _章节摘要汇总.md— it is a derived temporary file and is not delivered with 拆文库/ (拆文库/ will be preserved by story-import as a writing project).

See Stage 3-5 chunks at material-decomposition.md(sole authority).


Recovery mechanism

At startup, check _progress.md;paused_after_stage1 → resume directly from Stage 2. See pipeline-ops.md。


Process handoff

Pipeline: long-form Location: decomposition (long-form pipeline step 2, after story-long-scan and before story-long-write)

Timing Jump to Command
Ready to start writing story-long-write /story-long-write
Need market data story-long-scan /story-long-scan
Better suited for short-form story-short-scan → story-short-analyze /story-short-scan

Reference materials

File When to load
references/output-templates.md Full pipeline: output templates for each Stage + quick preview report template + 剧情/节奏.md / 剧情/情绪模块.md template + general quick-reference sheet
references/material-decomposition.md Stage 2-5: material decomposition methodology + quality thresholds + chunking strategy; for Stage 6 see also style materials
references/pipeline-ops.md Pipeline operations: _progress.md template, error handling, recovery mechanism operation steps
references/deconstruction-notes.md Book decomposition methods + film/TV decomposition + abstract decomposition method + genre practice
references/style-profile-protocol.md Stage 6: style template + credibility/usability notes
references/style-profile-generator.md Stage 6: style generation SOP (6 steps, including Chinese numeral chapter recognition + full-width colon tone grep)

Language

  • Reply in the user's language; use whatever language the user uses
  • Chinese replies follow the Chinese Copywriting Style Guide