🎩 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.8
to
3.0.9
+122
docs/architecture.en.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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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.
**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-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.
**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.
**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/`.
**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 at [design-principles.en.md Sec. 4.5.1](./design-principles.en.md)). **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
```mermaid
graph LR
K[".Knowledge/"] --> AI["Next Session\nAI"]
AI --> C["Code\nChanges"]
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-tech-design"] -->|f2s-kb-feat| K
GIT["After Git Merge"] -->|f2s-kb-merge| K
```
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使用说明.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)
# Flow2Spec — Let AI Always Know What You're Doing
> Cures the "amnesia" of Cursor / Claude Code — with one `init` command, AI
> remembers project context across sessions. No more re-explaining every time.
>
> 🌐 **[中文](./README.md)** · 中 / EN
🎬 **[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)
🔧 **Quick start**:
```bash
npx @double-codeing/flow2spec@latest init
```
---
## Before / After
The exact same request, two conversations:
```
> Update the batch re-scoring of the review template library
```
**Without Flow2Spec**:
```
AI: Which module has this table?
AI: Is batchReScore sync or async?
AI: Is there a lock? What's the idempotency key?
AI: What's the response format? What's the error code?
AI: (Digging through 416 APIs, 796 files, 4.7 MB of source code…)
```
Repeated introductions · Repeated code searches · Repeated mistakes
**With Flow2Spec**:
```
[matcher hit] m-product-review-template-library
[loading deps] 4 topics · ~300 lines
AI: Known — fire-and-forget
Redis lock smp:product-review:template-library:batch-rescore:lock (TTL 10 min)
Max 100 items per batch · error code 101
AI: Starting implementation, 3 files affected.
```
4.7 MB → 300 lines · Pinpoint accuracy in seconds
---
## What Flow2Spec Does (3 Things)
**① Remembers project context across devices and sessions**
`.Knowledge/` structured knowledge base: routing manifest (`manifest-routing.json`) + keyword indices (matchers) + topic shards (topics). AI only loads what's relevant.
**② Routing manifest means AI doesn't dig through your repo**
Each task hits 1–4 topics, ~300 lines. Business constraints — Redis lock keys, error codes, batch limits — are all in the topics. AI doesn't have to guess from source code.
**③ f2s-* skills update knowledge as you code**
`/f2s-kb-feat` writes topics while writing features, `/f2s-kb-fix` corrects topics while fixing bugs, `/f2s-git-commit` checks topic coverage before committing. Changing code == updating knowledge. No separate "documentation maintenance."
---
## Getting Started
**Minimum viable setup is an empty skeleton.**
```bash
npx @double-codeing/flow2spec@latest init
```
1 minute generates the directory structure + routing config. Empty, ready to use. **Next requirement hits whichever area → you document that area.** No upfront investment needed.
Real data from a production repo running for 3 months:
| Metric | Value |
|---|---|
| Public APIs | 416 |
| Source code | 796 files / 4.7 MB / ~100K lines |
| Flow2Spec per-task load | **≈ 300 lines** (99% noise removed) |
---
## When NOT to Use
- **One-off scripts** — throwaway code is faster with a few Markdown files for AI context
- **Solo small projects** — a single CLAUDE.md is enough; routing overhead > benefits
- **Team won't maintain .Knowledge/** — tools can't replace discipline
---
## Documentation
### 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)
### 中文
- [使用说明](./docs/Flow2Spec使用说明.md)
- [命令说明](./docs/README-命令说明.md)
- [目录与路径约定](./docs/README-目录与路径约定.md)
- [体系与原理](./docs/README-体系与原理.md)
- [使用案例·模拟对话](./docs/Flow2Spec-使用案例-模拟对话.md)
- [设计说明](./docs/Flow2Spec-设计说明.md)
## License
MIT. Copyright © 2026 兰涛
+1
-1
{
"name": "@double-codeing/flow2spec",
"version": "3.0.8",
"version": "3.0.9",
"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",

+78
-80

@@ -1,117 +0,115 @@

# Flow2Spec
# Flow2Spec — 让 AI 一直知道你在做什么
Flow2Spec 用于在业务仓库初始化一套可持续的 AI 协作结构:
> 解决 Cursor / Claude Code 的「失忆症」——用一个命令初始化,让 AI
> 跨会话记住项目上下文,不用每轮重新交代。
>
> 🌐 **[English](./README.en.md)** · 中 / EN
- **业务知识文档**统一在 `.Knowledge/`
- **规则与技能能力**保留在各 agent 配置根(`.cursor/`、`.claude/`、`.codex/`)
🎬 **[在线演示(中文)](https://lands-1203.github.io/Flow2Spec/)** | **[English Demo](https://lands-1203.github.io/Flow2Spec/en/)**(13 页 HTML PPT,`←` `→` 翻页,`S` 演讲者模式)
集中管理项目知识,同时不破坏各工具原生的 rules/skills 加载机制。
🔧 **快速体验**:
> 🎬 **在线演示**:组内分享用的 13 页 HTML PPT(脱敏版)——**<https://lands-1203.github.io/Flow2Spec/>**
> `←` `→` 翻页,`S` 打开演讲者模式。源文件见 [presentations/flow2spec-intro-public/](./presentations/flow2spec-intro-public/)。
```bash
npx @double-codeing/flow2spec@latest init
```
---
## 快速开始
## Before / After
```bash
npx @double-codeing/flow2spec@latest init
npx @double-codeing/flow2spec@latest init cursor claude codex
同样一句话,两段对话:
```
> 改一下评价模板文案库的批量重评分
```
可选:全局安装 CLI 后,可在仓库根直接使用 `flow2spec init …`(与上文等价):
**没有 Flow2Spec**:
```bash
npm install -g @double-codeing/flow2spec@latest
```
AI: 这个模块的表在哪?
AI: batchReScore 是同步还是异步?
AI: 有没有锁?幂等键是什么?
AI: 返回格式是什么?错误码是多少?
AI: (翻遍 416 个接口、796 份文件、4.7 MB 源码…)
```
反复介绍 · 反复翻代码 · 反复踩坑
`init` 完成后的目录结构:
**有 Flow2Spec**:
| 路径 | 用途 |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `.Knowledge/stock-docs/` | 架构说明、终稿等沉淀文档 |
| `.Knowledge/req-docs/` | 需求澄清与技术方案 |
| `.Knowledge/topics/` | 主题路由摘要 |
| `.Knowledge/template/` | 终稿与技术方案模板 |
| `.Knowledge/manifest-routing.json` + `matchers/` | 机器可读路由与关键词索引 |
| `配置根/rules/` + `配置根/skills/` | 各工具规则与技能入口 |
| `flow2spec.config.json` | 控制 `subAgent`、`switchAgentVerification`、`changeTracking`(各技能独立子项),默认均为 `false` |
```
[matcher 命中] m-product-review-template-library
[加载依赖] 4 个 topic · 约 300 行
AI: 已知 — fire-and-forget
Redis 锁 smp:product-review:template-library:batch-rescore:lock(TTL 10 分钟)
单次最多 100 条 · 错误码 101
AI: 开始改,预计 3 处文件。
```
4.7 MB → 300 行 · 秒级定位到硬约束
> `init` 只做结构与模板补齐,业务文档内容由 `f2s-*` 技能维护。详见 [Flow2Spec使用说明](./docs/Flow2Spec使用说明.md)。
包升级后可在业务仓库用 **`/f2s-kb-upgrade`** 对齐知识库模板与路由;细则见 [使用说明](./docs/Flow2Spec使用说明.md)。
---
## 工作流全景
## Flow2Spec 做三件事
所有技能均以 `f2s-*` 前缀或主题名在 Agent 内触发。以下按**业务场景**分组,标明推荐执行链路与前置条件。
**① 跨设备会话记住项目上下文**
`.Knowledge/` 结构化知识库:路由清单(manifest-routing.json)+ 关键词索引(matchers)+ 主题分片(topics)。AI
启动时只读该读的。
> **前置要求**:涉及「旧库迁移」或「包模板对齐」时,需先在本地安装最新 CLI:
>
> ```bash
> npm install -g @double-codeing/flow2spec@latest
> ```
>
> 其余场景以仓库内已初始化的规则与技能为准。
**② 路由清单让 AI 不翻仓库,只拿该拿的**
每次需求命中 1~4 个 topic,约 300 行。业务的硬约束——锁的 key、错误码、上限——都在
topic 里,AI 不用从源码猜。
### 一、需求交付链路
**③ f2s-* 技能改代码顺手更新知识**
`/f2s-kb-feat` 写功能时同步写 topic,`/f2s-kb-fix` 修 bug 时更正 topic,
`/f2s-git-commit` 提交前检查 topic 覆盖。改代码就是记知识,没有"单独维护文档"这件事。
从 PRD 到代码落地的完整路径。
---
> **任务清单控制**:`f2s-req-plan` **强制**创建任务清单;`f2s-implement-tech-design` 是否使用任务清单取决于 `changeTracking.implement` 配置。
## 上手成本
| 场景 | 执行链 | 产出 |
| ------------------------------ | ----------------------------------------------------------------------------------- | --------------------------------- |
| 有 PRD,需澄清后出方案并落地 | `f2s-req-clarify` → `f2s-req-backend` → `f2s-implement-tech-design` → `f2s-kb-feat` | 澄清纪要 → 技术方案 → 实现+知识库 |
| 已有方案,需强制任务清单后实现 | `f2s-req-plan`
| 可确认任务清单与实现编排 |
**最小可用集是一个空骨架。**
### 二、知识沉淀链路
```bash
npx @double-codeing/flow2spec@latest init
```
将非结构化信息(口述、草稿、外部文档、代码)转化为可检索的知识资产。
1 分钟生成目录结构 + 路由配置,空的,直接跑。**下次需求命中哪块,写哪块**,不提前建设。
| 场景 | 执行链 | 产出 |
| ----------------- | -------------------------------------------------- | ------------------------------ |
| 从口述/草稿到终稿 | `f2s-doc-arch` → `f2s-doc-final` → `f2s-ctx-build` | 架构初稿 → 规范终稿 → 主题路由 |
| 外部文档转知识库 | `f2s-doc-final` → `f2s-ctx-build` | 可检索 Markdown + 路由索引 |
| 存量代码/散稿补录 | `f2s-doc-add` 或 `f2s-kb-sync` | 自动提取能力 → 主题索引 |
真实仓库跑了三个月的数据:
### 三、日常协作
| 指标 | 数值 |
|---|---|
| 对外接口数 | 416 |
| 源码体积 | 796 文件 / 4.7 MB / ~10 万行 |
| Flow2Spec 每次加载 | **≈ 300 行**(噪声切掉 99%) |
缺陷修复、迭代与上下文同步。
---
| 场景 | 技能 |
| -------------- | -------------- |
| 修复缺陷 | `f2s-kb-fix` |
| 新增功能 | `f2s-kb-feat` |
| 同步已实现能力 | `f2s-kb-sync` |
| 解决合并冲突 | `f2s-kb-merge` |
## 什么时候别用
### 四、仓库治理
- **一次性脚本** — 写完就删的东西,直接丢几个 Markdown 给 AI 更快
- **单人小项目** — 一份 CLAUDE.md 就够,路由和分片的开销大于收益
- **团队不愿同步 .Knowledge/** — 工具不能替代纪律
一次性或周期性的结构化维护。
| 场景 | 技能 | 注意事项 |
| -------------------------------------------- | ---------------- | ------------------ |
| 旧版迁移(rules/skills 散稿 → `.Knowledge`) | `f2s-kb-migrate` | 一次性;执行前备份 |
| 模板对齐(包升级后同步) | `f2s-kb-upgrade` | 可重复执行 |
---
## 关键原则
## 详细文档
1. `.Knowledge/` 只放业务文档与索引,不放规则执行文件。
2. `rules/` `skills/` 始终在配置根,保证 Claude/Cursor/Codex 按各自方式加载。
3. Codex 不读取 `rules/` 目录,通过 `.codex/AGENTS.md` + `skills/ + .codex/topics/*.md`承载约束入口。
### 中文
- [使用说明](./docs/Flow2Spec使用说明.md) — 技能链、配置详解
- [命令说明](./docs/README-命令说明.md) — 所有 f2s-* 命令速查
- [目录与路径约定](./docs/README-目录与路径约定.md)
- [体系与原理](./docs/README-体系与原理.md)
- [使用案例·模拟对话](./docs/Flow2Spec-使用案例-模拟对话.md)
- [设计说明](./docs/Flow2Spec-设计说明.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)
## 文档导航
## 协议
- [Flow2Spec使用说明](./docs/Flow2Spec使用说明.md)
- [README-命令说明](./docs/README-命令说明.md)
- [README-目录与路径约定](./docs/README-目录与路径约定.md)
- [README-体系与原理](./docs/README-体系与原理.md)
- [Flow2Spec-使用案例-模拟对话](./docs/Flow2Spec-使用案例-模拟对话.md)
- [Flow2Spec-设计说明](./docs/Flow2Spec-设计说明.md)
MIT. Copyright © 2026 兰涛
---
name: f2s-ctx-build
description: 根据 .Knowledge/stock-docs 文档生成知识路由主题与索引;触发:生成项目上下文、f2s-ctx-build、终稿生成上下文
---

@@ -5,0 +6,0 @@ > 执行口径:本技能只维护 `.Knowledge`(`topics/index/manifest-routing/matchers` 分片),不改配置根 `rules/skills`。不再维护 `.Knowledge/manifest-matchers.json`(已废弃聚合文件;`flow2spec init` 会删除遗留副本)。