team-repair

SkillFiles & storage

Re-index OKF v0.2 index.md/log.md files, derive CDR.md, rebuild .skills.json and AGENTS.md in team-ai-directives, migrate v0.1→v0.2 frontmatter, scan for rule conflicts, and verify directive freshness. Use when indexes are inconsistent, orphans are detected, after bulk changes, or for periodic team AI directives health validation.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the team-repair skill

What this skill tells your AI

The instructions your AI receives, as published by tikalk/adlc-team-skills in skills/team/team-repair/SKILL.md and read by ahel’s review.

Overview

Re-indexes OKF v0.2 artifacts (index.md, log.md), derives the flat CDR.md inject, rebuilds .skills.json and AGENTS.md in team-ai-directives to fix inconsistencies, detect orphaned files, and auto-repair issues. Migrates OKF v0.1 frontmatter to v0.2 on every run (always-on, no opt-out). Begins with a health-check phase (Phase 0) that verifies the directives framework is installed, configured, and aligned before performing any repairs.

Input: team-ai-directives repository

Output: 0. Health check report (7 checks: team AI directives configured, context modules exist, skills registry, OKF log tracking, constitution alignment, OKF v0.2 type field presence, project AGENTS.md directive)

  1. Repaired AGENTS.md (if missing or corrupted)
  2. Migrated all context module frontmatter from OKF v0.1 to v0.2 (always-on)
  3. Rebuilt per-directory index.md files (OKF §8 catalog)
  4. Rebuilt per-directory log.md files (OKF §9 audit trail)
  5. Derived CDR.md flat table from index.md files (for team-boot system prompt injection)
  6. Rebuilt .skills.json manifest from skills/
  7. Auto-added OKF v0.2 YAML frontmatter to orphan context modules
  8. Auto-generated .skills.json entries for orphan skills
  9. Conflict scan across rules (creates conflict CDRs if issues found)
  10. Freshness verification (updates verified timestamps, flags stale directives)
  11. Summary report of all repairs

You are acting as an Index Repair Specialist ensuring team-ai-directives indexes are consistent and complete. Your role involves:

  • Verifying health checks before repair (Phase 0)
  • Scanning context_modules/ and skills/ directories
  • Detecting orphan files (missing frontmatter/manifest entries)
  • Auto-repairing issues by generating missing metadata
  • Rebuilding index files to reflect actual content
  • Reporting all changes made

Repair Targets

TargetLocationPurpose
AGENTS.md{TEAM_AI_DIRECTIVES}/AGENTS.mdMain instruction file for AI agents
index.md{TEAM_AI_DIRECTIVES}/context_modules/**/index.mdOKF §8 per-directory catalogs (progressive disclosure)
log.md{TEAM_AI_DIRECTIVES}/context_modules/**/log.mdOKF §9 per-directory audit trails
CDR.md{TEAM_AI_DIRECTIVES}/CDR.mdDerived flat table for team-boot system prompt injection (auto-generated from index.md files)
.skills.json{TEAM_AI_DIRECTIVES}/.skills.jsonSkills manifest registry

When to Use

User Input

$ARGUMENTS

You MUST consider the user input before proceeding (if not empty).

Examples of User Input:

  • "" - Repair all three indexes (default)
  • "--dry-run" - Report only, don't write changes
  • "--index-only" - Only rebuild OKF index.md + log.md + derive CDR.md
  • "--skills-only" - Only repair .skills.json
  • "--agents-only" - Only repair AGENTS.md
  • Empty input: Repair all indexes with auto-fix (includes v0.1→v0.2 migration)

Flags

FlagDescription
--dry-runReport only, don't write changes
--health-onlyRun Phase 0 health check only, then stop.
--validateRun conflict scan + freshness verification only (Phases 8-9)
--conflictsScan for rule conflicts only
--freshnessVerify directive freshness only
--build-to-deleteRun evals without directives to identify candidates for removal (Factor XII)
--index-onlyOnly rebuild OKF index.md + log.md + derive CDR.md
--skills-onlyOnly repair .skills.json
--agents-onlyOnly repair AGENTS.md
(default)Repair all indexes + migrate v0.1→v0.2 + validate conflicts and freshness

