# Team Repair

> Re-index CDR.md, .skills.json, and AGENTS.md in team-ai-directives, 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.

- **Type:** Skill
- **Install:** `agentstack add skill-tikalk-adlc-team-skills-team-repair`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [tikalk](https://agentstack.voostack.com/s/tikalk)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [tikalk](https://github.com/tikalk)
- **Source:** https://github.com/tikalk/adlc-team-skills/tree/main/skills/team/team-repair
- **Website:** https://github.com/tikalk/agentic-sdlc-12-factors

## Install

```sh
agentstack add skill-tikalk-adlc-team-skills-team-repair
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# team-repair

## Overview

Re-index CDR.md, .skills.json, and AGENTS.md in team-ai-directives to fix inconsistencies, detect orphaned files, and auto-repair issues. 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, CDR tracking, constitution alignment, type field presence, project AGENTS.md directive)
1. Repaired AGENTS.md (if missing or corrupted)
2. Rebuilt CDR.md index from context_modules/
3. Rebuilt .skills.json manifest from skills/
4. Auto-added YAML frontmatter to orphan context modules (including OKF fields: `resource`, `tags`, `timestamp`)
5. Auto-generated .skills.json entries for orphan skills
6. Conflict scan across rules (creates conflict CDRs if issues found)
7. Freshness verification (updates `verified` timestamps, flags stale directives)
8. 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

| Target | Location | Purpose |
|--------|----------|---------|
| **AGENTS.md** | `{TEAM_AI_DIRECTIVES}/AGENTS.md` | Main instruction file for AI agents |
| **CDR.md** | `{TEAM_AI_DIRECTIVES}/CDR.md` | Index of approved context contributions |
| **.skills.json** | `{TEAM_AI_DIRECTIVES}/.skills.json` | Skills manifest registry |

## When to Use

### User Input

```text
$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
- `"--cdr-only"` - Only repair CDR.md
- `"--skills-only"` - Only repair .skills.json
- `"--agents-only"` - Only repair AGENTS.md
- Empty input: Repair all indexes with auto-fix

### Flags

| Flag | Description |
|------|-------------|
| `--dry-run` | Report only, don't write changes |
| `--health-only` | Run Phase 0 health check only, then stop. |
| `--validate` | Run conflict scan + freshness verification only (Phases 8-9) |
| `--conflicts` | Scan for rule conflicts only |
| `--freshness` | Verify directive freshness only |
| `--build-to-delete` | Run evals without directives to identify candidates for removal (Factor XII) |
| `--cdr-only` | Only repair CDR.md |
| `--skills-only` | Only repair .skills.json |
| `--agents-only` | Only repair AGENTS.md |
| (default) | Repair all indexes + 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: CDR Tracking

- `{TEAM_AI_DIRECTIVES}/CDR.md` exists

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 Type Field Presence

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. Output:
   - `[OK]` — All concept files have valid `type` fields
   - `[WARN]` — Some files missing `type` field (list files)

#### Check 7: Project AGENTS.md Directive

1. Read `{REPO_ROOT}/AGENTS.md` (the project-level agent instructions file)
2. Check if it contains the `` 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:

```json
{
  "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**: `--cdr-only` or `--skills-only` flag provided

#### Step 1: Check AGENTS.md Exists

```bash
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:
```bash
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

| Status | Action |
|--------|--------|
| **Missing** | Create from `templates/agents-template.md` |
| **Corrupted** (missing sections) | Overwrite with template |
| **Valid** | No changes |

If `--dry-run`:
```markdown
### AGENTS.md Status: {MISSING|CORRUPTED|VALID}

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

Otherwise, execute repair:
```bash
cp "templates/agents-template.md" "{TEAM_AI_DIRECTIVES}/AGENTS.md"
```

#### Step 4: Track Results

Store for summary:
```json
{
  "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
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`:
```markdown
### 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 `` and `` markers), it replaces the section in place rather than duplicating.

Store for summary:
```json
{
  "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

```bash
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:

```yaml
---
id: rule-python-error-handling
cdr_ref: CDR-2026-001
created: 2026-04-15
modified: 2026-05-18
verified: 2026-05-18
age_days: 33
evidence:
  - commit: abc123
  - file: src/errors.py
---
```

Extraction logic:
1. Read file content
2. Check if starts with `---`
3. Parse YAML between `---` markers
4. Extract: `id`, `cdr_ref`, `created`, `modified`, `verified`, `age_days`

#### 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}`:

```bash
# 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  "{TEAM_AI_DIRECTIVES}/CDR.md"  "{TEAM_AI_DIRECTIVES}/.skills.json"  30 or whose `verified` date is older than 30 days.

```markdown
### Stale Directives

| File | Age | Last Verified |
|---|---|---|
| rules/old-pattern.md | 45d | 2026-04-01 |
```

### Phase 10: Build to Delete (Factor XII)

**Objective**: Identify directives that are no longer needed because baseline models handle them natively. This is the "Harness Decay" mechanism — run evals without directives; if the model passes independently, the directive is a candidate for removal.

**Skip if**: `--build-to-delete` flag is NOT provided.

**This phase makes LLM calls** — it runs goldenset cases against the agent to test whether directives are still needed.

#### Step 1: Load All Goldensets

Read all goldenset directories from `{TEAM_AI_DIRECTIVES}/evals/`:

```bash
ls -1 "$TEAM_AI_DIRECTIVES/evals/" 2>/dev/null
```

For each `{directive-id}` directory, read:
- `evals/{directive-id}/goldset.md` — human-readable cases
- `evals/{directive-id}/goldset.json` — machine-readable cases

If no goldensets exist, report: "No evals found — run /levelup-specify to create eval CDRs first." and skip this phase.

#### Step 2: Identify Paired Directives

For each goldenset, identify its paired directive:
- Read `paired_directive` from the goldenset frontmatter
- Read the directive file from `context_modules/` (e.g., `rules/security/sql_injection_prevention.md`)
- If the directive file doesn't exist → skip (already deleted or orphaned eval)

#### Step 3: Run Goldenset Without Directive

For each directive+eval pair:

1. **Temporarily remove the directive** from the context that would be loaded (simulate: the agent works without the rule)
2. **Run the goldenset cases** against the agent via LLM calls:
   - For each pass case: present the scenario and input context, ask the agent to produce output, check if it follows the (removed) directive
   - For each fail case: present the scenario and input context, ask the agent to produce output, check if it still makes the mistake
3. **Compute pass rate**: `cases_passed / total_cases`

#### Step 4: Classify Results

| Pass Rate | Verdict | Recommendation |
|---|---|---|
| 100% | **Delete candidate** | Model handles this natively — directive is obsolete |
| 80-99% | **Review candidate** | Model mostly handles it — consider simplifying the directive |
| 30d) | {n} |
| Skipped (has conflicts) | {n} |

### Files Modified

| File | Change |
|------|--------|
| {file} | {change description} |

{If --dry-run:}
> **Note**: Dry run mode - no files were modified

### Next Steps

1. Review repaired files
2. If conflict CDRs were created, run `/levelup-clarify` to resolve them
3. Commit changes if satisfied
```

### Notes

- **Auto-fix**: Always repairs issues automatically (no confirmation needed)
- **Dry run**: Use `--dry-run` to preview changes without writing
- **Selective repair**: Use `--cdr-only`, `--skills-only`, or `--agents-only` for specific targets
- **Validation modes**: `--validate` runs conflict scan + freshness; `--conflicts` and `--freshness` run each separately
- **YAML frontmatter**: Auto-generated for orphan context modules
- **Skills entries**: Auto-generated from SKILL.md content
- **AGENTS.md**: Overwrites if corrupted (missing required sections)
- **Idempotent**: Re-running produces same result

## Common Rationalizations

| Rationalization | Reality |
|-----------------|---------|
| "The indexes look fine — no need to reindex." | Orphaned files and missing frontmatter are invisible without a full directory scan. |
| "I'll just hand-edit CDR.md to add the missing row." | Manual edits drift from actual content; a rebuild guarantees the index

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [tikalk](https://github.com/tikalk)
- **Source:** [tikalk/adlc-team-skills](https://github.com/tikalk/adlc-team-skills)
- **License:** MIT
- **Homepage:** https://github.com/tikalk/agentic-sdlc-12-factors

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-tikalk-adlc-team-skills-team-repair
- Seller: https://agentstack.voostack.com/s/tikalk
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
