# novelops-skill

Adopt this skill: https://proskills.md/skills/other/qiyan233-novelops-skill

Page: https://proskills.md/skills/other/qiyan233-novelops-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 16763
sha: ceabed3ca60b34c8d0f5c58ec4fb1a0a0f191250
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/SKILL.md

````text
---
name: novelops-skill
description: Novel-production operating system skill for long-form fiction, web novels, serials, fanfiction, and side stories. Use when designing or running a structured writing pipeline with persistent world state, chapter summaries, hooks, character matrices, continuity audits, rewrite/revise loops, style guides, or per-book rules. Best for requests like building an InkOS-inspired novel workflow skill, creating a long-novel workflow, keeping multi-chapter story consistency, generating/auditing/revising chapters, or maintaining story files across many chapters.
---

# NovelOps Skill

Version: 1.1.0

Build and run long-form fiction as a stateful pipeline, not a one-shot prompt.

Treat this skill as a **novel OS skeleton**: it provides project structure, workflow, audit criteria, and helper scripts for a stateful long-form writing system that is conceptually close to InkOS.

**Agent-oriented, not host-specific.** The bundled tooling is a plain Python 3 CLI (stdlib only) over plain-text Markdown/JSON state files, so it does not depend on any particular agent runtime — OpenClaw, Claude Code, IDE-embedded agents, terminal agents, or a human at a terminal can all drive it. See `docs/agent-integration.md` for per-host setup.

## Core operating model / 核心运行模型

Use this loop:

1. **Load truth files**
2. **Plan the next chapter**
3. **Draft with constraints** — 可由人或 agent 执笔；也可用 `draft` 命令交给 Hermes 等 OpenAI 兼容模型自动起草（见下文 Bundled tools）
4. **Run knowledge-boundary checks when the chapter depends on hidden truths or limited POV**
5. **Audit for continuity / style / pacing / leaks**
6. **Revise with spot fixes first** — 局部性问题可用 `auto-revise` 命令做 LLM 段落级最小化重写（默认只出 diff，`--apply` 才写回）
7. **Extract candidate state updates from the accepted draft**
8. **Update story state**
9. **Queue unresolved issues for human review**

Prefer stable files over fragile memory. If information matters in later chapters, write it into a truth file.

## Project layout / 项目结构

When starting a new project, copy the template from `assets/project-template/`.

Expected files:

- `story_bible.md` — world rules, premise, factions, locations, power system
- `book_rules.md` — per-book rules, prohibitions, protagonist locks, tone limits
- `outline.md` — macro arc, chapter targets, payoff plan
- `current_state.md` — authoritative latest world state
- `chapter_summaries.md` — per-chapter summaries and state deltas
- `pending_hooks.md` — open promises, foreshadowing, unresolved conflicts
- `character_matrix.md` — who met whom, trust/conflict, information boundaries
- `character_knowledge.md` — optional structured knowledge boundary tracker for major characters
- `emotional_arcs.md` — tracked emotional movement by key character
- `subplot_board.md` — A/B/C line progress and stagnation notes
- `continuity_issues.md` — known inconsistencies or manual review backlog
- `style_guide.md` — qualitative style guide
- `style_profile.json` — optional quantitative style stats
- `novelops.config.json` — optional project config: LLM endpoint/model, audit rule overrides, knowledge-check overrides
- `chapters/` — chapter markdown files
- `reviews/` — audit and revision reports

`current_state.md` is the most important operational file. Keep it compact, current, and explicit.

## Recommended CLI workflow / 推荐 CLI 工作流

默认优先使用统一入口：

```bash
python scripts/novelops_cli.py <command> ...
```

这样更适合日常使用、文档引用和后续自动化；底层脚本仍可直接调用，但建议视为 advanced / lower-level usage。

### Quick start / 快速开始

#### 1) Initialize a project / 初始化项目

推荐：

```bash
python scripts/novelops_cli.py init /path/to/project "Book Title"
```

默认不会初始化到非空目录，避免覆盖已有小说项目；如果你确认要覆盖模板文件，可显式追加 `--force`。

Lower-level usage / 底层脚本方式：

```bash
bash scripts/init_novel_project.sh /path/to/project "Book Title"
```

This copies the template and creates the standard directory layout.
For cross-platform usage, prefer `python scripts/novelops_cli.py init ...`.

#### 2) Build next-chapter context / 构建下一章上下文

推荐：

```bash
python scripts/novelops_cli.py context \
  --project /path/to/project \
  --recent-chapters 3 \
  --json
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/build_next_chapter_context.py \
  --project /path/to/project \
  --recent-chapters 3 \
  --json
```

#### 3) Build write-next packet / 构建下一章工作包

推荐：

```bash
python scripts/novelops_cli.py write-next \
  --project /path/to/project \
  --json
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/build_write_next_packet.py \
  --project /path/to/project \
  --json
```

Use this when you want a more structured handoff than raw context: chapter goal, active hooks, constraints, state targets, suggested scene beats, and a single-chapter output contract.

## Workflow / 工作流

### 1) Before writing a chapter / 写章前准备

Read at least:

- `story_bible.md`
- `book_rules.md`
- `outline.md`
- `current_state.md`
- latest section of `chapter_summaries.md`
- `pending_hooks.md`
- `character_matrix.md`

If maintained, also read:

- `character_knowledge.md`

If the request is for a side story, prequel, sequel, or alternate timeline, also establish:

- parent canon constraints
- divergence point
- what characters do **not** know yet
- which original hooks must remain untouched

### 2) Planning rules / 规划规则

Before drafting, explicitly decide:

- chapter purpose
- POV
- conflict driver
- payoff or partial payoff
- hooks to advance, delay, or close
- state changes that must occur
- constraints that must not be violated

Write a short chapter plan into the response or a scratch file if useful.

### 3) Drafting rules / 起草规则

Draft from observed reality, not abstract explanation.

Prefer:

- concrete action
- sensory evidence
- state changes that can be tracked later
- character knowledge limited to what they have seen, inferred, or been told
- exactly one target chapter per draft

Avoid:

- breaking protagonist personality lock
- introducing untracked items/powers/injuries
- resolving major hooks accidentally
- report-speak in narrative prose
- broad whole-crowd reactions unless earned
- full-chapter rewrites when only a few lines are broken
- drafting chapter N and chapter N+1 in the same response
- multiple chapter headings in one draft
- continuing into later chapters after the current chapter has already landed its ending beat

### 4) Knowledge-boundary pass / 信息边界检查

When the chapter depends on mystery, hidden truths, or strict POV, run:

推荐：

```bash
python scripts/novelops_cli.py knowledge-check \
  --project /path/to/project \
  --chapter-file /path/to/project/chapters/ch12.md \
  --json
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/knowledge_check.py \
  --project /path/to/project \
  --chapter-file /path/to/project/chapters/ch12.md \
  --json
```

Use this to catch:

- characters knowing facts too early
- narration slipping into omniscient scope
- side-story / prequel spoiler contamination
- certainty that should still be suspicion

### 5) Audit pass / 审计检查

After drafting, audit against `references/audit-dimensions.md`.

Minimum audit set:

- continuity / timeline
- character consistency
- information boundary leaks
- world-rule violations
- unresolved logic gaps
- pacing / subplot movement
- repetitive diction / fatigue terms
- outline drift

Recommended command:

```bash
python scripts/novelops_cli.py audit \
  --project /path/to/project \
  --chapter-file /path/to/project/chapters/ch12.md \
  --json
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/audit_chapter.py \
  --project /path/to/project \
  --chapter-file /path/to/project/chapters/ch12.md \
  --json
```

Write reports into `reviews/` when operating on files.

### 6) Revision policy / 修订策略

Prefer this order:

1. **spot-fix** — patch only bad sentences/paragraphs
2. **polish** — improve local expression without changing story events
3. **rewrite scene** — only if scene logic is broken
4. **rewrite chapter** — last resort

Do not silently change:

- names
- outcomes of key events
- resource counts / power levels
- relationship states
- what characters know

If any of the above changes, also update truth files.

### 7) State extraction and update / 状态提取与更新

After a chapter is accepted, first extract candidate updates:

推荐：

```bash
python scripts/novelops_cli.py extract-state \
  --project /path/to/project \
  --chapter-file /path/to/project/chapters/ch12.md \
  --json
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/extract_state.py \
  --project /path/to/project \
  --chapter-file /path/to/project/chapters/ch12.md \
  --json
```

This produces candidate:

- summary
- state changes
- hook open / advance / close items
- relationship changes
- emotional changes

Then feed approved items into:

推荐：

```bash
python scripts/novelops_cli.py state-update \
  --project /path/to/project \
  --chapter 12 \
  --title "The Price of Silence" \
  --summary "..." \
  --state-change "Lin Jin now knows the token is fake" \
  --hook-open "Who replaced the token?" \
  --relationship "Lin Jin -> Xu An: trust decreased" \
  --emotion "Lin Jin: suspicion hardens into anger"
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/update_story_state.py \
  --project /path/to/project \
  --chapter 12 \
  --title "The Price of Silence" \
  --summary "..." \
  --state-change "Lin Jin now knows the token is fake" \
  --hook-open "Who replaced the token?" \
  --relationship "Lin Jin -> Xu An: trust decreased" \
  --emotion "Lin Jin: suspicion hardens into anger"
```

This updates `chapter_summaries.md` and also syncs `current_state.md` with the latest accepted chapter position plus a compact accepted-update block.

### 8) Hook pressure review / 钩子压力复核

When many hooks are active, run:

推荐：

```bash
python scripts/novelops_cli.py hook-report \
  --project /path/to/project \
  --stale-after 5 \
  --json
```

Lower-level usage / 底层脚本方式：

```bash
python scripts/hook_report.py \
  --project /path/to/project \
  --stale-after 5 \
  --json
```

Use this to spot:

- stale hooks that have been open too long
- current hook counts by status
- backlog pressure before the next chapter

## Modes to support / 支持模式

### Full pipeline mode / 全流程模式

Use when the user says things like:

- write the next chapter
- continue the novel
- run the full story pipeline
- draft and audit this chapter

Sequence:

1. run `write-next`
2. plan from chapter function and scene beats
3. draft
4. run `revise` or, if needed, knowledge-check + audit separately
5. extract candidate state
6. update state

In this mode, the draft should be **exactly one chapter**, not a chapter bundle.

### Audit-only mode / 仅审计模式

Use when the user already has chapter text and wants:

- continuity check
- OOC check
- pacing review
- world-rule validation
- AI-ish writing detection

Read `references/audit-dimensions.md`, produce findings grouped by severity, then propose minimal edits.

### State-maintenance mode / 状态维护模式

Use when the user says:

- remember this chapter
- update the story bible
- update hooks / character relations / arcs
- summarize what changed

Focus on truth-file accuracy, not prose generation.

### Side-story / fanfic / sequel mode / 外传同人续作模式

Use when the project depends on another canon. Read `references/canon-side-story.md` and establish:

- parent canon facts
- allowed divergence
- forbidden spoilers
- hook isolation

## File discipline / 文件纪律

When working over many chapters:

- prefer additive updates over destructive rewrites
- never delete hook history without a reason
- mark hooks as `OPEN`, `PAID OFF`, `BROKEN`, `DEFERRED`, or `ADVANCED`
- mark uncertain facts as `UNCONFIRMED`
- separate **world facts** from **character beliefs**

Good pattern:

```md
## Facts
- The seal broke in chapter 17.

## Character beliefs
- Lin Jin believes Xu An caused it.
- Xu An does not know the true source.
```

## Bundled tools / 内置工具入口

推荐优先记住这一个入口：`scripts/novelops_cli.py`。

Common commands:

- `python scripts/novelops_cli.py init ...` — scaffold a new novel project
- `python scripts/novelops_cli.py context ...` — assemble next-chapter context
- `python scripts/novelops_cli.py write-next ...` — build a structured write-next packet
- `python scripts/novelops_cli.py draft ...` — draft the next chapter with an OpenAI-compatible LLM (Hermes-first; supports `--dry-run` / `--mock-response`)
- `python scripts/novelops_cli.py auto-revise ...` — LLM paragraph-level minimal revision (diff by default, `--apply` writes back after snapshot + backup)
- `python scripts/novelops_cli.py audit ...` — run a chapter audit
- `python scripts/novelops_cli.py knowledge-check ...` — detect knowledge-boundary / POV leaks
- `python scripts/novelops_cli.py extract-state ...` — extract candidate state updates
- `python scripts/novelops_cli.py hook-report ...` — summarize hook lifecycle state
- `python scripts/novelops_cli.py state-update ...` — append structured story-state deltas and sync the latest accepted update into `current_state.md`
- `python scripts/novelops_cli.py revision-plan ...` — build revision plan from chapter or audit
- `python scripts/novelops_cli.py spot-fixes ...` — suggest low-risk local fixes
- `python scripts/novelops_cli.py revise ...` — run the revision workflow as one cycle
- `python scripts/novelops_cli.py snapshot ...` — create a state snapshot
- `python scripts/novelops_cli.py diff ...` — diff snapshots or current state
- `python scripts/novelops_cli.py smoke-test` — run smoke tests
- `python scripts/novelops_cli.py package` — create a clean `.skill` package

Advanced / lower-level usage:

- `scripts/init_novel_project.sh`
- `scripts/build_next_chapter_context.py`
- `scripts/build_write_next_packet.py`
- `scripts/draft_chapter.py`
- `scripts/auto_revise.py`
- `scripts/llm_client.py`（LLM 传输层）
- `scripts/novelops_config.py`（项目配置加载）
- `scripts/audit_chapter.py`
- `scripts/knowledge_check.py`
- `scripts/extract_state.py`
- `scripts/hook_report.py`
- `scripts/update_story_state.py`
- `scripts/build_revision_plan.py`
- `scripts/suggest_spot_fixes.py`
- `scripts/run_revision_cycle.py`
- `scripts/snapshot_story_state.py`
- `scripts/diff_story_state.py`
- `scripts/smoke_test.py`
- `scripts/package_skill.py`
- `scripts/smoke_test.sh` (legacy shell entry)
- `scripts/package_skill.sh` (legacy shell entry)

## Use bundled references / 参考文档

Read these only when needed:

- `references/audit-dimensions.md` — audit taxonomy and severity model
- `references/file-schemas.md` — what each truth file should contain
- `references/workflow-playbooks.md` — step-by-step operating playbooks
- `references/worked-examples.md` — concrete end-to-end examples from project setup to chapter progression
- `references/json-schemas.md` — stable JSON output contracts for tooling and automation
- `references/audit-rules.md` — structured rule inventory for the chapter auditor
- `references/revision-workflow.md` — how audit, revision plans, spot fixes, and snapshots fit together
- `references/canon-side-story.md` — how to handle prequels / sequels / alternate lines
- `references/style-learning.md` — how to learn and apply style without overfitting
- `docs/agent-integration.md` — how to wire this skill into a specific host (Claude Code / OpenClaw / IDE-embedded or terminal agents); read it when the user asks how to install or integrate the skill

## Output expectations / 输出期望

When responding in chat, prefer concise operational structure:

- **Plan**
- **Draft / Findings / Proposed fixes**
- **State updates needed**
- **Open questions**

When producing audits, use severity:

- `critical` — breaks logic / continuity / core characterization
- `major` — noticeably weakens chapter or damages setup/payoff
- `minor` — style, clarity, repetition, local pacing
- `note` — optional enhancement

## Design goal / 设计目标

This skill is not a magic novel writer. It is a discipline layer that makes long-form AI writing more stable, inspectable, and maintainable.

````

## File: examples/demo-novel/README.md
size: 3970
sha: 22c0a0bbfe333ea3918646df8f20a99a78152625
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/README.md

````text
# demo-novel

这是一个**最小但完整**的示例项目，用来展示这个仓库的核心闭环：

`context -> draft -> audit -> extract-state -> state-update`

这是教学用的最小演示链路。对应 SKILL.md / README 的推荐主线 `init -> write-next -> draft -> revise -> extract-state -> state-update`：`context` 是 `write-next` 工作包的底层组成部分，`audit` 是 `revise` 修订闭环中的一个环节，而 `draft`（写正文）由你或 agent 完成，不是脚本命令。

> 推荐入口 / Recommended entrypoint：`python scripts/novelops_cli.py ...`

故事设定是一个两章规模的古风悬疑开局：主角林烬发现徐家旧玉佩疑似被调包，但还不能直接确认幕后人。

## 你可以先读什么

建议顺序：

1. `current_state.md`
2. `chapter_summaries.md`
3. `pending_hooks.md`
4. `chapters/ch01.md`
5. `chapters/ch02.md`

这样能最快看懂：truth files 如何约束正文，正文又如何反过来更新 truth files。

## 这个 demo 重点演示什么 / What this demo shows

### 1. context

生成下一章上下文：

```bash
python scripts/novelops_cli.py context --project examples/demo-novel
```

脚本会读取如下一批 truth files：

- `story_bible.md`
- `book_rules.md`
- `outline.md`
- `current_state.md`
- `chapter_summaries.md`
- `pending_hooks.md`
- `character_matrix.md`
- `character_knowledge.md`

你会看到：下一章不是凭空写，而是基于“当前状态 + 已开伏笔 + 人物认知边界”来写。

### 2. audit

对现有章节跑审计：

```bash
python scripts/novelops_cli.py audit --project examples/demo-novel --chapter-file examples/demo-novel/chapters/ch02.md --json
```

这个结果不等于文学评价，而是帮助你检查：

- 连续性是否稳定
- 是否有知识边界泄露
- 是否把悬念过早讲破

### 3. extract-state

从章节正文中提取候选状态更新：

```bash
python scripts/novelops_cli.py extract-state --project examples/demo-novel --chapter-file examples/demo-novel/chapters/ch02.md --json
```

这里的输出是**候选项**，例如：

- 可作为摘要的句子
- 角色新认知
- hook 的打开 / 推进
- 关系与情绪变化

### 4. state-update

确认候选项后，再写回 truth files：

```bash
python scripts/novelops_cli.py state-update \
  --project examples/demo-novel \
  --chapter 2 \
  --title "第二章 雨夜试探" \
  --summary "林烬借试探确认徐安隐瞒了玉佩转手顺序，但仍不能确定幕后人。" \
  --state-change "林烬确认徐安知道更多内情。" \
  --hook-advance "徐安为什么隐瞒玉佩最早经手人的名字" \
  --relationship "林烬 -> 徐安：表面合作维持，但实质信任继续下降" \
  --emotion "林烬：怀疑转为克制的逼问" \
  --json
```

执行后会更新：

- `chapter_summaries.md`
- `pending_hooks.md`
- `character_matrix.md`
- `emotional_arcs.md`

### 5. 底层脚本 / Advanced usage

如果你在调试某个单独能力，也仍然可以直接运行：

- `python scripts/build_next_chapter_context.py --project examples/demo-novel`
- `python scripts/audit_chapter.py --project examples/demo-novel --chapter-file examples/demo-novel/chapters/ch02.md --json`
- `python scripts/extract_state.py --project examples/demo-novel --chapter-file examples/demo-novel/chapters/ch02.md --json`
- `python scripts/update_story_state.py ...`

## 为什么这里只放两章

因为这个 demo 的目标不是展示“长”，而是展示“工作流怎么落地”。

两章已经足够说明：

- 第 1 章如何建立异常与悬念
- 第 2 章如何推进怀疑，但不直接揭示真相
- truth files 如何成为下一章的稳定输入

如果你要从零做自己的书，建议再看：

- [docs/getting-started.md](../../docs/getting-started.md)
- [docs/cli.md](../../docs/cli.md)
- [docs/project-template.md](../../docs/project-template.md)
- [docs/user-paths.md](../../docs/user-paths.md)

````

## File: README.md
size: 6170
sha: c3081f69a89d26a275aa865f1f28dcad14532951
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/README.md

````text
# NovelOps Skill

[![CI](https://img.shields.io/github/actions/workflow/status/qiyan233/novelops-skill/ci.yml?branch=main&label=CI)](https://github.com/qiyan233/novelops-skill/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Version](https://img.shields.io/badge/version-v1.1.0-blue)](CHANGELOG.md)

当前版本：**1.1.0**

一个**面向智能体应用**的长篇小说工作流 skill。它把长篇 / 连载 / 网文 / 同人写作
跑成一个**长期可维护的流程**——重点不是“单次写一章”，而是写到第 50 章时设定不崩、状态可回溯。

底层是纯 Python 3 CLI 加纯文本状态文件，不绑定具体宿主：OpenClaw、Claude Code、
IDE 内与终端里的智能体都能驱动它，详见[在不同智能体应用中使用](docs/agent-integration.md)。

灵感参考 **InkOS**：<https://github.com/Narcooo/inkos>。本项目是受其启发的 skill skeleton，
不是原项目的官方移植版。

中文 | [English](README.en.md)

---

## 它解决什么问题

长篇写作真正的难点不是“写不出下一章”，而是**写到第 50 章时还记得谁在第 3 章知道了什么**。
这个仓库把这件事拆成可执行的流程：

- **truth files** 维护世界观、当前局势、角色认知边界
- **`write-next`** 把“下一章该写什么、该避开什么”整理成结构化工作包
- **`draft`** 交给 LLM 起草（Hermes 优先，默认本地 Ollama）
- **`revise` / `auto-revise`** 审计与修订闭环
- **`extract-state` / `state-update`** 把新发生的事实写回状态
- **`snapshot` / `diff`** 随时回退与对比

它不是只负责“写”，而是负责把**多章写作**组织起来。

## 适合谁

适合：

- 想长期、多章、可回溯地写小说，需要维护章节摘要、角色状态、伏笔与当前局势
- 想搭一个类似 InkOS 的小说写作 skill
- 希望写作之外还有审计、修订、状态更新、快照这些环节

不太适合：只想临时生成一篇短文。这个仓库会明显偏重。

## 快速开始

需要 Python 3，无第三方依赖。

```bash
git clone https://github.com/qiyan233/novelops-skill.git
cd novelops-skill

python scripts/novelops_cli.py smoke-test                      # 自检，应输出 Smoke test passed.

python scripts/novelops_cli.py init ./my-novel "我的小说"       # 初始化项目
python scripts/novelops_cli.py write-next --project ./my-novel # 准备下一章
```

> **Windows / 无 bash 环境**请统一使用 `python scripts/novelops_cli.py ...`；
> `scripts/*.sh` 是遗留入口，需要 bash。所有功能都有等价的 Python 命令。

更细的步骤见 [安装与环境](docs/installation.md) 和 [快速上手](docs/getting-started.md)。

## 核心主线

```text
init -> write-next -> draft -> revise -> extract-state -> state-update
```

`draft` 由人或 agent 执笔都可以，也可以直接交给 LLM；`revise` 内部串起
knowledge-check / audit / revision-plan / spot-fixes。命令细节见 [CLI 入口](docs/cli.md)。

## 当前能力

已经能覆盖：

- 下一章准备（`write-next`，含单章契约与场景节拍）
- LLM 写作执行器（`draft`，Hermes 优先，默认本地 Ollama，云端 Nous Portal 可切换）
- 修订闭环（`revise`）与 LLM 段落级自动修订（`auto-revise`，默认只出 diff，`--apply` 前自动快照）
- 知识边界检查（`knowledge-check`，检测角色提前知道不该知道的事）
- 可配置规则引擎（`novelops.config.json` 定制审计词表 / 阈值 / 禁用规则）
- 状态提取与 truth files 更新（`extract-state` / `state-update`）
- 快照、diff 与打包（`snapshot` / `diff` / `package`）
- 基础回归测试（`smoke-test`）

还没做到的：

- 更多完整示例项目
- 多模型对比与自动重试策略
- 更细粒度的风格学习自动化

## 仓库里主要有什么

| 路径 | 用途 |
| --- | --- |
| [`SKILL.md`](SKILL.md) | skill 主说明——这个仓库最核心的文件，智能体的真正使用入口 |
| [`scripts/`](scripts/) | CLI 入口与底层脚本 |
| [`assets/project-template/`](assets/project-template/) | 小说项目模板（`init` 时复制） |
| [`examples/demo-novel/`](examples/demo-novel/) | 完整示例项目 |
| [`docs/`](docs/) | 使用说明 |
| [`references/`](references/) | 规则、结构与 JSON 契约参考 |

## 文档导航

**第一次看这个仓库**，建议按这个顺序：

1. [`SKILL.md`](SKILL.md) —— 先看定位，这里才更接近“skill 真正怎么工作”
2. [`examples/demo-novel/README.md`](examples/demo-novel/README.md) —— 看一个完整例子，
   比先读实现细节直观得多
3. [`docs/cli.md`](docs/cli.md) —— 需要敲命令时再看

**按主题查阅：**

| 文档 | 内容 |
| --- | --- |
| [docs/agent-integration.md](docs/agent-integration.md) | 在各类智能体应用里怎么接入（Claude Code / OpenClaw / IDE / 终端） |
| [docs/installation.md](docs/installation.md) | 安装与最小运行要求 |
| [docs/getting-started.md](docs/getting-started.md) | 从零跑到第一章 |
| [docs/cli.md](docs/cli.md) | 全部命令与参数 |
| [docs/user-paths.md](docs/user-paths.md) | 不同使用场景的路径选择 |
| [docs/project-template.md](docs/project-template.md) | 项目模板里每个文件的作用 |
| [docs/llm-drafting.md](docs/llm-drafting.md) | LLM 起草 / 自动修订的配置与离线通道 |
| [docs/faq.md](docs/faq.md) | 常见问题 |
| [references/json-schemas.md](references/json-schemas.md) | 所有 JSON 输出契约 |
| [references/audit-rules.md](references/audit-rules.md) | 审计规则清单 |
| [references/workflow-playbooks.md](references/workflow-playbooks.md) | 工作流剧本 |

**项目相关：** [CHANGELOG.md](CHANGELOG.md) · [CONTRIBUTING.md](CONTRIBUTING.md) ·
[SECURITY.md](SECURITY.md) · [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) ·
[docs/audit-fixes.md](docs/audit-fixes.md)（维护者：审计修复技术日志）

---

本项目是受 [InkOS](https://github.com/Narcooo/inkos) 启发的 skill skeleton，不是官方移植版。
````

## File: scripts/audit_chapter.py
size: 20756
sha: 33816523d5cecf5fa41a51a71586e80fbfec44f6
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/audit_chapter.py

```text
#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path

from novelops_common import CHAPTER_HEADING_RE, extract_bullets, extract_keywords, iso_now, latest_sections, read_text, require_existing_file, require_project_markers, write_json
from novelops_config import config_file_path, load_project_config, resolve_disabled, resolve_keyword_table, resolve_thresholds

SEVERITY_ORDER = {'critical': 0, 'major': 1, 'minor': 2, 'note': 3}
TRANSITIONS = ['突然', '忽然', '仿佛', '竟然', '不禁', '猛地', '一时间', 'at that moment', 'suddenly', 'instantly', 'as if', 'unexpectedly']
REPORT_SPEAK = ['核心', '本质上', '某种意义上', '换句话说', '信息差', '底层逻辑', '情绪价值', '动机', 'strategy', 'framework']
CROWD_CLICHES = ['全场震惊', '所有人都', '全都愣住了', 'everyone gasped', 'the whole room fell silent']
TIME_JUMPS = ['次日', '第二天', '当夜', '当天晚上', '数日后', '三日后', '一周后', 'later that day', 'the next day', 'hours later']
TELLING_PHRASES = ['他感到', '她感到', '他意识到', '她意识到', 'he felt', 'she felt']
KNOWLEDGE_LEAPS = ['所有真相', '完整计划', '幕后之人就是', '答案已经摆在眼前', '真相大白']
PROTAGONIST_LOCK_BREAKS = ['突然心软', '轻易原谅', '毫无理由地退让', '无条件相信', '主动坦白一切']
STATE_TURN_MARKERS = ['决定', '确认', '发现', '明白', '知道', '拿到', '失去', '暴露', '受伤', '怀疑', 'betrayed', 'revealed', 'decided']

DEFAULT_KEYWORD_TABLES = {
    'TRANSITIONS': TRANSITIONS,
    'REPORT_SPEAK': REPORT_SPEAK,
    'CROWD_CLICHES': CROWD_CLICHES,
    'TIME_JUMPS': TIME_JUMPS,
    'TELLING_PHRASES': TELLING_PHRASES,
    'KNOWLEDGE_LEAPS': KNOWLEDGE_LEAPS,
    'PROTAGONIST_LOCK_BREAKS': PROTAGONIST_LOCK_BREAKS,
    'STATE_TURN_MARKERS': STATE_TURN_MARKERS,
    'AUD110_LEAK_TRIGGERS': ['早就知道', '其实早已明白', '他当然知道真相'],
}

DEFAULT_THRESHOLDS = {
    'AUD-101': {'min_count': 3, 'major_at': 5},
    'AUD-102': {'major_at': 3},
    'AUD-104': {'min_paragraphs': 4, 'closeness_chars': 25, 'uniform_ratio': 0.7},
    'AUD-105': {'min_open_hooks': 8, 'max_chapter_chars': 8000},
    'AUD-106': {'min_open_hooks': 3, 'min_chapter_chars': 1200, 'keyword_probe': 12},
    'AUD-107': {'keyword_probe': 15, 'min_chapter_chars': 1500},
    'AUD-108': {'max_overlap': 1, 'min_chapter_chars': 2000},
    'AUD-111': {'min_jumps': 2, 'max_chapter_chars': 2500, 'major_at': 3},
    'AUD-112': {'min_chapter_chars': 1800},
    'AUD-113': {'min_hits': 3},
    'AUD-114': {'min_hits': 4},
}

CONFIGURABLE_RULE_IDS = [
    'AUD-101', 'AUD-102', 'AUD-103', 'AUD-104', 'AUD-105', 'AUD-106', 'AUD-107',
    'AUD-108', 'AUD-109', 'AUD-110', 'AUD-111', 'AUD-112', 'AUD-113', 'AUD-114',
]

VALID_AUDIT_SECTION_KEYS = ('keywords', 'thresholds', 'rules_disabled')

def resolve_audit_config(project, config=None):
    """解析项目配置的 audit 节，返回 (关键词表, 阈值表, 禁用集合, summary.config 块)。"""
    if config is None:
        config = load_project_config(project)
    audit_cfg = config.get('audit') or {}
    for key in audit_cfg:
        if key not in VALID_AUDIT_SECTION_KEYS:
            raise SystemExit(
                'novelops.config.json audit section has unknown key %r (known: %s)'
                % (key, ', '.join(VALID_AUDIT_SECTION_KEYS)))
    kw_specs = audit_cfg.get('keywords') or {}
    for name in kw_specs:
        if name not in DEFAULT_KEYWORD_TABLES:
            raise SystemExit(
                'novelops.config.json audit.keywords has unknown table %r (known: %s)'
                % (name, ', '.join(sorted(DEFAULT_KEYWORD_TABLES))))
    tables = {}
    tables_overridden = {}
    for name, default in DEFAULT_KEYWORD_TABLES.items():
        merged, source = resolve_keyword_table(name, default, kw_specs.get(name))
        tables[name] = merged
        if source != 'default':
            tables_overridden[name] = source
    thresholds = resolve_thresholds(DEFAULT_THRESHOLDS, audit_cfg.get('thresholds'))
    disabled = resolve_disabled(set(CONFIGURABLE_RULE_IDS), audit_cfg.get('rules_disabled'), 'audit.rules_disabled')
    config_summary = {
        'config_file': config_file_path(project),
        'keyword_tables_overridden': tables_overridden,
        'thresholds_overridden': sorted((audit_cfg.get('thresholds') or {}).keys()),
        'rules_disabled': sorted(disabled),
    }
    return tables, thresholds, disabled, config_summary

def add(findings, rule_id, severity, dimension, message, evidence=None, repair_targets=None):
    findings.append({
        'rule_id': rule_id,
        'severity': severity,
        'dimension': dimension,
        'message': message,
        'evidence': evidence or [],
        'repair_targets': repair_targets or [],
    })

def finding_counts(findings):
    counts = {'critical': 0, 'major': 0, 'minor': 0, 'note': 0}
    for item in findings:
        counts[item['severity']] += 1
    return counts

def split_paragraphs(chapter):
    """切段落用于节奏分析。

    优先按空行分段；中文稿常以单换行分段，这时空行切分只会得到 1 段，
    会让 AUD-104 的 min_paragraphs 门槛永远不成立（等于规则失效），
    因此单段结果回退到按行切分。
    """
    paras = [p.strip() for p in re.split(r'\n\s*\n', chapter) if p.strip()]
    if len(paras) > 1:
        return paras
    return [p.strip() for p in chapter.splitlines() if p.strip()]

def chapter_metrics(chapter, time_jumps=None):
    paras = split_paragraphs(chapter)
    return {
        'char_count': len(chapter),
        'paragraph_count': len(paras),
        'dialogue_quote_count': chapter.count('“') + chapter.count('"'),
        'time_jump_markers': sum(chapter.count(x) for x in (time_jumps if time_jumps is not None else TIME_JUMPS)),
    }

def open_hook_keywords(pending_hooks):
    keywords = []
    open_hooks = [x for x in extract_bullets(pending_hooks) if '[OPEN]' in x]
    for hook in open_hooks:
        hook = re.sub(r'\[[^\]]+\]\s*', '', hook)
        hook = re.sub(r'\([^\)]*\)', '', hook)
        keywords.extend(extract_keywords(hook, min_len=2, limit=6))
    return open_hooks, list(dict.fromkeys(keywords))

def build_report(project, chapter_file, config=None):
    project = require_project_markers(project)
    kw, thresholds, disabled, config_summary = resolve_audit_config(project, config)
    chapter_file = require_existing_file(chapter_file, 'Chapter file')
    chapter = read_text(chapter_file)
    current_state = read_text(project / 'current_state.md')
    book_rules = read_text(project / 'book_rules.md')
    pending_hooks = read_text(project / 'pending_hooks.md')
    chapter_summaries = read_text(project / 'chapter_summaries.md')
    outline = read_text(project / 'outline.md')

    findings = []
    fix_plan = []
    rules_evaluated = []

    if not chapter.strip():
        add(findings, 'AUD-000', 'critical', 'chapter-input', 'Chapter text is empty.', repair_targets=['Provide chapter text before auditing.'])
        counts = finding_counts(findings)
        return {
            'schema_version': 'novelops.audit-report.v1',
            'tool': 'audit_chapter',
            'generated_at': iso_now(),
            'project': str(project),
            'chapter': str(chapter_file),
            'chapter_file': str(chapter_file),
            'overall': 'block',
            'summary': {'counts': counts, 'finding_count': 1, 'rules_evaluated': [], 'config': config_summary},
            'source_files': [str(chapter_file)],
            'chapter_metrics': chapter_metrics(chapter, kw['TIME_JUMPS']),
            'findings': findings,
            'minimal_fix_plan': ['Provide chapter text before auditing.'],
        }

    if 'AUD-101' not in disabled:
        rules_evaluated.append('AUD-101')
        th101 = thresholds['AUD-101']
        for word in kw['TRANSITIONS']:
            count = chapter.count(word)
            if count >= th101['min_count']:
                sev = 'major' if count >= th101['major_at'] else 'minor'
                add(findings, 'AUD-101', sev, 'repetition-fatigue', "Transition word '%s' appears %s times." % (word, count), evidence=[word], repair_targets=["Reduce repeated transition word '%s'." % word])
                fix_plan.append("Reduce repeated transition word '%s'." % word)

    if 'AUD-102' not in disabled:
        rules_evaluated.append('AUD-102')
        report_hits = [w for w in kw['REPORT_SPEAK'] if w in chapter]
        if report_hits:
            sev = 'major' if len(report_hits) >= thresholds['AUD-102']['major_at'] else 'minor'
            add(findings, 'AUD-102', sev, 'report-speak', 'Abstract/report-like wording detected: %s.' % ', '.join(report_hits[:6]), evidence=report_hits[:6], repair_targets=['Replace abstract explanation with concrete action, sensory evidence, or dialogue.'])
            fix_plan.append('Replace abstract explanation with concrete action, sensory evidence, or dialogue.')

    if 'AUD-103' not in disabled:
        rules_evaluated.append('AUD-103')
        crowd_hits = [w for w in kw['CROWD_CLICHES'] if w in chapter]
        if crowd_hits:
            add(findings, 'AUD-103', 'minor', 'crowd-cliche', 'Generic crowd-response cliché detected: %s.' % ', '.join(crowd_hits), evidence=crowd_hits, repair_targets=['Replace generic crowd reaction with 1-2 specific character reactions.'])
            fix_plan.append('Replace generic crowd reaction with 1-2 specific character reactions.')

    if 'AUD-104' not in disabled:
        rules_evaluated.append('AUD-104')
        th104 = thresholds['AUD-104']
        paras = split_paragraphs(chapter)
        if len(paras) >= th104['min_paragraphs']:
            lens = [len(p) for p in paras]
            avg = sum(lens) / float(len(lens))
            close = sum(1 for x in lens if abs(x - avg) <= th104['closeness_chars'])
            if close / float(len(lens)) >= th104['uniform_ratio']:
                add(findings, 'AUD-104', 'minor', 'paragraph-monotony', 'Paragraph lengths are too uniform; rhythm may feel machine-made.', repair_targets=['Vary paragraph length and beat density.'])
                fix_plan.append('Vary paragraph length and beat density.')

    open_hooks, hook_keywords = open_hook_keywords(pending_hooks)

    if 'AUD-105' not in disabled:
        rules_evaluated.append('AUD-105')
        th105 = thresholds['AUD-105']
        if len(open_hooks) >= th105['min_open_hooks'] and len(chapter) < th105['max_chapter_chars']:
            add(findings, 'AUD-105', 'minor', 'hook-overload', 'There are %s open hooks; consider advancing at least one clearly.' % len(open_hooks), evidence=open_hooks[:5], repair_targets=['Advance or partially pay off at least one existing hook.'])
            fix_plan.append('Advance or partially pay off at least one existing hook.')

    if 'AUD-106' not in disabled:
        rules_evaluated.append('AUD-106')
        th106 = thresholds['AUD-106']
        if len(open_hooks) >= th106['min_open_hooks'] and len(chapter) > th106['min_chapter_chars'] and hook_keywords:
            if not any(keyword in chapter for keyword in hook_keywords[:th106['keyword_probe']]):
                add(findings, 'AUD-106', 'minor', 'hook-advancement', 'Chapter does not appear to touch any currently open hook keywords.', evidence=hook_keywords[:8], repair_targets=['Check whether this chapter should advance, delay, or intentionally isolate current open hooks.'])
                fix_plan.append('Check whether this chapter should advance, delay, or intentionally isolate current open hooks.')

    if 'AUD-107' not in disabled:
        rules_evaluated.append('AUD-107')
        th107 = thresholds['AUD-107']
        outline_keywords = extract_keywords(outline, min_len=3, limit=40)
        if outline_keywords:
            hit = sum(1 for w in outline_keywords[:th107['keyword_probe']] if w in chapter)
            if hit == 0 and len(chapter) > th107['min_chapter_chars']:
                add(findings, 'AUD-107', 'major', 'outline-drift', 'Chapter appears weakly connected to the current outline keywords.', evidence=outline_keywords[:10], repair_targets=['Check whether the chapter still serves the planned arc or chapter function.'])
                fix_plan.append('Check whether the chapter still serves the planned arc or chapter function.')

    if 'AUD-108' not in disabled:
        rules_evaluated.append('AUD-108')
        th108 = thresholds['AUD-108']
        facts_section = current_state.split('## Character beliefs')[0]
        state_keywords = extract_keywords(facts_section, min_len=2, limit=20)
        if state_keywords:
            overlap = sum(1 for w in state_keywords if w in chapter)
            if overlap <= th108['max_overlap'] and len(chapter) > th108['min_chapter_chars']:
                add(findings, 'AUD-108', 'major', 'state-cohesion', 'Chapter barely references current authoritative state; risk of drift.', evidence=state_keywords[:10], repair_targets=['Re-check current_state.md and ensure the chapter reflects active facts, conflicts, and pressures.'])
                fix_plan.append('Re-check current_state.md and ensure the chapter reflects active facts, conflicts, and pressures.')

    if 'AUD-109' not in disabled:
        rules_evaluated.append('AUD-109')
        constraint_lines = [x for x in extract_bullets(book_rules) if re.search(r'不能|不得|不要|禁止|avoid|never|must not|do not|constraint|prohibition', x, flags=re.I)]
        lock_breaks = [x for x in kw['PROTAGONIST_LOCK_BREAKS'] if x in chapter]
        if constraint_lines and lock_breaks:
            add(findings, 'AUD-109', 'major', 'protagonist-lock', 'Potential protagonist lock break language found.', evidence=lock_breaks + constraint_lines[:3], repair_targets=['Re-check protagonist lock before keeping this turn in characterization.'])
            fix_plan.append('Re-check protagonist lock before keeping this turn in characterization.')

    if 'AUD-110' not in disabled:
        rules_evaluated.append('AUD-110')
        recent = latest_sections(chapter_summaries, CHAPTER_HEADING_RE, 3)
        if ('不知道' in current_state or '不知' in current_state) and any(x in chapter for x in kw['AUD110_LEAK_TRIGGERS']):
            add(findings, 'AUD-110', 'critical', 'information-boundary', 'Possible knowledge leak against current_state character-belief section.', repair_targets=['Verify who is allowed to know the revealed fact, then patch the leaking line.'])
            fix_plan.append('Verify who is allowed to know the revealed fact, then patch the leaking line.')
        elif recent and any(x in chapter for x in kw['KNOWLEDGE_LEAPS']):
            add(findings, 'AUD-110', 'minor', 'information-boundary', 'Check whether current POV earns this level of knowledge disclosure.', evidence=[x for x in kw['KNOWLEDGE_LEAPS'] if x in chapter], repair_targets=['Check whether current POV has actually earned this reveal level.'])
            fix_plan.append('Check whether current POV has actually earned this reveal level.')

    if 'AUD-111' not in disabled:
        rules_evaluated.append('AUD-111')
        th111 = thresholds['AUD-111']
        jump_hits = [x for x in kw['TIME_JUMPS'] if x in chapter]
        if len(jump_hits) >= th111['min_jumps'] and len(chapter) < th111['max_chapter_chars']:
            sev = 'major' if len(jump_hits) >= th111['major_at'] else 'minor'
            add(findings, 'AUD-111', sev, 'timeline-continuity', 'Multiple time-jump markers appear in a compact chapter; verify timeline coherence.', evidence=jump_hits, repair_targets=['Check whether time progression is clear and earned between scene beats.'])
            fix_plan.append('Check whether time progression is clear and earned between scene beats.')

    if 'AUD-112' not in disabled:
        rules_evaluated.append('AUD-112')
        quote_count = chapter.count('“') + chapter.count('"')
        if quote_count == 0 and len(chapter) > thresholds['AUD-112']['min_chapter_chars']:
            add(findings, 'AUD-112', 'note', 'dialogue-balance', 'Long chapter with no dialogue; verify that this is intentional.')

    if 'AUD-113' not in disabled:
        rules_evaluated.append('AUD-113')
        telling_hits = [w for w in kw['TELLING_PHRASES'] if w in chapter]
        if len(telling_hits) >= thresholds['AUD-113']['min_hits']:
            add(findings, 'AUD-113', 'minor', 'telling-vs-dramatizing', 'Repeated emotional labeling found: %s.' % ', '.join(sorted(set(telling_hits))), evidence=sorted(set(telling_hits)), repair_targets=['Replace some direct emotion labels with action or sensory cues.'])
            fix_plan.append('Replace some direct emotion labels with action or sensory cues.')

    if 'AUD-114' not in disabled:
        rules_evaluated.append('AUD-114')
        turn_hits = [w for w in kw['STATE_TURN_MARKERS'] if w in chapter]
        if len(turn_hits) >= thresholds['AUD-114']['min_hits']:
            add(findings, 'AUD-114', 'note', 'state-update-pressure', 'Chapter contains multiple state-turn markers; remember to update truth files after acceptance.', evidence=turn_hits[:8], repair_targets=['Prepare state updates for summaries, hooks, relationships, and emotional arcs.'])
            fix_plan.append('Prepare state updates for summaries, hooks, relationships, and emotional arcs.')

    findings.sort(key=lambda x: (SEVERITY_ORDER[x['severity']], x['rule_id']))
    dedup_fix_plan = []
    seen = set()
    for item in fix_plan:
        if item in seen:
            continue
        seen.add(item)
        dedup_fix_plan.append(item)
    if not dedup_fix_plan:
        dedup_fix_plan = ['No obvious high-severity issue found by heuristic audit. Do a human pass for subtle continuity and tone.']

    counts = finding_counts(findings)
    if counts['critical']:
        overall = 'block'
    elif counts['major']:
        overall = 'revise'
    else:
        overall = 'pass'

    return {
        'schema_version': 'novelops.audit-report.v1',
        'tool': 'audit_chapter',
        'generated_at': iso_now(),
        'project': str(project),
        'chapter': str(chapter_file),
        'chapter_file': str(chapter_file),
        'overall': overall,
        'summary': {
            'counts': counts,
            'finding_count': len(findings),
            'rules_evaluated': rules_evaluated,
            'config': config_summary,
        },
        'source_files': [
            str(chapter_file),
            str(project / 'current_state.md'),
            str(project / 'book_rules.md'),
            str(project / 'pending_hooks.md'),
            str(project / 'chapter_summaries.md'),
            str(project / 'outline.md'),
        ],
        'chapter_metrics': chapter_metrics(chapter, kw['TIME_JUMPS']),
        'findings': findings,
        'minimal_fix_plan': dedup_fix_plan,
    }

def main():
    parser = argparse.ArgumentParser(description='Heuristic chapter auditor for novelops-skill projects.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--chapter-file', required=True)
    parser.add_argument('--json', action='store_true', help='Output JSON instead of Markdown.')
    parser.add_argument('--write-report', action='store_true', help='Write report into project/reviews/.')
    args = parser.parse_args()

    report = build_report(args.project, args.chapter_file)

    if args.write_report:
        reviews = Path(args.project) / 'reviews'
        reviews.mkdir(parents=True, exist_ok=True)
        out = reviews / ('%s.audit.json' % Path(args.chapter_file).stem)
        report['report_path'] = str(out)
        write_json(out, report)

    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
        return

    print('# Chapter Audit')
    print()
    print('## Summary verdict')
    print('- overall: %s' % report['overall'])
    print()
    print('## Summary counts')
    for sev in ['critical', 'major', 'minor', 'note']:
        print('- %s: %s' % (sev, report['summary']['counts'][sev]))
    print()
    print('## Findings')
    grouped = {'critical': [], 'major': [], 'minor': [], 'note': []}
    for item in report['findings']:
        grouped[item['severity']].append(item)
    for sev in ['critical', 'major', 'minor', 'note']:
        print('### %s' % sev)
        if not grouped[sev]:
            print('- none')
        else:
            for item in grouped[sev]:
                print('- [%s/%s] %s' % (item['rule_id'], item['dimension'], item['message']))
        print()
    print('## Minimal fix plan')
    for item in report['minimal_fix_plan']:
        print('- %s' % item)

if __name__ == '__main__':
    main()
```

## File: scripts/auto_revise.py
size: 18176
sha: 3c3b82660b98440ab6f1ba3c57f109e422a2deeb
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/auto_revise.py

````text
#!/usr/bin/env python3
"""LLM 段落级最小化自动修订。

流程：跑修订闭环（run_revision_cycle）→ 取 local-dimension 且有 evidence 的 findings →
按 evidence 定位包含段落（同段多 finding 合并为一个 target）→ 每个 target 交 LLM 最小化重写。

三种模式：
- --dry-run：不联网不写盘，只输出每个 target 的请求 payload；
- 缺省（diff）：执行重写（mock 或 live），输出整章 unified diff，但不写盘；
- --apply：先自动 snapshot + 章节原文备份，再把重写结果写回。
"""
import argparse
import difflib
import json
import re
from pathlib import Path

from audit_chapter import SEVERITY_ORDER
from build_write_next_packet import book_constraints
from draft_chapter import find_chapter_headings
from llm_client import (
    build_chat_payload,
    chat,
    load_mock_responses,
    resolve_api_key,
    resolve_llm_config,
    resolve_mock_source,
)
from novelops_common import (
    atomic_write_text,
    clean_model_output,
    detect_newline,
    iso_now,
    parse_chapter_number,
    read_text,
    state_root,
    write_json,
)
from novelops_config import load_project_config
from run_revision_cycle import build_cycle
from snapshot_story_state import snapshot
from suggest_spot_fixes import LOCAL_DIMENSIONS, TEMPLATES

PARA_SPLIT_RE = re.compile(r'\n\s*\n')
DIFF_LINE_CAP = 400
LENGTH_RATIO_MIN = 0.4
LENGTH_RATIO_MAX = 2.5
# 单条 finding 最多牵引几个段落：evidence 是「突然」这类通用词时会命中很多段，
# 不设限的话一个 finding 就能吃满 --max-paragraphs 预算，让「最小化修订」名不副实。
MAX_PARAGRAPHS_PER_FINDING = 2

REWRITE_SYSTEM_PROMPT = (
    '你是长篇小说的最小化修订执行器。规则：\n'
    '- 只修订问题清单里列出的问题，能不动的句子保持原样。\n'
    '- 保持人称、时态、POV 与信息边界，不得让任何角色知道原文中不知道的事。\n'
    '- 不新增人物、事件、设定或伏笔，不删除关键信息。\n'
    '- 重写后段落长度与原段接近（±30%）。\n'
    '- 只输出重写后的段落纯文本，不要标题、解释或代码块。'
)

def split_paragraphs(text):
    """按空行切段并记录 (start, end) 偏移，供精确重建全文。"""
    paragraphs = []
    pos = 0
    for match in PARA_SPLIT_RE.finditer(text):
        segment = text[pos:match.start()]
        if segment.strip():
            paragraphs.append({'index': len(paragraphs), 'start': pos, 'end': match.start(), 'text': segment})
        pos = match.end()
    tail = text[pos:]
    if tail.strip():
        paragraphs.append({'index': len(paragraphs), 'start': pos, 'end': len(text), 'text': tail})
    return paragraphs

def is_heading_paragraph(text):
    return text.lstrip().startswith('#')

def collect_targets(chapter_text, findings, max_paragraphs):
    """把 local-dimension findings 映射到包含段落，合并同段，返回 (targets, skipped_findings)。"""
    paragraphs = split_paragraphs(chapter_text)
    skipped_findings = []
    para_findings = {}
    for finding in findings:
        if finding['dimension'] not in LOCAL_DIMENSIONS:
            continue
        evidence = [token for token in (finding.get('evidence') or []) if token]
        if not evidence:
            skipped_findings.append({
                'rule_id': finding.get('rule_id'),
                'dimension': finding['dimension'],
                'reason': 'no-evidence-anchor',
            })
            continue
        hit_indexes = set()
        for token in evidence:
            for para in paragraphs:
                if is_heading_paragraph(para['text']):
                    continue
                if token in para['text']:
                    hit_indexes.add(para['index'])
        if not hit_indexes:
            skipped_findings.append({
                'rule_id': finding.get('rule_id'),
                'dimension': finding['dimension'],
                'reason': 'evidence-not-found',
            })
            continue
        if len(hit_indexes) > MAX_PARAGRAPHS_PER_FINDING:
            kept = sorted(hit_indexes)[:MAX_PARAGRAPHS_PER_FINDING]
            skipped_findings.append({
                'rule_id': finding.get('rule_id'),
                'dimension': finding['dimension'],
                'reason': 'evidence-too-broad',
            })
            hit_indexes = set(kept)
        for index in hit_indexes:
            para_findings.setdefault(index, []).append(finding)

    def target_sort_key(index):
        best = min(SEVERITY_ORDER[f['severity']] for f in para_findings[index])
        return (best, index)

    ordered = sorted(para_findings, key=target_sort_key)
    targets = []
    for index in ordered[:max_paragraphs]:
        para = paragraphs[index]
        targets.append({
            'paragraph': para,
            'findings': para_findings[index],
        })
    for index in ordered[max_paragraphs:]:
        for finding in para_findings[index]:
            skipped_findings.append({
                'rule_id': finding.get('rule_id'),
                'dimension': finding['dimension'],
                'reason': 'over-paragraph-budget',
            })
    targets.sort(key=lambda t: t['paragraph']['index'])
    return targets, skipped_findings, paragraphs

def build_rewrite_messages(target, paragraphs, constraints):
    para = target['paragraph']
    prev_text = paragraphs[para['index'] - 1]['text'].strip() if para['index'] > 0 else '（本段已是开头）'
    next_text = (paragraphs[para['index'] + 1]['text'].strip()
                 if para['index'] + 1 < len(paragraphs) else '（本段已是结尾）')
    issue_lines = []
    for finding in target['findings']:
        template = TEMPLATES.get(finding['dimension'], 'Apply the smallest local patch that resolves the issue.')
        issue_lines.append('- [%s/%s] %s；建议动作：%s'
                           % (finding.get('rule_id'), finding['dimension'], finding['message'], template))
    constraint_lines = '\n'.join('- %s' % line for line in constraints) if constraints else '- （无显式禁令）'
    user = (
        '【书籍约束】\n%s\n\n'
        '【上文段落（仅供衔接，勿输出）】\n%s\n\n'
        '【待修订段落】\n%s\n\n'
        '【下文段落（仅供衔接，勿输出）】\n%s\n\n'
        '【问题清单】\n%s\n\n'
        '现在输出重写后的段落。'
        % (constraint_lines, prev_text, para['text'].strip(), next_text, '\n'.join(issue_lines))
    )
    return [
        {'role': 'system', 'content': REWRITE_SYSTEM_PROMPT},
        {'role': 'user', 'content': user},
    ]

def validate_rewrite(original, revised):
    """校验并净化重写结果；返回 (status, reason, cleaned)。

    净化必须在校验之前：模型返回 ``` 包裹或「好的，以下是修订后的段落：」开场白时，
    不剥掉就会把围栏和客套话当成合法正文写回小说。status: rewritten/unchanged/skipped。
    """
    cleaned = clean_model_output(revised)
    if not cleaned:
        return 'skipped', 'empty-rewrite', cleaned
    if find_chapter_headings(cleaned):
        return 'skipped', 'rewrite-contains-heading', cleaned
    ratio = len(cleaned) / float(len(original.strip()) or 1)
    if ratio < LENGTH_RATIO_MIN or ratio > LENGTH_RATIO_MAX:
        return 'skipped', 'rewrite-out-of-bounds', cleaned
    if cleaned == original.strip():
        return 'unchanged', None, cleaned
    return 'rewritten', None, cleaned

def rebuild_text(chapter_text, replacements):
    """replacements: [(start, end, new_text)]，按位置从后往前替换。"""
    result = chapter_text
    for start, end, new_text in sorted(replacements, key=lambda item: item[0], reverse=True):
        result = result[:start] + new_text + result[end:]
    return result

def build_auto_revise(project, chapter_file, dry_run=False, apply_changes=False, mock_path=None,
                      llm_overrides=None, max_paragraphs=5, skip_knowledge_check=False, force=False):
    chapter_file = Path(chapter_file)
    cycle = build_cycle(project, chapter_file, run_knowledge_check=not skip_knowledge_check)
    chapter_text = read_text(chapter_file)
    findings = cycle['audit']['findings']
    targets, skipped_findings, paragraphs = collect_targets(chapter_text, findings, max_paragraphs)

    project_config = load_project_config(project)
    llm_config = resolve_llm_config(project_config, llm_overrides)
    api_key, api_key_source = resolve_api_key(llm_config)
    constraints = book_constraints(read_text(Path(project) / 'book_rules.md'))

    mode = 'dry-run' if dry_run else ('apply' if apply_changes else 'diff')
    report = {
        'schema_version': 'novelops.auto-revise.v1',
        'tool': 'auto_revise',
        'generated_at': iso_now(),
        'project': cycle['project'],
        'chapter_file': str(chapter_file),
        'chapter': parse_chapter_number(chapter_file.stem),
        'mode': mode,
        'llm': {
            'provider': llm_config['provider'],
            'base_url': llm_config['base_url'],
            'model': llm_config['model'],
            'temperature': llm_config['temperature'],
            'top_p': llm_config['top_p'],
            'max_tokens': llm_config['max_tokens'],
            'api_key': None,
            'api_key_present': api_key is not None,
            'api_key_source': api_key_source,
        },
        'based_on': {
            'revision_cycle_status': cycle['status'],
            'audit_overall': cycle['audit']['overall'],
        },
        'summary': {
            'local_finding_count': sum(1 for f in findings if f['dimension'] in LOCAL_DIMENSIONS),
            'paragraphs_targeted': len(targets),
            'paragraphs_rewritten': 0,
            'paragraphs_skipped': 0,
            'applied': False,
        },
        'targets': [],
        'skipped_findings': skipped_findings,
        'diff': [],
        'diff_truncated': False,
        'snapshot': None,
    }

    # audit 判定 block 说明存在 critical 问题（如信息边界泄露）。局部段落重写修不了
    # 结构性问题，还可能把它盖住；在调用 LLM 之前就拒绝，附带 --force 逃生通道。
    if apply_changes and not force and report['based_on']['audit_overall'] == 'block':
        raise SystemExit(
            'Audit overall is "block"（存在 critical 问题）；段落级重写修不了结构性问题。'
            '请先处理 critical 项，确认仍要继续时加 --force。')

    def target_entry(target):
        return {
            'paragraph_index': target['paragraph']['index'],
            'findings': [
                {
                    'rule_id': f.get('rule_id'),
                    'dimension': f['dimension'],
                    'severity': f['severity'],
                    'evidence': f.get('evidence') or [],
                }
                for f in target['findings']
            ],
            'original': target['paragraph']['text'].strip(),
            'revised': None,
            'status': 'skipped',
            'skip_reason': None,
        }

    if dry_run:
        for target in targets:
            entry = target_entry(target)
            entry['payload'] = build_chat_payload(build_rewrite_messages(target, paragraphs, constraints), llm_config)
            report['targets'].append(entry)
        report['summary']['paragraphs_skipped'] = len(targets)
        return report

    mock_source = resolve_mock_source(mock_path)
    mock_responses = load_mock_responses(mock_source) if mock_source else None
    if mock_responses is not None and len(mock_responses) not in (1,) and len(mock_responses) < len(targets):
        raise SystemExit('mock responses exhausted: need %d, got %d' % (len(targets), len(mock_responses)))

    replacements = []
    transport = None
    for position, target in enumerate(targets):
        entry = target_entry(target)
        if mock_responses is not None:
            mock_content = mock_responses[0] if len(mock_responses) == 1 else mock_responses[position]
        else:
            mock_content = None
        result = chat(build_rewrite_messages(target, paragraphs, constraints), llm_config, mock_content=mock_content)
        transport = result['transport']
        status, reason, cleaned = validate_rewrite(target['paragraph']['text'], result['content'])
        entry['status'] = status
        entry['skip_reason'] = reason
        if status == 'rewritten':
            entry['revised'] = cleaned
            paragraph = target['paragraph']
            original_segment = chapter_text[paragraph['start']:paragraph['end']]
            # 保留原段落的首尾空白：段落切片本身可能带尾随换行（文件末尾尤其如此），
            # 直接用 strip 过的正文替换会把换行吃掉，重建后文件末尾就没有换行了。
            leading = original_segment[:len(original_segment) - len(original_segment.lstrip())]
            trailing = original_segment[len(original_segment.rstrip()):]
            body = cleaned.replace('\r\n', '\n').replace('\r', '\n')
            replacements.append((paragraph['start'], paragraph['end'], leading + body + trailing))
            report['summary']['paragraphs_rewritten'] += 1
        elif status == 'skipped':
            report['summary']['paragraphs_skipped'] += 1
        report['targets'].append(entry)
    report['llm']['transport'] = transport

    revised_text = rebuild_text(chapter_text, replacements)
    if revised_text != chapter_text:
        diff_lines = list(difflib.unified_diff(
            chapter_text.splitlines(),
            revised_text.splitlines(),
            fromfile='before/%s' % chapter_file.name,
            tofile='after/%s' % chapter_file.name,
            lineterm='',
        ))
        if len(diff_lines) > DIFF_LINE_CAP:
            report['diff'] = diff_lines[:DIFF_LINE_CAP]
            report['diff_truncated'] = True
        else:
            report['diff'] = diff_lines

    if apply_changes and revised_text != chapter_text:
        stem = chapter_file.stem
        manifest = snapshot(project, label='auto-revise-%s' % stem,
                            chapter=parse_chapter_number(stem), notes='pre auto-revise backup')
        backup_dir = state_root(project) / 'backups' / manifest['snapshot_id']
        backup_dir.mkdir(parents=True, exist_ok=True)
        backup_path = backup_dir / chapter_file.name
        # 原文件可能是 CRLF；read_text 已把它归一成 \n，写回时按原风格还原，
        # 否则只改一段却会把整文件行尾翻转，git diff 全红。
        newline = detect_newline(chapter_file, '\n')
        atomic_write_text(backup_path, chapter_text.replace('\n', newline))
        atomic_write_text(chapter_file, revised_text.replace('\n', newline))
        report['summary']['applied'] = True
        report['snapshot'] = {
            'snapshot_id': manifest['snapshot_id'],
            'snapshot_dir': manifest['snapshot_dir'],
            'chapter_backup': str(backup_path),
        }
    return report

def print_markdown(report):
    print('# Auto Revise')
    print()
    print('- mode: %s' % report['mode'])
    print('- chapter_file: %s' % report['chapter_file'])
    print('- targets: %s' % report['summary']['paragraphs_targeted'])
    print('- rewritten: %s' % report['summary']['paragraphs_rewritten'])
    print('- applied: %s' % ('yes' if report['summary']['applied'] else 'no'))
    if report['snapshot']:
        print('- snapshot: %s' % report['snapshot']['snapshot_id'])
        print('- chapter_backup: %s' % report['snapshot']['chapter_backup'])
    print()
    print('## Diff')
    if not report['diff']:
        print('- none')
    else:
        for line in report['diff']:
            print(line)

def main():
    parser = argparse.ArgumentParser(description='LLM paragraph-level minimal auto revision for a chapter.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--chapter-file', required=True)
    parser.add_argument('--dry-run', action='store_true', help='Only print per-target chat payloads.')
    parser.add_argument('--apply', action='store_true', help='Write revisions back (snapshot + backup first).')
    parser.add_argument('--force', action='store_true',
                        help='Apply even when the audit overall is "block" (critical findings present).')
    parser.add_argument('--mock-response', help='File whose content is used as the LLM response (offline).')
    parser.add_argument('--max-paragraphs', type=int, default=5)
    parser.add_argument('--skip-knowledge-check', action='store_true')
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--write-report', action='store_true')
    parser.add_argument('--model')
    parser.add_argument('--base-url')
    parser.add_argument('--temperature', type=float)
    parser.add_argument('--top-p', dest='top_p', type=float)
    parser.add_argument('--max-tokens', dest='max_tokens', type=int)
    parser.add_argument('--timeout', dest='timeout_seconds', type=int)
    args = parser.parse_args()

    llm_overrides = {
        'model': args.model,
        'base_url': args.base_url,
        'temperature': args.temperature,
        'top_p': args.top_p,
        'max_tokens': args.max_tokens,
        'timeout_seconds': args.timeout_seconds,
    }

    report = build_auto_revise(
        args.project,
        args.chapter_file,
        dry_run=args.dry_run,
        apply_changes=args.apply,
        mock_path=args.mock_response,
        llm_overrides=llm_overrides,
        max_paragraphs=args.max_paragraphs,
        skip_knowledge_check=args.skip_knowledge_check,
        force=args.force,
    )

    if args.write_report:
        out = Path(args.project) / 'reviews' / ('%s.auto-revise.json' % Path(args.chapter_file).stem)
        report['report_path'] = str(out)
        write_json(out, report)

    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print_markdown(report)

if __name__ == '__main__':
    main()
````

## File: scripts/build_next_chapter_context.py
size: 5836
sha: c5bf5a0d2ae095d386013e88980e89a029a4fdb1
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/build_next_chapter_context.py

```text
#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path

from novelops_common import (
    CHAPTER_HEADING_RE,
    infer_next_chapter_from_project,
    iso_now,
    limit_chars,
    latest_sections,
    read_text,
    require_project_markers,
)

FILES = [
    'story_bible.md',
    'book_rules.md',
    'outline.md',
    'current_state.md',
    'chapter_summaries.md',
    'pending_hooks.md',
    'character_matrix.md',
    'character_knowledge.md',
    'emotional_arcs.md',
    'subplot_board.md',
    'style_guide.md',
]

def select_outline_excerpt(text, target_chapter, max_chars):
    text = (text or '').strip()
    if not text:
        return ''
    lines = text.splitlines()
    patterns = [
        r'^\s*-\s*ch%s:\s*(.+)$' % target_chapter,
        r'^\s*-\s*chapter\s+%s:\s*(.+)$' % target_chapter,
        r'^\s*-\s*第\s*%s\s*章[:：]\s*(.+)$' % target_chapter,
    ]
    matched_index = None
    for idx, line in enumerate(lines):
        stripped = line.strip()
        if any(re.match(pattern, stripped, flags=re.I) for pattern in patterns):
            matched_index = idx
            break
    if matched_index is None:
        return limit_chars(text, max_chars)

    heading_index = matched_index
    while heading_index > 0:
        if re.match(r'^\s*##\s+', lines[heading_index], flags=re.M):
            break
        heading_index -= 1

    excerpt_lines = []
    if re.match(r'^\s*##\s+', lines[heading_index], flags=re.M):
        excerpt_lines.append(lines[heading_index].rstrip())
    excerpt_lines.append(lines[matched_index].rstrip())
    excerpt = '\n'.join(excerpt_lines).strip()
    return limit_chars(excerpt or text, max_chars)

def build_context_report(project, recent_chapters, max_chars_per_file, chapter=None):
    project = require_project_markers(project)
    target_chapter = infer_next_chapter_from_project(project, chapter)
    sections = {}
    section_meta = {}

    for name in FILES:
        text = read_text(project / name)
        if not text:
            continue
        original_chars = len(text.strip())
        if name == 'chapter_summaries.md':
            text = latest_sections(text, CHAPTER_HEADING_RE, recent_chapters, max_chars=max_chars_per_file)
        elif name == 'outline.md':
            text = select_outline_excerpt(text, target_chapter, max_chars_per_file)
        else:
            text = limit_chars(text, max_chars_per_file)
        sections[name] = text.strip()
        section_meta[name] = {
            'chars': len(sections[name]),
            'truncated': len(sections[name]) < original_chars,
        }

    prompt = []
    prompt.append('# Next Chapter Context')
    prompt.append('')
    prompt.append('Use this context to plan and draft the next chapter. Preserve continuity, character locks, world rules, and hook discipline.')
    prompt.append('')
    prompt.append('Target chapter: %s' % target_chapter)
    prompt.append('')
    for name in FILES:
        if name not in sections:
            continue
        prompt.append('## %s' % name)
        prompt.append(sections[name])
        prompt.append('')

    prompt.append('## Writing instructions')
    prompt.append('- Draft exactly one chapter only: chapter %s.' % target_chapter)
    prompt.append('- State the chapter function before drafting.')
    prompt.append('- Advance at least one active hook unless the chapter is deliberately transitional.')
    prompt.append('- Respect information boundaries: do not let characters know what they should not know.')
    prompt.append('- Do not output chapter %s, chapter %s, or multiple chapter headings in one response.' % (target_chapter + 1, target_chapter + 2))
    prompt.append('- Prefer spot-fixable prose over risky structural overreach.')
    prompt.append('- Stop after the current chapter ends; do not continue into later chapters.')
    prompt.append('- After acceptance, update chapter_summaries, current_state, pending_hooks, and relationship/emotion files.')

    return {
        'schema_version': 'novelops.next-context.v1',
        'tool': 'build_next_chapter_context',
        'generated_at': iso_now(),
        'project': str(project),
        'target_chapter': target_chapter,
        'config': {
            'recent_chapters': recent_chapters,
            'max_chars_per_file': max_chars_per_file,
        },
        'single_chapter_contract': [
            'Draft exactly one chapter only: chapter %s.' % target_chapter,
            'Do not output multiple chapter headings or continue into later chapters.',
            'Stop after the current chapter ends.',
        ],
        'files_loaded': list(sections.keys()),
        'summary': {
            'section_count': len(sections),
            'context_chars': len('\n'.join(prompt).strip()),
        },
        'section_meta': section_meta,
        'sections': sections,
        'context': '\n'.join(prompt).strip() + '\n',
    }

def main():
    parser = argparse.ArgumentParser(description='Build a compact next-chapter context from truth files.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--chapter', type=int)
    parser.add_argument('--recent-chapters', type=int, default=3)
    parser.add_argument('--max-chars-per-file', type=int, default=1800)
    parser.add_argument('--json', action='store_true')
    args = parser.parse_args()

    if args.recent_chapters < 0:
        raise SystemExit('--recent-chapters must be >= 0')
    if args.max_chars_per_file < 0:
        raise SystemExit('--max-chars-per-file must be >= 0')

    report = build_context_report(args.project, args.recent_chapters, args.max_chars_per_file, args.chapter)

    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print(report['context'])

if __name__ == '__main__':
    main()
```

## File: scripts/build_revision_plan.py
size: 7745
sha: 3f6b2b762ae7134b8f544aa67746c9e83cd2f7ec
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/build_revision_plan.py

```text
#!/usr/bin/env python3
import argparse
import json
from pathlib import Path

from audit_chapter import build_report
from novelops_common import iso_now, write_json

SCOPE_BY_DIMENSION = {
    'information-boundary': 'scene',
    'protagonist-lock': 'scene',
    'outline-drift': 'chapter',
    'state-cohesion': 'chapter',
    'timeline-continuity': 'scene',
    'hook-overload': 'planning',
    'hook-advancement': 'planning',
    'state-update-pressure': 'state-files',
    'repetition-fatigue': 'local',
    'report-speak': 'local',
    'crowd-cliche': 'local',
    'paragraph-monotony': 'local',
    'dialogue-balance': 'scene',
    'telling-vs-dramatizing': 'local',
}

STRATEGY_BY_DIMENSION = {
    'information-boundary': 'Patch the leaking line first; verify POV knowledge boundaries before touching prose style.',
    'protagonist-lock': 'Restore the protagonist lock before any style cleanup.',
    'outline-drift': 'Re-state the chapter function and decide whether the scene should be reframed or moved.',
    'state-cohesion': 'Re-anchor the chapter in current pressures, facts, and active conflicts.',
    'timeline-continuity': 'Clarify scene transitions and trim unearned time jumps.',
    'hook-overload': 'Choose one or two hooks to advance explicitly and defer the rest on purpose.',
    'hook-advancement': 'Decide whether the chapter is intentionally transitional; if not, advance at least one active hook.',
    'state-update-pressure': 'Prepare truth-file updates immediately after acceptance to avoid drift.',
    'repetition-fatigue': 'Trim repeated transition words and keep only the strongest beats.',
    'report-speak': 'Replace abstract explanation with concrete action, sensory detail, or dialogue.',
    'crowd-cliche': 'Swap generic crowd reactions for 1-2 specific character beats.',
    'paragraph-monotony': 'Vary paragraph rhythm by splitting heavy blocks or combining thin ones.',
    'dialogue-balance': 'Verify whether silence is intentional; add dialogue only if the scene needs interactive pressure.',
    'telling-vs-dramatizing': 'Convert labeled emotions into observable action, bodily response, or subtext.',
}

def load_audit(project, chapter_file, audit_report):
    if audit_report:
        return json.loads(Path(audit_report).read_text(encoding='utf-8'))
    if not project or not chapter_file:
        raise SystemExit('Either provide --audit-report or both --project and --chapter-file.')
    return build_report(project, chapter_file)

def overall_strategy(report):
    counts = report['summary']['counts']
    if counts['critical']:
        return {
            'mode': 'block-and-patch',
            'reason': 'Critical continuity or knowledge-boundary issues must be repaired before stylistic work.',
        }
    if counts['major'] >= 2:
        return {
            'mode': 'targeted-scene-rewrite',
            'reason': 'Multiple major findings suggest the chapter needs scene-level restructuring, not only line edits.',
        }
    if counts['major'] == 1:
        return {
            'mode': 'targeted-rewrite',
            'reason': 'One major issue exists; repair the structural problem first, then do local cleanup.',
        }
    if counts['minor'] >= 3:
        return {
            'mode': 'spot-fix-pass',
            'reason': 'No major blockers; prioritize a focused local revision pass.',
        }
    return {
        'mode': 'light-pass-or-accept',
        'reason': 'Only low-severity or note-level issues remain.',
    }

def build_actions(report):
    actions = []
    for idx, finding in enumerate(report['findings'], 1):
        dimension = finding['dimension']
        scope = SCOPE_BY_DIMENSION.get(dimension, 'local')
        needs_human = finding['severity'] in ('critical', 'major') or scope in ('scene', 'chapter', 'planning')
        actions.append({
            'action_id': 'REV-%03d' % idx,
            'priority': finding['severity'],
            'rule_id': finding.get('rule_id'),
            'dimension': dimension,
            'target_scope': scope,
            'needs_human_review': needs_human,
            'goal': finding['message'],
            'recommended_strategy': STRATEGY_BY_DIMENSION.get(dimension, 'Apply the smallest safe patch that resolves the finding.'),
            'repair_targets': finding.get('repair_targets', []),
            'evidence': finding.get('evidence', []),
        })
    return actions

def build_plan(project, chapter_file, audit_report):
    report = load_audit(project, chapter_file, audit_report)
    actions = build_actions(report)
    strategy = overall_strategy(report)
    return {
        'schema_version': 'novelops.revision-plan.v1',
        'tool': 'build_revision_plan',
        'generated_at': iso_now(),
        'project': report.get('project'),
        'chapter': report.get('chapter'),
        'chapter_file': report.get('chapter_file') or report.get('chapter'),
        'based_on': {
            'schema_version': report.get('schema_version'),
            'overall': report.get('overall'),
        },
        'overall_strategy': strategy,
        'summary': {
            'action_count': len(actions),
            'human_review_needed': sum(1 for action in actions if action['needs_human_review']),
            'counts': report['summary']['counts'],
        },
        'source_files': report.get('source_files', []),
        'minimal_fix_plan': report.get('minimal_fix_plan', []),
        'actions': actions,
    }

def print_markdown(plan):
    print('# Revision Plan')
    print()
    print('## Overall strategy')
    print('- mode: %s' % plan['overall_strategy']['mode'])
    print('- reason: %s' % plan['overall_strategy']['reason'])
    print()
    print('## Minimal fix plan')
    for item in plan['minimal_fix_plan']:
        print('- %s' % item)
    print()
    print('## Actions')
    if not plan['actions']:
        print('- none')
        return
    for action in plan['actions']:
        print('- [%s/%s] %s' % (action['action_id'], action['rule_id'], action['goal']))
        print('  - scope: %s' % action['target_scope'])
        print('  - strategy: %s' % action['recommended_strategy'])
        print('  - needs_human_review: %s' % ('yes' if action['needs_human_review'] else 'no'))
        if action['repair_targets']:
            print('  - repair_targets: %s' % '; '.join(action['repair_targets']))

def main():
    parser = argparse.ArgumentParser(description='Build a structured revision plan from an audit report.')
    parser.add_argument('--project')
    parser.add_argument('--chapter-file')
    parser.add_argument('--audit-report', help='Existing audit JSON report. If omitted, audit is run on the fly.')
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--write-report', action='store_true')
    args = parser.parse_args()

    plan = build_plan(args.project, args.chapter_file, args.audit_report)

    if args.write_report:
        project_dir = plan.get('project')
        chapter_ref = plan.get('chapter_file') or plan.get('chapter')
        if not project_dir or not chapter_ref:
            raise SystemExit(
                '--write-report requires "project" and "chapter"/"chapter_file" in the audit report; '
                'the provided --audit-report JSON is missing them. '
                'Pass --project/--chapter-file instead, or omit --write-report.')
        chapter_stem = Path(chapter_ref).stem
        out = Path(project_dir) / 'reviews' / ('%s.revision-plan.json' % chapter_stem)
        plan['report_path'] = str(out)
        write_json(out, plan)

    if args.json:
        print(json.dumps(plan, ensure_ascii=False, indent=2))
    else:
        print_markdown(plan)

if __name__ == '__main__':
    main()
```

## File: scripts/build_write_next_packet.py
size: 9731
sha: f6785667bdfd9374c58b4173d046a110f2049d40
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/build_write_next_packet.py

```text
#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path

from build_next_chapter_context import build_context_report
from novelops_common import (
    CHAPTER_HEADING_RE,
    chapter_sections,
    extract_bullets,
    extract_markdown_section,
    infer_next_chapter_from_project,
    iso_now,
    read_text,
    require_project_markers,
    write_json,
)

def infer_next_chapter(project, explicit_chapter=None):
    return infer_next_chapter_from_project(project, explicit_chapter)

def find_outline_target(outline_text, chapter):
    patterns = [
        r'^\s*-\s*ch%s:\s*(.+)$' % chapter,
        r'^\s*-\s*chapter\s+%s:\s*(.+)$' % chapter,
        r'^\s*-\s*第\s*%s\s*章[:：]\s*(.+)$' % chapter,
    ]
    for line in outline_text.splitlines():
        stripped = line.strip()
        for pattern in patterns:
            match = re.match(pattern, stripped, flags=re.I)
            if match:
                return match.group(1).strip()
    return ''

def latest_pov(chapter_summaries):
    sections = chapter_sections(chapter_summaries, CHAPTER_HEADING_RE)
    if not sections:
        return ''
    latest = sections[-1][1]
    match = re.search(r'^-\s*POV:\s*(.+)$', latest, flags=re.M)
    return match.group(1).strip() if match else ''

def active_hooks(pending_hooks_text, limit=5):
    items = []
    for bullet in extract_bullets(pending_hooks_text):
        match = re.match(r'\[(OPEN|ADVANCED)\]\s*(.+?)\s*\((.+)\)$', bullet)
        if not match:
            continue
        items.append({
            'status': match.group(1).lower(),
            'hook': match.group(2).strip(),
            'meta': match.group(3).strip(),
        })
        if len(items) >= limit:
            break
    return items

def book_constraints(book_rules_text, limit=6):
    bullets = extract_bullets(book_rules_text)
    keep = []
    for bullet in bullets:
        if re.search(r'不允许|不得|不要|禁止|must not|do not|constraint|prohibition|lock', bullet, flags=re.I):
            keep.append(bullet)
        if len(keep) >= limit:
            break
    return keep

def immediate_pressure(current_state_text):
    return extract_bullets(extract_markdown_section(current_state_text, 'Immediate next pressure'))

def open_conflicts(current_state_text):
    return extract_bullets(extract_markdown_section(current_state_text, 'Open conflicts'))

def recent_state_targets(chapter_summaries, limit=4):
    sections = chapter_sections(chapter_summaries, CHAPTER_HEADING_RE)
    if not sections:
        return []
    latest = sections[-1][1]
    lines = []
    in_state = False
    for line in latest.splitlines():
        stripped = line.rstrip()
        if re.match(r'^-\s*State changes:', stripped):
            in_state = True
            continue
        if in_state and re.match(r'^-\s+\S', stripped):
            break
        if in_state:
            match = re.match(r'^\s*-\s+(.+)$', stripped)
            if match:
                lines.append(match.group(1).strip())
        if len(lines) >= limit:
            break
    return lines

def build_scene_beats(outline_target, pressure_items, hook_items, conflict_items):
    beats = []
    if outline_target:
        beats.append('开场先服务本章目标：%s' % outline_target)
    if pressure_items:
        beats.append('尽快落地当前压力：%s' % pressure_items[0])
    if hook_items:
        beats.append('明确推进至少一个 active hook：%s' % hook_items[0]['hook'])
    if len(hook_items) >= 2:
        beats.append('保留次级悬念，不要把这条线一次性说透：%s' % hook_items[1]['hook'])
    if conflict_items:
        beats.append('把核心冲突具象化成可见动作或对话，而不是解释：%s' % conflict_items[0])
    return beats[:5]

def chapter_path_hint(project, chapter):
    return str(Path(project) / 'chapters' / ('ch%02d.md' % chapter))

def plan_template(chapter, suggested_pov, primary_goal, beats):
    lines = [
        '# Chapter %s Plan' % chapter,
        '',
        '- POV: %s' % (suggested_pov or '待定'),
        '- Primary goal: %s' % primary_goal,
        '- Planned payoff or partial payoff: ',
        '- State change to land: ',
        '',
        '## Scene Beats',
    ]
    if beats:
        lines.extend(['- %s' % item for item in beats])
    else:
        lines.append('- 待补充')
    return '\n'.join(lines).strip() + '\n'

def single_chapter_contract(chapter):
    return [
        '只输出第 %s 章正文。' % chapter,
        '不要额外输出第 %s 章或更后面的章节。' % (chapter + 1),
        '不要在同一份草稿里写多个章节标题。',
        '当前章节结束后立即停止，不要续写下一章。',
    ]

def build_packet(project, chapter=None, recent_chapters=3, max_chars_per_file=1800):
    project = require_project_markers(project)
    chapter = infer_next_chapter(project, chapter)
    context_report = build_context_report(project, recent_chapters, max_chars_per_file, chapter)

    outline_text = read_text(Path(project) / 'outline.md')
    current_state_text = read_text(Path(project) / 'current_state.md')
    pending_hooks_text = read_text(Path(project) / 'pending_hooks.md')
    chapter_summaries = read_text(Path(project) / 'chapter_summaries.md')
    book_rules_text = read_text(Path(project) / 'book_rules.md')

    outline_target = find_outline_target(outline_text, chapter)
    pressure_items = immediate_pressure(current_state_text)
    hook_items = active_hooks(pending_hooks_text)
    conflict_items = open_conflicts(current_state_text)
    constraints = book_constraints(book_rules_text)
    state_targets = recent_state_targets(chapter_summaries)
    suggested_pov = latest_pov(chapter_summaries)
    beats = build_scene_beats(outline_target, pressure_items, hook_items, conflict_items)

    primary_goal = outline_target or (pressure_items[0] if pressure_items else '推进当前主线并制造可记录的 state change')
    planned_payoff = hook_items[0]['hook'] if hook_items else primary_goal

    return {
        'schema_version': 'novelops.write-next.v1',
        'tool': 'build_write_next_packet',
        'generated_at': iso_now(),
        'project': str(project),
        'chapter': chapter,
        'chapter_file_hint': chapter_path_hint(project, chapter),
        'files_loaded': context_report['files_loaded'],
        'chapter_function': {
            'primary_goal': primary_goal,
            'pressure': pressure_items[:3],
            'planned_payoff_or_partial_payoff': planned_payoff,
        },
        'required_inputs': {
            'suggested_pov': suggested_pov,
            'active_hooks': hook_items,
            'open_conflicts': conflict_items[:4],
            'constraints': constraints,
            'state_targets': state_targets,
        },
        'single_chapter_contract': single_chapter_contract(chapter),
        'suggested_scene_beats': beats,
        'plan_template': plan_template(chapter, suggested_pov, primary_goal, beats),
        'context_packet': context_report,
        'next_actions': [
            '先用 chapter_function 和 suggested_scene_beats 写 1-3 条 chapter plan。',
            '正文必须只写当前目标章节，不要继续写后续章节。',
            '正文完成后按顺序跑 knowledge-check、audit、extract-state、state-update。',
        ],
    }

def print_markdown(packet):
    print('# Write-Next Packet')
    print()
    print('- chapter: %s' % packet['chapter'])
    print('- suggested_pov: %s' % (packet['required_inputs']['suggested_pov'] or 'unspecified'))
    print('- primary_goal: %s' % packet['chapter_function']['primary_goal'])
    print()
    print('## Active Hooks')
    if not packet['required_inputs']['active_hooks']:
        print('- none')
    else:
        for item in packet['required_inputs']['active_hooks']:
            print('- [%s] %s' % (item['status'], item['hook']))
    print()
    print('## Constraints')
    if not packet['required_inputs']['constraints']:
        print('- none')
    else:
        for item in packet['required_inputs']['constraints']:
            print('- %s' % item)
    print()
    print('## Suggested Scene Beats')
    if not packet['suggested_scene_beats']:
        print('- none')
    else:
        for item in packet['suggested_scene_beats']:
            print('- %s' % item)
    print()
    print('## Single Chapter Contract')
    for item in packet['single_chapter_contract']:
        print('- %s' % item)
    print()
    print(packet['context_packet']['context'])

def main():
    parser = argparse.ArgumentParser(description='Build a structured write-next packet for the next chapter.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--chapter', type=int)
    parser.add_argument('--recent-chapters', type=int, default=3)
    parser.add_argument('--max-chars-per-file', type=int, default=1800)
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--write-report', action='store_true')
    args = parser.parse_args()

    if args.recent_chapters < 0:
        raise SystemExit('--recent-chapters must be >= 0')
    if args.max_chars_per_file < 0:
        raise SystemExit('--max-chars-per-file must be >= 0')

    packet = build_packet(args.project, args.chapter, args.recent_chapters, args.max_chars_per_file)
    if args.write_report:
        out = Path(args.project) / 'reviews' / ('ch%02d.write-next.json' % packet['chapter'])
        packet['report_path'] = str(out)
        write_json(out, packet)
    if args.json:
        print(json.dumps(packet, ensure_ascii=False, indent=2))
    else:
        print_markdown(packet)

if __name__ == '__main__':
    main()
```

## File: scripts/diff_story_state.py
size: 5357
sha: 47c9778e41a12be7c2db6206f3db276c65f790e6
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/diff_story_state.py

```text
#!/usr/bin/env python3
import argparse
import difflib
import json
from pathlib import Path

from novelops_common import iso_now, read_text, require_project_markers, snapshot_roots, state_root
from snapshot_story_state import TRACKED_FILES

def is_snapshot_dir(path):
    """快照目录必须含 manifest.json。

    snapshot() 最后才写 manifest，所以它是「快照完整」的标记；只按 is_dir() 判断
    会把中途失败留下的半截目录（缺文件、无 manifest）也当成快照读进来。
    """
    return path.is_dir() and (path / 'manifest.json').is_file()

def resolve_snapshot(project, ref):
    project = Path(project)
    roots = snapshot_roots(project)
    if ref == 'current':
        return {'kind': 'current', 'id': 'current', 'path': project, 'path_str': str(project)}
    if ref == 'latest':
        choices = sorted(
            [p for root in roots for p in root.iterdir() if is_snapshot_dir(p)],
            key=lambda p: p.name,
        )
        if not choices:
            raise SystemExit('No snapshots found under %s' % (state_root(project) / 'snapshots'))
        target = choices[-1]
        return {'kind': 'snapshot', 'id': target.name, 'path': target, 'path_str': str(target)}
    path = Path(ref)
    if is_snapshot_dir(path):
        return {'kind': 'snapshot', 'id': path.name, 'path': path, 'path_str': str(path)}
    for root in roots:
        target = root / ref
        if is_snapshot_dir(target):
            return {'kind': 'snapshot', 'id': target.name, 'path': target, 'path_str': str(target)}
    raise SystemExit('Snapshot ref not found (or incomplete, missing manifest.json): %s' % ref)

def load_file(base, rel):
    """读取快照/项目里的文件，返回 (内容, 是否存在)。

    read_text 对缺失文件返回空串，无法区分「文件被删除」与「文件本来就是空的」，
    会让 diff 的 added/removed 判定失真。
    """
    path = Path(base) / rel
    if not path.is_file():
        return '', False
    return read_text(path), True

def diff_report(project, from_ref, to_ref):
    project = require_project_markers(project)
    left = resolve_snapshot(project, from_ref)
    right = resolve_snapshot(project, to_ref)

    file_diffs = []
    added_total = 0
    removed_total = 0
    changed = 0

    for rel in TRACKED_FILES:
        before, before_present = load_file(left['path'], rel)
        after, after_present = load_file(right['path'], rel)
        if before == after and before_present == after_present:
            continue
        changed += 1
        before_lines = before.splitlines()
        after_lines = after.splitlines()
        udiff = list(difflib.unified_diff(before_lines, after_lines, fromfile='%s:%s' % (left['id'], rel), tofile='%s:%s' % (right['id'], rel), lineterm=''))
        added = sum(1 for line in udiff if line.startswith('+') and not line.startswith('+++'))
        removed = sum(1 for line in udiff if line.startswith('-') and not line.startswith('---'))
        added_total += added
        removed_total += removed
        status = 'changed'
        if not before_present and after_present:
            status = 'added'
        elif before_present and not after_present:
            status = 'removed'
        file_diffs.append({
            'path': rel,
            'status': status,
            'present': {'from': before_present, 'to': after_present},
            'added_lines': added,
            'removed_lines': removed,
            'diff_excerpt': udiff[:80],
        })

    return {
        'schema_version': 'novelops.state-diff.v1',
        'tool': 'diff_story_state',
        'generated_at': iso_now(),
        'project': str(project),
        'from': {'kind': left['kind'], 'id': left['id'], 'path': left['path_str']},
        'to': {'kind': right['kind'], 'id': right['id'], 'path': right['path_str']},
        'summary': {
            'changed_files': changed,
            'added_lines': added_total,
            'removed_lines': removed_total,
        },
        'file_diffs': file_diffs,
    }

def print_markdown(report):
    print('# Story State Diff')
    print()
    print('## Summary')
    print('- from: %s' % report['from']['id'])
    print('- to: %s' % report['to']['id'])
    print('- changed_files: %s' % report['summary']['changed_files'])
    print('- added_lines: %s' % report['summary']['added_lines'])
    print('- removed_lines: %s' % report['summary']['removed_lines'])
    print()
    print('## File diffs')
    if not report['file_diffs']:
        print('- none')
        return
    for item in report['file_diffs']:
        print('- %s (%s, +%s/-%s)' % (item['path'], item['status'], item['added_lines'], item['removed_lines']))

def main():
    parser = argparse.ArgumentParser(description='Diff story-state snapshots or compare a snapshot to current state.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--from', dest='from_ref', required=True)
    parser.add_argument('--to', dest='to_ref', default='current')
    parser.add_argument('--json', action='store_true')
    args = parser.parse_args()

    report = diff_report(args.project, args.from_ref, args.to_ref)
    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print_markdown(report)

if __name__ == '__main__':
    main()
```

## File: scripts/draft_chapter.py
size: 12080
sha: bc067e6a6e1a4cf33c5570b74eab088be02550bb
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/draft_chapter.py

```text
#!/usr/bin/env python3
"""LLM 章节写作执行器：把 write-next 工作包交给 Hermes 等 OpenAI 兼容模型生成单章草稿。

三种模式：
- dry-run：只组装并输出完整请求 payload，不联网、不写盘；
- mock：--mock-response / NOVELOPS_LLM_MOCK 提供响应文件，跳过网络但走完整校验与落盘链路；
- live：真实调用 llm.base_url（默认本地 Ollama）。
"""
import argparse
import json
import re
from pathlib import Path

from build_write_next_packet import build_packet
from llm_client import (
    build_chat_payload,
    chat,
    load_mock_responses,
    resolve_api_key,
    resolve_llm_config,
    resolve_mock_source,
)
from novelops_common import (
    CN_NUMERAL_CHARS,
    atomic_write_text,
    clean_model_output,
    detect_newline,
    iso_now,
    parse_chinese_numeral,
    write_json,
)
from novelops_config import load_project_config

# 注意：末尾不能用 \b——Python 3 的 \w 含中文，`章` 与紧随其后的标题汉字之间不构成
# 词边界，`## 第一章夜雨` 这种最常见的写法会整条漏配，导致单章契约守卫失效。
# 改用 (?![0-9A-Za-z])，只排除「章」后紧跟 ASCII 字母数字的情况。
LOOSE_HEADING_RE = re.compile(
    r'^[ \t]{0,3}(#{1,6}[ \t]*)?(?:第\s*([%s]+)\s*章|Chapter\s+(\d+))(?![0-9A-Za-z])'
    % CN_NUMERAL_CHARS,
    re.M | re.I,
)

# 无 `#` 前缀的行还可能是正文句子（如「第一章的故事就这样结束了。」），用句末标点区分。
SENTENCE_PUNCT_RE = re.compile(r'[。！？；]')

def find_chapter_headings(text):
    """返回文本中所有章节标题的 (行文本, 解析出的编号或 None)。"""
    headings = []
    for match in LOOSE_HEADING_RE.finditer(text):
        end = text.find('\n', match.start())
        line = text[match.start():] if end == -1 else text[match.start():end]
        # 带 # 的按标题信任；不带 # 的必须不含句末标点，避免把正文句子误判成标题。
        if not match.group(1) and SENTENCE_PUNCT_RE.search(line):
            continue
        cn_num, en_num = match.group(2), match.group(3)
        number = None
        if en_num:
            number = int(en_num)
        elif cn_num:
            number = parse_chinese_numeral(cn_num)
        headings.append((line.strip(), number))
    return headings

def build_messages(packet):
    contract_lines = '\n'.join('- %s' % line for line in packet['single_chapter_contract'])
    constraints = packet['required_inputs'].get('constraints') or []
    constraint_lines = '\n'.join('- %s' % line for line in constraints) if constraints else '- （book_rules.md 未提供显式禁令）'
    system = (
        '你是长篇小说的章节写作执行器，唯一任务是写出目标章节的正文。\n\n'
        '必须严格遵守以下单章契约：\n%s\n\n'
        '必须遵守的书籍约束：\n%s\n\n'
        '输出格式要求：第一行输出章节标题 `## 第 %d 章 <可选标题>`，随后直接是正文段落；'
        '不要输出解释、前言、大纲、创作说明或除正文之外的任何附加内容。'
        % (contract_lines, constraint_lines, packet['chapter'])
    )
    function = packet['chapter_function']
    beats = packet.get('suggested_scene_beats') or []
    task_lines = [
        '## 本章写作任务',
        '- 主要目标：%s' % function.get('primary_goal', ''),
        '- 当前压力：%s' % ('；'.join(function.get('pressure') or []) or '（无显式压力项）'),
        '- 本章回报：%s' % (function.get('planned_payoff_or_partial_payoff') or '（按大纲推进）'),
    ]
    if beats:
        task_lines.append('- 建议场景节拍：')
        task_lines.extend('  - %s' % beat for beat in beats)
    user = (
        '%s\n\n---\n\n%s\n\n参考章计划模板（仅供构思，勿输出模板本身）：\n\n%s\n\n'
        '现在只写第 %d 章正文，写完立即停止。'
        % (packet['context_packet']['context'], '\n'.join(task_lines), packet['plan_template'], packet['chapter'])
    )
    return [
        {'role': 'system', 'content': system},
        {'role': 'user', 'content': user},
    ]

def validate_draft(text, chapter):
    """校验并规范化草稿：拒绝空响应与多章输出，缺标题时自动补齐。

    先净化模型输出（剥代码围栏、去开场白），否则模型偶尔加的
    「好的，以下是第 2 章：」会作为正文第一段落盘。
    """
    raw = (text or '').strip()
    text = clean_model_output(raw)
    if not text:
        raise SystemExit('LLM returned an empty draft. 请重试，或检查模型与提示词配置。')
    headings = find_chapter_headings(text)
    warnings = []
    if text != raw:
        warnings.append('已剥离模型附加的代码围栏或开场白。')
    heading_added = False
    if len(headings) > 1:
        raise SystemExit(
            'LLM response contains %d chapter headings (%s); 违反单章契约，草稿已拒绝。'
            '请重试，或调小 llm.max_tokens 以降低模型越章概率。'
            % (len(headings), ' / '.join(h[0] for h in headings[:4])))
    if not headings:
        text = '## 第 %d 章\n\n%s' % (chapter, text)
        heading_added = True
    else:
        number = headings[0][1]
        if number is not None and number != chapter:
            warnings.append(
                'Draft heading declares chapter %s but the target is chapter %s; kept as-is.' % (number, chapter))
    normalized = text.replace('\r\n', '\n').replace('\r', '\n').rstrip() + '\n'
    return normalized, {
        'heading_count': len(headings),
        'heading_added': heading_added,
        'sanitized': text != raw,
        'warnings': warnings,
    }

def build_draft(project, chapter=None, out=None, force=False, dry_run=False, mock_path=None,
                llm_overrides=None, recent_chapters=3, max_chars_per_file=1800):
    packet = build_packet(project, chapter=chapter, recent_chapters=recent_chapters,
                          max_chars_per_file=max_chars_per_file)
    target_chapter = packet['chapter']
    target_file = Path(out) if out else Path(packet['chapter_file_hint'])

    project_config = load_project_config(project)
    llm_config = resolve_llm_config(project_config, llm_overrides)
    api_key, api_key_source = resolve_api_key(llm_config)
    llm_info = {
        'provider': llm_config['provider'],
        'base_url': llm_config['base_url'],
        'model': llm_config['model'],
        'temperature': llm_config['temperature'],
        'top_p': llm_config['top_p'],
        'max_tokens': llm_config['max_tokens'],
        'api_key': None,
        'api_key_present': api_key is not None,
        'api_key_source': api_key_source,
    }

    messages = build_messages(packet)
    report = {
        'schema_version': 'novelops.draft.v1',
        'tool': 'draft_chapter',
        'generated_at': iso_now(),
        'project': packet['project'],
        'chapter': target_chapter,
        'chapter_file': str(target_file),
        'mode': 'dry-run',
        'llm': llm_info,
        'request': None,
        'response': None,
        'validation': None,
        'write': {'written': False, 'chapter_file': str(target_file), 'forced': bool(force)},
        'next_actions': [
            '对草稿依次跑 revise / knowledge-check / audit',
            '接受后跑 extract-state 与 state-update',
        ],
    }

    if dry_run:
        report['request'] = {'payload': build_chat_payload(messages, llm_config)}
        return report

    if target_file.exists() and not force:
        raise SystemExit('Draft target already exists: %s. Use --force to overwrite.' % target_file)

    mock_source = resolve_mock_source(mock_path)
    if mock_source:
        mock_responses = load_mock_responses(mock_source)
        # 空 JSON 数组会在这里直接炸 IndexError（非 SystemExit，不会被上层友好处理）
        if not mock_responses:
            raise SystemExit('Mock response file contains an empty list: %s' % mock_source)
        mock_content = mock_responses[0]
    else:
        mock_content = None
    result = chat(messages, llm_config, mock_content=mock_content)

    normalized, validation = validate_draft(result['content'], target_chapter)

    report['mode'] = 'mock' if result['transport'] == 'mock' else 'live'
    report['request'] = {
        'message_count': len(messages),
        'system_chars': len(messages[0]['content']),
        'user_chars': len(messages[1]['content']),
    }
    report['response'] = {
        'raw_chars': len(result['raw_content'] or ''),
        'content_chars': len(normalized),
        'think_stripped': result['raw_content'] != result['content'],
        'usage': result['usage'],
        'model': result['model'],
    }
    report['validation'] = validation

    # 原子写：write_text 会先截断目标文件，中途失败会留下半截章节。
    # 目标已存在（--force）时沿用其换行风格，避免整文件行尾被翻转。
    newline = detect_newline(target_file) if target_file.exists() else '\n'
    atomic_write_text(target_file, normalized.replace('\n', newline))
    report['write'] = {'written': True, 'chapter_file': str(target_file), 'forced': bool(force)}
    return report

def print_markdown(report):
    print('# Draft Chapter')
    print()
    print('- mode: %s' % report['mode'])
    print('- chapter: %s' % report['chapter'])
    print('- chapter_file: %s' % report['chapter_file'])
    print('- written: %s' % ('yes' if report['write']['written'] else 'no'))
    if report.get('validation'):
        print('- heading_added: %s' % ('yes' if report['validation']['heading_added'] else 'no'))
        for warning in report['validation']['warnings']:
            print('- warning: %s' % warning)
    print()
    print('## Next actions')
    for item in report['next_actions']:
        print('- %s' % item)

def main():
    parser = argparse.ArgumentParser(description='Draft the next chapter with an OpenAI-compatible LLM (Hermes-first).')
    parser.add_argument('--project', required=True)
    parser.add_argument('--chapter', type=int)
    parser.add_argument('--out')
    parser.add_argument('--force', action='store_true')
    parser.add_argument('--dry-run', action='store_true', help='Print the chat payload without calling the LLM.')
    parser.add_argument('--mock-response', help='File whose content is used as the LLM response (offline).')
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--write-report', action='store_true')
    parser.add_argument('--model')
    parser.add_argument('--base-url')
    parser.add_argument('--temperature', type=float)
    parser.add_argument('--top-p', type=float, dest='top_p')
    parser.add_argument('--max-tokens', type=int, dest='max_tokens')
    parser.add_argument('--timeout', type=int, dest='timeout_seconds')
    parser.add_argument('--recent-chapters', type=int, default=3)
    parser.add_argument('--max-chars-per-file', type=int, default=1800)
    args = parser.parse_args()

    llm_overrides = {
        'model': args.model,
        'base_url': args.base_url,
        'temperature': args.temperature,
        'top_p': args.top_p,
        'max_tokens': args.max_tokens,
        'timeout_seconds': args.timeout_seconds,
    }

    report = build_draft(
        args.project,
        chapter=args.chapter,
        out=args.out,
        force=args.force,
        dry_run=args.dry_run,
        mock_path=args.mock_response,
        llm_overrides=llm_overrides,
        recent_chapters=args.recent_chapters,
        max_chars_per_file=args.max_chars_per_file,
    )

    if args.write_report:
        reviews = Path(args.project) / 'reviews'
        out = reviews / ('ch%02d.draft.json' % report['chapter'])
        report['report_path'] = str(out)
        write_json(out, report)

    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print_markdown(report)

if __name__ == '__main__':
    main()
```

## File: scripts/extract_state.py
size: 6150
sha: 07f2608b48c286ba1b1958560b749f40f05155df
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/extract_state.py

```text
#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path

from novelops_common import iso_now, parse_chapter_number, read_text, require_existing_file, require_project_markers, split_sentences

SUMMARY_HINTS = ['怀疑', '确认', '发现', '决定', '暴露', '受伤', '失去', '拿到']
RELATION_HINTS = ['信任', '怀疑', '敌意', '合作', '试探', '关系']
EMOTION_HINTS = ['愤怒', '恐惧', '警觉', '怀疑', '悲伤', '羞耻', 'anger', 'fear', 'suspicion']
HOOK_HINTS = ['谁', '为何', '为什么', '如何', '秘密', '真相', '幕后', '替换', '去向']
STATE_HINTS = ['确认', '发现', '决定', '知道', '拿到', '失去', '暴露', '受伤', '怀疑', '异常', '不该', '开始', '察觉']

def guess_title(chapter_text, chapter_file):
    for line in chapter_text.splitlines():
        line = line.strip()
        if re.match(r'^#\s+', line):
            return re.sub(r'^#\s+', '', line).strip()
    return Path(chapter_file).stem

def pick_summary(sentences):
    """挑一句作为本章摘要。

    原实现只在前 12 句里打分，长章节真正的转折常在第 12 句之后，摘要于是
    永远取自开头。改为全文打分：关键词命中数优先，其次长度，同分取靠前的那句。
    """
    if not sentences:
        return ''
    best_score = None
    best_sentence = sentences[0]
    for sentence in sentences:
        score = sum(1 for hint in SUMMARY_HINTS if hint in sentence)
        score += min(len(sentence), 120) / 120.0
        if best_score is None or score > best_score:
            best_score = score
            best_sentence = sentence
    return best_sentence

def dedupe_keep_order(items, limit=None):
    out = []
    seen = set()
    for item in items:
        item = item.strip()
        if not item or item in seen:
            continue
        seen.add(item)
        out.append(item)
        if limit and len(out) >= limit:
            break
    return out

def extract_candidates(sentences):
    state_changes = []
    hooks = []
    relationships = []
    emotions = []

    for sentence in sentences:
        if any(hint in sentence for hint in STATE_HINTS):
            state_changes.append(sentence)
        if any(hint in sentence for hint in RELATION_HINTS):
            relationships.append(sentence)
        if any(hint in sentence for hint in EMOTION_HINTS):
            emotions.append(sentence)
        if any(hint in sentence for hint in HOOK_HINTS) and ('？' in sentence or '?' in sentence or '谁' in sentence or '为何' in sentence or '为什么' in sentence):
            hooks.append(sentence.rstrip('。！？!?'))

    hook_open = []
    hook_advance = []
    hook_close = []
    for hook in hooks:
        if any(token in hook for token in ['真相就是', '终于知道', '原来是']):
            hook_close.append(hook)
        elif any(token in hook for token in ['怀疑', '线索', '似乎', '也许']):
            hook_advance.append(hook)
        else:
            hook_open.append(hook)

    return {
        'state_changes': dedupe_keep_order(state_changes, limit=5),
        'hook_open': dedupe_keep_order(hook_open, limit=4),
        'hook_advance': dedupe_keep_order(hook_advance, limit=4),
        'hook_close': dedupe_keep_order(hook_close, limit=4),
        'relationships': dedupe_keep_order(relationships, limit=4),
        'emotions': dedupe_keep_order(emotions, limit=4),
    }

def build_report_from_text(chapter_text, chapter_file='', chapter_num=None, project=None, title_guess_value=None):
    sentences = split_sentences(chapter_text)
    candidates = extract_candidates(sentences)
    guessed_title = title_guess_value or guess_title(chapter_text, chapter_file or 'chapter')
    inferred_chapter = chapter_num
    if inferred_chapter is None:
        inferred_chapter = parse_chapter_number(Path(chapter_file).stem) if chapter_file else None
    if inferred_chapter is None:
        inferred_chapter = parse_chapter_number(chapter_text) or None
    return {
        'schema_version': 'novelops.extract-state.v1',
        'tool': 'extract_state',
        'generated_at': iso_now(),
        'project': str(project) if project is not None else '',
        'chapter': inferred_chapter,
        'chapter_file': str(chapter_file) if chapter_file else '',
        'title_guess': guessed_title,
        'summary': pick_summary(sentences),
        'state_changes': candidates['state_changes'],
        'hook_open': candidates['hook_open'],
        'hook_advance': candidates['hook_advance'],
        'hook_close': candidates['hook_close'],
        'relationships': candidates['relationships'],
        'emotions': candidates['emotions'],
        'write_mode': 'candidate-only',
    }

def build_report(project, chapter_file):
    project = require_project_markers(project)
    chapter_file = require_existing_file(chapter_file, 'Chapter file')
    chapter_text = read_text(chapter_file)
    return build_report_from_text(chapter_text, chapter_file=str(chapter_file), project=project)

def print_markdown(report):
    print('# Extracted State Candidates')
    print()
    print('- title_guess: %s' % report['title_guess'])
    print('- summary: %s' % report['summary'])
    print('- write_mode: %s' % report['write_mode'])
    print()
    for key in ['state_changes', 'hook_open', 'hook_advance', 'hook_close', 'relationships', 'emotions']:
        print('## %s' % key)
        if not report[key]:
            print('- none')
        else:
            for item in report[key]:
                print('- %s' % item)
        print()

def main():
    parser = argparse.ArgumentParser(description='Extract candidate story-state updates from a chapter draft.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--chapter-file', required=True)
    parser.add_argument('--json', action='store_true')
    args = parser.parse_args()

    report = build_report(args.project, args.chapter_file)
    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print_markdown(report)

if __name__ == '__main__':
    main()
```

## File: scripts/hook_report.py
size: 4479
sha: a184ae3617ab90ad021719d636bd917123a9f362
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/hook_report.py

```text
#!/usr/bin/env python3
import argparse
import json
import re
from collections import Counter

from novelops_common import (
    CHAPTER_HEADING_RE,
    iso_now,
    parse_chapter_number,
    read_text,
    require_project_markers,
)

STATUS_ALIASES = {
    'OPEN': 'OPEN',
    'ADVANCED': 'ADVANCED',
    'PAID OFF': 'PAID_OFF',
    'PAID_OFF': 'PAID_OFF',
    'DEFERRED': 'DEFERRED',
    'BROKEN': 'BROKEN',
}

STATUS_ORDER = ['OPEN', 'ADVANCED', 'PAID_OFF', 'DEFERRED', 'BROKEN']

def parse_line(line):
    match = re.match(r'^-\s*\[([^\]]+)\]\s*(.+)$', line.strip())
    if not match:
        return None
    raw_status = match.group(1).strip().upper()
    status = STATUS_ALIASES.get(raw_status)
    if not status:
        return None
    rest = match.group(2).strip()
    chapter_match = re.search(r'\b(?:opened|updated|closed)\s*:\s*ch\s*(\d+)\b', rest, flags=re.I)
    text = re.sub(r'\([^\)]*\)', '', rest).strip()
    return {
        'status': status,
        'hook': text,
        'chapter': int(chapter_match.group(1)) if chapter_match else None,
        'raw': line.strip(),
    }

def fallback_open_hooks(text):
    hooks = []
    for line in text.splitlines():
        line = line.strip()
        if not line.startswith('- '):
            continue
        hooks.append({'status': 'OPEN', 'hook': line[2:].strip(), 'chapter': None, 'raw': line})
    return hooks

def load_hooks(project):
    text = read_text(project / 'pending_hooks.md')
    parsed = [item for item in (parse_line(line) for line in text.splitlines()) if item]
    if parsed:
        return parsed
    return fallback_open_hooks(text)

def latest_chapter_seen(project):
    """最新章号；复用共享解析器以支持中文数字（「第十二章」）。"""
    text = read_text(project / 'chapter_summaries.md')
    chapters = [number for number in
                (parse_chapter_number(match.group(0))
                 for match in re.finditer(CHAPTER_HEADING_RE, text, flags=re.M))
                if number is not None]
    return max(chapters) if chapters else 0

def build_report(project, stale_after):
    project = require_project_markers(project)
    stale_after = int(stale_after)
    if stale_after < 0:
        raise SystemExit('--stale-after must be >= 0')
    hooks = load_hooks(project)
    counts = Counter(item['status'] for item in hooks)
    current_chapter = latest_chapter_seen(project)
    stale_hooks = []
    for item in hooks:
        if item['status'] != 'OPEN':
            continue
        if item['chapter'] is None:
            continue
        age = max(0, current_chapter - item['chapter'])
        if age >= stale_after:
            stale_hooks.append({
                'hook': item['hook'],
                'opened_in': item['chapter'],
                'age_chapters': age,
                'status': item['status'],
            })
    stale_hooks.sort(key=lambda x: (-x['age_chapters'], x['hook']))
    return {
        'schema_version': 'novelops.hook-report.v1',
        'tool': 'hook_report',
        'generated_at': iso_now(),
        'project': str(project),
        'config': {'stale_after': stale_after},
        'summary': {
            'hook_count': len(hooks),
            'counts': {status.lower(): counts.get(status, 0) for status in STATUS_ORDER},
            'current_chapter': current_chapter,
            'stale_hook_count': len(stale_hooks),
        },
        'hooks': hooks,
        'stale_hooks': stale_hooks,
    }

def print_markdown(report):
    print('# Hook Report')
    print()
    print('## Counts')
    for key, value in report['summary']['counts'].items():
        print('- %s: %s' % (key, value))
    print()
    print('## Stale hooks')
    if not report['stale_hooks']:
        print('- none')
    else:
        for item in report['stale_hooks']:
            print('- [%s] %s (opened: ch%s, age: %s)' % (item['status'], item['hook'], item['opened_in'], item['age_chapters']))

def main():
    parser = argparse.ArgumentParser(description='Summarize hook lifecycle status from pending_hooks.md.')
    parser.add_argument('--project', required=True)
    parser.add_argument('--stale-after', type=int, default=5)
    parser.add_argument('--json', action='store_true')
    args = parser.parse_args()

    report = build_report(args.project, args.stale_after)
    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print_markdown(report)

if __name__ == '__main__':
    main()
```

## File: scripts/init_novel_project.sh
size: 1611
sha: 3e82aa4c39683028ac67a1606c0aeb348305e18f
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/init_novel_project.sh

```text
#!/usr/bin/env bash
set -euo pipefail

if [[ $# -lt 2 || $# -gt 3 ]]; then
  echo "Usage: $0 <project-dir> <book-title> [--force]"
  exit 1
fi

PROJECT_DIR="$1"
BOOK_TITLE="$2"
FORCE="${3:-}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
TEMPLATE_DIR="$SKILL_DIR/assets/project-template"

if [[ -n "$FORCE" && "$FORCE" != "--force" ]]; then
  echo "Unknown option: $FORCE" >&2
  echo "Usage: $0 <project-dir> <book-title> [--force]" >&2
  exit 1
fi

if [[ -e "$PROJECT_DIR" && ! -d "$PROJECT_DIR" ]]; then
  echo "Init target exists but is not a directory: $PROJECT_DIR" >&2
  exit 1
fi

if [[ -d "$PROJECT_DIR" && "$FORCE" != "--force" ]]; then
  if [[ -n "$(find "$PROJECT_DIR" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then
    echo "Refusing to initialize non-empty directory: $PROJECT_DIR. Use --force to overwrite template files." >&2
    exit 1
  fi
fi

mkdir -p "$PROJECT_DIR"
cp -r "$TEMPLATE_DIR"/. "$PROJECT_DIR"/
mkdir -p "$PROJECT_DIR/chapters" "$PROJECT_DIR/reviews"

ESCAPED_TITLE="${BOOK_TITLE//\\/\\\\}"
ESCAPED_TITLE="${ESCAPED_TITLE//&/\\&}"
ESCAPED_TITLE="${ESCAPED_TITLE//\//\\/}"

sed -i "s/{{BOOK_TITLE}}/${ESCAPED_TITLE}/g" "$PROJECT_DIR"/README-project.md
sed -i "s/{{BOOK_TITLE}}/${ESCAPED_TITLE}/g" "$PROJECT_DIR"/story_bible.md
sed -i "s/{{BOOK_TITLE}}/${ESCAPED_TITLE}/g" "$PROJECT_DIR"/book_rules.md
sed -i "s/{{BOOK_TITLE}}/${ESCAPED_TITLE}/g" "$PROJECT_DIR"/outline.md
sed -i "s/{{BOOK_TITLE}}/${ESCAPED_TITLE}/g" "$PROJECT_DIR"/current_state.md

echo "Initialized novel project at: $PROJECT_DIR"
echo "Title: $BOOK_TITLE"
```

## File: scripts/inkos_cli.py
size: 164
sha: 97115c900564b124230a8157270e626f9c25cbb5
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/inkos_cli.py

```text
#!/usr/bin/env python3
"""Backward-compatible wrapper for the renamed NovelOps Skill CLI."""

from novelops_cli import main

if __name__ == '__main__':
    main()
```

## File: scripts/inkos_common.py
size: 169
sha: ff8af5ff8b75bd89f05ead2ca2b346cf889dde26
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/inkos_common.py

```text
#!/usr/bin/env python3
"""Backward-compatible wrapper for the renamed NovelOps shared helpers; use novelops_common."""

from novelops_common import *  # noqa: F401,F403
```

## File: scripts/knowledge_check.py
size: 13452
sha: 04c46ac69e08ecb92469fce28ff547aa1d79fb92
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/knowledge_check.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/knowledge_check.py

## File: scripts/llm_client.py
size: 8274
sha: 48c2c5802de89b8f9e84586bedfeba8855689f65
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/llm_client.py

```text
#!/usr/bin/env python3
"""OpenAI 兼容 chat completions 传输层（纯标准库）。

面向 Nous Hermes 系列模型：默认接本地 Ollama，Nous Portal 云端改 base_url + api_key 即可。
只负责配置解析、请求组包、HTTP 调用、<think> 推理块剥离与 mock 通道；
不包含任何业务提示词——那是 draft_chapter / auto_revise 的职责。
"""
import json
import os
import re
import socket
import urllib.error
import urllib.request
from pathlib import Path

from novelops_common import read_text

DEFAULT_LLM_CONFIG = {
    'provider': 'ollama',
    'base_url': 'http://localhost:11434/v1',
    'model': 'hermes4',
    'api_key': None,
    'api_key_env': 'NOVELOPS_LLM_API_KEY',
    'temperature': 0.6,
    'top_p': 0.95,
    'max_tokens': 4096,
    'timeout_seconds': 300,
    'strip_think': True,
}

MOCK_ENV_VAR = 'NOVELOPS_LLM_MOCK'

THINK_BLOCK_RE = re.compile(r'<think>.*?</think>\s*', re.S | re.I)

def resolve_llm_config(project_config, overrides=None):
    """DEFAULT 拷贝 → 项目配置 llm 节覆盖 → CLI overrides（仅非 None 键）覆盖。

    未知键一律 SystemExit，防拼写静默失效。
    """
    resolved = dict(DEFAULT_LLM_CONFIG)
    llm_section = (project_config or {}).get('llm') or {}
    for source_name, source in (('novelops.config.json llm section', llm_section), ('llm overrides', overrides or {})):
        for key, value in source.items():
            if key not in DEFAULT_LLM_CONFIG:
                raise SystemExit(
                    '%s has unknown key %r (known: %s)'
                    % (source_name, key, ', '.join(sorted(DEFAULT_LLM_CONFIG))))
            # None 一律视为「未设置」并跳过：配置文件里写 `"temperature": null`
            # 会把默认值覆盖成 None，请求体里就会出现 "temperature": null。
            if value is None:
                continue
            resolved[key] = value
    return resolved

def resolve_api_key(llm_config):
    """返回 (key_or_None, source)，source 为 'env' | 'config' | None；环境变量优先。"""
    env_name = llm_config.get('api_key_env')
    if env_name and os.environ.get(env_name):
        return os.environ[env_name], 'env'
    if llm_config.get('api_key'):
        return llm_config['api_key'], 'config'
    return None, None

def build_chat_payload(messages, llm_config):
    """组装 chat completions 请求体；dry-run 输出与真实请求共用此函数。"""
    return {
        'model': llm_config['model'],
        'messages': messages,
        'temperature': llm_config['temperature'],
        'top_p': llm_config['top_p'],
        'max_tokens': llm_config['max_tokens'],
        'stream': False,
    }

def strip_think_blocks(text):
    """剥离 Hermes 混合推理的 <think>...</think> 块。

    三种形态：闭合块直接剥除；只残留 </think>（模型偶发省略起始标签）时取最后一个
    闭合标签之后的内容；剥离后仍有未闭合 <think> 说明响应大概率被截断，直接报错。
    """
    text = text or ''
    stripped = THINK_BLOCK_RE.sub('', text)
    if '<think>' not in stripped.lower() and '</think>' in stripped.lower():
        lower = stripped.lower()
        stripped = stripped[lower.rindex('</think>') + len('</think>'):]
    if '<think>' in stripped.lower():
        raise SystemExit(
            'LLM response contains an unclosed <think> block; the response was likely truncated. '
            '请调大 novelops.config.json 的 llm.max_tokens 后重试。')
    return stripped.strip()

def resolve_mock_source(cli_mock_path):
    """--mock-response 优先，其次环境变量 NOVELOPS_LLM_MOCK；都没有返回 None。"""
    if cli_mock_path:
        return cli_mock_path
    return os.environ.get(MOCK_ENV_VAR) or None

def load_mock_responses(path):
    """读取 mock 文件为 assistant 响应列表。

    JSON 数组 → 逐项（字符串或 OpenAI 响应对象均可）；
    含 choices 的 JSON 对象 → 取 choices[0].message.content；
    其他 → 整个文件文本作为单条响应。
    """
    path = Path(path)
    if not path.is_file():
        raise SystemExit('Mock response file does not exist: %s' % path)
    raw = read_text(path)

    def unwrap(item):
        if isinstance(item, str):
            return item
        if isinstance(item, dict):
            try:
                return item['choices'][0]['message']['content']
            except (KeyError, IndexError, TypeError):
                raise SystemExit(
                    'Mock response object in %s is not an OpenAI chat completion '
                    '(missing choices[0].message.content)' % path)
        raise SystemExit('Mock response items in %s must be strings or OpenAI response objects' % path)

    try:
        data = json.loads(raw)
    except ValueError:
        return [raw]
    if isinstance(data, list):
        return [unwrap(item) for item in data]
    if isinstance(data, dict) and 'choices' in data:
        return [unwrap(data)]
    return [raw]

def _http_chat(payload, llm_config):
    url = llm_config['base_url'].rstrip('/') + '/chat/completions'
    headers = {'Content-Type': 'application/json'}
    api_key, _source = resolve_api_key(llm_config)
    if api_key:
        headers['Authorization'] = 'Bearer %s' % api_key
    request = urllib.request.Request(
        url,
        data=json.dumps(payload, ensure_ascii=False).encode('utf-8'),
        headers=headers,
        method='POST',
    )
    try:
        with urllib.request.urlopen(request, timeout=llm_config['timeout_seconds']) as response:
            body = response.read().decode('utf-8', errors='replace')
    except urllib.error.HTTPError as exc:
        body = ''
        try:
            body = exc.read().decode('utf-8', errors='replace')
        except Exception:
            pass
        message = 'LLM HTTP %s from %s: %s' % (exc.code, url, body[:500])
        if exc.code in (401, 403):
            message += ' 请检查 api_key 或环境变量 %s。' % llm_config.get('api_key_env')
        raise SystemExit(message)
    except (socket.timeout, TimeoutError):
        raise SystemExit(
            'LLM request timed out after %ss: %s. 可调大 novelops.config.json 的 llm.timeout_seconds。'
            % (llm_config['timeout_seconds'], url))
    except urllib.error.URLError as exc:
        if isinstance(getattr(exc, 'reason', None), (socket.timeout, TimeoutError)):
            raise SystemExit(
                'LLM request timed out after %ss: %s. 可调大 novelops.config.json 的 llm.timeout_seconds。'
                % (llm_config['timeout_seconds'], url))
        raise SystemExit(
            'LLM request failed: cannot connect to %s. 请确认 Ollama 已启动（ollama serve），'
            '或检查 novelops.config.json 的 llm.base_url。原始错误：%s' % (url, exc.reason))
    try:
        data = json.loads(body)
    except ValueError:
        raise SystemExit('LLM response is not valid JSON from %s: %s' % (url, body[:200]))
    try:
        content = data['choices'][0]['message']['content']
    except (KeyError, IndexError, TypeError):
        raise SystemExit('LLM response missing choices[0].message.content from %s' % url)
    return content, data.get('model'), data.get('usage')

def chat(messages, llm_config, mock_content=None):
    """执行一次 chat completion（或 mock 短路），返回统一结果结构。

    返回：{'content'(按 strip_think 配置剥离), 'raw_content', 'model', 'usage', 'transport'}。
    dry-run 不属于本函数——调用方在调用前用 build_chat_payload 组包即可。
    """
    if mock_content is not None:
        raw_content = mock_content
        model = llm_config['model']
        usage = None
        transport = 'mock'
    else:
        payload = build_chat_payload(messages, llm_config)
        raw_content, model, usage = _http_chat(payload, llm_config)
        transport = 'http'
    content = strip_think_blocks(raw_content) if llm_config.get('strip_think', True) else (raw_content or '').strip()
    return {
        'content': content,
        'raw_content': raw_content,
        'model': model or llm_config['model'],
        'usage': usage,
        'transport': transport,
    }
```

## File: scripts/novelops_cli.py
size: 17371
sha: 530c1cf026bc30b1a1c7d6bf3bbabc3ccd7dea9b
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/novelops_cli.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/novelops_cli.py

## File: scripts/novelops_common.py
size: 13151
sha: 4e1eb051c41d4de05b43bea6752f8a4ebd9e7741
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/novelops_common.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/novelops_common.py

## File: scripts/novelops_config.py
size: 4096
sha: a9f95200ea238491679b93049d7b2cfc821e3b4b
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/novelops_config.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/novelops_config.py

## File: scripts/package_skill.py
size: 4410
sha: 65d6b3d08b9ac473bf2792340803a00dbbbf685c
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/package_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/package_skill.py

## File: scripts/package_skill.sh
size: 1230
sha: c149c117db513bec8e89e9f14b49dd4d190cc673
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/package_skill.sh

```text
#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SKILL_NAME="novelops-skill"
OUTDIR="${1:-$(cd "$ROOT/../.." && pwd)/dist}"
VERSION_SUFFIX="${2:-}"
VERSION_FILE="$ROOT/VERSION"
TMPDIR="$(mktemp -d)"
cleanup() {
  rm -rf "$TMPDIR"
}
trap cleanup EXIT

normalize_tag() {
  local tag="$1"
  tag="${tag//$'\r'/}"
  tag="${tag//$'\n'/}"
  if [[ -n "$tag" && "$tag" != v* ]]; then
    tag="v$tag"
  fi
  printf '%s' "$tag"
}

if [[ -z "$VERSION_SUFFIX" && -f "$VERSION_FILE" ]]; then
  VERSION_SUFFIX="$(cat "$VERSION_FILE")"
fi
VERSION_SUFFIX="$(normalize_tag "$VERSION_SUFFIX")"

mkdir -p "$OUTDIR"
STAGE="$TMPDIR/$SKILL_NAME"
mkdir -p "$STAGE"
cp -R "$ROOT/." "$STAGE/"
find "$STAGE" -type d -name '__pycache__' -prune -exec rm -rf {} +
find "$STAGE" -type f \( -name '*.pyc' -o -name '.DS_Store' \) -delete
rm -rf "$STAGE/.git"

OUTFILE="$OUTDIR/$SKILL_NAME.skill"
rm -f "$OUTFILE"
(
  cd "$TMPDIR"
  zip -qr "$OUTFILE" "$SKILL_NAME" -x '*/.git/*' '*/__pycache__/*' '*/node_modules/*'
)
echo "$OUTFILE"

if [[ -n "$VERSION_SUFFIX" ]]; then
  VERSIONED_OUTFILE="$OUTDIR/$SKILL_NAME-$VERSION_SUFFIX.skill"
  rm -f "$VERSIONED_OUTFILE"
  cp "$OUTFILE" "$VERSIONED_OUTFILE"
  echo "$VERSIONED_OUTFILE"
fi
```

## File: scripts/reverse_long_document.py
size: 12181
sha: 556a2f27c8523e7ba0bb2ab29cd98e34a0edbfc0
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/reverse_long_document.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/reverse_long_document.py

## File: scripts/run_revision_cycle.py
size: 5140
sha: bf6ab645fc0a48aa03bb336d1c85345dd04933c3
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/run_revision_cycle.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/run_revision_cycle.py

## File: scripts/smoke_test.py
size: 53140
sha: 3281b390cd92bbba3f386b23ea4f51f057ccbeb8
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/smoke_test.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/smoke_test.py

## File: scripts/smoke_test.sh
size: 16114
sha: 9bad1f5c1a7bf2badeef2a142fe3777a64ac303e
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/smoke_test.sh

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/smoke_test.sh

## File: scripts/snapshot_story_state.py
size: 4427
sha: 61172ed0b1b9e5a843e3f9da3c308ffe46d09a18
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/snapshot_story_state.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/snapshot_story_state.py

## File: scripts/suggest_spot_fixes.py
size: 5623
sha: 2188a9aea1644b24303423677bdde0084b3e3ac6
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/suggest_spot_fixes.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/suggest_spot_fixes.py

## File: scripts/update_story_state.py
size: 7477
sha: 970039c1512fcb6c838f1c2743f46fb2b805752b
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/update_story_state.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/scripts/update_story_state.py

## File: references/audit-dimensions.md
size: 5039
sha: 9a9001997856c85b5230a77418a97ef5e276ac76
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/audit-dimensions.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/audit-dimensions.md

## File: references/audit-rules.md
size: 1436
sha: 849af9d33c02c1b18dd6d4751aa0078e473ef854
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/audit-rules.md

```text
# Audit Rules

当前 `audit_chapter.py` 使用的是“启发式但结构化”的规则集。

## 规则列表

- `AUD-101` repetition-fatigue
  - 重复转场词过多
- `AUD-102` report-speak
  - 解释腔 / 报告腔过强
- `AUD-103` crowd-cliche
  - 群体反应陈词滥调
- `AUD-104` paragraph-monotony
  - 段落长度过于平均
- `AUD-105` hook-overload
  - 开放 hook 过多但章节体量有限
- `AUD-106` hook-advancement
  - 章节似乎没有触碰当前开放 hook
- `AUD-107` outline-drift
  - 与当前大纲关键词联系太弱
- `AUD-108` state-cohesion
  - 与 `current_state.md` 的当前有效状态联系太弱
- `AUD-109` protagonist-lock
  - 可能触犯主角锁 / 禁区
- `AUD-110` information-boundary
  - POV / 角色认知边界可能泄漏
- `AUD-111` timeline-continuity
  - 紧凑章节内时间跳跃过多
- `AUD-112` dialogue-balance
  - 长章节没有对话，需确认是否故意
- `AUD-113` telling-vs-dramatizing
  - 直接情绪标签过多
- `AUD-114` state-update-pressure
  - 章节内状态转折很多，提醒接受后更新 truth files

## 设计意图

这些规则不是为了“自动判死刑”，而是为了：

- 先发现高风险问题
- 再优先修最小代价的问题
- 最后决定是否需要重写场景或章节

## 使用建议

- `critical`：优先拦下
- `major`：默认需要修
- `minor`：默认 spot-fix
- `note`：作为提醒，不一定必须改
```

## File: references/canon-side-story.md
size: 1211
sha: d22ea68c04d2faa2cf8b1abc555b9c76e7ae7fd6
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/canon-side-story.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/canon-side-story.md

## File: references/file-schemas.md
size: 2961
sha: 13afea15decd555d0aee5b11ce384a0532f68928
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/file-schemas.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/file-schemas.md

## File: references/json-schemas.md
size: 12796
sha: 21354a3291de06d667e9334626b2ed418c269324
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/json-schemas.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/json-schemas.md

## File: references/revision-workflow.md
size: 1403
sha: b4844ed2b9bc1ac0fbe31208ed068769a3cf0cb4
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/revision-workflow.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/revision-workflow.md

## File: references/style-learning.md
size: 1049
sha: 5ad86e3379bb26bad39875f2421fe66d6f060a63
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/style-learning.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/style-learning.md

## File: references/worked-examples.md
size: 5231
sha: e4dba0eefcc245c0716fb5aaa9f56289b51693f0
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/worked-examples.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/worked-examples.md

## File: references/workflow-playbooks.md
size: 2358
sha: 08ba94a2cbbda9f5d00fce95cdaf1612ef47565c
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/workflow-playbooks.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/references/workflow-playbooks.md

## File: assets/project-template/.gitignore
size: 169
sha: e5077038ab15bbef9563fddbe55e99a9f4f19840
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/.gitignore

```text
# 流水线生成的运行时状态：快照与章节备份会随写作不断累积，
# 属于本地工作产物，不该进版本库。
.novelops-state/
.inkos-state/
```

## File: assets/project-template/book_rules.md
size: 279
sha: faca71228d58a152aaa1d485157e80b6d5dd26a6
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/book_rules.md

```text
# Book Rules — {{BOOK_TITLE}}

## Protagonist lock
- personality:
- default response under pressure:
- moral floor / ceiling:

## Behavioral constraints
- 

## Prohibitions
- 

## Tone goals
- 

## Pacing rules
- 

## Genre-specific taboos
- 

## Canon / spoiler boundaries
- 
```

## File: assets/project-template/chapter_summaries.md
size: 187
sha: 002a7183460b5282ddd29519558c52f5b27898c5
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/chapter_summaries.md

```text
# Chapter Summaries

## Chapter 1 - Example
- POV:
- Summary:
- Key events:
- State changes:
- Hooks opened:
- Hooks advanced:
- Hooks closed:
- New facts:
- Character knowledge changes:
```

## File: assets/project-template/character_knowledge.md
size: 189
sha: 4961037bd33337d966e1789fded4e34d49d3ca07
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/character_knowledge.md

```text
# Character Knowledge

## Major characters

### 主角名
- knows:
- suspects:
- does not know:
- wrong beliefs:

### 关键配角名
- knows:
- suspects:
- does not know:
- wrong beliefs:
```

## File: assets/project-template/character_matrix.md
size: 19
sha: ca0a80a38597398718ba45f77fcd237bb3e5a49d
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/character_matrix.md

```text
# Character Matrix
```

## File: assets/project-template/continuity_issues.md
size: 20
sha: 8c1f56138202d4a13f8c3a8da6a15de706ff12cb
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/continuity_issues.md

```text
# Continuity Issues
```

## File: assets/project-template/current_state.md
size: 234
sha: bd516a45ec9be39bf7b7ed6485d75168b2a204ed
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/current_state.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/current_state.md

## File: assets/project-template/emotional_arcs.md
size: 17
sha: fab0779bc76233bfdc4ab4c0f9f37c5b8821b6cf
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/emotional_arcs.md

```text
# Emotional Arcs
```

## File: assets/project-template/novelops.config.json
size: 373
sha: 886a43995074d7902abc9cad285752dd1e2e53d1
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/novelops.config.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/novelops.config.json

## File: assets/project-template/outline.md
size: 203
sha: 2fb7b3c33bd70949eac14ea647b301dae8b2fe9d
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/outline.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/outline.md

## File: assets/project-template/pending_hooks.md
size: 281
sha: 4acd34a86f0f8a85fe27cbc39b6f5f73b39b1973
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/pending_hooks.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/pending_hooks.md

## File: assets/project-template/README-project.md
size: 502
sha: 70b9cdda2289d6277a0c64a5c54da214efd373c3
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/README-project.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/README-project.md

## File: assets/project-template/story_bible.md
size: 197
sha: a2302e28d46e8cd46d4e4ae530774a5963002a75
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/story_bible.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/story_bible.md

## File: assets/project-template/style_guide.md
size: 121
sha: 005e5472c46fc0b10fa16175f648ad8dc3e2fd4f
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/style_guide.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/style_guide.md

## File: assets/project-template/style_profile.json
size: 190
sha: 26e3d4cb7fd8a1575b8590a631e17c20b3388d78
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/style_profile.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/style_profile.json

## File: assets/project-template/subplot_board.md
size: 16
sha: 546e71c28207f5f4f5333caaab9c9506582a7420
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/assets/project-template/subplot_board.md

```text
# Subplot Board
```

## File: .github/ISSUE_TEMPLATE/bug_report.md
size: 570
sha: e5dbc94bca464ab981a9023c0f424f7ba88ec361
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/ISSUE_TEMPLATE/bug_report.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/ISSUE_TEMPLATE/bug_report.md

## File: .github/ISSUE_TEMPLATE/feature_request.md
size: 720
sha: bd3d9938f0f719ab0ea20df2684f4bcfcec43e4a
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/ISSUE_TEMPLATE/feature_request.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/ISSUE_TEMPLATE/feature_request.md

## File: .github/PULL_REQUEST_TEMPLATE.md
size: 558
sha: aa354752eb1c42c908fd8124108efc554f6aae1c
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/PULL_REQUEST_TEMPLATE.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/PULL_REQUEST_TEMPLATE.md

## File: .github/workflows/ci.yml
size: 858
sha: 2c79aff1c92c21d858d7fc85ae282fb0b69f259c
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/workflows/ci.yml

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/.github/workflows/ci.yml

## File: .gitignore
size: 113
sha: 4c010ffa6d167582d23b0d72f731112485bc1a55
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/.gitignore

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/.gitignore

## File: AGENTS.md
size: 335
sha: 0c95d523baf5b163ea08808ba8baef5d4e572856
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/AGENTS.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/AGENTS.md

## File: CHANGELOG.md
size: 14398
sha: d7d86097d0a04196108bef612dd93bc5abe28fdc
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/CHANGELOG.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/CHANGELOG.md

## File: CODE_OF_CONDUCT.md
size: 1365
sha: d030f6d876c127aade8b6fd46aed5f9087a83a00
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/CODE_OF_CONDUCT.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/CODE_OF_CONDUCT.md

## File: CONTRIBUTING.md
size: 2219
sha: 170e04f27baa58698e5276675095e7e6091345b3
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/CONTRIBUTING.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/CONTRIBUTING.md

## File: docs/agent-integration.md
size: 3961
sha: 68ded988c725221709200c9611f48c731ea97cc3
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/agent-integration.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/agent-integration.md

## File: docs/audit-fixes.md
size: 14486
sha: 9592f2401ffef4b87d546bb01025f8d4c9c0b52b
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/audit-fixes.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/audit-fixes.md

## File: docs/cli.md
size: 7090
sha: 10f8804764231fb8f3770e74a20829ce55c3e639
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/cli.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/cli.md

## File: docs/faq.md
size: 1873
sha: a8a7b5d984485fd3dca5f4054a52e7883d62d108
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/faq.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/faq.md

## File: docs/getting-started.md
size: 2929
sha: 7c91463e70d8923496a8d1d381a1010bf1edaaa1
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/getting-started.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/getting-started.md

## File: docs/installation.md
size: 1735
sha: f50f0648fa4d49cd732f63ab6a9636799a3a3618
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/installation.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/installation.md

## File: docs/llm-drafting.md
size: 4230
sha: 12b3dba07c2f28b76cae8c1c4283004128bad589
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/llm-drafting.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/llm-drafting.md

## File: docs/project-template.md
size: 2493
sha: 947e284b1a23b711be9a1dfb94f90b2f89d62bac
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/project-template.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/project-template.md

## File: docs/user-paths.md
size: 2173
sha: 6b0d7c380d5e3b12fa9678d44b68935923407a58
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/user-paths.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/docs/user-paths.md

## File: examples/demo-novel/book_rules.md
size: 756
sha: 2dc6391ff214f990b29adeb05c1fca48824bedfc
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/book_rules.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/book_rules.md

## File: examples/demo-novel/chapter_summaries.md
size: 1530
sha: a5ba53bb525e75a19b822a7c22dcfd0ef6fbb967
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/chapter_summaries.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/chapter_summaries.md

## File: examples/demo-novel/chapters/ch01.md
size: 3216
sha: 2d2cfd418f3c280d7008a2327c762e32d9a2dee7
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/chapters/ch01.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/chapters/ch01.md

## File: examples/demo-novel/chapters/ch02.md
size: 3891
sha: ea77b29c0d4af1d106fce83561625d3000927dd0
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/chapters/ch02.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/chapters/ch02.md

## File: examples/demo-novel/character_knowledge.md
size: 534
sha: a82320deea67c52da88bf7a089bd44956b6d14eb
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/character_knowledge.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/character_knowledge.md

## File: examples/demo-novel/character_matrix.md
size: 184
sha: 9cd39035cc28e2826ae423af652753acc274c09c
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/character_matrix.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/character_matrix.md

## File: examples/demo-novel/continuity_issues.md
size: 135
sha: 44994eee1a74e780155e864f682fd7eb8261f150
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/continuity_issues.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/continuity_issues.md

## File: examples/demo-novel/current_state.md
size: 968
sha: 447cb7a77149292cc21cf66767d9b762fff97ae1
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/current_state.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/current_state.md

## File: examples/demo-novel/emotional_arcs.md
size: 156
sha: 0365ccbbf84067917111b68572797094f0eb374a
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/emotional_arcs.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/emotional_arcs.md

## File: examples/demo-novel/outline.md
size: 581
sha: 36a7faf4febb6a568634a171fc2c5604222c9cd8
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/outline.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/outline.md

## File: examples/demo-novel/pending_hooks.md
size: 445
sha: cd3bdc97c5e26269affe15fc69207321ad9a0179
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/pending_hooks.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/pending_hooks.md

## File: examples/demo-novel/README-project.md
size: 419
sha: b207ca75a79001b52e0f340b4db4e9988f74e678
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/README-project.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/README-project.md

## File: examples/demo-novel/story_bible.md
size: 772
sha: ae557bc01a4e007184af6024a7d71eb7b9c845f5
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/story_bible.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/story_bible.md

## File: examples/demo-novel/style_guide.md
size: 639
sha: 9f6c5457d84de239498260d864328cb351500084
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/style_guide.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/style_guide.md

## File: examples/demo-novel/style_profile.json
size: 311
sha: a9f274ba385a3ff9934bb2b21e67dd6df4299f8a
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/style_profile.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/style_profile.json

## File: examples/demo-novel/subplot_board.md
size: 186
sha: f00acc29801fd8ccc4fb20c692d12d83bdf0c22d
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/subplot_board.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/examples/demo-novel/subplot_board.md

## File: LICENSE
size: 1069
sha: 7d3ab8fb06f41434d2a341c36e68dcdf0a5adfbd
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/LICENSE

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/LICENSE

## File: README.en.md
size: 6609
sha: 962137f518e24df53775f2dd08bf7e44c05fa898
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/README.en.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/README.en.md

## File: SECURITY.md
size: 1195
sha: 31f0029b12a096a8503604c4442a5bbc517fe7d8
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/SECURITY.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/qiyan233/novelops-skill/blob/HEAD/SECURITY.md

## File: VERSION
size: 6
sha: 9084fa2f716a7117829f3f32a5f4cef400e02903
upstream: https://github.com/qiyan233/novelops-skill/blob/HEAD/VERSION

```text
1.1.0
```