Core Process

Phase 0: Health Check

Objective: Run a non-destructive health check against the team directives framework before proceeding with repairs. If any check returns [FAIL], present the report and stop — the framework is not healthy enough to repair safely.

Execute all seven checks below. Each check prints a status line. If any check is [FAIL], abort repair.

Check 1: Team AI Directives Configured
  1. Read .adlc/init-options.json
  2. Verify team_ai_directives field exists and points to valid path
  3. Check the team AI directives path exists

Output: [OK] or [FAIL] with reason

Check 2: Context Modules Exist
  1. Read .adlc/init-options.json → get team AI directives path
  2. Verify:
    • {TEAM_AI_DIRECTIVES}/context_modules/constitution.md
    • {TEAM_AI_DIRECTIVES}/context_modules/personas/
    • {TEAM_AI_DIRECTIVES}/context_modules/rules/
    • {TEAM_AI_DIRECTIVES}/context_modules/examples/

Output: [OK] or [FAIL] with reason

Check 3: Skills Registry
  • {TEAM_AI_DIRECTIVES}/.skills.json exists and is valid JSON

Output: [OK] or [FAIL] with reason

Check 4: OKF Log Tracking
  • {TEAM_AI_DIRECTIVES}/context_modules/rules/log.md exists
  • {TEAM_AI_DIRECTIVES}/context_modules/personas/log.md exists
  • {TEAM_AI_DIRECTIVES}/context_modules/examples/log.md exists
  • {TEAM_AI_DIRECTIVES}/CDR.md exists (derived artifact)

Output: [OK] or [FAIL] with reason

Check 5: Constitution Alignment
  1. Read team constitution from {TEAM_AI_DIRECTIVES}/context_modules/constitution.md
  2. Locate project constitution: the project root (where .adlc/ lives) → {REPO_ROOT}/.adlc/memory/constitution.md
  3. If project constitution exists:
    • Check if it references team-ai-directives (e.g., "Based on team-ai-directives", "Inherits from")
    • Check if team principles are present in project constitution (compare principle titles)
    • Output:
      • [OK] — Project constitution exists and inherits team principles
      • [WARN] — Project constitution exists but missing team inheritance
  4. If project constitution doesn't exist:
    • [INFO] — Project constitution doesn't exist yet (first-time setup)
Check 6: OKF v0.2 Conformance
  1. Scan all .md files in context_modules/ (excluding index.md, log.md)
  2. Parse YAML frontmatter from each file
  3. Verify type field is present and has a valid value:
    • Valid types: Constitution, Persona, Rule, Example, Skill
  4. Verify OKF v0.2 fields (migrate if v0.1 detected):
    • generated: { by, at } present (not legacy timestamp)
    • verified is a list format (not bare string)
    • status present (e.g., stable, draft, deprecated)
    • stale_after present (e.g., 180d)
  5. Output:
    • [OK] — All concept files have valid type fields and v0.2 families
    • [WARN] — Some files missing v0.2 fields or still carry v0.1 fields (will be migrated in Phase 4)
