Token导航 LogoToken导航TokenDH.com
研究检索执行命令github未标认证来源可访问许可证需确认审计通过

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

Agent Skill

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

总安装

685

周安装

28

GitHub Stars

14

下载量

222
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 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

简介

根据审计反馈自动修复任务文档中的错误与遗漏。

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

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.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

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