team-repair
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, o
Install
npx skills add https://github.com/tikalk/adlc-team-skills/tree/main/skills/team/team-repair
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install tikalk-adlc-team-skills@llmmart
git clone https://github.com/tikalk/adlc-team-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole tikalk/adlc-team-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
team-repair
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)
- Repaired AGENTS.md (if missing or corrupted)
- Migrated all context module frontmatter from OKF v0.1 to v0.2 (always-on)
- Rebuilt per-directory
index.mdfiles (OKF §8 catalog) - Rebuilt per-directory
log.mdfiles (OKF §9 audit trail) - Derived
CDR.mdflat table fromindex.mdfiles (for team-boot system prompt injection) - Rebuilt .skills.json manifest from skills/
- Auto-added OKF v0.2 YAML frontmatter to orphan context modules
- Auto-generated .skills.json entries for orphan skills
- Conflict scan across rules (creates conflict CDRs if issues found)
- Freshness verification (updates
verifiedtimestamps, flags stale directives) - Draft validation report (if
--validate-drafts— read-only, no modifications) - 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 |
| index.md | {TEAM_AI_DIRECTIVES}/context_modules/**/index.md |
OKF §8 per-directory catalogs (progressive disclosure) |
| log.md | {TEAM_AI_DIRECTIVES}/context_modules/**/log.md |
OKF §9 per-directory audit trails |
| CDR.md | {TEAM_AI_DIRECTIVES}/CDR.md |
Derived flat table for team-boot system prompt injection (auto-generated from index.md files) |
| .skills.json | {TEAM_AI_DIRECTIVES}/.skills.json |
Skills 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"--validate-drafts"- Validate draft files in .adlc/drafts/ without modifying them- Empty input: Repair all indexes with auto-fix (includes v0.1→v0.2 migration)
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) |
--validate-drafts |
Validate draft files in .adlc/drafts/{adr,pdr,chdr,cdr,evals}/ — validation only, no modifications |
--update-confidence |
Aggregate usage data from adlc branch and update OKF frontmatter confidence scores |
--ensure-adlc |
Ensure the adlc orphan branch exists (create if missing) |
--index-only |
Only rebuild OKF index.md + log.md + derive CDR.md |
--skills-only |
Only repair .skills.json |
--agents-only |
Only 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 eight checks below. Each check prints a status line. If any check is [FAIL], abort repair.
Check 1: Team AI Directives Configured
- Read
.adlc/init-options.json - Verify
team_ai_directivesfield exists and points to valid path - Check the team AI directives path exists
Output: [OK] or [FAIL] with reason
Check 2: Context Modules Exist
- Read
.adlc/init-options.json→ get team AI directives path - 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.jsonexists and is valid JSON
Output: [OK] or [FAIL] with reason
Check 4: OKF Log Tracking
{TEAM_AI_DIRECTIVES}/context_modules/rules/log.mdexists{TEAM_AI_DIRECTIVES}/context_modules/personas/log.mdexists{TEAM_AI_DIRECTIVES}/context_modules/examples/log.mdexists{TEAM_AI_DIRECTIVES}/CDR.mdexists (derived artifact)
Output: [OK] or [FAIL] with reason
Check 5: Constitution Alignment
- Read team constitution from
{TEAM_AI_DIRECTIVES}/context_modules/constitution.md - Locate project constitution: the project root (where
.adlc/lives) →{REPO_ROOT}/.adlc/memory/constitution.md - 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
- If project constitution doesn't exist:
[INFO]— Project constitution doesn't exist yet (first-time setup)
Check 6: OKF v0.2 Conformance
- Scan all
.mdfiles incontext_modules/(excludingindex.md,log.md) - Parse YAML frontmatter from each file
- Verify
typefield is present and has a valid value:- Valid types:
Constitution,Persona,Rule,Example,Skill
- Valid types:
- Verify OKF v0.2 fields (migrate if v0.1 detected):
generated: { by, at }present (not legacytimestamp)verifiedis a list format (not bare string)statuspresent (e.g.,stable,draft,deprecated)stale_afterpresent (e.g.,180d)
- Output:
[OK]— All concept files have validtypefields 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
- Read
{REPO_ROOT}/AGENTS.md(the project-level agent instructions file) - Check if it contains the
<!-- TEAM_AI_DIRECTIVES START -->marker - If the marker exists, verify the managed section includes:
- A
team-bootinvocation directive - A reference to team AI directives context (constitution, CDR index)
- The Class Boots catalog (architect-boot / product-boot / change-boot / team-boot / tech-radar-boot)
- The compact Decision Capture triggers + Session Decision Ledger contract
- A
- 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-invoketeam-boot)[INFO]— Project AGENTS.md doesn't exist yet (first-time setup)
Check 8: Deterministic Enforcement Coverage
Advisory check — outputs [OK]/[WARN], never [FAIL] (deterministic-checks-first, EVAL-010). A missing guardrail is a finding on its own, not just a mistake's side effect.
- Scan rule CDRs in
{TEAM_AI_DIRECTIVES}/context_modules/rules/for mechanically-checkable patterns — fixed syntactic shapes, banned APIs, import shapes, file-location rules — that lack a paired deterministic check (unit test, binary grader, pre-commit hook, lint rule, or CI job) - Scan installed skills for missing eval coverage — a skill with neither a goldset criterion/grader nor a stated no-grader reason has no guardrail
Output:
[OK]— every mechanical rule has a paired check; every skill has eval coverage or a stated reason[WARN]— N mechanical rules lack checks; M skills lack eval coverage (promotion candidates → feed to factory-learn Maintenance route / team-learn Phase 2b, action P)
Check 9: adlc Orphan Branch
- Check if
git -C "$TEAM_AI_DIRECTIVES" show-ref --verify --quiet refs/heads/adlc - If missing, create it (call
setup-team.sh --ensure-adlcor create inline)
Output:
[OK]— adlc orphan branch exists withdrafts/cdr/andreports/structure[WARN]— adlc branch missing (auto-created during repair)[INFO]— adlc branch created
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.jsonis 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
| Status | Action |
|---|---|
| Missing | Create from ../templates/agents-template.md |
| Corrupted (missing sections) | Overwrite with template |
| Valid | No 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 7 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:
- Read file content
- Check if starts with
--- - Parse YAML between
---markers - Extract:
id,cdr_ref,created,type,title,description,tags,generated.at,verified(latestat),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:
- Generate
idfrom filename:- Strip the context type directory prefix (
rules/,personas/,examples/) - Remove
.mdextension, replace/with-, prepend type prefix - Example:
rules/python/new-pattern.md→ striprules/→python/new-pattern.md→rule-python-new-pattern - Example:
personas/architect.md→ strippersonas/→architect.md→persona-architect
- Strip the context type directory prefix (
- Determine context type from path:
rules/→Rulepersonas/→Personaexamples/→Example
- Compute the file's relative path from
TEAM_AI_DIRECTIVESand look it up inCDR_LOOKUP:- If found, use the existing
cdr_ref - If not found, set
cdr_ref: null
- If found, use the existing
- Generate
titlefrom filename (humanize the basename) - Generate
descriptionfrom first paragraph or filename - Generate
tagsfrom path segments (e.g.,rules/python/→[python]) - 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:
- Read file content
- Prepend generated YAML frontmatter
- 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):
| Detection | Action |
|---|---|
timestamp: present, generated: absent |
Rewrite to generated: { by: agent:legacy, at: <timestamp value> }, delete timestamp |
timestamp: present, generated: present |
Delete 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 entries |
Map each entry to sources[] entry (id, resource, title), delete evidence |
evidence: [] (empty list) |
Delete field, omit sources |
modified: present |
Delete (redundant with generated.at) |
age_days: present |
Delete (derived at render time) |
status: absent |
Add status: stable |
stale_after: absent |
Add stale_after: 180d |
resource: absent |
Add from file relative path |
generated already present, no v0.1 fields |
Skip (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:
- Check
SKILL.mdexists (required) - Check
.skills-entry.jsonexists (optional) - Parse SKILL.md for metadata
Step 3: Extract Skill Metadata
From SKILL.md:
- Description: First paragraph after title
- Categories: Look for
## Categoriesor## Trigger Keywordssection - 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:
- Git history:
git log --diff-filter=A --format="%ai %s" -- <file>for creation dates - Frontmatter
verifiedtimestamps for verification entries - Existing
log.mdcontent (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 branch 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}
Columns:
ID:cdr_reffrom frontmatter (oridifcdr_refis null)Path: relative path fromTEAM_AI_DIRECTIVESType:typefrom frontmatterDescription:descriptionfrom frontmatter (truncated to 80 chars)Generated:generated.atdate (YYYY-MM-DD)Verified: latestverified[].atdate (YYYY-MM-DD)Age: days sinceverifieddateStatus:statusfrom frontmatter (orstableif absent)
Step 4: Write Files
If --dry-run:
### OKF Files Preview
Would write:
- context_modules/index.md ({N} entries)
- context_modules/log.md
- context_modules/rules/index.md ({N} entries)
- context_modules/rules/log.md
- context_modules/personas/index.md ({N} entries)
- context_modules/personas/log.md
- context_modules/examples/index.md ({N} entries)
- context_modules/examples/log.md
- CDR.md ({N} derived entries)
Otherwise, write all 9 files.
Objective: Generate fresh .skills.json from scanned skills
Skip if: --index-only or --agents-only flag provided
Step 1: Generate Skills Manifest
{
"skills": {
"local:./skills/code-review": {
"version": "1.0.0",
"description": "Review code following team standards and best practices",
"categories": ["review", "quality"],
"instruction_type": "Review"
}
}
}
Step 2: Write .skills.json
If --dry-run:
### .skills.json Preview
Would write {N} skill entries
Otherwise:
cat > "{TEAM_AI_DIRECTIVES}/.skills.json" << 'EOF'
{generated JSON}
EOF
Phase 8: Conflict Scanning
Objective: Scan team-ai-directives rules for contradictions and overlaps.
Skip if: --skills-only, --agents-only, or --freshness flag provided.
Step 1: Load Rules and Constitution
Load:
{TEAM_AI_DIRECTIVES}/context_modules/constitution.md{TEAM_AI_DIRECTIVES}/context_modules/rules/**/*.md
Step 2: Detect Conflicts
Conflict levels:
| Level | Pattern | Severity |
|---|---|---|
| Direct Contradiction | must X vs never X |
CRITICAL |
| Implicit Contradiction | Numeric/logical impossibility | ERROR |
| Exception Conflict | Base rule vs exception | WARNING |
| Scope Overlap | Overlapping rules | INFO |
| Constitution Conflict | Rule vs principle | CRITICAL |
Use team-learn/scripts/helpers.sh conflict detection or implement inline:
skills/team/team-learn/scripts/helpers.sh --conflicts "$TEAM_AI_DIRECTIVES/context_modules/rules"
Step 3: Create Conflict CDRs
For each conflict, create a CDR in adlc branch drafts/cdr/CDR-{NNN}.md:
## CDR-{NNN}: Resolve Rule Conflict: {title}
### Status
**Discovered**
### Date
{today}
### Source
Rule conflict detection via /team-repair --validate
### Target Module
`context_modules/rules/{domain}/`
### Context Type
Rule
### Context
**Conflict Details**:
- Rule A: {path} — "{statement}"
- Rule B: {path} — "{statement}"
- Type: {critical|error|warning|info}
### Decision
**Proposed Resolution**:
1. Add exception
2. Edit rule to avoid conflict
3. Mark intentional
4. Deprecate one rule
Regenerate the local CDR index.
Handoff: if conflict CDRs created, suggest /team-learn.
Phase 9: Freshness Verification
Objective: Update verified timestamps for valid directives and flag stale ones.
Skip if: --skills-only, --agents-only, or --conflicts flag provided.
Step 1: Identify Valid Directives
For each context module file (rules, personas, examples, constitution) and skill SKILL.md:
- If no conflicts detected for this file → eligible for verification update
- If conflicts detected → skip (will be resolved via conflict CDRs)
Step 2: Update Verification Metadata
For each eligible directive:
- Parse YAML frontmatter
- Append to
verifiedlist:{ by: process:team-repair, at: {today}T00:00:00Z } - Update
generated.atif content changed during this repair run - Append verification entry to per-directory
log.md:
* **Verification**: Verified [{Title}](path) — no conflicts detected.
Step 3: Report Stale Directives
Flag directives whose latest verified[].at is older than stale_after (default 180d), or whose status is deprecated.
### Stale Directives
| File | Last Verified | Age | Stale After | Status |
|---|---|---|---|---|
| rules/old-pattern.md | 2026-04-01 | 190d | 180d | stale |
Phase 9b: Confidence Update
Skip if: --update-confidence flag is NOT provided.
Objective: Read usage data from adlc orphan branch, aggregate into
confidence scores, and update OKF frontmatter on main branch.
Step 1: Read Usage Data from adlc Branch
# Read all project usage files from adlc branch
for file in $(git -C "$TEAM_AI_DIRECTIVES" ls-tree --name-only "$ADLC_BRANCH" "reports/projects/" 2>/dev/null | grep '\.json$'); do
git -C "$TEAM_AI_DIRECTIVES" show "${ADLC_BRANCH}:${file}"
done
Step 2: Aggregate into confidence-scores.json
Merge all project JSONs, calculate:
usage_count: sum ofmatchedacross projectsapply_count: sum ofappliedacross projectssuccess_rate:apply_count / usage_countlast_used: most recentlast_usedacross projectstrend:rising(used in last 7 days),stable(last 30 days),falling(>30 days)projects: list of project names
Write to adlc branch: reports/confidence-scores.json.
Step 3: Update OKF Frontmatter on Main Branch
For each CDR in confidence-scores.json:
- Find corresponding context module file via
cdr_ref - Add/update
confidence:block in YAML frontmatter - Commit to main branch
Step 4: Rebuild CDR.md with Confidence Column
Add Confidence and Usage columns to the derived CDR.md table.
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/:
ls -1 "$TEAM_AI_DIRECTIVES/evals/" 2>/dev/null
For each {directive-id} directory, read:
evals/{directive-id}/goldset.md— human-readable casesevals/{directive-id}/goldset.json— machine-readable cases
If no goldensets exist, report: "No evals found — run /team-learn to create eval CDRs first." and skip this phase.
Step 2: Identify Paired Directives
For each goldenset, identify its paired directive:
- Read
paired_directivefrom 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:
- Temporarily remove the directive from the context that would be loaded (simulate: the agent works without the rule)
- 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
- 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 |
| < 80% | Keep | Model still needs the directive |
For every Keep (and Review candidate) verdict, ask the complementary promote-to-check question (EVAL-010): can a deterministic check (unit test / binary grader / pre-commit hook / lint rule / CI job) mechanically enforce this rule? If yes, it is a Promotion candidate — pay once for a check instead of re-injecting a fuzzy rule into every session.
Step 5: Generate Harness Decay Report
## Build to Delete Report
### Candidates for Removal (model passes 100% without directive)
| Directive | Eval | Pass Rate | Recommendation |
|---|---|---|---|
| rules/security/sql_injection.md | evals/CDR-001/ | 100% (6/6) | Delete — model handles this natively now |
### Review Candidates (80-99%)
| Directive | Eval | Pass Rate | Recommendation |
|---|---|---|---|
| rules/devops/helm_packaging.md | evals/CDR-008/ | 83% (5/6) | Simplify — model mostly handles it, 1 case failed |
### Still Needed (< 80%)
| Directive | Eval | Pass Rate | Recommendation |
|---|---|---|---|
| rules/style/python_pep8.md | evals/CDR-015/ | 40% (2/5) | Keep — model still needs guidance |
### Promotion Candidates (Keep, but check-enforceable)
| Directive | Eval | Pass Rate | Proposed Check |
|---|---|---|---|
| rules/architecture/import_boundaries.md | evals/CDR-011/ | 55% (3/5) | Promote to pre-commit lint rule — file-location pattern is mechanical |
Step 6: Create Deletion CDRs (and Promotion CDRs)
For each Delete candidate (100% pass rate), create a CDR in adlc branch drafts/cdr/CDR-{NNN}.md:
## CDR-{NNN}: Delete Directive: [Title]
### Status: **Discovered**
### Date: [YYYY-MM-DD]
### Source: Build to Delete via /team-repair --build-to-delete
### Target Module: `context_modules/rules/{domain}/{file}.md` + `evals/{directive-id}/`
### Context Type: Constitution Amendment
### Descriptor: Directive is obsolete — model handles natively without the rule.
### Context
The directive `{title}` was tested by running its goldenset cases without the directive loaded.
The model passed 100% of cases (N/N), indicating the baseline model now handles this pattern natively.
The directive is a candidate for Harness Decay removal.
### Decision
Delete both the directive file and its paired eval goldenset.
### Evidence
- Directive: context_modules/rules/{domain}/{file}.md
- Eval: evals/{directive-id}/goldset.md
- Pass rate: 100% (N/N cases passed without the directive)
- Test date: [YYYY-MM-DD]
Regenerate the local CDR index. Handoff: suggest /team-learn to review deletion candidates.
For each Promotion candidate, create a CDR in adlc branch drafts/cdr/CDR-{NNN}.md:
## CDR-{NNN}: Promote Directive to Deterministic Check: [Title]
### Status: **Discovered**
### Date: [YYYY-MM-DD]
### Source: Build to Delete via /team-repair --build-to-delete
### Target Module: `context_modules/rules/{domain}/{file}.md`
### Context Type: Rule
### Descriptor: Rule is mechanically enforceable — promote to a deterministic check.
### Context
The directive `{title}` survived build-to-delete (model still needs it, pass rate < 100%),
but its pattern is mechanical — a deterministic check (unit test / binary grader /
pre-commit hook / lint rule / CI job) can enforce it without session context.
### Decision
Build the deterministic check. Once it exists and runs in CI, deprecate the CDR
or reduce it to a thin pointer (`enforced by <check path>`). Route to
`/team-learn` action **P — Promote to check** (Phase 2b).
### Evidence
- Directive: context_modules/rules/{domain}/{file}.md
- Proposed check vehicle: [unit test | grader | pre-commit | lint | CI job]
- Pass rate without directive: N% (M/K cases) — rule still needed
- Test date: [YYYY-MM-DD]
Regenerate the local CDR index again. Handoff: suggest /team-learn to review promotion candidates (action P).
Phase 11: Validate Drafts
Objective: Validate draft decision records in .adlc/drafts/ for structural completeness — required frontmatter fields, required body sections, and valid enum values. This is a read-only validation mode — no files are created, modified, or deleted.
Skip if: --validate-drafts flag is NOT provided.
This phase makes NO LLM calls — it is purely mechanical file parsing and validation, like a linter.
Step 1: Scan Draft Directories
Scan all files in the following draft directories relative to {REPO_ROOT}:
.adlc/drafts/adr/
.adlc/drafts/pdr/
.adlc/drafts/chdr/
adlc branch drafts/cdr/
.adlc/drafts/evals/
For each directory, list all *.md files. If a directory does not exist, skip it silently (not an error — that draft type simply has no drafts).
If no draft files are found in any directory, report: "No draft files found in .adlc/drafts/ — nothing to validate." and skip this phase.
Step 2: Validate Frontmatter
For each draft file, parse YAML frontmatter (between --- delimiters) and verify the following required fields are present:
| Field | Required | Valid Values | Notes |
|---|---|---|---|
status |
Yes | proposed, accepted, rejected, deferred, superseded, discovered |
Case-insensitive match |
date |
Yes | Any non-empty string (expected YYYY-MM-DD) |
Must not be empty or placeholder |
type |
Yes | decision, product, pattern, incident, workaround, constraint, abandoned, eval |
Case-insensitive match |
evidence |
Yes | confirmed, inferred, unknown |
Case-insensitive match |
source |
Yes | Any non-empty string | Origin of the draft (skill name, session, etc.) |
revisit-when |
Yes (present) | Empty string, N/A, or any non-empty string |
Field must exist; value can be empty or N/A |
For each missing or invalid field, record:
- File path
- Line number (of the frontmatter key, or line 1 if frontmatter is entirely missing)
- Issue description (e.g., "Missing required field: status", "Invalid status value: 'draft' — expected one of: proposed, accepted, rejected, deferred, superseded, discovered")
Step 3: Validate Body Sections
After frontmatter, validate that the following required body sections are present as Markdown headings:
| Section | Required | Notes |
|---|---|---|
## Context (or ### Context) |
Yes | Must exist as a heading |
## Decision (or ### Decision) |
Yes | Must exist as a heading |
## Rejected Alternatives (or ### Rejected Alternatives) |
Yes | Must exist as a heading |
## Reason (or ### Reason) |
Yes | Must exist as a heading |
Heading level flexibility: accept ## or ### (or even ####) for each section. Match by heading text (case-insensitive, trimmed).
For each missing section, record:
- File path
- Line number (0 if section not found — report as "section not found")
- Issue description (e.g., "Missing required body section: Rejected Alternatives")
Step 4: Conditional Validation — Rejected Alternatives Non-Empty
For draft files where type is decision or abandoned, the ## Rejected Alternatives (or ### Rejected Alternatives) section must not be empty. "Empty" means:
- No content between the heading and the next heading or end of file
- Only whitespace or placeholder text (e.g., "N/A", "TBD", "TODO", "none")
For each violation, record:
- File path
- Line number of the heading
- Issue: "Rejected Alternatives section is empty for decision/abandoned type — must list at least one rejected alternative"
Step 5: Generate Validation Report
## Draft Validation Report
**Date**: {date}
**Mode**: VALIDATE ONLY (no modifications)
### Summary
| Metric | Count |
|--------|-------|
| Draft directories scanned | {n} |
| Draft files validated | {n} |
| Files with errors | {n} |
| Files with warnings | {n} |
| Files passing validation | {n} |
| Total findings | {n} |
### Findings
| Severity | File | Line | Issue |
|----------|------|------|-------|
| Error | .adlc/drafts/adr/ADR-301.md | 3 | Missing required field: evidence |
| Error | .adlc/drafts/adr/ADR-301.md | 0 | Missing required body section: Reason |
| Error | .adlc/drafts/pdr/PDR-005.md | 7 | Invalid status value: 'draft' — expected one of: proposed, accepted, rejected, deferred, superseded, discovered |
| Warning | adlc branch drafts/cdr/CDR-010.md | 15 | Rejected Alternatives section is empty for decision type — must list at least one rejected alternative |
{If no findings:}
> **All draft files passed validation — no issues found.**
Step 6: Handoff
- If errors were found: suggest fixing the draft files before promoting them via the appropriate clarify skill (
/architect-clarifyfor ADRs,/product-clarifyfor PDRs,/change-clarifyfor ChDRs,/team-learnfor CDRs). - If all drafts pass validation: confirm drafts are structurally ready for promotion.
- Remind: validation does not check semantic quality — only structural completeness. A draft that passes validation may still be rejected during clarification.
Phase 12: Summary Report
## Team Repair Summary
**Date**: {date}
**Team Directives**: {path}
**Mode**: {DRY RUN|LIVE}
### AGENTS.md Repair
| Status | Action |
|--------|--------|
| {VALID|CREATED|OVERWRITTEN} | {No changes needed|Created from template|Re-created from template} |
### OKF index.md + log.md + CDR.md Repair
| Action | Count |
|--------|-------|
| Files scanned | {n} |
| v0.1→v0.2 migrated | {n} |
| index.md files rebuilt | {n} |
| log.md files rebuilt | {n} |
| CDR.md derived entries | {n} |
| Orphans repaired | {n} |
| Missing removed | {n} |
### .skills.json Repair
| Action | Count |
|--------|-------|
| Skills scanned | {n} |
| Valid entries | {n} |
| Orphans repaired | {n} |
| Missing removed | {n} |
### Conflict Scanning
| Metric | Count |
|---|---|
| Conflicts detected | {n} |
| Conflict CDRs created | {n} |
| Critical | {n} |
| Error | {n} |
| Warning | {n} |
| Info | {n} |
### Freshness Verification
| Metric | Count |
|---|---|---|
| Directives updated | {n} |
| Stale directives (>30d) | {n} |
| Skipped (has conflicts) | {n} |
### Draft Validation
| Metric | Count |
|--------|-------|
| Draft files validated | {n} |
| Files with errors | {n} |
| Files with warnings | {n} |
| Files passing validation | {n} |
| Total findings | {n} |
{If --validate-drafts was not run:}
> **Note**: Draft validation not run (use `--validate-drafts` to validate .adlc/drafts/)
### 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 `/team-learn` to resolve them
3. Commit changes if satisfied
Notes
- Auto-fix: Always repairs issues automatically (no confirmation needed)
- Dry run: Use
--dry-runto preview changes without writing - Selective repair: Use
--index-only,--skills-only, or--agents-onlyfor specific targets - Validation modes:
--validateruns conflict scan + freshness;--conflictsand--freshnessrun each separately - Draft validation:
--validate-draftsvalidates.adlc/drafts/{adr,pdr,chdr,cdr,evals}/— read-only, no modifications (like--build-to-delete, it only reports findings) - 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 matches the filesystem. |
| "Dry run is unnecessary — just write the changes." | A dry run surfaces unexpected orphans and null CDR refs before any file is mutated. |
| "AGENTS.md looks valid, so I'll skip Phase 2." | Missing sections can be subtle (e.g., a renamed heading). Validation is cheap and idempotent. |
| "Skipping Step 5 — the project AGENTS.md is not my job." | The team AI directives' own AGENTS.md describes structure; the project-level AGENTS.md is what tells agents to invoke team-boot at session start. Without it, the directives remain invisible. |
| "I can skip the CDR_LOOKUP step for orphans." | Without the lookup, existing CDR refs are lost and orphaned entries get cdr_ref: null, breaking traceability. |
| "I'll just jump to the repair — no need for a health check first." | Phase 0 exists precisely because an unhealthy framework makes repairs dangerous or meaningless. Run it. |
"A [WARN] on Phase 0 is basically an [OK]." |
Warnings are non-blocking for exit code but often signal drift that becomes a [FAIL] later. Track warnings across runs. |
Red Flags
- Overwriting AGENTS.md without validating structure first — a "corrupted" verdict should require evidence of missing sections, not a hunch; otherwise custom content is destroyed.
- Generating
cdr_ref: nullwhen an existing CDR_LOOKUP entry exists — this silently severs the audit trail between a context module and its accepted CDR record. - Skipping the dry run when the orphan count is high — bulk auto-fix without review leads to fabricated IDs and metadata propagating into version control.
- Writing
.skills.jsonentries without parsing the actualSKILL.md— fabricated descriptions and categories make skills unsearchable and misrepresent capabilities. - Proceeding past Phase 2 when
TEAM_AI_DIRECTIVESis empty — operating without a configured repository writes to undefined paths and corrupts the wrong workspace. - Skipping Phase 0 Health Check — jumping straight into repairs without verifying the framework is installed risks writing to an absent or misconfigured workspace.
- Skipping Step 5 (project AGENTS.md injection) — the team AI directives' own
AGENTS.mddescribes its structure, but the project-levelAGENTS.mdis what tells agents to invoketeam-bootat session start. Without it, agents have no session-start instruction and the team AI directives remains invisible until manually loaded.
Verification
- Phase 0 Health Check passes all 8 checks (no
[FAIL]) before any repair is attempted. - AGENTS.md exists at
{TEAM_AI_DIRECTIVES}/AGENTS.mdand contains all six required sections. - Project-level
AGENTS.mdat{REPO_ROOT}/AGENTS.mdcontains the<!-- TEAM_AI_DIRECTIVES START -->managed section with the event-hook awareness note, fallbackteam-bootinvocation, Class Boots catalog, Team Context in Use output contract, and compact Decision Capture triggers. - CDR.md entry count equals the number of scanned context module
.mdfiles (excludingconstitution.md). - Every context module file under
context_modules/{rules,personas,examples}/has YAML frontmatter with a non-emptyidfield. - Every
cdr_refin orphan frontmatter matches the pre-existing CDR lookup (no regression tonullwhere a prior ref existed). - Every skill directory containing a
SKILL.mdhas a corresponding entry in.skills.json. - No
.skills.jsonentry references a skill directory that does not exist on disk. - The summary report lists non-zero counts for "Files scanned" / "Skills scanned" and shows consistent totals.
- Re-running the skill with no flags produces zero "Files Modified" entries (idempotency check).
- Conflict scan completed (if not skipped) and conflict CDRs created for any findings.
- Freshness verification completed (if not skipped) and stale directives reported.
- No rule contradictions remain unreported after
--validate. - If
--validate-draftswas run: every draft file in.adlc/drafts/{adr,pdr,chdr,cdr,evals}/was scanned and findings reported (if any). - If
--validate-draftswas run: no files in.adlc/drafts/were created, modified, or deleted (validation-only, read-only mode). - If
--validate-draftswas run: draft validation findings include file path, line number, and issue description for each finding.
Configuration
TEAM_AI_DIRECTIVES— Path to the team AI directives (overrides.adlc/init-options.json)..adlc/init-options.json— Project-level config file withteam_ai_directivesfield.- Default fallback:
team-ai-directives/relative to project root. team-helpers.sh/team-helpers.ps1— Shared scripts used for path resolution.
12-Factor Alignment
Factor XI (Directives as Code) — maintains integrity of version-controlled team directives.
Files (adlc-team-skills)
-
scripts
-
bash
-
setup-team.sh 7.6 KB
#!/usr/bin/env bash # setup-team.sh — Setup script for team-repair skill set -euo pipefail PROJECT_ROOT="${PROJECT_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" BRANCH="${BRANCH:-$(git branch --show-current 2>/dev/null || echo 'unknown')}" TEAM_AI_DIRECTIVES="" INIT_OPTIONS="${PROJECT_ROOT}/.adlc/init-options.json" if [[ -f "$INIT_OPTIONS" ]]; then TEAM_AI_DIRECTIVES=$(grep '"team_ai_directives"' "$INIT_OPTIONS" \ | sed 's/.*"team_ai_directives"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' \ | head -1) fi if [[ -z "$TEAM_AI_DIRECTIVES" || "$TEAM_AI_DIRECTIVES" = "null" ]]; then TEAM_AI_DIRECTIVES="${PROJECT_ROOT}/team-ai-directives" fi if [[ "${1:-}" == "--json" || "${1:-}" == "-Json" ]]; then printf '{"REPO_ROOT": "%s", "TEAM_AI_DIRECTIVES": "%s", "BRANCH": "%s"}\n' \ "$PROJECT_ROOT" "$TEAM_AI_DIRECTIVES" "$BRANCH" else echo "REPO_ROOT=$PROJECT_ROOT" echo "TEAM_AI_DIRECTIVES=$TEAM_AI_DIRECTIVES" echo "BRANCH=$BRANCH" fi ############################################################################### # ENSURE ADLC ORPHAN BRANCH ############################################################################### ensure_adlc_branch() { local td="${1:-$TEAM_AI_DIRECTIVES}" local adlc_branch="adlc" if [[ -z "$td" || ! -d "$td/.git" ]]; then echo "Skipping adlc branch creation — not a git repo: $td" return 0 fi if git -C "$td" show-ref --verify --quiet "refs/heads/$adlc_branch"; then echo "adlc branch already exists" return 0 fi echo "Creating adlc orphan branch..." local worktree="/tmp/adlc-init-$$" # Create orphan branch via worktree (doesn't touch main working tree) git -C "$td" worktree add --detach "$worktree" 2>/dev/null || { echo "Failed to create worktree — trying direct orphan branch creation" # Fallback: create orphan branch directly (requires clean working tree) local current_branch current_branch=$(git -C "$td" branch --show-current) git -C "$td" checkout --orphan "$adlc_branch" git -C "$td" rm -rf . 2>/dev/null || true mkdir -p "$td/drafts/cdr" "$td/reports/sessions" "$td/reports/projects" echo '{}' > "$td/reports/confidence-scores.json" touch "$td/drafts/cdr/.gitkeep" "$td/reports/sessions/.gitkeep" "$td/reports/projects/.gitkeep" git -C "$td" add -A git -C "$td" commit -m "Initialize adlc orphan branch (drafts + reports)" git -C "$td" checkout "$current_branch" 2>/dev/null || git -C "$td" checkout main 2>/dev/null || true git -C "$td" push origin "$adlc_branch" 2>/dev/null || true echo "adlc orphan branch created (direct)" return 0 } # In the detached worktree, create the orphan branch git -C "$worktree" checkout --orphan "$adlc_branch" # Remove all files from the orphan branch (start clean) git -C "$worktree" rm -rf . 2>/dev/null || true mkdir -p "$worktree/drafts/cdr" "$worktree/reports/sessions" "$worktree/reports/projects" echo '{}' > "$worktree/reports/confidence-scores.json" touch "$worktree/drafts/cdr/.gitkeep" "$worktree/reports/sessions/.gitkeep" "$worktree/reports/projects/.gitkeep" git -C "$worktree" add -A git -C "$worktree" commit -m "Initialize adlc orphan branch (drafts + reports)" git -C "$worktree" push origin "$adlc_branch" 2>/dev/null || true git -C "$td" worktree remove "$worktree" --force 2>/dev/null || true echo "adlc orphan branch created" } ############################################################################### # CONFIDENCE UPDATE FUNCTION (--update-confidence) ############################################################################### update_confidence() { local td="$TEAM_AI_DIRECTIVES" local adlc_branch="adlc" # Ensure adlc branch exists ensure_adlc_branch "$td" if ! git -C "$td" show-ref --verify --quiet "refs/heads/$adlc_branch"; then echo "adlc branch does not exist — cannot aggregate" return 0 fi local today today=$(date +%Y-%m-%d) _TMP_CONF=$(mktemp) trap 'rm -f "$_TMP_CONF" 2>/dev/null' EXIT cat > "$_TMP_CONF" << JSONHEAD { "last_updated": "$today", "cdrs": { JSONHEAD local first_entry=1 local project_files project_files=$(git -C "$td" ls-tree --name-only "$adlc_branch" "reports/projects/" 2>/dev/null | grep '\.json$') declare -A agg_usage=() declare -A agg_apply=() declare -A agg_last_used=() declare -A agg_projects=() for pf in $project_files; do local content content=$(git -C "$td" show "${adlc_branch}:${pf}" 2>/dev/null || echo "") [[ -z "$content" ]] && continue local project_name project_name=$(echo "$content" | grep '"project"' | sed 's/.*"project"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' | head -1) [[ -z "$project_name" ]] && project_name="unknown" local cdr_ids cdr_ids=$(echo "$content" | grep -oP '"CDR-[0-9]+"' | tr -d '"' | sort -u) for cdr_id in $cdr_ids; do local matched applied last_used matched=$(echo "$content" | grep -A10 "\"$cdr_id\"" | grep '"matched"' | sed 's/.*"matched"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/' | head -1) applied=$(echo "$content" | grep -A10 "\"$cdr_id\"" | grep '"applied"' | sed 's/.*"applied"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/' | head -1) last_used=$(echo "$content" | grep -A10 "\"$cdr_id\"" | grep '"last_used"' | sed 's/.*"last_used"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' | head -1) [[ -z "$matched" ]] && matched=0 [[ -z "$applied" ]] && applied=0 [[ -z "$last_used" ]] && last_used="" agg_usage[$cdr_id]=$(( ${agg_usage[$cdr_id]:-0} + matched )) agg_apply[$cdr_id]=$(( ${agg_apply[$cdr_id]:-0} + applied )) if [[ "$last_used" > "${agg_last_used[$cdr_id]:-}" ]]; then agg_last_used[$cdr_id]="$last_used" fi local existing="${agg_projects[$cdr_id]:-}" if [[ -z "$existing" ]]; then agg_projects[$cdr_id]="\"$project_name\"" elif ! echo "$existing" | grep -q "\"$project_name\""; then agg_projects[$cdr_id]="$existing, \"$project_name\"" fi done done for cdr_id in "${!agg_usage[@]}"; do local uc="${agg_usage[$cdr_id]}" local ac="${agg_apply[$cdr_id]}" local lu="${agg_last_used[$cdr_id]:-}" local success_rate="0.0" if [[ $uc -gt 0 ]]; then success_rate=$(awk "BEGIN { printf \"%.2f\", $ac / $uc }") fi local trend="unknown" if [[ -n "$lu" ]]; then local today_epoch lu_epoch today_epoch=$(date -d "$today" +%s 2>/dev/null || date -j -f "%Y-%m-%d" "$today" +%s 2>/dev/null || echo 0) lu_epoch=$(date -d "${lu:0:10}" +%s 2>/dev/null || date -j -f "%Y-%m-%d" "${lu:0:10}" +%s 2>/dev/null || echo 0) if [[ $today_epoch -gt 0 && $lu_epoch -gt 0 ]]; then local days=$(( (today_epoch - lu_epoch) / 86400 )) if [[ $days -le 7 ]]; then trend="rising" elif [[ $days -le 30 ]]; then trend="stable" else trend="falling" fi fi fi local projects_list="[${agg_projects[$cdr_id]}]" if [[ $first_entry -eq 0 ]]; then echo "," >> "$_TMP_CONF" fi first_entry=0 cat >> "$_TMP_CONF" << ENTRY "$cdr_id": { "usage_count": $uc, "apply_count": $ac, "success_rate": $success_rate, "last_used": "$lu", "trend": "$trend", "projects": $projects_list } ENTRY done cat >> "$_TMP_CONF" << JSONFOOT } } JSONFOOT cat "$_TMP_CONF" rm -f "$_TMP_CONF" } ############################################################################### # CLI ENTRY ############################################################################### if [[ "${1:-}" == "--ensure-adlc" ]]; then ensure_adlc_branch exit 0 fi if [[ "${1:-}" == "--update-confidence" ]]; then update_confidence exit 0 fi
-
-
powershell
-
setup-team.ps1 1.4 KB · in bundle
-
-
-
SKILL.md 50 KB
--- name: team-repair description: Use when indexes are inconsistent, orphans are detected, after bulk changes to team-ai-directives, or for periodic directives health validation; --build-to-delete proposes rules the model no longer needs; --validate-drafts validates draft files in .adlc/drafts/ without modifying them. disable-model-invocation: true --- # team-repair ## 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. Draft validation report (if `--validate-drafts` — read-only, no modifications) 12. 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 | | **index.md** | `{TEAM_AI_DIRECTIVES}/context_modules/**/index.md` | OKF §8 per-directory catalogs (progressive disclosure) | | **log.md** | `{TEAM_AI_DIRECTIVES}/context_modules/**/log.md` | OKF §9 per-directory audit trails | | **CDR.md** | `{TEAM_AI_DIRECTIVES}/CDR.md` | Derived flat table for team-boot system prompt injection (auto-generated from index.md files) | | **.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 - `"--index-only"` - Only rebuild OKF index.md + log.md + derive CDR.md - `"--skills-only"` - Only repair .skills.json - `"--agents-only"` - Only repair AGENTS.md - `"--validate-drafts"` - Validate draft files in .adlc/drafts/ without modifying them - Empty input: Repair all indexes with auto-fix (includes v0.1→v0.2 migration) ### 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) | | `--validate-drafts` | Validate draft files in .adlc/drafts/{adr,pdr,chdr,cdr,evals}/ — validation only, no modifications | | `--update-confidence` | Aggregate usage data from `adlc` branch and update OKF frontmatter confidence scores | | `--ensure-adlc` | Ensure the `adlc` orphan branch exists (create if missing) | | `--index-only` | Only rebuild OKF index.md + log.md + derive CDR.md | | `--skills-only` | Only repair .skills.json | | `--agents-only` | Only 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 eight 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) - The Class Boots catalog (architect-boot / product-boot / change-boot / team-boot / tech-radar-boot) - The compact Decision Capture triggers + Session Decision Ledger contract 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) #### Check 8: Deterministic Enforcement Coverage **Advisory check** — outputs `[OK]`/`[WARN]`, never `[FAIL]` (deterministic-checks-first, EVAL-010). A missing guardrail is a finding on its own, not just a mistake's side effect. 1. Scan rule CDRs in `{TEAM_AI_DIRECTIVES}/context_modules/rules/` for mechanically-checkable patterns — fixed syntactic shapes, banned APIs, import shapes, file-location rules — that lack a paired deterministic check (unit test, binary grader, pre-commit hook, lint rule, or CI job) 2. Scan installed skills for missing eval coverage — a skill with neither a goldset criterion/grader nor a stated no-grader reason has no guardrail Output: - `[OK]` — every mechanical rule has a paired check; every skill has eval coverage or a stated reason - `[WARN]` — N mechanical rules lack checks; M skills lack eval coverage (promotion candidates → feed to factory-learn Maintenance route / team-learn Phase 2b, action P) #### Check 9: adlc Orphan Branch 1. Check if `git -C "$TEAM_AI_DIRECTIVES" show-ref --verify --quiet refs/heads/adlc` 2. If missing, create it (call `setup-team.sh --ensure-adlc` or create inline) Output: - `[OK]` — adlc orphan branch exists with `drafts/cdr/` and `reports/` structure - `[WARN]` — adlc branch missing (auto-created during repair) - `[INFO]` — adlc branch created #### 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**: `--index-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 7 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 `<!-- TEAM_AI_DIRECTIVES START -->` and `<!-- TEAM_AI_DIRECTIVES END -->` 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 (OKF v0.2 form after migration): ```yaml --- 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}`: ```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 < <(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.md` → `rule-python-new-pattern` - Example: `personas/architect.md` → strip `personas/` → `architect.md` → `persona-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: ```yaml 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`: ```markdown ### 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): | Detection | Action | |---|---| | `timestamp:` present, `generated:` absent | Rewrite to `generated: { by: agent:legacy, at: <timestamp value> }`, delete `timestamp` | | `timestamp:` present, `generated:` present | Delete `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 entries | Map each entry to `sources[]` entry (`id`, `resource`, `title`), delete `evidence` | | `evidence: []` (empty list) | Delete field, omit `sources` | | `modified:` present | Delete (redundant with `generated.at`) | | `age_days:` present | Delete (derived at render time) | | `status:` absent | Add `status: stable` | | `stale_after:` absent | Add `stale_after: 180d` | | `resource:` absent | Add from file relative path | | `generated` already present, no v0.1 fields | Skip (already v0.2) | Preserve custom fields (`id`, `cdr_ref`, `created`, `type`, `title`, `description`, `tags`) as-is per OKF §4.1. If `--dry-run`: ```markdown ### 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: ```json { "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 ```bash 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 ```json { "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`: ```markdown ### 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 ```json { "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`): ```markdown --- 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): ```markdown # 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`**: ```markdown # 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): ```markdown # 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`**: ```markdown # 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 branch 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} ``` **Columns**: - `ID`: `cdr_ref` from frontmatter (or `id` if `cdr_ref` is null) - `Path`: relative path from `TEAM_AI_DIRECTIVES` - `Type`: `type` from frontmatter - `Description`: `description` from frontmatter (truncated to 80 chars) - `Generated`: `generated.at` date (YYYY-MM-DD) - `Verified`: latest `verified[].at` date (YYYY-MM-DD) - `Age`: days since `verified` date - `Status`: `status` from frontmatter (or `stable` if absent) #### Step 4: Write Files If `--dry-run`: ```markdown ### OKF Files Preview Would write: - context_modules/index.md ({N} entries) - context_modules/log.md - context_modules/rules/index.md ({N} entries) - context_modules/rules/log.md - context_modules/personas/index.md ({N} entries) - context_modules/personas/log.md - context_modules/examples/index.md ({N} entries) - context_modules/examples/log.md - CDR.md ({N} derived entries) ``` Otherwise, write all 9 files. **Objective**: Generate fresh .skills.json from scanned skills **Skip if**: `--index-only` or `--agents-only` flag provided #### Step 1: Generate Skills Manifest ```json { "skills": { "local:./skills/code-review": { "version": "1.0.0", "description": "Review code following team standards and best practices", "categories": ["review", "quality"], "instruction_type": "Review" } } } ``` #### Step 2: Write .skills.json If `--dry-run`: ```markdown ### .skills.json Preview Would write {N} skill entries ``` Otherwise: ```bash cat > "{TEAM_AI_DIRECTIVES}/.skills.json" << 'EOF' {generated JSON} EOF ``` ### Phase 8: Conflict Scanning **Objective**: Scan team-ai-directives rules for contradictions and overlaps. **Skip if**: `--skills-only`, `--agents-only`, or `--freshness` flag provided. #### Step 1: Load Rules and Constitution Load: - `{TEAM_AI_DIRECTIVES}/context_modules/constitution.md` - `{TEAM_AI_DIRECTIVES}/context_modules/rules/**/*.md` #### Step 2: Detect Conflicts Conflict levels: | Level | Pattern | Severity | |---|---|---| | Direct Contradiction | `must X` vs `never X` | CRITICAL | | Implicit Contradiction | Numeric/logical impossibility | ERROR | | Exception Conflict | Base rule vs exception | WARNING | | Scope Overlap | Overlapping rules | INFO | | Constitution Conflict | Rule vs principle | CRITICAL | Use `team-learn/scripts/helpers.sh` conflict detection or implement inline: ```bash skills/team/team-learn/scripts/helpers.sh --conflicts "$TEAM_AI_DIRECTIVES/context_modules/rules" ``` #### Step 3: Create Conflict CDRs For each conflict, create a CDR in `adlc branch drafts/cdr/CDR-{NNN}.md`: ```markdown ## CDR-{NNN}: Resolve Rule Conflict: {title} ### Status **Discovered** ### Date {today} ### Source Rule conflict detection via /team-repair --validate ### Target Module `context_modules/rules/{domain}/` ### Context Type Rule ### Context **Conflict Details**: - Rule A: {path} — "{statement}" - Rule B: {path} — "{statement}" - Type: {critical|error|warning|info} ### Decision **Proposed Resolution**: 1. Add exception 2. Edit rule to avoid conflict 3. Mark intentional 4. Deprecate one rule ``` Regenerate the local CDR index. Handoff: if conflict CDRs created, suggest `/team-learn`. ### Phase 9: Freshness Verification **Objective**: Update `verified` timestamps for valid directives and flag stale ones. **Skip if**: `--skills-only`, `--agents-only`, or `--conflicts` flag provided. #### Step 1: Identify Valid Directives For each context module file (rules, personas, examples, constitution) and skill SKILL.md: - If no conflicts detected for this file → eligible for verification update - If conflicts detected → skip (will be resolved via conflict CDRs) #### Step 2: Update Verification Metadata For each eligible directive: 1. Parse YAML frontmatter 2. Append to `verified` list: `{ by: process:team-repair, at: {today}T00:00:00Z }` 3. Update `generated.at` if content changed during this repair run 4. Append verification entry to per-directory `log.md`: ```markdown * **Verification**: Verified [{Title}](path) — no conflicts detected. ``` #### Step 3: Report Stale Directives Flag directives whose latest `verified[].at` is older than `stale_after` (default 180d), or whose `status` is `deprecated`. ```markdown ### Stale Directives | File | Last Verified | Age | Stale After | Status | |---|---|---|---|---| | rules/old-pattern.md | 2026-04-01 | 190d | 180d | stale | ``` ### Phase 9b: Confidence Update **Skip if**: `--update-confidence` flag is NOT provided. **Objective**: Read usage data from `adlc` orphan branch, aggregate into confidence scores, and update OKF frontmatter on main branch. #### Step 1: Read Usage Data from adlc Branch ```bash # Read all project usage files from adlc branch for file in $(git -C "$TEAM_AI_DIRECTIVES" ls-tree --name-only "$ADLC_BRANCH" "reports/projects/" 2>/dev/null | grep '\.json$'); do git -C "$TEAM_AI_DIRECTIVES" show "${ADLC_BRANCH}:${file}" done ``` #### Step 2: Aggregate into confidence-scores.json Merge all project JSONs, calculate: - `usage_count`: sum of `matched` across projects - `apply_count`: sum of `applied` across projects - `success_rate`: `apply_count / usage_count` - `last_used`: most recent `last_used` across projects - `trend`: `rising` (used in last 7 days), `stable` (last 30 days), `falling` (>30 days) - `projects`: list of project names Write to `adlc` branch: `reports/confidence-scores.json`. #### Step 3: Update OKF Frontmatter on Main Branch For each CDR in confidence-scores.json: 1. Find corresponding context module file via `cdr_ref` 2. Add/update `confidence:` block in YAML frontmatter 3. Commit to main branch #### Step 4: Rebuild CDR.md with Confidence Column Add `Confidence` and `Usage` columns to the derived CDR.md table. ### 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 /team-learn 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 | | < 80% | **Keep** | Model still needs the directive | For every **Keep** (and **Review candidate**) verdict, ask the complementary **promote-to-check** question (EVAL-010): can a deterministic check (unit test / binary grader / pre-commit hook / lint rule / CI job) mechanically enforce this rule? If yes, it is a **Promotion candidate** — pay once for a check instead of re-injecting a fuzzy rule into every session. #### Step 5: Generate Harness Decay Report ```markdown ## Build to Delete Report ### Candidates for Removal (model passes 100% without directive) | Directive | Eval | Pass Rate | Recommendation | |---|---|---|---| | rules/security/sql_injection.md | evals/CDR-001/ | 100% (6/6) | Delete — model handles this natively now | ### Review Candidates (80-99%) | Directive | Eval | Pass Rate | Recommendation | |---|---|---|---| | rules/devops/helm_packaging.md | evals/CDR-008/ | 83% (5/6) | Simplify — model mostly handles it, 1 case failed | ### Still Needed (< 80%) | Directive | Eval | Pass Rate | Recommendation | |---|---|---|---| | rules/style/python_pep8.md | evals/CDR-015/ | 40% (2/5) | Keep — model still needs guidance | ### Promotion Candidates (Keep, but check-enforceable) | Directive | Eval | Pass Rate | Proposed Check | |---|---|---|---| | rules/architecture/import_boundaries.md | evals/CDR-011/ | 55% (3/5) | Promote to pre-commit lint rule — file-location pattern is mechanical | ``` #### Step 6: Create Deletion CDRs (and Promotion CDRs) For each **Delete candidate** (100% pass rate), create a CDR in `adlc branch drafts/cdr/CDR-{NNN}.md`: ```markdown ## CDR-{NNN}: Delete Directive: [Title] ### Status: **Discovered** ### Date: [YYYY-MM-DD] ### Source: Build to Delete via /team-repair --build-to-delete ### Target Module: `context_modules/rules/{domain}/{file}.md` + `evals/{directive-id}/` ### Context Type: Constitution Amendment ### Descriptor: Directive is obsolete — model handles natively without the rule. ### Context The directive `{title}` was tested by running its goldenset cases without the directive loaded. The model passed 100% of cases (N/N), indicating the baseline model now handles this pattern natively. The directive is a candidate for Harness Decay removal. ### Decision Delete both the directive file and its paired eval goldenset. ### Evidence - Directive: context_modules/rules/{domain}/{file}.md - Eval: evals/{directive-id}/goldset.md - Pass rate: 100% (N/N cases passed without the directive) - Test date: [YYYY-MM-DD] ``` Regenerate the local CDR index. Handoff: suggest `/team-learn` to review deletion candidates. For each **Promotion candidate**, create a CDR in `adlc branch drafts/cdr/CDR-{NNN}.md`: ```markdown ## CDR-{NNN}: Promote Directive to Deterministic Check: [Title] ### Status: **Discovered** ### Date: [YYYY-MM-DD] ### Source: Build to Delete via /team-repair --build-to-delete ### Target Module: `context_modules/rules/{domain}/{file}.md` ### Context Type: Rule ### Descriptor: Rule is mechanically enforceable — promote to a deterministic check. ### Context The directive `{title}` survived build-to-delete (model still needs it, pass rate < 100%), but its pattern is mechanical — a deterministic check (unit test / binary grader / pre-commit hook / lint rule / CI job) can enforce it without session context. ### Decision Build the deterministic check. Once it exists and runs in CI, deprecate the CDR or reduce it to a thin pointer (`enforced by <check path>`). Route to `/team-learn` action **P — Promote to check** (Phase 2b). ### Evidence - Directive: context_modules/rules/{domain}/{file}.md - Proposed check vehicle: [unit test | grader | pre-commit | lint | CI job] - Pass rate without directive: N% (M/K cases) — rule still needed - Test date: [YYYY-MM-DD] ``` Regenerate the local CDR index again. Handoff: suggest `/team-learn` to review promotion candidates (action P). ### Phase 11: Validate Drafts **Objective**: Validate draft decision records in `.adlc/drafts/` for structural completeness — required frontmatter fields, required body sections, and valid enum values. This is a **read-only validation mode** — no files are created, modified, or deleted. **Skip if**: `--validate-drafts` flag is NOT provided. **This phase makes NO LLM calls** — it is purely mechanical file parsing and validation, like a linter. #### Step 1: Scan Draft Directories Scan all files in the following draft directories relative to `{REPO_ROOT}`: ``` .adlc/drafts/adr/ .adlc/drafts/pdr/ .adlc/drafts/chdr/ adlc branch drafts/cdr/ .adlc/drafts/evals/ ``` For each directory, list all `*.md` files. If a directory does not exist, skip it silently (not an error — that draft type simply has no drafts). If **no draft files are found in any directory**, report: "No draft files found in .adlc/drafts/ — nothing to validate." and skip this phase. #### Step 2: Validate Frontmatter For each draft file, parse YAML frontmatter (between `---` delimiters) and verify the following required fields are present: | Field | Required | Valid Values | Notes | |-------|----------|--------------|-------| | `status` | Yes | `proposed`, `accepted`, `rejected`, `deferred`, `superseded`, `discovered` | Case-insensitive match | | `date` | Yes | Any non-empty string (expected `YYYY-MM-DD`) | Must not be empty or placeholder | | `type` | Yes | `decision`, `product`, `pattern`, `incident`, `workaround`, `constraint`, `abandoned`, `eval` | Case-insensitive match | | `evidence` | Yes | `confirmed`, `inferred`, `unknown` | Case-insensitive match | | `source` | Yes | Any non-empty string | Origin of the draft (skill name, session, etc.) | | `revisit-when` | Yes (present) | Empty string, `N/A`, or any non-empty string | Field must exist; value can be empty or `N/A` | For each missing or invalid field, record: - File path - Line number (of the frontmatter key, or line 1 if frontmatter is entirely missing) - Issue description (e.g., "Missing required field: status", "Invalid status value: 'draft' — expected one of: proposed, accepted, rejected, deferred, superseded, discovered") #### Step 3: Validate Body Sections After frontmatter, validate that the following required body sections are present as Markdown headings: | Section | Required | Notes | |---------|----------|-------| | `## Context` (or `### Context`) | Yes | Must exist as a heading | | `## Decision` (or `### Decision`) | Yes | Must exist as a heading | | `## Rejected Alternatives` (or `### Rejected Alternatives`) | Yes | Must exist as a heading | | `## Reason` (or `### Reason`) | Yes | Must exist as a heading | Heading level flexibility: accept `##` or `###` (or even `####`) for each section. Match by heading text (case-insensitive, trimmed). For each missing section, record: - File path - Line number (0 if section not found — report as "section not found") - Issue description (e.g., "Missing required body section: Rejected Alternatives") #### Step 4: Conditional Validation — Rejected Alternatives Non-Empty For draft files where `type` is `decision` or `abandoned`, the `## Rejected Alternatives` (or `### Rejected Alternatives`) section **must not be empty**. "Empty" means: - No content between the heading and the next heading or end of file - Only whitespace or placeholder text (e.g., "N/A", "TBD", "TODO", "none") For each violation, record: - File path - Line number of the heading - Issue: "Rejected Alternatives section is empty for decision/abandoned type — must list at least one rejected alternative" #### Step 5: Generate Validation Report ```markdown ## Draft Validation Report **Date**: {date} **Mode**: VALIDATE ONLY (no modifications) ### Summary | Metric | Count | |--------|-------| | Draft directories scanned | {n} | | Draft files validated | {n} | | Files with errors | {n} | | Files with warnings | {n} | | Files passing validation | {n} | | Total findings | {n} | ### Findings | Severity | File | Line | Issue | |----------|------|------|-------| | Error | .adlc/drafts/adr/ADR-301.md | 3 | Missing required field: evidence | | Error | .adlc/drafts/adr/ADR-301.md | 0 | Missing required body section: Reason | | Error | .adlc/drafts/pdr/PDR-005.md | 7 | Invalid status value: 'draft' — expected one of: proposed, accepted, rejected, deferred, superseded, discovered | | Warning | adlc branch drafts/cdr/CDR-010.md | 15 | Rejected Alternatives section is empty for decision type — must list at least one rejected alternative | {If no findings:} > **All draft files passed validation — no issues found.** ``` #### Step 6: Handoff - If errors were found: suggest fixing the draft files before promoting them via the appropriate clarify skill (`/architect-clarify` for ADRs, `/product-clarify` for PDRs, `/change-clarify` for ChDRs, `/team-learn` for CDRs). - If all drafts pass validation: confirm drafts are structurally ready for promotion. - Remind: validation does not check semantic quality — only structural completeness. A draft that passes validation may still be rejected during clarification. ### Phase 12: Summary Report ```markdown ## Team Repair Summary **Date**: {date} **Team Directives**: {path} **Mode**: {DRY RUN|LIVE} ### AGENTS.md Repair | Status | Action | |--------|--------| | {VALID|CREATED|OVERWRITTEN} | {No changes needed|Created from template|Re-created from template} | ### OKF index.md + log.md + CDR.md Repair | Action | Count | |--------|-------| | Files scanned | {n} | | v0.1→v0.2 migrated | {n} | | index.md files rebuilt | {n} | | log.md files rebuilt | {n} | | CDR.md derived entries | {n} | | Orphans repaired | {n} | | Missing removed | {n} | ### .skills.json Repair | Action | Count | |--------|-------| | Skills scanned | {n} | | Valid entries | {n} | | Orphans repaired | {n} | | Missing removed | {n} | ### Conflict Scanning | Metric | Count | |---|---| | Conflicts detected | {n} | | Conflict CDRs created | {n} | | Critical | {n} | | Error | {n} | | Warning | {n} | | Info | {n} | ### Freshness Verification | Metric | Count | |---|---|---| | Directives updated | {n} | | Stale directives (>30d) | {n} | | Skipped (has conflicts) | {n} | ### Draft Validation | Metric | Count | |--------|-------| | Draft files validated | {n} | | Files with errors | {n} | | Files with warnings | {n} | | Files passing validation | {n} | | Total findings | {n} | {If --validate-drafts was not run:} > **Note**: Draft validation not run (use `--validate-drafts` to validate .adlc/drafts/) ### 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 `/team-learn` 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 `--index-only`, `--skills-only`, or `--agents-only` for specific targets - **Validation modes**: `--validate` runs conflict scan + freshness; `--conflicts` and `--freshness` run each separately - **Draft validation**: `--validate-drafts` validates `.adlc/drafts/{adr,pdr,chdr,cdr,evals}/` — read-only, no modifications (like `--build-to-delete`, it only reports findings) - **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 matches the filesystem. | | "Dry run is unnecessary — just write the changes." | A dry run surfaces unexpected orphans and null CDR refs before any file is mutated. | | "AGENTS.md looks valid, so I'll skip Phase 2." | Missing sections can be subtle (e.g., a renamed heading). Validation is cheap and idempotent. | | "Skipping Step 5 — the project AGENTS.md is not my job." | The team AI directives' own AGENTS.md describes structure; the project-level AGENTS.md is what tells agents to invoke `team-boot` at session start. Without it, the directives remain invisible. | | "I can skip the CDR_LOOKUP step for orphans." | Without the lookup, existing CDR refs are lost and orphaned entries get `cdr_ref: null`, breaking traceability. | | "I'll just jump to the repair — no need for a health check first." | Phase 0 exists precisely because an unhealthy framework makes repairs dangerous or meaningless. Run it. | | "A `[WARN]` on Phase 0 is basically an `[OK]`." | Warnings are non-blocking for exit code but often signal drift that becomes a `[FAIL]` later. Track warnings across runs. | ## Red Flags - **Overwriting AGENTS.md without validating structure first** — a "corrupted" verdict should require evidence of missing sections, not a hunch; otherwise custom content is destroyed. - **Generating `cdr_ref: null` when an existing CDR_LOOKUP entry exists** — this silently severs the audit trail between a context module and its accepted CDR record. - **Skipping the dry run when the orphan count is high** — bulk auto-fix without review leads to fabricated IDs and metadata propagating into version control. - **Writing `.skills.json` entries without parsing the actual `SKILL.md`** — fabricated descriptions and categories make skills unsearchable and misrepresent capabilities. - **Proceeding past Phase 2 when `TEAM_AI_DIRECTIVES` is empty** — operating without a configured repository writes to undefined paths and corrupts the wrong workspace. - **Skipping Phase 0 Health Check** — jumping straight into repairs without verifying the framework is installed risks writing to an absent or misconfigured workspace. - **Skipping Step 5 (project AGENTS.md injection)** — the team AI directives' own `AGENTS.md` describes its structure, but the **project-level** `AGENTS.md` is what tells agents to invoke `team-boot` at session start. Without it, agents have no session-start instruction and the team AI directives remains invisible until manually loaded. ## Verification - [ ] Phase 0 Health Check passes all 8 checks (no `[FAIL]`) before any repair is attempted. - [ ] AGENTS.md exists at `{TEAM_AI_DIRECTIVES}/AGENTS.md` and contains all six required sections. - [ ] Project-level `AGENTS.md` at `{REPO_ROOT}/AGENTS.md` contains the `<!-- TEAM_AI_DIRECTIVES START -->` managed section with the event-hook awareness note, fallback `team-boot` invocation, Class Boots catalog, Team Context in Use output contract, and compact Decision Capture triggers. - [ ] CDR.md entry count equals the number of scanned context module `.md` files (excluding `constitution.md`). - [ ] Every context module file under `context_modules/{rules,personas,examples}/` has YAML frontmatter with a non-empty `id` field. - [ ] Every `cdr_ref` in orphan frontmatter matches the pre-existing CDR lookup (no regression to `null` where a prior ref existed). - [ ] Every skill directory containing a `SKILL.md` has a corresponding entry in `.skills.json`. - [ ] No `.skills.json` entry references a skill directory that does not exist on disk. - [ ] The summary report lists non-zero counts for "Files scanned" / "Skills scanned" and shows consistent totals. - [ ] Re-running the skill with no flags produces zero "Files Modified" entries (idempotency check). - [ ] Conflict scan completed (if not skipped) and conflict CDRs created for any findings. - [ ] Freshness verification completed (if not skipped) and stale directives reported. - [ ] No rule contradictions remain unreported after `--validate`. - [ ] If `--validate-drafts` was run: every draft file in `.adlc/drafts/{adr,pdr,chdr,cdr,evals}/` was scanned and findings reported (if any). - [ ] If `--validate-drafts` was run: no files in `.adlc/drafts/` were created, modified, or deleted (validation-only, read-only mode). - [ ] If `--validate-drafts` was run: draft validation findings include file path, line number, and issue description for each finding. ## Configuration - `TEAM_AI_DIRECTIVES` — Path to the team AI directives (overrides `.adlc/init-options.json`). - `.adlc/init-options.json` — Project-level config file with `team_ai_directives` field. - Default fallback: `team-ai-directives/` relative to project root. - `team-helpers.sh` / `team-helpers.ps1` — Shared scripts used for path resolution. ## 12-Factor Alignment Factor XI (Directives as Code) — maintains integrity of version-controlled team directives. -
team-helpers.ps1 14.8 KB · in bundle
-
team-helpers.sh 16.9 KB
#!/usr/bin/env bash # team-helpers.sh — Shared utilities for team-* skills # # Flags: # --json Output path info as JSON (default: key=value) # --scaffold [DIR] Create a fresh 11-file team AI directives scaffold at DIR # --agents-only DIR Create only AGENTS.md at DIR (for repair use) # --inject-agents [DIR] Inject team-boot directive into project-level AGENTS.md at DIR # --name NAME Team name for scaffold (default: "My Team") set -euo pipefail ############################################################################### # 1. PATH RESOLUTION ############################################################################### resolve_paths() { PROJECT_ROOT="${PROJECT_ROOT:-$([[ -d ".adlc" ]] && pwd || git rev-parse --show-toplevel 2>/dev/null || pwd)}" BRANCH="${BRANCH:-$(git branch --show-current 2>/dev/null || echo 'unknown')}" TEAM_AI_DIRECTIVES="" # 1. Check TEAM_AI_DIRECTIVES env var (highest priority) if [[ -n "${TEAM_AI_DIRECTIVES:-}" ]]; then TEAM_AI_DIRECTIVES="$TEAM_AI_DIRECTIVES" fi # 2. Check .adlc/init-options.json if [[ -z "$TEAM_AI_DIRECTIVES" ]]; then INIT_OPTIONS="${PROJECT_ROOT}/.adlc/init-options.json" if [[ -f "$INIT_OPTIONS" ]]; then TEAM_AI_DIRECTIVES=$(python3 -c " import json, sys try: with open('$INIT_OPTIONS') as f: print(json.load(f).get('team_ai_directives', '')) except Exception: print('') " 2>/dev/null || true) fi fi # 3. Fallback to default path if [[ -z "$TEAM_AI_DIRECTIVES" ]]; then TEAM_AI_DIRECTIVES="${PROJECT_ROOT}/team-ai-directives" fi echo "PROJECT_ROOT=$PROJECT_ROOT" echo "TEAM_AI_DIRECTIVES=$TEAM_AI_DIRECTIVES" echo "BRANCH=$BRANCH" } output_json() { printf '{"REPO_ROOT": "%s", "TEAM_AI_DIRECTIVES": "%s", "BRANCH": "%s"}\n' \ "$PROJECT_ROOT" "$TEAM_AI_DIRECTIVES" "$BRANCH" } ############################################################################### # 2. TEAM AI DIRECTIVES STRUCTURE VALIDATION ############################################################################### validate_team_ai_directives() { local dir="$1" local missing=0 for required in \ "context_modules/constitution.md" \ "context_modules/rules" \ "context_modules/personas" \ "context_modules/examples" \ "CDR.md" \ ".skills.json"; do if [[ ! -e "${dir}/${required}" ]]; then echo "MISSING: ${required}" missing=$((missing + 1)) fi done return "$missing" } ############################################################################### # 3. SCAFFOLD ############################################################################### scaffold_team_ai_directives() { local dest="$1" local team_name="${2:-My Team}" local today today=$(date +%Y-%m-%d) if [[ -d "$dest" && -n "$(ls -A "$dest" 2>/dev/null)" ]]; then echo "ERROR: Destination '$dest' already exists and is not empty." >&2 exit 1 fi mkdir -p "${dest}/context_modules/rules" mkdir -p "${dest}/context_modules/personas" mkdir -p "${dest}/context_modules/examples" mkdir -p "${dest}/skills" cat > "${dest}/README.md" << README # ${team_name} Team AI Directives Team AI directives repository for ${team_name}. ## Getting Started 1. Wire this directives repository into a project: \`\`\` /team-setup \`\`\` Choose "Point to existing local path" and select this directory. 2. Add context modules to \`context_modules/\` (rules, personas, examples). 3. Add skills to \`skills/\` and register them in \`.skills.json\`. 4. Update \`CDR.md\` as context modules are approved. See [ADLC Team Skills](https://github.com/tikalk/adlc-team-skills) for full documentation. README cat > "${dest}/AGENTS.md" << 'AGENTS' # Agent Instructions ## Structure - `context_modules/constitution.md` — Team constitution - `context_modules/rules/` — Team rules and workflows - `context_modules/personas/` — Team personas - `context_modules/examples/` — Team examples - `skills/` — Team skills - `evals/` — Directive compliance goldensets (pass/fail cases) - `CDR.md` — Context Directive Records ## Loading Order 1. Load constitution.md first 2. Load relevant rules for the current task 3. Load relevant personas for the current task 4. Load relevant examples for the current task ## Using Skills Skills are located in the `skills/` directory. Browse available skills using team-skills and install them as needed. ## CDR.md The CDR.md file tracks approved context contributions. Update it when adding new context modules. AGENTS cat > "${dest}/CDR.md" << CDR # Context Directive Records Context Directive Records (CDRs) track decisions about contributing context modules (rules, personas, examples, skills) to team-ai-directives. ## CDR Index | ID | Target Module | Type | Status | Created | Verified | Age | Descriptor | |----|---------------|------|--------|---------|----------|-----|------------| **Stats**: 0 entries | Last Updated: ${today} CDR cat > "${dest}/.skills.json" << 'SKILLSJSON' { "version": "2.0.0", "source": "team-ai-directives", "description": "Team skills manifest. The `default` list contains skill names that are auto-installed during project setup. The `external` map contains on-demand skills fetched by URL. The `blocked` list contains skills that must never be installed.", "default": [], "external": {}, "blocked": [], "policy": { "auto_install_default": true, "enforce_blocked": true, "allow_project_override": true } } SKILLSJSON cat > "${dest}/.mcp.json.example" << 'MCPJSON' { "mcpServers": {} } MCPJSON cat > "${dest}/context_modules/constitution.md" << CONSTITUTION --- type: Constitution title: "${team_name} Constitution" description: "Team-wide principles and governance" resource: ./context_modules/constitution.md tags: [constitution] generated: { by: agent:team-setup, at: ${today}T00:00:00Z } id: constitution cdr_ref: null created: ${today} verified: - { by: agent:team-setup, at: ${today}T00:00:00Z } status: stable stale_after: 180d --- # ${team_name} Constitution No team-wide principles defined yet. Add principles as they are established. CONSTITUTION cat > "${dest}/context_modules/index.md" << 'INDEXTOP' --- 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 INDEXTOP cat > "${dest}/context_modules/log.md" << 'LOGTOP' # Context Modules Update Log LOGTOP cat > "${dest}/context_modules/rules/index.md" << 'INDEXRULES' # Rules No rules defined yet. Use /team-learn to create rules via CDRs. INDEXRULES cat > "${dest}/context_modules/rules/log.md" << 'LOGRULES' # Rules Update Log LOGRULES cat > "${dest}/context_modules/personas/index.md" << 'INDEXPERS' # Personas No personas defined yet. Use /team-learn to create personas via CDRs. INDEXPERS cat > "${dest}/context_modules/personas/log.md" << 'LOGPERS' # Personas Update Log LOGPERS cat > "${dest}/context_modules/examples/index.md" << 'INDEXEX' # Examples No examples defined yet. Use /team-learn to create examples via CDRs. INDEXEX cat > "${dest}/context_modules/examples/log.md" << 'LOGEX' # Examples Update Log LOGEX cat > "${dest}/CDR.md" << 'CDRDERIVED' # 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 the `adlc` orphan branch `drafts/cdr/`. ## CDR Index | ID | Path | Type | Description | Generated | Verified | Age | Status | |----|------|------|-------------|-----------|----------|-----|--------| **Stats**: 0 entries | Last Updated: PLACEHOLDER CDRDERIVED touch "${dest}/context_modules/rules/.gitkeep" touch "${dest}/context_modules/personas/.gitkeep" touch "${dest}/context_modules/examples/.gitkeep" touch "${dest}/skills/.gitkeep" echo "Scaffolded team-ai-directives at ${dest}" echo "Team name: ${team_name}" echo "Files created: 14" validate_team_ai_directives "$dest" || true } scaffold_agents_only() { local dest="$1" mkdir -p "$dest" cat > "${dest}/AGENTS.md" << 'AGENTS' # Agent Instructions ## Structure - `context_modules/constitution.md` — Team constitution - `context_modules/rules/` — Team rules and workflows - `context_modules/personas/` — Team personas - `context_modules/examples/` — Team examples - `skills/` — Team skills - `reports/sessions/` — Published session summaries (from `/team-learn`, on `adlc` branch) - `CDR.md` — Context Directive Records ## Loading Order 1. Load constitution.md first 2. Load relevant rules for the current task 3. Load relevant personas for the current task 4. Load relevant examples for the current task ## Using Skills Skills are located in the `skills/` directory. Browse available skills using team-skills and install them as needed. ## CDR.md The CDR.md file tracks approved context contributions. Update it when adding new context modules. AGENTS echo "Created AGENTS.md at ${dest}" } ############################################################################### # 4. INJECT PROJECT-LEVEL AGENTS.md DIRECTIVE ############################################################################### inject_project_agents() { local project_root="${1:-.}" local team_directive="${2:-}" # Resolve team_ai_directives if not provided if [[ -z "$team_directive" ]]; then local init_options="${project_root}/.adlc/init-options.json" if [[ -f "$init_options" ]]; then team_directive=$(python3 -c " import json, sys try: with open('$init_options') as f: print(json.load(f).get('team_ai_directives', '')) except Exception: print('') " 2>/dev/null || true) fi fi # Fallback to env var if [[ -z "$team_directive" ]] && [[ -n "${TEAM_AI_DIRECTIVES:-}" ]]; then team_directive="$TEAM_AI_DIRECTIVES" fi # Fallback to default path if [[ -z "$team_directive" ]]; then team_directive="${project_root}/team-ai-directives" fi local agents_file="${project_root}/AGENTS.md" local marker_start="<!-- TEAM_AI_DIRECTIVES START -->" local marker_end="<!-- TEAM_AI_DIRECTIVES END -->" # Build the managed section local section section=$(cat <<SECTION ${marker_start} # Team AI Directives This project is bound by the team AI directives repository at \`${team_directive}\`. team-boot runs automatically at session start via the event hook (for agents with event support), injecting a lean orientation into the first user message with the team constitution, CDR index, Class Boots catalog, skills registry, and MCP servers. If the team AI directives context is NOT in your system prompt or first user message (agent without event support), invoke the \`team-boot\` skill before responding to any task or question. If team AI directives are unconfigured, invoke the \`team-setup\` skill. Invoke the matching class boot when a task or decision matches a row: ## Class Boots | Boot | Injects | Invoke When | Capture Via | |--|--|--|--| | architect-boot | ADR index (.adlc/memory/adr/) | architecture work; tech-stack/pattern choice | /architect-specify | | product-boot | PDR index (.adlc/memory/pdr/) | product/feature scope, personas, monetization | /product-specify | | change-boot | ChDR index (.adlc/memory/chdr.md) | change-history rationale, reverts, issue-linked commits | /change-init | | team-boot | CDR module bodies (team-ai-directives) | CDR descriptor match; reusable team pattern | /team-learn | | tech-radar-boot | Tikal Tech Radar context | choosing/evaluating technology | radar context + /architect-specify | Each class boot emits its class context section and its own searched line (_Searched N records, K matched._). **Every response MUST include** a Team Context in Use section before the task answer: ## Team Context in Use | ID | Name | Type | Rel | |--|--|--|--| | CDR-YYYY-NNN | <name> | <type> | <relevance> | Plus: \`_Searched N CDRs, M skills, J matched._\` — **J MUST equal the number of rows in your table; if no CDRs/skills genuinely match, show an empty table with 0 matched (do not copy a hard-coded CDR or inflate the count).** ## Decision Capture Detect decisions as they emerge; full detection and capture guidance lives in the matching class boot: - Tech stack / pattern choice → ADR → /architect-specify (pull tech-radar-boot context first for tech selection) - Feature scope / persona / monetization → PDR → /product-specify - Reusable team rule / pattern → CDR → /team-learn - Revert/hotfix rationale / issue-linked commit → ChDR → /change-init Maintain a running Session Decision Ledger in every response (after the Team Context in Use table): | Decision | Type | Captured? | Skill | |----------|------|-----------|-------| | _none yet_ | — | — | — | _Unrecorded: N pending._ At session end, prompt to invoke the capture skills for any unrecorded decisions. Only suggest capture when genuinely warranted. ${marker_end} SECTION ) # Create AGENTS.md if it doesn't exist, or update the managed section python3 - "$agents_file" "$marker_start" "$marker_end" "$section" <<'PY' import os, sys agents_path, start, end, section_content = sys.argv[1:5] if os.path.exists(agents_path): with open(agents_path, "r", encoding="utf-8") as f: content = f.read() else: content = "" # Check if markers already exist s_idx = content.find(start) e_idx = content.find(end) if s_idx != -1 and e_idx != -1 and s_idx < e_idx: # Replace existing managed section new_content = content[:s_idx] + section_content + content[e_idx + len(end):] if new_content.endswith("\n"): new_content += "\n" elif not new_content.endswith("\n\n"): new_content += "\n" with open(agents_path, "w", encoding="utf-8") as f: f.write(new_content) print(f"Updated team AI directives section in {agents_path}") else: # Append managed section if content and not content.endswith("\n"): content += "\n" if content and not content.endswith("\n\n"): content += "\n" content += section_content + "\n" with open(agents_path, "w", encoding="utf-8") as f: f.write(content) print(f"Injected team AI directives section into {agents_path}") PY } ############################################################################### # MAIN ############################################################################### main() { if [[ "$#" -eq 0 ]]; then resolve_paths return fi local has_json=false local has_scaffold=false local has_agents_only=false local has_inject_agents=false local scaffold_dest="" local agents_only_dest="" local inject_dest="" local team_name="My Team" local parsing_scaffold=false local parsing_agents=false local parsing_name=false local parsing_inject=false for arg in "$@"; do if [[ "$arg" == "--json" || "$arg" == "-Json" ]]; then has_json=true continue fi if [[ "$arg" == "--help" || "$arg" == "-h" ]]; then echo "Usage: team-helpers.sh [--json] [--scaffold DIR] [--agents-only DIR] [--inject-agents [DIR]] [--name NAME]" exit 0 fi if [[ "$arg" == "--scaffold" ]]; then has_scaffold=true parsing_scaffold=true parsing_agents=false parsing_name=false parsing_inject=false continue fi if [[ "$arg" == "--agents-only" ]]; then has_agents_only=true parsing_agents=true parsing_scaffold=false parsing_name=false parsing_inject=false continue fi if [[ "$arg" == "--inject-agents" ]]; then has_inject_agents=true parsing_inject=true parsing_scaffold=false parsing_agents=false parsing_name=false continue fi if [[ "$arg" == "--name" ]]; then parsing_name=true parsing_scaffold=false parsing_agents=false parsing_inject=false continue fi if $parsing_scaffold && [[ -n "$arg" ]]; then scaffold_dest="$arg" parsing_scaffold=false continue fi if $parsing_agents && [[ -n "$arg" ]]; then agents_only_dest="$arg" parsing_agents=false continue fi if $parsing_inject && [[ -n "$arg" ]]; then inject_dest="$arg" parsing_inject=false continue fi if $parsing_name && [[ -n "$arg" ]]; then team_name="$arg" parsing_name=false continue fi done if $has_scaffold; then if [[ -z "$scaffold_dest" ]]; then echo "ERROR: --scaffold requires a destination directory argument" >&2 exit 1 fi scaffold_team_ai_directives "$scaffold_dest" "$team_name" return fi if $has_agents_only; then if [[ -z "$agents_only_dest" ]]; then echo "ERROR: --agents-only requires a destination directory argument" >&2 exit 1 fi scaffold_agents_only "$agents_only_dest" return fi if $has_inject_agents; then local project_root="${inject_dest:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" inject_project_agents "$project_root" return fi # Default: resolve paths resolve_paths > /dev/null if $has_json; then output_json else resolve_paths fi } main "$@"
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.