Check 7: Project AGENTS.md Directive
  1. Read {REPO_ROOT}/AGENTS.md (the project-level agent instructions file)
  2. Check if it contains the <!-- TEAM_AI_DIRECTIVES START --> marker
  3. If the marker exists, verify the managed section includes:
    • A team-boot invocation directive
    • A reference to team AI directives context (constitution, CDR index)
  4. Output:
    • [OK] — Project AGENTS.md contains a valid team AI directives managed section
    • [WARN] — Project AGENTS.md exists but is missing the managed section (agents won't auto-invoke team-boot)
    • [INFO] — Project AGENTS.md doesn't exist yet (first-time setup)
Health Check Output

Print verification status for each check:

  • [OK] — Check passed
  • [FAIL] — Check failed with reason (abort repair)
  • [WARN] — Check passed with warnings (non-blocking)
  • [INFO] — Informational only

If any check is [FAIL], print the report, set exit code 1, and STOP. Do not proceed to Phase 1.

Health Check Red Flags
  • [FAIL] on Check 1 or Check 2: the directives framework is effectively absent — agents have nothing to inherit from. Stop and reinstall before repairing.
  • Team AI Directives path resolves outside the repo or to a temp/scratch location: the project is pointing at a transient or shared team AI directives that may vanish or diverge.
  • {TEAM_AI_DIRECTIVES}/.skills.json is missing or not valid JSON: skill discovery is broken; agents cannot find team skills even if the files exist.
  • Project constitution exists but shows no team inheritance ([WARN] on Check 5): the project was bootstrapped without the team AI directives, or the constitution was hand-edited and the inheritance markers were removed.
  • Multiple checks return [WARN] simultaneously: systemic drift, usually from a moved .adlc/ directory or a reconfigured team AI directives path. Treat as a [FAIL]-equivalent and re-init.

Phase 1: Environment Setup

Objective: Resolve paths and validate infrastructure

Run $(dirname "$0")/team-helpers.sh --json (or the PowerShell equivalent) to resolve paths and parse JSON output:

{
  "REPO_ROOT": "/path/to/project",
  "TEAM_AI_DIRECTIVES": "/path/to/team-ai-directives",
  "BRANCH": "current-branch"
}

{REPO_ROOT} is the project root (where .adlc/ lives). Subsequent references use {REPO_ROOT}.

Phase 2: Validate Environment

Objective: Ensure team-ai-directives is configured

Check if TEAM_AI_DIRECTIVES has a value from script output.

If empty, STOP:

Team AI directives repository not configured.
Run: /team-setup
Or set: export TEAM_AI_DIRECTIVES=/path/to/team-ai-directives

Phase 3: Repair AGENTS.md

Objective: Ensure AGENTS.md exists with required structure

Skip if: --index-only or --skills-only flag provided

Step 1: Check AGENTS.md Exists
test -f "{TEAM_AI_DIRECTIVES}/AGENTS.md" && echo "EXISTS" || echo "MISSING"
Step 2: Validate Structure (if exists)

Required sections:

  • # Agent Instructions (title)
  • ## Structure
  • ## Loading Order
  • ## Functional Categories (Rules)
  • ## Using Skills
  • ## CDR.md

Check for each required section:

grep -q "^# Agent Instructions" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
grep -q "^## Structure" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
grep -q "^## Loading Order" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
grep -q "^## Functional Categories" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
grep -q "^## Using Skills" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
grep -qiE "##.*CDR\.md" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
Step 3: Auto-Repair
StatusAction
MissingCreate from templates/agents-template.md
Corrupted (missing sections)Overwrite with template
ValidNo changes

If --dry-run:

### AGENTS.md Status: {MISSING|CORRUPTED|VALID}

**Action**: {Would create|Would overwrite|No changes needed}

Otherwise, execute repair:

cp "templates/agents-template.md" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
Step 4: Track Results

Store for summary:

{
  "agents_md": {
    "status": "VALID|CREATED|OVERWRITTEN",
    "action": "No changes|Created from template|Re-created from template"
  }
}
Step 5: Inject Project-Level AGENTS.md Directive

After repairing the team AI directives' own AGENTS.md, also ensure the project-level AGENTS.md (at {REPO_ROOT}/AGENTS.md) contains the team-boot strict-compliance directive. This is what tells agents to invoke team-boot at session start.

If Check 8 returned [WARN] or [INFO], run the injection:

bash "$(dirname "$0")/team-helpers.sh" --inject-agents "{REPO_ROOT}"
# or: pwsh "$(Split-Path $PSCommandPath -Parent)/team-helpers.ps1" -InjectAgents "{REPO_ROOT}"

If --dry-run:

### Project AGENTS.md Status: {WARN|INFO}

**Action**: Would inject team AI directives managed section into {REPO_ROOT}/AGENTS.md

Otherwise, execute the injection. The function is idempotent — if the managed section already exists (between <!-- TEAM_AI_DIRECTIVES START --> and <!-- TEAM_AI_DIRECTIVES END --> markers), it replaces the section in place rather than duplicating.

Store for summary:

{
  "project_agents_md": {
    "status": "VALID|INJECTED|UPDATED",
    "action": "No changes|Created with managed section|Updated managed section"
  }
}

Phase 4: Scan Context Modules for CDR.md Reindex

Objective: Find all context modules and extract metadata

Skip if: --skills-only or --agents-only flag provided

Step 1: Find All Context Module Files
find "{TEAM_AI_DIRECTIVES}/context_modules/rules" -name "*.md" -type f 2>/dev/null
find "{TEAM_AI_DIRECTIVES}/context_modules/personas" -name "*.md" -type f 2>/dev/null
find "{TEAM_AI_DIRECTIVES}/context_modules/examples" -name "*.md" -type f 2>/dev/null

Skip constitution.md (not indexed in CDR.md).

Step 2: Extract YAML Frontmatter

For each file, parse YAML frontmatter (OKF v0.2 form after migration):

---
type: Rule
title: Python error handling
description: Python error handling patterns and best practices
tags: [python, error-handling]
resource: ./context_modules/rules/python/error-handling.md
generated: { by: agent:legacy, at: 2026-04-15T00:00:00Z }
id: rule-python-error-handling
cdr_ref: CDR-2026-001
created: 2026-04-15
verified:
  - { by: process:team-repair, at: 2026-05-18T00:00:00Z }
status: stable
stale_after: 180d
sources:
  - id: commit-abc123
    resource: src/errors.py
    title: Error handling implementation
---

Extraction logic:

  1. Read file content
  2. Check if starts with ---
  3. Parse YAML between --- markers
  4. Extract: id, cdr_ref, created, type, title, description, tags, generated.at, verified (latest at), status
Step 2a: Build CDR Lookup from Existing CDR.md

Before generating new frontmatter, read the existing CDR.md to find pre-existing CDR references for orphan files.

Parse the CDR.md index table to build a mapping of {relative_file_path → cdr_ref}:

# Read existing CDR.md and extract file path -> CDR reference mappings
CDR_LOOKUP=()
if [[ -f "{TEAM_AI_DIRECTIVES}/CDR.md" ]]; then
    while IFS='|' read -r _ id module _ _ _ _ _; do
        id="${id// /}"
        module="${module// /}"
        if [[ -n "$id" && -n "$module" && "$id" =~ ^CDR- ]]; then
            CDR_LOOKUP["$module"]="$id"
        fi
    done < <(grep "| CDR-" "{TEAM_AI_DIRECTIVES}/CDR.md")
fi

This creates an associative array:

context_modules/rules/style-guides/java/google_style_guide.md → CDR-2026-023
Step 3: Detect Orphans (No Frontmatter)

Files with .md extension but no YAML frontmatter.

For each orphan:

  1. Generate id from filename:
    • Strip the context type directory prefix (rules/, personas/, examples/)
    • Remove .md extension, replace / with -, prepend type prefix
    • Example: rules/python/new-pattern.md → strip rules/python/new-pattern.mdrule-python-new-pattern
    • Example: personas/architect.md → strip personas/architect.mdpersona-architect
  2. Determine context type from path:
    • rules/Rule
    • personas/Persona
    • examples/Example
  3. Compute the file's relative path from TEAM_AI_DIRECTIVES and look it up in CDR_LOOKUP:
    • If found, use the existing cdr_ref
    • If not found, set cdr_ref: null
  4. Generate title from filename (humanize the basename)
  5. Generate description from first paragraph or filename
  6. Generate tags from path segments (e.g., rules/python/[python])
  7. Set default metadata:
    type: {context-type}
    title: {generated-title}
    description: {generated-description}
    tags: {generated-tags}
    resource: {relative-path}
    generated: { by: agent:team-repair, at: {today}T00:00:00Z }
    id: {generated-id}
    cdr_ref: {from CDR_LOOKUP or null}
    created: {today}
    verified:
      - { by: agent:team-repair, at: {today}T00:00:00Z }
    status: stable
    stale_after: 180d
    

If --dry-run:

### Orphan Files Detected

| File | Generated ID | Existing CDR Ref | Action |
|------|--------------|-----------------|--------|
| rules/python/new-pattern.md | rule-python-new-pattern | CDR-2026-023 | Would add frontmatter (preserving CDR ref) |
| personas/architect.md | persona-architect | null | Would add frontmatter |

Otherwise, auto-fix:

  1. Read file content
  2. Prepend generated YAML frontmatter
  3. Write back to file
Step 3b: Migrate v0.1 Frontmatter to v0.2 (Always-On)

For every .md file in context_modules/ (excluding index.md, log.md) that has existing frontmatter, detect and migrate v0.1 fields to v0.2. This runs on every team-repair invocation — no flag, no opt-out.

Migration rules (idempotent — skip if already v0.2):

DetectionAction
timestamp: present, generated: absentRewrite to generated: { by: agent:legacy, at: <timestamp value> }, delete timestamp
timestamp: present, generated: presentDelete timestamp (v0.2 takes precedence)
verified: is a bare string (not a list)Rewrite to verified: [{ by: process:team-repair, at: <value>T00:00:00Z }]
evidence: present with entriesMap each entry to sources[] entry (id, resource, title), delete evidence
evidence: [] (empty list)Delete field, omit sources
modified: presentDelete (redundant with generated.at)
age_days: presentDelete (derived at render time)
status: absentAdd status: stable
stale_after: absentAdd stale_after: 180d
resource: absentAdd from file relative path
generated already present, no v0.1 fieldsSkip (already v0.2)

Preserve custom fields (id, cdr_ref, created, type, title, description, tags) as-is per OKF §4.1.

If --dry-run:

### v0.1 → v0.2 Migration Preview

| File | Fields Migrated | Fields Added | Fields Removed |
|------|----------------|--------------|----------------|
| rules/security/sql_injection_prevention.md | timestamp→generated, verified→list | status, stale_after, resource | modified, age_days, evidence |

Otherwise, rewrite frontmatter in place for each file.

Step 4: Build Context Module Index

Create index structure:

{
  "context_modules": [
    {
      "file": "context_modules/rules/python/error-handling.md",
      "id": "rule-python-error-handling",
      "cdr_ref": "CDR-2026-001",
      "type": "Rule",
      "created": "2026-04-15",
      "generated_at": "2026-04-15T00:00:00Z",
      "verified_at": "2026-05-18T00:00:00Z",
      "status": "stable",
      "stale_after": "180d",
      "descriptor": "Python error handling patterns and best practices"
    }
  ],
  "orphans": [
    {
      "file": "context_modules/rules/python/new-pattern.md",
      "id": "rule-python-new-pattern",
      "repaired": true
    }
  ]
}

Phase 5: Scan Skills for .skills.json Reindex

Objective: Find all skills and build manifest entries

Skip if: --index-only or --agents-only flag provided

Step 1: Find All Skill Directories
find "{TEAM_AI_DIRECTIVES}/skills" -mindepth 1 -maxdepth 1 -type d
Step 2: Check Each Skill

For each skill directory:

  1. Check SKILL.md exists (required)
  2. Check .skills-entry.json exists (optional)
  3. Parse SKILL.md for metadata
Step 3: Extract Skill Metadata

From SKILL.md:

  • Description: First paragraph after title
  • Categories: Look for ## Categories or ## Trigger Keywords section
  • Instruction Type: Look for **Instruction Type**: line
Step 4: Generate .skills.json Entry
{
  "local:./skills/{skill-name}": {
    "version": "1.0.0",
    "description": "{extracted from SKILL.md first paragraph}",
    "categories": ["{from SKILL.md}"],
    "instruction_type": "{from SKILL.md}"
  }
}
Step 5: Detect Orphans

Skills with SKILL.md but no entry in .skills.json.

If --dry-run:

### Orphan Skills Detected

| Skill | Action |
|-------|--------|
| code-review | Would add to .skills.json |
| deployment | Would add to .skills.json |

Otherwise, auto-generate entry.

Step 6: Detect Missing Files

Entries in .skills.json where skill directory doesn't exist.

Auto-remove invalid entries.

Step 7: Build Skills Index
{
  "skills": [
    {
      "name": "code-review",
      "path": "skills/code-review/",
      "has_skill_md": true,
      "has_entry": false,
      "repaired": true
    }
  ],
  "missing_removed": 1
}

Phase 6: Rebuild OKF index.md + log.md + Derive CDR.md

Objective: Generate OKF v0.2 per-directory index.md (§8) and log.md (§9) files from scanned context modules, then derive the flat CDR.md table from the index.md data for team-boot system prompt injection.

Skip if: --skills-only or --agents-only flag provided

Step 1: Rebuild Per-Directory index.md (OKF §8)

For each subdirectory (rules/, personas/, examples/) and the context_modules/ root, generate an index.md file in OKF §8 list format.

context_modules/index.md (root — carries okf_version):

---
okf_version: "0.2"
---

# Context Modules

* [Rules](rules/index.md) - Team rules and workflows
* [Personas](personas/index.md) - Team personas
* [Examples](examples/index.md) - Team examples

context_modules/rules/index.md (per-type catalog):

# Rules

* [Prevent SQL Injection](security/sql_injection_prevention.md) - Standards for preventing SQL injection vulnerabilities across all languages
* [Dependency Injection](architecture/dependency_injection.md) - Dependency injection patterns for maintainable code

Entries are derived from each module's frontmatter title and description. Sort alphabetically by title within each directory. If a module lacks description, derive from first body paragraph.

Personas and Examples follow the same pattern with # Personas and # Examples headings.

Step 2: Rebuild Per-Directory log.md (OKF §9)

For each subdirectory, generate a log.md file in OKF §9 date-grouped format (newest first).

context_modules/rules/log.md:

# Rules Update Log

## 2026-05-23
* **Creation**: Added [Dependency Injection](architecture/dependency_injection.md) — Dependency injection patterns for maintainable code. CDR: CDR-2026-008.
* **Verification**: Verified [SQL Injection Prevention](security/sql_injection_prevention.md). CDR: CDR-2026-021.

## 2026-05-21
* **Creation**: Added [SQL Injection Prevention](security/sql_injection_prevention.md) — Standards for preventing SQL injection. CDR: CDR-2026-021.

Log entries are derived from:

  1. Git history: git log --diff-filter=A --format="%ai %s" -- <file> for creation dates
  2. Frontmatter verified timestamps for verification entries
  3. Existing log.md content (preserve manual entries, append new)

context_modules/log.md (root — aggregate):

# Context Modules Update Log

## 2026-08-12
* **Re-index**: Rebuilt all index.md and log.md files via /team-repair. Rules: {N} files, Personas: {N} files, Examples: {N} files.
Step 3: Derive CDR.md (Flat Table for team-boot)

From the per-directory index.md data + module frontmatter, derive a flat CDR.md table for team-boot system prompt injection.

{TEAM_AI_DIRECTIVES}/CDR.md:

# Context Directive Records (Derived Index)

> ⚠️ Auto-generated by `/team-repair`. Do not edit manually.
> Source of truth: `context_modules/*/index.md` + module frontmatter.
> Decision lifecycle (Accepted/Rejected) lives in project `.adlc/drafts/cdr/`.

## CDR Index

| ID | Path | Type | Description | Generated | Verified | Age | Status |
|----|------|------|-------------|-----------|----------|-----|--------|
| CDR-2026-021 | context_modules/rules/security/sql_injection_prevention.md | Rule | Standards for preventing SQL injection... | 2026-06-14 | 2026-05-21 | 46d | stable |
| rule-frontend-routing | context_modules/rules/frontend/framework/frontend_routing.md | Rule | Client-side routing patterns... | 2026-06-15 | 2026-06-15 | 0d | stable |

**Stats**: {N} entries | Last Updated: {date}

Shortened here. Read the whole file on GitHub.

Signals

GitHub stars
133
Forks
1
Last commit
Sep 2026
Advanced
Catalog kind
skill
Gateway key
team-repair
Source
github.com/tikalk/adlc-team-skills