Token导航 LogoToken导航

Agent Skill · 研究检索

doc-tasks-fixer(文档任务修复程序)

用于辅助文档、README、Markdown、说明文和内容稿件的整理与改写。它适合让 Agent 提炼结构、补齐章节、统一术语、检查链接或把零散材料整理成可读文档。使用时应保留项目已有事实、命令和路径,不要把未确认的信息写成确定结论;涉及对外文案时,还需要控制语气,避免过度营销或夸大能力。

doc-tasks-fixer 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 48,496。

总安装 685周安装 28GitHub Stars 14下载 222核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:doc-tasks-fixer(文档任务修复程序)
来源仓库:https://github.com/vladm3105/aidoc-flow-framework
仓库路径:skills/doc-tasks-fixer
安装命令:
npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill doc-tasks-fixer
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill doc-tasks-fixer

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

根据审计反馈自动修复任务文档中的错误与遗漏。支持从 review 或 audit 报告中提取问题并应用修正。适用于 TASKS 文档迭代优化,维持任务清单高质量。依赖特定命名格式的审计报告文件,需规范报告生成流程。doc-tasks-fixer 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/doc-tasks-fixer

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill doc-tas…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

doc-tasks-fixer 怎么安装?

在终端执行 npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill doc-tasks-fixer。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

doc-tasks-fixer 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

doc-tasks-fixer 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill doc-tasks-fixer 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

doc-tasks-fixer 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

doc-tasks-fixer 用的人多吗?

公开数据是累计安装 685 次,近一周安装 28 次,下载 222 次,GitHub 14 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

doc-tasks-fixer 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
doc-tasks-fixer

文档任务修复程序 · 本页

68514执行命令未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

doc-tasks-fixer

Purpose

Automated fix skill that reads the latest audit/review report and applies fixes to TASKS (Implementation Tasks) documents. This skill bridges the gap between doc-tasks-reviewer / doc-tasks-audit findings and the corrected TASKS, enabling iterative improvement cycles.

Layer: 11 (TASKS Quality Improvement)

Upstream: SPEC documents, TSPEC documents, TASKS document, Audit/Review Report (TASKS-NN.A_audit_report_vNNN.md preferred; TASKS-NN.R_review_report_vNNN.md legacy-compatible)

Downstream: Fixed TASKS, Fix Report (TASKS-NN.F_fix_report_vNNN.md)


When to Use This Skill

Use doc-tasks-fixer when:

  • After Review: Run after doc-tasks-reviewer identifies issues
  • Iterative Improvement: Part of Review -> Fix -> Review cycle
  • Automated Pipeline: CI/CD integration for quality gates
  • Batch Fixes: Apply fixes to multiple TASKS based on review reports
  • Implementation Contract Issues: Contracts have incomplete or malformed structure

Do NOT use when:

  • No review report exists (run doc-tasks-reviewer first)
  • Creating new TASKS (use doc-tasks or doc-tasks-autopilot)
  • Only need validation (use doc-tasks-validator)

Skill Dependencies

SkillPurposeWhen Used
doc-tasks-reviewerSource of issues to fixInput (reads review report)
doc-namingElement ID standardsFix element IDs
doc-tasksTASKS creation rulesCreate missing sections
doc-specSPEC traceabilityValidate upstream links
doc-tspecTSPEC traceabilityValidate test links

Workflow Overview

flowchart TD
    A[Input: TASKS Path] --> B[Find Latest Review Report]
    B --> C{Review Found?}
    C -->|No| D[Run doc-tasks-reviewer First]
    C -->|Yes| E[Parse Review Report]

    E --> F[Categorize Issues]

    subgraph FixPhases["Fix Phases"]
        F --> F0[Phase 0: Fix Structure Violations]
        F0 --> G[Phase 1: Create Missing Files]
        G --> H[Phase 2: Fix Broken Links]
        H --> I[Phase 3: Fix Element IDs]
        I --> J[Phase 4: Fix Content Issues]
        J --> K[Phase 5: Update References]
        K --> K2[Phase 6: Handle Upstream Drift]
    end

    subgraph ContractFix["Implementation Contract Fixes"]
        K2 --> C1[Parse Contracts]
        C1 --> C2{Contracts Valid?}
        C2 -->|No| C3[Repair Contract Structure]
        C2 -->|Yes| C4[Validate Type Compliance]
        C3 --> C4
    end

    C4 --> L[Write Fixed TASKS]
    L --> M[Generate Fix Report]
    M --> N{Re-run Review?}
    N -->|Yes| O[Invoke doc-tasks-reviewer]
    O --> P{Score >= Threshold?}
    P -->|No, iterations < max| F
    P -->|Yes| Q[COMPLETE]
    N -->|No| Q

Fix Phases

Phase 0: Fix Structure Violations (CRITICAL)

Fixes TASKS documents that are not in nested folders. This phase runs FIRST because all subsequent phases depend on correct folder structure.

Nested Folder Rule: ALL TASKS documents MUST be in nested folders regardless of document size.

Required Structure:

TASKS TypeRequired Location
Monolithicdocs/11_TASKS/TASKS-NN_{slug}/TASKS-NN_{slug}.md

Fix Actions:

Issue CodeIssueFix Action
REV-STR001TASKS not in nested folderCreate folder, move file, update all links
REV-STR002TASKS folder name doesn't match TASKS IDRename folder to match
REV-STR003Monolithic TASKS >25KB should be sectionedFlag for manual review

Structure Fix Workflow:

def fix_tasks_structure(tasks_path: str) -> list[Fix]:
    """Fix TASKS structure violations."""
    fixes = []

    filename = os.path.basename(tasks_path)
    parent_folder = os.path.dirname(tasks_path)

    # Extract TASKS ID and slug from filename
    match = re.match(r'TASKS-(\d+)_([^/]+)\.md', filename)
    if not match:
        return []  # Cannot auto-fix invalid filename

    tasks_id = match.group(1)
    slug = match.group(2)
    expected_folder = f"TASKS-{tasks_id}_{slug}"

    # Check if already in nested folder
    if os.path.basename(parent_folder) != expected_folder:
        # Create nested folder
        new_folder = os.path.join(os.path.dirname(parent_folder), expected_folder)
        os.makedirs(new_folder, exist_ok=True)

        # Move file
        new_path = os.path.join(new_folder, filename)
        shutil.move(tasks_path, new_path)
        fixes.append(f"Moved {tasks_path} to {new_path}")

        # Update upstream links in moved file
        content = Path(new_path).read_text()
        updated_content = content.replace('../10_TSPEC/', '../../10_TSPEC/')
        updated_content = updated_content.replace('../09_SPEC/', '../../09_SPEC/')
        Path(new_path).write_text(updated_content)
        fixes.append(f"Updated relative links for nested folder structure")

    return fixes

Link Path Updates After Move:

Original PathUpdated Path
../09_SPEC/SPEC-01_slug/SPEC-01.yaml../../09_SPEC/SPEC-01_slug/SPEC-01.yaml
../10_TSPEC/UTEST/UTEST-01_slug/UTEST-01.md../../10_TSPEC/UTEST/UTEST-01_slug/UTEST-01.md

Phase 1: Create Missing Files

Creates files that are referenced but don't exist.

Scope:

Missing FileActionTemplate Used
TASKS-NN_contracts.pyCreate contracts stubPython contracts template
TASKS-NN_dependencies.yamlCreate dependencies fileDependencies template
IPLAN-NNN_*.mdCreate implementation planIPLAN template
Reference docsCreate placeholderREF template

Contracts Stub Template:

"""
TASKS-NN: Implementation Contracts
Auto-generated by doc-tasks-fixer - requires completion

This module defines the implementation contracts (Protocol interfaces,
exception hierarchies, state machines, data models) for TASKS-NN.
"""

from typing import Protocol, runtime_checkable
from enum import Enum, auto
from dataclasses import dataclass
from abc import ABC, abstractmethod

# =============================================================================
# Section 7: Protocol Interfaces
# =============================================================================

@runtime_checkable
class ExampleProtocol(Protocol):
    """Protocol interface placeholder.

    TODO: Define actual protocol methods based on SPEC requirements.
    """

    def execute(self, input_data: dict) -> dict:
        """Execute the main operation.

        Args:
            input_data: Input parameters

        Returns:
            Operation result
        """
        ...

# =============================================================================
# Section 8: Exception Hierarchies
# =============================================================================

class TasksBaseException(Exception):
    """Base exception for TASKS-NN operations."""

    def __init__(self, message: str, error_code: str = "ERR-000"):
        self.message = message
        self.error_code = error_code
        super().__init__(self.message)

class ValidationError(TasksBaseException):
    """Raised when validation fails."""

    def __init__(self, message: str, field: str = None):
        super().__init__(message, "ERR-VAL-001")
        self.field = field

class ProcessingError(TasksBaseException):
    """Raised when processing fails."""

    def __init__(self, message: str, step: str = None):
        super().__init__(message, "ERR-PROC-001")
        self.step = step

# =============================================================================
# Section 8: State Machine Contracts
# =============================================================================

class TaskState(Enum):
    """Task state machine states."""

    PENDING = auto()
    IN_PROGRESS = auto()
    BLOCKED = auto()
    COMPLETED = auto()
    FAILED = auto()

# Valid state transitions
STATE_TRANSITIONS = {
    TaskState.PENDING: [TaskState.IN_PROGRESS, TaskState.BLOCKED],
    TaskState.IN_PROGRESS: [TaskState.COMPLETED, TaskState.FAILED, TaskState.BLOCKED],
    TaskState.BLOCKED: [TaskState.PENDING, TaskState.IN_PROGRESS],
    TaskState.COMPLETED: [],  # Terminal state
    TaskState.FAILED: [TaskState.PENDING],  # Can retry
}

# =============================================================================
# Section 8: Data Models
# =============================================================================

@dataclass
class TaskModel:
    """Data model for a task.

    TODO: Extend based on SPEC requirements.
    """

    id: str
    title: str
    status: TaskState = TaskState.PENDING
    priority: int = 2
    assignee: str = None

    def validate(self) -> bool:
        """Validate the task data."""
        if not self.id or not self.title:
            return False
        if not 1 <= self.priority <= 5:
            return False
        return True

Dependencies Template:

# TASKS-NN: Dependencies
# Auto-generated by doc-tasks-fixer - requires completion

dependencies:
  version: "1.0.0"
  tasks_id: TASKS-NN
  created: "YYYY-MM-DD"
  status: draft

upstream:
  specs:
    - id: SPEC-XX
      version: "1.0.0"
      sections:
        # TODO: List required SPEC sections
        - SPEC-XX.section.element

  tspecs:
    - id: TSPEC-XX
      version: "1.0.0"
      test_cases:
        # TODO: List related test cases
        - TSPEC-XX.40.01

downstream:
  implementations:
    # TODO: List downstream implementations
    - file: src/module/component.py
      status: pending

  iplans:
    # TODO: List implementation plans
    - id: IPLAN-001
      status: pending

blocking:
  # Tasks that block this TASKS completion
  - task_id: TASKS-XX
    reason: "Dependency on shared component"

blocked_by:
  # Tasks that this TASKS blocks
  - task_id: TASKS-YY
    reason: "Provides foundation interfaces"

Phase 2: Fix Broken Links

Updates links to point to correct locations.

Fix Actions:

Issue CodeIssueFix Action
REV-L001Broken internal linkUpdate path or create target file
REV-L002External link unreachableAdd warning comment, keep link
REV-L003Absolute path usedConvert to relative path
REV-L010SPEC reference brokenUpdate SPEC path
REV-L011TSPEC reference brokenUpdate TSPEC path
REV-L012Contract import brokenFix Python import path

Path Resolution Logic:

def fix_link_path(tasks_location: str, target_path: str) -> str:
    """Calculate correct relative path based on TASKS location."""

    # TASKS files: docs/11_TASKS/TASKS-01.md
    # Contracts: docs/11_TASKS/contracts/
    # Dependencies: docs/11_TASKS/deps/

    if is_python_import(target_path):
        return fix_python_import(tasks_location, target_path)
    elif is_spec_reference(target_path):
        return fix_spec_ref(tasks_location, target_path)
    elif is_tspec_reference(target_path):
        return fix_tspec_ref(tasks_location, target_path)
    else:
        return calculate_relative_path(tasks_location, target_path)

Phase 3: Fix Element IDs

Converts invalid element IDs to correct format.

Conversion Rules:

PatternIssueConversion
TASKS.NN.XX.SSInvalid type codeConvert to valid TASKS code
TASK-XXXLegacy patternTASKS.NN.18.SS (Implementation Task)
CONTRACT-XXXLegacy patternTASKS.NN.30.SS (Contract Definition)
DEP-XXXLegacy patternTASKS.NN.18.SS

Type Code Mapping (TASKS-specific):

Invalid CodeValid CodeElement Type
01-1718Implementation Task
19-2930Contract Definition
Any other18/30Map to task or contract

Valid TASKS Type Codes:

CodeElement TypeDescription
18Implementation TaskIndividual implementation task
30Contract DefinitionProtocol, exception, state machine, or data model

Regex Patterns:

# Find element IDs with invalid type codes for TASKS
invalid_tasks_type = r'TASKS\.(\d{2})\.(?!18|30)(\d{2})\.(\d{2})'

# Find legacy patterns
legacy_task = r'###\s+TASK-(\d+):'
legacy_contract = r'###\s+CONTRACT-(\d+):'
legacy_dep = r'###\s+DEP-(\d+):'

Phase 4: Fix Content Issues

Addresses placeholders and incomplete content.

Fix Actions:

Issue CodeIssueFix Action
REV-P001[TODO] placeholderFlag for manual completion (cannot auto-fix)
REV-P002[TBD] placeholderFlag for manual completion (cannot auto-fix)
REV-P003Template date YYYY-MM-DDReplace with current date
REV-P004Template name [Name]Replace with metadata author or flag
REV-P005Empty sectionAdd minimum template content
REV-C001Missing Protocol signatureAdd placeholder method signature
REV-C002Missing exception hierarchyAdd base exception class
REV-C003Invalid state transitionsAdd transition validation

Auto-Replacements:

replacements = {
    'YYYY-MM-DDTHH:MM:SS': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
    'YYYY-MM-DD': datetime.now().strftime('%Y-%m-%d'),
    'MM/DD/YYYY': datetime.now().strftime('%m/%d/%Y'),
    '[Current date]': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
}

Contract Structure Repair:

Missing ElementAdded Template
Protocol methodsdef method(self) -> None:...
Exception baseclass BaseException(Exception): pass
State enumclass State(Enum): INITIAL = auto()
Data model@dataclass class Model: id: str

Phase 5: Update References

Ensures traceability and cross-references are correct.

Fix Actions:

IssueFix Action
Missing @spec: referenceAdd SPEC traceability tag
Missing @tspec: referenceAdd TSPEC traceability tag
Incorrect upstream pathUpdate to correct relative path
Missing traceability entryAdd to traceability matrix
Missing dependency linkAdd to dependencies section

SPEC/TSPEC Traceability Fix:

<!-- Before -->
## TASKS.01.1801: Implement Authentication Handler

<!-- After -->
## TASKS.01.1801: Implement Authentication Handler

@spec: [SPEC-01.auth.handler](../09_SPEC/SPEC-01.md#auth-handler)
@tspec: [TSPEC-01.40.01](../10_TSPEC/TSPEC-01.md#tspec-01-40-01)

Phase 6: Handle Upstream Drift (Auto-Merge)

Addresses issues where upstream SPEC/TSPEC documents have changed since TASKS creation using a tiered auto-merge system.

6.0.1 Hash Validation Fixes

FIX-H001: Invalid Hash Placeholder

Trigger: Hash contains placeholder instead of SHA-256

Fix:

sha256sum <upstream_file_path> | cut -d' ' -f1

Update cache with: sha256:<64_hex_output>

FIX-H002: Missing Hash Prefix

Trigger: 64 hex chars but missing sha256: prefix

Fix: Prepend sha256: to value

FIX-H003: Upstream File Not Found

Trigger: Cannot compute hash (file missing)

Fix: Set drift_detected: true, add to manual review

CodeDescriptionAuto-FixSeverity
FIX-H001Replace placeholder hash with actual SHA-256YesError
FIX-H002Add missing sha256: prefixYesWarning
FIX-H003Upstream file not foundPartialError

Upstream/Downstream Context:

DirectionArtifactsRelationship
UpstreamSPEC, TSPECSource of requirements and test specifications
DownstreamCode, IPLANImplementation artifacts that depend on TASKS
Tiered Auto-Merge Thresholds

The auto-merge system uses three tiers based on the percentage of change detected in upstream documents.

TierChange %ActionVersion BumpHuman Review
Tier 1< 5%Auto-merge new tasksPatch (x.x.+1)No
Tier 25-15%Auto-merge with detailed changelogMinor (x.+1.0)Optional
Tier 3> 15%Archive current, trigger regenerationMajor (+1.0.0)Required
Change Percentage Calculation
def calculate_change_percentage(
    upstream_doc: str,
    tasks_doc: str,
    drift_cache: dict
) -> float:
    """Calculate upstream change percentage affecting TASKS.

    Args:
        upstream_doc: Path to SPEC or TSPEC document
        tasks_doc: Path to TASKS document
        drift_cache: Previous drift state from .drift_cache.json

    Returns:
        Change percentage (0.0 to 100.0)
    """
    # Count affected elements
    current_refs = extract_upstream_references(tasks_doc)
    cached_refs = drift_cache.get('references', {})

    # Calculate changes
    added_refs = set(current_refs) - set(cached_refs)
    removed_refs = set(cached_refs) - set(current_refs)
    modified_refs = [r for r in current_refs
                     if r in cached_refs and current_refs[r] != cached_refs[r]]

    total_refs = max(len(current_refs), len(cached_refs), 1)
    changed_refs = len(added_refs) + len(removed_refs) + len(modified_refs)

    return (changed_refs / total_refs) * 100
Task ID Pattern

Auto-generated tasks follow the pattern: TASK-NN-SSS

ComponentDescriptionExample
NNModule number (from TASKS-NN)01, 02, 15
SSSSequence number within module001, 002, 999

Full Pattern: TASK-{module:02d}-{sequence:03d}

Examples:

  • TASK-01-001: First task in module 01
  • TASK-03-042: 42nd task in module 03
  • TASK-15-007: 7th task in module 15
def generate_task_id(module_number: int, existing_tasks: list[str]) -> str:
    """Generate next available task ID for a module.

    Args:
        module_number: The TASKS module number (NN from TASKS-NN)
        existing_tasks: List of existing task IDs in the module

    Returns:
        Next available task ID in format TASK-NN-SSS
    """
    # Extract sequence numbers from existing tasks
    pattern = re.compile(rf'TASK-{module_number:02d}-(\d{{3}})')
    sequences = [int(m.group(1)) for t in existing_tasks
                 if (m := pattern.match(t))]

    next_seq = max(sequences, default=0) + 1
    return f"TASK-{module_number:02d}-{next_seq:03d}"
No Deletion Policy

Tasks are NEVER deleted. Instead, they are marked as [CANCELLED] with a reason.

Rationale: Preserves audit trail, prevents orphaned downstream references, maintains traceability.

<!-- Before: Active task -->
### TASK-01-003: Implement Rate Limiting

@spec: SPEC-01.rate_limit
Status: pending
Priority: P2

<!-- After: Cancelled task -->
### TASK-01-003: Implement Rate Limiting [CANCELLED]

@spec: SPEC-01.rate_limit
Status: cancelled
Cancelled: 2026-02-10
Cancel-Reason: Upstream SPEC-01 removed rate limiting requirement (REV-D007)
Original-Priority: P2

<!-- Cancellation preserves all original content below -->

Cancellation Metadata:

FieldDescription
StatusChanged to cancelled
CancelledDate of cancellation (YYYY-MM-DD)
Cancel-ReasonWhy task was cancelled (with issue code)
Original-PriorityPreserved for audit trail
Tier 1: Auto-Merge (< 5% Change)

Minor changes are automatically merged without human intervention.

Actions:

  1. Generate new task IDs for added requirements
  2. Update existing task references to new upstream versions
  3. Increment patch version (e.g., 1.0.0 -> 1.0.1)
  4. Update drift cache
def tier1_auto_merge(tasks_doc: str, upstream_changes: dict) -> MergeResult:
    """Auto-merge minor upstream changes.

    Args:
        tasks_doc: Path to TASKS document
        upstream_changes: Dict of detected changes

    Returns:
        MergeResult with applied changes
    """
    result = MergeResult()

    # Add new tasks for new specifications
    for spec_ref in upstream_changes.get('added', []):
        task_id = generate_task_id(get_module_number(tasks_doc), get_existing_tasks(tasks_doc))
        new_task = create_task_from_spec(spec_ref, task_id)
        result.tasks_added.append(new_task)

    # Update version references
    for ref in upstream_changes.get('version_changed', []):
        update_spec_reference(tasks_doc, ref['old'], ref['new'])
        result.refs_updated.append(ref)

    # Increment patch version
    result.new_version = increment_patch_version(get_tasks_version(tasks_doc))

    return result
Tier 2: Auto-Merge with Changelog (5-15% Change)

Moderate changes are merged with detailed documentation.

Actions:

  1. All Tier 1 actions
  2. Generate detailed changelog entry
  3. Mark affected tasks with [DRIFT-REVIEWED] marker
  4. Increment minor version (e.g., 1.0.1 -> 1.1.0)
  5. Update dependency links
  6. Flag for optional human review

Changelog Format:

## Changelog

### v1.1.0 (2026-02-10) - Upstream Drift Merge

**Merge Type**: Tier 2 Auto-Merge (8.3% change)
**Upstream Documents**: SPEC-01.md, TSPEC-01.md

#### Tasks Added
| ID | Title | Source |
|----|-------|--------|
| TASK-01-015 | Implement OAuth2 PKCE flow | SPEC-01.auth.oauth2_pkce (added 2026-02-09) |
| TASK-01-016 | Add token refresh mechanism | SPEC-01.auth.token_refresh (added 2026-02-09) |

#### Tasks Modified
| ID | Change | Reason |
|----|--------|--------|
| TASK-01-003 | Updated acceptance criteria | SPEC-01.auth.session updated |

#### References Updated
| Old Reference | New Reference |
|---------------|---------------|
| SPEC-01.md@v1.2.0 | SPEC-01.md@v1.3.0 |
| TSPEC-01.md@v1.1.0 | TSPEC-01.md@v1.2.0 |

#### Implementation Contracts Affected
| Contract | Change |
|----------|--------|
| AuthProtocol | New method: `refresh_token()` |
| TokenModel | New field: `refresh_expires_at` |
Tier 3: Archive and Regenerate (> 15% Change)

Major changes require archiving and regeneration.

Actions:

  1. Create archive manifest
  2. Archive current TASKS version
  3. Trigger full TASKS regeneration via doc-tasks-autopilot
  4. Increment major version (e.g., 1.1.0 -> 2.0.0)
  5. Require human review before finalization

Archive Manifest Format:

# TASKS-NN_archive_manifest_vNNN.yaml
archive:
  document: TASKS-01
  archived_version: "1.1.0"
  archive_date: "2026-02-10T16:00:00"
  archive_reason: "Tier 3 upstream drift (23.5% change)"
  archive_location: "archive/TASKS-01_v1.1.0/"

drift_summary:
  total_change_percentage: 23.5
  upstream_documents:
    - document: SPEC-01.md
      previous_version: "1.3.0"
      current_version: "2.0.0"
      change_percentage: 18.2
    - document: TSPEC-01.md
      previous_version: "1.2.0"
      current_version: "1.5.0"
      change_percentage: 12.1

affected_tasks:
  total: 42
  cancelled: 8
  modified: 15
  unchanged: 19

implementation_contracts:
  protocols_affected: 3
  exceptions_affected: 1
  state_machines_affected: 2
  data_models_affected: 4

downstream_impact:
  iplan_documents:
    - IPLAN-001: "Requires regeneration"
    - IPLAN-002: "Minor updates needed"
  code_files:
    - src/auth/handler.py: "Interface changes required"
    - src/auth/models.py: "Data model updates required"

regeneration:
  trigger_skill: doc-tasks-autopilot
  trigger_args: "SPEC-01 --force-regenerate"
  new_version: "2.0.0"
  human_review_required: true
Enhanced Drift Cache

The drift cache tracks merge history and upstream state.

File: .drift_cache.json (in TASKS directory)

{
  "tasks_document": "TASKS-01",
  "cache_version": "2.0",
  "last_updated": "2026-02-10T16:00:00",
  "current_version": "1.1.0",

  "upstream_state": {
    "SPEC-01.md": {
      "version": "1.3.0",
      "hash": "sha256:abc123...",
      "last_checked": "2026-02-10T16:00:00",
      "sections_referenced": [
        "SPEC-01.auth.handler",
        "SPEC-01.auth.session",
        "SPEC-01.auth.oauth2_pkce"
      ]
    },
    "TSPEC-01.md": {
      "version": "1.2.0",
      "hash": "sha256:def456...",
      "last_checked": "2026-02-10T16:00:00",
      "test_cases_referenced": [
        "TSPEC-01.40.01",
        "TSPEC-01.40.02"
      ]
    }
  },

  "merge_history": [
    {
      "date": "2026-02-08T10:00:00",
      "tier": 1,
      "change_percentage": 2.3,
      "version_before": "1.0.0",
      "version_after": "1.0.1",
      "tasks_added": ["TASK-01-012"],
      "tasks_modified": [],
      "tasks_cancelled": []
    },
    {
      "date": "2026-02-10T16:00:00",
      "tier": 2,
      "change_percentage": 8.3,
      "version_before": "1.0.1",
      "version_after": "1.1.0",
      "tasks_added": ["TASK-01-015", "TASK-01-016"],
      "tasks_modified": ["TASK-01-003"],
      "tasks_cancelled": [],
      "changelog_entry": "v1.1.0"
    }
  ],

  "task_registry": {
    "TASK-01-001": {"status": "completed", "spec_ref": "SPEC-01.auth.init"},
    "TASK-01-002": {"status": "in_progress", "spec_ref": "SPEC-01.auth.login"},
    "TASK-01-003": {"status": "pending", "spec_ref": "SPEC-01.auth.session"},
    "TASK-01-012": {"status": "pending", "spec_ref": "SPEC-01.auth.logout"},
    "TASK-01-015": {"status": "pending", "spec_ref": "SPEC-01.auth.oauth2_pkce"},
    "TASK-01-016": {"status": "pending", "spec_ref": "SPEC-01.auth.token_refresh"}
  },

  "implementation_contracts": {
    "protocols": ["AuthProtocol", "SessionProtocol"],
    "exceptions": ["AuthException", "SessionException"],
    "state_machines": ["AuthState", "SessionState"],
    "data_models": ["UserModel", "TokenModel", "SessionModel"]
  }
}
Handling Task Dependencies

When upstream drift affects tasks with dependencies, the auto-merge system handles cascading updates.

def handle_task_dependencies(
    affected_task: str,
    task_graph: dict,
    change_type: str
) -> list[str]:
    """Propagate changes through task dependency graph.

    Args:
        affected_task: Task ID that was modified/cancelled
        task_graph: Dict mapping task IDs to their dependencies
        change_type: 'modified' or 'cancelled'

    Returns:
        List of downstream tasks requiring update
    """
    downstream_tasks = []

    # Find tasks that depend on the affected task
    for task_id, deps in task_graph.items():
        if affected_task in deps.get('blocked_by', []):
            downstream_tasks.append(task_id)

            if change_type == 'cancelled':
                # Remove dependency, add warning
                add_task_warning(task_id,
                    f"Dependency {affected_task} was cancelled")
            elif change_type == 'modified':
                # Mark for review
                add_task_marker(task_id, '[UPSTREAM-MODIFIED]')

    return downstream_tasks
Handling Implementation Contracts

When upstream drift affects implementation contracts, the auto-merge system updates contract definitions.

def update_implementation_contracts(
    contracts: dict,
    upstream_changes: dict
) -> ContractUpdateResult:
    """Update implementation contracts based on upstream drift.

    Args:
        contracts: Current contract definitions
        upstream_changes: Detected upstream changes

    Returns:
        ContractUpdateResult with changes applied
    """
    result = ContractUpdateResult()

    for spec_change in upstream_changes.get('spec_changes', []):
        # Check if change affects a protocol
        if affects_protocol(spec_change, contracts['protocols']):
            protocol = get_affected_protocol(spec_change)
            if spec_change['type'] == 'method_added':
                add_protocol_method(protocol, spec_change['method'])
                result.protocols_modified.append(protocol)
            elif spec_change['type'] == 'method_signature_changed':
                update_protocol_signature(protocol, spec_change)
                result.protocols_modified.append(protocol)

        # Check if change affects a data model
        if affects_data_model(spec_change, contracts['data_models']):
            model = get_affected_model(spec_change)
            if spec_change['type'] == 'field_added':
                add_model_field(model, spec_change['field'])
                result.models_modified.append(model)

    return result
Drift Issue Codes
CodeSeverityDescriptionAuto-FixTier
REV-D001InfoUpstream version incrementedYes1
REV-D002WarningMinor specification content changed (< 5%)Yes1
REV-D003WarningModerate specification change (5-15%)Yes2
REV-D004WarningNew specifications added to upstreamYes1-2
REV-D005ErrorSpecifications removed from upstreamYes (cancel)2
REV-D006ErrorMajor upstream modification (> 15%)Partial3
REV-D007ErrorBreaking change to implementation contractPartial3
REV-D008InfoTask dependency graph affectedYes1-2
Fix Actions Summary
TierIssue CodesAuto-Fix Action
1REV-D001, REV-D002, REV-D004 (minor)Auto-merge, patch version
2REV-D003, REV-D004 (moderate), REV-D005, REV-D008Auto-merge with changelog, minor version
3REV-D006, REV-D007Archive, regenerate, major version

Implementation Contract Fixes

TASKS documents contain implementation contracts in Sections 7-8. This section details specific contract repair strategies.

Contract Detection

def find_contracts(content: str) -> dict:
    """Find all contracts in TASKS content."""
    contracts = {
        'protocols': [],
        'exceptions': [],
        'state_machines': [],
        'data_models': []
    }

    # Find Python code blocks containing contracts
    code_blocks = re.findall(r'```python\n(.*?)```', content, re.DOTALL)

    for block in code_blocks:
        if 'class' in block and 'Protocol' in block:
            contracts['protocols'].append(block)
        if 'Exception' in block or 'Error' in block:
            contracts['exceptions'].append(block)
        if 'Enum' in block and 'State' in block.lower():
            contracts['state_machines'].append(block)
        if '@dataclass' in block or 'TypedDict' in block:
            contracts['data_models'].append(block)

    return contracts

Contract Type Requirements

Contract TypeRequired Elements
Protocol@runtime_checkable, method signatures with type hints
ExceptionBase class, error_code, retry semantics
State MachineEnum class, STATE_TRANSITIONS dict
Data ModelType annotations, validate() method

Contract Repair Actions

IssueRepair Action
Missing @runtime_checkableAdd decorator to Protocol
Missing type hintsAdd -> None default return type
Missing error_codeAdd error_code attribute to exception
Invalid state transitionsAdd missing states to transition dict
Missing dataclass decoratorAdd @dataclass decorator
Missing validate methodAdd placeholder validate method

Contract Template Sections

Section 7: Protocol Interfaces

@runtime_checkable
class ProtocolName(Protocol):
    """Protocol description.

    @spec: SPEC-XX.section
    """

    def method_name(self, param: Type) -> ReturnType:
        """Method description."""
        ...

Section 8: Exception Hierarchy

class ModuleBaseException(Exception):
    """Base exception for module.

    Attributes:
        message: Error message
        error_code: Unique error identifier
        retry_allowed: Whether operation can be retried
    """

    def __init__(self, message: str, error_code: str = "ERR-000"):
        self.message = message
        self.error_code = error_code
        self.retry_allowed = False
        super().__init__(self.message)

Section 8: State Machine

class EntityState(Enum):
    """State machine for Entity.

    @spec: SPEC-XX.state_machine
    """

    INITIAL = auto()
    PROCESSING = auto()
    COMPLETED = auto()
    FAILED = auto()

STATE_TRANSITIONS: dict[EntityState, list[EntityState]] = {
    EntityState.INITIAL: [EntityState.PROCESSING],
    EntityState.PROCESSING: [EntityState.COMPLETED, EntityState.FAILED],
    EntityState.COMPLETED: [],  # Terminal
    EntityState.FAILED: [EntityState.INITIAL],  # Retry
}

Section 8: Data Model

@dataclass
class EntityModel:
    """Data model for Entity.

    @spec: SPEC-XX.data_model
    """

    id: str
    name: str
    status: EntityState = EntityState.INITIAL
    created_at: datetime = field(default_factory=datetime.utcnow)

    def validate(self) -> bool:
        """Validate model data."""
        if not self.id or not self.name:
            return False
        return True

Command Usage

Basic Usage

# Fix TASKS based on latest review
/doc-tasks-fixer TASKS-01

# Fix with explicit review report
/doc-tasks-fixer TASKS-01 --review-report TASKS-01.R_review_report_v001.md

# Fix and re-run review
/doc-tasks-fixer TASKS-01 --revalidate

# Fix with iteration limit
/doc-tasks-fixer TASKS-01 --revalidate --max-iterations 3

# Fix contracts only
/doc-tasks-fixer TASKS-01 --fix-types contracts

# Handle upstream drift with auto-merge
/doc-tasks-fixer TASKS-01 --fix-types drift

# Force Tier 2 merge with changelog
/doc-tasks-fixer TASKS-01 --fix-types drift --auto-merge-tier 2

# Custom tier thresholds
/doc-tasks-fixer TASKS-01 --tier1-threshold 3 --tier2-threshold 10

# Force regeneration (Tier 3) for major upstream changes
/doc-tasks-fixer TASKS-01 --force-regenerate

# Preview drift merge without applying
/doc-tasks-fixer TASKS-01 --fix-types drift --dry-run

Options

OptionDefaultDescription
--review-reportlatestSpecific review report to use
--revalidatefalseRun reviewer after fixes
--max-iterations3Max fix-review cycles
--fix-typesallSpecific fix types (comma-separated)
--create-missingtrueCreate missing reference files
--backuptrueBackup TASKS before fixing
--dry-runfalsePreview fixes without applying
--validate-contractstrueValidate contract structure after fixes
--type-checkfalseRun mypy on contract code blocks
--acknowledge-driftfalseInteractive drift acknowledgment mode
--update-drift-cachetrueUpdate.drift_cache.json after fixes
--auto-merge-tierautoForce specific tier (1, 2, 3) or auto-detect
--tier1-threshold5Maximum change % for Tier 1 auto-merge
--tier2-threshold15Maximum change % for Tier 2 auto-merge
--skip-archivefalseSkip archive creation for Tier 3 (not recommended)
--force-regeneratefalseForce Tier 3 regeneration regardless of change %
--preserve-cancelledtrueKeep cancelled tasks in document
--generate-changelogtrueGenerate changelog for Tier 2+ merges
--notify-downstreamtrueFlag downstream IPLAN/Code for updates

Fix Types

TypeDescription
missing_filesCreate missing contract, dependency docs
broken_linksFix link paths and import references
element_idsConvert invalid/legacy element IDs (18, 30)
contentFix placeholders, dates, names
referencesUpdate SPEC/TSPEC traceability and cross-references
driftHandle upstream drift with tiered auto-merge (Tier 1-3)
contractsFix implementation contract structure issues
allAll fix types (default)

Drift Fix Sub-Options

Sub-OptionDescription
drift:detectOnly detect drift, do not apply fixes
drift:tier1Apply only Tier 1 (< 5%) auto-merges
drift:tier2Apply Tier 1 and Tier 2 (5-15%) auto-merges
drift:tier3Full drift handling including archive/regenerate
drift:changelogGenerate changelog without applying merges

Output Artifacts

Fix Report

Nested Folder Rule: ALL TASKS use nested folders (TASKS-NN_{slug}/) regardless of size. Fix reports are stored alongside the TASKS document in the nested folder.

File Naming: TASKS-NN.F_fix_report_vNNN.md

Location: Inside the TASKS nested folder: docs/11_TASKS/TASKS-NN_{slug}/

Structure:

---
title: "TASKS-NN.F: Fix Report v001"
tags:
  - tasks
  - fix-report
  - quality-assurance
custom_fields:
  document_type: fix-report
  artifact_type: TASKS-FIX
  layer: 11
  parent_doc: TASKS-NN
  source_review: TASKS-NN.R_review_report_v001.md
  fix_date: "YYYY-MM-DDTHH:MM:SS"
  fix_tool: doc-tasks-fixer
  fix_version: "1.0"
---

# TASKS-NN Fix Report v001

## Summary

| Metric | Value |
|--------|-------|
| Source Review | TASKS-NN.R_review_report_v001.md |
| Issues in Review | 22 |
| Issues Fixed | 18 |
| Issues Remaining | 4 (manual review required) |
| Files Created | 2 |
| Files Modified | 1 |
| Contracts Repaired | 6 |

## Files Created

| File | Type | Location |
|------|------|----------|
| TASKS-01_contracts.py | Contract Stubs | docs/11_TASKS/contracts/ |
| TASKS-01_dependencies.yaml | Dependencies | docs/11_TASKS/deps/ |

## Contract Structure Repairs

| Contract | Type | Issue | Repair Applied |
|----------|------|-------|----------------|
| AuthProtocol | Protocol | Missing @runtime_checkable | Added decorator |
| ValidationError | Exception | Missing error_code | Added attribute |
| TaskState | State Machine | Invalid transitions | Fixed transition dict |
| UserModel | Data Model | Missing validate() | Added method |
| ProcessProtocol | Protocol | Missing type hints | Added return types |
| ConfigError | Exception | Missing retry semantics | Added retry_allowed |

## Fixes Applied

| # | Issue Code | Issue | Fix Applied | File |
|---|------------|-------|-------------|------|
| 1 | REV-N004 | Invalid element type | Converted to type 18 | TASKS-01.md |
| 2 | REV-C001 | Missing Protocol signature | Added placeholder | TASKS-01.md |
| 3 | REV-L003 | Absolute path used | Converted to relative | TASKS-01.md |

## Issues Requiring Manual Review

| # | Issue Code | Issue | Location | Reason |
|---|------------|-------|----------|--------|
| 1 | REV-P001 | [TODO] placeholder | TASKS-01.md:L78 | Implementation logic needed |
| 2 | REV-D002 | SPEC content changed | SPEC-01.auth | Review specification update |

## Upstream Drift Summary

| Upstream Document | Reference | Modified | TASKS Updated | Days Stale | Action Required |
|-------------------|-----------|----------|---------------|------------|-----------------|
| SPEC-01.md | TASKS-01:L57 | 2026-02-08 | 2026-02-05 | 3 | Review for changes |
| TSPEC-01.md | TASKS-01:L92 | 2026-02-09 | 2026-02-05 | 4 | Review for changes |

## Type Check Results

| Contract | mypy Status | Issues |
|----------|-------------|--------|
| AuthProtocol | Pass | None |
| ValidationError | Pass | None |
| TaskState | Warning | Missing annotation on line 45 |

## Validation After Fix

| Metric | Before | After | Delta |
|--------|--------|-------|-------|
| Review Score | 80 | 93 | +13 |
| Errors | 7 | 0 | -7 |
| Warnings | 9 | 4 | -5 |
| Valid Contracts | 8/14 | 14/14 | +6 |

## Next Steps

1. Complete [TODO] placeholders in implementation tasks
2. Review upstream SPEC/TSPEC drift
3. Implement contract methods in TASKS-01_contracts.py
4. Run `/doc-tasks-reviewer TASKS-01` to verify fixes
5. Run mypy on contracts to ensure type compliance

Integration with Autopilot

This skill is invoked by doc-tasks-autopilot in the Review -> Fix cycle:

flowchart LR
    subgraph Phase5["Phase 5: Review & Fix Cycle"]
        A[doc-tasks-reviewer] --> B{Score >= 90?}
        B -->|No| C[doc-tasks-fixer]
        C --> D{Iteration < Max?}
        D -->|Yes| A
        D -->|No| E[Flag for Manual Review]
        B -->|Yes| F[PASS]
    end

Autopilot Integration Points:

PhaseActionSkill
Phase 5aRun initial reviewdoc-tasks-reviewer
Phase 5bApply fixes if issues founddoc-tasks-fixer
Phase 5cRe-run reviewdoc-tasks-reviewer
Phase 5dRepeat until pass or max iterationsLoop

Error Handling

Recovery Actions

ErrorAction
Review report not foundPrompt to run doc-tasks-reviewer first
Cannot create file (permissions)Log error, continue with other fixes
Cannot parse review reportAbort with clear error message
Contract parse errorAttempt repair, flag if unrecoverable
mypy validation failureLog warning, continue with fixes
Max iterations exceededGenerate report, flag for manual review

Backup Strategy

Before applying any fixes:

  1. Create backup in tmp/backup/TASKS-NN_YYYYMMDD_HHMMSS/
  2. Copy all TASKS files to backup location
  3. Apply fixes to original files
  4. If error during fix, restore from backup

Related Skills

SkillRelationship
doc-tasks-reviewerProvides review report (input)
doc-tasks-autopilotOrchestrates Review -> Fix cycle
doc-tasks-validatorStructural validation
doc-namingElement ID standards
doc-tasksTASKS creation rules
doc-specSPEC upstream traceability
doc-tspecTSPEC upstream traceability

Version History

VersionDateChanges
2.12026-02-11Structure Compliance: Added Phase 0 for nested folder rule enforcement (REV-STR001-STR003); Runs FIRST before other fix phases
2.02026-02-10Enhanced Phase 6 with tiered auto-merge system; Tier 1 (< 5%) auto-merge with patch version; Tier 2 (5-15%) auto-merge with changelog and minor version; Tier 3 (> 15%) archive and regenerate with major version; Task ID pattern TASK-NN-SSS; No deletion policy (mark as [CANCELLED]); Archive manifest creation for Tier 3; Enhanced drift cache with merge history and task registry; Task dependency propagation; Implementation contract update handling; New drift issue codes (REV-D001 through REV-D008)
1.02026-02-10Initial skill creation; 6-phase fix workflow; Implementation contract repair (Protocol, Exception, State Machine, Data Model); Contract stub and dependency file generation; Element ID conversion (types 18, 30); SPEC/TSPEC drift handling; Optional mypy type checking; Integration with autopilot Review->Fix cycle

Implementation Plan Consistency (IPLAN-004)

  • Treat plan-derived outputs as valid source mode and verify intent preservation from implementation plan scope/objectives.
  • Validate upstream autopilot precedence assumption: --iplan > --ref > --prompt.
  • Flag objective/scope conflicts between plan context and artifact output as blocking issues requiring clarification.
  • Do not introduce legacy fallback paths such as docs-v2.0/00_REF.

平台分布

Codex

35.03%
按下载量换算78

Claude

31.5%
按下载量换算70

Cursor

20.69%
按下载量换算46

Gemini CLI

9.04%
按下载量换算20

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill doc-tasks-fixer 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills