🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@double-codeing/flow2spec

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@double-codeing/flow2spec - npm Package Compare versions

Comparing version
3.0.14
to
3.0.15
+49
docs/.mermaid-cache.json
{
"设计说明.md": [
{
"content": "graph TB\n subgraph MC[\"Memory Coding · 仓内四环\"]\n KR[\"知识环 .Knowledge/\"]\n TR[\"任务环 .task/\"]\n RR[\"规则环 rules\"]\n SR[\"技能环 f2s-*\"]\n end\n SR -->|\"维护 ↑\"| KR\n RR -->|\"读与做 ↓\"| KR\n TR -.->|\"并列,不在 .Knowledge 内\"| KR",
"hash": "fae76e2801d0",
"marker": "MERMAID_fae76e2801d0"
},
{
"content": "graph TB\n subgraph H[\"横读 · 渐进式收窄\"]\n L0[\"L0 manifest-routing\"]\n L1[\"L1 matchers 分片\"]\n L2[\"L2 topics 摘要\"]\n L3[\"L3 stock-docs / req-docs\"]\n L0 --> L1 --> L2 --> L3\n end\n subgraph V[\"纵链 · topicDependencies\"]\n T1[\"通用约定\"]\n T2[\"子域边界\"]\n T3[\"端上白名单\"]\n T4[\"本域细则\"]\n T1 --> T2 --> T3 --> T4\n end\n L2 --- V",
"hash": "2c3581e0ec89",
"marker": "MERMAID_2c3581e0ec89"
},
{
"content": "graph LR\n subgraph K[\".Knowledge/ 知识层\"]\n K1[架构说明]\n K2[技术方案]\n K3[路由索引]\n end\n\n subgraph R[\"配置根 执行层\"]\n R1[.cursor/rules/]\n R2[.claude/rules/]\n R3[.codex/AGENTS.md]\n end\n\n K -->|知识输入| AI[AI 工具]\n R -->|规则约束| AI\n\n note1[\"知识随项目迭代\"] -.-> K\n note2[\"规则随工具升级\"] -.-> R",
"hash": "048f705f3b6a",
"marker": "MERMAID_048f705f3b6a"
},
{
"content": "graph LR\n T[任务] --> M[manifest-routing\\n读路由表]\n M -->|关键词匹配| MT[matchers/xxx.json\\n只读这一个分片]\n MT -->|命中| TP[topics/xxx.md]\n TP --> V{缺口检查}\n V -->|通过| ACT[执行]\n V -->|不足| Q[向用户澄清]\n M -->|未命中| FB[fallback-triage\\n结构化分诊]",
"hash": "a24148e2b009",
"marker": "MERMAID_a24148e2b009"
},
{
"content": "graph LR\n K[\".Knowledge/\"] --> AI[\"下次会话\\n的 AI\"]\n AI --> C[\"功能迭代\"]\n\n C -->|\"修复 Bug\"| FIX[\"f2s-kb-fix\"] --> K\n C -->|\"新增能力\"| FEAT[\"f2s-kb-feat\"] --> K\n C -->|\"会话结束\"| SYNC[\"f2s-kb-sync\"] --> K\n C -->|\"提交代码\"| CMT[\"f2s-git-commit\\n收口检查\"]\n CMT -->|\"未入库则提醒\\n-> kb-sync/kb-feat\"| K\n\n D1[\"架构文档\"] -->|f2s-doc-arch| FIN[\"f2s-doc-final\"]\n D2[\"PDF/初稿\"] -->|f2s-doc-final| FIN\n FIN --> CTX[\"f2s-ctx-build\"] --> K\n\n OLD[\"存量代码/文档\"] -->|f2s-doc-add| K\n\n NR[\"新需求\"] --> CL[\"f2s-req-clarify\"] --> BE[\"f2s-req-backend\"]\n BE --> IMPL[\"实现xxx技术方案\"] -->|自动触发implement-tech-design规则| K\n\n GIT[\"Git 合并后\"] -->|f2s-kb-merge| K",
"hash": "6335fa6eda40",
"marker": "MERMAID_6335fa6eda40"
},
{
"content": "graph LR\n SKILL[\"f2s-kb-feat / f2s-kb-fix\\nimplement-tech-design\"] -->|\"changeTracking: true\"| TJ[\".task/active/\\ntask.md · todo.json\"]\n RP[\"f2s-req-plan\\n(始终创建)\"] --> TJ\n\n TJ --> NS[新会话首条消息]\n NS -->|关键词匹配| LD[\"加载剩余 checklist\\n+ linkedSkill 上下文\"]\n LD --> RS[按原技能约束继续]",
"hash": "954431299027",
"marker": "MERMAID_954431299027"
},
{
"content": "graph TD\n F[进入 fallback-triage] --> S1{路由是否命中?}\n S1 -->|已命中但上下文不足| EXP[展开依赖主题\\n补齐后继续]\n S1 -->|未命中| Q[询问用户:\\n这个领域文档是否已录入?]\n Q -->|是| HINT[路由词条缺失\\n建议补路由]\n Q -->|否| CHOICE[下钻源码\\n或补充 req-docs]\n Q -->|不确定| STOP[停止执行\\n等待明确指令]",
"hash": "4318b3c68d8d",
"marker": "MERMAID_4318b3c68d8d"
},
{
"content": "graph LR\n S1[步骤1: 素材汇总] -->|subAgent=true 可并行| SUB[子 agent]\n SUB -->|只读,不落盘| S2\n\n S2[步骤2: 输出大纲\\n用户确认] -->|必须主 agent| USER[用户]\n USER -->|确认| S3\n\n S3[步骤3: 落盘] -->|subAgent=true 可并行| SUB2[子 agent]",
"hash": "a2564dc94095",
"marker": "MERMAID_a2564dc94095"
},
{
"content": "graph LR\n T[触发 f2s-kb-sync] --> O[输出更新大纲]\n O --> U{用户确认}\n U -->|确认| W[写入 .Knowledge/]\n U -->|修改| O\n U -->|取消| STOP[不写入]",
"hash": "07d348a75406",
"marker": "MERMAID_07d348a75406"
}
]
}
{
"Flow2Spec-设计说明.md": {
"hash": ""
},
"体系与原理.md": {
"dedup_reuse": true,
"doc_token": "MJ3ddOEadoSalLxup2tctXC3nSh",
"hash": "36d6d00cae030bf24d8b669471ae4c27333ab0a3f59f73871b87ea271c35f112",
"last_sync": "2026-05-21T11:32:28",
"node_token": "JPX7wpAUxilS43kP31XclcJfnYb",
"space_id": "7516389318031998979",
"title": "体系与原理"
},
"使用案例-模拟对话.md": {
"doc_token": "PtAyd2CPloSUjcxZu5Rco7ylnRd",
"hash": "35fe556b103e683f1fcf15de79a68d775430c0fb9ebe456b8e1d326e8b3371c0",
"last_sync": "2026-05-21T11:31:57",
"node_token": "BzpzwlXVIiiJjNkqjDBcVVmGngu",
"space_id": "7516389318031998979",
"title": "Flow2Spec 使用案例(模拟对话)",
"url": "https://trip.larkenterprise.com/docx/PtAyd2CPloSUjcxZu5Rco7ylnRd"
},
"使用说明.md": {
"doc_token": "ULCudGycqo8G7gx6Jm9cxaD8nPf",
"hash": "8b627acc009e0405785f400bb6a9f250fdf93ffcd15a992c22bb5b4cc52d90e2",
"last_sync": "2026-05-21T11:32:24",
"node_token": "XpLYw8SCri3zzskG9Xhc3Ir1nsf",
"space_id": "7516389318031998979",
"title": "Flow2Spec 使用说明",
"url": "https://trip.larkenterprise.com/docx/ULCudGycqo8G7gx6Jm9cxaD8nPf"
},
"命令说明.md": {
"doc_token": "SfrGd4Fj2odWvsxj944cINqQnWh",
"hash": "7498e8d5b551db305dd1fa348044f66ffcdde77372f0ab963e6163e022a15186",
"last_sync": "2026-05-21T11:32:40",
"node_token": "AyE5wuPhoi4pPMkqxLgc4v53nfb",
"space_id": "7516389318031998979",
"title": "工作流与技能说明",
"url": "https://trip.larkenterprise.com/docx/SfrGd4Fj2odWvsxj944cINqQnWh"
},
"目录与路径约定.md": {
"dedup_reuse": true,
"doc_token": "KPebdJeyKoxFxLx66lgcmvVNnkc",
"hash": "c4fcff4abf8290910840a6448e5b49793be47c9e37a7b0d737095f0942444812",
"last_sync": "2026-05-21T11:32:44",
"node_token": "FNaCwSIGNiye0wkp9mEc76ohn1g",
"space_id": "7516389318031998979",
"title": "目录与路径约定"
},
"设计说明.md": {
"doc_token": "DSD8duoqwoIb2XxsspKcKirinjg",
"hash": "440310cf3c35a80b4ba21ce15d6e7d07e754169ab1fa2de92756362a10b12f6e",
"last_sync": "2026-05-21T11:32:09",
"node_token": "SsZJwXuNyiGPcBk4ftdcIrIhnwb",
"space_id": "7516389318031998979",
"title": "Flow2Spec 设计说明",
"url": "https://trip.larkenterprise.com/docx/DSD8duoqwoIb2XxsspKcKirinjg"
}
}
[中文](../体系与原理.md) | [English](./architecture.md)
# Architecture & Principles
Flow2Spec separates "business knowledge curation" from "Agent capability loading", and uses **Memory Coding** to persist "what must be remembered" as versioned Git assets.
- **Knowledge ring** (`.Knowledge/`): documents and machine-readable routing (multi-layer, see below)
- **Task ring** (`.task/`): cross-session task checklists
- **Rules ring** (tool `rules` / `AGENTS.md`): how to **read** and **act**
- **Skills ring** (`f2s-*`): maintain knowledge and trigger workflows
> Flow2Spec is not "just a knowledge base." All four rings are Memory Coding; the two-layer table below is the **knowledge ring vs tool-side execution** lifecycle split.
---
## 1. Memory Coding and Four Rings
**Memory Coding**: encode durable context into the **committed repo**—not private model memory, not chat-only repetition, not whole-repo vector guessing.
Four rings in the repo (do not collapse rules + skills into a single "third ring"):
| Ring | Location | Stores |
| --- | --- | --- |
| **Knowledge** | `.Knowledge/` | Routing, topics, stock/req docs (§2 layers) |
| **Task** | `.task/` | `todo.json`, checklists, user todos |
| **Rules** | `.cursor/.claude/.codex` rules, `AGENTS.md` | Read order, gap gates, execution constraints |
| **Skills** | config root `skills/*/SKILL.md` | `f2s-kb-feat/fix/sync`, etc. |
---
## 2. Multi-Layer Memory Inside the Knowledge Ring
`.Knowledge/` is not a flat pile of Markdown. It combines **horizontal narrowing** (progressive routing) and **vertical chaining** (topic dependencies):
| Layer | Path / mechanism | Stores | Typical read |
| --- | --- | --- | --- |
| **L0 routing** | `manifest-routing.json` | task→topic, `topicDependencies`, `topicPaths` | First read (machine source of truth) |
| **L1 matcher shard** | `matchers/<id>.json` | `includeAny` triggers | **match**: one shard only |
| **L2 topic summary** | `topics/<topic>.md` | Hard constraints, boundaries, pointers | **expand**: pull dependency topics |
| **L3 long docs** | `stock-docs/`, `req-docs/` | Architecture finals, tech specs | Drill down on demand |
| **Vertical chain** | `topicDependencies` | Common → subdomain → whitelist → domain rules | **expand** stacks layers |
The pipeline `match → expand → verify → act` operates on L0–L2 (and L3 when needed). Topic-level dependencies are declared once and shared by all tasks.
`index.md` is human navigation only; it does not replace the machine-readable chain.
---
## 3. Knowledge Layer vs Execution Layer (Two Layers)
| Layer | Location | Role |
| --- | --- | --- |
| Knowledge layer (knowledge ring) | `.Knowledge/` | Business docs, index, routing (§2 layers) |
| Execution layer (rules + skills rings) | `.cursor/.claude/.codex` | Rules and skill entry points |
---
## 4. Progressive Reading
The recommended unified order:
1. `.Knowledge/manifest-routing.json`
2. `.Knowledge/matchers/<matcher>.json` (on demand: directly located by `manifest-routing.taskToTopicRules[].matcherPath`)
3. `.Knowledge/index.md`
4. The matched `stock-docs` / `req-docs` documents
5. Source code drill-down when necessary
After reading, execute the four-step pipeline `match -> expand -> verify -> act`: expand dependency topics after hitting the primary candidate, perform gap analysis, execute only when confidence is sufficient; clarify first when confidence is low.
Simultaneously, loading behavior is governed by the config root entry points (Flow2Spec package rules: `f2s-flow2spec-unified-entry.mdc` / `f2s-flow2spec-unified-entry.md`; legacy business repos commonly use `main.md(c)`; and `AGENTS.md`).
Codex does not read the `rules/` directory; execution constraints are carried through `.codex/AGENTS.md` + `skills/`.
---
## 5. Key Chains
- Documentation curation chain: `f2s-doc-arch` -> `f2s-doc-final` -> `f2s-ctx-build`
- Implementation chain: `.Knowledge/req-docs/*.md` -> `implement-tech-design` -> code
- Maintenance chain: `f2s-kb-fix` / `f2s-kb-feat` / `f2s-kb-sync` / `f2s-kb-merge`
- Requirements planning chain: `f2s-req-plan` (planning + implementation, always creates task checklist)
- Change tracking chain: `changeTracking.*` config -> `f2s-task` rules (automatic) -> `.task/` task checklist -> cross-session continuation
- Package template/routing shape alignment with config root: `f2s-kb-upgrade` (**do not** equate running `flow2spec init` alone with "knowledge base upgrade"); migrate legacy repo structure into `.Knowledge`: `f2s-kb-migrate`
---
## 6. Agent Execution Model
Flow2Spec controls execution behavior through two fields in the project root `flow2spec.config.json`: `subAgent` and `switchAgentVerification`.
**How the Agent reads the above truth values**: multi-end prompts + **Read** as authority, see [usage-guide.md § 1 (the only detailed table)](./usage-guide.md); design summary see [design-principles.md § 4, 5.1](./design-principles.md).
### 6.1 Primary/Sub Agent Responsibility Division Principle
**`subAgent: false` (default)**: All `f2s-*` skills execute sequentially within the primary agent, no parallel decomposition.
**`subAgent: true`**: When the scale threshold agreed upon in the skill body is reached, sub-agents may be spawned for parallel processing. Responsibility boundaries are as follows:
| Role | Responsibility Boundary |
|------|----------|
| Primary agent | Overall planning, determining task granularity and allocation strategy, aggregating sub-agent output, verifying cross-unit consistency, final write-to-disk |
| Sub agent | Processes the assigned unit (module/document/topic), outputs results in the agreed format, does not make cross-unit decisions |
The decomposition boundaries for sub-agents are progressively defined by each `f2s-*` skill body (e.g., thresholds for module count, document count, code line count). **There is currently no unified stage table at the template layer**; the skill body takes precedence.
### 6.2 Verification Ownership Principle
**Default (whoever writes to disk verifies)**: Verification after write-to-disk or changes is performed within the agent that wrote to disk. If a sub-agent wrote, the sub-agent self-verifies; if the primary agent wrote, the primary agent self-verifies.
**Cross-verification (`switchAgentVerification: true`)**: The counterpart agent bears the verification responsibility, suitable for scenarios requiring higher confidence. The enabling conditions must be **satisfied simultaneously**:
1. Configuration `switchAgentVerification: true`
2. The currently executing `f2s-*` skill body **explicitly states** that the step depends on this field
Cross-verification rules:
| Writer | Verifier | Prerequisite |
|--------|--------|----------|
| Sub-agent writes | Primary agent verifies | No additional conditions |
| Primary agent writes | Sub-agent verifies | Requires `subAgent: true` and that sub-tasks have actually been decomposed; otherwise, the primary agent self-verifies |
Design intent: Cross-verification introduces an external perspective, reducing the blind spots in the writer's self-verification, but increases execution overhead. It is therefore an explicit opt-in rather than the default behavior.
### 6.3 Change Tracking (changeTracking)
`changeTracking` is a third dimension independent of `subAgent` / `switchAgentVerification`. It controls whether the skill automatically creates a task checklist that can be continued across sessions during execution.
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
- Each skill sub-item is independently controlled and does not affect each other
- When enabled: automatically checks `.task/todo.json` before skill execution, creates or resumes tasks; automatically archives upon completion
- Cross-session: when a new session describes related content, the `f2s-task` rule (`alwaysApply`) loads the remaining checklist and corresponding skill context after keyword matching
- `f2s-req-plan` is not constrained by this configuration and always creates a task checklist
---
## 7. Design Benefits
1. Share the same business knowledge source across tools
2. Does not break the rule loading conventions of Claude/Cursor/Codex
3. Controls task routing and dependencies via `manifest-routing` + `matcherPath` shards (`matchers/*.json`), reducing misreading and full scans
4. Clear primary/sub-agent responsibility boundaries: the primary agent always holds the global view, sub-agents focus on unit processing, consistency is ensured by the primary agent
5. Configurable verification ownership: default self-verification by the writer keeps overhead low; cross-verification can be enabled on demand to boost confidence in critical scenarios
---
## 8. Related Documents
- [Usage Guide](./usage-guide.md)
- [Commands Reference](./commands-reference.md)
- [Directory Conventions](./directory-conventions.md)
- [Usage Scenarios](./usage-scenarios.md)
[中文](../命令说明.md) | [English](./commands-reference.md)
# Workflow and Skill Reference
## 1) Document Curation (stock-docs Pipeline)
### `f2s-doc-arch`
**Purpose**: Generates an architecture overview draft based on user descriptions or code scanning. No fixed format required; it should clearly describe the system structure, module relationships, and key decisions.
**How It Works**: Centered on inventory-driven scanning: the main agent first produces a module inventory and a scan contract (which entry points to read, which dimensions to focus on), then performs read-only code scanning according to that inventory, and finally aggregates the results into a human-readable architecture draft persisted under `stock-docs/`. The flow does not change code; it is one-way "code → document" extraction only.
**Use Cases**:
- A new project needs architecture documentation
- An existing project needs architecture descriptions supplemented
- Architecture descriptions need updating after a system refactor
**Relationships**:
- **Prerequisite**: None
- **Next Step**: `f2s-doc-final` (normalized final draft) or direct use with `f2s-ctx-build`
- **Output**: `.Knowledge/stock-docs/<Architecture Overview>_draft.md`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent scans the code and generates the output
- `subAgent: true`: Defaults to **B Mode** (main agent produces inventory + scan contract, sub-agents do parallel read-only table scans, main agent merges and persists); upgraded to **C Mode** (multi-round correction) when any of the following conditions are met: multi-workspace / monorepo, more than 20 source paths, first-round sub-tables have conflicts or gaps, or multi-source narratives have severe contradictions
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Produces inventory (entry points + core module names) and scan contract, aggregates sub-agent deliverables, persists stock-docs draft |
| Sub-Agent (B/C Mode) | Performs parallel read-only scans per the main agent's written inventory, delivers in a unified YAML schema (`source / scope / cross_refs / pending`), must not self-crop the scope |
---
### `f2s-doc-final`
**Purpose**: Converts PDF technical proposals or draft documents into the standardized "Final Draft Template" format, unifying the document structure for subsequent knowledge base ingestion.
**How It Works**: Unstructured or heterogeneous documents (PDF/drafts) are normalized against the built-in final-draft template: core concept tables, business rules, key flows, configuration, error handling, and other standard sections are extracted; missing section markers are filled in; the output is a consistently structured `_final.md`. The final draft is the standard input for `f2s-ctx-build`, keeping knowledge-base entry structure uniform.
**Use Cases**:
- PDF technical proposals need conversion to Markdown
- Draft documents need normalization for long-term storage
- External documents need to be incorporated into Flow2Spec management
**Relationships**:
- **Prerequisite**: PDF document or draft document
- **Next Step**: `f2s-ctx-build` (final draft imported into the knowledge base)
- **Output**: `.Knowledge/stock-docs/<Document>_final.md`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the full workflow
- `subAgent: true`: When the PDF exceeds 50 pages or 5MB, sub-agents may be used for template application and layout drafting; sub-agents must not ask the user questions, write process descriptions, or claim final-draft compliance; the main agent identifies format gaps and accepts the finalized draft
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Identifies format gaps, accepts the finalized draft against the template and clarification document |
| Sub-Agent | Applies templates and produces layout drafts; does not ask users questions or write process descriptions |
---
### `f2s-ctx-build`
**Purpose**: Synchronizes documents from `stock-docs/` (architecture, final drafts) into the knowledge base routing system, generating/updating topic files, the index, manifest-routing, and matchers.
**How It Works**: Starting from a final-draft document, it runs a three-step "document → routing" mapping: (1) extract capability topics and keywords from the draft; (2) generate `topics/<topic>.md` (routing summary with execution boundaries and next-step pointers) and `matchers/<id>.json` (machine-readable `includeAny` terms); (3) register task→topic rules in `manifest-routing.json` and update the human-readable `index.md`. After that, the task routing engine can hit the topic via keywords.
**Use Cases**:
- After a final draft is complete, the knowledge base needs to "know about" these documents
- A new business domain needs routing mappings established
- Document content has been updated and the knowledge base index needs to be synced
**Relationships**:
- **Prerequisite**: `f2s-doc-arch`, `f2s-doc-final`, or a directly authored final draft
- **Next Step**: None (ready for use once imported into the knowledge base)
- **Input**: `.Knowledge/stock-docs/*.md`
- **Output**:
- `.Knowledge/topics/<topic>.md`
- `.Knowledge/index.md`
- `.Knowledge/manifest-routing.json`
- `.Knowledge/matchers/*.json`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent processes each document sequentially
- `subAgent: true`: Enabled when changes exceed thresholds (more than 2 topics added/modified OR more than 1 matcher added OR cross-topic bulk reference adjustments); sub-agent A writes only to `topics/`, sub-agent B writes only to `matchers/`; the main agent handles single-point edits to `manifest-routing.json` and `index.md`; sub-agents must not cross boundaries
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Single-point persist of `manifest-routing.json` and `index.md`, overall acceptance |
| Sub-Agent (topics) | Writes only topic files under `topics/`, does not touch manifest or index |
| Sub-Agent (matchers) | Writes only shard files under `matchers/`, does not touch manifest or index |
---
### `f2s-doc-add`
**Purpose**: Parses already-implemented capabilities (aggregated from multiple files) into the knowledge base. Suitable when code already exists but lacks documentation, or when multiple documents need to be imported into the knowledge base in a unified manner.
**How It Works**: Aggregates capability descriptions from multiple scattered sources (code, config, loose docs) and runs the full "draft → final draft → topics/index/manifest" pipeline. Unlike `f2s-ctx-build`, the input differs: `ctx-build` is driven from a single existing final draft; `doc-add` aggregates many scattered sources first, then follows the same pipeline. It closes the gap of "implementation exists but documentation does not."
**Use Cases**:
- Existing code needs knowledge base documentation
- Multiple related documents need aggregated import
- Bulk import of third-party documents
**Relationships**:
- **Prerequisite**: None (can be triggered directly)
- **Next Step**: None (ends once imported into the knowledge base)
- **Flow**: Draft -> Final Draft -> topics/index/manifest
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent processes sequentially
- `subAgent: true`: Enabled when any of the following thresholds are met; defaults to **B Mode** (main agent produces inventory, sub-agents do parallel read-only schema-based table fills, main agent merges and persists); upgraded to **C Mode** (multi-round correction) for multi-workspace / monorepo, first-round sub-table conflicts or gaps, or severe multi-source contradictions
- Thresholds: 5 or more input paths OR single source exceeds 3000 lines OR total across multiple paths exceeds 10000 lines
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Produces inventory and scan contract, aggregates sub-tables, persists topics/index/manifest |
| Sub-Agent (B/C Mode) | Performs read-only scans per the main agent's written inventory, delivers tables in schema format (`source / scope / capabilities / cross_refs / pending`); must not self-crop the scope, write manifest or index, or claim "already in the knowledge base" |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topic files persisted by sub-agents -> Main agent verifies routing mapping completeness and keyword coverage
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-ctx-rm`
**Purpose**: Deletes corresponding knowledge topics and index mappings based on `stock-docs` documents. Only removes reference relationships in the knowledge base, not the source documents themselves.
**How It Works**: The inverse of `f2s-ctx-build` — given a `stock-docs` document path, locate its task→topic rules in `manifest-routing.json`, the corresponding `matchers/<id>.json` shard, `topics/<topic>.md`, and entries in `index.md`, and remove those references one by one. If a topic has no remaining task references after deletion, remove that topic file. Source documents are left in place; the user may delete them physically if desired.
**Use Cases**:
- A document is deprecated and needs removal from the knowledge routing
- A document was imported by mistake and its routing mapping needs revocation
- Cleaning up old mappings after document consolidation
**Relationships**:
- **Prerequisite**: A stock-docs document that has already been imported
- **Next Step**: None
- **Note**: Only deletes routing mappings, not source documents
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent handles the full workflow (single-point deletion has low sub-agent ROI)
- `subAgent: true`: Sub-agents are used only for **batch deletion of 5 or more topics**; the main agent must control scope confirmation and `fallbackTopic` re-pointing; `manifest-routing.json` and `index.md` are always persisted by the main agent
---
### `f2s-doc-pdf`
**Purpose**: Converts PDF technical proposals to Markdown format, saves to `req-docs/`, and can supplement the process description.
**How It Works**: Extracts structured content from the PDF (API definitions, data models, sequence flows, etc.) into Markdown under `req-docs/` for editing and follow-up with `f2s-req-clarify` / `f2s-req-backend`. Unlike `f2s-doc-final`, `doc-pdf` writes to `req-docs/`; `doc-final` writes to `stock-docs/` for `ctx-build`. **Not recommended** as a shortcut for "PDF straight to coding" without clarification and a backend technical proposal.
**Use Cases**:
- Cross-team deliverables are in PDF format and need conversion to editable Markdown
- Historical PDF proposals need to live under `req-docs/`
- Provide a readable draft before `f2s-req-clarify` / `f2s-req-backend`
**Relationships**:
- **Prerequisite**: PDF document
- **Output**: `.Knowledge/req-docs/<Proposal>.md`
- **Next Step** (recommended): `f2s-req-clarify` → `f2s-req-backend` → implement from the technical proposal MD via `implement-tech-design`; for knowledge base archival use `f2s-doc-final` → `f2s-ctx-build`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the full workflow
- `subAgent: true`: When the PDF exceeds 50 pages or 5MB, sub-agents may be used for the PDF -> MD first draft and persist to `req-docs`; sub-agents must not ask the user questions or supplement process description sections; the main agent handles follow-up questions and process description supplementation
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Asks the user for process description supplements, completes `req-docs` deposition acceptance |
| Sub-Agent | Only performs PDF -> MD first draft and persists to `req-docs`, does not ask the user questions |
---
## 2) Requirements and Proposals
### `f2s-req-clarify`
**Purpose**: Asks clarifying questions against PRDs/requirement documents, using multi-round Q&A to define requirement boundaries, non-goals, and key flows, until the requirements are clear enough for a technical proposal.
**How It Works**: Uses a "structured questioning" strategy — decomposes the requirement document along six dimensions (roles, scenarios, flows, boundaries, exceptions, non-goals), checks each for vague wording, undefined concepts, or contradictions, and generates targeted questions for each gap. Dialogue continues until all dimensions are unambiguous, then outputs a clarification record as input for `f2s-req-backend`. It turns unstructured PRDs into structured, actionable requirement constraints.
**Use Cases**:
- First step after receiving a PRD, ensuring correct understanding
- When requirement boundaries are fuzzy or acceptance criteria are missing
- Cross-team collaboration requirements that need clear interface contracts
**Relationships**:
- **Prerequisite**: None (can be triggered directly)
- **Next Step**: `f2s-req-backend` (generates a technical proposal after clarification)
- **Output**: Requirement clarification record (optionally saved to `.Knowledge/req-docs/`)
**Sub-Agent Invocation**: None (clarification relies on continuous dialogue and immediate user feedback throughout; no sub-agent splitting)
---
### `f2s-req-backend`
**Purpose**: Based on clarified requirements and the project knowledge base, generates a backend technical proposal document including API design, data models, flow descriptions, error codes, etc.
**How It Works**: Centered on "knowledge base constraints + template-driven" authoring — first pull a constraint summary for the current project from `topics/stock-docs` (architecture conventions, API style, data model norms, etc.), then fill the backend technical proposal template (APIs / models / flows / errors / config / migrations) chapter by chapter against the clarified requirements so the proposal matches the existing architecture. Output is persisted under `req-docs/` as the coding contract for `implement-tech-design`.
**Use Cases**:
- After `f2s-req-clarify` completes, output a proposal based on clarification results
- When clear requirement documents already exist, directly generate a technical proposal
**Relationships**:
- **Prerequisite**: `f2s-req-clarify` (recommended) or a clear requirement document
- **Output**: `.Knowledge/req-docs/<Technical Proposal>.md`
- **Next Step**: Provide the technical proposal path with instructions "implement according to the technical proposal", driven by the `implement-tech-design` rule
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the proposal within the session
- `subAgent: true`: The main agent must first extract a project convention summary (under 80 lines) from topics/stock-docs (covering architecture conventions, API style, data model standards, etc. across 6 categories) as the mandatory sub-agent context, then dispatch sub-agents to write the `req-docs` draft in parallel; the main agent handles contract finalization and acceptance
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Extracts project convention summary, assigns writing tasks, finalizes the draft against the template, and writes to `req-docs` |
| Sub-Agent | Read-only access to multiple sources (topics / stock-docs / clarified req-docs / templates), writes `req-docs` draft per template; must not expand the read scope on its own |
**Cross-Verification (when `switchAgentVerification: true`)**:
- API/model/flow documents persisted by sub-agents -> Main agent verifies cross-chapter consistency (API signatures align with data models, flows and error handling coverage)
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-req-plan`
**Purpose**: Starting from a technical proposal or requirement description, **always creates a task checklist**, then implements the code accordingly. Does not depend on the `changeTracking` configuration; represents the user's explicit need for traceable task management.
**How It Works**: Runs a five-phase closed loop: parse → plan → confirm → implement → archive. (1) Parse the technical proposal for implementation points; (2) split into executable tasks at module/feature granularity and write to `.task/`; (3) show the draft to the user, lock the checklist after confirmation; (4) implement item by item, checking off `task.md` immediately when each item completes; (5) archive when all are done. Unlike the `implement-tech-design` rule, `req-plan` always carries task tracking and can parallelize implementation with sub-agents for large work; the rule path is lightweight, single-threaded coding.
**Use Cases**:
- A technical proposal document exists and needs to be broken down into a task list before implementation
- The requirement description is complex and the user wants to confirm the checklist before starting work
- The user wants to track implementation progress across sessions
**Relationships**:
- **Prerequisite**: Technical proposal document path (`.Knowledge/req-docs/*.md` or PDF) or requirement/change description
- **Output**: `.task/active/<task-name>/task.md` + `context.md`; implementation code
- **Next Step**: Optionally invoke `f2s-kb-sync` to supplement the knowledge base
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes parsing, confirmation, and implementation in full
- `subAgent: true`: Step 1 (document parsing) can dispatch sub-agents for parallel read-only; Step 2 (draft confirmation) must be done by the main agent; Step 4 (code implementation) can dispatch sub-agents per module; `todo.json` is always written by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Outputs draft, gets user confirmation, writes `todo.json`, aggregates implementation summary |
| Sub-Agent (parsing) | Read-only document parsing, outputs parsing result summary, does not persist |
| Sub-Agent (implementation) | Implements code per module, does not touch `.task/` or `.Knowledge/` |
---
## 3) Git Commit
### `f2s-git-commit`
**Purpose**: Executes a Git commit after code is written. Automatically checks changed files, compares knowledge base coverage, prompts the user about capabilities not yet imported, and performs the commit after the commit message is confirmed.
**How It Works**: Layers a "knowledge base coverage gate" on top of `git commit` — infer touched capability areas from `git diff`, cross-check against `.Knowledge/topics/` and `stock-docs/`, and decide whether changed capabilities are documented in the knowledge base. If not covered, block and offer three choices (document first / skip / cancel) to avoid silent drift where "code exists but the knowledge base does not know." Commit messages use emoji + Conventional Commits for consistent, machine-friendly `git log`.
**Use Cases**:
- Committing code after each feature implementation or bug fix
- Wanting reminders about knowledge base coverage at commit time
- Needing AI help to generate meaningful commit messages
**Relationships**:
- **Prerequisite**: Code has been written (after `implement-tech-design`, `f2s-kb-fix`, `f2s-kb-feat`, etc.)
- **Next Step**: None (ends when commit completes; does not auto-push)
- **Bridging**: If the knowledge base is not yet covered, you can first run `f2s-kb-sync` or `f2s-kb-feat` to supplement before committing
**Execution Flow**:
1. `git status --short` + `git diff HEAD` to classify files into staged / unstaged / untracked; immediately terminates if merge conflict markers are found
2. Compare `.Knowledge/topics/` and `stock-docs/` to determine whether the changed capabilities have been imported; skips and notifies if `.Knowledge` does not exist
3. If not covered, prompt the user to choose: A) Import first, then commit / B) Commit now, import later / C) Cancel
4. Generate a commit message draft based on `git diff` content, wait for user confirmation or changes
5. `git add <specific files>` + `git commit`; if a hook fails, prompt for fix, do not skip
6. Output the commit hash; if option B was selected, include a reminder about capabilities not yet imported
**Constraints**:
- `git add -A` / `git add .` is forbidden; only add confirmed changed files
- `--no-verify` is forbidden; hook failures must be fixed and retried
- Auto-push is forbidden
- The commit message must be confirmed by the user; silent commits are not allowed
**Sub-Agent Invocation**: None (full interactive confirmation, handled within the main agent)
---
## 4) Knowledge Base Maintenance
### `f2s-kb-fix`
**Purpose**: Fixes code based on implementation or rule errors reported by the user, and **by default automatically syncs** the knowledge base documents and index.
**How It Works**: Three steps: locate → fix → sync. From the user's description, locate context and code via the knowledge routing path (manifest → topic → stock-docs) and confirm root cause; after fixing code, automatically check whether related descriptions in `topics/stock-docs/matchers` need updates and revise in place if so (current truth only, no stacked historical negation). "Fix code, sync docs" is the core principle to prevent knowledge drift.
**Use Cases**:
- Code implementation does not match the technical proposal
- Rule understanding errors need correction
- Documentation needs to be synced after bug fixes
**Change Tracking**: If `changeTracking.fix: true`, automatically checks `.task/todo.json` before execution, creates a task checklist, and automatically archives upon completion; cross-session continuation via keywords is supported (see `f2s-task` rules).
**Relationships**:
- **Prerequisite**: Problem discovered (code implementation error or rule deviation)
- **Next Step**: None (ends when fixes and sync are complete)
- **Feature**: No need for the user to explicitly request "please sync the knowledge base"; it is done automatically
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes fixes and knowledge base sync
- `subAgent: true`: Code sub-packages (bug fixes) can be outsourced to sub-agents; documentation sub-packages (rules/skills/topics style-related) default to the main agent writing directly; if sub-agents are used, they only output before/after diff snippets, not full-file rewrites; manifest and index are always persisted by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Locates root cause, devises fix plan, persists style-compliant content, verifies knowledge base consistency |
| Sub-Agent (code) | Responsible for bug fixes in designated modules, outputs changes and reports impact scope |
| Sub-Agent (documentation, optional) | Only outputs before/after diff snippets, no full-file rewrites, does not touch manifest or index |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Code changes persisted by sub-agents -> Main agent verifies fix correctness and knowledge base consistency
- Knowledge base sync persisted by the main agent -> Sub-agent reviews topic/manifest consistency (requires `subAgent: true` and sub-tasks actually dispatched; otherwise self-verification within the main agent)
- The reviewer and the persister must be different agent instances
---
### `f2s-kb-feat`
**Purpose**: When adding a new capability, completes both the implementation and the knowledge base; if the capability is already implemented, only syncs the knowledge base.
**How It Works**: Three phases: assess → implement → ingest. First assess whether the described capability is not implemented, partially implemented, or already implemented in code; if not or partial, complete the code first; then sync the knowledge base: write a capability description in `stock-docs`, generate or update `topics` summaries, register routing in `manifest-routing` and `matchers`. Unlike `f2s-kb-fix`, `kb-feat` targets **new** work; `kb-fix` targets **correcting existing** work.
**Use Cases**:
- New feature development
- Adding knowledge base documentation for an existing feature
**Change Tracking**: If `changeTracking.feat: true`, automatically checks `.task/todo.json` before execution, creates a task checklist, and automatically archives upon completion; cross-session continuation via keywords is supported (see `f2s-task` rules).
**Relationships**:
- **Prerequisite**: None (can be triggered directly)
- **Next Step**: None (ends when implementation + sync are complete)
- **Feature**: Knowledge base sync is automatic; no additional user request needed
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes everything
- `subAgent: true`: Code sub-packages (new implementation) can be outsourced to sub-agents; documentation sub-packages (rules/skills/topics style-related) default to the main agent writing directly; if sub-agents are used, they only output before/after diff snippets; manifest and index are always persisted by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Defines capability boundaries and implementation scope, persists style-compliant content, performs final verification of knowledge base consistency |
| Sub-Agent (code) | Responsible for code implementation (APIs, logic, data layer), outputs implementation checklist |
| Sub-Agent (documentation, optional) | Only outputs before/after diff snippets, no full-file rewrites, does not touch manifest or index |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topics persisted by documentation sub-agents -> Main agent verifies consistency between the capability description and the implementation code
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-kb-sync`
**Purpose**: Sinks already-implemented capabilities from the conversation back into the knowledge base. Can accept an explicit capability description or infer with zero input.
**Use Cases**:
- Implementation is complete within the conversation and needs knowledge base documentation
- Reverse-documenting knowledge from code
- Periodic knowledge base organization
**Relationships**:
- **Prerequisite**: None (can be triggered directly, or with zero-input inference)
- **Next Step**: None
- **Feature**: First outputs a knowledge base update outline, then writes only after user confirmation
- **Difference from `f2s-ctx-build`**: `ctx-build` is driven from `stock-docs`; `kb-sync` infers from the conversation/code
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes inference and sync
- `subAgent: true`: Steps are split -- **Step 1** (aggregation and inference) can dispatch sub-agents for parallel read-only access to conversation history; **Step 2** (user confirmation of the outline) must be done by the main agent; **Step 3** (persist sync) can dispatch sub-agents to write topic/matcher files, but sub-agents must read 2-3 neighboring topic summaries for style alignment before persisting; manifest and index are always persisted by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Outputs outline and gets confirmation, single-point persists manifest and index, final acceptance |
| Sub-Agent (aggregation) | Read-only access to conversation history, infers capability points, generates structured update outline fragments |
| Sub-Agent (sync) | Writes topic/matcher per outline, loads neighboring topic summaries for style alignment before persisting, does not touch manifest or index |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topics/matchers persisted by sync sub-agents -> Main agent verifies cross-topic routing completeness and `includeAny` keyword coverage
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-kb-merge`
**Purpose**: Resolves editor context conflicts after Git merges. An optional conflict file path can be provided.
**How It Works**: Layered by file kind — split conflict files into "safe to auto-merge" (structured files such as index, manifest, matchers, using union or latest) vs "needs user judgment" (implementation code, business rules, and other semantic files). Auto-resolve the former; for the latter, produce a comparison table (ours/theirs summary + recommendation) and list differences for the user to decide item by item. Design idea: knowledge-base metadata can be automated; business semantics must not be decided unilaterally.
**Use Cases**:
- Context conflicts arise after a Git merge/rebase
- Knowledge base file conflicts caused by multi-person collaboration
- Need to unify knowledge base state after branch merging
**Relationships**:
- **Prerequisite**: Conflicts generated by a Git merge
- **Next Step**: None (ends when conflicts are resolved)
- **Feature**: Implementation-side conflicts are only listed for the user to confirm
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent analyzes and resolves conflicts
- `subAgent: true`: Sub-agents can be dispatched for conflict scanning and classification into a comparison table (`file / category / ours_summary / theirs_summary / recommendation`); sub-agents must not merge files on their own; the main agent persists per strategy, handles implementation-side decisions, and completes acceptance
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Persists merge results per strategy, handles implementation-side conflict decisions, acceptance |
| Sub-Agent | Only performs conflict scanning and classification, delivers comparison table in the five-field schema, does not merge files on its own |
---
### `f2s-kb-migrate`
**Purpose**: Migrates an old-format knowledge base (`docs-index.md` + `rules/` pattern) into the `.Knowledge/` structure organized by topic.
**How It Works**: Uses the legacy `docs-index.md` and `rules/main.md(c)` as index clues, recursively finds all referenced business rules and skill files, and reorganizes by topic into `.Knowledge/` (`topics` / `stock-docs` / `req-docs`). After migration, persist `migration-report.md` (mapping table + proposed deletion paths), then clean up old files after user confirmation. A one-time structural merge of scattered rules/docs into one knowledge base.
**Use Cases**:
- Upgrading an old project to the new Flow2Spec version
- An existing knowledge base needs structured reorganization
**Relationships**:
- **Prerequisite**: Old-format knowledge base (`docs-index.md`, `rules/`, `skills/`)
- **Next Step**: `f2s-kb-upgrade` (**Flow V1**: old knowledge base must migrate first, then upgrade; **Current V2+ knowledge base** (including npm v3.x): see the upgrade skill Step 0)
- **Flow**:
1. Use `docs-index.md` + `rules/main.md(c)` as the primary index
2. Process all business `rules/` and business `skills/` in full (excluding `f2s-*` package skills)
3. Migrate all `stock-docs`/`req-docs`
4. Persist `.Knowledge/migration-report.md`
5. Delete migrated old files after user confirmation
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent migrates topic by topic
- `subAgent: true`: Sub-agents only handle migration + draft migration-report fragments (delivered as patches); status files (migration-report.md, deletion execution records) are exclusively persisted by the main agent; the main agent leads the deletion confirmation and closure
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Creates migration plan, consolidates migration results, persists migration-report, leads deletion confirmation and execution closure |
| Sub-Agent | Handles topic migration and draft fragment generation (patch format) for designated topics; does not write status files or deletion execution records |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topics migrated and persisted by sub-agents -> Main agent verifies migration completeness (whether old paths are fully covered, whether topic boundaries overlap)
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-kb-upgrade`
**Purpose**: Knowledge base template upgrade. Aligns manifest-routing and matchers shards.
**How It Works**: Uses "version branching + delegated init" — detect whether the current knowledge base is V1 (legacy structure, migrate first) or V2+ (already has `.Knowledge`): V1 runs migrate then init; V2+ runs `flow2spec init` directly for incremental package alignment (new templates, manifest schema upgrades, matcher shard format alignment). After upgrade, re-read SKILL.md to see if certain steps must be re-run. Unlike a standalone `init`, `kb-upgrade` includes version routing and re-run logic; `init` alone is a one-shot structural fill-in.
**Use Cases**:
- After a `flow2spec` package version upgrade, upgrade the project knowledge base template
- Upgrade an old project to the latest structure
**Relationships**:
- **Prerequisite**: `f2s-kb-migrate` (V1 flow) or an existing `.Knowledge/`
- **Includes**: Internally invokes `flow2spec init` for structural alignment
- **Note**: A standalone `flow2spec init` is **not** an upgrade command
**Flow Differences (in-skill routing codes, **not** equivalent to npm major versions)**:
- **V1**: First `f2s-kb-migrate`, then runs `flow2spec init`
- **Current Knowledge Base (V2+)**: When `.Knowledge` + `manifest-routing` are already stable, runs `flow2spec init` to align manifest-routing + matchers shards (**includes Flow2Spec npm v3.x, etc.**; see `skills/f2s-kb-upgrade/SKILL.md` Step 0 for details)
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the upgrade
- `subAgent: true`: Sub-agents only handle shell command execution (running `flow2spec init`), not knowledge base content persistence; the following steps must not be delegated by the main agent: version routing (V1 / Current V2+), re-reading SKILL.md after init and determining a full skill re-run, Step 3b index.md consolidation, verification summary output
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Version routing, re-reading and determining re-run after init, Step 3b index.md consolidation, verification summary; persists `manifest-routing.json` and `index.md` |
| Sub-Agent | Only runs shell commands like `flow2spec init`, does not persist knowledge base content |
**Cross-Verification**: This skill is not bound to cross-verification; self-verification by the persisting side.
---
## 5) Rule Descriptions
The following are not skill commands but rules activated by trigger words to guide Agent behavior.
### `f2s-karpathy-guidelines`
**Trigger Words**: `alwaysApply` (always on; no explicit trigger needed)
**Purpose**: Flow2Spec's built-in Karpathy-style coding discipline to improve the quality of agent coding decisions.
**How It Works**: Four behavioral constraints distilled from Andrej Karpathy's observations on common LLM coding mistakes, applied as an `alwaysApply` rule that implicitly governs all `f2s-*` skill runs: (1) think before coding (state assumptions; ask when unsure); (2) simplicity first (minimum code to solve the problem); (3) surgical edits (touch only what must change; match existing style); (4) goal-driven execution (define verifiable success criteria, then iterate). When these guidelines conflict with mandatory `f2s-*` steps, the `f2s-*` steps win.
---
### `f2s-task`
**Trigger Words**: changeTracking, change tracking, task tracking, continuation, continue last task
**Purpose**: Change tracking rules (`alwaysApply`). When the corresponding skill's `changeTracking.*` is set to `true`, automatically creates, progressively updates, and finally archives task checklists under `.task/` before and after skill execution, supporting cross-session continuation.
**How It Works**: Cross-session persistence via "disk checkpoints + keyword matching" — each active task records progress with checkboxes (`[ ]` / `[x]`) in `.task/active/<name>/task.md`, with `todo.json` as the active-task index. At the start of a new session, the rule fuzzy-matches the user's first message to each task's `keywords`; on a match, it loads the remaining steps in `task.md` and the skill file for `linkedSkill`, restoring full execution context. Completed tasks move to `completed/`. Design: the file system, not chat memory, is the source of truth so interrupted sessions do not lose progress.
**Scope**:
| Config Item | Corresponding Skill |
|-------------|-------------------|
| `changeTracking.feat` | `f2s-kb-feat` |
| `changeTracking.fix` | `f2s-kb-fix` |
| `changeTracking.implement` | `f2s-implement-tech-design` |
**Cross-Session Continuation**: When a new session starts and `.task/todo.json` exists, automatically matches the user's first message against each task's `keywords`; on a match, loads the corresponding `task.md` and `linkedSkill` skill file, displays the remaining checklist, and asks whether to continue; if there is no match, proceeds without interruption.
**Rule Location**: `Config Root/rules/f2s-task.*`
---
### `stock-docs-vs-req-docs`
**Trigger Words**: stock-docs, req-docs, implemented capability, where to put the technical proposal, PDF final draft
**Purpose**: Distinguishes the boundary between the knowledge archival directory and the requirements implementation directory.
**How It Works**: "Purpose isolation" to avoid mixing folders — `stock-docs/` holds archived existing knowledge (architecture, final drafts), consumed by `ctx-build` for ingestion into the knowledge base and **must not** be used directly as coding input; `req-docs/` holds implementation-facing requirements and technical proposals, consumed by the `implement-tech-design` rule to drive coding. Writers and readers are fully separated so "stock descriptions are not mistaken for coding contracts" and "implementation proposals are not mistaken for capability archival."
**Directory Division**:
| Directory | Purpose | When It Is Written |
|-----------|---------|-------------------|
| `stock-docs/` | Archival of existing knowledge (architecture, final drafts) | `f2s-doc-arch`, `f2s-doc-final`, `f2s-ctx-build` |
| `req-docs/` | Requirements and technical proposals (driving implementation) | `f2s-req-backend`, `f2s-doc-pdf`, manual placement |
**Use Cases**:
- Unsure where a document should go
- Need to clarify the division of labor between stock-docs and req-docs
---
### `implement-tech-design`
**Trigger Words**: implement according to technical proposal, implement-tech-design, implement per proposal
**Purpose**: Implements runnable code based on technical proposal documents in `req-docs/`.
**How It Works**: "Proposal as contract" — the agent treats the technical proposal in `req-docs/` as the sole coding contract and must follow the mandatory six-step pipeline: understand proposal → output task list → ask clarifying questions before coding → implement step by step → output remaining work and post-implementation reminders. The task list and pre-implementation Q&A are non-skippable gates so coding does not start on a misunderstood spec. Unlike `f2s-req-plan`, this rule is lightweight single-threaded coding and does not force `.task/` tracking unless `changeTracking.implement: true`.
**Change Tracking**: If `changeTracking.implement: true`, after outputting the task list in Step 2.5, synchronously writes to `.task/active/<task-name>/task.md`; archives the task in Step 5 during wrap-up.
**Use Cases**:
- Technical proposal is ready and needs to be coded per the proposal
- After a proposal change, code needs to be updated accordingly
**Relationships**:
- **Prerequisite**: `.Knowledge/req-docs/<Technical Proposal>.md` (via `f2s-req-backend` or manual placement)
- **Rule Location**:
- Cursor: `.cursor/rules/f2s-implement-tech-design.mdc`
- Claude: `.claude/rules/f2s-implement-tech-design.md`
- Codex: `.codex/AGENTS.md` + `.codex/topics/f2s-implement-tech-design.md`
**Execution Flow (mandatory by rules)**:
1. Input normalization
2. Understand the proposal and context
3. **Output the implementation task list** (required, cannot be skipped)
4. **Ask questions before implementing** (required, cannot be skipped)
5. Implement per task list
6. **Output the remaining checklist and post-implementation reminders** (required)
**Sub-Agent Invocation**: None (rule-driven coding; the main agent completes the full workflow)
---
## 6) Sub-Agent Configuration
Controlled via `flow2spec.config.json` at the project root (all fields default to `false`).
### How Different Products "See" the Configuration (use with the field table below)
`subAgent` and similar fields are written to the **on-disk JSON**; products do not guarantee automatic file opening. Therefore, multi-layered hints are provided via **Cursor rules / Claude hooks / Codex AGENTS snapshot table / knowledge base `config-precheck` summary**, but **the authoritative source remains `Read("flow2spec.config.json")`** (design rationale in [design-principles.md — Agent Orchestration § 5.1](./design-principles.md); talk / deck pacing in [intro deck HTML](../../presentations/flow2spec-intro-public-en/index.html) (internal); Chinese source in `flow2spec-intro-draft`, config section). **The full path and table are maintained in one place**: [usage-guide.md Sec. 1, `f2s-*` and `flow2spec.config.json`](./usage-guide.md).
### `subAgent` Field
| Value | Behavior |
|-------|----------|
| `false` (default) | All `f2s-*` skills complete within the main agent |
| `true` | Certain skills may use sub-agents per their documentation (large-scale parallel processing scenarios) |
### `switchAgentVerification` Field
| Value | Behavior |
|-------|----------|
| `false` (default) | Self-verification on the persisting side: whoever persists verifies |
| `true` | When a skill explicitly states this step, enables cross-verification: sub-agent persists -> main agent verifies; main agent persists -> sub-agent verifies (requires `subAgent: true` and sub-tasks actually dispatched) |
### `changeTracking` Field
A nested object, with each skill independently controlled:
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
| Sub-field | Corresponding Skill | Effect |
|-----------|---------------------|--------|
| `feat` | `f2s-kb-feat` | Creates a task checklist before execution, archives on completion, supports cross-session continuation |
| `fix` | `f2s-kb-fix` | Same as above |
| `implement` | `f2s-implement-tech-design` | Same as above |
> `f2s-req-plan` is not constrained by this configuration; it always creates a task checklist. Legacy boolean values (`"changeTracking": true/false`) are backward-compatible and automatically expand to all three sub-fields on/off.
For full principles and design intent, see [architecture.md Sec. 4. Agent Execution Model](./architecture.md).
---
## 7) Quick Reference
For typical work scenarios and full workflows, see [Usage Guide § 3. Typical Workflows](./usage-guide.md).
For a complete directory description, see [Directory Conventions](./directory-conventions.md).
---
Related Documents:
- [Usage Guide](./usage-guide.md)
- [Directory Conventions](./directory-conventions.md)
- [Architecture](./architecture.md)
- [Usage Scenarios](./usage-scenarios.md)
[中文](../设计说明.md) | [English](./design-principles.md)
# Flow2Spec Design Principles
## Problem Statement
```
❌ Current State ✅ After Flow2Spec
Architecture conventions ──┐ .Knowledge/
Technical designs ──┼──► scattered ├── manifest-routing.json
Module boundaries ──┤ unstructured ├── matchers/
Team experience ──┘ reinterpreted ├── topics/
every time ├── stock-docs/
└── req-docs/
AI can read the project anytime
```
---
## Core Design
### 0. Memory Coding and Four Rings
**Memory Coding**: encode durable context into the **committed repository** (PR-reviewable), not private model memory or chat-only context.
Four rings in the repo (rules ring and skills ring are separate—do not merge):
| Ring | Location | Role |
| --- | --- | --- |
| Knowledge | `.Knowledge/` | Routing, topics, stock/req docs |
| Task | `.task/` | Cross-session continuation, user todos |
| Rules | Tool `rules` / `AGENTS.md` | How to read and act |
| Skills | `f2s-*` / `skills/` | Maintain KB, trigger workflows |
Flow2Spec delivers the **Memory Coding persistence and maintenance loop**, not "another RAG knowledge base."
### 0.1 Knowledge Ring: Multi-Layer Memory
Inside the knowledge ring: **horizontal narrowing** (L0 manifest → L1 matchers → L2 topics → L3 long docs) plus **vertical chaining** (`topicDependencies`: common → subdomain → whitelist → domain). The `match → expand → verify → act` pipeline operates on these layers; see [architecture.md §4](./architecture.md).
### 1. Separation of Knowledge and Rules
```mermaid
graph LR
subgraph K[".Knowledge/ Knowledge Layer"]
K1[Architecture Docs]
K2[Technical Designs]
K3[Routing Index]
end
subgraph R["Config Root Execution Layer"]
R1[.cursor/rules/]
R2[.claude/rules/]
R3[.codex/AGENTS.md]
end
K -->|Knowledge Input| AI[AI Tools]
R -->|Rule Constraints| AI
note1["Knowledge evolves with the project"] -.-> K
note2["Rules evolve with tool upgrades"] -.-> R
```
### 2. Progressive Routing
```mermaid
graph LR
T[Task] --> M[manifest-routing\nRead routing table]
M -->|Keyword match| MT[matchers/xxx.json\nRead only this shard]
MT -->|Hit| TP[topics/xxx.md]
TP --> V{Gap Check}
V -->|Pass| ACT[Execute]
V -->|Insufficient| Q[Ask user for clarification]
M -->|No match| FB[fallback-triage\nStructured triage]
```
### 3. Skill Maintenance Loop
<p><img src="./images/process-1.png" alt="Skill maintenance loop" style="max-width:100%;" /></p>
<details>
<summary>Mermaid source</summary>
```mermaid
graph LR
K[".Knowledge/"] --> AI["Next Session\nAI"]
AI --> C["Feature iteration"]
C -->|"Fix Bug"| FIX["f2s-kb-fix"] --> K
C -->|"New Capability"| FEAT["f2s-kb-feat"] --> K
C -->|"Session End"| SYNC["f2s-kb-sync"] --> K
C -->|"Commit Code"| CMT["f2s-git-commit\nGate Check"]
CMT -->|"Not in KB, remind\n-> kb-sync/kb-feat"| K
D1["Architecture Docs"] -->|f2s-doc-arch| FIN["f2s-doc-final"]
D2["PDF/draft"] -->|f2s-doc-final| FIN
FIN --> CTX["f2s-ctx-build"] --> K
OLD["Existing Code/Docs"] -->|f2s-doc-add| K
NR["New Requirement"] --> CL["f2s-req-clarify"] --> BE["f2s-req-backend"]
BE --> IMPL["Implement xxx technical design"] -->|auto-trigger implement-tech-design rule| K
GIT["After Git Merge"] -->|f2s-kb-merge| K
```
</details>
Seven entry points · `f2s-git-commit` is the knowledge discipline gate at commit time · `.Knowledge/` is the single convergence point · Knowledge drives AI, AI drives the next development cycle
### 4. Task Checklist and Cross-Session Continuation
```mermaid
graph LR
SKILL["f2s-kb-feat / f2s-kb-fix\nimplement-tech-design"] -->|"changeTracking: true"| TJ[".task/active/\ntask.md · todo.json"]
RP["f2s-req-plan\n(always created)"] --> TJ
TJ --> NS[First message of new session]
NS -->|Keyword match| LD["Load remaining checklist\n+ linkedSkill context"]
LD --> RS[Continue per original skill constraints]
```
Tasks do not get lost when a session ends · Keywords enable automatic continuation without re-explaining context · Skill constraints are fully restored
---
## Design Highlights
### A. Routing and Context Loading
#### 1. matchers sharded, not embedded in manifest
```
❌ Embedded in manifest ✅ Independent shards
manifest.json (full read every time) manifest-routing.json
├── task1: keywords:[...] → ├── task1 → m-order.json ──► read only this one
├── task2: keywords:[...] ├── task2 → m-payment.json
└── task3: keywords:[...] └── task3 → m-refund.json
Updating keywords doesn't touch routing structure
Per-routing token cost is fixed
```
#### 2. topicDependencies: dependencies on topics
```
❌ Attached at task level ✅ Attached at topic level
taskA → [dep, main] topicDependencies:
taskB → [main] ← forgot main: [dep]
taskC → [main] ← forgot
Any path loading main
Forgot when adding new task automatically brings in prerequisite
→ silent failure dependencies
```
#### 3. topics store summaries, rules files store full text
```
.Knowledge/topics/implement-tech-design.md ← lightweight, loaded during routing
┌──────────────────────────────────────────┐
│ Topic id, path conventions, next pointer │
│ ~100 lines │
└──────────────────────────────────────────┘
↓ read only after hit
.claude/rules/f2s-implement-tech-design.md ← full text, loaded during execution
┌──────────────────────────────────────────┐
│ Complete execution constraints, │
│ mandatory steps, prohibitions, │
│ boundary descriptions │
│ ~500 lines │
└──────────────────────────────────────────┘
```
Routing layer stays lightweight · Execution details load on demand · The two evolve independently
#### 4. Full-scan prohibition is a hard constraint
```
Read order (mandatory)
1. manifest-routing.json ← read the routing table first
2. matchers/xxx.json ← read only the matched shard
3. index.md ← on demand, confirm semantics
4. stock-docs / req-docs ← on demand, supplement context
5. Business source code ← last resort
❌ Before reading manifest, full-repo unbounded scan is prohibited
❌ Within the same task line, manifest already read, do not re-read in full
❌ index.md must not be alternated with manifest as a "checklist" to replace decisions
```
#### 5. Skill trigger words in the description field
```yaml
name: f2s-kb-sync
description: >
Sync implemented capabilities to the knowledge base.
Triggers: f2s-kb-sync, full sync, knowledge base sync, implemented capabilities
```
```
User input → Agent scans description for semantic match → triggers corresponding skill
```
Trigger words are in the `description` field · not in the skill body · higher hit rate · bilingual coverage reduces missed triggers
---
### B. Knowledge Structure
#### 1. stock-docs vs req-docs semantic prohibition
```
stock-docs/ req-docs/
Architecture docs / Final draft Requirements / Technical designs
↓ used for ↓ used for
Knowledge routing / Background Drive coding implementation
reference
✅ May be read ✅ May be read
❌ Cannot be used as coding input ✅ Input for implement-tech-design
```
Prevents: driving implementation with outdated reference docs → code diverging from the latest design
#### 2. init is idempotent
```
flow2spec init can be safely re-run
✅ Does ❌ Does NOT
┌─────────────────────┐ ┌─────────────────────┐
│ Fill missing │ │ Write business │
│ directories/templates│ │ document content │
│ Install rules/skills │ │ Update routing │
│ │ │ keywords │
│ Align package-level │ │ Overwrite existing │
│ structure │ │ knowledge content │
└─────────────────────┘ └─────────────────────┘
Structural operations ≠ Business semantics The two have no overlapping responsibilities
```
#### 3. Knowledge versioning
```
git log .Knowledge/
a3f1c2 f2s-kb-feat: add refund state machine routing
b7e9d1 f2s-kb-fix: fix RestTemplate injection conventions
c2a8f0 f2s-ctx-build: onboard order service architecture docs
d5b3e9 f2s-kb-sync: consolidate payment retry queue design
Code changes + Knowledge changes → same commit or adjacent commits
```
Knowledge has versions · is reviewable · is traceable · is blameable
#### 4. No accumulation of historical negation
```
❌ Wrong approach (knowledge base grows bloated) ✅ Correct approach (only current truth)
RestTemplate convention (updated 2026-05) RestTemplate must be injected via Bean
~~Previously incorrectly used new RestTemplate()~~ Direct new RestTemplate() is prohibited
→ No longer related to direct instantiation
→ Old approach deprecated, now uses Bean injection
```
Rewrite in place with each fix · don't layer history · the knowledge base always describes only the present
---
### C. Execution Constraints
#### 1. Mandatory steps are constraints, not suggestions
```
implement-tech-design execution flow
Input normalization
Read proposal and context
★ Output implementation task list ← cannot skip
★ Confirm before implementing ← cannot skip
Implement per task list
Output pending checklist and reminders ← cannot skip
```
Suggestions → can be skipped · Constraints → must be explicitly addressed before proceeding
#### 2. fallback is itself a procedurally-defined topic
```mermaid
graph TD
F[Enter fallback-triage] --> S1{Route matched?}
S1 -->|Matched but insufficient context| EXP[Expand dependency topics\nfill gaps and continue]
S1 -->|Not matched| Q[Ask user:\nHas this domain been documented?]
Q -->|Yes| HINT[Routing entry missing\nsuggest adding routing]
Q -->|No| CHOICE[Drill into source code\nor add req-docs]
Q -->|Not sure| STOP[Stop execution\nwait for clear instructions]
```
No match ≠ silent failure · degradation itself has a clear procedure
#### 3. manifest / index write authority hard constraint
```
Sub-agents MAY write Sub-agents MUST NOT touch
──────────────────── ────────────────────
Code implementation files manifest-routing.json ← always written by main agent
stock-docs content files .Knowledge/index.md ← always written by main agent
topics content files (diff mode)
matchers/*.json (diff mode)
```
When multiple sub-agents run in parallel, shared state files are written single-point by the main agent to prevent concurrent conflicts
#### 4. Document changes vs code changes: different splitting strategies
```
Code sub-packages Document sub-packages
──────────────────── ────────────────────
✅ Can delegate to sub-agents ❌ Not split by default, main agent writes directly
✅ Sub-agents write directly If outsourcing is necessary →
Sub-side only outputs before/after diff snippets
Main agent reviews and merges
❌ Full-file rewrite is strictly prohibited
```
Rationale: documents need to guarantee "current truth coverage / consistent style / no accumulation of historical negation" · requires the writer to see the full context
#### 5. Task checklist and cross-session continuation
```
Keyword-based automatic continuation example
First sentence of a new session: "There's still an issue with payment callback"
Matches each entry's keywords in todo.json
Hit { name: "payment_callback_fix", keywords: ["payment", "callback"] }
Load task.md (show remaining steps)
linkedSkill = "f2s-kb-fix" → load SKILL.md
Skill's write rules / style requirements / self-check checklist are fully restored
User doesn't need to re-describe context, can continue directly
✅ No need to say "continue the previous task"
✅ Skill constraints are fully restored, consistent with the first invocation
```
```
todo.json write authority constraint
Main agent ── read / write todo.json ✅
Sub-agent ── read todo.json ✅
Sub-agent ── write todo.json ❌
Rationale: when multiple sub-agents write concurrently,
concurrent writes cause entries to overwrite each other
```
Lifecycle is driven by skills · keyword routing enables cross-session automatic continuation · linkedSkill ensures full restoration of skill constraints
---
### D. Agent Orchestration
#### 1. subAgent × switchAgentVerification are orthogonal
```
switchAgentVerification
false true
subAgent ┌────────────┬─────────────────┐
true → │ Parallel │ Parallel │
│ execution │ execution │
│ Writer-side │ Sub writes→Main │
│ self-verify │ verifies │
│ │ Main writes→Sub │
│ │ verifies │
├────────────┼─────────────────┤
false → │ Sequential │ Sequential │
│ execution │ execution │
│ Main agent │ Main agent │
│ self- │ self-verifies │
│ verifies │ (no sub-side │
│ │ for cross-check) │
└────────────┴─────────────────┘
```
Two orthogonal dimensions · independently configurable · default is bottom-left
#### 2. Confirmation authority cannot be delegated to sub-agents
```mermaid
graph LR
S1[Step 1: Gather materials] -->|subAgent=true may parallelize| SUB[Sub-agent]
SUB -->|Read-only, no writes| S2
S2[Step 2: Output outline\nUser confirms] -->|Must be main agent| USER[User]
USER -->|Confirm| S3
S3[Step 3: Write] -->|subAgent=true may parallelize| SUB2[Sub-agent]
```
User dialogue only flows through the main agent · confirmation decisions cannot bypass the user · sub-agents only execute, never decide
#### 3. Skills can override global subAgent configuration
```
flow2spec.config.json f2s-req-clarify SKILL.md
subAgent: true This skill does not split by default:
regardless of subAgent value,
the clarification process stays
entirely in the main session
Rationale: requirement clarification depends heavily on continuous same-session follow-up
splitting would break context, degrading clarification quality
```
Global configuration is the upper bound for allowing splits · each skill decides for itself whether splitting is appropriate · config being true does not guarantee splitting
#### 4. f2s-kb-sync: outline first, write after confirmation
```mermaid
graph LR
T[Trigger f2s-kb-sync] --> O[Output update outline]
O --> U{User confirms}
U -->|Confirm| W[Write to .Knowledge/]
U -->|Modify| O
U -->|Cancel| STOP[No write]
```
Writing is a destructive operation · the outline is the user's only chance to correct · nothing is written before confirmation
#### 5. Zero-input inference
```
f2s-kb-sync three input modes
Mode 1: User explicitly provides capability list "Sync the refund state machine into the knowledge base"
Mode 2: User provides supplementary materials @src/refund/ @docs/proposal.md
Mode 3: Zero input "f2s-kb-sync" (just this one sentence)
Agent infers based on session context
what was implemented and what is worth consolidating
```
Session context itself is an information source · no need for users to organize and re-input
#### 5.1 How execution switches reach the Agent (multi-platform prompts)
`flow2spec.config.json` determines **`subAgent` / `switchAgentVerification` / `changeTracking`**, but AI products **do not guarantee** that the file is automatically opened at session start. The design uses **multiple weak constraint layers** to reduce the probability of "running `f2s-*` without reading the config", while avoiding maintaining a verbose duplicate of `.codex/topics/f2s-config-check.md` in `.Knowledge`:
| Mechanism | Design Intent |
| --- | --- |
| **Cursor `f2s-config-check.mdc`** | Rule-layer enforcement: "Read before skill body." |
| **Claude `f2s-config-inject` PreToolUse** | Injects parsed results when calling **`f2s-*` Skill**; **missing file / broken JSON / hook exception** still outputs a note with default semantics, no silent failure. |
| **Codex `AGENTS.md` + `renderProjectConfigBlock`** | Top-level **Read** hard constraint + **init snapshot table** (if inconsistent with disk, Read takes precedence). |
| **Knowledge base `config-precheck` topic** | When routing hits, provides only **summary** and a pointer to the Codex full text, **not** a substitute for Read JSON. |
**Authority remains** the **Read** result of the project-root JSON; each layer is a prompt, not a second source of truth. For the complete operational table and paths, see **[Usage Guide § 1. `f2s-*` and `flow2spec.config.json`](./usage-guide.md)**.
#### 6. Skills don't restate unified entry rules, only reference them
```
Each SKILL.md's orchestration section reads:
subAgent / switchAgentVerification semantics
are defined in the unified entry as the sole source of truth,
not restated here.
Cursor/Claude → rules/f2s-flow2spec-unified-entry.*
Codex → .codex/topics/f2s-flow2spec-unified-entry.md
15 skills, each only writes its own unique orchestration constraints
Common rules are defined in one place; modifying one location affects all
```
---
### E. Pluggable Architecture
#### 1. Tools are pluggable: one knowledge base, any tool combination
```
flow2spec init cursor claude codex ← all three tools installed
flow2spec init claude ← only Claude
flow2spec init cursor codex ← skip Claude
.Knowledge/ stays the same, tools can be added or removed at any time
```
The same `.Knowledge/` drives all tools · adding/removing tools does not affect knowledge content · new tools integrate with zero rebuild
#### 2. Knowledge topics are pluggable: add/remove without side effects
```
Adding a topic Removing a topic
───────────────────── ─────────────────────
1. Write topics/xxx.md f2s-ctx-rm stock-docs/xxx.md
2. Write matchers/m-xxx.json ↓
3. Register in manifest-routing Automatically cleans up topics/ + manifest
+ index references
Other topics remain completely unaffected
```
New topics simply declare dependencies in `topicDependencies` · if they don't, they're independent · removal has no side effects
#### 3. Skills are pluggable: self-contained units, project-level overrides package-level
```
Package-level skills (shipped with flow2spec init) Project-level skills (placed in config root/skills/)
f2s-kb-sync/SKILL.md my-domain-skill/SKILL.md
f2s-doc-arch/SKILL.md my-review-skill/SKILL.md
...
If names don't conflict they coexist · same name → project-level overrides package-level · they're unaware of each other
```
Skills describe their own trigger words via the `description` field · no registry needed · no global config changes needed · effective upon deployment
#### 4. Routing vocabulary is pluggable: shard isolation, local updates
Vocabulary changes only modify the corresponding `matchers/m-xxx.json`, with zero diff for other routes; see structure in "[A. Routing and Context Loading → matchers sharding](#1-matchers-sharded-not-embedded-in-manifest)".
Vocabulary changes are localized · merge conflicts are minimized · new routes don't affect existing ones
#### 5. Execution model is pluggable: config switches per project
```
flow2spec.config.json
subAgent: false → main agent throughout, low overhead, suitable for small projects
subAgent: true → allow sub-agent parallelization, suitable for large-scale changes
switchAgentVerification: false → writer-side self-verify, daily use
switchAgentVerification: true → cross-verification, high-confidence critical scenarios
changeTracking.feat/fix/implement: false → no task checklist created
changeTracking.feat/fix/implement: true → automatic task checklist creation when corresponding skills run, supporting cross-session continuation
Three orthogonal dimensions · each skill can further refine and override global config
```
Change one line of config to switch execution strategy · no skill files need modification · new projects work out of the box, existing projects upgrade on demand
---
## Strengths and Limitations
```
✅ Strengths ⚠️ Limitations
Precise context Upfront investment: knowledge must be built via skills
└─ Routing loads only relevant docs Scale threshold: overhead > benefit for small projects
Cross-tool sharing Requires team discipline
└─ Write knowledge once, use in all └─ Skills reduce friction, don't eliminate it
Tool-agnostic Learning curve
└─ Switch tools without rebuilding └─ stock/req boundary, routing structure aren't intuitive
Sustainable
└─ Maintenance tied to development actions
```
---
## Who Is It For
```
Project Scale
Small ◄──────────► Large
┌──────────┬────────────┐
Short │ Not │ Can use │
Term │ needed │ │
├──────────┼────────────┤
Long │ Can use │ Highly │
Term │ │ recommended│
└──────────┴────────────┘
Best suited when: has scale · long-term iteration · multi-tool or multi-person AI collaboration
```
---
## Related Documents
- [Usage Guide](./usage-guide.md)
- [Commands Reference](./commands-reference.md)
- [Architecture](./architecture.md)
- [Usage Scenarios](./usage-scenarios.md)
[中文](../目录与路径约定.md) | [English](./directory-conventions.md)
# Directory and Path Conventions
## Core Boundary
- `.Knowledge/`: **Knowledge ring** — business docs and machine-readable routing ([architecture.md §2](./architecture.md))
- `.task/`: **Task ring** — change tracking (not inside `.Knowledge/`)
- `Config Root` (`.cursor/.claude/.codex`): **Rules ring + skills ring**
See [architecture.md §1](./architecture.md) for Memory Coding four rings.
---
## Directory Responsibilities
| Path | Responsibility |
| --- | --- |
| `docs/` | Product docs (**Chinese**): usage guide, commands reference, design principles, etc. |
| `docs/en/` | Product docs (**English**): six paired documents; see [README.md](./README.md) |
| `.Knowledge/stock-docs/` | **L3** Architecture, final drafts, reference documents |
| `.Knowledge/req-docs/` | **L3** Requirement clarification, technical proposals |
| `.Knowledge/topics/` | **L2** Topic summaries (hard constraints, boundaries, pointers) |
| `.Knowledge/template/` | Templates for final drafts / technical proposals |
| `.Knowledge/index.md` | Human-readable index |
| `.Knowledge/manifest-routing.json` | **L0** Machine-readable routing skeleton (task/topic/`topicDependencies`) |
| `.Knowledge/matchers/*.json` | **L1** Keyword fragments (`id/includeAny`); **match** reads one shard via `matcherPath` |
| `.Knowledge/migration-report.md` | Migration comparison table and deletion path list written by `f2s-kb-migrate` |
| `.task/` | Change tracking task directory (`active/` for in-progress, `completed/` for archived with directory name in the format **`<YYYYMMDD>-<task-name>`** (date first), `todo.json` for active task index); created only when `changeTracking.*` is `true` or `f2s-req-plan` is explicitly invoked |
| `Config Root/rules/` | Rule files (Cursor `.mdc`, Claude `.md`) |
| `Config Root/skills/` | Skill definitions (`SKILL.md`) |
| `Config Root/template/` | (Deprecated) No longer written to; historical directories may be cleaned up |
| `.codex/AGENTS.md` | Codex unified entry point and loading instructions |
| `flow2spec.config.json` | Project root configuration, controls `subAgent`, `switchAgentVerification`, `changeTracking` (nested object with `feat` / `fix` / `implement` sub-items) |
> See [Usage Guide Section 1](./usage-guide.md) for multi-platform references and path tables (detail maintained in a single table); **the authoritative source remains `Read(flow2spec.config.json)`**.
---
## Path Constraints
1. `.Knowledge/topics` is the knowledge routing topic layer; it is allowed and encouraged to be maintained via `f2s-*` skills.
2. `f2s-ctx-build` reads from `.Knowledge/stock-docs` and updates `.Knowledge/topics`, `.Knowledge/index.md`, `.Knowledge/manifest-routing.json`, `.Knowledge/matchers/*.json`.
3. Implementation tasks uniformly read from `.Knowledge/req-docs/*.md`.
4. `manifest-routing.json` and `matchers/*.json` are maintained by `f2s-*` skill workflows; `.Knowledge/manifest-matchers.json` is no longer used (`flow2spec init` will delete legacy files).
---
## Related Documents
- [Usage Guide](./usage-guide.md)
- [Commands Reference](./commands-reference.md)
- [Architecture](./architecture.md)
- [Usage Scenarios](./usage-scenarios.md)
# English documentation
Product docs in English live under `docs/en/`. Chinese docs are in `docs/` (repository root of this folder).
| Document | Chinese counterpart |
| --- | --- |
| [usage-guide.md](./usage-guide.md) | [使用说明.md](../使用说明.md) |
| [commands-reference.md](./commands-reference.md) | [命令说明.md](../命令说明.md) |
| [directory-conventions.md](./directory-conventions.md) | [目录与路径约定.md](../目录与路径约定.md) |
| [architecture.md](./architecture.md) | [体系与原理.md](../体系与原理.md) |
| [usage-scenarios.md](./usage-scenarios.md) | [使用案例-模拟对话.md](../使用案例-模拟对话.md) |
| [design-principles.md](./design-principles.md) | [设计说明.md](../设计说明.md) |
[中文](../使用说明.md) | [English](./usage-guide.md)
# Flow2Spec Usage Guide
## 1. What `init` Does
Execute in the project root:
```bash
flow2spec init [cursor|claude|codex ...]
# To force reset .Knowledge from template:
flow2spec init [cursor|claude|codex ...] --reset-knowledge
```
| What `init` does | What `init` does NOT do |
|---------|----------|
| Fills in missing directories and template files | Write or update business document content |
| Writes agent config root `rules/` `skills/` | Update `includeAny` business terms |
| Aligns `manifest-routing` + `matchers/` package-level structure | Replace `f2s-*` skills for writing business semantics |
| Overwrites `.Knowledge` template files with `--reset-knowledge` | Override existing `.Knowledge` content (without this flag) |
> **`init` and "knowledge base upgrade" are two different things**: `init` only handles structural alignment — business semantics (topics content, routing terms, stock-docs/req-docs) are maintained by skills like `f2s-doc-add`, `f2s-kb-fix`, `f2s-kb-feat`, `f2s-kb-sync`, `f2s-ctx-build`, etc. For cross-version upgrades, use `f2s-kb-upgrade`. **Do not treat a standalone `init` as an upgrade command.**
### `f2s-*` and `flow2spec.config.json`: Multi-Client, Multi-Layered Reminders (Authority Remains the Disk JSON)
Before executing any **`f2s-*` skill**, the Agent needs to obtain the actual values of **`subAgent` / `switchAgentVerification` / `changeTracking`**, etc. Flow2Spec enforces this via **different mechanisms** on **different clients**; they **complement** each other and do **not** replace one another. **Authority always** resides in the project root **`flow2spec.config.json`** (call **Read** to verify against disk before proceeding into skill body).
| Client | `init` Output & Behavior | Description |
| --- | --- | --- |
| **Cursor** | `.cursor/rules/f2s-config-check.mdc` (`alwaysApply`) | Rule requires: **Read(`flow2spec.config.json`)** before entering skill body. |
| **Claude Code** | `.claude/hooks/f2s-config-inject.js` + `.claude/settings.json` (PreToolUse, `Skill` matching) | Injects a config summary when invoking **`f2s-*` Skill**; when **file is missing, JSON is invalid, or hook throws an unexpected exception**, it also injects a **notice + default semantics consistent with "file not found"** to avoid silent failure; it is still recommended to **Read** for confirmation when in doubt or after config changes. |
| **Codex** | `.codex/AGENTS.md` top-level mandatory step + `{{FLOW2SPEC_PROJECT_CONFIG}}` expansion table | **Read** is a hard requirement; the config table is a **snapshot from the last `flow2spec init`** — when it differs from disk, **Read** takes precedence. The adjacent **`.codex/topics/f2s-config-check.md`** shares its origin with the Cursor rule (including the **changeTracking** detail table); open it **as needed** — it does not need to be grouped with the three "topic long-form" examples as required reading. |
| **Knowledge Base (optional)** | When `.Knowledge/manifest-routing` hits **`config-precheck`** | `.Knowledge/topics/f2s-config-precheck.md` is a **routing summary** that links to the Codex long-form article; Flow2Spec does **not** maintain a second full copy in `.Knowledge`, nor does it replace a `Read` of the JSON. |
For field semantics and default value rules, see [Commands Reference § 6) Sub-Agent Configuration](./commands-reference.md). For the design perspective, see [Design Principles § 4.5.1](./design-principles.md).
---
## 2. Directory Conventions
Core distinction: `stock-docs/` holds solidified documents (driving knowledge routing), `req-docs/` holds technical designs (driving coding implementation); they are not interchangeable.
See [Directory Conventions](./directory-conventions.md) for the full directory description.
---
## 3. Typical Workflows
### Change Tracking and Cross-Session Continuation (Recommended)
Enable `changeTracking` per skill in `flow2spec.config.json` (each sub-field is independent):
```json
{
"changeTracking": {
"feat": true,
"fix": true,
"implement": true
}
}
```
When enabled, `f2s-kb-feat` / `f2s-kb-fix` / `f2s-implement-tech-design` automatically create a checklist under `.task/active/`, check off steps, and archive on completion. In later sessions, the `f2s-task` rule matches related wording and resumes the remaining steps — no need to re-explain context.
If **`changeTracking` is off** but you still need a `.task/` checklist temporarily, call `f2s-req-plan` explicitly (always creates a checklist, ignores config) — a **fallback**, not the default path. See [Commands Reference § f2s-req-plan](./commands-reference.md).
### New Feature Development
```
f2s-req-clarify → f2s-req-backend → implement-tech-design → f2s-kb-feat
```
When requirements are already clear, `f2s-req-clarify` can be skipped, starting directly from `f2s-req-backend`. After the technical design is written into `req-docs/`, the `implement-tech-design` rule drives coding.
### Document Ingestion
```
New architecture document ingestion: f2s-doc-arch → f2s-doc-final → f2s-ctx-build
PDF/draft ingestion: f2s-doc-final → f2s-ctx-build
```
Integrate architecture descriptions or PDF final drafts into knowledge routing (generates topics/matchers/manifest-routing). To ingest a PDF into the knowledge base, use `f2s-doc-final` then `f2s-ctx-build`. `f2s-doc-pdf` only converts a PDF to Markdown under `req-docs/` for editing; it is **not** the recommended path for "PDF straight to coding."
### Backfilling Existing Capabilities
```
f2s-doc-add # Aggregate multiple files, extract from source code / documents
f2s-kb-sync # Infer already-implemented capabilities from current session
```
Use these when code has already been shipped but the knowledge base has no record. `f2s-doc-add` is suitable for batch imports; `f2s-kb-sync` is suitable for real-time consolidation at the end of a session.
### Routine Maintenance
```
f2s-kb-fix # Fix implementation or rule errors, auto-sync knowledge base
f2s-kb-feat # Add new capabilities, auto-sync knowledge base
f2s-kb-sync # Periodic sync or backfill
f2s-kb-merge # Resolve context conflicts after Git merges
```
### Cross-Version Knowledge Base Upgrade
```
f2s-kb-migrate (Legacy V1: old knowledge base) → f2s-kb-upgrade
f2s-kb-upgrade (Current V2+: already has .Knowledge; includes npm v3.x projects, etc.; see skill step 0)
```
---
## 4. Agent Execution Configuration
Controlled via the project root `flow2spec.config.json`. For complete field rules, see [Commands Reference § 6) Sub-Agent Configuration](./commands-reference.md). **How each client is reminded to read the config, and why `Read` remains authoritative** — see **§ 1** (this § only explains **when** to toggle each switch).
**When to enable `subAgent: true`**: When the task is large (multi-module parallel implementation, batch document ingestion, large-scale migration). When enabled, each skill decides whether to actually split based on its own size threshold; tasks below the threshold are still completed within the main agent.
**When to enable `switchAgentVerification: true`**: When higher write consistency is needed (large-scale migration, critical design implementation). The trade-off is increased execution rounds; for routine maintenance, the default `false` is sufficient. Requires `subAgent: true` to trigger the "main-writes, sub-verifies" cross-check direction.
**When to enable `changeTracking.*`**: When you want each skill execution to automatically leave a resumable task checklist. Each skill sub-item is independently configurable without mutual interference:
```json
{
"changeTracking": {
"feat": true,
"fix": false,
"implement": true
}
}
```
Use `f2s-req-plan` only when all `changeTracking` sub-fields are off and you still need a checklist (see § 3 footnote).
---
## 5. Customization Suggestions
- When customizing the "implement from technical design" logic for your project, prioritize adjusting **`f2s-implement-tech-design`**: Cursor `.cursor/rules/f2s-implement-tech-design.mdc`, Claude `.claude/rules/f2s-implement-tech-design.md`; Codex uses `.codex/AGENTS.md` and associated `skills/` as the source of truth.
- Running `init` again by default only fills in missing templates and performs package-level structural alignment — it does **not** replace `f2s-*` skills for maintaining business content. To reset `.Knowledge` from the template, add `--reset-knowledge`.
---
## 6. Skill Identification
Skills are triggered by matching `name` and `description`. Files are located under `config-root/skills/*/SKILL.md`.
---
## 7. Related Documents
- [Commands Reference](./commands-reference.md)
- [Directory Conventions](./directory-conventions.md)
- [Architecture](./architecture.md)
- [Usage Scenarios](./usage-scenarios.md)
[中文](../使用案例-模拟对话.md) | [English](./usage-scenarios.md)
# Flow2Spec Usage Scenarios (Simulated Dialogues)
The following examples revolve around the same e-commerce project, covering the full pipeline from requirements clarification through post-launch maintenance.
**Prerequisite**: The project has executed `flow2spec init`, and `flow2spec.config.json` uses the default configuration (`subAgent: false`). `f2s-*` skills do not modify the configuration root `rules/` or `skills/` files.
---
## Scenario 1: New Requirement -> Clarification -> Technical Design
**You**
> /f2s-req-clarify The product team provided a refund requirement doc, but it does not specify whether partial refunds and full refunds go through the same API, or whether points should be reversed after a successful refund. The document is at `.Knowledge/req-docs/refund-requirements-v1.md`.
**Agent**
> I have read the requirements document. There are a few points that need clarification:
>
> 1. Do partial refunds and full refunds reuse the same endpoint, differentiated by the `amount` field, or should they be two separate endpoints?
> 2. Should points be reversed after a successful refund? If the reversal fails, should it block the refund flow?
> 3. Is the refund processed synchronously or asynchronously (T+1)?
> 4. Is there a seller-side review step?
**You**
> 1. Same endpoint, differentiated by amount; 2. Points are reversed; failure does not block the flow, retry asynchronously; 3. Asynchronous T+1; 4. No review needed.
**Agent**
> Clarification complete. Run `/f2s-req-backend` to produce the technical design.
**You**
> /f2s-req-backend
**Agent**
> Generated `.Knowledge/req-docs/refund-tech-design.md`, which includes:
> - API design: `POST /refunds`, `amount` field distinguishes full / partial refunds
> - State machine: `PENDING -> SUCCESS / FAILED`
> - Points reversal: asynchronous queue, failures go to dead letter queue, alert for manual handling
> - Error code list
>
> Next step: say "implement according to `.Knowledge/req-docs/refund-tech-design.md`" to trigger coding.
---
## Scenario 2: Architectural Documentation into Knowledge Base
**You**
> /f2s-doc-arch Help me draft an order service architecture document, focusing on the creation flow, payment callback, idempotency, and message delivery. The code is in `src/order` and `src/payment`.
**Agent**
> Scanned the relevant directories. Generated `.Knowledge/stock-docs/order-service-architecture-draft.md`, which includes:
> - Module boundaries and dependencies
> - Creation flow sequence diagram
> - Payment callback idempotency mechanism (based on the `payment_callback_log` table)
> - Message delivery retry strategy
>
> Confirm it looks good, then run `/f2s-doc-final` to normalize the format.
**You**
> /f2s-doc-final .Knowledge/stock-docs/order-service-architecture-draft.md
**Agent**
> Generated `.Knowledge/stock-docs/order-service-architecture-final.md`, formatted according to the final-draft template, with placeholders for items still to be filled in.
**You**
> f2s-ctx-build .Knowledge/stock-docs/order-service-architecture-final.md
**Agent**
> Knowledge base sync complete:
> - Added `.Knowledge/topics/order-service.md`
> - Updated `.Knowledge/manifest-routing.json` (added routing rule)
> - Generated `.Knowledge/matchers/order-service.json` (keywords: order creation, payment callback, idempotency, message delivery)
> - Updated `.Knowledge/index.md`
>
> Future tasks related to the order service will automatically hit this topic.
---
## Scenario 3: Implementation from Technical Design
**You**
> Implement according to `.Knowledge/req-docs/refund-tech-design.md`. Only modify `src/refund/`; do not touch the payment module.
**Agent**
> I have read the design document. Task list for implementation:
>
> 1. Create `RefundController` with `POST /refunds`
> 2. Create `RefundService` with state machine transition logic
> 3. Create `RefundRepository` for the `refund` table
> 4. Create `PointRollbackProducer` to send rollback messages to the points queue
> 5. Unit tests covering state machine transitions
>
> Before proceeding, I need to confirm:
> - Does the `refund` table already exist, or do I need to generate a migration?
> - What is the points queue topic name?
**You**
> The table already exists; no migration needed. The topic is `point-rollback-events`.
**Agent**
> Completed all 5 tasks above, all within `src/refund/`. Did not touch `src/payment/`.
>
> **Requires manual action**:
> - Consumer side for `point-rollback-events` (on the points service side)
> - Dead letter monitoring and alerting rule configuration
>
> Recommend running `/f2s-kb-feat` to sync this new capability into the knowledge base.
---
## Scenario 4: Post-Implementation Knowledge Base Recording
**You**
> /f2s-kb-sync The refund feature has gone live. Help me record the payment failure retry queue naming, dead letter table fields, and monitoring alerting criteria into the knowledge base. Give me an outline first so I can confirm before you write.
**Agent**
> Knowledge base update outline (pending confirmation):
>
> **Update topic**: `order-service` (already exists)
>
> - Add "Payment Failure Retry Mechanism": queue name `payment-retry-queue`, max retries 3, intervals 30s / 120s / 300s
> - Add "Dead Letter Table": table name `payment_dead_letter`, fields `order_id / error_code / retry_count / created_at`
> - Add "Monitoring Criteria": alert threshold `retry_count >= 3`, notification channel DingTalk
>
> Confirm to write, or let me know what needs to be changed.
**You**
> Confirm, go ahead and write.
**Agent**
> Updated `.Knowledge/topics/order-service.md`. `manifest-routing` unchanged (topic already exists).
---
## Scenario 5: Non-compliant Implementation Found, Fix and Sync Knowledge Base
**You**
> /f2s-kb-fix `RefundService` directly calls `new RestTemplate()`, which violates the Spring Bean injection convention.
**Agent**
> Fixed: Line 34 of `RefundService.java` changed to constructor injection; `RefundConfig` supplemented with `@Bean` declaration.
>
> Knowledge base synced: the "HTTP Client Conventions" section in `.Knowledge/stock-docs/` has been updated, noting that `RestTemplate` must be injected as a Bean, and direct instantiation is prohibited.
---
## Scenario 6: Knowledge Base Conflicts After Git Merge
**You**
> /f2s-kb-merge `.Knowledge/index.md` and `.Knowledge/stock-docs/order-service-architecture-final.md` have conflict markers after the merge. I have already resolved the conflicts in the business code manually.
**Agent**
> Scanned the conflict markers in both files:
>
> - `index.md`: 2 conflicts, both in topic description fields. Took the HEAD version (newer content). Resolved automatically.
> - `order-service-architecture-final.md`: 1 conflict. The "monitoring alert threshold" differs between branches (3 vs. 5). Please confirm which one to keep.
**You**
> Use 3.
**Agent**
> All conflict markers have been cleaned up per your confirmation. The files are ready to commit.
---
## Related Documentation
- [Usage Guide](./usage-guide.md)
- [Commands Reference](./commands-reference.md)
- [Directory Conventions](./directory-conventions.md)
- [Architecture](./architecture.md)
# 体系与原理
[English](./en/architecture.md)
Flow2Spec 的目标是把"业务知识沉淀"与"Agent 能力加载"拆开,并在仓库里用 **Memory Coding(记忆编码)** 把「要记住的东西」落盘为可 diff、可评审的 Git 资产。
- **知识环**(`.Knowledge/`):业务文档与机读路由(见下文多层结构)
- **任务环**(`.task/`):跨会话续作清单
- **规则环**(各工具 `rules` / `AGENTS.md`):规定 Agent **怎么读、怎么做**
- **技能环**(`f2s-*`):维护知识、触发流程
> Flow2Spec ≠ 只有知识库;上述四环同属 Memory Coding,下文「两层结构」描述的是**知识环 vs 工具侧执行落点**的生命周期分工。
---
## 1. Memory Coding 与仓内四环
**Memory Coding**:把必须长期记住的上下文**编码进可提交仓库**——不押在模型私有 Memory、不只在聊天里重复,也不靠全仓向量概率猜。
仓内拆成 **四环**(勿说成「三环」把规则与技能合并):
| 环 | 落点 | 记什么 |
| --- | --- | --- |
| **知识环** | `.Knowledge/` | 路由、主题、存量/需求文档(见 §2 多层) |
| **任务环** | `.task/` | `todo.json`、checklist、用户代办 |
| **规则环** | `.cursor/.claude/.codex` 下 rules、`AGENTS.md` | 读取顺序、缺口闸门、实现约束 |
| **技能环** | 配置根 `skills/*/SKILL.md` | `f2s-kb-feat/fix/sync` 等维护与触发 |
与「两层结构」的关系:**知识环**对应「随项目走」的知识层;**规则环 + 技能环**落在各工具配置根,随工具升级迭代;**任务环**与 `.Knowledge/` 并列于仓内,不属于 `.Knowledge/` 目录。
---
## 2. 知识环内的多层记忆结构
`.Knowledge/` 不是扁平「一堆 Markdown」,而是 **横读(渐进式路由)+ 纵链(主题依赖)** 的多层记忆:
| 层级 | 路径 / 机制 | 记什么 | 典型读法 |
| --- | --- | --- | --- |
| **L0 路由索引** | `manifest-routing.json` | task→topic、`topicDependencies`、`topicPaths` | 会话首读(机读事实源) |
| **L1 关键词分片** | `matchers/<id>.json` | `includeAny` 触发词 | **match**:只打开命中的一个分片 |
| **L2 主题摘要** | `topics/<topic>.md` | 硬约束摘要、边界、下一步指针 | **expand**:拉齐依赖主题 |
| **L3 长文档** | `stock-docs/`、`req-docs/` | 架构终稿、技术方案全文 | 按需下钻背景 |
| **纵链(横切)** | `topicDependencies` | 通用约定 → 子域 → 白名单 → 本域细则 | **expand** 时按依赖顺序叠层 |
**渐进式读取**(`match → expand → verify → act`)作用在 L0–L2(必要时再到 L3):先收窄入口,再展开依赖与缺口检查,最后才改代码。主题级依赖挂一次、所有任务共享,避免每个任务重复声明前置约束。
人读导航:`index.md` 仅作语义边界校验,**不**替代 `manifest-routing` 机读链。
---
## 3. 知识层与执行层(两层结构)
| 层 | 位置 | 作用 |
| --- | --- | --- |
| 知识层(知识环) | `.Knowledge/` | 保存业务文档、索引、路由(§2 多层) |
| 执行层(规则环 + 技能环) | `.cursor/.claude/.codex` | 保存规则与技能入口 |
---
## 4. 渐进式读取
统一建议顺序:
1. `.Knowledge/manifest-routing.json`
2. `.Knowledge/matchers/<matcher>.json`(按需:由 `manifest-routing.taskToTopicRules[].matcherPath` 直链定位)
3. `.Knowledge/index.md`
4. 命中的 `stock-docs` / `req-docs` 文档
5. 必要时下钻源码
读取后执行 `match → expand → verify → act` 四步流水线:命中主候选后展开依赖主题、缺口检查,置信度足够时才执行;低置信度先澄清。
同时由配置根入口(Flow2Spec 包规则:`f2s-flow2spec-unified-entry.mdc` / `f2s-flow2spec-unified-entry.md`;旧版业务仓库常见为 `main.md(c)`;以及 `AGENTS.md`)约束加载行为。
其中 Codex 不读取 `rules/` 目录,统一通过 `.codex/AGENTS.md` + `skills/` 承载执行约束。
---
## 5. 关键链路
- 文档沉淀链:`f2s-doc-arch` → `f2s-doc-final` → `f2s-ctx-build`
- 实现链:`.Knowledge/req-docs/*.md` → `implement-tech-design` → 代码
- 维护链:`f2s-kb-fix` / `f2s-kb-feat` / `f2s-kb-sync` / `f2s-kb-merge`
- 需求规划链:`f2s-req-plan`(规划 + 实现,始终创建任务清单)
- 变更追踪链:`changeTracking.*` 配置 → `f2s-task` 规则(自动)→ `.task/` 任务清单 → 跨会话续作
- 包模板/路由形态与配置根对齐:`f2s-kb-upgrade`(**勿**将单独 `flow2spec init` 等同于「知识库升级」);旧库结构迁入 `.Knowledge`:`f2s-kb-migrate`
---
## 6. Agent 执行模型
Flow2Spec 通过项目根 `flow2spec.config.json` 的 `subAgent`、`switchAgentVerification` 两个字段控制执行行为。
**Agent 如何读到上述真值**:多端提示 + **Read** 权威,见 [使用说明 § 一(唯一详表)](./使用说明.md);设计归纳见 [设计说明 § 四、5.1](./设计说明.md)。
### 6.1 主/子 Agent 职责划分原则
**`subAgent: false`(默认)**:全部 `f2s-*` 技能在主 agent 内顺序完成,无并行拆分。
**`subAgent: true`**:达到技能正文约定的规模门槛时,允许拆分子 agent 并行处理。职责边界如下:
| 角色 | 职责边界 |
|------|----------|
| 主 agent | 统筹规划、确定任务粒度与分配策略、汇总子 agent 输出、校验跨单元一致性、最终落盘 |
| 子 agent | 处理指定单元(模块/文档/主题),按约定格式输出结果,不跨单元决策 |
子 agent 的拆分边界由各 `f2s-*` 技能正文逐步约定(如模块数、文档数、代码行数等门槛),**当前尚未在模板层给出统一阶段表**,以技能正文为准。
### 6.2 验证归属原则
**默认(谁落盘谁验)**:落盘或变更后的验证在落盘侧 agent 内完成。子 agent 落盘则子 agent 自验,主 agent 落盘则主 agent 自验。
**交叉验证(`switchAgentVerification: true`)**:由对方 agent 承担验证,适用于需要更高置信度的场景。启用条件必须**同时满足**:
1. 配置 `switchAgentVerification: true`
2. 当前执行的 `f2s-*` 技能正文**明确写出**该步骤依赖本项
交叉验证规则:
| 落盘方 | 验证方 | 前提条件 |
|--------|--------|----------|
| 子 agent 落盘 | 主 agent 验证 | 无额外条件 |
| 主 agent 落盘 | 子 agent 验证 | 须 `subAgent: true` 且实际已拆出子任务;否则仍由主 agent 自验 |
设计意图:交叉验证引入外部视角,降低落盘侧的自验盲区,但增加执行开销,因此设为显式 opt-in 而非默认行为。
### 6.3 变更追踪(changeTracking)
`changeTracking` 是独立于 `subAgent` / `switchAgentVerification` 的第三个维度,控制技能执行时是否自动创建可跨会话续作的任务清单。
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
- 各技能子项独立控制,互不影响
- 开启后:技能执行前自动检查 `.task/todo.json`,创建或续接任务;完成后自动归档
- 跨会话:新会话描述相关内容,`f2s-task` 规则(`alwaysApply`)关键词匹配命中后自动加载剩余清单和对应技能上下文
- `f2s-req-plan` 不受此配置约束,始终创建任务清单
---
## 7. 设计收益
1. 跨工具共享同一业务知识源
2. 不破坏 Claude/Cursor/Codex 的规则加载习惯
3. 通过 `manifest-routing` + `matcherPath` 分片(`matchers/*.json`)控制任务路由与依赖,减少误读与全量扫描
4. 主/子 agent 职责边界清晰,主 agent 始终持有全局视图,子 agent 专注单元处理,汇总一致性由主 agent 保证
5. 验证归属可配置:默认落盘侧自验保持低开销,交叉验证按需启用提升关键场景置信度
---
## 8. 相关文档
- [使用说明](./使用说明.md)
- [命令说明](./命令说明.md)
- [目录与路径约定](./目录与路径约定.md)
- [使用案例-模拟对话](./使用案例-模拟对话.md)
# Flow2Spec 使用案例(模拟对话)
[English](./en/usage-scenarios.md)
以下示例围绕同一个电商项目展开,贯穿从需求澄清到上线后维护的完整流程。
**前提**:项目已执行 `flow2spec init`,`flow2spec.config.json` 使用默认配置(`subAgent: false`)。`f2s-*` 技能不改动配置根 `rules/`、`skills/` 文件。
---
## 场景一:新需求 → 澄清 → 技术方案
**你**
> /f2s-req-clarify 产品给了一份退款需求,但没说清楚部分退款和全额退款走不走同一接口,退款成功后积分是否回撤。文档在 `.Knowledge/req-docs/退款需求v1.md`。
**Agent**
> 已读取需求文档,有几个点需要确认:
>
> 1. 部分退款与全额退款是否复用同一接口,通过 `amount` 区分,还是拆成两个端点?
> 2. 退款成功后积分是否回撤?回撤失败是否阻断退款流程?
> 3. 退款申请是同步到账还是异步(T+1)?
> 4. 卖家侧是否需要审核步骤?
**你**
> 1. 同一接口用 amount 区分;2. 积分回撤,失败不阻断,异步重试;3. 异步 T+1;4. 不需要审核。
**Agent**
> 澄清完成。执行 `/f2s-req-backend` 输出技术方案。
**你**
> /f2s-req-backend
**Agent**
> 已生成 `.Knowledge/req-docs/退款功能_技术方案.md`,包含:
> - 接口设计:`POST /refunds`,`amount` 字段区分全额/部分
> - 状态机:`PENDING → SUCCESS / FAILED`
> - 积分回撤:异步队列,失败进死信,告警人工处理
> - 错误码清单
>
> 下一步:说"按方案实现 `.Knowledge/req-docs/退款功能_技术方案.md`"触发编码。
---
## 场景二:架构说明沉淀进知识库
**你**
> /f2s-doc-arch 帮我出一份订单服务架构初稿,重点看创建流、支付回调、幂等与消息投递;代码在 `src/order`、`src/payment`。
**Agent**
> 已扫描相关目录,生成 `.Knowledge/stock-docs/订单服务架构说明_初稿.md`,包含:
> - 模块边界与依赖关系
> - 创建流时序
> - 支付回调幂等机制(基于 `payment_callback_log` 表)
> - 消息投递重试策略
>
> 确认无误后执行 `/f2s-doc-final` 规范化格式。
**你**
> /f2s-doc-final .Knowledge/stock-docs/订单服务架构说明_初稿.md
**Agent**
> 已生成 `.Knowledge/stock-docs/订单服务架构说明_终稿.md`,按终稿模板整理,标注了待补充项。
**你**
> f2s-ctx-build .Knowledge/stock-docs/订单服务架构说明_终稿.md
**Agent**
> 已完成知识库同步:
> - 新增 `.Knowledge/topics/order-service.md`
> - 更新 `.Knowledge/manifest-routing.json`(新增路由规则)
> - 生成 `.Knowledge/matchers/order-service.json`(关键词:订单创建、支付回调、幂等、消息投递)
> - 更新 `.Knowledge/index.md`
>
> 后续与订单服务相关的任务会自动命中此主题。
---
## 场景三:按技术方案实现
**你**
> 按方案实现:`.Knowledge/req-docs/退款功能_技术方案.md`,只改 `src/refund/`,不要动支付模块。
**Agent**
> 已读取方案。实现任务列表:
>
> 1. 新建 `RefundController`,实现 `POST /refunds`
> 2. 新建 `RefundService`,含状态机流转逻辑
> 3. 新建 `RefundRepository`,对应 `refund` 表
> 4. 新建 `PointRollbackProducer`,向积分队列发送回撤消息
> 5. 单元测试覆盖状态机流转
>
> 实现前确认:
> - `refund` 表是否已存在,还是需要生成 migration?
> - 积分队列 Topic 名称是什么?
**你**
> 表已存在,不用 migration;Topic 是 `point-rollback-events`。
**Agent**
> 已完成以上 5 项,均在 `src/refund/` 内,未触碰 `src/payment/`。
>
> **待完成(需人工)**:
> - `point-rollback-events` 消费端(积分服务侧)
> - 死信监控告警规则配置
>
> 建议执行 `/f2s-kb-feat` 将本次新增能力同步进知识库。
---
## 场景四:实现后补录知识库
**你**
> /f2s-kb-sync 退款功能上线了,帮我把支付失败重试队列命名、死信表字段、监控告警口径沉淀进知识库,先给大纲我确认再写。
**Agent**
> 知识库更新大纲(待确认):
>
> **更新主题**:`order-service`(已有)
>
> - 新增「支付失败重试机制」:队列名 `payment-retry-queue`,最大重试 3 次,间隔 30s / 120s / 300s
> - 新增「死信表」:表名 `payment_dead_letter`,字段 `order_id / error_code / retry_count / created_at`
> - 新增「监控口径」:告警阈值 `retry_count >= 3`,通知渠道 DingTalk
>
> 确认后写入,或告诉我需要修改的地方。
**你**
> 确认写入。
**Agent**
> 已更新 `.Knowledge/topics/order-service.md`,`manifest-routing` 未变动(主题已存在)。
---
## 场景五:发现违规实现,修复并同步知识库
**你**
> /f2s-kb-fix `RefundService` 里直接 `new RestTemplate()` 了,违反 Spring Bean 注入约定。
**Agent**
> 已修复:`RefundService.java` 第 34 行改为构造注入,`RefundConfig` 补充 `@Bean` 声明。
>
> 同步知识库:`.Knowledge/stock-docs/` 中「HTTP 客户端约定」节更新,注明 `RestTemplate` 必须通过 Bean 注入,禁止直接实例化。
---
## 场景六:Git 合并后知识库冲突
**你**
> /f2s-kb-merge `.Knowledge/index.md` 和 `.Knowledge/stock-docs/订单服务架构说明_终稿.md` 合并后有冲突标记,业务代码我已手动合完。
**Agent**
> 已扫描两个文件的冲突标记:
>
> - `index.md`:2 处冲突,均为主题描述字段,取 HEAD 版本(内容较新),已自动处理。
> - `订单服务架构说明_终稿.md`:1 处冲突,「监控告警阈值」两个分支不同(3 次 vs 5 次),需你确认。
**你**
> 用 3 次。
**Agent**
> 已按确认结果清理全部冲突标记,文件可提交。
---
## 相关文档
- [使用说明](./使用说明.md)
- [命令说明](./命令说明.md)
- [目录与路径约定](./目录与路径约定.md)
- [体系与原理](./体系与原理.md)
# Flow2Spec 使用说明
[English](./en/usage-guide.md)
## 一、init 做了什么
在业务仓库根执行:
```bash
flow2spec init [cursor|claude|codex ...]
# 需要强制重置 .Knowledge 到模板时:
flow2spec init [cursor|claude|codex ...] --reset-knowledge
```
| init 做 | init 不做 |
|---------|----------|
| 补齐缺失的目录与模板文件 | 撰写或更新业务文档内容 |
| 落盘各 agent 配置根 `rules/` `skills/` | 更新 `includeAny` 业务词条 |
| `manifest-routing` + `matchers/` 包级结构对齐 | 替代 `f2s-*` 技能对业务语义的书写 |
| `--reset-knowledge` 时强制覆盖 `.Knowledge` 模板文件 | (不加此参数时)覆盖已有 `.Knowledge` 内容 |
> **`init` 与「知识库升级」是两件事**:`init` 只做结构补齐,业务语义(topics 内容、路由词条、stock-docs/req-docs)由 `f2s-doc-add`、`f2s-kb-fix`、`f2s-kb-feat`、`f2s-kb-sync`、`f2s-ctx-build` 等技能维护。跨版本升级用 `f2s-kb-upgrade`,**不要把单独 `init` 当作升级命令**。
### `f2s-*` 与 `flow2spec.config.json`:多端多重提示(权威仍为磁盘 JSON)
执行任意 **`f2s-*` 技能**前,需要让 Agent 拿到 **`subAgent` / `switchAgentVerification` / `changeTracking`** 等实际值。Flow2Spec 在 **不同客户端** 用 **不同机制** 强化这一点;它们彼此**补充**,**不**互相替代,**权威始终**是项目根 **`flow2spec.config.json`**(须用 **Read** 与磁盘一致后再进技能正文)。
| 端 | `init` 落盘与行为 | 说明 |
| --- | --- | --- |
| **Cursor** | `.cursor/rules/f2s-config-check.mdc`(`alwaysApply`) | 规则要求:技能正文前先 **Read(`flow2spec.config.json`)**。 |
| **Claude Code** | `.claude/hooks/f2s-config-inject.js` + `.claude/settings.json`(PreToolUse,`Skill` 匹配) | 在调用 **`f2s-*` Skill** 时注入配置摘要;**文件缺失、JSON 无效或 hook 未预期异常**时也会注入**说明 + 与「文件不存在」一致的默认语义**,避免静默;仍建议在存疑或刚改过配置时 **Read** 核对。 |
| **Codex** | `.codex/AGENTS.md` 顶部强制步骤 + `{{FLOW2SPEC_PROJECT_CONFIG}}` 展开表 | **Read** 为硬要求;配置表为 **最近一次 `flow2spec init` 的快照**,与磁盘不一致时以 **Read** 为准。同目录 **`.codex/topics/f2s-config-check.md`** 与 Cursor 规则同源(含 **changeTracking** 细表),**按需**打开即可,不必与「专题长文」三条示例并列必读。 |
| **知识库(可选)** | `.Knowledge/manifest-routing` 命中 **`config-precheck`** 时 | `.Knowledge/topics/f2s-config-precheck.md` 为**路由摘要**,链向 Codex 长文;**不**在 `.Knowledge` 再维护第二份全文,也**不**替代 Read JSON。 |
字段语义与默认值规则见 [命令说明 § 6) 子 Agent 配置说明](./命令说明.md)。设计视角见 [设计说明 § 四、5.1](./设计说明.md);口述见 [Flow2Spec-演讲稿 Slide 13b](./Flow2Spec-演讲稿.md)。
---
## 二、目录约定
核心区分:`stock-docs/` 放沉淀文档(驱动知识路由),`req-docs/` 放技术方案(驱动编码实现),两者不互换。
完整目录说明见 [目录与路径约定](./目录与路径约定.md)。
---
## 三、典型工作场景
### 变更追踪与跨会话续作(推荐)
在 `flow2spec.config.json` 按技能开启 `changeTracking`(各子项独立):
```json
{
"changeTracking": {
"feat": true,
"fix": true,
"implement": true
}
}
```
开启后,`f2s-kb-feat` / `f2s-kb-fix` / `f2s-implement-tech-design` 执行时会在 `.task/active/` 自动创建任务清单,逐步勾选,完成后归档。下次会话描述相关内容时,`f2s-task` 规则会匹配并加载剩余步骤,无需重复交代上下文。
若你**关闭了** `changeTracking` 但仍临时需要 `.task/` 清单,可显式调用 `f2s-req-plan`(不读配置、始终建清单)——这是兜底用法,非常规主路径;详见 [命令说明 § f2s-req-plan](./命令说明.md)。
### 新需求开发
```
f2s-req-clarify → f2s-req-backend → implement-tech-design → f2s-kb-feat
```
需求已明确时可跳过 `f2s-req-clarify`,直接从 `f2s-req-backend` 开始。技术方案落入 `req-docs/` 后,由 `implement-tech-design` 规则驱动编码。
### 文档沉淀
```
新增架构文档沉淀:f2s-doc-arch → f2s-doc-final → f2s-ctx-build
PDF/初稿沉淀: f2s-doc-final → f2s-ctx-build
```
把架构说明或 PDF 终稿纳入知识路由(生成 topics/matchers/manifest-routing)。若仅有 PDF 且要入库,先用 `f2s-doc-final` 转为终稿再 `f2s-ctx-build`;`f2s-doc-pdf` 仅把 PDF 转为 `req-docs/` 下的 Markdown 便于编辑,**不**作为「PDF 直驱编码」的推荐路径。
### 存量能力补录
```
f2s-doc-add # 多文件聚合,从源码/文档提取
f2s-kb-sync # 从当前会话推断已实现能力
```
代码已落地但知识库没有记录时使用。`f2s-doc-add` 适合批量导入,`f2s-kb-sync` 适合会话结束时的即时沉淀。
### 日常维护
```
f2s-kb-fix # 修复实现或规则错误,自动同步知识库
f2s-kb-feat # 新增能力,自动同步知识库
f2s-kb-sync # 定期同步或补录
f2s-kb-merge # Git 合并后解决上下文冲突
```
### 知识库跨版本升级
```
f2s-kb-migrate(流程 V1:旧库)→ f2s-kb-upgrade
f2s-kb-upgrade(流程现行库 V2+:已有 .Knowledge;含 npm v3.x 等,见技能步骤 0)
```
---
## 四、Agent 执行配置
通过项目根 `flow2spec.config.json` 控制,字段完整规则见 [命令说明 § 6) 子 Agent 配置说明](./命令说明.md)。**各端如何被提示读到配置、为何仍以 Read 为权威**见 **§ 一**(本 § 仅说明**何时**打开各开关)。
**何时开启 `subAgent: true`**:任务规模较大时(多模块并行实现、批量文档入库、大规模迁移)。开启后各技能按自身规模门槛决定是否实际拆分,未达门槛的仍在主 agent 内完成。
**何时开启 `switchAgentVerification: true`**:需要更高落盘一致性时(大规模迁移、重要方案实现)。代价是增加执行轮次;常规维护场景默认 `false` 足够。须搭配 `subAgent: true` 才能触发"主落子验"方向的交叉。
**何时开启 `changeTracking.*`**:希望每次技能执行自动留下可续作的任务清单时。各技能子项独立配置,互不影响:
```json
{
"changeTracking": {
"feat": true,
"fix": false,
"implement": true
}
}
```
`changeTracking` 全关且仍要任务清单时,再考虑 `f2s-req-plan`(见 § 三「变更追踪」脚注)。
---
## 五、规则改造建议
- 项目特化「按技术方案实现」逻辑时,优先调整 **`f2s-implement-tech-design`**:Cursor `.cursor/rules/f2s-implement-tech-design.mdc`,Claude `.claude/rules/f2s-implement-tech-design.md`;Codex 以 `.codex/AGENTS.md` 与相关 `skills/` 为准
- 再次 `init` 默认仅补齐缺失模板并做包级结构对齐,**不**替代 `f2s-*` 对业务内容的维护;需用模板重置 `.Knowledge` 时加 `--reset-knowledge`
---
## 六、技能标识
技能以 `name` 与 `description` 匹配触发,文件位于 `配置根/skills/*/SKILL.md`。
---
## 七、相关文档
- [命令说明](./命令说明.md)
- [目录与路径约定](./目录与路径约定.md)
- [体系与原理](./体系与原理.md)
- [使用案例-模拟对话](./使用案例-模拟对话.md)
# 工作流与技能说明
[English](./en/commands-reference.md)
## 1) 文档沉淀(stock-docs 链路)
### `f2s-doc-arch`
**作用**:根据用户说明或扫描代码,生成项目架构说明初稿。无固定格式要求,描述清楚系统结构、模块关系、关键决策即可。
**工作原理**:以「inventory 驱动扫描」为核心——先由主 agent 产出模块清单(inventory)与扫描契约(读哪些入口、关注哪些维度),再按 inventory 执行只读代码扫描,最后将扫描结果聚合为人可读的架构初稿落盘 `stock-docs/`。整个流程不改代码,仅做「代码→文档」的单向提取。
**使用场景**:
- 新项目需要架构文档
- 存量项目需要补充架构说明
- 系统重构后更新架构描述
**关联关系**:
- **前置**:无
- **后续**:`f2s-doc-final`(规范化终稿)或直接用于 `f2s-ctx-build`
- **输出**:`.Knowledge/stock-docs/<架构说明>_初稿.md`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内扫描代码并生成
- `subAgent: true`:默认走 **B 模式**(主产出 inventory + 扫描契约 → 子 agent 并行只读扫表 → 主合并落盘);满足以下任一条件时升级为 **C 模式**(多轮纠偏):多 workspace / monorepo、源路径 > 20 条、首轮子表有矛盾或空洞、多源叙述冲突严重
**职责划分**:
| 角色 | 职责 |
| --------------- | ------------------------------------------------------------------------------------------ |
| 主 agent | 产出 inventory(入口 + 核心模块名)与扫描契约,汇总子 agent 交付,落盘 stock-docs 初稿 |
| 子 agent(B/C 模式) | 按主手写 inventory 并行只读扫描,按统一 YAML schema 交付(`source / scope / cross_refs / pending`),不得自行裁剪范围 |
---
### `f2s-doc-final`
**作用**:将 PDF 技术方案或初稿文档转为《终稿模版》规范格式,统一文档结构,便于后续进入知识库。
**工作原理**:将非结构化或格式各异的文档(PDF/初稿)对照内置终稿模版进行格式归一化:提取核心概念表、业务规则、关键流程、配置与错误处理等标准章节,补齐缺失段落标记,最终输出格式统一的 `_终稿.md`。终稿是 `f2s-ctx-build` 的标准输入物,确保知识库入口的结构一致性。
**使用场景**:
- PDF 技术方案需要转为 Markdown
- 初稿需要规范化以便沉淀
- 外部文档需要纳入 Flow2Spec 管理
**关联关系**:
- **前置**:PDF 文档或初稿文档
- **后续**:`f2s-ctx-build`(终稿入库)
- **输出**:`.Knowledge/stock-docs/<文档>_终稿.md`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成全流程
- `subAgent: true`:PDF > 50 页或 > 5MB 时,可拆子做套模版与排版草稿;子不追问用户、不补写流程说明、不宣称终稿合规;主 agent 识别格式缺口并定稿验收
**职责划分**:
| 角色 | 职责 |
| ------- | --------------------- |
| 主 agent | 识别格式缺口、对照模版与澄清文档验收定稿 |
| 子 agent | 套模版与排版草稿,不追问用户、不写流程说明 |
---
### `f2s-ctx-build`
**作用**:将 `stock-docs/` 中的沉淀文档(架构、终稿)同步到知识库路由系统,生成/更新主题文件、索引、manifest-routing、matchers。
**工作原理**:以终稿文档为输入,执行「文档→路由」的三步映射:① 从终稿中提取能力主题与关键词;② 生成 `topics/<topic>.md`(路由摘要,含执行边界与下一步指针)和 `matchers/<id>.json`(机读匹配词 `includeAny`);③ 在 `manifest-routing.json` 注册 task→topic 映射规则,并更新 `index.md` 人读导航。完成后,任务路由引擎即可通过关键词命中该主题。
**使用场景**:
- 终稿文档完成后,需要让知识库"知道"这些文档
- 新增业务领域,需要建立路由映射
- 文档内容更新后,同步更新知识库索引
**关联关系**:
- **前置**:`f2s-doc-arch`、`f2s-doc-final` 或直接编写的终稿
- **后续**:无(入库完成后可直接使用)
- **输入**:`.Knowledge/stock-docs/*.md`
- **输出**:
- `.Knowledge/topics/<topic>.md`
- `.Knowledge/index.md`
- `.Knowledge/manifest-routing.json`
- `.Knowledge/matchers/*.json`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内顺序处理各文档
- `subAgent: true`:改动超过阈值(新增/修改主题 > 2 个 OR 新增 matcher > 1 个 OR 涉及跨主题批量引用调整)时拆子;子A 只写 topics/、子B 只写 matchers/;主 agent 单点编辑 manifest-routing.json 和 index.md,子 agent 不跨边界落盘
**职责划分**:
| 角色 | 职责 |
| ----------------- | ------------------------------------------ |
| 主 agent | 单点落盘 manifest-routing.json 和 index.md,整体验收 |
| 子 agent(topics) | 仅写 topics/ 目录下的主题文件,不触碰 manifest 和 index |
| 子 agent(matchers) | 仅写 matchers/ 目录下的分片文件,不触碰 manifest 和 index |
---
### `f2s-doc-add`
**作用**:将已落地能力(多文件聚合)解析进知识库。适用于代码已实现但缺少文档,或已有多个文档需要统一入库的场景。
**工作原理**:从多个分散的源文件(代码、配置、散落文档)中聚合提取能力描述,走完整的「初稿→终稿→topics/index/manifest」沉淀链路。与 `f2s-ctx-build` 的区别在于输入:`ctx-build` 从已有的单份终稿驱动,`doc-add` 从多个散落源聚合后再走同一管线。本质是补齐「有实现无文档」的缺口。
**使用场景**:
- 存量代码需要补录知识库
- 多份相关文档需要聚合入库
- 第三方文档批量导入
**关联关系**:
- **前置**:无(可直接触发)
- **后续**:无(入库完成即结束)
- **流程**:初稿 → 终稿 → topics/index/manifest
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内顺序处理
- `subAgent: true`:满足以下任一阈值时启用,默认走 **B 模式**(主产出 inventory → 子并行只读按 schema 填表 → 主合并落盘);多 workspace / monorepo、首轮子表矛盾或空洞、多源叙述冲突严重时升级 **C 模式**(多轮纠偏)
- 阈值:输入路径 ≥ 5 条 OR 单源 > 3000 行 OR 多路径总量 > 10000 行
**职责划分**:
| 角色 | 职责 |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| 主 agent | 产出 inventory 与扫描契约,汇总子表,落盘 topics/index/manifest |
| 子 agent(B/C 模式) | 按主手写 inventory 执行只读扫描,按 schema 交表(`source / scope / capabilities / cross_refs / pending`);不得自行裁剪范围、不写 manifest 和 index、不宣布"已进知识库" |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 落盘的 topic 文件 → 主 agent 校验路由映射完整性与关键词覆盖
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-ctx-rm`
**作用**:按 stock-docs 文档删除对应的知识主题与索引映射。仅删除知识库中的引用关系,不删除源文档本身。
**工作原理**:`f2s-ctx-build` 的逆操作——给定一份 `stock-docs` 文档路径,定位其在 `manifest-routing.json` 中的 task→topic 规则、对应的 `matchers/<id>.json` 分片、`topics/<topic>.md` 文件以及 `index.md` 中的行项,逐一清除引用。若删除后某 topic 无任何 task 引用,则移除该 topic 文件。源文档本身保留不动,用户可自行决定是否物理删除。
**使用场景**:
- 文档已废弃,需要从知识路由中移除
- 误入库的文档需要撤销路由映射
- 文档合并后清理旧映射
**关联关系**:
- **前置**:已入库的 stock-docs 文档
- **后续**:无
- **注意**:只删路由映射,不删源文档
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内全流程执行(单点删除拆子收益低)
- `subAgent: true`:仅当**批量删除 ≥ 5 个主题**时才拆子执行删除与清引用;主 agent 必控范围确认与 fallbackTopic 重指;manifest-routing.json 与 index.md 恒由主落盘
---
### `f2s-doc-pdf`
**作用**:将 PDF 技术方案转为 Markdown 格式,保存到 `req-docs/`,可补全流程说明。
**工作原理**:将 PDF 中的接口定义、数据模型、时序流程等提取为 Markdown 并落盘 `req-docs/`,便于后续编辑或与 `f2s-req-clarify` / `f2s-req-backend` 衔接。与 `f2s-doc-final` 的区别:`doc-pdf` 输出到 `req-docs/`(实现侧文档目录),`doc-final` 输出到 `stock-docs/` 供 `ctx-build` 入库。**不推荐**把「PDF 转 MD」当作跳过澄清与后端技术方案的直驱编码路径。
**使用场景**:
- 跨团队交付物为 PDF,需转为可编辑的 Markdown
- 历史 PDF 技术方案需纳入 `req-docs/` 管理
- 为后续 `f2s-req-clarify` / `f2s-req-backend` 提供可读底稿
**关联关系**:
- **前置**:PDF 文档
- **输出**:`.Knowledge/req-docs/<方案>.md`
- **下一步**(推荐):`f2s-req-clarify` → `f2s-req-backend` → 按 `req-docs/` 中技术方案 MD 触发 `implement-tech-design`;若目标是知识库沉淀则 `f2s-doc-final` → `f2s-ctx-build`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成全流程
- `subAgent: true`:PDF > 50 页或 > 5MB 时,可拆子做 PDF→MD 首稿落盘 req-docs;子不追问用户、不补写流程说明章节;主 agent 接手追问与流程说明补写
**职责划分**:
| 角色 | 职责 |
| ------- | ------------------------------- |
| 主 agent | 追问用户补充流程说明、完成 req-docs 落盘验收 |
| 子 agent | 仅做 PDF→MD 首稿并落盘 req-docs,不向用户追问 |
---
## 2) 需求与方案
### `f2s-req-clarify`
**作用**:针对 PRD/需求文档进行反问澄清,通过多轮问答明确需求边界、非目标、关键流程,直至需求足够清晰可供技术方案编写。
**工作原理**:采用「结构化追问」策略——将需求文档按「角色/场景/流程/边界/异常/非目标」六维拆解,逐维检查是否存在模糊表述、未定义概念或矛盾点,对每个缺口生成针对性追问。多轮对话直到所有维度无歧义后,输出需求澄清记录作为 `f2s-req-backend` 的输入。本质是将非结构化 PRD 转为可落地的结构化需求约束。
**使用场景**:
- 收到 PRD 后首步骤,确保理解正确
- 需求边界模糊、缺少验收标准时
- 跨团队协作需求,需明确接口契约
**关联关系**:
- **前置**:无(可直接触发)
- **后续**:`f2s-req-backend`(澄清后生成技术方案)
- **输出**:需求澄清记录(可选保存至 `.Knowledge/req-docs/`)
**子 agent 调用**:无(澄清全程依赖连续对话与用户即时反馈,不拆子 agent)
---
### `f2s-req-backend`
**作用**:基于已澄清的需求和项目知识库,生成后端技术方案文档,包含接口设计、数据模型、流程说明、错误码等。
**工作原理**:以「知识库约束 + 模版驱动」为核心——先从 `topics/stock-docs` 中抽取当前项目的架构约定、接口风格、数据模型规范等约束摘要,再将澄清后的需求对照后端技术方案模版(接口/模型/流程/异常/配置/迁移)逐章填写,确保方案与现有架构一致。输出落盘 `req-docs/`,即为 `implement-tech-design` 的编码依据。
**使用场景**:
- `f2s-req-clarify` 完成后,基于澄清结果输出方案
- 已有明确需求文档,直接生成技术方案
**关联关系**:
- **前置**:`f2s-req-clarify`(推荐)或明确的需求文档
- **输出**:`.Knowledge/req-docs/<技术方案>.md`
- **下一步**:提供技术方案路径并说明"按技术方案实现",由 `implement-tech-design` 规则驱动编码
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成方案编写
- `subAgent: true`:主 agent 必须先从 topics/stock-docs 抽取 < 80 行项目约定摘要(含架构约定、接口风格、数据模型规范等 6 类条款)作为子强制上下文,再拆子并行写 req-docs 初稿;主 agent 做契约定稿与验收
**职责划分**:
| 角色 | 职责 |
| ------- | ----------------------------------------------------------------------- |
| 主 agent | 抽取项目约定摘要、分配写作任务、对照模版做定稿验收并写入 req-docs |
| 子 agent | 只读多源(topics / stock-docs / 澄清 req-docs / 模版),按模版写 req-docs 初稿;不自行扩展读取范围 |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 落盘的接口/模型/流程文档 → 主 agent 校验跨章节一致性(接口签名与数据模型对齐、流程与异常处理覆盖)
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-req-plan`
**作用**:从技术方案或需求描述出发,**始终创建任务清单**,然后按清单实现代码。不依赖 `changeTracking` 配置,代表用户明确需要可追溯的任务管理。
**工作原理**:执行「解析→规划→确认→实现→归档」五阶段闭环。① 解析技术方案文档提取实现要点;② 按模块/功能粒度拆分为可执行任务清单并写入 `.task/`;③ 展示草稿给用户确认后锁定清单;④ 按清单逐项实现代码,每完成一项立即打钩 `task.md`;⑤ 全部完成后归档。与 `implement-tech-design` 规则的区别:`req-plan` 始终带任务追踪且支持并行子 agent 实现,适合大型需求;后者是轻量规则驱动的单线程编码。
**使用场景**:
- 有技术方案文档,需要拆解为任务清单后再实现
- 需求描述较复杂,希望先确认清单再动手
- 希望跨会话追踪实现进度
**关联关系**:
- **前置**:技术方案文档路径(`.Knowledge/req-docs/*.md` 或 PDF)或需求/变更描述
- **输出**:`.task/active/<task-name>/task.md` + `context.md`;实现代码
- **后续**:可按需调用 `f2s-kb-sync` 补充知识库
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成解析、确认、实现全流程
- `subAgent: true`:步骤 1(解析文档)可拆子并行只读;步骤 2(草稿确认)必须主 agent;步骤 4(实现代码)可按模块拆子并行;`todo.json` 恒由主 agent 写
**职责划分**:
| 角色 | 职责 |
| ----------- | ------------------------------------ |
| 主 agent | 输出草稿、用户确认、写 `todo.json`、汇总实现摘要 |
| 子 agent(解析) | 只读文档,输出解析结果摘要,不落盘 |
| 子 agent(实现) | 按模块实现代码,不触碰 `.task/` 和 `.Knowledge/` |
---
## 3) Git 提交
### `f2s-git-commit`
**作用**:代码写完后执行 Git 提交。自动检查变更文件、比对知识库覆盖情况,未入库的能力会提示用户处理,确认提交信息后执行 commit。
**工作原理**:在 `git commit` 之上叠加「知识库覆盖门控」——先通过 `git diff` 推断本次变更涉及的功能模块,再与 `.Knowledge/topics/` 和 `stock-docs/` 交叉比对,判断变更能力是否已有知识库记录。未覆盖时阻断并提示三选(补录/跳过/取消),避免「代码有了但知识库不知道」的静默漂移。提交信息强制 emoji + Conventional Commits 格式,保证 git log 的机读一致性。
**使用场景**:
- 每次功能实现或 Bug 修复后提交代码
- 希望在提交时得到知识库覆盖情况的提醒
- 需要 AI 帮助生成有意义的提交信息
**关联关系**:
- **前置**:代码已写完(`implement-tech-design`、`f2s-kb-fix`、`f2s-kb-feat` 等执行后)
- **后续**:无(commit 完成即结束,不自动 push)
- **可衔接**:若知识库未覆盖,可先运行 `f2s-kb-sync` 或 `f2s-kb-feat` 补录后继续提交
**执行流程**:
1. `git status --short` + `git diff HEAD` 区分 staged / unstaged / untracked 三类文件;发现 merge conflict 标记立即终止
2. 对比 `.Knowledge/topics/` 与 `stock-docs/`,判断本次变更能力是否已入库;`.Knowledge` 不存在时跳过并提示
3. 未覆盖时提示用户选择:A) 先补录再提交 / B) 先提交稍后补录 / C) 取消
4. 基于 `git diff` 实际内容生成提交信息草稿,等待用户确认或修改
5. `git add <具体文件>` + `git commit`;hook 失败则提示修复,不跳过
6. 输出 commit hash;若选 B 则附带未补录能力提醒
**约束**:
- 禁止 `git add -A` / `git add .`,只 add 已确认的变更文件
- 禁止 `--no-verify`,hook 失败须修复后重试
- 禁止自动 push
- 提交信息必须经用户确认,不可静默提交
**子 agent 调用**:无(全程交互确认,主 agent 内完成)
---
## 4) 知识库维护
### `f2s-kb-fix`
**作用**:根据用户指出的实现或规则错误修正代码,并**默认自动同步**知识库相关文档与索引。
**工作原理**:执行「定位→修复→同步」三步——先根据用户描述在知识库路由(manifest→topic→stock-docs)中定位相关上下文与代码位置,确认问题根因;修复代码后,自动检查 `topics/stock-docs/matchers` 中与该能力相关的描述是否因修复而需要更新,若有则原位修订(现行真值覆盖,不追加历史否定句)。「修代码必同步文档」是核心原则,避免知识库与实现漂移。
**使用场景**:
- 代码实现与技术方案不符
- 规则理解有误需要修正
- Bug 修复后需要同步文档
**变更追踪**:若 `changeTracking.fix: true`,执行前自动检查 `.task/todo.json` 并创建任务清单,完成后自动归档;跨会话可通过关键词续作(见 `f2s-task` 规则)。
**关联关系**:
- **前置**:问题发现(代码实现错误或规则偏差)
- **后续**:无(修复并同步完成即结束)
- **特点**:无需用户额外要求"请同步知识库",自动完成
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成修复和知识库同步
- `subAgent: true`:代码子包(bug 修复)可外包给子 agent;文档子包(rules/skills/topics 文风类)默认主 agent 直接写,如拆则子 agent 仅输出 before/after diff 片段,不整文件重写;manifest 和 index 恒由主落盘
**职责划分**:
| 角色 | 职责 |
| -------------- | ---------------------------------------------------- |
| 主 agent | 定位问题根因、制定修复方案、落盘文风合规内容、校验知识库一致性 |
| 子 agent(代码) | 负责指定模块的代码 bug 修复,输出变更并报告影响范围 |
| 子 agent(文档,可选) | 仅输出 before/after diff 片段,不整文件重写,不触碰 manifest 和 index |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 落盘的代码变更 → 主 agent 校验修复正确性与知识库一致性
- 主 agent 落盘的知识库同步 → 子 agent 复核 topic/manifest 一致性(须 `subAgent: true` 且已拆出子任务,否则主 agent 内自验)
- 复核方与落盘方必须为不同 agent 实例
---
### `f2s-kb-feat`
**作用**:新增能力时补全实现与知识库;若能力已实现,则仅同步知识库。
**工作原理**:执行「判断→实现→入库」三阶段——先判断用户描述的能力在代码中处于「未实现/部分实现/已实现」哪种状态;未实现或部分实现时先补齐代码;最后走知识库同步:写 `stock-docs` 能力说明、生成或更新 `topics` 主题摘要、在 `manifest-routing` 和 `matchers` 注册路由映射。与 `f2s-kb-fix` 的区别:`kb-feat` 面向「新增」,`kb-fix` 面向「修正已有」。
**使用场景**:
- 新功能开发
- 存量功能需要补录知识库
**变更追踪**:若 `changeTracking.feat: true`,执行前自动检查 `.task/todo.json` 并创建任务清单,完成后自动归档;跨会话可通过关键词续作(见 `f2s-task` 规则)。
**关联关系**:
- **前置**:无(可直接触发)
- **后续**:无(实现+同步完成即结束)
- **特点**:自动同步知识库,无需用户额外要求
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成
- `subAgent: true`:代码子包(新增实现)可外包给子 agent;文档子包(rules/skills/topics 文风类)默认主 agent 直接写,如拆则子 agent 仅输出 before/after diff 片段;manifest 和 index 恒由主落盘
**职责划分**:
| 角色 | 职责 |
| -------------- | ---------------------------------------------------- |
| 主 agent | 确定能力边界与实现范围、落盘文风合规内容、最终校验知识库一致性 |
| 子 agent(代码) | 负责代码实现(接口、逻辑、数据层),输出实现清单 |
| 子 agent(文档,可选) | 仅输出 before/after diff 片段,不整文件重写,不触碰 manifest 和 index |
**交叉验证(`switchAgentVerification: true` 时)**:
- 文档子 agent 落盘的 topic → 主 agent 校验与实现代码的能力描述一致性
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-kb-sync`
**作用**:将会话中的已实现能力沉淀回知识库。可显式给出能力或零输入推断。
**使用场景**:
- 会话中已完成实现,需要补录知识库
- 从代码反向沉淀知识
- 定期知识库整理
**关联关系**:
- **前置**:无(可直接触发,或零输入推断)
- **后续**:无
- **特点**:先输出知识库更新大纲,用户确认后才写入
- **与 `f2s-ctx-build` 区别**:`ctx-build` 从 `stock-docs` 驱动,`kb-sync` 从会话/代码推断
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成推断和同步
- `subAgent: true`:分步骤拆子——**步骤 1**(汇总推断)可拆子并行只读会话历史;**步骤 2**(用户确认大纲)必须在主 agent 完成;**步骤 3**(落盘同步)可拆子写 topic/matcher,但子落盘前须读近邻 2–3 个主题摘要做风格对齐;manifest 和 index 恒由主落盘
**职责划分**:
| 角色 | 职责 |
| ----------- | ------------------------------------------------------- |
| 主 agent | 输出大纲并确认、单点落盘 manifest 和 index、最终验收 |
| 子 agent(汇总) | 只读会话历史、推断能力点、生成结构化更新大纲片段 |
| 子 agent(同步) | 按大纲写 topic/matcher,落盘前加载近邻主题摘要对齐风格,不触碰 manifest 和 index |
**交叉验证(`switchAgentVerification: true` 时)**:
- 同步子 agent 落盘的 topic/matcher → 主 agent 校验跨 topic 路由完整性与 `includeAny` 关键词覆盖
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-kb-merge`
**作用**:解决 Git 合并后的编辑器上下文冲突。可选传入冲突文件路径。
**工作原理**:按文件类别分层处理冲突——将冲突文件分为「可安全自动合并」(index、manifest、matchers 等结构化文件,取并集或最新版本)和「须用户确认」(实现代码、业务规则等语义文件)两类。对前者自动 resolve,对后者生成分类对照表(ours/theirs 摘要 + 建议)并罗列差异,等待用户逐项裁决。核心设计思想:知识库元数据可自动化,业务语义不可擅自裁定。
**使用场景**:
- Git merge/rebase 后出现上下文冲突
- 多人协作导致知识库文件冲突
- 分支合并后需要统一知识库状态
**关联关系**:
- **前置**:Git 合并产生的冲突
- **后续**:无(冲突解决即结束)
- **特点**:实现侧冲突仅罗列待用户确认
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内分析与解决冲突
- `subAgent: true`:可拆子做冲突扫描与分类对照表(`file / category / ours_summary / theirs_summary / recommendation` 五字段);子不得自行合并文件;主 agent 按策略落盘、处理实现侧决策、完成验收
**职责划分**:
| 角色 | 职责 |
| ------- | ----------------------------------- |
| 主 agent | 按策略落盘合并结果、处理实现侧冲突决策、验收 |
| 子 agent | 仅做冲突扫描与分类,按五字段 schema 交付对照表,不自行合并文件 |
---
### `f2s-kb-migrate`
**作用**:将旧版知识库(`docs-index.md` + `rules/` 模式)按主题迁移到 `.Knowledge/` 结构。
**工作原理**:以旧版 `docs-index.md` 和 `rules/main.md(c)` 为「索引线索」,递归识别所有被引用的业务规则和技能文件,按主题粒度重新组织到 `.Knowledge/` 的 `topics/stock-docs/req-docs` 三层结构中。迁移完成后落盘 `migration-report.md`(对照表 + 拟删路径),待用户确认后清理旧文件。本质是一次性的结构重组,将分散的规则/文档归并为统一知识库。
**使用场景**:
- 旧项目升级到 Flow2Spec 新版
- 存量知识库需要结构化整理
**关联关系**:
- **前置**:旧版知识库(`docs-index.md`、`rules/`、`skills/`)
- **后续**:`f2s-kb-upgrade`(**流程 V1** 旧库须先 migrate 再 upgrade;**现行库 V2+**(含 npm v3.x)见 upgrade 技能步骤 0)
- **流程**:
1. 以 `docs-index.md` + `rules/main.md(c)` 为主索引
2. 全量处理业务 `rules/` 与业务 `skills/`(排除 `f2s-`* 包技能)
3. 全量迁移 `stock-docs`/`req-docs`
4. 落盘 `.Knowledge/migration-report.md`
5. 用户确认后删除已迁旧的文件
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内逐主题迁移
- `subAgent: true`:子只做搬运 + migration-report 草案片段(以 patch 形式交付);状态文件(migration-report.md、删除执行记录)由主 agent 唯一落盘;主 agent 主导删除清单确认与删除闭环
**职责划分**:
| 角色 | 职责 |
| ------- | --------------------------------------------- |
| 主 agent | 制定迁移规划、合并迁移结果、落盘 migration-report、主导删除确认与执行闭环 |
| 子 agent | 负责指定主题的搬运与草案片段生成(patch 形式),不写状态文件、不写删除执行记录 |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 迁移落盘的主题 → 主 agent 校验迁移完整性(旧路径是否全量覆盖、主题边界是否重叠)
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-kb-upgrade`
**作用**:知识库模板升级。对齐 manifest-routing + matchers 分片。
**工作原理**:通过「版本分流 + init 代跑」实现升级——先检测当前知识库属于 V1(旧结构,需先 migrate)还是 V2+(已有 `.Knowledge`),V1 走 migrate 后再 init,V2+ 直接代跑 `flow2spec init` 进行包级结构增量对齐(补齐新模板、升级 manifest schema、对齐 matchers 分片格式)。升级后重读 SKILL.md 判断是否需要重跑某些步骤。与单独 `init` 的区别:`kb-upgrade` 包含版本判断和重跑逻辑,`init` 仅做一次性结构补齐。
**使用场景**:
- flow2spec 包版本升级后,升级项目知识库模板
- 旧项目升级到最新结构
**关联关系**:
- **前置**:`f2s-kb-migrate`(V1 流程)或已存在的 `.Knowledge/`
- **包含**:内部会调用 `flow2spec init` 进行结构对齐
- **注意**:单独的 `flow2spec init` **不是**升级命令
**流程差异**(技能内分流代号,**不等于** npm 包主版本号):
- **V1**:先 `f2s-kb-migrate` 再代跑 `flow2spec init`
- **现行库(V2+)**:已稳定 `.Knowledge` + `manifest-routing` 时,代跑 `flow2spec init` 以对齐 manifest-routing + matchers 分片(**含 Flow2Spec npm v3.x 等**,详见 `skills/f2s-kb-upgrade/SKILL.md` 步骤 0)
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成升级
- `subAgent: true`:子 agent 仅承接 shell 命令执行(代跑 `flow2spec init`),不承担知识库正文落盘;以下步骤主 agent 不可下放:版本分流(V1 / 现行库 V2+)、init 后重读 SKILL.md 并判断是否整技能重跑、步骤 3b index.md 融合、校验摘要输出
**职责划分**:
| 角色 | 职责 |
| ------- | ----------------------------------------------------------------------------- |
| 主 agent | 版本分流、init 后重读并判断重跑、步骤 3b index.md 融合、校验摘要;落盘 manifest-routing.json 和 index.md |
| 子 agent | 仅代跑 `flow2spec init` 等 shell 命令,不落盘知识库内容 |
**交叉验证**:本技能不绑定交叉校验,落盘侧自验。
---
## 5) 规则说明
以下不是技能命令,而是通过触发词激活的规则,用于辅助指导 Agent 的行为。
### `f2s-karpathy-guidelines`
**触发词**:`alwaysApply`(始终生效,无需显式触发)
**作用**:Flow2Spec 内置的 Karpathy 式编码行为准则,约束 Agent 的编码决策质量。
**工作原理**:从 Andrej Karpathy 对 LLM 写代码常见失误的观察中提炼四条行为约束,作为 `alwaysApply` 规则在所有 `f2s-*` 技能执行时隐式生效:① 先想清楚再写代码(假设要说清楚,不确定就问);② 简单优先(用最少代码解决问题);③ 手术式修改(只动该动的,风格对齐现有代码);④ 目标驱动执行(先定义可验证的成功标准再循环迭代)。当这些准则与 `f2s-*` 强制步骤冲突时,以 `f2s-*` 为准。
---
### `f2s-task`
**触发词**:changeTracking、变更追踪、任务追踪、续作、继续上次任务
**作用**:变更追踪规则(`alwaysApply`)。当对应技能的 `changeTracking.`* 为 `true` 时,在技能执行前后自动创建、逐步更新、最终归档 `.task/` 下的任务清单,支持跨会话续作。
**工作原理**:基于「磁盘 checkpoint + 关键词匹配」实现跨会话状态持久化——每个活跃任务在 `.task/active/<name>/task.md` 中以 checkbox 记录进度(`[ ]`/`[x]`),`todo.json` 作为活跃任务索引。新会话开始时,规则自动将用户首条消息与各任务的 `keywords` 做模糊匹配:命中则加载 `task.md` 剩余步骤和 `linkedSkill` 对应的技能文件,恢复完整执行上下文。任务完成后移入 `completed/` 归档。核心设计:以文件系统而非对话记忆作为状态真值,对话中断不丢进度。
**生效范围**:
| 配置项 | 对应技能 |
| -------------------------- | --------------------------- |
| `changeTracking.feat` | `f2s-kb-feat` |
| `changeTracking.fix` | `f2s-kb-fix` |
| `changeTracking.implement` | `f2s-implement-tech-design` |
**跨会话续作**:新会话开始时若存在 `.task/todo.json`,自动将用户首条消息与各任务 `keywords` 匹配;命中则加载对应 `task.md` 及 `linkedSkill` 技能文件,展示剩余清单,提示是否继续;无命中则不打扰。
**规则位置**:`配置根/rules/f2s-task.`*
---
### `stock-docs-vs-req-docs`
**触发词**:stock-docs、req-docs、已落地能力、技术方案放哪、PDF 终稿
**作用**:区分知识沉淀目录与需求实现目录的边界。
**工作原理**:通过「用途隔离」避免文档混放——`stock-docs/` 存放已沉淀的存量知识(架构、终稿),由 `ctx-build` 消费入库,禁止直接用于编码;`req-docs/` 存放面向实现的需求与技术方案,由 `implement-tech-design` 规则消费驱动编码。两目录的写入者和消费者完全隔离,防止「存量描述被当编码依据」或「实现方案被当能力沉淀」的混淆。
**目录分工**:
| 目录 | 用途 | 写入时机 |
| ------------- | ------------- | ---------------------------------------------- |
| `stock-docs/` | 存量沉淀(架构、终稿) | `f2s-doc-arch`、`f2s-doc-final`、`f2s-ctx-build` |
| `req-docs/` | 需求与技术方案(驱动实现) | `f2s-req-backend`、`f2s-doc-pdf`、手动放置 |
**使用场景**:
- 不确定文档应该放哪里
- 需要明确 stock-docs 与 req-docs 的分工
---
### `implement-tech-design`
**触发词**:按技术方案实现、implement-tech-design、根据方案实现
**作用**:根据 `req-docs/` 中的技术方案文档实现可运行代码。
**工作原理**:以「方案即合约」为核心约束——Agent 以 `req-docs/` 中的技术方案为唯一编码依据,按「理解方案→输出任务列表→提问确认→逐步实现→输出待完成列表」的强制六步流水线执行。任务列表和实现前提问是不可跳过的门禁,确保不会在理解偏差的情况下动手编码。与 `f2s-req-plan` 的区别:本规则是轻量单线程编码驱动,不强制创建 `.task/` 追踪(除非 `changeTracking.implement: true`)。
**变更追踪**:若 `changeTracking.implement: true`,在步骤 2.5 输出任务列表后同步写入 `.task/active/<task-name>/task.md`;步骤 5 收尾时归档任务。
**使用场景**:
- 技术方案已就绪,需要按方案编码
- 方案变更后需要同步更新代码
**关联关系**:
- **前置**:`.Knowledge/req-docs/<技术方案>.md`(通过 `f2s-req-backend` 或手动放置)
- **规则位置**:
- Cursor:`.cursor/rules/f2s-implement-tech-design.mdc`
- Claude:`.claude/rules/f2s-implement-tech-design.md`
- Codex:`.codex/AGENTS.md` + `.codex/topics/f2s-implement-tech-design.md`
**执行流程**(规则强制):
1. 输入标准化
2. 理解方案与上下文
3. **输出实现任务列表**(必做,不可跳过)
4. **实现前提问**(必做,不可跳过)
5. 按任务列表实现
6. **输出待完成列表与实现后提醒**(必做)
**子 agent 调用**:无(规则驱动编码,主 agent 内完成全流程)
---
## 6) 子 Agent 配置说明
通过项目根 `flow2spec.config.json` 控制(字段默认均为 `false`)。
### 多端如何「看到」配置(与下文字段表配合)
`subAgent` 等写在 **磁盘 JSON**;各产品不保证自动打开文件,故用 **Cursor 规则 / Claude hook / Codex AGENTS 快照表 / 知识库 `config-precheck` 摘要** 多层提示,**权威仍为 Read(`flow2spec.config.json`)**(设计意图见 [设计说明 § 四、5.1](./设计说明.md),演讲口径见 [Flow2Spec-演讲稿 Slide 13b](./Flow2Spec-演讲稿.md))。**完整路径与表格只维护一处**:[使用说明 § 一、`f2s-`* 与 `flow2spec.config.json](./使用说明.md)`。
### `subAgent` 字段
| 取值 | 行为 |
| ----------- | ------------------------------ |
| `false`(默认) | 所有 `f2s-*` 技能在主 agent 内完成 |
| `true` | 部分技能可按正文约定使用子 agent(大规模并行处理场景) |
### `switchAgentVerification` 字段
| 取值 | 行为 |
| ----------- | --------------------------------------------------------------------------------------------- |
| `false`(默认) | 落盘侧自验:谁落盘谁验 |
| `true` | 技能正文明确写出该步骤时,启用交叉校验:子 agent 落盘 → 主 agent 验;主 agent 落盘 → 子 agent 验(须 `subAgent: true` 且已拆出子任务) |
### `changeTracking` 字段
嵌套对象,各技能子项独立控制:
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
| 子项 | 对应技能 | 效果 |
| ----------- | --------------------------- | ----------------------- |
| `feat` | `f2s-kb-feat` | 执行前创建任务清单,完成后归档,支持跨会话续作 |
| `fix` | `f2s-kb-fix` | 同上 |
| `implement` | `f2s-implement-tech-design` | 同上 |
> `f2s-req-plan` 不受此配置约束,始终创建任务清单。旧版布尔值(`"changeTracking": true/false`)向下兼容,自动展开为三项全开/全关。
完整原则与设计意图见 [体系与原理 § 4. Agent 执行模型](./体系与原理.md)。
---
## 7) 快速参考
典型工作场景与完整链路见 [使用说明 § 三、典型工作场景](./使用说明.md)。
目录完整说明见 [目录与路径约定](./目录与路径约定.md)。
---
相关文档:
- [使用说明](./使用说明.md)
- [目录与路径约定](./目录与路径约定.md)
- [体系与原理](./体系与原理.md)
- [使用案例-模拟对话](./使用案例-模拟对话.md)
# 目录与路径约定
[English](./en/directory-conventions.md)
## 核心边界
- `.Knowledge/`:**知识环**——业务知识文档与机读路由(见 [体系与原理 §2 多层记忆](./体系与原理.md))
- `.task/`:**任务环**——变更追踪与跨会话续作(不在 `.Knowledge/` 内)
- `配置根`(`.cursor/.claude/.codex`):**规则环 + 技能环**入口
Memory Coding 四环总览见 [体系与原理 §1](./体系与原理.md)。
---
## 目录职责
| 路径 | 职责 |
| --- | --- |
| `docs/` | 产品说明(**中文**):使用说明、命令说明、设计说明等 |
| `docs/en/` | 产品说明(**英文**):与上表一一对应的 6 篇文档,见 [en/README.md](./en/README.md) |
| `.Knowledge/stock-docs/` | **L3** 架构、终稿、沉淀长文档 |
| `.Knowledge/req-docs/` | **L3** 需求澄清、技术方案长文档 |
| `.Knowledge/topics/` | **L2** 主题摘要(硬约束、边界、路由指针) |
| `.Knowledge/template/` | 终稿/技术方案模板 |
| `.Knowledge/index.md` | 人类可读索引 |
| `.Knowledge/manifest-routing.json` | **L0** 机读路由骨架(task/topic/`topicDependencies`) |
| `.Knowledge/matchers/*.json` | **L1** 关键词分片(`id/includeAny`),由 `matcherPath` 直链;**match** 只读一片 |
| `.Knowledge/migration-report.md` | `f2s-kb-migrate` 落盘的迁移对照表与拟删除路径列表 |
| `.task/` | 变更追踪任务清单目录(`active/` 进行中,`completed/` 已归档且目录名为 **`<YYYYMMDD>-<task-name>`**(日期在前),`todo.json` 活跃任务索引);仅当 `changeTracking.*` 为 `true` 或显式调用 `f2s-req-plan` 时创建 |
| `配置根/rules/` | 规则文件(Cursor `.mdc`,Claude `.md`) |
| `配置根/skills/` | 技能定义(`SKILL.md`) |
| `配置根/template/` | (废弃)不再写入;历史目录可清理 |
| `.codex/AGENTS.md` | Codex 统一入口与加载说明 |
| `flow2spec.config.json` | 项目根配置,控制 `subAgent`、`switchAgentVerification`、`changeTracking`(嵌套对象,含 `feat` / `fix` / `implement` 三个子项) |
> 多端提示与路径表见 [使用说明 § 一](./使用说明.md)(详表单点维护);**权威仍为 Read(`flow2spec.config.json`)**。
---
## 路径约束
1. `.Knowledge/topics` 是知识路由主题层,允许并鼓励通过 `f2s-*` 技能维护。
2. `f2s-ctx-build` 从 `.Knowledge/stock-docs` 读,更新 `.Knowledge/topics`、`.Knowledge/index.md`、`.Knowledge/manifest-routing.json`、`.Knowledge/matchers/*.json`。
3. 实现类任务统一读取 `.Knowledge/req-docs/*.md`。
4. `manifest-routing.json` 与 `matchers/*.json` 由 `f2s-*` 技能流程维护;不再使用 `.Knowledge/manifest-matchers.json`(`flow2spec init` 会删除遗留文件)。
---
## 相关文档
- [使用说明](./使用说明.md)
- [命令说明](./命令说明.md)
- [体系与原理](./体系与原理.md)
- [使用案例-模拟对话](./使用案例-模拟对话.md)
# Flow2Spec 设计说明
[English](./en/design-principles.md)
## 解决的问题
```
❌ 现状 ✅ Flow2Spec 之后
架构约定 ──┐ .Knowledge/
技术方案 ──┼──► 散落 ├── manifest-routing.json
模块边界 ──┤ 无结构 ├── matchers/
团队经验 ──┘ 每次重新解释 ├── topics/
├── stock-docs/
└── req-docs/
AI 随时能读懂项目
```
---
## 核心设计
### 0. Memory Coding 与仓内四环
**Memory Coding**:把必须长期记住的上下文**编码进可提交仓库**(可 PR、可 review),而不是押在模型 Memory 或聊天里。
仓内 **四环**(规则环与技能环分列,勿合并为「规则+技能」):
| 环 | 落点 | 职责 |
| --- | --- | --- |
| 知识环 | `.Knowledge/` | 路由 + 主题 + 存量/需求文档 |
| 任务环 | `.task/` | 跨会话续作、用户代办 |
| 规则环 | 各工具 `rules` / `AGENTS.md` | 怎么读、怎么做(缺口闸门、路由顺序) |
| 技能环 | `f2s-*` / `skills/` | 维护知识、触发 feat/fix/sync 等 |
```mermaid
graph TB
subgraph MC["Memory Coding · 仓内四环"]
KR["知识环 .Knowledge/"]
TR["任务环 .task/"]
RR["规则环 rules"]
SR["技能环 f2s-*"]
end
SR -->|"维护 ↑"| KR
RR -->|"读与做 ↓"| KR
TR -.->|"并列,不在 .Knowledge 内"| KR
```
Flow2Spec 提供的是 **Memory Coding 的落盘与维护闭环**,不是「又一个 RAG 知识库」。
### 0.1 知识环:多层记忆结构
知识环内部是 **横读 + 纵链** 的多层结构(与下文「渐进式路由」「topicDependencies」对应):
```mermaid
graph TB
subgraph H["横读 · 渐进式收窄"]
L0["L0 manifest-routing"]
L1["L1 matchers 分片"]
L2["L2 topics 摘要"]
L3["L3 stock-docs / req-docs"]
L0 --> L1 --> L2 --> L3
end
subgraph V["纵链 · topicDependencies"]
T1["通用约定"]
T2["子域边界"]
T3["端上白名单"]
T4["本域细则"]
T1 --> T2 --> T3 --> T4
end
L2 --- V
```
| 层级 | 路径 | 作用 |
| --- | --- | --- |
| L0 | `manifest-routing.json` | 机读路由、依赖声明 |
| L1 | `matchers/*.json` | 关键词命中,**match** 只读一片 |
| L2 | `topics/*.md` | 硬约束摘要;**expand** 拉依赖 |
| L3 | `stock-docs/`、`req-docs/` | 长文档,按需下钻 |
| 纵链 | `topicDependencies` | 主题级前置,所有任务共享 |
读取流水线:`match → expand → verify → act`(详见 [体系与原理 §4](./体系与原理.md))。
### 1. 知识与规则分离
```mermaid
graph LR
subgraph K[".Knowledge/ 知识层"]
K1[架构说明]
K2[技术方案]
K3[路由索引]
end
subgraph R["配置根 执行层"]
R1[.cursor/rules/]
R2[.claude/rules/]
R3[.codex/AGENTS.md]
end
K -->|知识输入| AI[AI 工具]
R -->|规则约束| AI
note1["知识随项目迭代"] -.-> K
note2["规则随工具升级"] -.-> R
```
### 2. 渐进式路由
```mermaid
graph LR
T[任务] --> M[manifest-routing\n读路由表]
M -->|关键词匹配| MT[matchers/xxx.json\n只读这一个分片]
MT -->|命中| TP[topics/xxx.md]
TP --> V{缺口检查}
V -->|通过| ACT[执行]
V -->|不足| Q[向用户澄清]
M -->|未命中| FB[fallback-triage\n结构化分诊]
```
### 3. 技能维护闭环
<p><img src="./images/flow-1.png" alt="技能维护闭环" style="max-width:100%;" /></p>
<details>
<summary>Mermaid 源码</summary>
```mermaid
graph LR
K[".Knowledge/"] --> AI["下次会话\n的 AI"]
AI --> C["功能迭代"]
C -->|"修复 Bug"| FIX["f2s-kb-fix"] --> K
C -->|"新增能力"| FEAT["f2s-kb-feat"] --> K
C -->|"会话结束"| SYNC["f2s-kb-sync"] --> K
C -->|"提交代码"| CMT["f2s-git-commit\n收口检查"]
CMT -->|"未入库则提醒\n-> kb-sync/kb-feat"| K
D1["架构文档"] -->|f2s-doc-arch| FIN["f2s-doc-final"]
D2["PDF/初稿"] -->|f2s-doc-final| FIN
FIN --> CTX["f2s-ctx-build"] --> K
OLD["存量代码/文档"] -->|f2s-doc-add| K
NR["新需求"] --> CL["f2s-req-clarify"] --> BE["f2s-req-backend"]
BE --> IMPL["实现xxx技术方案"] -->|自动触发implement-tech-design规则| K
GIT["Git 合并后"] -->|f2s-kb-merge| K
```
</details>
七条入口 · `f2s-git-commit` 是提交时的知识纪律收口 · `.Knowledge/` 是唯一汇聚点 · 知识驱动 AI,AI 驱动下轮开发
### 4. 任务清单与跨会话续作
```mermaid
graph LR
SKILL["f2s-kb-feat / f2s-kb-fix\nimplement-tech-design"] -->|"changeTracking: true"| TJ[".task/active/\ntask.md · todo.json"]
RP["f2s-req-plan\n(始终创建)"] --> TJ
TJ --> NS[新会话首条消息]
NS -->|关键词匹配| LD["加载剩余 checklist\n+ linkedSkill 上下文"]
LD --> RS[按原技能约束继续]
```
任务不因会话结束丢失 · 关键词自动续作,无需重新说明上下文 · 技能约束完整恢复
---
## 设计亮点
### 一、路由与上下文加载
#### 1. matchers 分片,不嵌入 manifest
```
❌ 嵌入 manifest ✅ 独立分片
manifest.json (每次全读) manifest-routing.json
├── task1: keywords:[...] → ├── task1 → m-order.json ──► 只读这一个
├── task2: keywords:[...] ├── task2 → m-payment.json
└── task3: keywords:[...] └── task3 → m-refund.json
更新关键词不动路由结构
每次路由 token 成本固定
```
#### 2. topicDependencies:依赖挂在主题上
```
❌ 挂在任务级 ✅ 挂在主题级
taskA → [dep, main] topicDependencies:
taskB → [main] ← 漏写了 main: [dep]
taskC → [main] ← 漏写了
任何路径加载 main
新增任务时漏写 → 静默失效 都自动带上前置依赖
```
#### 3. topic 只存摘要,规则文件存全文
```
.Knowledge/topics/implement-tech-design.md ← 轻量,路由时加载
┌──────────────────────────────────────────┐
│ 主题 id、路径约定、下一步指针 │
│ ~100 行 │
└──────────────────────────────────────────┘
↓ 命中后才读
.claude/rules/f2s-implement-tech-design.md ← 全文,执行时加载
┌──────────────────────────────────────────┐
│ 完整执行约束、强制步骤、禁止项、边界说明 │
│ ~500 行 │
└──────────────────────────────────────────┘
```
路由层保持轻量 · 执行细节按需加载 · 两者独立更新
#### 4. 禁止全量扫描是硬约束
```
读取顺序(必须)
1. manifest-routing.json ← 先看路由表
2. matchers/xxx.json ← 只读命中分片
3. index.md ← 按需,确认语义
4. stock-docs / req-docs ← 按需,补充背景
5. 业务源码 ← 最后手段
❌ 未读 manifest 前,禁止全仓无范围扫描
❌ 同一任务线内,manifest 已读则不重复全文读取
❌ index.md 禁止与 manifest 交替"刷清单"代替决策
```
#### 5. 技能触发词写在 description 字段
```yaml
name: f2s-kb-sync
description: >
同步已实现能力到知识库。
触发词:f2s-kb-sync、全局同步、知识库同步、已实现能力
```
```
用户输入 → Agent 扫 description 做语义匹配 → 触发对应技能
```
触发词在 description 里 · 不在正文里 · 命中率更高 · 双语覆盖减少漏触发
---
### 二、知识结构
#### 1. stock-docs vs req-docs 语义禁止
```
stock-docs/ req-docs/
架构说明 / 终稿 需求 / 技术方案
↓ 用于 ↓ 用于
知识路由 / 背景参考 驱动编码实现
✅ 可以读 ✅ 可以读
❌ 不能作为编码输入 ✅ implement-tech-design 的输入
```
防止:用过期参考文档驱动实现 → 代码与最新方案脱节
#### 2. init 幂等
```
flow2spec init 可以安全重跑
✅ 做 ❌ 不做
┌─────────────────────┐ ┌─────────────────────┐
│ 补齐缺失目录和模板 │ │ 写业务文档内容 │
│ 落盘 rules/skills │ │ 更新路由关键词 │
│ 包级结构对齐 │ │ 覆盖已有知识内容 │
└─────────────────────┘ └─────────────────────┘
结构操作 ≠ 业务语义 两者职责不交叉
```
#### 3. 知识版本化
```
git log .Knowledge/
a3f1c2 f2s-kb-feat: 新增退款状态机路由
b7e9d1 f2s-kb-fix: 修正 RestTemplate 注入约定
c2a8f0 f2s-ctx-build: 订单服务架构说明入库
d5b3e9 f2s-kb-sync: 沉淀支付重试队列设计
代码变更 + 知识变更 → 同一 commit 或相邻 commit
```
知识有版本 · 可 review · 可回溯 · 可 blame
#### 4. 禁止历史否定堆砌
```
❌ 错误写法(知识库越来越臃肿) ✅ 正确写法(只保留当前成立的表述)
RestTemplate 约定(更新于 2026-05) RestTemplate 必须通过 Bean 注入
~~原错误地使用 new RestTemplate()~~ 禁止直接 new RestTemplate()
→ 不再与直接实例化有关
→ 原写法已废弃,现改为 Bean 注入
```
每次修复原位改写 · 不叠加历史 · 知识库永远只描述现在
---
### 三、执行约束
#### 1. 强制步骤是约束,不是建议
```
implement-tech-design 执行流
输入标准化
读取方案与上下文
★ 输出实现任务列表 ← 不可跳过
★ 实现前提问确认 ← 不可跳过
按任务列表实现
输出待完成清单与提醒 ← 不可跳过
```
建议 → 可以被跳过 · 约束 → 必须明确处理才能继续
#### 2. fallback 本身是有程序的 topic
```mermaid
graph TD
F[进入 fallback-triage] --> S1{路由是否命中?}
S1 -->|已命中但上下文不足| EXP[展开依赖主题\n补齐后继续]
S1 -->|未命中| Q[询问用户:\n这个领域文档是否已录入?]
Q -->|是| HINT[路由词条缺失\n建议补路由]
Q -->|否| CHOICE[下钻源码\n或补充 req-docs]
Q -->|不确定| STOP[停止执行\n等待明确指令]
```
未命中 ≠ 静默失败 · 降级本身有明确程序
#### 3. manifest / index 写权硬约束
```
子 agent 可以落盘的 子 agent 不得触碰
──────────────────── ────────────────────
代码实现文件 manifest-routing.json ← 恒主 agent 落盘
stock-docs 内容文件 .Knowledge/index.md ← 恒主 agent 落盘
topics 内容文件(diff 模式)
matchers/*.json(diff 模式)
```
多个子 agent 并行时,共享状态文件由主 agent 单点写入,防止并发冲突
#### 4. 文档改动 vs 代码改动,拆分策略不同
```
代码子包 文档子包
──────────────────── ────────────────────
✅ 可下放子 agent 执行 ❌ 默认不拆,主 agent 直接写
✅ 子 agent 直接落盘 若确需外包 →
子侧只输出 before/after diff 片段
主 agent 审核后合并落盘
❌ 整文件重写严格禁止
```
原因:文档需要保证「现行真值覆盖 / 文风一致 / 禁历史否定堆砌」 · 要求写的人看到全文上下文
#### 5. 任务清单与跨会话续作
```
关键词自动续作示例
新会话第一句:"支付回调还有个问题"
匹配 todo.json 各条目 keywords
命中 { name: "payment_callback_fix", keywords: ["支付", "回调"] }
加载 task.md(展示剩余步骤)
linkedSkill = "f2s-kb-fix" → 加载 SKILL.md
技能的落盘规则 / 文风要求 / 自检清单全部恢复
用户无需重新描述上下文,直接继续
✅ 不需要说"继续上次任务"
✅ 技能约束完整恢复,与首次调用一致
```
```
todo.json 写权约束
主 agent ── 读 / 写 todo.json ✅
子 agent ── 读 todo.json ✅
子 agent ── 写 todo.json ❌
原因:多子 agent 并行落盘时,并发写会导致条目互相覆盖
```
生命周期由技能驱动 · 关键词路由实现跨会话自动续作 · linkedSkill 保证技能约束完整恢复
---
### 四、Agent 编排
#### 1. subAgent × switchAgentVerification 正交
```
switchAgentVerification
false true
subAgent ┌────────────┬─────────────────┐
true → │ 并行执行 │ 并行执行 │
│ 落盘侧自验 │ 子落盘→主验 │
│ │ 主落盘→子验 │
├────────────┼─────────────────┤
false → │ 顺序执行 │ 顺序执行 │
│ 主 agent │ 主 agent 自验 │
│ 自验 │(无子侧可交叉) │
└────────────┴─────────────────┘
```
两个维度正交 · 独立配置 · 默认左下角
#### 2. 确认权不可下放子 agent
```mermaid
graph LR
S1[步骤1: 素材汇总] -->|subAgent=true 可并行| SUB[子 agent]
SUB -->|只读,不落盘| S2
S2[步骤2: 输出大纲\n用户确认] -->|必须主 agent| USER[用户]
USER -->|确认| S3
S3[步骤3: 落盘] -->|subAgent=true 可并行| SUB2[子 agent]
```
用户对话只经过主 agent · 确认决策不可绕过用户 · 子 agent 只做执行不做决策
#### 3. 技能可覆盖全局 subAgent 配置
```
flow2spec.config.json f2s-req-clarify SKILL.md
subAgent: true 本技能默认不拆子:
无论 subAgent 真值,
澄清流程全程在主会话
原因:需求澄清强依赖连续同会话追问
拆子会断上下文,导致澄清质量下降
```
全局配置是允许拆的上限 · 技能自己判断是否适合拆 · 配置 true 不等于一定拆
#### 4. f2s-kb-sync 先出大纲,确认后再写
```mermaid
graph LR
T[触发 f2s-kb-sync] --> O[输出更新大纲]
O --> U{用户确认}
U -->|确认| W[写入 .Knowledge/]
U -->|修改| O
U -->|取消| STOP[不写入]
```
写入是破坏性操作 · 大纲是用户唯一的纠错机会 · 确认前不落盘
#### 5. 零输入推断
```
f2s-kb-sync 三种输入方式
方式 1:用户显式给出能力列表 "帮我把退款状态机同步进知识库"
方式 2:用户给辅助材料 @src/refund/ @docs/方案.md
方式 3:零输入 "f2s-kb-sync"(仅此一句)
Agent 基于会话上下文推断
本次实现了什么、有什么值得沉淀
```
会话上下文本身就是信息源 · 不需要用户整理再输入
#### 5.1 执行开关如何进入 Agent(多端提示)
`flow2spec.config.json` 决定 **`subAgent` / `switchAgentVerification` / `changeTracking`**,但各 AI 产品**不保证**会话启动即自动打开该文件。设计上用 **多条弱约束叠加** 降低「未读配置就开跑 `f2s-*`」的概率,同时避免在 `.Knowledge` 再维护一份与 `.codex/topics/f2s-config-check.md` 逐字重复的长文:
| 机制 | 设计意图 |
| --- | --- |
| **Cursor `f2s-config-check.mdc`** | 规则层强制「技能正文前先 Read」。 |
| **Claude `f2s-config-inject` PreToolUse** | 在调用 **`f2s-*` Skill** 时注入解析结果;**缺文件 / 坏 JSON / hook 异常**仍输出说明与默认语义,避免静默。 |
| **Codex `AGENTS.md` + `renderProjectConfigBlock`** | 顶部 **Read** 硬约束 + **init 快照表**(与磁盘不一致时以 Read 为准)。 |
| **知识库 `config-precheck` 主题** | 路由命中时只提供**摘要**与链向 Codex 长文,**不**替代 Read JSON。 |
**权威仍为**项目根 JSON 的 **Read** 结果;各层为提示而非第二份真值源。操作侧完整表格与路径见 **[使用说明 § 一、`f2s-*` 与 `flow2spec.config.json`](./使用说明.md)**;口述节奏见 **[Flow2Spec-演讲稿 Slide 13b](./Flow2Spec-演讲稿.md)**。
#### 6. 技能不复述统一入口规则,只引用
```
每个 SKILL.md 的编排部分写法:
subAgent / switchAgentVerification 语义
以统一入口为唯一事实源,本处不复述。
Cursor/Claude → rules/f2s-flow2spec-unified-entry.*
Codex → .codex/topics/f2s-flow2spec-unified-entry.md
15 个技能,每个只写自己特有的编排约束
公共规则统一在一处定义,修改一处全部生效
```
---
### 五、可插拔架构
#### 1. 工具可插拔:一份知识,任意组合工具
```
flow2spec init cursor claude codex ← 三工具全装
flow2spec init claude ← 只装 Claude
flow2spec init cursor codex ← 跳过 Claude
.Knowledge/ 始终不变,工具随时加减
```
同一份 `.Knowledge/` 驱动所有工具 · 加减工具不影响知识内容 · 新工具接入零重建
#### 2. 知识主题可插拔:增删不连带
```
添加主题 删除主题
───────────────────── ─────────────────────
1. 写 topics/xxx.md f2s-ctx-rm stock-docs/xxx.md
2. 写 matchers/m-xxx.json ↓
3. 在 manifest-routing 注册 自动清除 topics/ + manifest
+ index 引用
其他主题完全不受影响
```
新主题只需在 `topicDependencies` 里声明依赖 · 不声明则彼此独立 · 删除无副作用
#### 3. 技能可插拔:自包含单元,项目级可覆盖包级
```
包级技能(随 flow2spec init 分发) 项目级技能(放 配置根/skills/)
f2s-kb-sync/SKILL.md my-domain-skill/SKILL.md
f2s-doc-arch/SKILL.md my-review-skill/SKILL.md
...
名字不冲突则共存 · 同名则项目级覆盖包级 · 互不感知
```
技能靠 `description` 字段自描述触发词 · 不需要注册表 · 不需要改全局配置 · 上线即生效
#### 4. 路由词表可插拔:分片隔离,局部更新
词条变更只改对应 `matchers/m-xxx.json`,其他路由 diff 为零;结构见「[一、路由与上下文加载 → matchers 分片](#matchers-分片不嵌入-manifest)」。
词条变更局部化 · 合并冲突最小化 · 新增路由不影响存量
#### 5. 执行模型可插拔:config 按项目切换
```
flow2spec.config.json
subAgent: false → 全程主 agent,低开销,适合小项目
subAgent: true → 允许拆子并行,适合大规模改动
switchAgentVerification: false → 落盘侧自验,日常使用
switchAgentVerification: true → 交叉校验,高置信度关键场景
changeTracking.feat/fix/implement: false → 不创建任务清单
changeTracking.feat/fix/implement: true → 对应技能执行时自动创建任务清单,支持跨会话续作
三个维度正交 · 各技能可进一步细化覆盖全局配置
```
改一行配置切换执行策略 · 不修改任何技能文件 · 新项目开箱即用,老项目按需升级
---
## 优势与劣势
```
✅ 优势 ⚠️ 局限
上下文精准 前期投入:知识要靠技能建起来
└─ 路由只加载相关文档 规模门槛:小项目开销 > 收益
跨工具共享 需要团队纪律
└─ 知识写一份,三工具都用 └─ 技能只降低摩擦,不消灭摩擦
工具无关 学习曲线
└─ 换工具不重建知识 └─ stock/req 边界、路由结构不直觉
可持续
└─ 维护绑定开发动作
```
---
## 适合谁
```
项目规模
小 ◄──────────► 大
┌──────────┬────────────┐
短期 │ 不需要 │ 可以用 │
├──────────┼────────────┤
长期 │ 可以用 │ 强烈推荐 │
└──────────┴────────────┘
同时满足:有规模 · 长期迭代 · 多工具或多人 AI 协作
```
---
## 相关文档
- [使用说明](./使用说明.md)
- [命令说明](./命令说明.md)
- [体系与原理](./体系与原理.md)
- [使用案例-模拟对话](./使用案例-模拟对话.md)
- [Flow2Spec-演讲稿](./Flow2Spec-演讲稿.md)
MIT License
Copyright (c) 2026 兰涛
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+2
-2

@@ -61,3 +61,3 @@ #!/usr/bin/env node

更多说明见 README.md 或 docs/Flow2Spec使用说明.md
更多说明见 README.md 或 docs/使用说明.md
`;

@@ -328,3 +328,3 @@

建议阅读 README 或 docs/Flow2Spec使用说明.md,按「规则在配置根、文档在 .Knowledge」的方式使用。
建议阅读 README 或 docs/使用说明.md,按「规则在配置根、文档在 .Knowledge」的方式使用。
`);

@@ -331,0 +331,0 @@ })

{
"name": "@double-codeing/flow2spec",
"version": "3.0.14",
"version": "3.0.15",
"description": "在业务仓库初始化「文档驱动、可写回知识库」的 AI 协作骨架:项目根 .Knowledge 承载 stock-docs/req-docs 与机读路由,.cursor/.claude/.codex 写入 f2s-* 规则与技能(含 Karpathy 式编码行为准则 f2s-karpathy-guidelines,init 同步 rules / Codex topics / skills);init 只落结构与模板,业务内容由各 f2s-* 技能在对话中维护。",

@@ -5,0 +5,0 @@ "homepage": "https://github.com/Lands-1203/Flow2Spec#readme",

@@ -8,3 +8,3 @@ # Flow2Spec — Let AI Always Know What You're Doing

🎬 **[Live Demo (English)](https://lands-1203.github.io/Flow2Spec/en/)** | **[中文演示](https://lands-1203.github.io/Flow2Spec/)** (13-slide HTML PPT, `←` `→` to navigate, `S` for presenter mode)
🎬 **[Live Demo](https://lands-1203.github.io/Flow2Spec/)** (13-slide HTML PPT, `←` `→` to navigate, `S` for presenter mode)

@@ -14,3 +14,3 @@ 🔧 **Quick start**:

```bash
npx @double-codeing/flow2spec@latest init
npx @ctrip/flow2spec@latest init
```

@@ -73,3 +73,3 @@

```bash
npx @double-codeing/flow2spec@latest init
npx @ctrip/flow2spec@latest init
```

@@ -100,16 +100,16 @@

### English
- [Usage Guide](./docs/usage-guide.en.md) — skill chains, config details
- [Commands Reference](./docs/commands-reference.en.md) — all f2s-* command reference
- [Directory Conventions](./docs/directory-conventions.en.md)
- [Architecture & Principles](./docs/architecture.en.md)
- [Usage Scenarios](./docs/usage-scenarios.en.md)
- [Design Principles](./docs/design-principles.en.md)
- [Usage Guide](./docs/en/usage-guide.md) — skill chains, config details
- [Commands Reference](./docs/en/commands-reference.md) — all f2s-* command reference
- [Directory Conventions](./docs/en/directory-conventions.md)
- [Architecture & Principles](./docs/en/architecture.md)
- [Usage Scenarios](./docs/en/usage-scenarios.md)
- [Design Principles](./docs/en/design-principles.md)
### 中文
- [使用说明](./docs/Flow2Spec使用说明.md)
- [命令说明](./docs/README-命令说明.md)
- [目录与路径约定](./docs/README-目录与路径约定.md)
- [体系与原理](./docs/README-体系与原理.md)
- [使用案例·模拟对话](./docs/Flow2Spec-使用案例-模拟对话.md)
- [设计说明](./docs/Flow2Spec-设计说明.md)
- [使用说明](./docs/使用说明.md)
- [命令说明](./docs/命令说明.md)
- [目录与路径约定](./docs/目录与路径约定.md)
- [体系与原理](./docs/体系与原理.md)
- [使用案例·模拟对话](./docs/使用案例-模拟对话.md)
- [设计说明](./docs/设计说明.md)

@@ -116,0 +116,0 @@ ## License

+15
-15

@@ -8,3 +8,3 @@ # Flow2Spec — 让 AI 一直知道你在做什么

🎬 **[在线演示(中文)](https://lands-1203.github.io/Flow2Spec/)** | **[English Demo](https://lands-1203.github.io/Flow2Spec/en/)**(13 页 HTML PPT,`←` `→` 翻页,`S` 演讲者模式)
🎬 **[在线演示](https://lands-1203.github.io/Flow2Spec/)**(13 页 HTML PPT,`←` `→` 翻页,`S` 演讲者模式)

@@ -14,3 +14,3 @@ 🔧 **快速体验**:

```bash
npx @double-codeing/flow2spec@latest init
npx @ctrip/flow2spec@latest init
```

@@ -74,3 +74,3 @@

```bash
npx @double-codeing/flow2spec@latest init
npx @ctrip/flow2spec@latest init
```

@@ -101,16 +101,16 @@

### 中文
- [使用说明](./docs/Flow2Spec使用说明.md) — 技能链、配置详解
- [命令说明](./docs/README-命令说明.md) — 所有 f2s-* 命令速查
- [目录与路径约定](./docs/README-目录与路径约定.md)
- [体系与原理](./docs/README-体系与原理.md)
- [使用案例·模拟对话](./docs/Flow2Spec-使用案例-模拟对话.md)
- [设计说明](./docs/Flow2Spec-设计说明.md)
- [使用说明](./docs/使用说明.md) — 技能链、配置详解
- [命令说明](./docs/命令说明.md) — 所有 f2s-* 命令速查
- [目录与路径约定](./docs/目录与路径约定.md)
- [体系与原理](./docs/体系与原理.md)
- [使用案例·模拟对话](./docs/使用案例-模拟对话.md)
- [设计说明](./docs/设计说明.md)
### English
- [Usage Guide](./docs/usage-guide.en.md)
- [Commands Reference](./docs/commands-reference.en.md)
- [Directory Conventions](./docs/directory-conventions.en.md)
- [Architecture & Principles](./docs/architecture.en.md)
- [Usage Scenarios](./docs/usage-scenarios.en.md)
- [Design Principles](./docs/design-principles.en.md)
- [Usage Guide](./docs/en/usage-guide.md)
- [Commands Reference](./docs/en/commands-reference.md)
- [Directory Conventions](./docs/en/directory-conventions.md)
- [Architecture & Principles](./docs/en/architecture.md)
- [Usage Scenarios](./docs/en/usage-scenarios.md)
- [Design Principles](./docs/en/design-principles.md)

@@ -117,0 +117,0 @@ ## 协议

@@ -33,3 +33,3 @@ > **主口径(统一知识库)**:技术方案模板与产物统一维护在 `/.Knowledge/template/` 与 `/.Knowledge/req-docs/`。

- 二级标题:`## 外部对接和内部调用`
- 简要列出:依赖的外部 HTTP/RPC/券台/订单等;本服务内部会调用的模块或方法(不必展开到每个参数)。
- 简要列出:依赖的外部 HTTP/RPC/消息队列等;本服务内部会调用的模块或方法(不必展开到每个参数)。

@@ -36,0 +36,0 @@ ---

@@ -1,3 +0,2 @@

> **主口径(统一知识库)**:终稿模板与终稿文档统一维护在 `/.Knowledge/template/` 与 `/.Knowledge/stock-docs/`。
> 本模板唯一来源为 `templates/knowledge/template/终稿模版.md`。
> **主口径(统一知识库)**:终稿模板与终稿文档统一维护在 `.Knowledge/template/` 与 `.Knowledge/stock-docs/`。

@@ -4,0 +3,0 @@ # 终稿概述模版

@@ -1,2 +0,2 @@

> **主口径**:模板在 `templates/knowledge/template/项目里程碑模版.md`;生成物在 `.Knowledge/stock-docs/<范围名>里程碑.md`。
> **主口径**:模板在 `.Knowledge/template/项目里程碑模版.md`(由 `flow2spec init` 落地);生成物在 `.Knowledge/stock-docs/<范围名>里程碑.md`。
> **执行 `f2s-doc-milestone`**:结构以本模版为准;内容仅来自 **req-docs、git log、.task** 与知识库主题,禁止臆造。

@@ -3,0 +3,0 @@ > **阶段**:Mx **仅**功能/能力变更;**不得**单独成阶段的联调、测试、验收或纯环境运维;工程性改动并入对应功能阶段。

@@ -5,3 +5,3 @@ # f2s-req-plan(路由摘要)

> **`.task/` 真值源**:配置根 **`rules/f2s-task.*`**(Codex:`.codex/topics/f2s-task.md`)。
> 设计背景:[Flow2Spec 任务清单与变更追踪](../stock-docs/<任务清单说明>.md)(可选)。
> 设计背景(可选):[任务清单与变更追踪](../stock-docs/<任务清单说明>.md)。

@@ -8,0 +8,0 @@ ## 依赖

# f2s-task(路由摘要)
> 长文见配置根 **`rules/f2s-task.*`**。
> 体系化设计说明(两种模式、目录、`todo.json`):[Flow2Spec 任务清单与变更追踪](../stock-docs/Flow2Spec-任务清单与变更追踪.md)。
> 体系化设计说明(可选):在 `stock-docs/` 自建任务清单说明后,于本主题或 `index.md` 中链接,例如 `../stock-docs/<任务清单说明>.md`。

@@ -6,0 +6,0 @@ ## 作用

@@ -92,6 +92,6 @@ ---

用户输入:`f2s-ctx-build .Knowledge/stock-docs/支付回调改造_终稿.md`,且现有 `topics/payment.md` 已存在。
用户输入:`f2s-ctx-build .Knowledge/stock-docs/回调改造_终稿.md`,且现有 `topics/callback.md` 已存在。
- 若新文档与现有 `payment` 主题高度重合:原位更新 `topics/payment.md`,不要新建 `payment-v2.md`。
- 若新文档新增“重试补偿”子能力:可新增 `topics/payment-retry.md`,并在 `manifest-routing.topicDependencies` 中声明 `payment-retry -> payment`。
- 若新文档与现有 `callback` 主题高度重合:原位更新 `topics/callback.md`,不要新建 `callback-v2.md`。
- 若新文档新增「重试补偿」子能力:可新增 `topics/callback-retry.md`,并在 `manifest-routing.topicDependencies` 中声明 `callback-retry -> callback`。
- 更新后同步 `index` 与路由清单,确保 `topicPaths`、`fallbackTopic`、`matcherId` 仍有效。

@@ -98,0 +98,0 @@

@@ -42,3 +42,3 @@ ---

用户输入文件名片段“支付”,匹配到 2 个主题文档。
用户输入文件名片段「回调」,匹配到 2 个主题文档。

@@ -45,0 +45,0 @@ - 先列出两个候选并要求用户确认删除范围,避免误删。

@@ -91,3 +91,3 @@ ---

- 先继续处理可读文件,初稿中明确列出不可读路径和缺口,不因部分失败中断全流程。
- 若发现已有 `.Knowledge/stock-docs/支付能力_终稿.md`:优先在该终稿上修订,而不是新建重复终稿。
- 若发现已有 `.Knowledge/stock-docs/<能力名>_终稿.md`:优先在该终稿上修订,而不是新建重复终稿。
- 用户要求“先审初稿”:必须停在初稿,等待确认后再生成终稿并进入 `f2s-ctx-build` 同步。

@@ -94,0 +94,0 @@

@@ -73,3 +73,3 @@ ---

| 整个项目(默认) | 不传 / `整个项目` / `全项目` | `项目里程碑.md` |
| 某一需求或能力 | `支付回调改造` / `登录模块` | `<简述>里程碑.md` |
| 某一需求或能力 | `回调改造` / `登录模块` | `<简述>里程碑.md` |

@@ -76,0 +76,0 @@ **文件名规则**:后缀 `里程碑.md`;整个项目 → 前缀 `项目`;单一需求 → 语义或 req 标题简述(≤ 20 字)。

@@ -49,3 +49,3 @@ ---

1. 从 `git diff HEAD` 及 untracked 文件路径推断本次变更涉及的**功能模块**(如:支付、订单、用户认证等)。
1. 从 `git diff HEAD` 及 untracked 文件路径推断本次变更涉及的**功能模块**(以仓库内目录/包名为准,勿臆测未出现的业务名)。
2. 读取 `.Knowledge/topics/` 目录列表与 `.Knowledge/stock-docs/` 目录列表。

@@ -52,0 +52,0 @@ 3. 对比步骤 1 推断出的功能模块,判断对应文档是否已在知识库中登记。

@@ -62,3 +62,3 @@ ---

用户指出"订单回调幂等实现错误",但未给明确文件范围。
用户指出「某回调接口幂等实现错误」,但未给明确文件范围。

@@ -65,0 +65,0 @@ - 先按最小可行范围修复已定位的回调处理链路,并在摘要中说明"可继续扩展全仓同类修复"。

@@ -91,3 +91,3 @@ ---

- 步骤 1 先做最小推断(例如支付、订单两个高频能力),并给出推断依据。
- 步骤 1 先做最小推断(例如从 `git diff` / 目录名归纳 1~2 个能力域),并给出推断依据。
- 步骤 2 必须输出大纲并等待“确认”;未确认前禁止写入任何 `.Knowledge` 文件。

@@ -94,0 +94,0 @@ - 用户确认后只执行大纲内条目;若用户中途缩小范围,未执行项写入收尾摘要。

@@ -35,2 +35,2 @@ ---

见 Flow2Spec 包内 **`docs/README-目录与路径约定.md`**;技能顺序与 **f2s-doc-arch** / **f2s-doc-add** 见 **`docs/README-命令说明.md`**。具体步骤以配置根 **`skills/<技能名>/SKILL.md`**(如 **f2s-ctx-build**、**f2s-doc-add**)为准。
以本技能对照表与配置根 **`skills/<技能名>/SKILL.md`**(如 **f2s-ctx-build**、**f2s-doc-add**、**f2s-doc-arch**)为准;`.Knowledge/topics/f2s-stock-docs-vs-req-docs.md` 为路由摘要。
[中文](./README-体系与原理.md) | [English](./architecture.en.md)
# Architecture & Principles
Flow2Spec's goal is to separate "business knowledge curation" from "Agent capability loading":
- **Knowledge layer**: `.Knowledge` (documents and index)
- **Execution layer**: config root `rules/skills` (natively loaded by each tool)
---
## 1. Two-Layer Structure
| Layer | Location | Role |
| --- | --- | --- |
| Knowledge layer | `.Knowledge/` | Stores business documents, index, routing |
| Execution layer | `.cursor/.claude/.codex` | Stores rules and skill entry points |
---
## 2. Progressive Reading
The recommended unified order:
1. `.Knowledge/manifest-routing.json`
2. `.Knowledge/matchers/<matcher>.json` (on demand: directly located by `manifest-routing.taskToTopicRules[].matcherPath`)
3. `.Knowledge/index.md`
4. The matched `stock-docs` / `req-docs` documents
5. Source code drill-down when necessary
After reading, execute the four-step pipeline `match -> expand -> verify -> act`: expand dependency topics after hitting the primary candidate, perform gap analysis, execute only when confidence is sufficient; clarify first when confidence is low.
Simultaneously, loading behavior is governed by the config root entry points (Flow2Spec package rules: `f2s-flow2spec-unified-entry.mdc` / `f2s-flow2spec-unified-entry.md`; legacy business repos commonly use `main.md(c)`; and `AGENTS.md`).
Codex does not read the `rules/` directory; execution constraints are carried through `.codex/AGENTS.md` + `skills/`.
---
## 3. Key Chains
- Documentation curation chain: `f2s-doc-arch` -> `f2s-doc-final` -> `f2s-ctx-build`
- Implementation chain: `.Knowledge/req-docs/*.md` -> `implement-tech-design` -> code
- Maintenance chain: `f2s-kb-fix` / `f2s-kb-feat` / `f2s-kb-sync` / `f2s-kb-merge`
- Requirements planning chain: `f2s-req-plan` (planning + implementation, always creates task checklist)
- Change tracking chain: `changeTracking.*` config -> `f2s-task` rules (automatic) -> `.task/` task checklist -> cross-session continuation
- Package template/routing shape alignment with config root: `f2s-kb-upgrade` (**do not** equate running `flow2spec init` alone with "knowledge base upgrade"); migrate legacy repo structure into `.Knowledge`: `f2s-kb-migrate`
---
## 4. Agent Execution Model
Flow2Spec controls execution behavior through two fields in the project root `flow2spec.config.json`: `subAgent` and `switchAgentVerification`.
**How the Agent reads the above truth values**: multi-end prompts + **Read** as authority, see [usage-guide.en.md § 1 (the only detailed table)](./usage-guide.en.md); design summary see [design-principles.en.md § 4, 5.1](./design-principles.en.md).
### 4.1 Primary/Sub Agent Responsibility Division Principle
**`subAgent: false` (default)**: All `f2s-*` skills execute sequentially within the primary agent, no parallel decomposition.
**`subAgent: true`**: When the scale threshold agreed upon in the skill body is reached, sub-agents may be spawned for parallel processing. Responsibility boundaries are as follows:
| Role | Responsibility Boundary |
|------|----------|
| Primary agent | Overall planning, determining task granularity and allocation strategy, aggregating sub-agent output, verifying cross-unit consistency, final write-to-disk |
| Sub agent | Processes the assigned unit (module/document/topic), outputs results in the agreed format, does not make cross-unit decisions |
The decomposition boundaries for sub-agents are progressively defined by each `f2s-*` skill body (e.g., thresholds for module count, document count, code line count). **There is currently no unified stage table at the template layer**; the skill body takes precedence.
### 4.2 Verification Ownership Principle
**Default (whoever writes to disk verifies)**: Verification after write-to-disk or changes is performed within the agent that wrote to disk. If a sub-agent wrote, the sub-agent self-verifies; if the primary agent wrote, the primary agent self-verifies.
**Cross-verification (`switchAgentVerification: true`)**: The counterpart agent bears the verification responsibility, suitable for scenarios requiring higher confidence. The enabling conditions must be **satisfied simultaneously**:
1. Configuration `switchAgentVerification: true`
2. The currently executing `f2s-*` skill body **explicitly states** that the step depends on this field
Cross-verification rules:
| Writer | Verifier | Prerequisite |
|--------|--------|----------|
| Sub-agent writes | Primary agent verifies | No additional conditions |
| Primary agent writes | Sub-agent verifies | Requires `subAgent: true` and that sub-tasks have actually been decomposed; otherwise, the primary agent self-verifies |
Design intent: Cross-verification introduces an external perspective, reducing the blind spots in the writer's self-verification, but increases execution overhead. It is therefore an explicit opt-in rather than the default behavior.
### 4.3 Change Tracking (changeTracking)
`changeTracking` is a third dimension independent of `subAgent` / `switchAgentVerification`. It controls whether the skill automatically creates a task checklist that can be continued across sessions during execution.
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
- Each skill sub-item is independently controlled and does not affect each other
- When enabled: automatically checks `.task/todo.json` before skill execution, creates or resumes tasks; automatically archives upon completion
- Cross-session: when a new session describes related content, the `f2s-task` rule (`alwaysApply`) loads the remaining checklist and corresponding skill context after keyword matching
- `f2s-req-plan` is not constrained by this configuration and always creates a task checklist
---
## 5. Design Benefits
1. Share the same business knowledge source across tools
2. Does not break the rule loading conventions of Claude/Cursor/Codex
3. Controls task routing and dependencies via `manifest-routing` + `matcherPath` shards (`matchers/*.json`), reducing misreading and full scans
4. Clear primary/sub-agent responsibility boundaries: the primary agent always holds the global view, sub-agents focus on unit processing, consistency is ensured by the primary agent
5. Configurable verification ownership: default self-verification by the writer keeps overhead low; cross-verification can be enabled on demand to boost confidence in critical scenarios
---
## 6. Related Documents
- [Usage Guide](./usage-guide.en.md)
- [Commands Reference](./commands-reference.en.md)
- [Directory Conventions](./directory-conventions.en.md)
- [Usage Scenarios](./usage-scenarios.en.md)
[中文](./README-命令说明.md) | [English](./commands-reference.en.md)
# Workflow and Skill Reference
## 1) Document Curation (stock-docs Pipeline)
### `f2s-doc-arch`
**Purpose**: Generates an architecture overview draft based on user descriptions or code scanning. No fixed format required; it should clearly describe the system structure, module relationships, and key decisions.
**How It Works**: Centered on inventory-driven scanning: the main agent first produces a module inventory and a scan contract (which entry points to read, which dimensions to focus on), then performs read-only code scanning according to that inventory, and finally aggregates the results into a human-readable architecture draft persisted under `stock-docs/`. The flow does not change code; it is one-way "code → document" extraction only.
**Use Cases**:
- A new project needs architecture documentation
- An existing project needs architecture descriptions supplemented
- Architecture descriptions need updating after a system refactor
**Relationships**:
- **Prerequisite**: None
- **Next Step**: `f2s-doc-final` (normalized final draft) or direct use with `f2s-ctx-build`
- **Output**: `.Knowledge/stock-docs/<Architecture Overview>_draft.md`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent scans the code and generates the output
- `subAgent: true`: Defaults to **B Mode** (main agent produces inventory + scan contract, sub-agents do parallel read-only table scans, main agent merges and persists); upgraded to **C Mode** (multi-round correction) when any of the following conditions are met: multi-workspace / monorepo, more than 20 source paths, first-round sub-tables have conflicts or gaps, or multi-source narratives have severe contradictions
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Produces inventory (entry points + core module names) and scan contract, aggregates sub-agent deliverables, persists stock-docs draft |
| Sub-Agent (B/C Mode) | Performs parallel read-only scans per the main agent's written inventory, delivers in a unified YAML schema (`source / scope / cross_refs / pending`), must not self-crop the scope |
---
### `f2s-doc-final`
**Purpose**: Converts PDF technical proposals or draft documents into the standardized "Final Draft Template" format, unifying the document structure for subsequent knowledge base ingestion.
**How It Works**: Unstructured or heterogeneous documents (PDF/drafts) are normalized against the built-in final-draft template: core concept tables, business rules, key flows, configuration, error handling, and other standard sections are extracted; missing section markers are filled in; the output is a consistently structured `_final.md`. The final draft is the standard input for `f2s-ctx-build`, keeping knowledge-base entry structure uniform.
**Use Cases**:
- PDF technical proposals need conversion to Markdown
- Draft documents need normalization for long-term storage
- External documents need to be incorporated into Flow2Spec management
**Relationships**:
- **Prerequisite**: PDF document or draft document
- **Next Step**: `f2s-ctx-build` (final draft imported into the knowledge base)
- **Output**: `.Knowledge/stock-docs/<Document>_final.md`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the full workflow
- `subAgent: true`: When the PDF exceeds 50 pages or 5MB, sub-agents may be used for template application and layout drafting; sub-agents must not ask the user questions, write process descriptions, or claim final-draft compliance; the main agent identifies format gaps and accepts the finalized draft
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Identifies format gaps, accepts the finalized draft against the template and clarification document |
| Sub-Agent | Applies templates and produces layout drafts; does not ask users questions or write process descriptions |
---
### `f2s-ctx-build`
**Purpose**: Synchronizes documents from `stock-docs/` (architecture, final drafts) into the knowledge base routing system, generating/updating topic files, the index, manifest-routing, and matchers.
**How It Works**: Starting from a final-draft document, it runs a three-step "document → routing" mapping: (1) extract capability topics and keywords from the draft; (2) generate `topics/<topic>.md` (routing summary with execution boundaries and next-step pointers) and `matchers/<id>.json` (machine-readable `includeAny` terms); (3) register task→topic rules in `manifest-routing.json` and update the human-readable `index.md`. After that, the task routing engine can hit the topic via keywords.
**Use Cases**:
- After a final draft is complete, the knowledge base needs to "know about" these documents
- A new business domain needs routing mappings established
- Document content has been updated and the knowledge base index needs to be synced
**Relationships**:
- **Prerequisite**: `f2s-doc-arch`, `f2s-doc-final`, or a directly authored final draft
- **Next Step**: None (ready for use once imported into the knowledge base)
- **Input**: `.Knowledge/stock-docs/*.md`
- **Output**:
- `.Knowledge/topics/<topic>.md`
- `.Knowledge/index.md`
- `.Knowledge/manifest-routing.json`
- `.Knowledge/matchers/*.json`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent processes each document sequentially
- `subAgent: true`: Enabled when changes exceed thresholds (more than 2 topics added/modified OR more than 1 matcher added OR cross-topic bulk reference adjustments); sub-agent A writes only to `topics/`, sub-agent B writes only to `matchers/`; the main agent handles single-point edits to `manifest-routing.json` and `index.md`; sub-agents must not cross boundaries
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Single-point persist of `manifest-routing.json` and `index.md`, overall acceptance |
| Sub-Agent (topics) | Writes only topic files under `topics/`, does not touch manifest or index |
| Sub-Agent (matchers) | Writes only shard files under `matchers/`, does not touch manifest or index |
---
### `f2s-doc-add`
**Purpose**: Parses already-implemented capabilities (aggregated from multiple files) into the knowledge base. Suitable when code already exists but lacks documentation, or when multiple documents need to be imported into the knowledge base in a unified manner.
**How It Works**: Aggregates capability descriptions from multiple scattered sources (code, config, loose docs) and runs the full "draft → final draft → topics/index/manifest" pipeline. Unlike `f2s-ctx-build`, the input differs: `ctx-build` is driven from a single existing final draft; `doc-add` aggregates many scattered sources first, then follows the same pipeline. It closes the gap of "implementation exists but documentation does not."
**Use Cases**:
- Existing code needs knowledge base documentation
- Multiple related documents need aggregated import
- Bulk import of third-party documents
**Relationships**:
- **Prerequisite**: None (can be triggered directly)
- **Next Step**: None (ends once imported into the knowledge base)
- **Flow**: Draft -> Final Draft -> topics/index/manifest
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent processes sequentially
- `subAgent: true`: Enabled when any of the following thresholds are met; defaults to **B Mode** (main agent produces inventory, sub-agents do parallel read-only schema-based table fills, main agent merges and persists); upgraded to **C Mode** (multi-round correction) for multi-workspace / monorepo, first-round sub-table conflicts or gaps, or severe multi-source contradictions
- Thresholds: 5 or more input paths OR single source exceeds 3000 lines OR total across multiple paths exceeds 10000 lines
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Produces inventory and scan contract, aggregates sub-tables, persists topics/index/manifest |
| Sub-Agent (B/C Mode) | Performs read-only scans per the main agent's written inventory, delivers tables in schema format (`source / scope / capabilities / cross_refs / pending`); must not self-crop the scope, write manifest or index, or claim "already in the knowledge base" |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topic files persisted by sub-agents -> Main agent verifies routing mapping completeness and keyword coverage
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-ctx-rm`
**Purpose**: Deletes corresponding knowledge topics and index mappings based on `stock-docs` documents. Only removes reference relationships in the knowledge base, not the source documents themselves.
**How It Works**: The inverse of `f2s-ctx-build` — given a `stock-docs` document path, locate its task→topic rules in `manifest-routing.json`, the corresponding `matchers/<id>.json` shard, `topics/<topic>.md`, and entries in `index.md`, and remove those references one by one. If a topic has no remaining task references after deletion, remove that topic file. Source documents are left in place; the user may delete them physically if desired.
**Use Cases**:
- A document is deprecated and needs removal from the knowledge routing
- A document was imported by mistake and its routing mapping needs revocation
- Cleaning up old mappings after document consolidation
**Relationships**:
- **Prerequisite**: A stock-docs document that has already been imported
- **Next Step**: None
- **Note**: Only deletes routing mappings, not source documents
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent handles the full workflow (single-point deletion has low sub-agent ROI)
- `subAgent: true`: Sub-agents are used only for **batch deletion of 5 or more topics**; the main agent must control scope confirmation and `fallbackTopic` re-pointing; `manifest-routing.json` and `index.md` are always persisted by the main agent
---
### `f2s-doc-pdf`
**Purpose**: Converts PDF technical proposals to Markdown format, saves to `req-docs/`, and can supplement the process description.
**How It Works**: Targets the step before "implement from a proposal" — extracts structured content from the PDF (API definitions, data models, sequence flows, etc.) into Markdown under `req-docs/`. Unlike `f2s-doc-final`, the destination and use differ: `doc-pdf` writes to `req-docs/` for consumption by the `implement-tech-design` rule to drive coding; `doc-final` writes to `stock-docs/` for ingestion via `ctx-build`.
**Use Cases**:
- A PDF technical proposal needs to be implemented
- Historical PDF documents need to be managed
- Cross-team deliverables are in PDF format and need conversion
**Relationships**:
- **Prerequisite**: PDF document
- **Output**: `.Knowledge/req-docs/<Proposal>.md`
- **Next Step**:
- 1. If it is a requirement to implement: provide the converted proposal path with instructions "implement according to the technical proposal", driven by the `implement-tech-design` rule
- 2. If it is for knowledge base archival: follow the final-draft conversion flow `f2s-doc-final` -> `f2s-ctx-build`
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the full workflow
- `subAgent: true`: When the PDF exceeds 50 pages or 5MB, sub-agents may be used for the PDF -> MD first draft and persist to `req-docs`; sub-agents must not ask the user questions or supplement process description sections; the main agent handles follow-up questions and process description supplementation
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Asks the user for process description supplements, completes `req-docs` deposition acceptance |
| Sub-Agent | Only performs PDF -> MD first draft and persists to `req-docs`, does not ask the user questions |
---
## 2) Requirements and Proposals
### `f2s-req-clarify`
**Purpose**: Asks clarifying questions against PRDs/requirement documents, using multi-round Q&A to define requirement boundaries, non-goals, and key flows, until the requirements are clear enough for a technical proposal.
**How It Works**: Uses a "structured questioning" strategy — decomposes the requirement document along six dimensions (roles, scenarios, flows, boundaries, exceptions, non-goals), checks each for vague wording, undefined concepts, or contradictions, and generates targeted questions for each gap. Dialogue continues until all dimensions are unambiguous, then outputs a clarification record as input for `f2s-req-backend`. It turns unstructured PRDs into structured, actionable requirement constraints.
**Use Cases**:
- First step after receiving a PRD, ensuring correct understanding
- When requirement boundaries are fuzzy or acceptance criteria are missing
- Cross-team collaboration requirements that need clear interface contracts
**Relationships**:
- **Prerequisite**: None (can be triggered directly)
- **Next Step**: `f2s-req-backend` (generates a technical proposal after clarification)
- **Output**: Requirement clarification record (optionally saved to `.Knowledge/req-docs/`)
**Sub-Agent Invocation**: None (clarification relies on continuous dialogue and immediate user feedback throughout; no sub-agent splitting)
---
### `f2s-req-backend`
**Purpose**: Based on clarified requirements and the project knowledge base, generates a backend technical proposal document including API design, data models, flow descriptions, error codes, etc.
**How It Works**: Centered on "knowledge base constraints + template-driven" authoring — first pull a constraint summary for the current project from `topics/stock-docs` (architecture conventions, API style, data model norms, etc.), then fill the backend technical proposal template (APIs / models / flows / errors / config / migrations) chapter by chapter against the clarified requirements so the proposal matches the existing architecture. Output is persisted under `req-docs/` as the coding contract for `implement-tech-design`.
**Use Cases**:
- After `f2s-req-clarify` completes, output a proposal based on clarification results
- When clear requirement documents already exist, directly generate a technical proposal
**Relationships**:
- **Prerequisite**: `f2s-req-clarify` (recommended) or a clear requirement document
- **Output**: `.Knowledge/req-docs/<Technical Proposal>.md`
- **Next Step**: Provide the technical proposal path with instructions "implement according to the technical proposal", driven by the `implement-tech-design` rule
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the proposal within the session
- `subAgent: true`: The main agent must first extract a project convention summary (under 80 lines) from topics/stock-docs (covering architecture conventions, API style, data model standards, etc. across 6 categories) as the mandatory sub-agent context, then dispatch sub-agents to write the `req-docs` draft in parallel; the main agent handles contract finalization and acceptance
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Extracts project convention summary, assigns writing tasks, finalizes the draft against the template, and writes to `req-docs` |
| Sub-Agent | Read-only access to multiple sources (topics / stock-docs / clarified req-docs / templates), writes `req-docs` draft per template; must not expand the read scope on its own |
**Cross-Verification (when `switchAgentVerification: true`)**:
- API/model/flow documents persisted by sub-agents -> Main agent verifies cross-chapter consistency (API signatures align with data models, flows and error handling coverage)
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-req-plan`
**Purpose**: Starting from a technical proposal or requirement description, **always creates a task checklist**, then implements the code accordingly. Does not depend on the `changeTracking` configuration; represents the user's explicit need for traceable task management.
**How It Works**: Runs a five-phase closed loop: parse → plan → confirm → implement → archive. (1) Parse the technical proposal for implementation points; (2) split into executable tasks at module/feature granularity and write to `.task/`; (3) show the draft to the user, lock the checklist after confirmation; (4) implement item by item, checking off `task.md` immediately when each item completes; (5) archive when all are done. Unlike the `implement-tech-design` rule, `req-plan` always carries task tracking and can parallelize implementation with sub-agents for large work; the rule path is lightweight, single-threaded coding.
**Use Cases**:
- A technical proposal document exists and needs to be broken down into a task list before implementation
- The requirement description is complex and the user wants to confirm the checklist before starting work
- The user wants to track implementation progress across sessions
**Relationships**:
- **Prerequisite**: Technical proposal document path (`.Knowledge/req-docs/*.md` or PDF) or requirement/change description
- **Output**: `.task/active/<task-name>/task.md` + `context.md`; implementation code
- **Next Step**: Optionally invoke `f2s-kb-sync` to supplement the knowledge base
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes parsing, confirmation, and implementation in full
- `subAgent: true`: Step 1 (document parsing) can dispatch sub-agents for parallel read-only; Step 2 (draft confirmation) must be done by the main agent; Step 4 (code implementation) can dispatch sub-agents per module; `todo.json` is always written by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Outputs draft, gets user confirmation, writes `todo.json`, aggregates implementation summary |
| Sub-Agent (parsing) | Read-only document parsing, outputs parsing result summary, does not persist |
| Sub-Agent (implementation) | Implements code per module, does not touch `.task/` or `.Knowledge/` |
---
## 3) Git Commit
### `f2s-git-commit`
**Purpose**: Executes a Git commit after code is written. Automatically checks changed files, compares knowledge base coverage, prompts the user about capabilities not yet imported, and performs the commit after the commit message is confirmed.
**How It Works**: Layers a "knowledge base coverage gate" on top of `git commit` — infer touched capability areas from `git diff`, cross-check against `.Knowledge/topics/` and `stock-docs/`, and decide whether changed capabilities are documented in the knowledge base. If not covered, block and offer three choices (document first / skip / cancel) to avoid silent drift where "code exists but the knowledge base does not know." Commit messages use emoji + Conventional Commits for consistent, machine-friendly `git log`.
**Use Cases**:
- Committing code after each feature implementation or bug fix
- Wanting reminders about knowledge base coverage at commit time
- Needing AI help to generate meaningful commit messages
**Relationships**:
- **Prerequisite**: Code has been written (after `implement-tech-design`, `f2s-kb-fix`, `f2s-kb-feat`, etc.)
- **Next Step**: None (ends when commit completes; does not auto-push)
- **Bridging**: If the knowledge base is not yet covered, you can first run `f2s-kb-sync` or `f2s-kb-feat` to supplement before committing
**Execution Flow**:
1. `git status --short` + `git diff HEAD` to classify files into staged / unstaged / untracked; immediately terminates if merge conflict markers are found
2. Compare `.Knowledge/topics/` and `stock-docs/` to determine whether the changed capabilities have been imported; skips and notifies if `.Knowledge` does not exist
3. If not covered, prompt the user to choose: A) Import first, then commit / B) Commit now, import later / C) Cancel
4. Generate a commit message draft based on `git diff` content, wait for user confirmation or changes
5. `git add <specific files>` + `git commit`; if a hook fails, prompt for fix, do not skip
6. Output the commit hash; if option B was selected, include a reminder about capabilities not yet imported
**Constraints**:
- `git add -A` / `git add .` is forbidden; only add confirmed changed files
- `--no-verify` is forbidden; hook failures must be fixed and retried
- Auto-push is forbidden
- The commit message must be confirmed by the user; silent commits are not allowed
**Sub-Agent Invocation**: None (full interactive confirmation, handled within the main agent)
---
## 4) Knowledge Base Maintenance
### `f2s-kb-fix`
**Purpose**: Fixes code based on implementation or rule errors reported by the user, and **by default automatically syncs** the knowledge base documents and index.
**How It Works**: Three steps: locate → fix → sync. From the user's description, locate context and code via the knowledge routing path (manifest → topic → stock-docs) and confirm root cause; after fixing code, automatically check whether related descriptions in `topics/stock-docs/matchers` need updates and revise in place if so (current truth only, no stacked historical negation). "Fix code, sync docs" is the core principle to prevent knowledge drift.
**Use Cases**:
- Code implementation does not match the technical proposal
- Rule understanding errors need correction
- Documentation needs to be synced after bug fixes
**Change Tracking**: If `changeTracking.fix: true`, automatically checks `.task/todo.json` before execution, creates a task checklist, and automatically archives upon completion; cross-session continuation via keywords is supported (see `f2s-task` rules).
**Relationships**:
- **Prerequisite**: Problem discovered (code implementation error or rule deviation)
- **Next Step**: None (ends when fixes and sync are complete)
- **Feature**: No need for the user to explicitly request "please sync the knowledge base"; it is done automatically
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes fixes and knowledge base sync
- `subAgent: true`: Code sub-packages (bug fixes) can be outsourced to sub-agents; documentation sub-packages (rules/skills/topics style-related) default to the main agent writing directly; if sub-agents are used, they only output before/after diff snippets, not full-file rewrites; manifest and index are always persisted by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Locates root cause, devises fix plan, persists style-compliant content, verifies knowledge base consistency |
| Sub-Agent (code) | Responsible for bug fixes in designated modules, outputs changes and reports impact scope |
| Sub-Agent (documentation, optional) | Only outputs before/after diff snippets, no full-file rewrites, does not touch manifest or index |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Code changes persisted by sub-agents -> Main agent verifies fix correctness and knowledge base consistency
- Knowledge base sync persisted by the main agent -> Sub-agent reviews topic/manifest consistency (requires `subAgent: true` and sub-tasks actually dispatched; otherwise self-verification within the main agent)
- The reviewer and the persister must be different agent instances
---
### `f2s-kb-feat`
**Purpose**: When adding a new capability, completes both the implementation and the knowledge base; if the capability is already implemented, only syncs the knowledge base.
**How It Works**: Three phases: assess → implement → ingest. First assess whether the described capability is not implemented, partially implemented, or already implemented in code; if not or partial, complete the code first; then sync the knowledge base: write a capability description in `stock-docs`, generate or update `topics` summaries, register routing in `manifest-routing` and `matchers`. Unlike `f2s-kb-fix`, `kb-feat` targets **new** work; `kb-fix` targets **correcting existing** work.
**Use Cases**:
- New feature development
- Adding knowledge base documentation for an existing feature
**Change Tracking**: If `changeTracking.feat: true`, automatically checks `.task/todo.json` before execution, creates a task checklist, and automatically archives upon completion; cross-session continuation via keywords is supported (see `f2s-task` rules).
**Relationships**:
- **Prerequisite**: None (can be triggered directly)
- **Next Step**: None (ends when implementation + sync are complete)
- **Feature**: Knowledge base sync is automatic; no additional user request needed
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes everything
- `subAgent: true`: Code sub-packages (new implementation) can be outsourced to sub-agents; documentation sub-packages (rules/skills/topics style-related) default to the main agent writing directly; if sub-agents are used, they only output before/after diff snippets; manifest and index are always persisted by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Defines capability boundaries and implementation scope, persists style-compliant content, performs final verification of knowledge base consistency |
| Sub-Agent (code) | Responsible for code implementation (APIs, logic, data layer), outputs implementation checklist |
| Sub-Agent (documentation, optional) | Only outputs before/after diff snippets, no full-file rewrites, does not touch manifest or index |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topics persisted by documentation sub-agents -> Main agent verifies consistency between the capability description and the implementation code
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-kb-sync`
**Purpose**: Sinks already-implemented capabilities from the conversation back into the knowledge base. Can accept an explicit capability description or infer with zero input.
**Use Cases**:
- Implementation is complete within the conversation and needs knowledge base documentation
- Reverse-documenting knowledge from code
- Periodic knowledge base organization
**Relationships**:
- **Prerequisite**: None (can be triggered directly, or with zero-input inference)
- **Next Step**: None
- **Feature**: First outputs a knowledge base update outline, then writes only after user confirmation
- **Difference from `f2s-ctx-build`**: `ctx-build` is driven from `stock-docs`; `kb-sync` infers from the conversation/code
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes inference and sync
- `subAgent: true`: Steps are split -- **Step 1** (aggregation and inference) can dispatch sub-agents for parallel read-only access to conversation history; **Step 2** (user confirmation of the outline) must be done by the main agent; **Step 3** (persist sync) can dispatch sub-agents to write topic/matcher files, but sub-agents must read 2-3 neighboring topic summaries for style alignment before persisting; manifest and index are always persisted by the main agent
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Outputs outline and gets confirmation, single-point persists manifest and index, final acceptance |
| Sub-Agent (aggregation) | Read-only access to conversation history, infers capability points, generates structured update outline fragments |
| Sub-Agent (sync) | Writes topic/matcher per outline, loads neighboring topic summaries for style alignment before persisting, does not touch manifest or index |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topics/matchers persisted by sync sub-agents -> Main agent verifies cross-topic routing completeness and `includeAny` keyword coverage
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-kb-merge`
**Purpose**: Resolves editor context conflicts after Git merges. An optional conflict file path can be provided.
**How It Works**: Layered by file kind — split conflict files into "safe to auto-merge" (structured files such as index, manifest, matchers, using union or latest) vs "needs user judgment" (implementation code, business rules, and other semantic files). Auto-resolve the former; for the latter, produce a comparison table (ours/theirs summary + recommendation) and list differences for the user to decide item by item. Design idea: knowledge-base metadata can be automated; business semantics must not be decided unilaterally.
**Use Cases**:
- Context conflicts arise after a Git merge/rebase
- Knowledge base file conflicts caused by multi-person collaboration
- Need to unify knowledge base state after branch merging
**Relationships**:
- **Prerequisite**: Conflicts generated by a Git merge
- **Next Step**: None (ends when conflicts are resolved)
- **Feature**: Implementation-side conflicts are only listed for the user to confirm
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent analyzes and resolves conflicts
- `subAgent: true`: Sub-agents can be dispatched for conflict scanning and classification into a comparison table (`file / category / ours_summary / theirs_summary / recommendation`); sub-agents must not merge files on their own; the main agent persists per strategy, handles implementation-side decisions, and completes acceptance
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Persists merge results per strategy, handles implementation-side conflict decisions, acceptance |
| Sub-Agent | Only performs conflict scanning and classification, delivers comparison table in the five-field schema, does not merge files on its own |
---
### `f2s-kb-migrate`
**Purpose**: Migrates an old-format knowledge base (`docs-index.md` + `rules/` pattern) into the `.Knowledge/` structure organized by topic.
**How It Works**: Uses the legacy `docs-index.md` and `rules/main.md(c)` as index clues, recursively finds all referenced business rules and skill files, and reorganizes by topic into `.Knowledge/` (`topics` / `stock-docs` / `req-docs`). After migration, persist `migration-report.md` (mapping table + proposed deletion paths), then clean up old files after user confirmation. A one-time structural merge of scattered rules/docs into one knowledge base.
**Use Cases**:
- Upgrading an old project to the new Flow2Spec version
- An existing knowledge base needs structured reorganization
**Relationships**:
- **Prerequisite**: Old-format knowledge base (`docs-index.md`, `rules/`, `skills/`)
- **Next Step**: `f2s-kb-upgrade` (**Flow V1**: old knowledge base must migrate first, then upgrade; **Current V2+ knowledge base** (including npm v3.x): see the upgrade skill Step 0)
- **Flow**:
1. Use `docs-index.md` + `rules/main.md(c)` as the primary index
2. Process all business `rules/` and business `skills/` in full (excluding `f2s-*` package skills)
3. Migrate all `stock-docs`/`req-docs`
4. Persist `.Knowledge/migration-report.md`
5. Delete migrated old files after user confirmation
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent migrates topic by topic
- `subAgent: true`: Sub-agents only handle migration + draft migration-report fragments (delivered as patches); status files (migration-report.md, deletion execution records) are exclusively persisted by the main agent; the main agent leads the deletion confirmation and closure
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Creates migration plan, consolidates migration results, persists migration-report, leads deletion confirmation and execution closure |
| Sub-Agent | Handles topic migration and draft fragment generation (patch format) for designated topics; does not write status files or deletion execution records |
**Cross-Verification (when `switchAgentVerification: true`)**:
- Topics migrated and persisted by sub-agents -> Main agent verifies migration completeness (whether old paths are fully covered, whether topic boundaries overlap)
- Only effective when `subAgent: true` and sub-tasks are actually dispatched; otherwise all verification happens within the main agent
---
### `f2s-kb-upgrade`
**Purpose**: Knowledge base template upgrade. Aligns manifest-routing and matchers shards.
**How It Works**: Uses "version branching + delegated init" — detect whether the current knowledge base is V1 (legacy structure, migrate first) or V2+ (already has `.Knowledge`): V1 runs migrate then init; V2+ runs `flow2spec init` directly for incremental package alignment (new templates, manifest schema upgrades, matcher shard format alignment). After upgrade, re-read SKILL.md to see if certain steps must be re-run. Unlike a standalone `init`, `kb-upgrade` includes version routing and re-run logic; `init` alone is a one-shot structural fill-in.
**Use Cases**:
- After a `flow2spec` package version upgrade, upgrade the project knowledge base template
- Upgrade an old project to the latest structure
**Relationships**:
- **Prerequisite**: `f2s-kb-migrate` (V1 flow) or an existing `.Knowledge/`
- **Includes**: Internally invokes `flow2spec init` for structural alignment
- **Note**: A standalone `flow2spec init` is **not** an upgrade command
**Flow Differences (in-skill routing codes, **not** equivalent to npm major versions)**:
- **V1**: First `f2s-kb-migrate`, then runs `flow2spec init`
- **Current Knowledge Base (V2+)**: When `.Knowledge` + `manifest-routing` are already stable, runs `flow2spec init` to align manifest-routing + matchers shards (**includes Flow2Spec npm v3.x, etc.**; see `skills/f2s-kb-upgrade/SKILL.md` Step 0 for details)
**Sub-Agent Invocation**:
- `subAgent: false` (default): The main agent completes the upgrade
- `subAgent: true`: Sub-agents only handle shell command execution (running `flow2spec init`), not knowledge base content persistence; the following steps must not be delegated by the main agent: version routing (V1 / Current V2+), re-reading SKILL.md after init and determining a full skill re-run, Step 3b index.md consolidation, verification summary output
**Responsibility Matrix**:
| Role | Responsibilities |
|------|-----------------|
| Main Agent | Version routing, re-reading and determining re-run after init, Step 3b index.md consolidation, verification summary; persists `manifest-routing.json` and `index.md` |
| Sub-Agent | Only runs shell commands like `flow2spec init`, does not persist knowledge base content |
**Cross-Verification**: This skill is not bound to cross-verification; self-verification by the persisting side.
---
## 5) Rule Descriptions
The following are not skill commands but rules activated by trigger words to guide Agent behavior.
### `f2s-karpathy-guidelines`
**Trigger Words**: `alwaysApply` (always on; no explicit trigger needed)
**Purpose**: Flow2Spec's built-in Karpathy-style coding discipline to improve the quality of agent coding decisions.
**How It Works**: Four behavioral constraints distilled from Andrej Karpathy's observations on common LLM coding mistakes, applied as an `alwaysApply` rule that implicitly governs all `f2s-*` skill runs: (1) think before coding (state assumptions; ask when unsure); (2) simplicity first (minimum code to solve the problem); (3) surgical edits (touch only what must change; match existing style); (4) goal-driven execution (define verifiable success criteria, then iterate). When these guidelines conflict with mandatory `f2s-*` steps, the `f2s-*` steps win.
---
### `f2s-task`
**Trigger Words**: changeTracking, change tracking, task tracking, continuation, continue last task
**Purpose**: Change tracking rules (`alwaysApply`). When the corresponding skill's `changeTracking.*` is set to `true`, automatically creates, progressively updates, and finally archives task checklists under `.task/` before and after skill execution, supporting cross-session continuation.
**How It Works**: Cross-session persistence via "disk checkpoints + keyword matching" — each active task records progress with checkboxes (`[ ]` / `[x]`) in `.task/active/<name>/task.md`, with `todo.json` as the active-task index. At the start of a new session, the rule fuzzy-matches the user's first message to each task's `keywords`; on a match, it loads the remaining steps in `task.md` and the skill file for `linkedSkill`, restoring full execution context. Completed tasks move to `completed/`. Design: the file system, not chat memory, is the source of truth so interrupted sessions do not lose progress.
**Scope**:
| Config Item | Corresponding Skill |
|-------------|-------------------|
| `changeTracking.feat` | `f2s-kb-feat` |
| `changeTracking.fix` | `f2s-kb-fix` |
| `changeTracking.implement` | `f2s-implement-tech-design` |
**Cross-Session Continuation**: When a new session starts and `.task/todo.json` exists, automatically matches the user's first message against each task's `keywords`; on a match, loads the corresponding `task.md` and `linkedSkill` skill file, displays the remaining checklist, and asks whether to continue; if there is no match, proceeds without interruption.
**Rule Location**: `Config Root/rules/f2s-task.*`
---
### `stock-docs-vs-req-docs`
**Trigger Words**: stock-docs, req-docs, implemented capability, where to put the technical proposal, PDF final draft
**Purpose**: Distinguishes the boundary between the knowledge archival directory and the requirements implementation directory.
**How It Works**: "Purpose isolation" to avoid mixing folders — `stock-docs/` holds archived existing knowledge (architecture, final drafts), consumed by `ctx-build` for ingestion into the knowledge base and **must not** be used directly as coding input; `req-docs/` holds implementation-facing requirements and technical proposals, consumed by the `implement-tech-design` rule to drive coding. Writers and readers are fully separated so "stock descriptions are not mistaken for coding contracts" and "implementation proposals are not mistaken for capability archival."
**Directory Division**:
| Directory | Purpose | When It Is Written |
|-----------|---------|-------------------|
| `stock-docs/` | Archival of existing knowledge (architecture, final drafts) | `f2s-doc-arch`, `f2s-doc-final`, `f2s-ctx-build` |
| `req-docs/` | Requirements and technical proposals (driving implementation) | `f2s-req-backend`, `f2s-doc-pdf`, manual placement |
**Use Cases**:
- Unsure where a document should go
- Need to clarify the division of labor between stock-docs and req-docs
---
### `implement-tech-design`
**Trigger Words**: implement according to technical proposal, implement-tech-design, implement per proposal
**Purpose**: Implements runnable code based on technical proposal documents in `req-docs/`.
**How It Works**: "Proposal as contract" — the agent treats the technical proposal in `req-docs/` as the sole coding contract and must follow the mandatory six-step pipeline: understand proposal → output task list → ask clarifying questions before coding → implement step by step → output remaining work and post-implementation reminders. The task list and pre-implementation Q&A are non-skippable gates so coding does not start on a misunderstood spec. Unlike `f2s-req-plan`, this rule is lightweight single-threaded coding and does not force `.task/` tracking unless `changeTracking.implement: true`.
**Change Tracking**: If `changeTracking.implement: true`, after outputting the task list in Step 2.5, synchronously writes to `.task/active/<task-name>/task.md`; archives the task in Step 5 during wrap-up.
**Use Cases**:
- Technical proposal is ready and needs to be coded per the proposal
- After a proposal change, code needs to be updated accordingly
**Relationships**:
- **Prerequisite**: `.Knowledge/req-docs/<Technical Proposal>.md` (via `f2s-req-backend` or manual placement)
- **Rule Location**:
- Cursor: `.cursor/rules/f2s-implement-tech-design.mdc`
- Claude: `.claude/rules/f2s-implement-tech-design.md`
- Codex: `.codex/AGENTS.md` + `.codex/topics/f2s-implement-tech-design.md`
**Execution Flow (mandatory by rules)**:
1. Input normalization
2. Understand the proposal and context
3. **Output the implementation task list** (required, cannot be skipped)
4. **Ask questions before implementing** (required, cannot be skipped)
5. Implement per task list
6. **Output the remaining checklist and post-implementation reminders** (required)
**Sub-Agent Invocation**: None (rule-driven coding; the main agent completes the full workflow)
---
## 6) Sub-Agent Configuration
Controlled via `flow2spec.config.json` at the project root (all fields default to `false`).
### How Different Products "See" the Configuration (use with the field table below)
`subAgent` and similar fields are written to the **on-disk JSON**; products do not guarantee automatic file opening. Therefore, multi-layered hints are provided via **Cursor rules / Claude hooks / Codex AGENTS snapshot table / knowledge base `config-precheck` summary**, but **the authoritative source remains `Read("flow2spec.config.json")`** (design rationale in [design-principles.en.md — Agent Orchestration § 5.1](./design-principles.en.md); talk / deck pacing in [intro deck HTML](../presentations/flow2spec-intro-public-en/index.html), config section). **The full path and table are maintained in one place**: [usage-guide.en.md Sec. 1, `f2s-*` and `flow2spec.config.json`](./usage-guide.en.md).
### `subAgent` Field
| Value | Behavior |
|-------|----------|
| `false` (default) | All `f2s-*` skills complete within the main agent |
| `true` | Certain skills may use sub-agents per their documentation (large-scale parallel processing scenarios) |
### `switchAgentVerification` Field
| Value | Behavior |
|-------|----------|
| `false` (default) | Self-verification on the persisting side: whoever persists verifies |
| `true` | When a skill explicitly states this step, enables cross-verification: sub-agent persists -> main agent verifies; main agent persists -> sub-agent verifies (requires `subAgent: true` and sub-tasks actually dispatched) |
### `changeTracking` Field
A nested object, with each skill independently controlled:
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
| Sub-field | Corresponding Skill | Effect |
|-----------|---------------------|--------|
| `feat` | `f2s-kb-feat` | Creates a task checklist before execution, archives on completion, supports cross-session continuation |
| `fix` | `f2s-kb-fix` | Same as above |
| `implement` | `f2s-implement-tech-design` | Same as above |
> `f2s-req-plan` is not constrained by this configuration; it always creates a task checklist. Legacy boolean values (`"changeTracking": true/false`) are backward-compatible and automatically expand to all three sub-fields on/off.
For full principles and design intent, see [architecture.en.md Sec. 4. Agent Execution Model](./architecture.en.md).
---
## 7) Quick Reference
For typical work scenarios and full workflows, see [Usage Guide § 3. Typical Workflows](./usage-guide.en.md).
For a complete directory description, see [Directory Conventions](./directory-conventions.en.md).
---
Related Documents:
- [Usage Guide](./usage-guide.en.md)
- [Directory Conventions](./directory-conventions.en.md)
- [Architecture](./architecture.en.md)
- [Usage Scenarios](./usage-scenarios.en.md)
[中文](./Flow2Spec-设计说明.md) | [English](./design-principles.en.md)
# Flow2Spec Design Principles
## Problem Statement
```
❌ Current State ✅ After Flow2Spec
Architecture conventions ──┐ .Knowledge/
Technical designs ──┼──► scattered ├── manifest-routing.json
Module boundaries ──┤ unstructured ├── matchers/
Team experience ──┘ reinterpreted ├── topics/
every time ├── stock-docs/
└── req-docs/
AI can read the project anytime
```
---
## Core Design
### 1. Separation of Knowledge and Rules
```mermaid
graph LR
subgraph K[".Knowledge/ Knowledge Layer"]
K1[Architecture Docs]
K2[Technical Designs]
K3[Routing Index]
end
subgraph R["Config Root Execution Layer"]
R1[.cursor/rules/]
R2[.claude/rules/]
R3[.codex/AGENTS.md]
end
K -->|Knowledge Input| AI[AI Tools]
R -->|Rule Constraints| AI
note1["Knowledge evolves with the project"] -.-> K
note2["Rules evolve with tool upgrades"] -.-> R
```
### 2. Progressive Routing
```mermaid
graph LR
T[Task] --> M[manifest-routing\nRead routing table]
M -->|Keyword match| MT[matchers/xxx.json\nRead only this shard]
MT -->|Hit| TP[topics/xxx.md]
TP --> V{Gap Check}
V -->|Pass| ACT[Execute]
V -->|Insufficient| Q[Ask user for clarification]
M -->|No match| FB[fallback-triage\nStructured triage]
```
### 3. Skill Maintenance Loop
<p><img src="./images/process-1.png" alt="Skill maintenance loop" style="max-width:100%;" /></p>
<details>
<summary>Mermaid source</summary>
```mermaid
graph LR
K[".Knowledge/"] --> AI["Next Session\nAI"]
AI --> C["Feature iteration"]
C -->|"Fix Bug"| FIX["f2s-kb-fix"] --> K
C -->|"New Capability"| FEAT["f2s-kb-feat"] --> K
C -->|"Session End"| SYNC["f2s-kb-sync"] --> K
C -->|"Commit Code"| CMT["f2s-git-commit\nGate Check"]
CMT -->|"Not in KB, remind\n-> kb-sync/kb-feat"| K
D1["Architecture Docs"] -->|f2s-doc-arch| FIN["f2s-doc-final"]
D2["PDF Proposal"] -->|f2s-doc-pdf| FIN
FIN --> CTX["f2s-ctx-build"] --> K
OLD["Existing Code/Docs"] -->|f2s-doc-add| K
NR["New Requirement"] --> CL["f2s-req-clarify"] --> BE["f2s-req-backend"]
BE --> IMPL["Implement xxx technical design"] -->|auto-trigger implement-tech-design rule| K
GIT["After Git Merge"] -->|f2s-kb-merge| K
```
</details>
Seven entry points · `f2s-git-commit` is the knowledge discipline gate at commit time · `.Knowledge/` is the single convergence point · Knowledge drives AI, AI drives the next development cycle
### 4. Task Checklist and Cross-Session Continuation
```mermaid
graph LR
SKILL["f2s-kb-feat / f2s-kb-fix\nimplement-tech-design"] -->|"changeTracking: true"| TJ[".task/active/\ntask.md · todo.json"]
RP["f2s-req-plan\n(always created)"] --> TJ
TJ --> NS[First message of new session]
NS -->|Keyword match| LD["Load remaining checklist\n+ linkedSkill context"]
LD --> RS[Continue per original skill constraints]
```
Tasks do not get lost when a session ends · Keywords enable automatic continuation without re-explaining context · Skill constraints are fully restored
---
## Design Highlights
### A. Routing and Context Loading
#### 1. matchers sharded, not embedded in manifest
```
❌ Embedded in manifest ✅ Independent shards
manifest.json (full read every time) manifest-routing.json
├── task1: keywords:[...] → ├── task1 → m-order.json ──► read only this one
├── task2: keywords:[...] ├── task2 → m-payment.json
└── task3: keywords:[...] └── task3 → m-refund.json
Updating keywords doesn't touch routing structure
Per-routing token cost is fixed
```
#### 2. topicDependencies: dependencies on topics
```
❌ Attached at task level ✅ Attached at topic level
taskA → [dep, main] topicDependencies:
taskB → [main] ← forgot main: [dep]
taskC → [main] ← forgot
Any path loading main
Forgot when adding new task automatically brings in prerequisite
→ silent failure dependencies
```
#### 3. topics store summaries, rules files store full text
```
.Knowledge/topics/implement-tech-design.md ← lightweight, loaded during routing
┌──────────────────────────────────────────┐
│ Topic id, path conventions, next pointer │
│ ~100 lines │
└──────────────────────────────────────────┘
↓ read only after hit
.claude/rules/f2s-implement-tech-design.md ← full text, loaded during execution
┌──────────────────────────────────────────┐
│ Complete execution constraints, │
│ mandatory steps, prohibitions, │
│ boundary descriptions │
│ ~500 lines │
└──────────────────────────────────────────┘
```
Routing layer stays lightweight · Execution details load on demand · The two evolve independently
#### 4. Full-scan prohibition is a hard constraint
```
Read order (mandatory)
1. manifest-routing.json ← read the routing table first
2. matchers/xxx.json ← read only the matched shard
3. index.md ← on demand, confirm semantics
4. stock-docs / req-docs ← on demand, supplement context
5. Business source code ← last resort
❌ Before reading manifest, full-repo unbounded scan is prohibited
❌ Within the same task line, manifest already read, do not re-read in full
❌ index.md must not be alternated with manifest as a "checklist" to replace decisions
```
#### 5. Skill trigger words in the description field
```yaml
name: f2s-kb-sync
description: >
Sync implemented capabilities to the knowledge base.
Triggers: f2s-kb-sync, full sync, knowledge base sync, implemented capabilities
```
```
User input → Agent scans description for semantic match → triggers corresponding skill
```
Trigger words are in the `description` field · not in the skill body · higher hit rate · bilingual coverage reduces missed triggers
---
### B. Knowledge Structure
#### 1. stock-docs vs req-docs semantic prohibition
```
stock-docs/ req-docs/
Architecture docs / Final draft Requirements / Technical designs
↓ used for ↓ used for
Knowledge routing / Background Drive coding implementation
reference
✅ May be read ✅ May be read
❌ Cannot be used as coding input ✅ Input for implement-tech-design
```
Prevents: driving implementation with outdated reference docs → code diverging from the latest design
#### 2. init is idempotent
```
flow2spec init can be safely re-run
✅ Does ❌ Does NOT
┌─────────────────────┐ ┌─────────────────────┐
│ Fill missing │ │ Write business │
│ directories/templates│ │ document content │
│ Install rules/skills │ │ Update routing │
│ │ │ keywords │
│ Align package-level │ │ Overwrite existing │
│ structure │ │ knowledge content │
└─────────────────────┘ └─────────────────────┘
Structural operations ≠ Business semantics The two have no overlapping responsibilities
```
#### 3. Knowledge versioning
```
git log .Knowledge/
a3f1c2 f2s-kb-feat: add refund state machine routing
b7e9d1 f2s-kb-fix: fix RestTemplate injection conventions
c2a8f0 f2s-ctx-build: onboard order service architecture docs
d5b3e9 f2s-kb-sync: consolidate payment retry queue design
Code changes + Knowledge changes → same commit or adjacent commits
```
Knowledge has versions · is reviewable · is traceable · is blameable
#### 4. No accumulation of historical negation
```
❌ Wrong approach (knowledge base grows bloated) ✅ Correct approach (only current truth)
RestTemplate convention (updated 2026-05) RestTemplate must be injected via Bean
~~Previously incorrectly used new RestTemplate()~~ Direct new RestTemplate() is prohibited
→ No longer related to direct instantiation
→ Old approach deprecated, now uses Bean injection
```
Rewrite in place with each fix · don't layer history · the knowledge base always describes only the present
---
### C. Execution Constraints
#### 1. Mandatory steps are constraints, not suggestions
```
implement-tech-design execution flow
Input normalization
Read proposal and context
★ Output implementation task list ← cannot skip
★ Confirm before implementing ← cannot skip
Implement per task list
Output pending checklist and reminders ← cannot skip
```
Suggestions → can be skipped · Constraints → must be explicitly addressed before proceeding
#### 2. fallback is itself a procedurally-defined topic
```mermaid
graph TD
F[Enter fallback-triage] --> S1{Route matched?}
S1 -->|Matched but insufficient context| EXP[Expand dependency topics\nfill gaps and continue]
S1 -->|Not matched| Q[Ask user:\nHas this domain been documented?]
Q -->|Yes| HINT[Routing entry missing\nsuggest adding routing]
Q -->|No| CHOICE[Drill into source code\nor add req-docs]
Q -->|Not sure| STOP[Stop execution\nwait for clear instructions]
```
No match ≠ silent failure · degradation itself has a clear procedure
#### 3. manifest / index write authority hard constraint
```
Sub-agents MAY write Sub-agents MUST NOT touch
──────────────────── ────────────────────
Code implementation files manifest-routing.json ← always written by main agent
stock-docs content files .Knowledge/index.md ← always written by main agent
topics content files (diff mode)
matchers/*.json (diff mode)
```
When multiple sub-agents run in parallel, shared state files are written single-point by the main agent to prevent concurrent conflicts
#### 4. Document changes vs code changes: different splitting strategies
```
Code sub-packages Document sub-packages
──────────────────── ────────────────────
✅ Can delegate to sub-agents ❌ Not split by default, main agent writes directly
✅ Sub-agents write directly If outsourcing is necessary →
Sub-side only outputs before/after diff snippets
Main agent reviews and merges
❌ Full-file rewrite is strictly prohibited
```
Rationale: documents need to guarantee "current truth coverage / consistent style / no accumulation of historical negation" · requires the writer to see the full context
#### 5. Task checklist and cross-session continuation
```
Keyword-based automatic continuation example
First sentence of a new session: "There's still an issue with payment callback"
Matches each entry's keywords in todo.json
Hit { name: "payment_callback_fix", keywords: ["payment", "callback"] }
Load task.md (show remaining steps)
linkedSkill = "f2s-kb-fix" → load SKILL.md
Skill's write rules / style requirements / self-check checklist are fully restored
User doesn't need to re-describe context, can continue directly
✅ No need to say "continue the previous task"
✅ Skill constraints are fully restored, consistent with the first invocation
```
```
todo.json write authority constraint
Main agent ── read / write todo.json ✅
Sub-agent ── read todo.json ✅
Sub-agent ── write todo.json ❌
Rationale: when multiple sub-agents write concurrently,
concurrent writes cause entries to overwrite each other
```
Lifecycle is driven by skills · keyword routing enables cross-session automatic continuation · linkedSkill ensures full restoration of skill constraints
---
### D. Agent Orchestration
#### 1. subAgent × switchAgentVerification are orthogonal
```
switchAgentVerification
false true
subAgent ┌────────────┬─────────────────┐
true → │ Parallel │ Parallel │
│ execution │ execution │
│ Writer-side │ Sub writes→Main │
│ self-verify │ verifies │
│ │ Main writes→Sub │
│ │ verifies │
├────────────┼─────────────────┤
false → │ Sequential │ Sequential │
│ execution │ execution │
│ Main agent │ Main agent │
│ self- │ self-verifies │
│ verifies │ (no sub-side │
│ │ for cross-check) │
└────────────┴─────────────────┘
```
Two orthogonal dimensions · independently configurable · default is bottom-left
#### 2. Confirmation authority cannot be delegated to sub-agents
```mermaid
graph LR
S1[Step 1: Gather materials] -->|subAgent=true may parallelize| SUB[Sub-agent]
SUB -->|Read-only, no writes| S2
S2[Step 2: Output outline\nUser confirms] -->|Must be main agent| USER[User]
USER -->|Confirm| S3
S3[Step 3: Write] -->|subAgent=true may parallelize| SUB2[Sub-agent]
```
User dialogue only flows through the main agent · confirmation decisions cannot bypass the user · sub-agents only execute, never decide
#### 3. Skills can override global subAgent configuration
```
flow2spec.config.json f2s-req-clarify SKILL.md
subAgent: true This skill does not split by default:
regardless of subAgent value,
the clarification process stays
entirely in the main session
Rationale: requirement clarification depends heavily on continuous same-session follow-up
splitting would break context, degrading clarification quality
```
Global configuration is the upper bound for allowing splits · each skill decides for itself whether splitting is appropriate · config being true does not guarantee splitting
#### 4. f2s-kb-sync: outline first, write after confirmation
```mermaid
graph LR
T[Trigger f2s-kb-sync] --> O[Output update outline]
O --> U{User confirms}
U -->|Confirm| W[Write to .Knowledge/]
U -->|Modify| O
U -->|Cancel| STOP[No write]
```
Writing is a destructive operation · the outline is the user's only chance to correct · nothing is written before confirmation
#### 5. Zero-input inference
```
f2s-kb-sync three input modes
Mode 1: User explicitly provides capability list "Sync the refund state machine into the knowledge base"
Mode 2: User provides supplementary materials @src/refund/ @docs/proposal.md
Mode 3: Zero input "f2s-kb-sync" (just this one sentence)
Agent infers based on session context
what was implemented and what is worth consolidating
```
Session context itself is an information source · no need for users to organize and re-input
#### 5.1 How execution switches reach the Agent (multi-platform prompts)
`flow2spec.config.json` determines **`subAgent` / `switchAgentVerification` / `changeTracking`**, but AI products **do not guarantee** that the file is automatically opened at session start. The design uses **multiple weak constraint layers** to reduce the probability of "running `f2s-*` without reading the config", while avoiding maintaining a verbose duplicate of `.codex/topics/f2s-config-check.md` in `.Knowledge`:
| Mechanism | Design Intent |
| --- | --- |
| **Cursor `f2s-config-check.mdc`** | Rule-layer enforcement: "Read before skill body." |
| **Claude `f2s-config-inject` PreToolUse** | Injects parsed results when calling **`f2s-*` Skill**; **missing file / broken JSON / hook exception** still outputs a note with default semantics, no silent failure. |
| **Codex `AGENTS.md` + `renderProjectConfigBlock`** | Top-level **Read** hard constraint + **init snapshot table** (if inconsistent with disk, Read takes precedence). |
| **Knowledge base `config-precheck` topic** | When routing hits, provides only **summary** and a pointer to the Codex full text, **not** a substitute for Read JSON. |
**Authority remains** the **Read** result of the project-root JSON; each layer is a prompt, not a second source of truth. For the complete operational table and paths, see **[Usage Guide § 1. `f2s-*` and `flow2spec.config.json`](./usage-guide.en.md)**.
#### 6. Skills don't restate unified entry rules, only reference them
```
Each SKILL.md's orchestration section reads:
subAgent / switchAgentVerification semantics
are defined in the unified entry as the sole source of truth,
not restated here.
Cursor/Claude → rules/f2s-flow2spec-unified-entry.*
Codex → .codex/topics/f2s-flow2spec-unified-entry.md
15 skills, each only writes its own unique orchestration constraints
Common rules are defined in one place; modifying one location affects all
```
---
### E. Pluggable Architecture
#### 1. Tools are pluggable: one knowledge base, any tool combination
```
flow2spec init cursor claude codex ← all three tools installed
flow2spec init claude ← only Claude
flow2spec init cursor codex ← skip Claude
.Knowledge/ stays the same, tools can be added or removed at any time
```
The same `.Knowledge/` drives all tools · adding/removing tools does not affect knowledge content · new tools integrate with zero rebuild
#### 2. Knowledge topics are pluggable: add/remove without side effects
```
Adding a topic Removing a topic
───────────────────── ─────────────────────
1. Write topics/xxx.md f2s-ctx-rm stock-docs/xxx.md
2. Write matchers/m-xxx.json ↓
3. Register in manifest-routing Automatically cleans up topics/ + manifest
+ index references
Other topics remain completely unaffected
```
New topics simply declare dependencies in `topicDependencies` · if they don't, they're independent · removal has no side effects
#### 3. Skills are pluggable: self-contained units, project-level overrides package-level
```
Package-level skills (shipped with flow2spec init) Project-level skills (placed in config root/skills/)
f2s-kb-sync/SKILL.md my-domain-skill/SKILL.md
f2s-doc-arch/SKILL.md my-review-skill/SKILL.md
...
If names don't conflict they coexist · same name → project-level overrides package-level · they're unaware of each other
```
Skills describe their own trigger words via the `description` field · no registry needed · no global config changes needed · effective upon deployment
#### 4. Routing vocabulary is pluggable: shard isolation, local updates
Vocabulary changes only modify the corresponding `matchers/m-xxx.json`, with zero diff for other routes; see structure in "[A. Routing and Context Loading → matchers sharding](#1-matchers-sharded-not-embedded-in-manifest)".
Vocabulary changes are localized · merge conflicts are minimized · new routes don't affect existing ones
#### 5. Execution model is pluggable: config switches per project
```
flow2spec.config.json
subAgent: false → main agent throughout, low overhead, suitable for small projects
subAgent: true → allow sub-agent parallelization, suitable for large-scale changes
switchAgentVerification: false → writer-side self-verify, daily use
switchAgentVerification: true → cross-verification, high-confidence critical scenarios
changeTracking.feat/fix/implement: false → no task checklist created
changeTracking.feat/fix/implement: true → automatic task checklist creation when corresponding skills run, supporting cross-session continuation
Three orthogonal dimensions · each skill can further refine and override global config
```
Change one line of config to switch execution strategy · no skill files need modification · new projects work out of the box, existing projects upgrade on demand
---
## Strengths and Limitations
```
✅ Strengths ⚠️ Limitations
Precise context Upfront investment: knowledge must be built via skills
└─ Routing loads only relevant docs Scale threshold: overhead > benefit for small projects
Cross-tool sharing Requires team discipline
└─ Write knowledge once, use in all └─ Skills reduce friction, don't eliminate it
Tool-agnostic Learning curve
└─ Switch tools without rebuilding └─ stock/req boundary, routing structure aren't intuitive
Sustainable
└─ Maintenance tied to development actions
```
---
## Who Is It For
```
Project Scale
Small ◄──────────► Large
┌──────────┬────────────┐
Short │ Not │ Can use │
Term │ needed │ │
├──────────┼────────────┤
Long │ Can use │ Highly │
Term │ │ recommended│
└──────────┴────────────┘
Best suited when: has scale · long-term iteration · multi-tool or multi-person AI collaboration
```
---
## Related Documents
- [Usage Guide](./usage-guide.en.md)
- [Commands Reference](./commands-reference.en.md)
- [Architecture](./architecture.en.md)
- [Usage Scenarios](./usage-scenarios.en.md)
[中文](./README-目录与路径约定.md) | [English](./directory-conventions.en.md)
# Directory and Path Conventions
## Core Boundary
- `.Knowledge/`: Business knowledge documents and index only
- `Config Root` (`.cursor/.claude/.codex`): Rules and skill entry points
---
## Directory Responsibilities
| Path | Responsibility |
| --- | --- |
| `.Knowledge/stock-docs/` | Architecture, final drafts, reference documents |
| `.Knowledge/req-docs/` | Requirement clarification, technical proposals |
| `.Knowledge/topics/` | Topic routing documents (for rules and workflow execution) |
| `.Knowledge/template/` | Templates for final drafts / technical proposals |
| `.Knowledge/index.md` | Human-readable index |
| `.Knowledge/manifest-routing.json` | Machine-readable routing skeleton (task/topic/dependencies) |
| `.Knowledge/matchers/*.json` | Keyword fragments (`id/includeAny`), directly linked by `manifest-routing.taskToTopicRules[].matcherPath` |
| `.Knowledge/migration-report.md` | Migration comparison table and deletion path list written by `f2s-kb-migrate` |
| `.task/` | Change tracking task directory (`active/` for in-progress, `completed/` for archived with directory name in the format **`<YYYYMMDD>-<task-name>`** (date first), `todo.json` for active task index); created only when `changeTracking.*` is `true` or `f2s-req-plan` is explicitly invoked |
| `Config Root/rules/` | Rule files (Cursor `.mdc`, Claude `.md`) |
| `Config Root/skills/` | Skill definitions (`SKILL.md`) |
| `Config Root/template/` | (Deprecated) No longer written to; historical directories may be cleaned up |
| `.codex/AGENTS.md` | Codex unified entry point and loading instructions |
| `flow2spec.config.json` | Project root configuration, controls `subAgent`, `switchAgentVerification`, `changeTracking` (nested object with `feat` / `fix` / `implement` sub-items) |
> See [Usage Guide Section 1](./usage-guide.en.md) for multi-platform references and path tables (detail maintained in a single table); **the authoritative source remains `Read(flow2spec.config.json)`**.
---
## Path Constraints
1. `.Knowledge/topics` is the knowledge routing topic layer; it is allowed and encouraged to be maintained via `f2s-*` skills.
2. `f2s-ctx-build` reads from `.Knowledge/stock-docs` and updates `.Knowledge/topics`, `.Knowledge/index.md`, `.Knowledge/manifest-routing.json`, `.Knowledge/matchers/*.json`.
3. Implementation tasks uniformly read from `.Knowledge/req-docs/*.md`.
4. `manifest-routing.json` and `matchers/*.json` are maintained by `f2s-*` skill workflows; `.Knowledge/manifest-matchers.json` is no longer used (`flow2spec init` will delete legacy files).
---
## Related Documents
- [Usage Guide](./usage-guide.en.md)
- [Commands Reference](./commands-reference.en.md)
- [Architecture](./architecture.en.md)
- [Usage Scenarios](./usage-scenarios.en.md)
# Flow2Spec 使用案例(模拟对话)
以下示例围绕同一个电商项目展开,贯穿从需求澄清到上线后维护的完整流程。
**前提**:项目已执行 `flow2spec init`,`flow2spec.config.json` 使用默认配置(`subAgent: false`)。`f2s-*` 技能不改动配置根 `rules/`、`skills/` 文件。
---
## 场景一:新需求 → 澄清 → 技术方案
**你**
> /f2s-req-clarify 产品给了一份退款需求,但没说清楚部分退款和全额退款走不走同一接口,退款成功后积分是否回撤。文档在 `.Knowledge/req-docs/退款需求v1.md`。
**Agent**
> 已读取需求文档,有几个点需要确认:
>
> 1. 部分退款与全额退款是否复用同一接口,通过 `amount` 区分,还是拆成两个端点?
> 2. 退款成功后积分是否回撤?回撤失败是否阻断退款流程?
> 3. 退款申请是同步到账还是异步(T+1)?
> 4. 卖家侧是否需要审核步骤?
**你**
> 1. 同一接口用 amount 区分;2. 积分回撤,失败不阻断,异步重试;3. 异步 T+1;4. 不需要审核。
**Agent**
> 澄清完成。执行 `/f2s-req-backend` 输出技术方案。
**你**
> /f2s-req-backend
**Agent**
> 已生成 `.Knowledge/req-docs/退款功能_技术方案.md`,包含:
> - 接口设计:`POST /refunds`,`amount` 字段区分全额/部分
> - 状态机:`PENDING → SUCCESS / FAILED`
> - 积分回撤:异步队列,失败进死信,告警人工处理
> - 错误码清单
>
> 下一步:说"按方案实现 `.Knowledge/req-docs/退款功能_技术方案.md`"触发编码。
---
## 场景二:架构说明沉淀进知识库
**你**
> /f2s-doc-arch 帮我出一份订单服务架构初稿,重点看创建流、支付回调、幂等与消息投递;代码在 `src/order`、`src/payment`。
**Agent**
> 已扫描相关目录,生成 `.Knowledge/stock-docs/订单服务架构说明_初稿.md`,包含:
> - 模块边界与依赖关系
> - 创建流时序
> - 支付回调幂等机制(基于 `payment_callback_log` 表)
> - 消息投递重试策略
>
> 确认无误后执行 `/f2s-doc-final` 规范化格式。
**你**
> /f2s-doc-final .Knowledge/stock-docs/订单服务架构说明_初稿.md
**Agent**
> 已生成 `.Knowledge/stock-docs/订单服务架构说明_终稿.md`,按终稿模板整理,标注了待补充项。
**你**
> f2s-ctx-build .Knowledge/stock-docs/订单服务架构说明_终稿.md
**Agent**
> 已完成知识库同步:
> - 新增 `.Knowledge/topics/order-service.md`
> - 更新 `.Knowledge/manifest-routing.json`(新增路由规则)
> - 生成 `.Knowledge/matchers/order-service.json`(关键词:订单创建、支付回调、幂等、消息投递)
> - 更新 `.Knowledge/index.md`
>
> 后续与订单服务相关的任务会自动命中此主题。
---
## 场景三:按技术方案实现
**你**
> 按方案实现:`.Knowledge/req-docs/退款功能_技术方案.md`,只改 `src/refund/`,不要动支付模块。
**Agent**
> 已读取方案。实现任务列表:
>
> 1. 新建 `RefundController`,实现 `POST /refunds`
> 2. 新建 `RefundService`,含状态机流转逻辑
> 3. 新建 `RefundRepository`,对应 `refund` 表
> 4. 新建 `PointRollbackProducer`,向积分队列发送回撤消息
> 5. 单元测试覆盖状态机流转
>
> 实现前确认:
> - `refund` 表是否已存在,还是需要生成 migration?
> - 积分队列 Topic 名称是什么?
**你**
> 表已存在,不用 migration;Topic 是 `point-rollback-events`。
**Agent**
> 已完成以上 5 项,均在 `src/refund/` 内,未触碰 `src/payment/`。
>
> **待完成(需人工)**:
> - `point-rollback-events` 消费端(积分服务侧)
> - 死信监控告警规则配置
>
> 建议执行 `/f2s-kb-feat` 将本次新增能力同步进知识库。
---
## 场景四:PDF 方案 → 实现
**你**
> /f2s-doc-pdf /Users/me/Downloads/营销优惠券_v2.pdf
**Agent**
> 已转换并保存为 `.Knowledge/req-docs/营销优惠券_v2.md`,补全了 PDF 中缺失的幂等处理流程描述和错误码说明。
**你**
> 按方案实现:`.Knowledge/req-docs/营销优惠券_v2.md`
**Agent**
> 已读取方案,输出实现任务列表:
>
> 1. 新建 `CouponController`(领券、核销、退券接口)
> 2. 新建 `CouponService`,含库存扣减与幂等校验
> 3. …
>
> 实现前确认:优惠券库存是用 Redis 还是数据库行锁?
---
## 场景五:实现后补录知识库
**你**
> /f2s-kb-sync 退款功能上线了,帮我把支付失败重试队列命名、死信表字段、监控告警口径沉淀进知识库,先给大纲我确认再写。
**Agent**
> 知识库更新大纲(待确认):
>
> **更新主题**:`order-service`(已有)
>
> - 新增「支付失败重试机制」:队列名 `payment-retry-queue`,最大重试 3 次,间隔 30s / 120s / 300s
> - 新增「死信表」:表名 `payment_dead_letter`,字段 `order_id / error_code / retry_count / created_at`
> - 新增「监控口径」:告警阈值 `retry_count >= 3`,通知渠道 DingTalk
>
> 确认后写入,或告诉我需要修改的地方。
**你**
> 确认写入。
**Agent**
> 已更新 `.Knowledge/topics/order-service.md`,`manifest-routing` 未变动(主题已存在)。
---
## 场景六:发现违规实现,修复并同步知识库
**你**
> /f2s-kb-fix `RefundService` 里直接 `new RestTemplate()` 了,违反 Spring Bean 注入约定。
**Agent**
> 已修复:`RefundService.java` 第 34 行改为构造注入,`RefundConfig` 补充 `@Bean` 声明。
>
> 同步知识库:`.Knowledge/stock-docs/` 中「HTTP 客户端约定」节更新,注明 `RestTemplate` 必须通过 Bean 注入,禁止直接实例化。
---
## 场景七:Git 合并后知识库冲突
**你**
> /f2s-kb-merge `.Knowledge/index.md` 和 `.Knowledge/stock-docs/订单服务架构说明_终稿.md` 合并后有冲突标记,业务代码我已手动合完。
**Agent**
> 已扫描两个文件的冲突标记:
>
> - `index.md`:2 处冲突,均为主题描述字段,取 HEAD 版本(内容较新),已自动处理。
> - `订单服务架构说明_终稿.md`:1 处冲突,「监控告警阈值」两个分支不同(3 次 vs 5 次),需你确认。
**你**
> 用 3 次。
**Agent**
> 已按确认结果清理全部冲突标记,文件可提交。
---
## 相关文档
- [Flow2Spec使用说明](./Flow2Spec使用说明.md)
- [README-命令说明](./README-命令说明.md)
- [README-目录与路径约定](./README-目录与路径约定.md)
- [README-体系与原理](./README-体系与原理.md)
# Flow2Spec 设计说明
## 解决的问题
```
❌ 现状 ✅ Flow2Spec 之后
架构约定 ──┐ .Knowledge/
技术方案 ──┼──► 散落 ├── manifest-routing.json
模块边界 ──┤ 无结构 ├── matchers/
团队经验 ──┘ 每次重新解释 ├── topics/
├── stock-docs/
└── req-docs/
AI 随时能读懂项目
```
---
## 核心设计
### 1. 知识与规则分离
```mermaid
graph LR
subgraph K[".Knowledge/ 知识层"]
K1[架构说明]
K2[技术方案]
K3[路由索引]
end
subgraph R["配置根 执行层"]
R1[.cursor/rules/]
R2[.claude/rules/]
R3[.codex/AGENTS.md]
end
K -->|知识输入| AI[AI 工具]
R -->|规则约束| AI
note1["知识随项目迭代"] -.-> K
note2["规则随工具升级"] -.-> R
```
### 2. 渐进式路由
```mermaid
graph LR
T[任务] --> M[manifest-routing\n读路由表]
M -->|关键词匹配| MT[matchers/xxx.json\n只读这一个分片]
MT -->|命中| TP[topics/xxx.md]
TP --> V{缺口检查}
V -->|通过| ACT[执行]
V -->|不足| Q[向用户澄清]
M -->|未命中| FB[fallback-triage\n结构化分诊]
```
### 3. 技能维护闭环
<p><img src="./images/flow-1.png" alt="技能维护闭环" style="max-width:100%;" /></p>
<details>
<summary>Mermaid 源码</summary>
```mermaid
graph LR
K[".Knowledge/"] --> AI["下次会话\n的 AI"]
AI --> C["功能迭代"]
C -->|"修复 Bug"| FIX["f2s-kb-fix"] --> K
C -->|"新增能力"| FEAT["f2s-kb-feat"] --> K
C -->|"会话结束"| SYNC["f2s-kb-sync"] --> K
C -->|"提交代码"| CMT["f2s-git-commit\n收口检查"]
CMT -->|"未入库则提醒\n-> kb-sync/kb-feat"| K
D1["架构文档"] -->|f2s-doc-arch| FIN["f2s-doc-final"]
D2["PDF 方案"] -->|f2s-doc-pdf| FIN
FIN --> CTX["f2s-ctx-build"] --> K
OLD["存量代码/文档"] -->|f2s-doc-add| K
NR["新需求"] --> CL["f2s-req-clarify"] --> BE["f2s-req-backend"]
BE --> IMPL["实现xxx技术方案"] -->|自动触发implement-tech-design规则| K
GIT["Git 合并后"] -->|f2s-kb-merge| K
```
</details>
七条入口 · `f2s-git-commit` 是提交时的知识纪律收口 · `.Knowledge/` 是唯一汇聚点 · 知识驱动 AI,AI 驱动下轮开发
### 4. 任务清单与跨会话续作
```mermaid
graph LR
SKILL["f2s-kb-feat / f2s-kb-fix\nimplement-tech-design"] -->|"changeTracking: true"| TJ[".task/active/\ntask.md · todo.json"]
RP["f2s-req-plan\n(始终创建)"] --> TJ
TJ --> NS[新会话首条消息]
NS -->|关键词匹配| LD["加载剩余 checklist\n+ linkedSkill 上下文"]
LD --> RS[按原技能约束继续]
```
任务不因会话结束丢失 · 关键词自动续作,无需重新说明上下文 · 技能约束完整恢复
---
## 设计亮点
### 一、路由与上下文加载
#### 1. matchers 分片,不嵌入 manifest
```
❌ 嵌入 manifest ✅ 独立分片
manifest.json (每次全读) manifest-routing.json
├── task1: keywords:[...] → ├── task1 → m-order.json ──► 只读这一个
├── task2: keywords:[...] ├── task2 → m-payment.json
└── task3: keywords:[...] └── task3 → m-refund.json
更新关键词不动路由结构
每次路由 token 成本固定
```
#### 2. topicDependencies:依赖挂在主题上
```
❌ 挂在任务级 ✅ 挂在主题级
taskA → [dep, main] topicDependencies:
taskB → [main] ← 漏写了 main: [dep]
taskC → [main] ← 漏写了
任何路径加载 main
新增任务时漏写 → 静默失效 都自动带上前置依赖
```
#### 3. topic 只存摘要,规则文件存全文
```
.Knowledge/topics/implement-tech-design.md ← 轻量,路由时加载
┌──────────────────────────────────────────┐
│ 主题 id、路径约定、下一步指针 │
│ ~100 行 │
└──────────────────────────────────────────┘
↓ 命中后才读
.claude/rules/f2s-implement-tech-design.md ← 全文,执行时加载
┌──────────────────────────────────────────┐
│ 完整执行约束、强制步骤、禁止项、边界说明 │
│ ~500 行 │
└──────────────────────────────────────────┘
```
路由层保持轻量 · 执行细节按需加载 · 两者独立更新
#### 4. 禁止全量扫描是硬约束
```
读取顺序(必须)
1. manifest-routing.json ← 先看路由表
2. matchers/xxx.json ← 只读命中分片
3. index.md ← 按需,确认语义
4. stock-docs / req-docs ← 按需,补充背景
5. 业务源码 ← 最后手段
❌ 未读 manifest 前,禁止全仓无范围扫描
❌ 同一任务线内,manifest 已读则不重复全文读取
❌ index.md 禁止与 manifest 交替"刷清单"代替决策
```
#### 5. 技能触发词写在 description 字段
```yaml
name: f2s-kb-sync
description: >
同步已实现能力到知识库。
触发词:f2s-kb-sync、全局同步、知识库同步、已实现能力
```
```
用户输入 → Agent 扫 description 做语义匹配 → 触发对应技能
```
触发词在 description 里 · 不在正文里 · 命中率更高 · 双语覆盖减少漏触发
---
### 二、知识结构
#### 1. stock-docs vs req-docs 语义禁止
```
stock-docs/ req-docs/
架构说明 / 终稿 需求 / 技术方案
↓ 用于 ↓ 用于
知识路由 / 背景参考 驱动编码实现
✅ 可以读 ✅ 可以读
❌ 不能作为编码输入 ✅ implement-tech-design 的输入
```
防止:用过期参考文档驱动实现 → 代码与最新方案脱节
#### 2. init 幂等
```
flow2spec init 可以安全重跑
✅ 做 ❌ 不做
┌─────────────────────┐ ┌─────────────────────┐
│ 补齐缺失目录和模板 │ │ 写业务文档内容 │
│ 落盘 rules/skills │ │ 更新路由关键词 │
│ 包级结构对齐 │ │ 覆盖已有知识内容 │
└─────────────────────┘ └─────────────────────┘
结构操作 ≠ 业务语义 两者职责不交叉
```
#### 3. 知识版本化
```
git log .Knowledge/
a3f1c2 f2s-kb-feat: 新增退款状态机路由
b7e9d1 f2s-kb-fix: 修正 RestTemplate 注入约定
c2a8f0 f2s-ctx-build: 订单服务架构说明入库
d5b3e9 f2s-kb-sync: 沉淀支付重试队列设计
代码变更 + 知识变更 → 同一 commit 或相邻 commit
```
知识有版本 · 可 review · 可回溯 · 可 blame
#### 4. 禁止历史否定堆砌
```
❌ 错误写法(知识库越来越臃肿) ✅ 正确写法(只保留当前成立的表述)
RestTemplate 约定(更新于 2026-05) RestTemplate 必须通过 Bean 注入
~~原错误地使用 new RestTemplate()~~ 禁止直接 new RestTemplate()
→ 不再与直接实例化有关
→ 原写法已废弃,现改为 Bean 注入
```
每次修复原位改写 · 不叠加历史 · 知识库永远只描述现在
---
### 三、执行约束
#### 1. 强制步骤是约束,不是建议
```
implement-tech-design 执行流
输入标准化
读取方案与上下文
★ 输出实现任务列表 ← 不可跳过
★ 实现前提问确认 ← 不可跳过
按任务列表实现
输出待完成清单与提醒 ← 不可跳过
```
建议 → 可以被跳过 · 约束 → 必须明确处理才能继续
#### 2. fallback 本身是有程序的 topic
```mermaid
graph TD
F[进入 fallback-triage] --> S1{路由是否命中?}
S1 -->|已命中但上下文不足| EXP[展开依赖主题\n补齐后继续]
S1 -->|未命中| Q[询问用户:\n这个领域文档是否已录入?]
Q -->|是| HINT[路由词条缺失\n建议补路由]
Q -->|否| CHOICE[下钻源码\n或补充 req-docs]
Q -->|不确定| STOP[停止执行\n等待明确指令]
```
未命中 ≠ 静默失败 · 降级本身有明确程序
#### 3. manifest / index 写权硬约束
```
子 agent 可以落盘的 子 agent 不得触碰
──────────────────── ────────────────────
代码实现文件 manifest-routing.json ← 恒主 agent 落盘
stock-docs 内容文件 .Knowledge/index.md ← 恒主 agent 落盘
topics 内容文件(diff 模式)
matchers/*.json(diff 模式)
```
多个子 agent 并行时,共享状态文件由主 agent 单点写入,防止并发冲突
#### 4. 文档改动 vs 代码改动,拆分策略不同
```
代码子包 文档子包
──────────────────── ────────────────────
✅ 可下放子 agent 执行 ❌ 默认不拆,主 agent 直接写
✅ 子 agent 直接落盘 若确需外包 →
子侧只输出 before/after diff 片段
主 agent 审核后合并落盘
❌ 整文件重写严格禁止
```
原因:文档需要保证「现行真值覆盖 / 文风一致 / 禁历史否定堆砌」 · 要求写的人看到全文上下文
#### 5. 任务清单与跨会话续作
```
关键词自动续作示例
新会话第一句:"支付回调还有个问题"
匹配 todo.json 各条目 keywords
命中 { name: "payment_callback_fix", keywords: ["支付", "回调"] }
加载 task.md(展示剩余步骤)
linkedSkill = "f2s-kb-fix" → 加载 SKILL.md
技能的落盘规则 / 文风要求 / 自检清单全部恢复
用户无需重新描述上下文,直接继续
✅ 不需要说"继续上次任务"
✅ 技能约束完整恢复,与首次调用一致
```
```
todo.json 写权约束
主 agent ── 读 / 写 todo.json ✅
子 agent ── 读 todo.json ✅
子 agent ── 写 todo.json ❌
原因:多子 agent 并行落盘时,并发写会导致条目互相覆盖
```
生命周期由技能驱动 · 关键词路由实现跨会话自动续作 · linkedSkill 保证技能约束完整恢复
---
### 四、Agent 编排
#### 1. subAgent × switchAgentVerification 正交
```
switchAgentVerification
false true
subAgent ┌────────────┬─────────────────┐
true → │ 并行执行 │ 并行执行 │
│ 落盘侧自验 │ 子落盘→主验 │
│ │ 主落盘→子验 │
├────────────┼─────────────────┤
false → │ 顺序执行 │ 顺序执行 │
│ 主 agent │ 主 agent 自验 │
│ 自验 │(无子侧可交叉) │
└────────────┴─────────────────┘
```
两个维度正交 · 独立配置 · 默认左下角
#### 2. 确认权不可下放子 agent
```mermaid
graph LR
S1[步骤1: 素材汇总] -->|subAgent=true 可并行| SUB[子 agent]
SUB -->|只读,不落盘| S2
S2[步骤2: 输出大纲\n用户确认] -->|必须主 agent| USER[用户]
USER -->|确认| S3
S3[步骤3: 落盘] -->|subAgent=true 可并行| SUB2[子 agent]
```
用户对话只经过主 agent · 确认决策不可绕过用户 · 子 agent 只做执行不做决策
#### 3. 技能可覆盖全局 subAgent 配置
```
flow2spec.config.json f2s-req-clarify SKILL.md
subAgent: true 本技能默认不拆子:
无论 subAgent 真值,
澄清流程全程在主会话
原因:需求澄清强依赖连续同会话追问
拆子会断上下文,导致澄清质量下降
```
全局配置是允许拆的上限 · 技能自己判断是否适合拆 · 配置 true 不等于一定拆
#### 4. f2s-kb-sync 先出大纲,确认后再写
```mermaid
graph LR
T[触发 f2s-kb-sync] --> O[输出更新大纲]
O --> U{用户确认}
U -->|确认| W[写入 .Knowledge/]
U -->|修改| O
U -->|取消| STOP[不写入]
```
写入是破坏性操作 · 大纲是用户唯一的纠错机会 · 确认前不落盘
#### 5. 零输入推断
```
f2s-kb-sync 三种输入方式
方式 1:用户显式给出能力列表 "帮我把退款状态机同步进知识库"
方式 2:用户给辅助材料 @src/refund/ @docs/方案.md
方式 3:零输入 "f2s-kb-sync"(仅此一句)
Agent 基于会话上下文推断
本次实现了什么、有什么值得沉淀
```
会话上下文本身就是信息源 · 不需要用户整理再输入
#### 5.1 执行开关如何进入 Agent(多端提示)
`flow2spec.config.json` 决定 **`subAgent` / `switchAgentVerification` / `changeTracking`**,但各 AI 产品**不保证**会话启动即自动打开该文件。设计上用 **多条弱约束叠加** 降低「未读配置就开跑 `f2s-*`」的概率,同时避免在 `.Knowledge` 再维护一份与 `.codex/topics/f2s-config-check.md` 逐字重复的长文:
| 机制 | 设计意图 |
| --- | --- |
| **Cursor `f2s-config-check.mdc`** | 规则层强制「技能正文前先 Read」。 |
| **Claude `f2s-config-inject` PreToolUse** | 在调用 **`f2s-*` Skill** 时注入解析结果;**缺文件 / 坏 JSON / hook 异常**仍输出说明与默认语义,避免静默。 |
| **Codex `AGENTS.md` + `renderProjectConfigBlock`** | 顶部 **Read** 硬约束 + **init 快照表**(与磁盘不一致时以 Read 为准)。 |
| **知识库 `config-precheck` 主题** | 路由命中时只提供**摘要**与链向 Codex 长文,**不**替代 Read JSON。 |
**权威仍为**项目根 JSON 的 **Read** 结果;各层为提示而非第二份真值源。操作侧完整表格与路径见 **[Flow2Spec使用说明 § 一、`f2s-*` 与 `flow2spec.config.json`](./Flow2Spec使用说明.md)**;口述节奏见 **[Flow2Spec-演讲稿 Slide 13b](./Flow2Spec-演讲稿.md)**。
#### 6. 技能不复述统一入口规则,只引用
```
每个 SKILL.md 的编排部分写法:
subAgent / switchAgentVerification 语义
以统一入口为唯一事实源,本处不复述。
Cursor/Claude → rules/f2s-flow2spec-unified-entry.*
Codex → .codex/topics/f2s-flow2spec-unified-entry.md
15 个技能,每个只写自己特有的编排约束
公共规则统一在一处定义,修改一处全部生效
```
---
### 五、可插拔架构
#### 1. 工具可插拔:一份知识,任意组合工具
```
flow2spec init cursor claude codex ← 三工具全装
flow2spec init claude ← 只装 Claude
flow2spec init cursor codex ← 跳过 Claude
.Knowledge/ 始终不变,工具随时加减
```
同一份 `.Knowledge/` 驱动所有工具 · 加减工具不影响知识内容 · 新工具接入零重建
#### 2. 知识主题可插拔:增删不连带
```
添加主题 删除主题
───────────────────── ─────────────────────
1. 写 topics/xxx.md f2s-ctx-rm stock-docs/xxx.md
2. 写 matchers/m-xxx.json ↓
3. 在 manifest-routing 注册 自动清除 topics/ + manifest
+ index 引用
其他主题完全不受影响
```
新主题只需在 `topicDependencies` 里声明依赖 · 不声明则彼此独立 · 删除无副作用
#### 3. 技能可插拔:自包含单元,项目级可覆盖包级
```
包级技能(随 flow2spec init 分发) 项目级技能(放 配置根/skills/)
f2s-kb-sync/SKILL.md my-domain-skill/SKILL.md
f2s-doc-arch/SKILL.md my-review-skill/SKILL.md
...
名字不冲突则共存 · 同名则项目级覆盖包级 · 互不感知
```
技能靠 `description` 字段自描述触发词 · 不需要注册表 · 不需要改全局配置 · 上线即生效
#### 4. 路由词表可插拔:分片隔离,局部更新
词条变更只改对应 `matchers/m-xxx.json`,其他路由 diff 为零;结构见「[一、路由与上下文加载 → matchers 分片](#matchers-分片不嵌入-manifest)」。
词条变更局部化 · 合并冲突最小化 · 新增路由不影响存量
#### 5. 执行模型可插拔:config 按项目切换
```
flow2spec.config.json
subAgent: false → 全程主 agent,低开销,适合小项目
subAgent: true → 允许拆子并行,适合大规模改动
switchAgentVerification: false → 落盘侧自验,日常使用
switchAgentVerification: true → 交叉校验,高置信度关键场景
changeTracking.feat/fix/implement: false → 不创建任务清单
changeTracking.feat/fix/implement: true → 对应技能执行时自动创建任务清单,支持跨会话续作
三个维度正交 · 各技能可进一步细化覆盖全局配置
```
改一行配置切换执行策略 · 不修改任何技能文件 · 新项目开箱即用,老项目按需升级
---
## 优势与劣势
```
✅ 优势 ⚠️ 局限
上下文精准 前期投入:知识要靠技能建起来
└─ 路由只加载相关文档 规模门槛:小项目开销 > 收益
跨工具共享 需要团队纪律
└─ 知识写一份,三工具都用 └─ 技能只降低摩擦,不消灭摩擦
工具无关 学习曲线
└─ 换工具不重建知识 └─ stock/req 边界、路由结构不直觉
可持续
└─ 维护绑定开发动作
```
---
## 适合谁
```
项目规模
小 ◄──────────► 大
┌──────────┬────────────┐
短期 │ 不需要 │ 可以用 │
├──────────┼────────────┤
长期 │ 可以用 │ 强烈推荐 │
└──────────┴────────────┘
同时满足:有规模 · 长期迭代 · 多工具或多人 AI 协作
```
---
## 相关文档
- [Flow2Spec使用说明](./Flow2Spec使用说明.md)
- [README-命令说明](./README-命令说明.md)
- [README-体系与原理](./README-体系与原理.md)
- [Flow2Spec-使用案例-模拟对话](./Flow2Spec-使用案例-模拟对话.md)
- [Flow2Spec-演讲稿](./Flow2Spec-演讲稿.md)
# Flow2Spec 使用说明
## 一、init 做了什么
在业务仓库根执行:
```bash
flow2spec init [cursor|claude|codex ...]
# 需要强制重置 .Knowledge 到模板时:
flow2spec init [cursor|claude|codex ...] --reset-knowledge
```
| init 做 | init 不做 |
|---------|----------|
| 补齐缺失的目录与模板文件 | 撰写或更新业务文档内容 |
| 落盘各 agent 配置根 `rules/` `skills/` | 更新 `includeAny` 业务词条 |
| `manifest-routing` + `matchers/` 包级结构对齐 | 替代 `f2s-*` 技能对业务语义的书写 |
| `--reset-knowledge` 时强制覆盖 `.Knowledge` 模板文件 | (不加此参数时)覆盖已有 `.Knowledge` 内容 |
> **`init` 与「知识库升级」是两件事**:`init` 只做结构补齐,业务语义(topics 内容、路由词条、stock-docs/req-docs)由 `f2s-doc-add`、`f2s-kb-fix`、`f2s-kb-feat`、`f2s-kb-sync`、`f2s-ctx-build` 等技能维护。跨版本升级用 `f2s-kb-upgrade`,**不要把单独 `init` 当作升级命令**。
### `f2s-*` 与 `flow2spec.config.json`:多端多重提示(权威仍为磁盘 JSON)
执行任意 **`f2s-*` 技能**前,需要让 Agent 拿到 **`subAgent` / `switchAgentVerification` / `changeTracking`** 等实际值。Flow2Spec 在 **不同客户端** 用 **不同机制** 强化这一点;它们彼此**补充**,**不**互相替代,**权威始终**是项目根 **`flow2spec.config.json`**(须用 **Read** 与磁盘一致后再进技能正文)。
| 端 | `init` 落盘与行为 | 说明 |
| --- | --- | --- |
| **Cursor** | `.cursor/rules/f2s-config-check.mdc`(`alwaysApply`) | 规则要求:技能正文前先 **Read(`flow2spec.config.json`)**。 |
| **Claude Code** | `.claude/hooks/f2s-config-inject.js` + `.claude/settings.json`(PreToolUse,`Skill` 匹配) | 在调用 **`f2s-*` Skill** 时注入配置摘要;**文件缺失、JSON 无效或 hook 未预期异常**时也会注入**说明 + 与「文件不存在」一致的默认语义**,避免静默;仍建议在存疑或刚改过配置时 **Read** 核对。 |
| **Codex** | `.codex/AGENTS.md` 顶部强制步骤 + `{{FLOW2SPEC_PROJECT_CONFIG}}` 展开表 | **Read** 为硬要求;配置表为 **最近一次 `flow2spec init` 的快照**,与磁盘不一致时以 **Read** 为准。同目录 **`.codex/topics/f2s-config-check.md`** 与 Cursor 规则同源(含 **changeTracking** 细表),**按需**打开即可,不必与「专题长文」三条示例并列必读。 |
| **知识库(可选)** | `.Knowledge/manifest-routing` 命中 **`config-precheck`** 时 | `.Knowledge/topics/f2s-config-precheck.md` 为**路由摘要**,链向 Codex 长文;**不**在 `.Knowledge` 再维护第二份全文,也**不**替代 Read JSON。 |
字段语义与默认值规则见 [README-命令说明 § 6) 子 Agent 配置说明](./README-命令说明.md)。设计视角见 [Flow2Spec-设计说明 § 四、5.1](./Flow2Spec-设计说明.md);口述见 [Flow2Spec-演讲稿 Slide 13b](./Flow2Spec-演讲稿.md)。
---
## 二、目录约定
核心区分:`stock-docs/` 放沉淀文档(驱动知识路由),`req-docs/` 放技术方案(驱动编码实现),两者不互换。
完整目录说明见 [README-目录与路径约定](./README-目录与路径约定.md)。
---
## 三、典型工作场景
### 需求规划并实现
```
f2s-req-plan
```
输入技术方案文档路径或需求描述,先输出任务清单草稿并等待确认,确认后按清单实现代码。始终创建 `.task/` 任务清单,不需要配置 `changeTracking`。适合希望先看清全貌再动手、或需要跨会话追踪进度的场景。
### 变更追踪与跨会话续作
```
# 自动模式:配置开启(各技能独立)
flow2spec.config.json → changeTracking.feat / fix / implement: true
# 显式模式:调用 f2s-req-plan(规划 + 实现,不依赖配置)
f2s-req-plan
```
**自动模式**:开启后,`f2s-kb-feat` / `f2s-kb-fix` / `f2s-implement-tech-design` 执行时自动在 `.task/active/` 创建任务清单,逐步勾选,完成后归档。下次会话描述相关内容,`f2s-task` 规则自动匹配并加载剩余清单,无需重新说明上下文。
**显式模式**:直接调用 `f2s-req-plan`,不管 `changeTracking` 配置,始终创建任务清单并按清单实现代码,适合希望先确认全貌再动手的场景。
### 新需求开发
```
f2s-req-clarify → f2s-req-backend → implement-tech-design → f2s-kb-feat
```
需求已明确时可跳过 `f2s-req-clarify`,直接从 `f2s-req-backend` 开始。技术方案落入 `req-docs/` 后,由 `implement-tech-design` 规则驱动编码。
### 文档沉淀
```
新增架构文档沉淀:f2s-doc-arch → f2s-doc-final → f2s-ctx-build
PDF 文档沉淀: f2s-doc-pdf → f2s-doc-final → f2s-ctx-build
```
把架构说明或 PDF 技术方案纳入知识路由(生成 topics/matchers/manifest-routing)。
### PDF 方案实现
```
f2s-doc-pdf → implement-tech-design
```
拿到 PDF 技术方案后直接转 Markdown 落入 `req-docs/`,再由 `implement-tech-design` 规则驱动编码。
### 存量能力补录
```
f2s-doc-add # 多文件聚合,从源码/文档提取
f2s-kb-sync # 从当前会话推断已实现能力
```
代码已落地但知识库没有记录时使用。`f2s-doc-add` 适合批量导入,`f2s-kb-sync` 适合会话结束时的即时沉淀。
### 日常维护
```
f2s-kb-fix # 修复实现或规则错误,自动同步知识库
f2s-kb-feat # 新增能力,自动同步知识库
f2s-kb-sync # 定期同步或补录
f2s-kb-merge # Git 合并后解决上下文冲突
```
### 知识库跨版本升级
```
f2s-kb-migrate(流程 V1:旧库)→ f2s-kb-upgrade
f2s-kb-upgrade(流程现行库 V2+:已有 .Knowledge;含 npm v3.x 等,见技能步骤 0)
```
---
## 四、Agent 执行配置
通过项目根 `flow2spec.config.json` 控制,字段完整规则见 [README-命令说明 § 6) 子 Agent 配置说明](./README-命令说明.md)。**各端如何被提示读到配置、为何仍以 Read 为权威**见 **§ 一**(本 § 仅说明**何时**打开各开关)。
**何时开启 `subAgent: true`**:任务规模较大时(多模块并行实现、批量文档入库、大规模迁移)。开启后各技能按自身规模门槛决定是否实际拆分,未达门槛的仍在主 agent 内完成。
**何时开启 `switchAgentVerification: true`**:需要更高落盘一致性时(大规模迁移、重要方案实现)。代价是增加执行轮次;常规维护场景默认 `false` 足够。须搭配 `subAgent: true` 才能触发"主落子验"方向的交叉。
**何时开启 `changeTracking.*`**:希望每次技能执行自动留下可续作的任务清单时。各技能子项独立配置,互不影响:
```json
{
"changeTracking": {
"feat": true,
"fix": false,
"implement": true
}
}
```
不想依赖配置、希望按需显式规划任务时,直接使用 `f2s-req-plan`。
---
## 五、规则改造建议
- 项目特化「按技术方案实现」逻辑时,优先调整 **`f2s-implement-tech-design`**:Cursor `.cursor/rules/f2s-implement-tech-design.mdc`,Claude `.claude/rules/f2s-implement-tech-design.md`;Codex 以 `.codex/AGENTS.md` 与相关 `skills/` 为准
- 再次 `init` 默认仅补齐缺失模板并做包级结构对齐,**不**替代 `f2s-*` 对业务内容的维护;需用模板重置 `.Knowledge` 时加 `--reset-knowledge`
---
## 六、技能标识
技能以 `name` 与 `description` 匹配触发,文件位于 `配置根/skills/*/SKILL.md`。
---
## 七、相关文档
- [README-命令说明](./README-命令说明.md)
- [README-目录与路径约定](./README-目录与路径约定.md)
- [README-体系与原理](./README-体系与原理.md)
- [Flow2Spec-使用案例-模拟对话](./Flow2Spec-使用案例-模拟对话.md)
# 体系与原理
Flow2Spec 的目标是把"业务知识沉淀"与"Agent 能力加载"拆开:
- **知识层**:`.Knowledge`(文档与索引)
- **执行层**:配置根 `rules/skills`(供各工具原生加载)
---
## 1. 两层结构
| 层 | 位置 | 作用 |
| --- | --- | --- |
| 知识层 | `.Knowledge/` | 保存业务文档、索引、路由 |
| 执行层 | `.cursor/.claude/.codex` | 保存规则与技能入口 |
---
## 2. 渐进式读取
统一建议顺序:
1. `.Knowledge/manifest-routing.json`
2. `.Knowledge/matchers/<matcher>.json`(按需:由 `manifest-routing.taskToTopicRules[].matcherPath` 直链定位)
3. `.Knowledge/index.md`
4. 命中的 `stock-docs` / `req-docs` 文档
5. 必要时下钻源码
读取后执行 `match → expand → verify → act` 四步流水线:命中主候选后展开依赖主题、缺口检查,置信度足够时才执行;低置信度先澄清。
同时由配置根入口(Flow2Spec 包规则:`f2s-flow2spec-unified-entry.mdc` / `f2s-flow2spec-unified-entry.md`;旧版业务仓库常见为 `main.md(c)`;以及 `AGENTS.md`)约束加载行为。
其中 Codex 不读取 `rules/` 目录,统一通过 `.codex/AGENTS.md` + `skills/` 承载执行约束。
---
## 3. 关键链路
- 文档沉淀链:`f2s-doc-arch` → `f2s-doc-final` → `f2s-ctx-build`
- 实现链:`.Knowledge/req-docs/*.md` → `implement-tech-design` → 代码
- 维护链:`f2s-kb-fix` / `f2s-kb-feat` / `f2s-kb-sync` / `f2s-kb-merge`
- 需求规划链:`f2s-req-plan`(规划 + 实现,始终创建任务清单)
- 变更追踪链:`changeTracking.*` 配置 → `f2s-task` 规则(自动)→ `.task/` 任务清单 → 跨会话续作
- 包模板/路由形态与配置根对齐:`f2s-kb-upgrade`(**勿**将单独 `flow2spec init` 等同于「知识库升级」);旧库结构迁入 `.Knowledge`:`f2s-kb-migrate`
---
## 4. Agent 执行模型
Flow2Spec 通过项目根 `flow2spec.config.json` 的 `subAgent`、`switchAgentVerification` 两个字段控制执行行为。
**Agent 如何读到上述真值**:多端提示 + **Read** 权威,见 [Flow2Spec使用说明 § 一(唯一详表)](./Flow2Spec使用说明.md);设计归纳见 [Flow2Spec-设计说明 § 四、5.1](./Flow2Spec-设计说明.md)。
### 4.1 主/子 Agent 职责划分原则
**`subAgent: false`(默认)**:全部 `f2s-*` 技能在主 agent 内顺序完成,无并行拆分。
**`subAgent: true`**:达到技能正文约定的规模门槛时,允许拆分子 agent 并行处理。职责边界如下:
| 角色 | 职责边界 |
|------|----------|
| 主 agent | 统筹规划、确定任务粒度与分配策略、汇总子 agent 输出、校验跨单元一致性、最终落盘 |
| 子 agent | 处理指定单元(模块/文档/主题),按约定格式输出结果,不跨单元决策 |
子 agent 的拆分边界由各 `f2s-*` 技能正文逐步约定(如模块数、文档数、代码行数等门槛),**当前尚未在模板层给出统一阶段表**,以技能正文为准。
### 4.2 验证归属原则
**默认(谁落盘谁验)**:落盘或变更后的验证在落盘侧 agent 内完成。子 agent 落盘则子 agent 自验,主 agent 落盘则主 agent 自验。
**交叉验证(`switchAgentVerification: true`)**:由对方 agent 承担验证,适用于需要更高置信度的场景。启用条件必须**同时满足**:
1. 配置 `switchAgentVerification: true`
2. 当前执行的 `f2s-*` 技能正文**明确写出**该步骤依赖本项
交叉验证规则:
| 落盘方 | 验证方 | 前提条件 |
|--------|--------|----------|
| 子 agent 落盘 | 主 agent 验证 | 无额外条件 |
| 主 agent 落盘 | 子 agent 验证 | 须 `subAgent: true` 且实际已拆出子任务;否则仍由主 agent 自验 |
设计意图:交叉验证引入外部视角,降低落盘侧的自验盲区,但增加执行开销,因此设为显式 opt-in 而非默认行为。
### 4.3 变更追踪(changeTracking)
`changeTracking` 是独立于 `subAgent` / `switchAgentVerification` 的第三个维度,控制技能执行时是否自动创建可跨会话续作的任务清单。
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
- 各技能子项独立控制,互不影响
- 开启后:技能执行前自动检查 `.task/todo.json`,创建或续接任务;完成后自动归档
- 跨会话:新会话描述相关内容,`f2s-task` 规则(`alwaysApply`)关键词匹配命中后自动加载剩余清单和对应技能上下文
- `f2s-req-plan` 不受此配置约束,始终创建任务清单
---
## 5. 设计收益
1. 跨工具共享同一业务知识源
2. 不破坏 Claude/Cursor/Codex 的规则加载习惯
3. 通过 `manifest-routing` + `matcherPath` 分片(`matchers/*.json`)控制任务路由与依赖,减少误读与全量扫描
4. 主/子 agent 职责边界清晰,主 agent 始终持有全局视图,子 agent 专注单元处理,汇总一致性由主 agent 保证
5. 验证归属可配置:默认落盘侧自验保持低开销,交叉验证按需启用提升关键场景置信度
---
## 6. 相关文档
- [Flow2Spec使用说明](./Flow2Spec使用说明.md)
- [README-命令说明](./README-命令说明.md)
- [README-目录与路径约定](./README-目录与路径约定.md)
- [Flow2Spec-使用案例-模拟对话](./Flow2Spec-使用案例-模拟对话.md)
# 工作流与技能说明
## 1) 文档沉淀(stock-docs 链路)
### `f2s-doc-arch`
**作用**:根据用户说明或扫描代码,生成项目架构说明初稿。无固定格式要求,描述清楚系统结构、模块关系、关键决策即可。
**工作原理**:以「inventory 驱动扫描」为核心——先由主 agent 产出模块清单(inventory)与扫描契约(读哪些入口、关注哪些维度),再按 inventory 执行只读代码扫描,最后将扫描结果聚合为人可读的架构初稿落盘 `stock-docs/`。整个流程不改代码,仅做「代码→文档」的单向提取。
**使用场景**:
- 新项目需要架构文档
- 存量项目需要补充架构说明
- 系统重构后更新架构描述
**关联关系**:
- **前置**:无
- **后续**:`f2s-doc-final`(规范化终稿)或直接用于 `f2s-ctx-build`
- **输出**:`.Knowledge/stock-docs/<架构说明>_初稿.md`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内扫描代码并生成
- `subAgent: true`:默认走 **B 模式**(主产出 inventory + 扫描契约 → 子 agent 并行只读扫表 → 主合并落盘);满足以下任一条件时升级为 **C 模式**(多轮纠偏):多 workspace / monorepo、源路径 > 20 条、首轮子表有矛盾或空洞、多源叙述冲突严重
**职责划分**:
| 角色 | 职责 |
| --------------- | ------------------------------------------------------------------------------------------ |
| 主 agent | 产出 inventory(入口 + 核心模块名)与扫描契约,汇总子 agent 交付,落盘 stock-docs 初稿 |
| 子 agent(B/C 模式) | 按主手写 inventory 并行只读扫描,按统一 YAML schema 交付(`source / scope / cross_refs / pending`),不得自行裁剪范围 |
---
### `f2s-doc-final`
**作用**:将 PDF 技术方案或初稿文档转为《终稿模版》规范格式,统一文档结构,便于后续进入知识库。
**工作原理**:将非结构化或格式各异的文档(PDF/初稿)对照内置终稿模版进行格式归一化:提取核心概念表、业务规则、关键流程、配置与错误处理等标准章节,补齐缺失段落标记,最终输出格式统一的 `_终稿.md`。终稿是 `f2s-ctx-build` 的标准输入物,确保知识库入口的结构一致性。
**使用场景**:
- PDF 技术方案需要转为 Markdown
- 初稿需要规范化以便沉淀
- 外部文档需要纳入 Flow2Spec 管理
**关联关系**:
- **前置**:PDF 文档或初稿文档
- **后续**:`f2s-ctx-build`(终稿入库)
- **输出**:`.Knowledge/stock-docs/<文档>_终稿.md`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成全流程
- `subAgent: true`:PDF > 50 页或 > 5MB 时,可拆子做套模版与排版草稿;子不追问用户、不补写流程说明、不宣称终稿合规;主 agent 识别格式缺口并定稿验收
**职责划分**:
| 角色 | 职责 |
| ------- | --------------------- |
| 主 agent | 识别格式缺口、对照模版与澄清文档验收定稿 |
| 子 agent | 套模版与排版草稿,不追问用户、不写流程说明 |
---
### `f2s-ctx-build`
**作用**:将 `stock-docs/` 中的沉淀文档(架构、终稿)同步到知识库路由系统,生成/更新主题文件、索引、manifest-routing、matchers。
**工作原理**:以终稿文档为输入,执行「文档→路由」的三步映射:① 从终稿中提取能力主题与关键词;② 生成 `topics/<topic>.md`(路由摘要,含执行边界与下一步指针)和 `matchers/<id>.json`(机读匹配词 `includeAny`);③ 在 `manifest-routing.json` 注册 task→topic 映射规则,并更新 `index.md` 人读导航。完成后,任务路由引擎即可通过关键词命中该主题。
**使用场景**:
- 终稿文档完成后,需要让知识库"知道"这些文档
- 新增业务领域,需要建立路由映射
- 文档内容更新后,同步更新知识库索引
**关联关系**:
- **前置**:`f2s-doc-arch`、`f2s-doc-final` 或直接编写的终稿
- **后续**:无(入库完成后可直接使用)
- **输入**:`.Knowledge/stock-docs/*.md`
- **输出**:
- `.Knowledge/topics/<topic>.md`
- `.Knowledge/index.md`
- `.Knowledge/manifest-routing.json`
- `.Knowledge/matchers/*.json`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内顺序处理各文档
- `subAgent: true`:改动超过阈值(新增/修改主题 > 2 个 OR 新增 matcher > 1 个 OR 涉及跨主题批量引用调整)时拆子;子A 只写 topics/、子B 只写 matchers/;主 agent 单点编辑 manifest-routing.json 和 index.md,子 agent 不跨边界落盘
**职责划分**:
| 角色 | 职责 |
| ----------------- | ------------------------------------------ |
| 主 agent | 单点落盘 manifest-routing.json 和 index.md,整体验收 |
| 子 agent(topics) | 仅写 topics/ 目录下的主题文件,不触碰 manifest 和 index |
| 子 agent(matchers) | 仅写 matchers/ 目录下的分片文件,不触碰 manifest 和 index |
---
### `f2s-doc-add`
**作用**:将已落地能力(多文件聚合)解析进知识库。适用于代码已实现但缺少文档,或已有多个文档需要统一入库的场景。
**工作原理**:从多个分散的源文件(代码、配置、散落文档)中聚合提取能力描述,走完整的「初稿→终稿→topics/index/manifest」沉淀链路。与 `f2s-ctx-build` 的区别在于输入:`ctx-build` 从已有的单份终稿驱动,`doc-add` 从多个散落源聚合后再走同一管线。本质是补齐「有实现无文档」的缺口。
**使用场景**:
- 存量代码需要补录知识库
- 多份相关文档需要聚合入库
- 第三方文档批量导入
**关联关系**:
- **前置**:无(可直接触发)
- **后续**:无(入库完成即结束)
- **流程**:初稿 → 终稿 → topics/index/manifest
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内顺序处理
- `subAgent: true`:满足以下任一阈值时启用,默认走 **B 模式**(主产出 inventory → 子并行只读按 schema 填表 → 主合并落盘);多 workspace / monorepo、首轮子表矛盾或空洞、多源叙述冲突严重时升级 **C 模式**(多轮纠偏)
- 阈值:输入路径 ≥ 5 条 OR 单源 > 3000 行 OR 多路径总量 > 10000 行
**职责划分**:
| 角色 | 职责 |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| 主 agent | 产出 inventory 与扫描契约,汇总子表,落盘 topics/index/manifest |
| 子 agent(B/C 模式) | 按主手写 inventory 执行只读扫描,按 schema 交表(`source / scope / capabilities / cross_refs / pending`);不得自行裁剪范围、不写 manifest 和 index、不宣布"已进知识库" |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 落盘的 topic 文件 → 主 agent 校验路由映射完整性与关键词覆盖
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-ctx-rm`
**作用**:按 stock-docs 文档删除对应的知识主题与索引映射。仅删除知识库中的引用关系,不删除源文档本身。
**工作原理**:`f2s-ctx-build` 的逆操作——给定一份 `stock-docs` 文档路径,定位其在 `manifest-routing.json` 中的 task→topic 规则、对应的 `matchers/<id>.json` 分片、`topics/<topic>.md` 文件以及 `index.md` 中的行项,逐一清除引用。若删除后某 topic 无任何 task 引用,则移除该 topic 文件。源文档本身保留不动,用户可自行决定是否物理删除。
**使用场景**:
- 文档已废弃,需要从知识路由中移除
- 误入库的文档需要撤销路由映射
- 文档合并后清理旧映射
**关联关系**:
- **前置**:已入库的 stock-docs 文档
- **后续**:无
- **注意**:只删路由映射,不删源文档
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内全流程执行(单点删除拆子收益低)
- `subAgent: true`:仅当**批量删除 ≥ 5 个主题**时才拆子执行删除与清引用;主 agent 必控范围确认与 fallbackTopic 重指;manifest-routing.json 与 index.md 恒由主落盘
---
### `f2s-doc-pdf`
**作用**:将 PDF 技术方案转为 Markdown 格式,保存到 `req-docs/`,可补全流程说明。
**工作原理**:面向「按方案实现代码」的前置环节——将 PDF 中的接口定义、数据模型、时序流程等结构化内容提取为 Markdown 格式并落盘 `req-docs/`。与 `f2s-doc-final` 的区别在于目标路径和用途:`doc-pdf` 输出到 `req-docs/` 供 `implement-tech-design` 规则消费驱动编码,`doc-final` 输出到 `stock-docs/` 供 `ctx-build` 入库。
**使用场景**:
- 收到 PDF 格式技术方案需要实现
- 历史 PDF 文档需要纳入管理
- 跨团队交付物为 PDF 时需要转换
**关联关系**:
- **前置**:PDF 文档
- **输出**:`.Knowledge/req-docs/<方案>.md`
- **下一步**:
- 1. 如果是需求实现:提供转换后的方案路径并说明"按技术方案实现",由 `implement-tech-design` 规则驱动编码
- 1. 如果是转存知识库:走转换终稿流程 `f2s-doc-final` → `f2s-ctx-build`
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成全流程
- `subAgent: true`:PDF > 50 页或 > 5MB 时,可拆子做 PDF→MD 首稿落盘 req-docs;子不追问用户、不补写流程说明章节;主 agent 接手追问与流程说明补写
**职责划分**:
| 角色 | 职责 |
| ------- | ------------------------------- |
| 主 agent | 追问用户补充流程说明、完成 req-docs 落盘验收 |
| 子 agent | 仅做 PDF→MD 首稿并落盘 req-docs,不向用户追问 |
---
## 2) 需求与方案
### `f2s-req-clarify`
**作用**:针对 PRD/需求文档进行反问澄清,通过多轮问答明确需求边界、非目标、关键流程,直至需求足够清晰可供技术方案编写。
**工作原理**:采用「结构化追问」策略——将需求文档按「角色/场景/流程/边界/异常/非目标」六维拆解,逐维检查是否存在模糊表述、未定义概念或矛盾点,对每个缺口生成针对性追问。多轮对话直到所有维度无歧义后,输出需求澄清记录作为 `f2s-req-backend` 的输入。本质是将非结构化 PRD 转为可落地的结构化需求约束。
**使用场景**:
- 收到 PRD 后首步骤,确保理解正确
- 需求边界模糊、缺少验收标准时
- 跨团队协作需求,需明确接口契约
**关联关系**:
- **前置**:无(可直接触发)
- **后续**:`f2s-req-backend`(澄清后生成技术方案)
- **输出**:需求澄清记录(可选保存至 `.Knowledge/req-docs/`)
**子 agent 调用**:无(澄清全程依赖连续对话与用户即时反馈,不拆子 agent)
---
### `f2s-req-backend`
**作用**:基于已澄清的需求和项目知识库,生成后端技术方案文档,包含接口设计、数据模型、流程说明、错误码等。
**工作原理**:以「知识库约束 + 模版驱动」为核心——先从 `topics/stock-docs` 中抽取当前项目的架构约定、接口风格、数据模型规范等约束摘要,再将澄清后的需求对照后端技术方案模版(接口/模型/流程/异常/配置/迁移)逐章填写,确保方案与现有架构一致。输出落盘 `req-docs/`,即为 `implement-tech-design` 的编码依据。
**使用场景**:
- `f2s-req-clarify` 完成后,基于澄清结果输出方案
- 已有明确需求文档,直接生成技术方案
**关联关系**:
- **前置**:`f2s-req-clarify`(推荐)或明确的需求文档
- **输出**:`.Knowledge/req-docs/<技术方案>.md`
- **下一步**:提供技术方案路径并说明"按技术方案实现",由 `implement-tech-design` 规则驱动编码
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成方案编写
- `subAgent: true`:主 agent 必须先从 topics/stock-docs 抽取 < 80 行项目约定摘要(含架构约定、接口风格、数据模型规范等 6 类条款)作为子强制上下文,再拆子并行写 req-docs 初稿;主 agent 做契约定稿与验收
**职责划分**:
| 角色 | 职责 |
| ------- | ----------------------------------------------------------------------- |
| 主 agent | 抽取项目约定摘要、分配写作任务、对照模版做定稿验收并写入 req-docs |
| 子 agent | 只读多源(topics / stock-docs / 澄清 req-docs / 模版),按模版写 req-docs 初稿;不自行扩展读取范围 |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 落盘的接口/模型/流程文档 → 主 agent 校验跨章节一致性(接口签名与数据模型对齐、流程与异常处理覆盖)
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-req-plan`
**作用**:从技术方案或需求描述出发,**始终创建任务清单**,然后按清单实现代码。不依赖 `changeTracking` 配置,代表用户明确需要可追溯的任务管理。
**工作原理**:执行「解析→规划→确认→实现→归档」五阶段闭环。① 解析技术方案文档提取实现要点;② 按模块/功能粒度拆分为可执行任务清单并写入 `.task/`;③ 展示草稿给用户确认后锁定清单;④ 按清单逐项实现代码,每完成一项立即打钩 `task.md`;⑤ 全部完成后归档。与 `implement-tech-design` 规则的区别:`req-plan` 始终带任务追踪且支持并行子 agent 实现,适合大型需求;后者是轻量规则驱动的单线程编码。
**使用场景**:
- 有技术方案文档,需要拆解为任务清单后再实现
- 需求描述较复杂,希望先确认清单再动手
- 希望跨会话追踪实现进度
**关联关系**:
- **前置**:技术方案文档路径(`.Knowledge/req-docs/*.md` 或 PDF)或需求/变更描述
- **输出**:`.task/active/<task-name>/task.md` + `context.md`;实现代码
- **后续**:可按需调用 `f2s-kb-sync` 补充知识库
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成解析、确认、实现全流程
- `subAgent: true`:步骤 1(解析文档)可拆子并行只读;步骤 2(草稿确认)必须主 agent;步骤 4(实现代码)可按模块拆子并行;`todo.json` 恒由主 agent 写
**职责划分**:
| 角色 | 职责 |
| ----------- | ------------------------------------ |
| 主 agent | 输出草稿、用户确认、写 `todo.json`、汇总实现摘要 |
| 子 agent(解析) | 只读文档,输出解析结果摘要,不落盘 |
| 子 agent(实现) | 按模块实现代码,不触碰 `.task/` 和 `.Knowledge/` |
---
## 3) Git 提交
### `f2s-git-commit`
**作用**:代码写完后执行 Git 提交。自动检查变更文件、比对知识库覆盖情况,未入库的能力会提示用户处理,确认提交信息后执行 commit。
**工作原理**:在 `git commit` 之上叠加「知识库覆盖门控」——先通过 `git diff` 推断本次变更涉及的功能模块,再与 `.Knowledge/topics/` 和 `stock-docs/` 交叉比对,判断变更能力是否已有知识库记录。未覆盖时阻断并提示三选(补录/跳过/取消),避免「代码有了但知识库不知道」的静默漂移。提交信息强制 emoji + Conventional Commits 格式,保证 git log 的机读一致性。
**使用场景**:
- 每次功能实现或 Bug 修复后提交代码
- 希望在提交时得到知识库覆盖情况的提醒
- 需要 AI 帮助生成有意义的提交信息
**关联关系**:
- **前置**:代码已写完(`implement-tech-design`、`f2s-kb-fix`、`f2s-kb-feat` 等执行后)
- **后续**:无(commit 完成即结束,不自动 push)
- **可衔接**:若知识库未覆盖,可先运行 `f2s-kb-sync` 或 `f2s-kb-feat` 补录后继续提交
**执行流程**:
1. `git status --short` + `git diff HEAD` 区分 staged / unstaged / untracked 三类文件;发现 merge conflict 标记立即终止
2. 对比 `.Knowledge/topics/` 与 `stock-docs/`,判断本次变更能力是否已入库;`.Knowledge` 不存在时跳过并提示
3. 未覆盖时提示用户选择:A) 先补录再提交 / B) 先提交稍后补录 / C) 取消
4. 基于 `git diff` 实际内容生成提交信息草稿,等待用户确认或修改
5. `git add <具体文件>` + `git commit`;hook 失败则提示修复,不跳过
6. 输出 commit hash;若选 B 则附带未补录能力提醒
**约束**:
- 禁止 `git add -A` / `git add .`,只 add 已确认的变更文件
- 禁止 `--no-verify`,hook 失败须修复后重试
- 禁止自动 push
- 提交信息必须经用户确认,不可静默提交
**子 agent 调用**:无(全程交互确认,主 agent 内完成)
---
## 4) 知识库维护
### `f2s-kb-fix`
**作用**:根据用户指出的实现或规则错误修正代码,并**默认自动同步**知识库相关文档与索引。
**工作原理**:执行「定位→修复→同步」三步——先根据用户描述在知识库路由(manifest→topic→stock-docs)中定位相关上下文与代码位置,确认问题根因;修复代码后,自动检查 `topics/stock-docs/matchers` 中与该能力相关的描述是否因修复而需要更新,若有则原位修订(现行真值覆盖,不追加历史否定句)。「修代码必同步文档」是核心原则,避免知识库与实现漂移。
**使用场景**:
- 代码实现与技术方案不符
- 规则理解有误需要修正
- Bug 修复后需要同步文档
**变更追踪**:若 `changeTracking.fix: true`,执行前自动检查 `.task/todo.json` 并创建任务清单,完成后自动归档;跨会话可通过关键词续作(见 `f2s-task` 规则)。
**关联关系**:
- **前置**:问题发现(代码实现错误或规则偏差)
- **后续**:无(修复并同步完成即结束)
- **特点**:无需用户额外要求"请同步知识库",自动完成
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成修复和知识库同步
- `subAgent: true`:代码子包(bug 修复)可外包给子 agent;文档子包(rules/skills/topics 文风类)默认主 agent 直接写,如拆则子 agent 仅输出 before/after diff 片段,不整文件重写;manifest 和 index 恒由主落盘
**职责划分**:
| 角色 | 职责 |
| -------------- | ---------------------------------------------------- |
| 主 agent | 定位问题根因、制定修复方案、落盘文风合规内容、校验知识库一致性 |
| 子 agent(代码) | 负责指定模块的代码 bug 修复,输出变更并报告影响范围 |
| 子 agent(文档,可选) | 仅输出 before/after diff 片段,不整文件重写,不触碰 manifest 和 index |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 落盘的代码变更 → 主 agent 校验修复正确性与知识库一致性
- 主 agent 落盘的知识库同步 → 子 agent 复核 topic/manifest 一致性(须 `subAgent: true` 且已拆出子任务,否则主 agent 内自验)
- 复核方与落盘方必须为不同 agent 实例
---
### `f2s-kb-feat`
**作用**:新增能力时补全实现与知识库;若能力已实现,则仅同步知识库。
**工作原理**:执行「判断→实现→入库」三阶段——先判断用户描述的能力在代码中处于「未实现/部分实现/已实现」哪种状态;未实现或部分实现时先补齐代码;最后走知识库同步:写 `stock-docs` 能力说明、生成或更新 `topics` 主题摘要、在 `manifest-routing` 和 `matchers` 注册路由映射。与 `f2s-kb-fix` 的区别:`kb-feat` 面向「新增」,`kb-fix` 面向「修正已有」。
**使用场景**:
- 新功能开发
- 存量功能需要补录知识库
**变更追踪**:若 `changeTracking.feat: true`,执行前自动检查 `.task/todo.json` 并创建任务清单,完成后自动归档;跨会话可通过关键词续作(见 `f2s-task` 规则)。
**关联关系**:
- **前置**:无(可直接触发)
- **后续**:无(实现+同步完成即结束)
- **特点**:自动同步知识库,无需用户额外要求
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成
- `subAgent: true`:代码子包(新增实现)可外包给子 agent;文档子包(rules/skills/topics 文风类)默认主 agent 直接写,如拆则子 agent 仅输出 before/after diff 片段;manifest 和 index 恒由主落盘
**职责划分**:
| 角色 | 职责 |
| -------------- | ---------------------------------------------------- |
| 主 agent | 确定能力边界与实现范围、落盘文风合规内容、最终校验知识库一致性 |
| 子 agent(代码) | 负责代码实现(接口、逻辑、数据层),输出实现清单 |
| 子 agent(文档,可选) | 仅输出 before/after diff 片段,不整文件重写,不触碰 manifest 和 index |
**交叉验证(`switchAgentVerification: true` 时)**:
- 文档子 agent 落盘的 topic → 主 agent 校验与实现代码的能力描述一致性
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-kb-sync`
**作用**:将会话中的已实现能力沉淀回知识库。可显式给出能力或零输入推断。
**使用场景**:
- 会话中已完成实现,需要补录知识库
- 从代码反向沉淀知识
- 定期知识库整理
**关联关系**:
- **前置**:无(可直接触发,或零输入推断)
- **后续**:无
- **特点**:先输出知识库更新大纲,用户确认后才写入
- **与 `f2s-ctx-build` 区别**:`ctx-build` 从 `stock-docs` 驱动,`kb-sync` 从会话/代码推断
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成推断和同步
- `subAgent: true`:分步骤拆子——**步骤 1**(汇总推断)可拆子并行只读会话历史;**步骤 2**(用户确认大纲)必须在主 agent 完成;**步骤 3**(落盘同步)可拆子写 topic/matcher,但子落盘前须读近邻 2–3 个主题摘要做风格对齐;manifest 和 index 恒由主落盘
**职责划分**:
| 角色 | 职责 |
| ----------- | ------------------------------------------------------- |
| 主 agent | 输出大纲并确认、单点落盘 manifest 和 index、最终验收 |
| 子 agent(汇总) | 只读会话历史、推断能力点、生成结构化更新大纲片段 |
| 子 agent(同步) | 按大纲写 topic/matcher,落盘前加载近邻主题摘要对齐风格,不触碰 manifest 和 index |
**交叉验证(`switchAgentVerification: true` 时)**:
- 同步子 agent 落盘的 topic/matcher → 主 agent 校验跨 topic 路由完整性与 `includeAny` 关键词覆盖
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-kb-merge`
**作用**:解决 Git 合并后的编辑器上下文冲突。可选传入冲突文件路径。
**工作原理**:按文件类别分层处理冲突——将冲突文件分为「可安全自动合并」(index、manifest、matchers 等结构化文件,取并集或最新版本)和「须用户确认」(实现代码、业务规则等语义文件)两类。对前者自动 resolve,对后者生成分类对照表(ours/theirs 摘要 + 建议)并罗列差异,等待用户逐项裁决。核心设计思想:知识库元数据可自动化,业务语义不可擅自裁定。
**使用场景**:
- Git merge/rebase 后出现上下文冲突
- 多人协作导致知识库文件冲突
- 分支合并后需要统一知识库状态
**关联关系**:
- **前置**:Git 合并产生的冲突
- **后续**:无(冲突解决即结束)
- **特点**:实现侧冲突仅罗列待用户确认
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内分析与解决冲突
- `subAgent: true`:可拆子做冲突扫描与分类对照表(`file / category / ours_summary / theirs_summary / recommendation` 五字段);子不得自行合并文件;主 agent 按策略落盘、处理实现侧决策、完成验收
**职责划分**:
| 角色 | 职责 |
| ------- | ----------------------------------- |
| 主 agent | 按策略落盘合并结果、处理实现侧冲突决策、验收 |
| 子 agent | 仅做冲突扫描与分类,按五字段 schema 交付对照表,不自行合并文件 |
---
### `f2s-kb-migrate`
**作用**:将旧版知识库(`docs-index.md` + `rules/` 模式)按主题迁移到 `.Knowledge/` 结构。
**工作原理**:以旧版 `docs-index.md` 和 `rules/main.md(c)` 为「索引线索」,递归识别所有被引用的业务规则和技能文件,按主题粒度重新组织到 `.Knowledge/` 的 `topics/stock-docs/req-docs` 三层结构中。迁移完成后落盘 `migration-report.md`(对照表 + 拟删路径),待用户确认后清理旧文件。本质是一次性的结构重组,将分散的规则/文档归并为统一知识库。
**使用场景**:
- 旧项目升级到 Flow2Spec 新版
- 存量知识库需要结构化整理
**关联关系**:
- **前置**:旧版知识库(`docs-index.md`、`rules/`、`skills/`)
- **后续**:`f2s-kb-upgrade`(**流程 V1** 旧库须先 migrate 再 upgrade;**现行库 V2+**(含 npm v3.x)见 upgrade 技能步骤 0)
- **流程**:
1. 以 `docs-index.md` + `rules/main.md(c)` 为主索引
2. 全量处理业务 `rules/` 与业务 `skills/`(排除 `f2s-`* 包技能)
3. 全量迁移 `stock-docs`/`req-docs`
4. 落盘 `.Knowledge/migration-report.md`
5. 用户确认后删除已迁旧的文件
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内逐主题迁移
- `subAgent: true`:子只做搬运 + migration-report 草案片段(以 patch 形式交付);状态文件(migration-report.md、删除执行记录)由主 agent 唯一落盘;主 agent 主导删除清单确认与删除闭环
**职责划分**:
| 角色 | 职责 |
| ------- | --------------------------------------------- |
| 主 agent | 制定迁移规划、合并迁移结果、落盘 migration-report、主导删除确认与执行闭环 |
| 子 agent | 负责指定主题的搬运与草案片段生成(patch 形式),不写状态文件、不写删除执行记录 |
**交叉验证(`switchAgentVerification: true` 时)**:
- 子 agent 迁移落盘的主题 → 主 agent 校验迁移完整性(旧路径是否全量覆盖、主题边界是否重叠)
- 仅当 `subAgent: true` 且实际拆出子任务时生效;否则全部在主 agent 内验证
---
### `f2s-kb-upgrade`
**作用**:知识库模板升级。对齐 manifest-routing + matchers 分片。
**工作原理**:通过「版本分流 + init 代跑」实现升级——先检测当前知识库属于 V1(旧结构,需先 migrate)还是 V2+(已有 `.Knowledge`),V1 走 migrate 后再 init,V2+ 直接代跑 `flow2spec init` 进行包级结构增量对齐(补齐新模板、升级 manifest schema、对齐 matchers 分片格式)。升级后重读 SKILL.md 判断是否需要重跑某些步骤。与单独 `init` 的区别:`kb-upgrade` 包含版本判断和重跑逻辑,`init` 仅做一次性结构补齐。
**使用场景**:
- flow2spec 包版本升级后,升级项目知识库模板
- 旧项目升级到最新结构
**关联关系**:
- **前置**:`f2s-kb-migrate`(V1 流程)或已存在的 `.Knowledge/`
- **包含**:内部会调用 `flow2spec init` 进行结构对齐
- **注意**:单独的 `flow2spec init` **不是**升级命令
**流程差异**(技能内分流代号,**不等于** npm 包主版本号):
- **V1**:先 `f2s-kb-migrate` 再代跑 `flow2spec init`
- **现行库(V2+)**:已稳定 `.Knowledge` + `manifest-routing` 时,代跑 `flow2spec init` 以对齐 manifest-routing + matchers 分片(**含 Flow2Spec npm v3.x 等**,详见 `skills/f2s-kb-upgrade/SKILL.md` 步骤 0)
**子 agent 调用**:
- `subAgent: false`(默认):主 agent 内完成升级
- `subAgent: true`:子 agent 仅承接 shell 命令执行(代跑 `flow2spec init`),不承担知识库正文落盘;以下步骤主 agent 不可下放:版本分流(V1 / 现行库 V2+)、init 后重读 SKILL.md 并判断是否整技能重跑、步骤 3b index.md 融合、校验摘要输出
**职责划分**:
| 角色 | 职责 |
| ------- | ----------------------------------------------------------------------------- |
| 主 agent | 版本分流、init 后重读并判断重跑、步骤 3b index.md 融合、校验摘要;落盘 manifest-routing.json 和 index.md |
| 子 agent | 仅代跑 `flow2spec init` 等 shell 命令,不落盘知识库内容 |
**交叉验证**:本技能不绑定交叉校验,落盘侧自验。
---
## 5) 规则说明
以下不是技能命令,而是通过触发词激活的规则,用于辅助指导 Agent 的行为。
### `f2s-karpathy-guidelines`
**触发词**:`alwaysApply`(始终生效,无需显式触发)
**作用**:Flow2Spec 内置的 Karpathy 式编码行为准则,约束 Agent 的编码决策质量。
**工作原理**:从 Andrej Karpathy 对 LLM 写代码常见失误的观察中提炼四条行为约束,作为 `alwaysApply` 规则在所有 `f2s-*` 技能执行时隐式生效:① 先想清楚再写代码(假设要说清楚,不确定就问);② 简单优先(用最少代码解决问题);③ 手术式修改(只动该动的,风格对齐现有代码);④ 目标驱动执行(先定义可验证的成功标准再循环迭代)。当这些准则与 `f2s-*` 强制步骤冲突时,以 `f2s-*` 为准。
---
### `f2s-task`
**触发词**:changeTracking、变更追踪、任务追踪、续作、继续上次任务
**作用**:变更追踪规则(`alwaysApply`)。当对应技能的 `changeTracking.`* 为 `true` 时,在技能执行前后自动创建、逐步更新、最终归档 `.task/` 下的任务清单,支持跨会话续作。
**工作原理**:基于「磁盘 checkpoint + 关键词匹配」实现跨会话状态持久化——每个活跃任务在 `.task/active/<name>/task.md` 中以 checkbox 记录进度(`[ ]`/`[x]`),`todo.json` 作为活跃任务索引。新会话开始时,规则自动将用户首条消息与各任务的 `keywords` 做模糊匹配:命中则加载 `task.md` 剩余步骤和 `linkedSkill` 对应的技能文件,恢复完整执行上下文。任务完成后移入 `completed/` 归档。核心设计:以文件系统而非对话记忆作为状态真值,对话中断不丢进度。
**生效范围**:
| 配置项 | 对应技能 |
| -------------------------- | --------------------------- |
| `changeTracking.feat` | `f2s-kb-feat` |
| `changeTracking.fix` | `f2s-kb-fix` |
| `changeTracking.implement` | `f2s-implement-tech-design` |
**跨会话续作**:新会话开始时若存在 `.task/todo.json`,自动将用户首条消息与各任务 `keywords` 匹配;命中则加载对应 `task.md` 及 `linkedSkill` 技能文件,展示剩余清单,提示是否继续;无命中则不打扰。
**规则位置**:`配置根/rules/f2s-task.`*
---
### `stock-docs-vs-req-docs`
**触发词**:stock-docs、req-docs、已落地能力、技术方案放哪、PDF 终稿
**作用**:区分知识沉淀目录与需求实现目录的边界。
**工作原理**:通过「用途隔离」避免文档混放——`stock-docs/` 存放已沉淀的存量知识(架构、终稿),由 `ctx-build` 消费入库,禁止直接用于编码;`req-docs/` 存放面向实现的需求与技术方案,由 `implement-tech-design` 规则消费驱动编码。两目录的写入者和消费者完全隔离,防止「存量描述被当编码依据」或「实现方案被当能力沉淀」的混淆。
**目录分工**:
| 目录 | 用途 | 写入时机 |
| ------------- | ------------- | ---------------------------------------------- |
| `stock-docs/` | 存量沉淀(架构、终稿) | `f2s-doc-arch`、`f2s-doc-final`、`f2s-ctx-build` |
| `req-docs/` | 需求与技术方案(驱动实现) | `f2s-req-backend`、`f2s-doc-pdf`、手动放置 |
**使用场景**:
- 不确定文档应该放哪里
- 需要明确 stock-docs 与 req-docs 的分工
---
### `implement-tech-design`
**触发词**:按技术方案实现、implement-tech-design、根据方案实现
**作用**:根据 `req-docs/` 中的技术方案文档实现可运行代码。
**工作原理**:以「方案即合约」为核心约束——Agent 以 `req-docs/` 中的技术方案为唯一编码依据,按「理解方案→输出任务列表→提问确认→逐步实现→输出待完成列表」的强制六步流水线执行。任务列表和实现前提问是不可跳过的门禁,确保不会在理解偏差的情况下动手编码。与 `f2s-req-plan` 的区别:本规则是轻量单线程编码驱动,不强制创建 `.task/` 追踪(除非 `changeTracking.implement: true`)。
**变更追踪**:若 `changeTracking.implement: true`,在步骤 2.5 输出任务列表后同步写入 `.task/active/<task-name>/task.md`;步骤 5 收尾时归档任务。
**使用场景**:
- 技术方案已就绪,需要按方案编码
- 方案变更后需要同步更新代码
**关联关系**:
- **前置**:`.Knowledge/req-docs/<技术方案>.md`(通过 `f2s-req-backend` 或手动放置)
- **规则位置**:
- Cursor:`.cursor/rules/f2s-implement-tech-design.mdc`
- Claude:`.claude/rules/f2s-implement-tech-design.md`
- Codex:`.codex/AGENTS.md` + `.codex/topics/f2s-implement-tech-design.md`
**执行流程**(规则强制):
1. 输入标准化
2. 理解方案与上下文
3. **输出实现任务列表**(必做,不可跳过)
4. **实现前提问**(必做,不可跳过)
5. 按任务列表实现
6. **输出待完成列表与实现后提醒**(必做)
**子 agent 调用**:无(规则驱动编码,主 agent 内完成全流程)
---
## 6) 子 Agent 配置说明
通过项目根 `flow2spec.config.json` 控制(字段默认均为 `false`)。
### 多端如何「看到」配置(与下文字段表配合)
`subAgent` 等写在 **磁盘 JSON**;各产品不保证自动打开文件,故用 **Cursor 规则 / Claude hook / Codex AGENTS 快照表 / 知识库 `config-precheck` 摘要** 多层提示,**权威仍为 Read(`flow2spec.config.json`)**(设计意图见 [Flow2Spec-设计说明 § 四、5.1](./Flow2Spec-设计说明.md),演讲口径见 [Flow2Spec-演讲稿 Slide 13b](./Flow2Spec-演讲稿.md))。**完整路径与表格只维护一处**:[Flow2Spec使用说明 § 一、`f2s-`* 与 `flow2spec.config.json](./Flow2Spec使用说明.md)`。
### `subAgent` 字段
| 取值 | 行为 |
| ----------- | ------------------------------ |
| `false`(默认) | 所有 `f2s-*` 技能在主 agent 内完成 |
| `true` | 部分技能可按正文约定使用子 agent(大规模并行处理场景) |
### `switchAgentVerification` 字段
| 取值 | 行为 |
| ----------- | --------------------------------------------------------------------------------------------- |
| `false`(默认) | 落盘侧自验:谁落盘谁验 |
| `true` | 技能正文明确写出该步骤时,启用交叉校验:子 agent 落盘 → 主 agent 验;主 agent 落盘 → 子 agent 验(须 `subAgent: true` 且已拆出子任务) |
### `changeTracking` 字段
嵌套对象,各技能子项独立控制:
```json
{
"changeTracking": {
"feat": false,
"fix": false,
"implement": false
}
}
```
| 子项 | 对应技能 | 效果 |
| ----------- | --------------------------- | ----------------------- |
| `feat` | `f2s-kb-feat` | 执行前创建任务清单,完成后归档,支持跨会话续作 |
| `fix` | `f2s-kb-fix` | 同上 |
| `implement` | `f2s-implement-tech-design` | 同上 |
> `f2s-req-plan` 不受此配置约束,始终创建任务清单。旧版布尔值(`"changeTracking": true/false`)向下兼容,自动展开为三项全开/全关。
完整原则与设计意图见 [README-体系与原理 § 4. Agent 执行模型](./README-体系与原理.md)。
---
## 7) 快速参考
典型工作场景与完整链路见 [Flow2Spec使用说明 § 三、典型工作场景](./Flow2Spec使用说明.md)。
目录完整说明见 [README-目录与路径约定](./README-目录与路径约定.md)。
---
相关文档:
- [Flow2Spec使用说明](./Flow2Spec使用说明.md)
- [README-目录与路径约定](./README-目录与路径约定.md)
- [README-体系与原理](./README-体系与原理.md)
- [Flow2Spec-使用案例-模拟对话](./Flow2Spec-使用案例-模拟对话.md)
# 目录与路径约定
## 核心边界
- `.Knowledge/`:只放业务知识文档与索引
- `配置根`(`.cursor/.claude/.codex`):放规则与技能入口
---
## 目录职责
| 路径 | 职责 |
| --- | --- |
| `.Knowledge/stock-docs/` | 架构、终稿、沉淀文档 |
| `.Knowledge/req-docs/` | 需求澄清、技术方案 |
| `.Knowledge/topics/` | 主题路由文档(用于规则与流程执行) |
| `.Knowledge/template/` | 终稿/技术方案模板 |
| `.Knowledge/index.md` | 人类可读索引 |
| `.Knowledge/manifest-routing.json` | 机器可读路由骨架(task/topic/dependencies) |
| `.Knowledge/matchers/*.json` | 关键词分片(`id/includeAny`),由 `manifest-routing.taskToTopicRules[].matcherPath` 直链指向 |
| `.Knowledge/migration-report.md` | `f2s-kb-migrate` 落盘的迁移对照表与拟删除路径列表 |
| `.task/` | 变更追踪任务清单目录(`active/` 进行中,`completed/` 已归档且目录名为 **`<YYYYMMDD>-<task-name>`**(日期在前),`todo.json` 活跃任务索引);仅当 `changeTracking.*` 为 `true` 或显式调用 `f2s-req-plan` 时创建 |
| `配置根/rules/` | 规则文件(Cursor `.mdc`,Claude `.md`) |
| `配置根/skills/` | 技能定义(`SKILL.md`) |
| `配置根/template/` | (废弃)不再写入;历史目录可清理 |
| `.codex/AGENTS.md` | Codex 统一入口与加载说明 |
| `flow2spec.config.json` | 项目根配置,控制 `subAgent`、`switchAgentVerification`、`changeTracking`(嵌套对象,含 `feat` / `fix` / `implement` 三个子项) |
> 多端提示与路径表见 [Flow2Spec使用说明 § 一](./Flow2Spec使用说明.md)(详表单点维护);**权威仍为 Read(`flow2spec.config.json`)**。
---
## 路径约束
1. `.Knowledge/topics` 是知识路由主题层,允许并鼓励通过 `f2s-*` 技能维护。
2. `f2s-ctx-build` 从 `.Knowledge/stock-docs` 读,更新 `.Knowledge/topics`、`.Knowledge/index.md`、`.Knowledge/manifest-routing.json`、`.Knowledge/matchers/*.json`。
3. 实现类任务统一读取 `.Knowledge/req-docs/*.md`。
4. `manifest-routing.json` 与 `matchers/*.json` 由 `f2s-*` 技能流程维护;不再使用 `.Knowledge/manifest-matchers.json`(`flow2spec init` 会删除遗留文件)。
---
## 相关文档
- [Flow2Spec使用说明](./Flow2Spec使用说明.md)
- [README-命令说明](./README-命令说明.md)
- [README-体系与原理](./README-体系与原理.md)
- [Flow2Spec-使用案例-模拟对话](./Flow2Spec-使用案例-模拟对话.md)
[中文](./Flow2Spec使用说明.md) | [English](./usage-guide.en.md)
# Flow2Spec Usage Guide
## 1. What `init` Does
Execute in the project root:
```bash
flow2spec init [cursor|claude|codex ...]
# To force reset .Knowledge from template:
flow2spec init [cursor|claude|codex ...] --reset-knowledge
```
| What `init` does | What `init` does NOT do |
|---------|----------|
| Fills in missing directories and template files | Write or update business document content |
| Writes agent config root `rules/` `skills/` | Update `includeAny` business terms |
| Aligns `manifest-routing` + `matchers/` package-level structure | Replace `f2s-*` skills for writing business semantics |
| Overwrites `.Knowledge` template files with `--reset-knowledge` | Override existing `.Knowledge` content (without this flag) |
> **`init` and "knowledge base upgrade" are two different things**: `init` only handles structural alignment — business semantics (topics content, routing terms, stock-docs/req-docs) are maintained by skills like `f2s-doc-add`, `f2s-kb-fix`, `f2s-kb-feat`, `f2s-kb-sync`, `f2s-ctx-build`, etc. For cross-version upgrades, use `f2s-kb-upgrade`. **Do not treat a standalone `init` as an upgrade command.**
### `f2s-*` and `flow2spec.config.json`: Multi-Client, Multi-Layered Reminders (Authority Remains the Disk JSON)
Before executing any **`f2s-*` skill**, the Agent needs to obtain the actual values of **`subAgent` / `switchAgentVerification` / `changeTracking`**, etc. Flow2Spec enforces this via **different mechanisms** on **different clients**; they **complement** each other and do **not** replace one another. **Authority always** resides in the project root **`flow2spec.config.json`** (call **Read** to verify against disk before proceeding into skill body).
| Client | `init` Output & Behavior | Description |
| --- | --- | --- |
| **Cursor** | `.cursor/rules/f2s-config-check.mdc` (`alwaysApply`) | Rule requires: **Read(`flow2spec.config.json`)** before entering skill body. |
| **Claude Code** | `.claude/hooks/f2s-config-inject.js` + `.claude/settings.json` (PreToolUse, `Skill` matching) | Injects a config summary when invoking **`f2s-*` Skill**; when **file is missing, JSON is invalid, or hook throws an unexpected exception**, it also injects a **notice + default semantics consistent with "file not found"** to avoid silent failure; it is still recommended to **Read** for confirmation when in doubt or after config changes. |
| **Codex** | `.codex/AGENTS.md` top-level mandatory step + `{{FLOW2SPEC_PROJECT_CONFIG}}` expansion table | **Read** is a hard requirement; the config table is a **snapshot from the last `flow2spec init`** — when it differs from disk, **Read** takes precedence. The adjacent **`.codex/topics/f2s-config-check.md`** shares its origin with the Cursor rule (including the **changeTracking** detail table); open it **as needed** — it does not need to be grouped with the three "topic long-form" examples as required reading. |
| **Knowledge Base (optional)** | When `.Knowledge/manifest-routing` hits **`config-precheck`** | `.Knowledge/topics/f2s-config-precheck.md` is a **routing summary** that links to the Codex long-form article; Flow2Spec does **not** maintain a second full copy in `.Knowledge`, nor does it replace a `Read` of the JSON. |
For field semantics and default value rules, see [Commands Reference § 6) Sub-Agent Configuration](./commands-reference.en.md). For the design perspective, see [Design Principles § 4.5.1](./design-principles.en.md).
---
## 2. Directory Conventions
Core distinction: `stock-docs/` holds solidified documents (driving knowledge routing), `req-docs/` holds technical designs (driving coding implementation); they are not interchangeable.
See [Directory Conventions](./directory-conventions.en.md) for the full directory description.
---
## 3. Typical Workflows
### Requirements Planning and Implementation
```
f2s-req-plan
```
Provide a path to the technical design document or a requirements description. A draft task checklist is produced first and awaits confirmation. After confirmation, implementation proceeds according to the checklist. A `.task/` task checklist is always created — no `changeTracking` configuration is needed. Suitable for scenarios where you want to see the full picture before starting, or need cross-session progress tracking.
### Change Tracking and Cross-Session Continuation
```
# Automatic mode: enabled by config (independent per skill)
flow2spec.config.json → changeTracking.feat / fix / implement: true
# Explicit mode: call f2s-req-plan (planning + implementation, no config dependency)
f2s-req-plan
```
**Automatic mode**: When enabled, `f2s-kb-feat` / `f2s-kb-fix` / `f2s-implement-tech-design` automatically create a task checklist under `.task/active/`, check off steps progressively, and archive upon completion. In subsequent sessions, when describing related content, the `f2s-task` rule automatically matches and loads the remaining checklist — no need to re-explain the context.
**Explicit mode**: Call `f2s-req-plan` directly — regardless of the `changeTracking` configuration, a task checklist is always created and code is implemented against it. Suitable for scenarios where you want to confirm the full picture before taking action.
### New Feature Development
```
f2s-req-clarify → f2s-req-backend → implement-tech-design → f2s-kb-feat
```
When requirements are already clear, `f2s-req-clarify` can be skipped, starting directly from `f2s-req-backend`. After the technical design is written into `req-docs/`, the `implement-tech-design` rule drives coding.
### Document Ingestion
```
New architecture document ingestion: f2s-doc-arch → f2s-doc-final → f2s-ctx-build
PDF document ingestion: f2s-doc-pdf → f2s-doc-final → f2s-ctx-build
```
Integrate architecture descriptions or PDF technical designs into the knowledge routing (generates topics/matchers/manifest-routing).
### PDF-Based Implementation
```
f2s-doc-pdf → implement-tech-design
```
Convert a PDF technical design to Markdown and place it in `req-docs/`, then let the `implement-tech-design` rule drive coding.
### Backfilling Existing Capabilities
```
f2s-doc-add # Aggregate multiple files, extract from source code / documents
f2s-kb-sync # Infer already-implemented capabilities from current session
```
Use these when code has already been shipped but the knowledge base has no record. `f2s-doc-add` is suitable for batch imports; `f2s-kb-sync` is suitable for real-time consolidation at the end of a session.
### Routine Maintenance
```
f2s-kb-fix # Fix implementation or rule errors, auto-sync knowledge base
f2s-kb-feat # Add new capabilities, auto-sync knowledge base
f2s-kb-sync # Periodic sync or backfill
f2s-kb-merge # Resolve context conflicts after Git merges
```
### Cross-Version Knowledge Base Upgrade
```
f2s-kb-migrate (Legacy V1: old knowledge base) → f2s-kb-upgrade
f2s-kb-upgrade (Current V2+: already has .Knowledge; includes npm v3.x projects, etc.; see skill step 0)
```
---
## 4. Agent Execution Configuration
Controlled via the project root `flow2spec.config.json`. For complete field rules, see [Commands Reference § 6) Sub-Agent Configuration](./commands-reference.en.md). **How each client is reminded to read the config, and why `Read` remains authoritative** — see **§ 1** (this § only explains **when** to toggle each switch).
**When to enable `subAgent: true`**: When the task is large (multi-module parallel implementation, batch document ingestion, large-scale migration). When enabled, each skill decides whether to actually split based on its own size threshold; tasks below the threshold are still completed within the main agent.
**When to enable `switchAgentVerification: true`**: When higher write consistency is needed (large-scale migration, critical design implementation). The trade-off is increased execution rounds; for routine maintenance, the default `false` is sufficient. Requires `subAgent: true` to trigger the "main-writes, sub-verifies" cross-check direction.
**When to enable `changeTracking.*`**: When you want each skill execution to automatically leave a resumable task checklist. Each skill sub-item is independently configurable without mutual interference:
```json
{
"changeTracking": {
"feat": true,
"fix": false,
"implement": true
}
}
```
If you prefer not to rely on configuration and want to explicitly plan tasks on demand, use `f2s-req-plan` directly.
---
## 5. Customization Suggestions
- When customizing the "implement from technical design" logic for your project, prioritize adjusting **`f2s-implement-tech-design`**: Cursor `.cursor/rules/f2s-implement-tech-design.mdc`, Claude `.claude/rules/f2s-implement-tech-design.md`; Codex uses `.codex/AGENTS.md` and associated `skills/` as the source of truth.
- Running `init` again by default only fills in missing templates and performs package-level structural alignment — it does **not** replace `f2s-*` skills for maintaining business content. To reset `.Knowledge` from the template, add `--reset-knowledge`.
---
## 6. Skill Identification
Skills are triggered by matching `name` and `description`. Files are located under `config-root/skills/*/SKILL.md`.
---
## 7. Related Documents
- [Commands Reference](./commands-reference.en.md)
- [Directory Conventions](./directory-conventions.en.md)
- [Architecture](./architecture.en.md)
- [Usage Scenarios](./usage-scenarios.en.md)
[中文](./Flow2Spec-使用案例-模拟对话.md) | [English](./usage-scenarios.en.md)
# Flow2Spec Usage Scenarios (Simulated Dialogues)
The following examples revolve around the same e-commerce project, covering the full pipeline from requirements clarification through post-launch maintenance.
**Prerequisite**: The project has executed `flow2spec init`, and `flow2spec.config.json` uses the default configuration (`subAgent: false`). `f2s-*` skills do not modify the configuration root `rules/` or `skills/` files.
---
## Scenario 1: New Requirement -> Clarification -> Technical Design
**You**
> /f2s-req-clarify The product team provided a refund requirement doc, but it does not specify whether partial refunds and full refunds go through the same API, or whether points should be reversed after a successful refund. The document is at `.Knowledge/req-docs/refund-requirements-v1.md`.
**Agent**
> I have read the requirements document. There are a few points that need clarification:
>
> 1. Do partial refunds and full refunds reuse the same endpoint, differentiated by the `amount` field, or should they be two separate endpoints?
> 2. Should points be reversed after a successful refund? If the reversal fails, should it block the refund flow?
> 3. Is the refund processed synchronously or asynchronously (T+1)?
> 4. Is there a seller-side review step?
**You**
> 1. Same endpoint, differentiated by amount; 2. Points are reversed; failure does not block the flow, retry asynchronously; 3. Asynchronous T+1; 4. No review needed.
**Agent**
> Clarification complete. Run `/f2s-req-backend` to produce the technical design.
**You**
> /f2s-req-backend
**Agent**
> Generated `.Knowledge/req-docs/refund-tech-design.md`, which includes:
> - API design: `POST /refunds`, `amount` field distinguishes full / partial refunds
> - State machine: `PENDING -> SUCCESS / FAILED`
> - Points reversal: asynchronous queue, failures go to dead letter queue, alert for manual handling
> - Error code list
>
> Next step: say "implement according to `.Knowledge/req-docs/refund-tech-design.md`" to trigger coding.
---
## Scenario 2: Architectural Documentation into Knowledge Base
**You**
> /f2s-doc-arch Help me draft an order service architecture document, focusing on the creation flow, payment callback, idempotency, and message delivery. The code is in `src/order` and `src/payment`.
**Agent**
> Scanned the relevant directories. Generated `.Knowledge/stock-docs/order-service-architecture-draft.md`, which includes:
> - Module boundaries and dependencies
> - Creation flow sequence diagram
> - Payment callback idempotency mechanism (based on the `payment_callback_log` table)
> - Message delivery retry strategy
>
> Confirm it looks good, then run `/f2s-doc-final` to normalize the format.
**You**
> /f2s-doc-final .Knowledge/stock-docs/order-service-architecture-draft.md
**Agent**
> Generated `.Knowledge/stock-docs/order-service-architecture-final.md`, formatted according to the final-draft template, with placeholders for items still to be filled in.
**You**
> f2s-ctx-build .Knowledge/stock-docs/order-service-architecture-final.md
**Agent**
> Knowledge base sync complete:
> - Added `.Knowledge/topics/order-service.md`
> - Updated `.Knowledge/manifest-routing.json` (added routing rule)
> - Generated `.Knowledge/matchers/order-service.json` (keywords: order creation, payment callback, idempotency, message delivery)
> - Updated `.Knowledge/index.md`
>
> Future tasks related to the order service will automatically hit this topic.
---
## Scenario 3: Implementation from Technical Design
**You**
> Implement according to `.Knowledge/req-docs/refund-tech-design.md`. Only modify `src/refund/`; do not touch the payment module.
**Agent**
> I have read the design document. Task list for implementation:
>
> 1. Create `RefundController` with `POST /refunds`
> 2. Create `RefundService` with state machine transition logic
> 3. Create `RefundRepository` for the `refund` table
> 4. Create `PointRollbackProducer` to send rollback messages to the points queue
> 5. Unit tests covering state machine transitions
>
> Before proceeding, I need to confirm:
> - Does the `refund` table already exist, or do I need to generate a migration?
> - What is the points queue topic name?
**You**
> The table already exists; no migration needed. The topic is `point-rollback-events`.
**Agent**
> Completed all 5 tasks above, all within `src/refund/`. Did not touch `src/payment/`.
>
> **Requires manual action**:
> - Consumer side for `point-rollback-events` (on the points service side)
> - Dead letter monitoring and alerting rule configuration
>
> Recommend running `/f2s-kb-feat` to sync this new capability into the knowledge base.
---
## Scenario 4: PDF Design -> Implementation
**You**
> /f2s-doc-pdf /Users/me/Downloads/marketing-coupon-v2.pdf
**Agent**
> Converted and saved as `.Knowledge/req-docs/marketing-coupon-v2.md`. Filled in the idempotency handling flow description and error code explanations that were missing in the PDF.
**You**
> Implement according to `.Knowledge/req-docs/marketing-coupon-v2.md`
**Agent**
> I have read the design document. Task list for implementation:
>
> 1. Create `CouponController` (coupon claim, redemption, and return endpoints)
> 2. Create `CouponService` with inventory deduction and idempotency checks
> 3. ...
>
> Before proceeding, I need to confirm: is the coupon inventory managed via Redis or database row locks?
---
## Scenario 5: Post-Implementation Knowledge Base Recording
**You**
> /f2s-kb-sync The refund feature has gone live. Help me record the payment failure retry queue naming, dead letter table fields, and monitoring alerting criteria into the knowledge base. Give me an outline first so I can confirm before you write.
**Agent**
> Knowledge base update outline (pending confirmation):
>
> **Update topic**: `order-service` (already exists)
>
> - Add "Payment Failure Retry Mechanism": queue name `payment-retry-queue`, max retries 3, intervals 30s / 120s / 300s
> - Add "Dead Letter Table": table name `payment_dead_letter`, fields `order_id / error_code / retry_count / created_at`
> - Add "Monitoring Criteria": alert threshold `retry_count >= 3`, notification channel DingTalk
>
> Confirm to write, or let me know what needs to be changed.
**You**
> Confirm, go ahead and write.
**Agent**
> Updated `.Knowledge/topics/order-service.md`. `manifest-routing` unchanged (topic already exists).
---
## Scenario 6: Non-compliant Implementation Found, Fix and Sync Knowledge Base
**You**
> /f2s-kb-fix `RefundService` directly calls `new RestTemplate()`, which violates the Spring Bean injection convention.
**Agent**
> Fixed: Line 34 of `RefundService.java` changed to constructor injection; `RefundConfig` supplemented with `@Bean` declaration.
>
> Knowledge base synced: the "HTTP Client Conventions" section in `.Knowledge/stock-docs/` has been updated, noting that `RestTemplate` must be injected as a Bean, and direct instantiation is prohibited.
---
## Scenario 7: Knowledge Base Conflicts After Git Merge
**You**
> /f2s-kb-merge `.Knowledge/index.md` and `.Knowledge/stock-docs/order-service-architecture-final.md` have conflict markers after the merge. I have already resolved the conflicts in the business code manually.
**Agent**
> Scanned the conflict markers in both files:
>
> - `index.md`: 2 conflicts, both in topic description fields. Took the HEAD version (newer content). Resolved automatically.
> - `order-service-architecture-final.md`: 1 conflict. The "monitoring alert threshold" differs between branches (3 vs. 5). Please confirm which one to keep.
**You**
> Use 3.
**Agent**
> All conflict markers have been cleaned up per your confirmation. The files are ready to commit.
---
## Related Documentation
- [Usage Guide](./usage-guide.en.md)
- [Commands Reference](./commands-reference.en.md)
- [Directory Conventions](./directory-conventions.en.md)
- [Architecture](./architecture.en.md)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet