22 validated skills and 4 specialized agents for systematic AI methodology engineering via OCA cycles and dual-layer value functions

version
1.4.0
GitHub stars
7

Install

/plugin install baime@baime

Run it inside Claude Code after adding the marketplace with /plugin marketplace add yaleh/baime.

Contents

Discovered from source

Skills 3

λ(topic) → epicToBacklog(topic)

Spec

EpicConfig :: { testCmd : String, -- per-phase test runner; carried into child plans later testAll : String, -- full suite; carried into child plans later docPath : String -- root for proposals/ and plans/ subdirectories }

loadConfig :: () → EpicConfig -- see spec-stdlib § loadConfig loadConfig() = | fromClaudeMd() -- explicit: "## L0 Config" section in CLAUDE.md | autoDetect() -- implicit: probe package.json, go.mod, Cargo.toml, etc.

autoDetect :: () → EpicConfig autoDetect() = -- see spec-stdlib § loadConfig

detectLang :: () → Lang -- see spec-stdlib § detectLang -- see spec-stdlib § detectLang

-- Core document types

EpicProposal :: { background : String, -- WHY this epic is needed (3-8 lines) goals : [VerifiableGoal], -- each Goal checkable by inspection or shell command sketch : [SubTaskHint], -- rough decomposition: the would-be child basic tasks tradeoffs : String -- what we are NOT doing; known risks }

SubTaskHint :: { title : String, -- candidate child basic-task title oneLine : String -- one-line description of that child's scope }

EpicPlan :: { background : String, -- carried from approved proposal goals : [VerifiableGoal], subTasks : [SubTaskHint], -- "Sub-Task Decomposition": intended child basic tasks sequencing : String, -- ordering / dependency notes between children constraints : [String] -- non-executable criteria for the epic as a whole }

-- Input: topic is either a task ID (e.g. TASK-12, task-12) or a free-form description. -- Task ID → resolve existing epic; resume from its current status using its description as draft. -- Description → create a new epic and run the full proposal → plan workflow.

EntryPoint = ProposalLoop | PlanLoop -- ProposalLoop : enter proposal reviewLoop (new epic, or Epic: Proposal status) -- PlanLoop : skip proposal; enter plan reviewLoop (Epic: Plan status)

resolveOrCreate :: Topic → (Task, EntryPoint) resolveOrCreate(T) = | isTaskId(T) → (lookupTask(T), fromStatus(lookupTask(T).status)) | otherwise → (createEpicTask(T), ProposalLoop)

fromStatus :: Status → EntryPoint fromStatus("Epic: Plan") = PlanLoop fromStatus(_) = ProposalLoop -- Epic: Proposal or other

createEpicTask :: Topic → Task -- creates with kind:epic label and Epic: Proposal status createEpicTask(T) = backlogTaskCreate({ title: T, status: "Epic: Proposal", labels: ["kind:epic"], description: T })

-- Workflow

epicToBacklog :: Topic → EpicTask epicToBacklog(T) = { cfg: loadConfig(), (task, entry): resolveOrCreate(T), -- proposalLoop: use existing description as proposal draft (skips fresh draft if task ID given) -- planLoop: skip proposal stage entirely proposal: case entry of ProposalLoop → proposalLoop(task, task.description, 8) PlanLoop → task.description -- not used; plan stage reads task.description directly plan: case entry of ProposalLoop → planLoop(task, draftEpicPlan(task, proposal, cfg), 8) PlanLoop → planLoop(task, task.description, 8) -- description IS the plan draft _: finalise(task, proposal, plan, cfg), return: task -- status: Epic: Backlog }

-- proposalLoop / planLoop are reviewLoop instantiations (MaxRounds = 8) proposalLoop :: (Task, Doc, Int) → ApprovedDoc proposalLoop(task, doc, n) = reviewLoop(task, doc, n) -- see spec-stdlib § reviewLoop -- human approves: Epic: Proposal → Epic: Plan

planLoop :: (Task, Doc, Int) → ApprovedDoc planLoop(task, doc, n) = reviewLoop(task, doc, n) -- see spec-stdlib § reviewLoop -- human approves: Epic: Plan → Epic: Backlog

-- Proposal review invariants (all must hold for APPROVED)

reviewProposal :: EpicProposal → Verdict reviewProposal(P) = { assert: explainsWhy(P.background), -- Background states WHY, 3-8 lines assert: ∀goal ∈ P.goals: verifiable(goal), assert: ¬empty(P.sketch), -- decomposition sketch must exist assert: identified(P.tradeoffs), return: APPROVED | NEEDS_REVISION }

-- Plan review invariants (all must hold for APPROVED)

reviewPlan :: EpicPlan → Verdict reviewPlan(P) = { assert: ¬empty(P.subTasks), -- Sub-Task Decomposition must list children assert: ∀st ∈ P.subTasks: hasOneLine(st), -- each child has title + one-line assert: ∀goal ∈ P.goals: coveredBy(goal, P.subTasks), assert: coherent(P.sequencing), return: APPROVED | NEEDS_REVISION }

-- This skill stops at Epic: Backlog. It creates NO child tasks and performs NO -- decomposition. The epic DAG continues only after a human promotes the epic: -- Epic: Backlog → Epic: Ready → (autonomous) Epic: Decomposing → -- Epic: Awaiting Children → Epic: Evaluating → Epic: Done | Epic: Needs Human

Implementation

loadConfig

REPO_ROOT=$(git rev-parse --show-toplevel)

resolveBaimeScripts() {
  local proj_scripts="${REPO_ROOT}/.claude/plugins/baime/scripts"
  if [ -d "$proj_scripts" ]; then echo "$proj_scripts"; return 0; fi
  for settings_file in "${HOME}/.claude/settings.json" "${HOME}/.claude/settings.local.json"; do
    if [ -f "$settings_file" ]; then
      local baime_path
      baime_path=$(python3 -c "
import json, sys
try:
  d = json.load(open('$settings_file'))
  for mp in d.get('extraKnownMarketplaces', []):
    p = mp.get('path', '')
    if 'baime' in p:
      import os
      scripts = os.path.join(p, 'scripts')
      if os.path.isdir(scripts):
        print(scripts)
        sys.exit(0)
except Exception:
  pass
" 2>/dev/null || true)
      if [ -n "$baime_path" ]; then echo "$baime_path"; return 0; fi
    fi
  done
  local xdg_scripts="${XDG_DATA_HOME:-${HOME}/.local/share}/baime/scripts"
  if [ -d "$xdg_scripts" ]; then echo "$xdg_scripts"; return 0; fi
  echo "resolveBaimeScripts: ERROR — cannot locate BAIME plugin scripts directory." >&2
  return 1
}
BAIME_SCRIPTS=$(resolveBaimeScripts) || exit 1

# --- fromClaudeMd ---
L0_SECTION=$(awk '/^## L0 Config/{found=1; next} found && /^## /{exit} found{print}' \
  "${REPO_ROOT}/CLAUDE.md" 2>/dev/null)

parse_cfg() { echo "$L0_SECTION" | grep -oP "(?<=^$1:\s)\S.*" | head -1 | xargs; }

CFG_TEST_CMD=$(parse_cfg "test-cmd")
CFG_TEST_ALL=$(parse_cfg "test-all")
CFG_DOC_PATH=$(parse_cfg "doc-path")

# --- autoDetect fallback ---
if [ -z "$L0_SECTION" ]; then
  if   [ -f "${REPO_ROOT}/package.json"  ]; then LANG=node
  elif [ -f "${REPO_ROOT}/go.mod"        ]; then LANG=go
  elif [ -f "${REPO_ROOT}/Cargo.toml"    ]; then LANG=rust
  elif [ -f "${REPO_ROOT}/pyproject.toml" ] || [ -f "${REPO_ROOT}/setup.py" ]; then LANG=python
  else LANG=unknown; fi

  case "$LANG" in
    node)   CFG_TEST_CMD="${CFG_TEST_CMD:-npm test -- --run}"; CFG_TEST_ALL="${CFG_TEST_ALL:-npm test}" ;;
    go)     CFG_TEST_CMD="${CFG_TEST_CMD:-go test ./...}";    CFG_TEST_ALL="${CFG_TEST_ALL:-go test ./...}" ;;
    rust)   CFG_TEST_CMD="${CFG_TEST_CMD:-cargo test}";       CFG_TEST_ALL="${CFG_TEST_ALL:-cargo test --workspace}" ;;
    python) CFG_TEST_CMD="${CFG_TEST_CMD:-pytest -k}";        CFG_TEST_ALL="${CFG_TEST_ALL:-pytest}" ;;
    *)      CFG_TEST_CMD="${CFG_TEST_CMD:-make test}";        CFG_TEST_ALL="${CFG_TEST_ALL:-make test}" ;;
  esac
  CFG_DOC_PATH="${CFG_DOC_PATH:-docs}"
  echo "L0 auto-detected config: lang=${LANG} testCmd=${CFG_TEST_CMD} testAll=${CFG_TEST_ALL} docPath=${CFG_DOC_PATH}"
else
  CFG_TEST_CMD="${CFG_TEST_CMD:-make test}"
  CFG_TEST_ALL="${CFG_TEST_ALL:-make test}"
  CFG_DOC_PATH="${CFG_DOC_PATH:-docs}"
  echo "L0 config loaded from CLAUDE.md: testCmd=${CFG_TEST_CMD} testAll=${CFG_TEST_ALL} docPath=${CFG_DOC_PATH}"
fi

Derive slug and title from <topic>:

SLUG=$(echo "<topic>" | tr '[:upper:] ' '[:lower:]-' | tr -cd '[:alnum:]-' | cut -c1-50)
TITLE=$(echo "<topic>" | cut -c1-70)

If <topic> is empty: print usage and stop.


Phase 0: Manifest Generation and Lint

Before executing any phase, generate a manifest JSON that describes the planned execution:

{
  "skill": "epic-to-backlog",
  "task_id": null,
  "entry_point": "createEpicTask",
  "skip_draft": false,
  "field_writes": [
    { "tool": "backlog task edit", "field": "plan", "source": "$TMPDIR/etb-plan.md" },
    { "tool": "backlog task edit", "field": "status", "value": "Epic: Backlog" }
  ],
  "phases_to_execute": ["createEpicTask", "proposalLoop", "planLoop", "finalise"]
}

Write the manifest to $TMPDIR/epic-to-backlog-manifest.json, then validate it:

bash "$BAIME_SCRIPTS/skill-lint.sh" --manifest "$TMPDIR/epic-to-backlog-manifest.json"

If validation fails, stop and report the error before proceeding.


Phase 1: resolveOrCreate + maybe draftProposal

1a. resolveOrCreate (orchestrator runs directly):

if echo "<topic>" | grep -qiP '^task-\d+$'; then
  # Existing epic path — resolve and extract description as initial draft
  TASK_ID=$(echo "<topic>" | tr '[:lower:]' '[:upper:]')
  backlog task view "$TASK_ID" --plain > $TMPDIR/etb-existing-task.txt
  echo "$TASK_ID" > $TMPDIR/etb-task-id.txt
  # Extract description block into etb-proposal.md (reused as proposal or plan draft)
  awk '/^Description:/{found=1;next} found && /^-{10,}/{if(!sep){sep=1;next};exit} found && sep{print}' \
    $TMPDIR/etb-existing-task.txt > $TMPDIR/etb-proposal.md
  # Determine entry point from status
  TASK_STATUS=$(grep -oP '(?<=Status:).*' $TMPDIR/etb-existing-task.txt | head -1 | grep -oP '(Basic|Epic): [A-Za-z ]+' | head -1 | xargs)
  case "$TASK_STATUS" in
    "Epic: Plan") echo "PlanLoop"     > $TMPDIR/etb-entry-point.txt ;;
    *)            echo "ProposalLoop" > $TMPDIR/etb-entry-point.txt ;;
  esac
else
  # New topic path — create epic task with kind:epic label at Epic: Proposal
  backlog task create "$TITLE" \
    --status "Epic: Proposal" \
    --labels "kind:epic" \
    --description "<topic>" \
    --plain
  # Extract task ID from output line `Task TASK-N`. Write to $TMPDIR/etb-task-id.txt.
  echo "ProposalLoop" > $TMPDIR/etb-entry-point.txt
fi

If $TMPDIR/etb-entry-point.txt contains PlanLoop: skip phase 1b and phases 2–3; proceed directly to Phase 4 using $TMPDIR/etb-proposal.md as the plan draft (rename it to $TMPDIR/etb-plan.md).

1b. draftAndReview — spawn Task agent (label: "Draft epic proposal with built-in self-review"; only when entry point is ProposalLoop AND topic is a new description; skip if existing task ID was given — its description is already in $TMPDIR/etb-proposal.md):

Draft an epic proposal with built-in self-review.

Task ID: <TASK_ID>

You have up to 3 total rounds. Start at round 1.

Round start:

  1. Search the codebase to understand current architecture relevant to: <topic>

  2. Write (or revise) $TMPDIR/etb-proposal.md:

    # Epic Proposal: <title>
    
    ## Background
    (3-8 lines: WHY this epic is needed, what cross-cutting problem it solves)
    
    ## Goals
    1. (concrete, verifiable outcome for the epic as a whole)
    2. ...
    
    ## Decomposition Sketch
    (Rough list of the would-be child sub-tasks this epic will spawn.
     One bullet per candidate basic task — title plus a one-line scope.
     This is a SKETCH; the firm decomposition is produced in the Plan stage.)
    - <candidate child title> — <one-line scope>
    - ...
    
    ## Trade-offs and Risks
    (What we are not doing, known risks, alternatives considered)
    
  3. Self-review — check ALL of the following:

    • Motivation: Does Background explain WHY (not just WHAT)? Is it 3-8 lines?
    • Goals: All numbered and concretely verifiable? No vague language?
    • Decomposition Sketch: Present and lists ≥2 candidate child sub-tasks, each with a one-line scope? Do the children collectively cover the Goals?
    • Feasibility: Does the epic align with the codebase? (you already searched)
    • Completeness: Are trade-offs and risks identified?
    • Consistency: No contradictions between sections?

4a. ALL criteria pass:

backlog task edit <TASK_ID> \
  --plan "$(cat $TMPDIR/etb-proposal.md)" \
  --append-notes "Epic proposal self-review: APPROVED"
echo "APPROVED" > $TMPDIR/etb-proposal-verdict.txt

在写 APPROVED 时,把 verdict 扩展为结构化前提账本(premise-ledger): 对你检查的每条 criterion,追加一行 [E|C|H] <criterion>: <你判断所凭的前提>, 分类规则:E=该前提可直接从本任务 task 文件读到;C=须跳转外部 task/doc/parent 才能确认; H=任何 artifact 都没有、靠背景知识或记忆推断。 末尾追加一行 GCL-self-report: E=<n> C=<n> H=<n>(各类计数)。 写法示例: backlog task edit <TASK_ID> --append-notes "Epic proposal self-review: APPROVED premise-ledger: [E] background lines: 背景段行数从 proposal 文件直接数 [C] decomposition coverage: 子任务覆盖了 Goals(须对照每条 Goal) [H] epic 粒度基准: 何为'合理的 epic 粒度'靠背景知识判断 GCL-self-report: E=1 C=2 H=1" Immediately after writing the GCL-self-report note, append one line to docs/research/gcl-events.jsonl (gate_type=proposal, task_kind=epic):

python3 -c "
import json, datetime
record = {
'task_id': '<TASK_ID>',
'gate_type': 'proposal',
'task_kind': 'epic',
'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
'E': <E>, 'C': <C>, 'H': <H>, 'GCL': <E>+<C>+<H>,
'reviewer_model': 'claude-sonnet-4-6',
'sample_run_id': None,
'evidence_independence': 'low',
'gate_actor_type': 'llm',
'premise_lines': <count of premise-ledger lines>
}
with open('docs/research/gcl-events.jsonl', 'a') as f:
 f.write(json.dumps(record) + '\n')
"

Replace <TASK_ID>, <E>, <C>, <H> with the actual values from the self-report.

Reliability sampling (~10% of gates): After appending the primary JSONL record above, check whether this task falls in the ~10% reliability sample:

import hashlib
if int(hashlib.md5('<TASK_ID>'.encode()).hexdigest(), 16) % 10 == 0:

If and only if the condition is true, perform a second independent GCL self-report pass:

  • Re-read the same gate content (epic proposal) with fresh eyes, as if reviewing it for the first time.
  • Produce a second premise-ledger with its own E/C/H counts (may differ from run 1).
  • Append a second JSONL line to docs/research/gcl-events.jsonl with the same fields but 'sample_run_id': '<TASK_ID>-r2' (instead of None).
  • Log intra-rater-variance: |H_run1 - H_run2| by appending to the task notes:
    backlog task edit <TASK_ID> --append-notes "reliability-sample: intra-rater-variance H=|<H_run1>-<H_run2>|=<diff>"
    

If the condition is false, skip this block entirely (no second pass, no extra JSONL line).

Print: "Proposal APPROVED. Proceeding to epic plan draft."

4b. ANY criterion fails AND round < 3: fix the failing sections in $TMPDIR/etb-proposal.md, update task:

backlog task edit <TASK_ID> --plan "$(cat $TMPDIR/etb-proposal.md)"
echo "NEEDS_REVISION" > $TMPDIR/etb-proposal-verdict.txt

Increment round and repeat from Round start.

4c. ANY criterion fails AND round == 3: update task and stop:

backlog task edit <TASK_ID> \
  --plan "$(cat $TMPDIR/etb-proposal.md)" \
  --status "Epic: Needs Human" \
  --append-notes "Epic proposal self-review did not converge after 3 rounds. Manual review required."
echo "NEEDS_REVISION" > $TMPDIR/etb-proposal-verdict.txt

Print current $TMPDIR/etb-proposal.md and STOP.

Rules: Background must state WHY, not just WHAT. Each Goal must be verifiable. The Decomposition Sketch must list at least two candidate child sub-tasks. Do NOT create any child tasks. No implementation phases or DoD commands here.


Phase 2: self-review (integrated into Phase 1b)

For new-description topics (ProposalLoop entry), proposal self-review is handled inside the draftAndReview agent in Phase 1b — no separate review agent is spawned.

For existing task ID topics (PlanLoop entry), no proposal review is needed; proceed directly to Phase 3 (draftEpicPlan) or Phase 4 (planLoop).


Phase 3: draftEpicPlan

If $TMPDIR/etb-entry-point.txt contains PlanLoop: $TMPDIR/etb-plan.md already holds the task's existing description as the plan draft — skip this phase and proceed directly to Phase 4.

backlog task edit $TASK_ID \
  --status "Epic: Plan" \
  --append-notes "Epic proposal approved. Starting epic plan draft."

Spawn Task agent (pass CFG_TEST_CMD, CFG_TEST_ALL, CFG_DOC_PATH as literal values):

Draft an epic plan and update the backlog task.

Task ID: <TASK_ID> Test command (carried into children): <CFG_TEST_CMD> Full suite command (carried into children): <CFG_TEST_ALL> Doc root: <CFG_DOC_PATH>

  1. Read the approved proposal from $TMPDIR/etb-proposal.md

  2. Search the codebase to firm up the intended child sub-tasks and their boundaries.

  3. Write $TMPDIR/etb-plan.md:

    # Epic Plan: <title>
    
    ## Background
    (carried from the approved proposal)
    
    ## Goals
    1. ...
    
    ## Sub-Task Decomposition
    (The firm list of intended child basic tasks. The autonomous epic worker will
     later turn each of these into a real child task — do NOT create them here.
     One entry per child: a title plus a one-line description.)
    1. <child basic-task title> — <one-line description>
    2. <child basic-task title> — <one-line description>
    3. ...
    
    ## Sequencing
    (Ordering and dependencies between the children: which must land before which,
     and why. Note any children that can proceed in parallel.)
    
    ## Constraints
    (Non-executable criteria for the epic as a whole.)
    

    Rules (STRICT):

    • ## Sub-Task Decomposition MUST exist and list ≥2 children, each title + one-line.
    • Every proposal Goal must be covered by at least one child sub-task.
    • Do NOT create any child tasks. Do NOT decompose into real backlog entries.
    • This is a plan only; the autonomous worker performs the actual decomposition later.
  4. Update task:

    backlog task edit <TASK_ID> \
      --plan "$(cat $TMPDIR/etb-plan.md)" \
      --status "Epic: Plan"
    

Phase 4: planLoop — reviewLoop(plan)

Soft limit: 8 iterations. On exhaustion: move to Epic: Needs Human, print plan, stop.

Each iteration — spawn Task agent with run_in_background=true (self-chaining background agent):

You are a strict software architect reviewing an epic plan.

Task ID: <TASK_ID> — Iteration: <N> — Max iterations: 8

  1. Read $TMPDIR/etb-proposal.md and $TMPDIR/etb-plan.md

  2. Check each item:

    • Sub-Task Decomposition present: ## Sub-Task Decomposition exists and lists ≥2 children, each with a title and a one-line description.
    • Goal coverage: Every proposal Goal is covered by at least one child sub-task.
    • Sequencing coherence: Dependencies between children are stated and acyclic.
    • Scope discipline: No child outside the epic's Goals; no child that should be its own epic.
    • No premature creation: The plan does NOT create child tasks or decompose — it only describes the intended children.
    • File paths / feasibility: Referenced areas exist in the codebase (search to verify).

3a. ALL pass:

backlog task edit <TASK_ID> \
  --append-notes "Epic plan review iteration <N>: APPROVED"
echo "APPROVED" > $TMPDIR/etb-plan-verdict.txt

在写 APPROVED 时,把 verdict 扩展为结构化前提账本(premise-ledger): 对你检查的每条 criterion,追加一行 [E|C|H] <criterion>: <你判断所凭的前提>, 分类规则:E=该前提可直接从本任务 task 文件读到;C=须跳转外部 task/doc/parent 才能确认; H=任何 artifact 都没有、靠背景知识或记忆推断。 末尾追加一行 GCL-self-report: E=<n> C=<n> H=<n>(各类计数)。 写法示例: backlog task edit <TASK_ID> --append-notes "Epic plan review iteration : APPROVED premise-ledger: [E] sub-task count: 子任务数量从 plan 文件直接数 [C] goal coverage: 须对照 proposal Goals 逐条验证 [H] sequencing 合理性: 依赖顺序靠背景知识判断 GCL-self-report: E=1 C=2 H=1" Immediately after writing the GCL-self-report note, append one line to docs/research/gcl-events.jsonl:

python3 -c "
import json, datetime
record = {
'task_id': '<TASK_ID>',
'gate_type': 'plan',
'task_kind': 'epic',
'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
'E': <E>, 'C': <C>, 'H': <H>, 'GCL': <E>+<C>+<H>,
'reviewer_model': 'claude-sonnet-4-6',
'sample_run_id': None,
'evidence_independence': 'low',
'gate_actor_type': 'llm',
'premise_lines': <count of premise-ledger lines>
}
with open('docs/research/gcl-events.jsonl', 'a') as f:
 f.write(json.dumps(record) + '\n')
"

Replace <TASK_ID>, <E>, <C>, <H> with the actual values from the self-report.

Reliability sampling (~10% of gates): After appending the primary JSONL record above, check whether this task falls in the ~10% reliability sample:

import hashlib
if int(hashlib.md5('<TASK_ID>'.encode()).hexdigest(), 16) % 10 == 0:

If and only if the condition is true, perform a second independent GCL self-report pass:

  • Re-read the same gate content (epic plan) with fresh eyes, as if reviewing it for the first time.
  • Produce a second premise-ledger with its own E/C/H counts (may differ from run 1).
  • Append a second JSONL line to docs/research/gcl-events.jsonl with the same fields but 'sample_run_id': '<TASK_ID>-r2' (instead of None).
  • Log intra-rater-variance: |H_run1 - H_run2| by appending to the task notes:
    backlog task edit <TASK_ID> --append-notes "reliability-sample: intra-rater-variance H=|<H_run1>-<H_run2>|=<diff>"
    

If the condition is false, skip this block entirely (no second pass, no extra JSONL line).

Print: "Plan APPROVED. Proceeding to finalise."

3b. ANY fail: fix $TMPDIR/etb-plan.md (and $TMPDIR/etb-proposal.md if needed), update task plan:

backlog task edit <TASK_ID> --plan "$(cat $TMPDIR/etb-plan.md)"
echo "NEEDS_REVISION" > $TMPDIR/etb-plan-verdict.txt

If <N> < 8: spawn next iteration as background agent (run_in_background=true) with N+1 and STOP. If <N> == 8: move to Epic: Needs Human, print plan, STOP.

After the first iteration is spawned (run_in_background=true), the orchestrator exits. The background agent self-chains by spawning the next iteration on NEEDS_REVISION. On APPROVED, the background agent proceeds directly to Phase 5 (finalise).


Phase 5: finalise

Run the following bash commands directly (no agent spawn needed — all steps are mechanical):

Step B — Write combined proposal+plan into task and set status to Epic: Backlog:

{
  cat $TMPDIR/etb-proposal.md
  printf '\n\n---\n\n'
  cat $TMPDIR/etb-plan.md
} > $TMPDIR/etb-combined.md

backlog task edit <TASK_ID> \
  --plan "$(cat $TMPDIR/etb-combined.md)" \
  --status "Epic: Backlog" \
  --append-notes "cap:propose=approved"

Step D — Run Layer 0-2 validation gate:

bash "$BAIME_SCRIPTS/validate-plugin.sh"

If validation fails, fix the SKILL.md contracts or internals before proceeding.

Step E — Print completion:

✅ Epic <TASK_ID> is now in Epic: Backlog.

一轮起草 + 迭代审查(提案、计划)已完成。计划中已列出预期的子任务分解,
但本技能不会创建任何子任务,也不会执行分解。

请在 web UI 审阅 Epic Proposal / Epic Plan:
  backlog browser --no-open --port 6421

确认无误后,将 epic 推进到 Epic: Ready 以授权自主分解:
  backlog task edit <TASK_ID> --status "Epic: Ready"

之后统一的 loop-backlog worker(basic-daemon 在 Epic: Ready 时发 epic-ready 事件)会接管:
  Epic: Ready → Epic: Decomposing → Epic: Awaiting Children →
  Epic: Evaluating(写 FINISH/ITERATE 建议,软停等你确认)→ Epic: Done | Epic: Needs Human
子任务建在 Basic: Backlog;由你提升选中的子任务到 Basic: Ready 来执行。

(print the above completion message as text output)


Constraints

  • Granularity gate (use an epic only when it earns it): an epic is justified ONLY when the goal needs ≥2 independent Basic Tasks with ordering/dependencies and a combined acceptance. A Basic Task is NOT small — its plan may have two levels (Phase + Stage) and reach ~1000s LOC (e.g. TASK-16: 16 skills, ~430-line plan). "A few related fixes" is ONE Basic Task with multiple Phases, not an epic. See docs/proposals/proposal-epic-split-board.md § 颗粒度. If the idea is really one Basic Task, stop and use task-to-backlog / feature-to-backlog.
  • This skill outputs an epic proposal + plan and a backlog task only — it does not implement code
  • It creates NO child tasks and performs NO decomposition; that is the autonomous worker's job
  • No branch creation, no worktree operations, no git push, no PR creation
  • One task per epic throughout; the same TASK_ID moves Epic: Proposal → Epic: Plan → Epic: Backlog
  • The skill stops at Epic: Backlog; the human promotes to Epic: Ready to start decomposition
  • Proposal and plan text live in the task's Implementation Plan field; no docs/ files are written
  • Must run from the project root of a git repository

Run Quantitative Experiment

Operator Skill for executing pre-registered quantitative experiments with held-out fixtures, multi-model runs, and hard statistical verdicts.

This skill encodes the epistemic discipline required by docs/baime-and-quantitative-experiments.md §二 Codify: every claim about methodology effectiveness must come from hypotheses frozen before execution, not from post-hoc rationalization.


λ spec

runQuantitativeExperiment :: (Domain, Hypotheses, FixtureSet, ModelConfig[], k) → ExperimentResult

runQuantitativeExperiment(domain, hypotheses, fixtures, models, k) =
  | ¬frozen(hypotheses)   → raise NotPreRegistered
  | ¬calibrated(oracle)   → raise OracleNotCalibrated
  | otherwise             → execute(fixtures, models, k)
                              ∧ score(results)
                              ∧ verdict(hypotheses, scores)
                              ∧ writeBack(evidence_pointer)

ExperimentResult = {
  verdicts: HypothesisVerdict[],   -- CONFIRMED | NULL | REJECTED
  V_meta_experiment: number,       -- [measured] experiment quality score
  evidence_pointer: string         -- path for write-back to frontmatter
}

HypothesisVerdict = {
  id: string,
  direction: "CONFIRMED" | "NULL" | "REJECTED",
  observed: number,
  threshold: number,
  confidence: "high" | "medium" | "[underpowered]"
}

contracts

The following epistemic constraints are mechanically enforced by validate-plugin.sh Layer 2:

  1. hypotheses must appear: Every experiment run must reference pre-registered hypotheses
  2. Hard verdicts required: Results must include CONFIRMED, NULL, or REJECTED — not soft scores alone
  3. [measured] annotation: Any numeric claim in results must be tagged [measured] (oracle-validated) or [soft] (self-assessed)
  4. evidence_pointer present: The write-back path to the source results file must be declared
  5. No bare V_instance self-scores: The V_instance field used with bare decimal values (e.g. V_instance = 0.XX) is prohibited — use [measured] or [soft] tags

lifecycle

Each experiment run proceeds through five mandatory phases:

Phase 1 — Pre-register hypotheses

  • Write hypotheses.md with explicit thresholds and direction
  • Git commit before any LLM calls (timestamp proves freeze)
  • Format: H-<id>: metric ≥ threshold or metric ≤ threshold
  • Output: frozen hypotheses.md with commit hash

Phase 2 — Construct fixtures

  • Create held-out fixtures in fixtures/ directory (version-controlled)
  • Validate fixture schema matches the oracle's expected input format
  • Minimum: n ≥ 8 per decision class for adequate statistical power; n < 8 → tag [underpowered]
  • Output: fixtures/<class>/*.json with id, answer, answerType

Phase 3 — Execute (multi-model, k=5)

  • Run against ≥ 2 models (cross-model consistency check)
  • Default k = 5 repetitions per fixture for variance estimate
  • Checkpoint/resume support to handle timeout
  • Output: artifacts/runs/<experiment>/<class>/<model>/<fixture_id>/result.json

Backend: runner.ts

Execution is delegated to experiments/skill-quality/lib/runner.ts via the runExperiment function:

runExperiment(config: ExperimentConfig): Promise<ExperimentResult>

interface ExperimentConfig {
  variants:    string[];       // experiment variant names
  modelList:   string[];       // model IDs to run (≥ 2 required)
  k:           number;         // repetitions per fixture (default: 5)
  outDir:      string;         // output directory for run artifacts
  buildPrompt: (fixture: Fixture, variant: string) => string;
  sanityDir:   string;         // path to sanity/calibration fixtures
}

The orchestrating agent calls runExperiment(config) and receives a structured ExperimentResult — no hand-coded fixture traversal is required.

Phase 4 — Verdict

  • Score each hypothesis against its pre-registered threshold
  • Label: CONFIRMED (observed ≥ threshold), REJECTED (observed < threshold), NULL (direction reversed)
  • Compute V_meta_experiment from the four [measured] components below
  • Output: artifacts/analysis/<experiment>-results.json with verdicts and evidence_pointer

Phase 5 — Write-back

  • Use evidence_pointer to update originating SKILL.md frontmatter or docs
  • Tag written-back claims as [measured: <evidence_pointer>]
  • Trigger knowledge-extractor agent if claim updates existing methodology
  • Set cap:experiment=<verdict> on the backlog task (where <verdict> is one of CONFIRMED|NULL|REJECTED|UNDERPOWERED) after the evidence_pointer write-back is complete

V_meta(experiment) components

Four components, all [measured] (mechanically verifiable):

ComponentMeasurementPass condition
Pre-registration disciplinegit commit timestamp of hypotheses.md vs first LLM callcommit is earlier
Statistical powerk ≥ 5 and n ≥ 8 per fixture classboth met; else [underpowered]
Oracle calibrationoracle model has independent calibration experiment before usecalibration run exists
Confound controlno known uncontrolled variables in experimental designopen_confounds list is empty

V_meta_experiment = (components_passed / 4) — tagged [measured] in results.


directory layout

experiments/<domain>-<NNN>/
  hypotheses.md          # pre-registered, frozen, git-committed before Phase 3
  fixtures/
    <class-a>/*.json     # held-out fixtures, version-controlled
    <class-b>/*.json
  artifacts/
    runs/                # gitignored — raw LLM responses
    analysis/
      <exp>-results.json # final verdicts + evidence_pointer
  lib/                   # domain-specific harness (or symlink to shared lib)
  iteration-N.md         # per-round observations, [measured]/[soft] tagged
  results.md             # human-readable summary + evidence_pointer
  knowledge/             # knowledge-extractor write-back artifacts

integration

Hooking into iteration-executor

During work_execution in lifecycle_execution, when the current domain has an external oracle:

  1. Identify whether the task involves a quantitative claim that needs hard validation
  2. If yes, invoke /run-quantitative-experiment instead of relying on dual_value_calculation
  3. The skill returns evidence_pointer pointing to artifacts/analysis/<exp>-results.json
  4. Pass evidence_pointer to knowledge-extractor for write-back to methodology docs

This replaces soft V_instance self-scoring with hard CONFIRMED/NULL/REJECTED verdicts when an oracle is available.

When to use this skill vs. soft assessment

SituationApproach
New methodology claim, oracle available/run-quantitative-experiment → [measured] tag
Existing claim, no oracle budgetKeep as-is, add [soft] tag
Cross-model consistency check neededAlways use this skill (≥2 models required)
k < 5 or n < 8Run but output [underpowered] tag in verdicts

[measured]/[soft] annotation rules

All numeric claims in experiment outputs and methodology docs must carry one of:

  • [measured]: Value comes from a pre-registered experiment with held-out fixtures and oracle verdict. The evidence_pointer field identifies the source.
  • [soft]: Value comes from self-assessment, theoretical estimate, or non-pre-registered observation.
  • [underpowered]: Value comes from a pre-registered experiment but with k < 5 or n < 8; treat as directional only.

Example usage in results.md:

H-oracle-C: CONFIRMED [measured] — Haiku F1 = 1.00 ≥ 0.80 threshold
evidence_pointer: experiments/skill-quality/artifacts/analysis/exp-b-results.json

λ(slug) → taskFromTemplate(slug)

Spec

Template :: { slug : String, -- kebab-case identifier; matches filename title : String, -- human-readable task name lastUsed : Date, -- ISO date of most recent use applicableWhen: String, -- one-sentence precondition summary body : String -- plan text (front-matter stripped) }

data FreshnessVerdict = FRESH | STALE Reason

-- Main entry point taskFromTemplate :: Slug → BacklogTask | Stopped taskFromTemplate(slug) = { repo: repoRoot(), tmpl: loadTemplate(repo, slug), changes: recentChanges(tmpl.lastUsed), verdict: freshnessCheck(tmpl, changes), if (verdict == STALE r): print("Template is STALE: " + r), print("Re-generate with: /task-to-backlog"), return: Stopped, task: createTask(tmpl), _: updateLastUsed(repo, slug), return: task -- status: Ready }

loadTemplate :: (RepoRoot, Slug) → Template loadTemplate(root, slug) = | exists(root + "/backlog/templates/" + slug + ".md") → parse(read(root + "/backlog/templates/" + slug + ".md")) | otherwise → error("Template not found: " + slug)

recentChanges :: Date → String recentChanges(since) = eval("git log --oneline --since=" + since + " HEAD | head -20")

-- Single LLM call; first output line must be FRESH or STALE: freshnessCheck :: (Template, Changes) → FreshnessVerdict freshnessCheck(tmpl, changes) = { prompt: freshnessPrompt(tmpl, changes), result: llm(prompt), return: parseVerdict(result.lines[0]) }

createTask :: Template → BacklogTask createTask(tmpl) = eval("backlog task create " + quote(tmpl.title) + " --status Ready" + " --description " + quote(tmpl.body))

updateLastUsed :: (RepoRoot, Slug) → () updateLastUsed(root, slug) = { path: root + "/backlog/templates/" + slug + ".md", _: eval("sed -i 's/^last-used: .*/last-used: " + today() + "/' " + path), _: eval("git add " + path), _: eval("git commit -m 'chore(templates): update last-used for " + slug + "'") }

Implementation

Step 1: locate template

REPO_ROOT=$(git rev-parse --show-toplevel)
SLUG="${1:-}"

if [ -z "$SLUG" ]; then
  echo "Usage: /task-from-template <template-slug>"
  echo ""
  echo "Available templates:"
  ls "${REPO_ROOT}/backlog/templates/"*.md 2>/dev/null \
    | xargs -I{} basename {} .md | grep -v README || echo "  (none)"
  exit 1
fi

TEMPLATE_FILE="${REPO_ROOT}/backlog/templates/${SLUG}.md"
if [ ! -f "$TEMPLATE_FILE" ]; then
  echo "Error: template not found: $TEMPLATE_FILE"
  echo ""
  echo "Available templates:"
  ls "${REPO_ROOT}/backlog/templates/"*.md 2>/dev/null \
    | xargs -I{} basename {} .md | grep -v README || echo "  (none)"
  exit 1
fi

Step 2: parse front-matter and extract body

# Extract front-matter fields
TMPL_TITLE=$(grep -oP '(?<=^title: ).+' "$TEMPLATE_FILE" | head -1)
TMPL_LAST_USED=$(grep -oP '(?<=^last-used: ).+' "$TEMPLATE_FILE" | head -1)
TMPL_APPLICABLE_WHEN=$(grep -oP '(?<=^applicable-when: ).+' "$TEMPLATE_FILE" | head -1)

# Extract body (everything after the closing ---)
TMPL_BODY=$(awk '/^---$/{n++; if(n==2){found=1; next}} found{print}' "$TEMPLATE_FILE")

echo "Template: $SLUG"
echo "Title: $TMPL_TITLE"
echo "Last used: $TMPL_LAST_USED"
echo "Applicable when: $TMPL_APPLICABLE_WHEN"

Step 3: gather recent git changes

GIT_CHANGES=$(git -C "$REPO_ROOT" log --oneline --since="$TMPL_LAST_USED" HEAD | head -20)

if [ -z "$GIT_CHANGES" ]; then
  GIT_CHANGES="(no commits since $TMPL_LAST_USED)"
fi

echo "Recent changes since $TMPL_LAST_USED:"
echo "$GIT_CHANGES"

Step 4: freshness check (single LLM call via Task agent)

Spawn a Task agent with the following prompt (substitute literal values for all <VARIABLE> placeholders):

You are performing a freshness check on a task template.

Template slug: <SLUG> Last used: <TMPL_LAST_USED> Applicable when: <TMPL_APPLICABLE_WHEN> Today's date: <TODAY>

Template body:

<TMPL_BODY>

Git changes since last use (git log --oneline --since=<TMPL_LAST_USED>):

<GIT_CHANGES>

Decide whether the template is still valid for its stated purpose. Consider:

  • Do the Phase steps and DoD commands still match the current project structure?
  • Have any scripts or tools that the template directly invokes (e.g. in Phase bash blocks or DoD commands) been renamed or removed? Check only what the executor runs, not what those scripts do internally.
  • Do the git changes suggest the overall workflow has fundamentally changed?

Important: do NOT check files that are only mentioned in descriptive text, or files that a script modifies internally. Only the script/tool entry points matter.

Your output MUST begin with exactly one of:

  • FRESH — template is still valid; no changes required
  • STALE:<one-line reason> — template needs updating

After the first line, you may write a brief explanation (optional).

Write only the verdict line to $TMPDIR/tft-verdict.txt:

echo "FRESH" > $TMPDIR/tft-verdict.txt
# or
echo "STALE: <reason>" > $TMPDIR/tft-verdict.txt

After the agent completes, read the verdict:

VERDICT=$(cat "$TMPDIR/tft-verdict.txt" | head -1)

if echo "$VERDICT" | grep -q '^STALE'; then
  STALE_REASON=$(echo "$VERDICT" | sed 's/^STALE[: ]*//')
  echo ""
  echo "⚠️  Template '$SLUG' is STALE: $STALE_REASON"
  echo ""
  echo "The template was last used $TMPL_LAST_USED and recent changes make it unreliable."
  echo "Please regenerate it with:"
  echo "  /task-to-backlog $TMPL_APPLICABLE_WHEN"
  exit 0
fi

echo "✅ Template '$SLUG' is FRESH — creating task..."

Step 5: create backlog task

TASK_OUTPUT=$(backlog task create "$TMPL_TITLE" \
  --status "Basic: Ready" \
  --label "kind:basic" \
  --description "$TMPL_BODY" \
  --plain)

TASK_ID=$(echo "$TASK_OUTPUT" | grep -oP 'TASK-\d+' | head -1)
echo "Created task: $TASK_ID — $TMPL_TITLE"

Step 6: update last-used and commit

TODAY=$(date +%Y-%m-%d)
sed -i "s/^last-used: .*/last-used: ${TODAY}/" "$TEMPLATE_FILE"

git -C "$REPO_ROOT" add "$TEMPLATE_FILE"
git -C "$REPO_ROOT" commit -m "chore(templates): update last-used for ${SLUG} (${TASK_ID})"

echo ""
echo "✅ Task $TASK_ID created with status Ready."
echo "   Template last-used updated to $TODAY."
echo ""
echo "Run /loop-backlog to execute, or check status with:"
echo "  backlog task view $TASK_ID"

Constraints

  • This skill does NOT walk through a full proposal/plan review cycle — that is intentional
  • The freshness check is a single LLM call; it does not iterate
  • If freshness check returns STALE, the skill exits without creating a task
  • last-used is updated only after a task is successfully created
  • Templates must live in backlog/templates/ and be committed to the repository
  • This skill must be run from the project root of a git repository
  • $TMPDIR files are ephemeral; do not reference them after the skill completes

Commands 22

Agent Prompt Evolution

Systematically track how agents specialize during methodology development.

Specialized agents emerge from need, not prediction. Track their evolution to understand when specialization adds value.


When to Use This Skill

Use this skill when:

  • 🔄 Agent specialization emerges: Generic agents show >5x performance gap
  • 📊 Multi-experiment comparison: Want to learn across experiments
  • 🧩 Methodology transferability: Analyzing what's reusable vs domain-specific
  • 📈 M₀ optimization: Want to evolve base Meta-Agent capabilities
  • 🎯 Specialization decisions: Deciding when to create new agents
  • 📚 Agent library: Building reusable agent catalog

Don't use when:

  • ❌ Single experiment with no specialization
  • ❌ Generic agents sufficient throughout
  • ❌ No cross-experiment learning goals
  • ❌ Tracking overhead not worth insights

Quick Start (10 minutes per iteration)

Track Agent Evolution in Each Iteration

iteration-N.md template:

## Agent Set Evolution

### Current Agent Set (Aₙ)
1. **coder** (generic) - Write code, implement features
2. **doc-writer** (generic) - Documentation
3. **data-analyst** (generic) - Data analysis
4. **coverage-analyzer** (specialized, created iteration 3) - Analyze test coverage gaps

### Changes from Previous Iteration
- Added: coverage-analyzer (10x speedup for coverage analysis)
- Removed: None
- Modified: None

### Specialization Decision
**Why coverage-analyzer?**
- Generic data-analyst took 45 min for coverage analysis
- Identified 10x performance gap
- Coverage analysis is recurring task (every iteration)
- Domain knowledge: Go coverage tools, gap identification patterns
- **ROI**: 3 hours creation cost, saves 40 min/iteration × 3 remaining iterations = 2 hours saved

### Agent Reusability Assessment
- **coder**: Universal (100% transferable)
- **doc-writer**: Universal (100% transferable)
- **data-analyst**: Universal (100% transferable)
- **coverage-analyzer**: Domain-specific (testing methodology, 70% transferable to other languages)

### System State
- Aₙ ≠ Aₙ₋₁ (new agent added)
- System UNSTABLE (need iteration N+1 to confirm stability)

Four Tracking Dimensions

1. Agent Set Evolution (Aₙ)

Track changes iteration-to-iteration:

A₀ = {coder, doc-writer, data-analyst}
A₁ = {coder, doc-writer, data-analyst} (unchanged)
A₂ = {coder, doc-writer, data-analyst} (unchanged)
A₃ = {coder, doc-writer, data-analyst, coverage-analyzer} (new specialist)
A₄ = {coder, doc-writer, data-analyst, coverage-analyzer, test-generator} (new specialist)
A₅ = {coder, doc-writer, data-analyst, coverage-analyzer, test-generator} (stable)

Stability: Aₙ == Aₙ₋₁ for convergence

2. Meta-Agent Evolution (Mₙ)

Standard M₀ capabilities:

  1. observe: Pattern observation
  2. plan: Iteration planning
  3. execute: Agent orchestration
  4. reflect: Value assessment
  5. evolve: System evolution

Track enhancements:

M₀ = {observe, plan, execute, reflect, evolve}
M₁ = {observe, plan, execute, reflect, evolve, gap-identify} (new capability)
M₂ = {observe, plan, execute, reflect, evolve, gap-identify} (stable)

Finding (from 8 experiments): M₀ sufficient in all cases (no evolution needed)

3. Specialization Decision Tree

When to create specialized agent:

Decision tree:
1. Is generic agent sufficient? (performance within 2x)
   YES → No specialization
   NO → Continue

2. Is task recurring? (happens ≥3 times)
   NO → One-off, tolerate slowness
   YES → Continue

3. Is performance gap >5x?
   NO → Tolerate moderate slowness
   YES → Continue

4. Is creation cost <ROI?
   Creation cost < (Time saved per use × Remaining uses)
   NO → Not worth it
   YES → Create specialized agent

Example (Bootstrap-002):

Task: Test coverage gap analysis
Generic agent (data-analyst): 45 min
Potential specialist (coverage-analyzer): 4.5 min (10x faster)

Recurring: YES (every iteration, 3 remaining)
Performance gap: 10x (>5x threshold)
Creation cost: 3 hours
ROI: (45-4.5) min × 3 = 121.5 min = 2 hours saved
Decision: CREATE (positive ROI)

4. Reusability Assessment

Three categories:

Universal (90-100% transferable):

  • Generic agents (coder, doc-writer, data-analyst)
  • No domain knowledge required
  • Applicable across all domains

Domain-Specific (60-80% transferable):

  • Requires domain knowledge (testing, CI/CD, error handling)
  • Patterns apply within domain
  • Needs adaptation for other domains

Task-Specific (10-30% transferable):

  • Highly specialized for particular task
  • One-off creation
  • Unlikely to reuse

Examples:

Agent: coverage-analyzer
Domain: Testing methodology
Transferability: 70%
- Go coverage tools (language-specific, 30% adaptation)
- Gap identification patterns (universal, 100%)
- Overall: 70% transferable to Python/Rust/TypeScript testing

Agent: test-generator
Domain: Testing methodology
Transferability: 40%
- Go test syntax (language-specific, 0% to other languages)
- Test pattern templates (moderately transferable, 60%)
- Overall: 40% transferable

Agent: log-analyzer
Domain: Observability
Transferability: 85%
- Log parsing (universal, 95%)
- Pattern recognition (universal, 100%)
- Structured logging concepts (universal, 100%)
- Go slog specifics (language-specific, 20%)
- Overall: 85% transferable

Evolution Log Template

Create agents/EVOLUTION-LOG.md:

# Agent Evolution Log

## Experiment Overview
- Domain: Testing Strategy
- Baseline agents: 3 (coder, doc-writer, data-analyst)
- Final agents: 5 (+coverage-analyzer, +test-generator)
- Specialization count: 2

---

## Iteration-by-Iteration Evolution

### Iteration 0
**Agent Set**: {coder, doc-writer, data-analyst}
**Changes**: None (baseline)
**Observations**: Generic agents sufficient for baseline establishment

### Iteration 3
**Agent Set**: {coder, doc-writer, data-analyst, coverage-analyzer}
**Changes**: +coverage-analyzer
**Reason**: 10x performance gap (45 min → 4.5 min)
**Creation Cost**: 3 hours
**ROI**: Positive (2 hours saved over 3 iterations)
**Reusability**: 70% (domain-specific, testing)

### Iteration 4
**Agent Set**: {coder, doc-writer, data-analyst, coverage-analyzer, test-generator}
**Changes**: +test-generator
**Reason**: 200x performance gap (manual test writing too slow)
**Creation Cost**: 4 hours
**ROI**: Massive (saved 10+ hours)
**Reusability**: 40% (task-specific, Go testing)

### Iteration 5
**Agent Set**: {coder, doc-writer, data-analyst, coverage-analyzer, test-generator}
**Changes**: None
**System**: STABLE (Aₙ == Aₙ₋₁)

---

## Specialization Analysis

### coverage-analyzer
**Purpose**: Analyze test coverage, identify gaps
**Performance**: 10x faster than generic data-analyst
**Domain**: Testing methodology
**Transferability**: 70%
**Lessons**: Coverage gap identification patterns are universal, tool integration is language-specific

### test-generator
**Purpose**: Generate test boilerplate from coverage gaps
**Performance**: 200x faster than manual
**Domain**: Testing methodology (Go-specific)
**Transferability**: 40%
**Lessons**: High speedup justified low transferability, patterns reusable but syntax is not

---

## Cross-Experiment Reuse

### From Previous Experiments
- **validation-builder** (from API design experiment) → Used for smoke test validation
- Reusability: Excellent (validation patterns are universal)
- Adaptation: Minimal (10 min to adapt from API to CI/CD context)

### To Future Experiments
- **coverage-analyzer** → Reusable for Python/Rust/TypeScript testing (70% transferable)
- **test-generator** → Less reusable (40% transferable, needs rewrite for other languages)

---

## Meta-Agent Evolution

### M₀ Capabilities
{observe, plan, execute, reflect, evolve}

### Changes
None (M₀ sufficient throughout)

### Observations
- M₀'s "evolve" capability successfully identified need for specialization
- No Meta-Agent evolution required
- Convergence: Mₙ == M₀ for all iterations

---

## Lessons Learned

### Specialization Decisions
- **10x performance gap** is good threshold (< 5x not worth it, >10x clear win)
- **Positive ROI required**: Creation cost must be justified by time savings
- **Recurring tasks only**: One-off tasks don't justify specialization

### Reusability Patterns
- **Generic agents always reusable**: coder, doc-writer, data-analyst (100%)
- **Domain agents moderately reusable**: coverage-analyzer (70%)
- **Task agents rarely reusable**: test-generator (40%)

### When NOT to Specialize
- Performance gap <5x (tolerable slowness)
- Task is one-off (no recurring benefit)
- Creation cost >ROI (not worth time investment)
- Generic agent will improve with practice (learning curve)

Cross-Experiment Analysis

After 3+ experiments, create agents/CROSS-EXPERIMENT-ANALYSIS.md:

# Cross-Experiment Agent Analysis

## Agent Reuse Matrix

| Agent | Exp1 | Exp2 | Exp3 | Reuse Rate | Transferability |
|-------|------|------|------|------------|-----------------|
| coder | ✓ | ✓ | ✓ | 100% | Universal |
| doc-writer | ✓ | ✓ | ✓ | 100% | Universal |
| data-analyst | ✓ | ✓ | ✓ | 100% | Universal |
| coverage-analyzer | ✓ | - | ✓ | 67% | Domain (testing) |
| test-generator | ✓ | - | - | 33% | Task-specific |
| validation-builder | - | ✓ | ✓ | 67% | Domain (validation) |
| log-analyzer | - | - | ✓ | 33% | Domain (observability) |

## Specialization Patterns

### Universal Agents (100% reuse)
- Generic capabilities (coder, doc-writer, data-analyst)
- No domain knowledge
- Always included in A₀

### Domain Agents (50-80% reuse)
- Require domain knowledge (testing, CI/CD, observability)
- Reusable within domain
- Examples: coverage-analyzer, validation-builder, log-analyzer

### Task Agents (10-40% reuse)
- Highly specialized
- One-off or rare reuse
- Examples: test-generator (Go-specific)

## M₀ Sufficiency

**Finding**: M₀ = {observe, plan, execute, reflect, evolve} sufficient in ALL experiments

**Implications**:
- No Meta-Agent evolution needed
- Base capabilities handle all domains
- Specialization occurs at Agent layer, not Meta-Agent layer

## Specialization Threshold

**Data** (from 3 experiments):
- Average performance gap for specialization: 15x (range: 5x-200x)
- Average creation cost: 3.5 hours (range: 2-5 hours)
- Average ROI: Positive in 8/9 cases (89% success rate)

**Recommendation**: Use 5x performance gap as threshold

---

**Updated**: After each new experiment

Success Criteria

Agent evolution tracking succeeded when:

  1. Complete tracking: All agent changes documented each iteration
  2. Specialization justified: Each specialized agent has clear ROI
  3. Reusability assessed: Each agent categorized (universal/domain/task)
  4. Cross-experiment learning: Patterns identified across 2+ experiments
  5. M₀ stability documented: Meta-Agent evolution (or lack thereof) tracked

Related Skills

Parent framework:

Complementary:


References

Core guide:

Examples:


Status: ✅ Formalized | 2-3 hours overhead | Enables systematic learning

Spec

λ(requirements: APIRequirements) → APIDesign

API Design

Systematic API design with validated patterns and automated quality enforcement.

Good APIs are designed, not discovered. 82.5% of patterns transfer across domains.


When to Use This Skill

Use this skill when:

  • 🎯 Designing new API: Need systematic parameter organization and naming conventions
  • 🔄 Refactoring existing API: Improving consistency without breaking changes
  • 📊 API quality enforcement: Building validation tools and quality gates
  • 📝 API documentation: Writing clear, example-driven documentation
  • 🚀 API evolution: Implementing versioning, deprecation, and migration policies
  • 🔍 API consistency: Standardizing conventions across multiple endpoints

Don't use when:

  • ❌ API has <5 endpoints (overhead not justified)
  • ❌ No team collaboration (conventions only valuable for teams)
  • ❌ Prototype/throwaway code (skip formalization)
  • ❌ Non-REST/non-JSON APIs without adaptation (patterns assume JSON-based APIs)

Prerequisites

Tools

  • API framework (language-specific): Go, Python, TypeScript, etc.
  • Validation tools (optional): Linters, schema validators
  • Version control: Git (for pre-commit hooks)

Concepts

  • REST principles: Resource-based design, HTTP methods
  • JSON specification: Object property ordering (unordered), schema design
  • Semantic Versioning: Major.Minor.Patch versioning (if using Pattern 1)
  • Pre-commit hooks: Git hooks for quality gates

Background Knowledge

  • API design basics (endpoints, parameters, responses)
  • Backward compatibility principles
  • Testing strategies (integration tests, contract tests)

Quick Start (30 minutes)

This skill was extracted using systematic knowledge extraction methodology from Bootstrap-006 experiment.

Status: PARTIAL EXTRACTION (demonstration of methodology, not complete skill)

Note: This is a minimal viable skill created to validate the knowledge extraction methodology. A complete skill would include:

  • Detailed pattern descriptions with code examples
  • Step-by-step walkthroughs for each pattern
  • Templates for API specifications
  • Scripts for validation and quality gates
  • Comprehensive reference documentation

Extraction Evidence:

  • Source experiment: Bootstrap-006 (V_instance=0.87, V_meta=0.786)
  • Patterns extracted: 6/6 identified (not yet fully documented here)
  • Principles extracted: 8/8 identified (not yet fully documented here)
  • Extraction time: 30 minutes (partial, demonstration only)

Patterns Overview

Pattern 1: Deterministic Parameter Categorization

Context: When designing or refactoring API parameters, categorization decisions must be consistent and unambiguous.

Solution: Use 5-tier decision tree system:

  • Tier 1: Required parameters (can't execute without)
  • Tier 2: Filtering parameters (affect WHAT is returned)
  • Tier 3: Range parameters (define bounds/thresholds)
  • Tier 4: Output control parameters (affect HOW MUCH is returned)
  • Tier 5: Standard parameters (cross-cutting concerns, framework-applied)

Evidence: 100% determinism across 8 tools, 37.5% efficiency gain through pre-audit

Transferability: ✅ Universal to all query-based APIs (REST, GraphQL, CLI)


Pattern 2: Safe API Refactoring via JSON Property

Context: Need to improve API schema readability without breaking existing clients.

Solution: Leverage JSON specification guarantee that object properties are unordered. Parameter order in schema definition is documentation only. This is a non-destructive change: no client code breaks because JSON parsers ignore property order.

Evidence: 60 lines changed, 100% test pass rate, zero compatibility issues

Transferability: ✅ Universal to all JSON-based APIs


Pattern 3: Audit-First Refactoring

Context: Need to refactor multiple targets (tools, parameters, schemas) for consistency.

Solution: Systematic audit process before making changes:

  1. List all targets to audit
  2. Define compliance criteria
  3. Assess each target (compliant vs. non-compliant)
  4. Categorize and prioritize
  5. Execute changes on non-compliant targets only
  6. Verify compliant targets (no changes)

Evidence: 37.5% unnecessary work avoided (3 of 8 tools already compliant)

Transferability: ✅ Universal to any refactoring effort (not API-specific)


Patterns 4-6

Note: Patterns 4-6 (Automated Consistency Validation, Automated Quality Gates, Example-Driven Documentation) are documented in the source experiment (Bootstrap-006) but not yet extracted here due to time constraints in this validation iteration.

Source: See experiments/bootstrap-006-api-design/results.md lines 616-733 for full descriptions.


Core Principles

1. Specifications Alone are Insufficient

Statement: Methodology extraction requires observing execution, not just reading design documents.

Evidence: Bootstrap-006 Iterations 0-3 produced 0 patterns (specifications only), Iterations 4-6 extracted 6 patterns (execution observed).

Application: Always combine design work with implementation to enable pattern extraction.


2. Operational Quality > Design Quality

Statement: Operational implementation scores higher than design quality when verification is rigorous.

Evidence: Design V_consistency = 0.87, Operational V_consistency = 0.94 (+0.07).

Application: Be conservative with design estimates. Reserve high scores (0.90+) for operational verification.


3-8. Additional Principles

Note: Principles 3-8 are documented in source experiment but not yet extracted here due to time constraints.


Success Metrics

Instance Layer (Task Quality):

  • API usability: 0.83
  • API consistency: 0.97
  • API completeness: 0.76
  • API evolvability: 0.88
  • Overall: V_instance = 0.87 (exceeds 0.80 threshold by +8.75%)

Meta Layer (Methodology Quality):

  • Methodology completeness: 0.85
  • Methodology effectiveness: 0.66
  • Methodology reusability: 0.825
  • Overall: V_meta = 0.786 (approaches 0.80 threshold, gap -1.4%)

Validation: Transfer test across domains achieved 82.5% average pattern transferability (empirically validated).


Transferability

Language Independence: ✅ HIGH (75-85%)

  • Patterns focus on decision-making processes, not language features
  • Tested primarily in Go, but applicable to Python, TypeScript, Rust, Java

Domain Independence: ✅ HIGH (82.5% empirically validated)

  • Patterns transfer from MCP Tools API to Slash Command Capabilities with minor adaptation
  • Universal patterns (3, 4, 5, 6): 67% of methodology
  • Domain-specific patterns (1, 2): Require adaptation for different parameter models

Codebase Generality: ✅ MODERATE (60-75%)

  • Validated on meta-cc (16 MCP tools, moderate scale)
  • Application to very large APIs (100+ tools) unvalidated
  • Principles scale-independent, but tooling may need adaptation

Limitations and Gaps

Known Limitations

  1. Single domain validation: Patterns extracted from API design only, need validation in non-API contexts
  2. JSON-specific: Pattern 2 (Safe Refactoring) assumes JSON-based APIs
  3. Moderate scale: Validated on 16-tool API, not tested on 100+ tool systems
  4. Conservative effectiveness: No control group study (ad-hoc vs. methodology comparison)

Skill Completeness

Current Status: PARTIAL EXTRACTION (30% complete)

Completed:

  • ✅ Frontmatter (name, description, allowed-tools)
  • ✅ When to Use / Prerequisites
  • ✅ Patterns 1-3 documented (summaries)
  • ✅ Principles 1-2 documented
  • ✅ Success Metrics / Transferability / Limitations

Missing (to be completed in future iterations):

  • ❌ Patterns 4-6 detailed documentation
  • ❌ Principles 3-8 documentation
  • ❌ Step-by-step walkthroughs (examples/)
  • ❌ Templates directory (API specification templates)
  • ❌ Scripts directory (validation tools, quality gates)
  • ❌ Reference documentation (comprehensive pattern catalog)

Reason for Incompleteness: This skill created as validation of knowledge extraction methodology, not as production-ready artifact. Demonstrates methodology viability but requires additional 60-90 minutes for completion.


Related Skills

  • Testing Strategy: API testing patterns, integration tests, contract tests
  • Error Recovery: API error handling, error taxonomy
  • CI/CD Optimization: Pre-commit hooks, automated quality gates (overlaps with Pattern 5)

Quick Reference

5-Tier Parameter System:

  1. Required (must have)
  2. Filtering (WHAT is returned)
  3. Range (bounds/thresholds)
  4. Output control (HOW MUCH)
  5. Standard (cross-cutting)

Audit-First Efficiency: 37.5% work avoided (3/8 tools already compliant)

Transferability: 82.5% average (empirical validation across domains)

Convergence: V_instance = 0.87, V_meta = 0.786


Skill Status: DEMONSTRATION / PARTIAL EXTRACTION Extraction Source: Bootstrap-006-api-design Extraction Date: 2025-10-19 Extraction Time: 30 minutes (partial) Next Steps: Complete Patterns 4-6, add examples, create templates and scripts

λ() → backlogSetup()

Spec

-- Columns required by each skill

REQUIRED_COLUMNS := [ "Epic: Proposal", "Epic: Plan", "Epic: Backlog", "Epic: Ready", "Epic: Decomposing", "Epic: Awaiting Children", "Epic: Evaluating", "Epic: Done", "Epic: Needs Human", "Basic: Proposal", "Basic: Plan", "Basic: Backlog", "Basic: Ready", "Basic: In Progress", "Basic: Done", "Basic: Needs Human" ]

backlogSetup :: () → SetupResult backlogSetup() = { _: checkCli(), _: initProject(), missing: verifyColumns(REQUIRED_COLUMNS), _: addColumns(missing), _: initL0Config(), _: seedExamples(), _: printSummary() }

-- Only seeds when backlog/docs/ and backlog/decisions/ are both empty -- (i.e. first-time init). Idempotent: skips if any file already exists. seedExamples :: () → () seedExamples() = | ¬empty(backlog/docs/) ∨ ¬empty(backlog/decisions/) → skip | otherwise → { backlog document create --type guide, backlog decision create --status "Accepted" }

checkCli :: () → () checkCli() = | which("backlog") succeeds → continue | otherwise → print(installInstructions); halt

initProject :: () → () initProject() = | exists("backlog/") → skip -- already initialised | otherwise → backlog init --defaults --agent-instructions none

verifyColumns :: [String] → [String] verifyColumns(required) = required ∖ existingColumns()

addColumns :: [String] → () addColumns(cols) = ∀col ∈ cols: backlog column add col

-- Detects project type from marker files and appends ## L0 Config to CLAUDE.md. -- Idempotent: skips if ## L0 Config already present. -- Pauses for human confirmation before writing. initL0Config :: () → () initL0Config() = | grep -q "## L0 Config" CLAUDE.md → skip | otherwise → { type: detectProjectType(), block: renderL0Block(type), _: printProposed(block), _: awaitConfirmation(), _: appendOrCreateClaudeMd(block) }

detectProjectType :: () → ProjectType detectProjectType() = | exists("scripts/validate-plugin.sh") → baime | exists("package.json") → node | exists("go.mod") → go | exists("Cargo.toml") → rust | exists("pyproject.toml") → python | exists("Makefile") → make | otherwise → unknown

Implementation

checkCli

if ! command -v backlog &>/dev/null; then
  echo "❌ 'backlog' CLI not found."
  echo ""
  echo "Install instructions:"
  echo "  npm install -g @backlog-md/cli"
  echo "  # or: pip install backlog-md"
  echo "  # or: see https://github.com/backlog-md/backlog"
  echo ""
  echo "After installing, re-run /backlog-setup."
  exit 1
fi
echo "✓ backlog CLI found: $(backlog --version 2>/dev/null || echo 'version unknown')"

initProject

if [ ! -d "backlog" ]; then
  echo "Initialising backlog project..."
  PROJECT_NAME=$(basename "$PWD")
  backlog init "$PROJECT_NAME" --defaults --agent-instructions none
  echo "✓ backlog project initialised"
else
  echo "✓ backlog project already exists"
fi

verifyColumns + addColumns

backlog column add does not exist in backlog CLI v1.45+. Statuses must be set by editing backlog/config.yml directly. Use Python to parse and rewrite the YAML line in-place, preserving all other fields.

REQUIRED_COLUMNS=(
  "Epic: Proposal" "Epic: Plan" "Epic: Backlog" "Epic: Ready"
  "Epic: Decomposing" "Epic: Awaiting Children" "Epic: Evaluating"
  "Epic: Done" "Epic: Needs Human"
  "Basic: Proposal" "Basic: Plan" "Basic: Backlog" "Basic: Ready"
  "Basic: In Progress" "Basic: Done" "Basic: Needs Human"
)

# Read existing statuses and compute missing ones via Python
python3 - <<'PYEOF'
import re, sys

CONFIG = "backlog/config.yml"
REQUIRED = [
  "Epic: Proposal", "Epic: Plan", "Epic: Backlog", "Epic: Ready",
  "Epic: Decomposing", "Epic: Awaiting Children", "Epic: Evaluating",
  "Epic: Done", "Epic: Needs Human",
  "Basic: Proposal", "Basic: Plan", "Basic: Backlog", "Basic: Ready",
  "Basic: In Progress", "Basic: Done", "Basic: Needs Human",
]

with open(CONFIG) as f:
    content = f.read()

# Extract existing statuses from the YAML array on the statuses line
m = re.search(r'^statuses:\s*\[([^\]]*)\]', content, re.MULTILINE)
existing = []
if m:
    existing = [s.strip().strip('"') for s in m.group(1).split(',') if s.strip()]

missing = [c for c in REQUIRED if c not in existing]

# Always write exactly REQUIRED (authoritative); discard unrelated defaults like "To Do"
new_statuses = ', '.join(f'"{c}"' for c in REQUIRED)
content = re.sub(
    r'^statuses:\s*\[.*?\]',
    f'statuses: [{new_statuses}]',
    content, flags=re.MULTILINE
)

# Ensure default_status is "Proposal"
content = re.sub(
    r'^default_status:\s*"[^"]*"',
    'default_status: "Basic: Proposal"',
    content, flags=re.MULTILINE
)

with open(CONFIG, 'w') as f:
    f.write(content)

if missing:
    print("Added: " + ", ".join(missing))
else:
    print("All required columns already present.")
PYEOF

initL0Config

# Idempotency guard: skip if ## L0 Config already present
if grep -q "## L0 Config" CLAUDE.md 2>/dev/null; then
  echo "✓ CLAUDE.md already contains ## L0 Config — skipping"
else
  # Detection: probe marker files in priority order
  if [ -f "scripts/validate-plugin.sh" ]; then
    PROJECT_TYPE="baime"
    TEST_CMD="bash scripts/validate-plugin.sh"
    TEST_ALL="bash scripts/validate-plugin.sh"
    DOC_PATH="docs"
    WORKTREE_SYMLINKS=""
  elif [ -f "package.json" ]; then
    PROJECT_TYPE="node"
    TEST_CMD="npm test"
    TEST_ALL="npm test"
    DOC_PATH="docs"
    WORKTREE_SYMLINKS="node_modules"
  elif [ -f "go.mod" ]; then
    PROJECT_TYPE="go"
    TEST_CMD="go test ./..."
    TEST_ALL="go test ./..."
    DOC_PATH="docs"
    WORKTREE_SYMLINKS=""
  elif [ -f "Cargo.toml" ]; then
    PROJECT_TYPE="rust"
    TEST_CMD="cargo test"
    TEST_ALL="cargo test"
    DOC_PATH="docs"
    WORKTREE_SYMLINKS=""
  elif [ -f "pyproject.toml" ]; then
    PROJECT_TYPE="python"
    TEST_CMD="pytest"
    TEST_ALL="pytest"
    DOC_PATH="docs"
    WORKTREE_SYMLINKS=""
  elif [ -f "Makefile" ]; then
    PROJECT_TYPE="make"
    TEST_CMD="make test"
    TEST_ALL="make test"
    DOC_PATH="docs"
    WORKTREE_SYMLINKS=""
  else
    PROJECT_TYPE="unknown"
    TEST_CMD="<fill in>"
    TEST_ALL="<fill in>"
    DOC_PATH="docs"
    WORKTREE_SYMLINKS=""
  fi

  # Render proposed block
  L0_BLOCK="## L0 Config

test-cmd: ${TEST_CMD}
test-all: ${TEST_ALL}
doc-path: ${DOC_PATH}
worktree-symlinks: ${WORKTREE_SYMLINKS}"

  echo ""
  echo "Detected project type: ${PROJECT_TYPE}"
  echo ""
  echo "Proposed ## L0 Config block to append to CLAUDE.md:"
  echo "────────────────────────────────────────"
  echo "${L0_BLOCK}"
  echo "────────────────────────────────────────"
  echo ""
  printf "Write this block to CLAUDE.md? [y/N] "
  read -r CONFIRM
  if [ "${CONFIRM}" = "y" ] || [ "${CONFIRM}" = "Y" ]; then
    if [ ! -f "CLAUDE.md" ]; then
      printf "%s\n" "${L0_BLOCK}" > CLAUDE.md
      echo "✓ Created CLAUDE.md with ## L0 Config"
    else
      printf "\n%s\n" "${L0_BLOCK}" >> CLAUDE.md
      echo "✓ Appended ## L0 Config to CLAUDE.md"
    fi
  else
    echo "Skipped — edit CLAUDE.md manually to add ## L0 Config"
  fi
fi

seedExamples

Run only when both backlog/docs/ and backlog/decisions/ are empty (first-time init).

DOCS_EMPTY=true
DECISIONS_EMPTY=true
[ -d backlog/docs ] && [ -n "$(ls -A backlog/docs 2>/dev/null)" ] && DOCS_EMPTY=false
[ -d backlog/decisions ] && [ -n "$(ls -A backlog/decisions 2>/dev/null)" ] && DECISIONS_EMPTY=false

if $DOCS_EMPTY && $DECISIONS_EMPTY; then
  # --- Example document ---
  backlog document create "Backlog Web UI 快速参考" --type guide --tags "onboarding,howto" <<'EOF'
## 三个内容区域

`backlog browser` 打开 web UI,顶部导航有三个区域:

| 区域 | CLI 命令 | 存储路径 | 用途 |
|---|---|---|---|
| **TASKS** | `backlog task create` | `backlog/tasks/` | 功能、缺陷、任务 |
| **DOCUMENTS** | `backlog document create` | `backlog/docs/` | 指南、规范、参考文档 |
| **DECISIONS** | `backlog decision create` | `backlog/decisions/` | 架构决策记录(ADR) |

## 注意事项

- 手动在 `backlog/docs/` 或 `backlog/decisions/` 创建的 `.md` 文件,**若没有 backlog frontmatter 则不可见**。
- 请始终通过 CLI 命令创建,或在文件头加上 `id`/`title`/`date`/`status` 等 frontmatter。
- Documents 支持 `--type`(readme/guide/specification/other)和 `--tags`。
- Decisions 支持 `--status`(Proposed/Accepted/Deprecated/Superseded)。
EOF

  # --- Example decision ---
  backlog decision create "示例:架构决策记录模板" --status "Proposed"
  # Then write template body into the created file:
  DECISION_FILE=$(ls backlog/decisions/decision-* 2>/dev/null | head -1)
  if [ -n "$DECISION_FILE" ]; then
    python3 - "$DECISION_FILE" <<'PYEOF'
import re, sys
path = sys.argv[1]
with open(path) as f:
    content = f.read()
body = """
## Context

(描述导致需要做此决策的背景、约束或问题。包含已考虑的备选方案。)

## Decision

(清晰陈述所做的决定。)

## Consequences

**正面:**
- (此决策带来的好处)

**负面 / 约束:**
- (权衡、限制、或需要注意的事项)
"""
# Replace empty section bodies
content = re.sub(r'(## Context\n)\n(## Decision)', r'\1(描述背景)\n\n\2', content)
# Just append the template body after the frontmatter block
parts = content.split('---', 2)
if len(parts) == 3:
    content = '---'.join(parts[:2]) + '---' + body
    with open(path, 'w') as f:
        f.write(content)
PYEOF
  fi

  echo "✓ seeded example document and decision"
else
  echo "✓ docs/decisions not empty — skipping seed"
fi

printSummary

echo ""
echo "═══════════════════════════════════════"
echo "  backlog-setup complete"
echo "═══════════════════════════════════════"
echo ""

if [ ${#EXISTING[@]} -gt 0 ]; then
  echo "Already present:"
  for COL in "${EXISTING[@]}"; do echo "  ✓ $COL"; done
fi

if [ ${#ADDED[@]} -gt 0 ]; then
  echo "Added:"
  for COL in "${ADDED[@]}"; do echo "  + $COL"; done
fi

echo ""
echo "All required columns are ready."
echo ""
echo "Next steps:"
echo "  1. Create your first task:"
echo "     /feature-to-backlog <feature description>"
echo ""
echo "  2. Move the task to Ready, then start the worker:"
echo "     /loop-backlog"
echo ""
echo "─── Web UI ────────────────────────────────"
echo "  backlog browser"
echo ""
echo "  TASKS      — tasks created by /feature-to-backlog, /task-to-backlog"
echo "  DOCUMENTS  — guides & specs:  backlog document create <title> --type guide"
echo "  DECISIONS  — ADRs:            backlog decision create <title> --status Accepted"
echo ""
echo "  ⚠  Files placed manually in backlog/docs/ or backlog/decisions/"
echo "     are invisible in the web UI unless they have backlog frontmatter."
echo "     Always use the CLI commands above."

Notes

  • Statuses are managed by direct edit of backlog/config.yml (Python regex rewrite); backlog column add was removed in CLI v1.45+.
  • The script is idempotent: running it multiple times only adds truly missing columns. The seed step is also idempotent: skipped if backlog/docs/ or backlog/decisions/ already contain any files.
  • backlog-setup auto-detects the project type and appends a ## L0 Config block to CLAUDE.md (with human confirmation). The step is idempotent — it skips if the block already exists.
  • Web UI content areas and their CLI commands:
    • TASKS → backlog task create
    • DOCUMENTS → backlog document create (stores in backlog/docs/)
    • DECISIONS → backlog decision create (stores in backlog/decisions/)
    • Manual .md files without backlog frontmatter are invisible in the web UI.

Spec

λ(project: ProjectContext) → QualityBaseline

Baseline Quality Assessment

Invest in iteration 0 to save 40-50% total time.

A strong baseline (V_meta ≥0.40) is the foundation of rapid convergence. Spend hours in iteration 0 to save days overall.


When to Use This Skill

Use this skill when:

  • 📋 Planning iteration 0: Deciding time allocation and priorities
  • 🎯 Targeting rapid convergence: Want 3-4 iterations (not 5-7)
  • 📚 Prior art exists: Domain has established practices to reference
  • 📊 Historical data available: Can quantify baseline immediately
  • ⏰ Time constraints: Need methodology in 10-15 hours total
  • 🔍 Gap clarity needed: Want obvious iteration objectives

Don't use when:

  • ❌ Exploratory domain (no prior art)
  • ❌ Greenfield project (no historical data)
  • ❌ Time abundant (standard convergence acceptable)
  • ❌ Incremental baseline acceptable (build up gradually)

Quick Start (30 minutes)

Baseline Quality Self-Assessment

Calculate your V_meta(s₀):

V_meta = (Completeness + Effectiveness + Reusability + Validation) / 4

Completeness (Documentation exists?):

  • 0.00: No documentation
  • 0.25: Basic notes only
  • 0.50: Partial documentation (some categories)
  • 0.75: Most documentation complete
  • 1.00: Comprehensive documentation

Effectiveness (Speedup quantified?):

  • 0.00: No baseline measurement
  • 0.25: Informal estimates
  • 0.50: Some metrics measured
  • 0.75: Most metrics quantified
  • 1.00: Full quantitative baseline

Reusability (Transferable patterns?):

  • 0.00: No patterns identified
  • 0.25: Ad-hoc solutions only
  • 0.50: Some patterns emerging
  • 0.75: Most patterns codified
  • 1.00: Universal patterns documented

Validation (Evidence-based?):

  • 0.00: No validation
  • 0.25: Anecdotal only
  • 0.50: Some data analysis
  • 0.75: Systematic analysis
  • 1.00: Comprehensive validation

Example (Bootstrap-003, V_meta(s₀) = 0.48):

Completeness: 0.60 (10-category taxonomy, 79.1% coverage)
Effectiveness: 0.40 (Error rate quantified: 5.78%)
Reusability: 0.40 (5 workflows, 5 patterns, 8 guidelines)
Validation: 0.50 (1,336 errors analyzed)
---
V_meta(s₀) = (0.60 + 0.40 + 0.40 + 0.50) / 4 = 0.475 ≈ 0.48

Target: V_meta(s₀) ≥ 0.40 for rapid convergence


Four Baseline Quality Levels

Level 1: Minimal (V_meta <0.20)

Characteristics:

  • No or minimal documentation
  • No quantitative metrics
  • No pattern identification
  • No validation

Iteration 0 time: 1-2 hours Total iterations: 6-10 (standard to slow convergence) Example: Starting from scratch in novel domain

When acceptable: Exploratory research, no prior art

Level 2: Basic (V_meta 0.20-0.39)

Characteristics:

  • Basic documentation (notes, informal structure)
  • Some metrics identified (not quantified)
  • Ad-hoc patterns (not codified)
  • Anecdotal validation

Iteration 0 time: 2-3 hours Total iterations: 5-7 (standard convergence) Example: Bootstrap-002 (V_meta(s₀) = 0.04, but quickly built to basic)

When acceptable: Standard timelines, incremental approach

Level 3: Comprehensive (V_meta 0.40-0.60) ⭐ TARGET

Characteristics:

  • Structured documentation (taxonomy, categories)
  • Quantified metrics (baseline measured)
  • Codified patterns (initial pattern library)
  • Systematic validation (data analysis)

Iteration 0 time: 3-5 hours Total iterations: 3-4 (rapid convergence) Example: Bootstrap-003 (V_meta(s₀) = 0.48, converged in 3 iterations)

When to target: Time constrained, prior art exists, data available

Level 4: Exceptional (V_meta >0.60)

Characteristics:

  • Comprehensive documentation (≥90% coverage)
  • Full quantitative baseline (all metrics)
  • Extensive pattern library
  • Validated methodology (proven in 1+ contexts)

Iteration 0 time: 5-8 hours Total iterations: 2-3 (exceptional rapid convergence) Example: Hypothetical (not yet observed in experiments)

When to target: Adaptation of proven methodology, domain expertise high


Three Strategies for Comprehensive Baseline

Strategy 1: Leverage Prior Art (2-3 hours)

When: Domain has established practices

Steps:

  1. Literature review (30 min):

    • Industry best practices
    • Existing methodologies
    • Academic research
  2. Extract patterns (60 min):

    • Common approaches
    • Known anti-patterns
    • Success metrics
  3. Adapt to context (60 min):

    • What's applicable?
    • What needs modification?
    • What's missing?

Example (Bootstrap-003):

Prior art: Error handling literature
- Detection: Industry standard (logs, monitoring)
- Diagnosis: Root cause analysis patterns
- Recovery: Retry, fallback patterns
- Prevention: Static analysis, linting

Adaptation:
- Detection: meta-cc MCP queries (novel application)
- Diagnosis: Session history analysis (context-specific)
- Recovery: Generic patterns apply
- Prevention: Pre-tool validation (novel approach)

Result: V_completeness = 0.60 (60% from prior art, 40% novel)

Strategy 2: Quantify Baseline (1-2 hours)

When: Rich historical data exists

Steps:

  1. Identify data sources (15 min):

    • Logs, session history, metrics
    • Git history, CI/CD logs
    • Issue trackers, user feedback
  2. Extract metrics (30 min):

    • Volume (total instances)
    • Rate (frequency)
    • Distribution (categories)
    • Impact (cost)
  3. Analyze patterns (45 min):

    • What's most common?
    • What's most costly?
    • What's preventable?

Example (Bootstrap-003):

Data source: meta-cc MCP server
Query: meta-cc query-tools --status error

Results:
- Volume: 1,336 errors
- Rate: 5.78% error rate
- Distribution: File-not-found 12.2%, Read-before-write 5.2%, etc.
- Impact: MTTD 15 min, MTTR 30 min

Analysis:
- Top 3 categories account for 23.7% of errors
- File path issues most preventable
- Clear automation opportunities

Result: V_effectiveness = 0.40 (baseline quantified)

Strategy 3: Domain Universality Analysis (1-2 hours)

When: Domain is universal (errors, testing, CI/CD)

Steps:

  1. Identify universal patterns (30 min):

    • What applies to all projects?
    • What's language-agnostic?
    • What's platform-agnostic?
  2. Document transferability (30 min):

    • What % is reusable?
    • What needs adaptation?
    • What's project-specific?
  3. Create initial taxonomy (30 min):

    • Categorize patterns
    • Identify gaps
    • Estimate coverage

Example (Bootstrap-003):

Universal patterns:
- Errors affect all software (100% universal)
- Detection, diagnosis, recovery, prevention (universal workflow)
- File operations, API calls, data validation (universal categories)

Taxonomy (iteration 0):
- 10 categories identified
- 1,058 errors classified (79.1% coverage)
- Gaps: Edge cases, complex interactions

Result: V_reusability = 0.40 (universal patterns identified)

Baseline Investment ROI

Trade-off: Spend more in iteration 0 to save overall time

Data (from experiments):

BaselineIter 0 TimeTotal IterationsTotal TimeSavings
Minimal (<0.20)1-2h6-1024-40hBaseline
Basic (0.20-0.39)2-3h5-720-28h10-30%
Comprehensive (0.40-0.60)3-5h3-412-16h40-50%
Exceptional (>0.60)5-8h2-310-15h50-60%

Example (Bootstrap-003):

Comprehensive baseline:
- Iteration 0: 3 hours (vs 1 hour minimal)
- Total: 10 hours, 3 iterations
- Savings: 15-25 hours vs minimal baseline (60-70%)

ROI: +2 hours investment → 15-25 hours saved

Recommendation: Target comprehensive (V_meta ≥0.40) when:

  • Time constrained (need fast convergence)
  • Prior art exists (can leverage quickly)
  • Data available (can quantify immediately)

Component-by-Component Guide

Completeness (Documentation)

0.00: No documentation

0.25: Basic notes

  • Informal observations
  • Bullet points
  • No structure

0.50: Partial documentation

  • Some categories/patterns
  • 40-60% coverage
  • Basic structure

0.75: Most documentation

  • Structured taxonomy
  • 70-90% coverage
  • Clear organization

1.00: Comprehensive

  • Complete taxonomy
  • 90%+ coverage
  • Production-ready

Target for V_meta ≥0.40: Completeness ≥0.50

Effectiveness (Quantification)

0.00: No baseline measurement

0.25: Informal estimates

  • "Errors happen sometimes"
  • No numbers

0.50: Some metrics

  • Volume measured (e.g., 1,336 errors)
  • Rate not calculated

0.75: Most metrics

  • Volume, rate, distribution
  • Missing impact (MTTD/MTTR)

1.00: Full quantification

  • All metrics measured
  • Baseline fully quantified

Target for V_meta ≥0.40: Effectiveness ≥0.30

Reusability (Patterns)

0.00: No patterns

0.25: Ad-hoc solutions

  • One-off fixes
  • No generalization

0.50: Some patterns

  • 3-5 patterns identified
  • Partial universality

0.75: Most patterns

  • 5-10 patterns codified
  • High transferability

1.00: Universal patterns

  • Complete pattern library
  • 90%+ transferable

Target for V_meta ≥0.40: Reusability ≥0.40

Validation (Evidence)

0.00: No validation

0.25: Anecdotal

  • "Seems to work"
  • No data

0.50: Some data

  • Basic analysis
  • Limited scope

0.75: Systematic

  • Comprehensive analysis
  • Clear evidence

1.00: Validated

  • Multiple contexts
  • Statistical confidence

Target for V_meta ≥0.40: Validation ≥0.30


Iteration 0 Checklist (for V_meta ≥0.40)

Documentation (Target: Completeness ≥0.50):

  • Create initial taxonomy (≥5 categories)
  • Document 3-5 patterns/workflows
  • Achieve 60-80% coverage
  • Structured markdown documentation

Quantification (Target: Effectiveness ≥0.30):

  • Measure volume (total instances)
  • Calculate rate (frequency)
  • Analyze distribution (category breakdown)
  • Baseline quantified with numbers

Patterns (Target: Reusability ≥0.40):

  • Identify 3-5 universal patterns
  • Document transferability
  • Estimate reusability %
  • Distinguish universal vs domain-specific

Validation (Target: Validation ≥0.30):

  • Analyze historical data
  • Sample validation (≥30 instances)
  • Evidence-based claims
  • Data sources documented

Time Investment: 3-5 hours

Expected V_meta(s₀): 0.40-0.50


Success Criteria

Baseline quality assessment succeeded when:

  1. V_meta target met: V_meta(s₀) ≥ 0.40 achieved
  2. Iteration reduction: 3-4 iterations vs 5-7 (40-50% reduction)
  3. Time savings: Total time ≤12-16 hours (comprehensive baseline)
  4. Gap clarity: Clear objectives for iteration 1-2
  5. ROI positive: Baseline investment <total time saved

Bootstrap-003 Validation:

  • ✅ V_meta(s₀) = 0.48 (target met)
  • ✅ 3 iterations (vs 6 for Bootstrap-002 with minimal baseline)
  • ✅ 10 hours total (60% reduction)
  • ✅ Gaps clear (top 3 automations identified)
  • ✅ ROI: +2h investment → 15h saved

Related Skills

Parent framework:

Uses baseline for:

Validation:


References

Core guide:

Examples:


Status: ✅ Validated | 40-50% iteration reduction | Positive ROI

Spec

λ(repo: Repo) → GateConfig

data GateConfig = GateConfig { lintGate : Bool , testGate : Bool , typeGate : Bool , ciIntegrated : Bool }

Trigger

Use this skill when: The user asks to add quality gates, set up CI checks, configure pre-commit hooks, add linting/testing to CI, or enforce code quality standards automatically.

Do NOT use when: The user wants to run existing tests (use the test runner directly), or wants code review without automation.

Boundaries

Allowed files: .github/workflows/, Makefile, .pre-commit-config.yaml, pyproject.toml/setup.cfg (tool config sections), package.json (scripts section), CI config files, scripts/check-*.sh.

Forbidden: Business logic files, application source code, database migrations, production configuration.

Workflow

  1. Audit current CI/CD pipeline and identify missing gates
  2. Select gate types appropriate to the tech stack (lint, type-check, unit tests, integration tests)
  3. Configure each gate in CI configuration
  4. Add pre-commit hooks for fast local feedback
  5. Verify all gates pass on current codebase before marking done

Verification

# Run after implementation to confirm all gates pass
make ci              # or equivalent: make check-full lint test
pre-commit run --all-files
# For GitHub Actions: gh act -j quality

Implementation

Reference: Historical Results

Past implementations using the BAIME 3-iteration approach (P0 → P1 → P2):

MetricBaselineAfter P0After P1After P2 (Final)
V_instance0.470.720.8220.876
V_meta0.525——0.933
Error Coverage30%50–70%80–90%98%
CI Failure Rate40%——5%
Detection Time480s<10s<30s17.4s

ROI: ~400% in first month (Go CLI project with 5–10 developers).

Reference: Implementation Roadmap

P0 — Core gates (do first, target <10s)

  • check-temp-files.sh — detect debug/temp files accidentally staged
  • check-deps.sh — verify go.mod/package-lock integrity
  • check-fixtures.sh — verify test fixtures exist
  • Wire into make check-workspace and pre-commit hook

P1 — Enhanced coverage (target <30s)

  • check-scripts.sh — shellcheck on all shell scripts
  • check-debug.sh — detect leftover console.log / TODO / FIXME
  • check-imports.sh — goimports / isort / eslint --fix
  • Wire into make check-quality and CI pipeline

P2 — Advanced (target <60s)

  • Language-specific quality: go vet / mypy / tsc
  • Security scanning: gosec / npm audit / safety
  • Coverage threshold gate
  • Branch protection rules requiring CI pass

Reference: Configuration Templates

GitHub Actions (.github/workflows/ci.yml)

name: CI
on: [push, pull_request]
jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install tools
        run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.8
      - name: Quality gates
        run: make ci
      - name: Upload coverage
        uses: codecov/codecov-action@v3

Makefile targets

.PHONY: check-workspace check-quality check-full ci

# P0: Critical (blocks commit, <10s)
check-workspace: check-temp-files check-fixtures check-deps
	@echo "Workspace validation passed"

# P1: Enhanced quality (<30s)
check-quality: check-workspace check-scripts check-debug check-imports
	@echo "Quality validation passed"

# P2: Full validation (<60s)
check-full: check-quality check-go-quality check-security
	@echo "Comprehensive validation passed"

# CI target
ci: check-full test-all build-all
	@echo "CI validation passed"

# Parallel execution (optimization)
check-parallel:
	@make check-temp-files & make check-fixtures & make check-deps & wait

Pre-commit (.pre-commit-config.yaml)

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml

Check script template (scripts/check-<category>.sh)

#!/bin/bash
# check-<category>.sh — <one-line purpose>
# Iteration: P0/P1/P2  |  Historical impact: X% of errors
set -euo pipefail
RED='\033[0;31m'; GREEN='\033[0;32m'; NC='\033[0m'
ERRORS=0

echo "  [1/N] Checking <pattern>..."
if <condition>; then
    echo -e "${RED}ERROR: <description>${NC}"
    echo "Fix: <command>"
    ((ERRORS++)) || true
fi

[ $ERRORS -eq 0 ] && echo -e "${GREEN}All checks passed${NC}" && exit 0
echo -e "${RED}Found $ERRORS error(s) — fix before committing${NC}"; exit 1

Language-specific quality tools

LanguageFormattingLintingType-checkSecurity
Gogo fmtgolangci-lintgo vetgosec
Pythonblackflake8mypysafety
JavaScriptprettiereslinttscnpm audit
Rustcargo fmtcargo clippybuilt-incargo audit

Version pinning (.tool-versions for asdf)

golangci-lint 1.64.8
golang 1.21.0
nodejs 18.17.0
python 3.11.4

Reference: Validation Methods

Error coverage test

# Introduce known error, verify gate catches it
touch test_temp.go
if make check-workspace 2>/dev/null; then echo "MISSED"; exit 1; fi
rm test_temp.go
echo "Detection confirmed"

Performance benchmark

time make check-full   # target: <60s

V_instance formula (for tracking improvement):

V_instance = 0.4×(1−CI_failure_rate)
           + 0.3×(1−avg_iterations/baseline_iterations)
           + 0.2×min(baseline_time/actual_time, 10)/10
           + 0.1×error_coverage_rate

Target: V_instance ≥ 0.85, V_meta ≥ 0.80.

Spec

λ(pipeline: PipelineContext) → OptimizedPipeline

CI/CD Optimization

Transform manual releases into automated, quality-gated, observable pipelines.

Quality gates prevent regression. Automation prevents human error. Observability enables continuous optimization.


When to Use This Skill

Use this skill when:

  • 🚀 Setting up CI/CD: New project needs pipeline infrastructure
  • ⏱️ Slow builds: Build time exceeds 5 minutes
  • 🚫 No quality gates: Coverage, lint, tests not enforced automatically
  • 👤 Manual releases: Human-driven deployment process
  • 📊 No observability: Cannot track pipeline performance metrics
  • 🔄 Broken releases: Defects reaching production regularly
  • 📝 Manual CHANGELOG: Release notes created by hand

Don't use when:

  • ❌ CI/CD already optimal (<2min builds, fully automated, quality-gated)
  • ❌ Non-GitHub Actions without adaptation time (70-80% transferable)
  • ❌ Infrequent releases (monthly or less, automation ROI low)
  • ❌ Single developer projects (overhead may exceed benefit)

Quick Start (30 minutes)

Step 1: Implement Coverage Gate (10 min)

# .github/workflows/ci.yml
- name: Check coverage threshold
  run: |
    COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')
    if (( $(echo "$COVERAGE < 75" | bc -l) )); then
      echo "Coverage $COVERAGE% below threshold 75%"
      exit 1
    fi

Step 2: Automate CHANGELOG Generation (15 min)

# scripts/generate-changelog-entry.sh
# Parse conventional commits: feat:, fix:, docs:, etc.
# Generate CHANGELOG entry automatically
# Zero manual editing required

Step 3: Add Basic Smoke Tests (5 min)

# scripts/smoke-tests.sh
# Test 1: Binary executes
./dist/meta-cc --version

# Test 2: Help output valid
./dist/meta-cc --help | grep "Usage:"

# Test 3: Basic command works
./dist/meta-cc get-session-stats

Five Quality Gate Categories

1. Coverage Threshold Gate

Purpose: Prevent coverage regression Threshold: 75-80% (project-specific) Action: Block merge if below threshold

Implementation:

- name: Coverage gate
  run: |
    COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')
    if (( $(echo "$COVERAGE < 80" | bc -l) )); then
      exit 1
    fi

Principle: Enforcement before improvement - implement gate even if not at target yet

2. Lint Blocking

Purpose: Maintain code quality standards Tool: golangci-lint (Go), pylint (Python), ESLint (JS) Action: Block merge on lint failures

3. CHANGELOG Validation

Purpose: Ensure release notes completeness Check: CHANGELOG.md updated for version changes Action: Block release if CHANGELOG missing

4. Build Verification

Purpose: Ensure compilable code Platforms: Native + cross-compilation targets Action: Block merge on build failure

5. Test Pass Rate

Purpose: Maintain test reliability Threshold: 100% (zero tolerance for flaky tests) Action: Block merge on test failures


Release Automation

Conventional Commits

Format: type(scope): description

Types:

  • feat: - New feature
  • fix: - Bug fix
  • docs: - Documentation only
  • refactor: - Code restructuring
  • test: - Test additions/changes
  • chore: - Maintenance

Automatic CHANGELOG Generation

Tool: Custom script (135 lines, zero dependencies) Process:

  1. Parse git commits since last release
  2. Group by type (Features, Fixes, Documentation)
  3. Generate markdown entry
  4. Prepend to CHANGELOG.md

Time savings: 5-10 minutes per release

GitHub Releases

Automation: Triggered on version tags Artifacts: Binaries, packages, checksums Release notes: Auto-generated from CHANGELOG


Smoke Testing (25 Tests)

Execution Tests (10 tests)

  • Binary runs without errors
  • Help output valid
  • Version command works
  • Basic commands execute
  • Exit codes correct

Consistency Tests (8 tests)

  • Output format stable
  • JSON structure valid
  • Error messages formatted
  • Logging output consistent

Structure Tests (7 tests)

  • Package contents complete
  • File permissions correct
  • Dependencies bundled
  • Configuration files present

Validation: 25/25 tests passing in meta-cc


CI Observability

Metrics Tracked

  1. Build time: Total pipeline duration
  2. Test time: Test execution duration
  3. Coverage: Test coverage percentage
  4. Artifact size: Binary/package size

Storage Strategy

Approach: Git-committed CSV files Location: .ci-metrics/*.csv Retention: Last 100 builds (auto-trimmed) Advantages: Zero infrastructure, automatic versioning

Regression Detection

Method: Moving average baseline (last 10 builds) Threshold: >20% regression triggers PR block Metrics: Build time, test time, artifact size

Implementation:

# scripts/check-performance-regression.sh
BASELINE=$(tail -10 .ci-metrics/build-time.csv | awk '{sum+=$2} END {print sum/NR}')
CURRENT=$BUILD_TIME
if (( $(echo "$CURRENT > $BASELINE * 1.2" | bc -l) )); then
  echo "Build time regression: ${CURRENT}s > ${BASELINE}s + 20%"
  exit 1
fi

Performance Optimization

Native-Only Testing

Principle: Trust mature cross-compilation (Go, Rust) Savings: 5-10 minutes per build (avoid emulation) Risk: Platform-specific bugs (mitigated by Go's 99%+ reliability)

Decision criteria:

  • Mature tooling: YES → native-only
  • Immature tooling: NO → test all platforms

Caching Strategies

  • Go module cache
  • Build artifact cache
  • Test cache for unchanged packages

Parallel Execution

  • Run linters in parallel with tests
  • Matrix builds for multiple Go versions
  • Parallel smoke tests

Proven Results

Validated in bootstrap-007 (meta-cc project):

  • ✅ 11/12 patterns validated (91.7%)
  • ✅ Coverage gate operational (80% threshold)
  • ✅ CHANGELOG automation (zero manual editing)
  • ✅ 25 smoke tests (100% pass rate)
  • ✅ Metrics tracking (4 metrics, 100 builds history)
  • ✅ Regression detection (20% threshold)
  • ✅ 6 iterations, ~18 hours
  • ✅ V_instance: 0.85, V_meta: 0.82

Estimated speedup: 2.5-3.5x vs manual process

Not validated (1/12):

  • E2E pipeline tests (requires staging environment, deferred)

Transferability:

  • GitHub Actions: 100% (native)
  • GitLab CI: 75% (YAML similar, runner differences)
  • Jenkins: 70% (concepts transfer, syntax very different)
  • Overall: 70-80% transferable

Templates

GitHub Actions CI Workflow

# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Go
        uses: actions/setup-go@v4
      - name: Test
        run: go test -coverprofile=coverage.out ./...
      - name: Coverage gate
        run: ./scripts/check-coverage.sh
      - name: Lint
        run: golangci-lint run
      - name: Track metrics
        run: ./scripts/track-metrics.sh
      - name: Check regression
        run: ./scripts/check-performance-regression.sh

GitHub Actions Release Workflow

# .github/workflows/release.yml
name: Release
on:
  push:
    tags: ['v*']
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build
        run: make build-all
      - name: Smoke tests
        run: ./scripts/smoke-tests.sh
      - name: Create release
        uses: actions/create-release@v1
      - name: Upload artifacts
        uses: actions/upload-release-asset@v1

Anti-Patterns

❌ Quality theater: Gates that don't actually block (warnings only) ❌ Over-automation: Automating steps that change frequently ❌ Metrics without action: Tracking data but never acting on it ❌ Flaky gates: Tests that fail randomly (undermines trust) ❌ One-size-fits-all: Same thresholds for all project types


Related Skills

Parent framework:

Complementary:


References

Core guides:

  • Reference materials in experiments/bootstrap-007-cicd-pipeline/
  • Quality gates methodology
  • Release automation guide
  • Smoke testing patterns
  • Observability patterns

Scripts:

  • scripts/check-coverage.sh
  • scripts/generate-changelog-entry.sh
  • scripts/smoke-tests.sh
  • scripts/track-metrics.sh
  • scripts/check-performance-regression.sh

Status: ✅ Production-ready | 91.7% validation | 2.5-3.5x speedup | 70-80% transferable

Spec

λ(target_pkg, target_hotspot, metrics_target) → (refactor_plan, metrics_snapshot, validation_report) | ∧ configs = read_json(experiment-config.json)? ∧ catalogue = configs.metrics_targets ∨ [] ∧ require(cyclomatic(target_hotspot) > 8) ∧ require(catalogue = [] ∨ metrics_target ∈ catalogue) ∧ require(run("make " + metrics_target)) ∧ baseline = results.md ∧ iterations/ ∧ apply(pattern_set = reference/patterns.md) ∧ use(templates/{iteration-template.md,refactoring-safety-checklist.md,tdd-refactoring-workflow.md,incremental-commit-protocol.md}) ∧ automate(metrics_snapshot) via scripts/{capture-*-metrics.sh,count-artifacts.sh} ∧ document(knowledge) → knowledge/{patterns,principles,best-practices} ∧ ensure(complexity_delta(target_hotspot) ≥ 0.30 ∧ cyclomatic(target_hotspot) ≤ 10) ∧ ensure(coverage_delta(target_pkg) ≥ 0.01 ∨ coverage(target_pkg) ≥ 0.70) ∧ validation_report = validate-skill.sh → {inventory.json, V_instance ≥ 0.85} ∧ guarantee(behavior-preserving: all existing tests pass before and after each iteration)

Spec

λ(codebase: CodebaseContext) → StandardizedConventions

Cross-Cutting Concerns

Transform inconsistent patterns into standardized, enforceable conventions with automated compliance.

Detect before standardize. Prioritize by value. Build infrastructure first. Enrich with context. Automate enforcement.


When to Use This Skill

Use this skill when:

  • 🔍 Inconsistent patterns: Error handling, logging, or configuration varies across codebase
  • 📊 Pattern extraction needed: Want to standardize existing practices
  • 🚨 Manual review doesn't scale: Need automated compliance detection
  • 🎯 Prioritization unclear: Many files need work, unclear where to start
  • 🔄 Prevention needed: Want to prevent non-compliant code from merging
  • 👥 Team scaling: Multiple developers need consistent patterns

Don't use when:

  • ❌ Patterns already consistent and enforced with linters/CI
  • ❌ Codebase very small (<1K LOC, minimal benefit)
  • ❌ No refactoring capacity (detection without action is wasteful)
  • ❌ Tools unavailable (need static analysis capabilities)

Quick Start (30 minutes)

Step 1: Pattern Inventory (15 min)

For error handling:

# Count error creation patterns
grep -r "fmt.Errorf\|errors.New" . --include="*.go" | wc -l
grep -r "raise.*Error\|Exception" . --include="*.py" | wc -l
grep -r "throw new Error\|Error(" . --include="*.js" | wc -l

# Identify inconsistencies
# - Bare errors vs wrapped errors
# - Custom error types vs generic
# - Context preservation patterns

For logging:

# Count logging approaches
grep -r "log\.\|slog\.\|logrus\." . --include="*.go" | wc -l
grep -r "logging\.\|logger\." . --include="*.py" | wc -l
grep -r "console\.\|logger\." . --include="*.js" | wc -l

# Identify inconsistencies
# - Multiple logging libraries
# - Structured vs unstructured
# - Log level usage

For configuration:

# Count configuration access patterns
grep -r "os.Getenv\|viper\.\|env:" . --include="*.go" | wc -l
grep -r "os.environ\|config\." . --include="*.py" | wc -l
grep -r "process.env\|config\." . --include="*.js" | wc -l

# Identify inconsistencies
# - Direct env access vs centralized config
# - Missing validation
# - No defaults

Step 2: Prioritize by File Tier (10 min)

Tier 1 (ROI > 10x): User-facing APIs, public interfaces, error infrastructure Tier 2 (ROI 5-10x): Internal services, CLI commands, data processors Tier 3 (ROI < 5x): Test utilities, stubs, deprecated code

Decision: Standardize Tier 1 fully, Tier 2 selectively, defer Tier 3

Step 3: Define Initial Conventions (5 min)

Error Handling:

  • Standard: Sentinel errors + wrapping (Go: %w, Python: from, JS: cause)
  • Context: Operation + Resource + Error Type + Guidance

Logging:

  • Standard: Structured logging (Go: log/slog, Python: logging, JS: winston)
  • Levels: DEBUG, INFO, WARN, ERROR with clear usage guidelines

Configuration:

  • Standard: Centralized Config struct with validation
  • Source: Environment variables (12-Factor App pattern)

Five Universal Principles

1. Detect Before Standardize

Pattern: Automate identification of non-compliant code

Why: Manual inspection doesn't scale, misses edge cases

Implementation:

  1. Create linter/static analyzer for your conventions
  2. Run on full codebase to quantify scope
  3. Categorize violations by severity and user impact
  4. Generate compliance report

Examples by Language:

  • Go: scripts/lint-errors.sh detects bare fmt.Errorf, missing %w
  • Python: pylint rule for bare raise Exception(), missing from clause
  • JavaScript: ESLint rule for throw new Error() without context
  • Rust: clippy rule for unwrap() without context

Validation: Enables data-driven prioritization (know scope before starting)


2. Prioritize by Value

Pattern: High-value files first, low-value files later (or never)

Why: ROI diminishes after 85-90% coverage, focus maximizes impact

File Tier Classification:

Tier 1 (ROI > 10x):

  • User-facing APIs
  • Public interfaces
  • Error infrastructure (sentinel definitions, enrichment functions)
  • Impact: User experience, external API quality

Tier 2 (ROI 5-10x):

  • Internal services
  • CLI commands
  • Data processors
  • Impact: Developer experience, debugging efficiency

Tier 3 (ROI < 5x):

  • Test utilities
  • Stubs/mocks
  • Deprecated code
  • Impact: Minimal, defer or skip

Decision Rule: Standardize Tier 1 fully (100%), Tier 2 selectively (50-80%), defer Tier 3 (0-20%)

Validated Data (meta-cc):

  • Tier 1 (capabilities.go): 16.7x ROI, 25.5% value gain
  • Tier 2 (internal utilities): 8.3x ROI, 6% value gain
  • Tier 3 (stubs): 3x ROI, 1% value gain (skipped)

3. Infrastructure Enables Scale

Pattern: Build foundational components before standardizing call sites

Why: 1000 call sites depend on 10 sentinel errors → build sentinels first

Infrastructure Components:

  1. Sentinel errors/exceptions: Define reusable error types
  2. Error enrichment functions: Add context consistently
  3. Linter/analyzer: Detect non-compliant code
  4. CI integration: Enforce standards automatically

Example Sequence (Go):

1. Create internal/errors/errors.go with sentinels (3 hours)
2. Integrate linter into Makefile (10 minutes)
3. Standardize 53 call sites (5 hours total)
4. Add GitHub Actions workflow (10 minutes)

ROI: Infrastructure (3.3 hours) enables 53 sites (5 hours) + ongoing enforcement (infinite ROI)

Example Sequence (Python):

1. Create errors.py with custom exception classes (2 hours)
2. Create pylint plugin for enforcement (1 hour)
3. Standardize call sites (4 hours)
4. Add tox integration (10 minutes)

Principle: Invest in infrastructure early for multiplicative returns


4. Context Is King

Pattern: Enrich errors with operation context, resource IDs, actionable guidance

Why: 60-75% faster diagnosis with rich context (validated in Bootstrap-013)

Context Layers:

  1. Operation: What was being attempted?
  2. Resource: Which file/URL/record failed?
  3. Error Type: What category of failure?
  4. Guidance: What should user/developer do?

Examples by Language:

Go (Before/After):

// Before: Poor context
return fmt.Errorf("failed to load: %v", err)

// After: Rich context
return fmt.Errorf("failed to load capability '%s' from source '%s': %w",
    name, source, ErrFileIO)

Python (Before/After):

# Before: Poor context
raise Exception(f"failed to load: {err}")

# After: Rich context
raise FileNotFoundError(
    f"failed to load capability '{name}' from source '{source}': {err}",
    name=name, source=source) from err

JavaScript (Before/After):

// Before: Poor context
throw new Error(`failed to load: ${err}`);

// After: Rich context
throw new FileLoadError(
    `failed to load capability '${name}' from source '${source}': ${err}`,
    { name, source, cause: err }
);

Rust (Before/After):

// Before: Poor context
Err(err)?

// After: Rich context
Err(err).context(format!(
    "failed to load capability '{}' from source '{}'", name, source))?

Impact: Error diagnosis time reduced by 60-75% (from minutes to seconds)


5. Automate Enforcement

Pattern: CI blocks non-compliant code, prevents regression

Why: Manual review doesn't scale, humans forget conventions

Implementation (language-agnostic):

  1. Integrate linter into build system (Makefile, package.json, Cargo.toml)
  2. Add CI workflow (GitHub Actions, GitLab CI, CircleCI)
  3. Run on every push/PR
  4. Block merge if violations found
  5. Provide clear error messages with fix guidance

Example CI Setup (GitHub Actions):

name: Lint Cross-Cutting Concerns
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Run error handling linter
        run: make lint-errors
      - name: Fail on violations
        run: exit $?

Validated Data (meta-cc):

  • CI setup time: 20 minutes
  • Ongoing maintenance: 0 hours (fully automated)
  • Regression rate: 0% (100% enforcement)
  • False positive rate: 0% (accurate linter)

File Tier Prioritization Framework

ROI Calculation

Formula:

For each file:
  1. User Impact: high (10) / medium (5) / low (1)
  2. Error Sites (N): Count of patterns to standardize
  3. Time Investment (T): Estimated hours to refactor
  4. Value Gain (ΔV): Expected improvement (0-100%)
  5. ROI = (ΔV × Project Horizon) / T

Project Horizon: Expected lifespan (e.g., 2 years = 24 months)

Example Calculation (capabilities.go, meta-cc):

User Impact: High (10) - Affects capability loading
Error Sites: 8 sites
Time Investment: 0.5 hours
Value Gain: 25.5% (from 0.233 to 0.488)
Project Horizon: 24 months
ROI = (0.255 × 24) / 0.5 = 12.24 (round to 12x)

Classification: Tier 1 (ROI > 10x)

Tier Decision Matrix

TierROI RangeStrategyCoverage Target
Tier 1>10xStandardize fully100%
Tier 25-10xSelective standardization50-80%
Tier 3<5xDefer or skip0-20%

Meta-cc Results:

  • 1 Tier 1 file (capabilities.go): 100% standardized
  • 5 Tier 2 files: 60% standardized (strategic selection)
  • 10+ Tier 3 files: 0% standardized (deferred)

Pattern Extraction Workflow

Phase 1: Observe (Iterations 0-1)

Objective: Catalog existing patterns and measure consistency

Steps:

  1. Pattern Inventory:

    • Count patterns by type (error handling, logging, config)
    • Identify variations (fmt.Errorf vs errors.New, log vs slog)
    • Calculate consistency percentage
  2. Baseline Metrics:

    • Total occurrences per pattern
    • Consistency ratio (dominant pattern / total)
    • Coverage gaps (files without patterns)
  3. Gap Analysis:

    • What's missing? (sentinel errors, structured logging, config validation)
    • What's inconsistent? (multiple approaches in same concern)
    • What's priority? (user-facing vs internal)

Output: Pattern inventory, baseline metrics, gap analysis


Phase 2: Codify (Iterations 2-4)

Objective: Define conventions and create enforcement tools

Steps:

  1. Convention Selection:

    • Choose standard library or tool per concern
    • Document usage guidelines (when to use each pattern)
    • Define anti-patterns (what to avoid)
  2. Infrastructure Creation:

    • Create sentinel errors/exceptions
    • Create enrichment utilities
    • Create configuration struct with validation
  3. Linter Development:

    • Detect non-compliant patterns
    • Provide fix suggestions
    • Generate compliance reports

Output: Conventions document, infrastructure code, linter script


Phase 3: Automate (Iterations 5-6)

Objective: Enforce conventions and prevent regressions

Steps:

  1. Standardize High-Value Files (Tier 1):

    • Apply conventions systematically
    • Test thoroughly (no behavior changes)
    • Measure value improvement
  2. CI Integration:

    • Add linter to Makefile/build system
    • Create GitHub Actions workflow
    • Configure blocking on violations
  3. Documentation:

    • Update contributing guidelines
    • Add examples to README
    • Document migration process for remaining files

Output: Standardized Tier 1 files, CI enforcement, documentation


Convention Selection Process

Error Handling Conventions

Decision Tree:

1. Does language have built-in error wrapping?
   Go 1.13+: Use fmt.Errorf with %w
   Python 3+: Use raise ... from err
   JavaScript: Use Error.cause (Node 16.9+)
   Rust: Use thiserror + anyhow

2. Define sentinel errors:
   - ErrFileIO, ErrNetworkFailure, ErrParseError, ErrNotFound, etc.
   - Use custom error types for domain-specific errors

3. Context enrichment template:
   Operation + Resource + Error Type + Guidance

13 Best Practices (Go example, adapt to language):

  1. Use sentinel errors for common failures
  2. Wrap errors with %w for Is/As support
  3. Add operation context (what was attempted)
  4. Include resource IDs (file paths, URLs, record IDs)
  5. Preserve error chain (don't break wrapping)
  6. Don't log and return (caller decides)
  7. Provide actionable guidance in user-facing errors
  8. Use custom error types for domain logic
  9. Validate error paths in tests
  10. Document error contract in godoc/docstrings
  11. Use errors.Is for sentinel matching
  12. Use errors.As for type extraction
  13. Avoid panic (except unrecoverable programmer errors)

Logging Conventions

Decision Tree:

1. Choose structured logging library:
   Go: log/slog (standard library, performant)
   Python: logging (standard library)
   JavaScript: winston or pino
   Rust: tracing or log

2. Define log levels:
   - DEBUG: Detailed diagnostic (dev only)
   - INFO: General informational (default)
   - WARN: Unexpected but handled
   - ERROR: Requires intervention

3. Structured logging format:
   logger.Info("operation complete",
     "resource", resourceID,
     "duration_ms", duration.Milliseconds())

13 Best Practices (Go log/slog example):

  1. Use structured logging (key-value pairs)
  2. Configure log level via environment variable
  3. Use contextual logger (logger.With for request context)
  4. Include operation name in every log
  5. Add resource IDs for traceability
  6. Use DEBUG for diagnostic details
  7. Use INFO for business events
  8. Use WARN for recoverable issues
  9. Use ERROR for failures requiring action
  10. Don't log sensitive data (passwords, tokens)
  11. Use consistent key names (user_id not userId/userID)
  12. Output to stderr (stdout for application output)
  13. Include timestamps and source location

Configuration Conventions

Decision Tree:

1. Choose configuration approach:
   - 12-Factor App: Environment variables (recommended)
   - Config files: YAML/TOML (if complex config needed)
   - Hybrid: Env vars with file override

2. Create centralized Config struct:
   - All configuration in one place
   - Validation on load
   - Sensible defaults
   - Clear documentation

3. Environment variable naming:
   PREFIX_COMPONENT_SETTING (e.g., APP_DB_HOST)

14 Best Practices (Go example):

  1. Centralize config in single struct
  2. Load config once at startup
  3. Validate all required fields
  4. Provide sensible defaults
  5. Use environment variables for deployment differences
  6. Use config files for complex/nested config
  7. Never hardcode secrets (use env vars or secret management)
  8. Document all config options (README or godoc)
  9. Use consistent naming (PREFIX_COMPONENT_SETTING)
  10. Parse and validate early (fail fast)
  11. Make config immutable after load
  12. Support config reload for long-running services (optional)
  13. Log effective config on startup (mask secrets)
  14. Provide example config file (.env.example)

Proven Results

Validated in bootstrap-013 (meta-cc project):

  • ✅ Error handling: 70% baseline consistency → 90% standardized (Tier 1 files)
  • ✅ Logging: 0.7% baseline coverage → 90% adoption (MCP server, capabilities)
  • ✅ Configuration: 40% baseline consistency → 80% centralized
  • ✅ ROI: 16.7x for Tier 1 files (capabilities.go), 8.3x for Tier 2
  • ✅ Diagnosis speed: 60-75% faster with rich error context
  • ✅ CI enforcement: 0% regression rate, 20-minute setup

Transferability Validation:

  • Go: 90% (native implementation)
  • Python: 80-85% (exception classes, logging module)
  • JavaScript: 75-80% (Error.cause, winston)
  • Rust: 85-90% (thiserror, anyhow, tracing)
  • Overall: 80-90% transferable ✅

Universal Components (language-agnostic):

  • 5 principles (100% universal)
  • File tier prioritization (100% universal)
  • ROI calculation framework (100% universal)
  • Pattern extraction workflow (95% universal, tooling varies)
  • Context enrichment structure (100% universal)

Common Anti-Patterns

❌ Pattern Sprawl: Multiple error handling approaches in same codebase (consistency loss) ❌ Standardize Everything: Wasting effort on Tier 3 files (low ROI) ❌ No Infrastructure: Standardizing call sites before creating sentinels (rework needed) ❌ Poor Context: Generic errors without operation/resource info (slow diagnosis) ❌ Manual Enforcement: Relying on code review instead of CI (regression risk) ❌ Premature Optimization: Building complex linter before understanding patterns (over-engineering)


Templates and Examples

Templates

Examples


Related Skills

Parent framework:

Complementary domains:


References

Core methodology:

Best practices by concern:

Language-specific guides:


Status: ✅ Production-ready | Validated in meta-cc | 60-75% faster diagnosis | 80-90% transferable

Spec

λ(project: ProjectContext) → DependencyHealthReport

Dependency Health

Systematic dependency management: security-first, batch remediation, policy-driven.

Dependencies are attack surface. Manage them systematically, not reactively.


When to Use This Skill

Use this skill when:

  • 🔒 Security vulnerabilities: Known CVEs in dependencies
  • 📅 Outdated dependencies: Packages months/years behind
  • ⚖️ License compliance: Need to verify license compatibility
  • 🎯 Systematic management: Ad-hoc updates causing issues
  • 🔄 Frequent breakage: Dependency updates break builds
  • 📊 No visibility: Don't know dependency health status

Don't use when:

  • ❌ Zero dependencies (static binary, no external deps)
  • ❌ Dependencies already managed systematically
  • ❌ Short-lived projects (throwaway tools, prototypes)
  • ❌ Frozen dependencies (legacy systems, no updates allowed)

Quick Start (30 minutes)

Step 1: Audit Current State (10 min)

# Go projects
go list -m -u all | grep '\['

# Node.js
npm audit

# Python
pip list --outdated

# Identify:
# - Security vulnerabilities
# - Outdated packages (>6 months old)
# - License issues

Step 2: Prioritize by Security (10 min)

Severity levels:

  • Critical: Actively exploited, RCE, data breach
  • High: Authentication bypass, privilege escalation
  • Medium: DoS, information disclosure
  • Low: Minor issues, limited impact

Action timeline:

  • Critical: Immediate (same day)
  • High: Within 1 week
  • Medium: Within 1 month
  • Low: Next quarterly update

Step 3: Batch Remediation (10 min)

# Group compatible updates
# Test together
# Create single PR with all updates

# Example: Update all patch versions
go get -u=patch ./...
go test ./...
git commit -m "chore(deps): update dependencies (security + freshness)"

Security-First Prioritization

Vulnerability Assessment

Critical vulnerabilities (immediate action):

  • RCE (Remote Code Execution)
  • SQL Injection
  • Authentication bypass
  • Data breach potential

High vulnerabilities (1 week):

  • Privilege escalation
  • XSS (Cross-Site Scripting)
  • CSRF (Cross-Site Request Forgery)
  • Sensitive data exposure

Medium vulnerabilities (1 month):

  • DoS (Denial of Service)
  • Information disclosure
  • Insecure defaults
  • Weak cryptography

Low vulnerabilities (quarterly):

  • Minor issues
  • Informational
  • False positives

Remediation Strategy

Priority queue:
1. Critical vulnerabilities (immediate)
2. High vulnerabilities (week)
3. Dependency freshness (monthly)
4. License compliance (quarterly)
5. Medium/low vulnerabilities (quarterly)

Batch Remediation Strategy

Why Batch Updates?

Problems with one-at-a-time:

  • Update fatigue (100+ dependencies)
  • Test overhead (N tests for N updates)
  • PR overhead (N reviews)
  • Potential conflicts (update A breaks with update B)

Benefits of batching:

  • Single test run for all updates
  • Single PR review
  • Detect incompatibilities early
  • 6x faster (validated in meta-cc)

Batching Strategies

Strategy 1: By Severity

# Batch 1: All security patches
# Batch 2: All minor/patch updates
# Batch 3: All major updates (breaking changes)

Strategy 2: By Compatibility

# Batch 1: Compatible updates (no breaking changes)
# Batch 2: Breaking changes (one at a time)

Strategy 3: By Timeline

# Batch 1: Immediate (critical vulnerabilities)
# Batch 2: Weekly (high vulnerabilities + freshness)
# Batch 3: Monthly (medium vulnerabilities)
# Batch 4: Quarterly (low vulnerabilities + license)

Policy-Driven Compliance

Security Policies

# .dependency-policy.yml
security:
  critical_vulnerabilities:
    action: block_merge
    max_age: 0 days
  high_vulnerabilities:
    action: block_merge
    max_age: 7 days
  medium_vulnerabilities:
    action: warn
    max_age: 30 days

Freshness Policies

freshness:
  max_age:
    major: 12 months
    minor: 6 months
    patch: 3 months
  exceptions:
    - package: legacy-lib
      reason: "No maintained alternative"

License Policies

licenses:
  allowed:
    - MIT
    - Apache-2.0
    - BSD-3-Clause
  denied:
    - GPL-3.0  # Copyleft issues
    - AGPL-3.0
  review_required:
    - Custom
    - Proprietary

Automation Tools

Vulnerability Scanning

# Go: govulncheck
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...

# Node.js: npm audit
npm audit --audit-level=moderate

# Python: safety
pip install safety
safety check

# Rust: cargo-audit
cargo install cargo-audit
cargo audit

Automated Updates

# Dependabot (GitHub)
# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "gomod"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 5
    groups:
      security:
        patterns:
          - "*"
        update-types:
          - "patch"
          - "minor"

License Checking

# Go: go-licenses
go install github.com/google/go-licenses@latest
go-licenses check ./...

# Node.js: license-checker
npx license-checker --summary

# Python: pip-licenses
pip install pip-licenses
pip-licenses

Proven Results

Validated in bootstrap-010 (meta-cc project):

  • ✅ Security-first prioritization implemented
  • ✅ Batch remediation (5 dependencies updated together)
  • ✅ 6x speedup: 9 hours manual → 1.5 hours systematic
  • ✅ 3 iterations (rapid convergence)
  • ✅ V_instance: 0.92 (highest among experiments)
  • ✅ V_meta: 0.85

Metrics:

  • Vulnerabilities: 2 critical → 0 (resolved immediately)
  • Freshness: 45% outdated → 15% outdated
  • License compliance: 100% (all MIT/Apache-2.0/BSD)

Transferability:

  • Go (gomod): 100% (native)
  • Node.js (npm): 90% (npm audit similar)
  • Python (pip): 85% (safety similar)
  • Rust (cargo): 90% (cargo audit similar)
  • Java (Maven): 85% (OWASP dependency-check)
  • Overall: 88% transferable

Common Patterns

Pattern 1: Security Update Workflow

# 1. Scan for vulnerabilities
govulncheck ./...

# 2. Review severity
# Critical/High → immediate
# Medium/Low → batch

# 3. Update dependencies
go get -u github.com/vulnerable/package@latest

# 4. Test
go test ./...

# 5. Commit
git commit -m "fix(deps): resolve CVE-XXXX-XXXXX in package X"

Pattern 2: Monthly Freshness Update

# 1. Check for updates
go list -m -u all

# 2. Batch updates (patch/minor)
go get -u=patch ./...

# 3. Test
go test ./...

# 4. Commit
git commit -m "chore(deps): monthly dependency freshness update"

Pattern 3: Major Version Upgrade

# One at a time (breaking changes)
# 1. Update single package
go get package@v2

# 2. Fix breaking changes
# ... code modifications ...

# 3. Test extensively
go test ./...

# 4. Commit
git commit -m "feat(deps): upgrade package to v2"

Anti-Patterns

❌ Ignoring security advisories: "We'll update later" ❌ One-at-a-time updates: 100 separate PRs for 100 dependencies ❌ Automatic merging: Dependabot auto-merge without testing ❌ Dependency pinning forever: Never updating to avoid breakage ❌ License ignorance: Not checking license compatibility ❌ No testing after updates: Assuming updates won't break anything


Related Skills

Parent framework:

Complementary:

Acceleration:


References

Core guides:

  • Reference materials in experiments/bootstrap-010-dependency-health/
  • Security-first prioritization framework
  • Batch remediation strategies
  • Policy-driven compliance

Tools:

  • govulncheck (Go)
  • npm audit (Node.js)
  • safety (Python)
  • cargo-audit (Rust)
  • go-licenses (license checking)

Status: ✅ Production-ready | 6x speedup | 88% transferable | V_instance 0.92 (highest)

Spec

λ(project: ProjectContext) → DocumentationArtifacts

Documentation Management Skill

Systematic documentation methodology for Claude Code projects using empirically validated templates, patterns, and automation. All artifacts are written in Markdown.


Frontmatter

name: documentation-management
version: 1.0.0
status: validated
domain: Documentation
tags: [documentation, writing, templates, automation, quality]
validated_on: meta-cc
convergence_iterations: 4
total_development_time: 20-22 hours
value_instance: 0.82
value_meta: 0.82
transferability: 93%

Validation Evidence:

  • V_instance = 0.82: Accuracy 0.75, Completeness 0.85, Usability 0.80, Maintainability 0.85
  • V_meta = 0.82: Completeness 0.75, Effectiveness 0.70, Reusability 0.85, Validation 0.80
  • Retrospective Validation: 90% structural match, 93% transferability, -3% adaptation effort across 3 diverse documentation types
  • Dual Convergence: Both layers exceeded 0.80 threshold in Iteration 3

Quick Start

1. Understand Your Documentation Need

Identify which documentation type you need:

  • Tutorial: Step-by-step learning path (use templates/tutorial-structure.md)
  • Concept: Explain technical concept (use templates/concept-explanation.md)
  • Example: Demonstrate methodology (use templates/example-walkthrough.md)
  • Reference: Comprehensive command/API guide (use templates/quick-reference.md)
  • Troubleshooting: Problem-solution guide (use templates/troubleshooting-guide.md)

2. Start with a Template

# Copy the appropriate template
cp .claude/skills/documentation-management/templates/tutorial-structure.md docs/tutorials/my-guide.md

# Follow the template structure and guidelines
# Fill in sections with your content

3. Apply Core Patterns

Use these validated patterns while writing:

  • Progressive Disclosure: Start simple, add complexity gradually
  • Example-Driven: Pair every concept with concrete example
  • Problem-Solution: Structure around user problems, not features

4. Automate Quality Checks

# Validate all links
python .claude/skills/documentation-management/tools/validate-links.py docs/

# Validate command syntax
python .claude/skills/documentation-management/tools/validate-commands.py docs/

5. Evaluate Quality

Use the quality checklist in each template to self-assess:

  • Accuracy: Technical correctness
  • Completeness: All user needs addressed
  • Usability: Clear navigation and examples
  • Maintainability: Modular structure and automation

Core Methodology

Documentation Lifecycle

This methodology follows a 4-phase lifecycle:

Phase 1: Needs Analysis

  • Identify target audience and their questions
  • Determine documentation type needed
  • Gather technical details and examples

Phase 2: Strategy Formation

  • Select appropriate template
  • Plan progressive disclosure structure
  • Identify core patterns to apply

Phase 3: Writing/Execution

  • Follow template structure
  • Apply patterns (progressive disclosure, example-driven, problem-solution)
  • Create concrete examples

Phase 4: Validation

  • Run automation tools (link validation, command validation)
  • Review against template quality checklist
  • Test with target audience if possible

Value Function (Quality Assessment)

V_instance (Documentation Quality) = (Accuracy + Completeness + Usability + Maintainability) / 4

Component Definitions:

  • Accuracy (0.0-1.0): Technical correctness, working links, valid commands
  • Completeness (0.0-1.0): User needs addressed, edge cases covered
  • Usability (0.0-1.0): Navigation, clarity, examples, accessibility
  • Maintainability (0.0-1.0): Modular structure, automation, version tracking

Target: V_instance ≥ 0.80 for production-ready documentation

Example Scoring:

  • 0.90+: Exceptional (comprehensive, validated, highly usable)
  • 0.80-0.89: Excellent (production-ready, all needs met)
  • 0.70-0.79: Good (functional, minor gaps)
  • 0.60-0.69: Fair (usable, notable gaps)
  • <0.60: Poor (significant issues)

Templates

This skill provides 5 empirically validated templates:

1. Tutorial Structure (templates/tutorial-structure.md)

  • Purpose: Step-by-step learning path for complex topics
  • Size: ~300 lines
  • Validation: 100% match with Installation Guide
  • Best For: Onboarding, feature walkthroughs, methodology guides
  • Key Sections: What/Why/Prerequisites/Concepts/Workflow/Examples/Troubleshooting

2. Concept Explanation (templates/concept-explanation.md)

  • Purpose: Explain single technical concept clearly
  • Size: ~200 lines
  • Validation: 100% match with JSONL Reference
  • Best For: Architecture docs, design patterns, technical concepts
  • Key Sections: Definition/Why/When/How/Examples/Edge Cases/Related

3. Example Walkthrough (templates/example-walkthrough.md)

  • Purpose: Demonstrate methodology through concrete example
  • Size: ~250 lines
  • Validation: Validated in Testing and Error Recovery examples
  • Best For: Case studies, success stories, before/after demos
  • Key Sections: Context/Setup/Execution/Results/Lessons/Transferability

4. Quick Reference (templates/quick-reference.md)

  • Purpose: Comprehensive command/API reference
  • Size: ~350 lines
  • Validation: 70% match with CLI Reference (85% transferability)
  • Best For: CLI tools, APIs, configuration options
  • Key Sections: Overview/Common Tasks/Commands/Parameters/Examples/Troubleshooting

5. Troubleshooting Guide (templates/troubleshooting-guide.md)

  • Purpose: Problem-solution structured guide
  • Size: ~550 lines
  • Validation: Validated with 3 BAIME issues
  • Best For: FAQ, debugging guides, error resolution
  • Key Sections: Problem Categories/Symptoms/Diagnostics/Solutions/Prevention

Retrospective Validation Results:

  • 90% structural match across 3 diverse documentation types
  • 93% transferability (templates work with <10% adaptation)
  • -3% adaptation effort (net time savings)
  • 9/10 template fit quality

Patterns

1. Progressive Disclosure

Problem: Users overwhelmed by complex topics presented all at once. Solution: Structure content from simple to complex, general to specific.

Implementation:

  • Start with "What is X?" before "How does X work?"
  • Show simple examples before advanced scenarios
  • Use hierarchical sections (Overview → Details → Edge Cases)
  • Defer advanced topics to separate sections

Validation: 4+ uses across BAIME guide, iteration docs, FAQ, examples

See: patterns/progressive-disclosure.md for comprehensive guide

2. Example-Driven Explanation

Problem: Abstract concepts hard to understand without concrete examples. Solution: Pair every concept with concrete, realistic example.

Implementation:

  • Define concept briefly
  • Immediately show example
  • Explain how example demonstrates concept
  • Show variations (simple → complex)

Validation: 3+ uses across BAIME concepts, templates, examples

See: patterns/example-driven-explanation.md for comprehensive guide

3. Problem-Solution Structure

Problem: Documentation organized around features, not user problems. Solution: Structure around problems users actually face.

Implementation:

  • Identify user pain points
  • Group by problem category (not feature)
  • Format: Symptom → Diagnosis → Solution → Prevention
  • Include real error messages and outputs

Validation: 3+ uses across troubleshooting guides, error recovery

See: patterns/problem-solution-structure.md for comprehensive guide


Automation Tools

1. Link Validation (tools/validate-links.py)

Purpose: Detect broken internal/external links, missing files Usage: python tools/validate-links.py docs/ Output: List of broken links with file locations Speedup: 30x faster than manual checking Tested: 13/15 links valid in meta-cc docs

2. Command Validation (tools/validate-commands.py)

Purpose: Validate code blocks for correct syntax, detect typos Usage: python tools/validate-commands.py docs/ Output: Invalid commands with line numbers Speedup: 20x faster than manual testing Tested: 20/20 commands valid in BAIME guide

Both tools are production-ready and integrate with CI/CD for automated quality gates.


Examples

Example 1: BAIME Usage Guide (Tutorial)

Context: Create comprehensive guide for BAIME methodology Template Used: tutorial-structure.md Result: 1100-line tutorial with V_instance = 0.82

Key Decisions:

  • Two domain examples (Testing + Error Recovery) to demonstrate transferability
  • FAQ section for quick answers (11 questions)
  • Troubleshooting section with concrete examples (3 issues)
  • Progressive disclosure: What → Why → How → Examples

Lessons Learned:

  • Multiple examples prove universality (single example insufficient)
  • Comparison table synthesizes insights
  • FAQ should be added early (high ROI)

Example 2: CLI Reference (Quick Reference)

Context: Document meta-cc CLI commands Template Used: quick-reference.md Result: Comprehensive command reference with 70% template match

Adaptations:

  • Added command categories (MCP tools vs CLI)
  • Emphasized output format (JSONL/TSV)
  • Included jq filter examples
  • More example-heavy than template (CLI needs concrete usage)

Lessons Learned:

  • Quick reference template adapts well to CLI tools
  • Examples more critical than structure for CLI docs
  • ~15% adaptation effort for specialized domains

Example 3: Retrospective Validation Study

Context: Test templates on existing meta-cc documentation Approach: Applied templates to 3 diverse docs (CLI, Installation, JSONL)

Results:

  • 90% structural match: Templates matched existing high-quality docs
  • 93% transferability: <10% adaptation needed
  • -3% adaptation effort: Net time savings
  • Independent evolution: 2/3 docs evolved same structure naturally

Insight: Templates extract genuine universal patterns (descriptive, not prescriptive)


Quality Standards

Production-Ready Criteria

Documentation is production-ready when:

  • ✅ V_instance ≥ 0.80 (all components)
  • ✅ All links valid (automated check)
  • ✅ All commands tested (automated check)
  • ✅ Template quality checklist complete
  • ✅ Examples concrete and realistic
  • ✅ Reviewed by domain expert (if available)

Quality Scoring Guide

Accuracy Assessment:

  • All technical details correct?
  • Links valid?
  • Commands work as documented?
  • Examples realistic and tested?

Completeness Assessment:

  • All user questions answered?
  • Edge cases covered?
  • Prerequisites clear?
  • Examples sufficient?

Usability Assessment:

  • Navigation intuitive?
  • Examples concrete?
  • Jargon defined?
  • Progressive disclosure applied?

Maintainability Assessment:

  • Modular structure?
  • Automated validation?
  • Version tracked?
  • Easy to update?

Transferability

Cross-Domain Validation

This methodology has been validated across:

  • Tutorial Documentation: BAIME guide, Installation guide
  • Reference Documentation: CLI reference, JSONL reference
  • Concept Documentation: BAIME concepts (6 concepts)
  • Troubleshooting: BAIME issues, error recovery

Transferability Rate: 93% (empirically measured) Adaptation Effort: -3% (net time savings) Domain Independence: Universal (applies to all documentation types)

Adaptation Guidelines

When adapting templates to your domain:

  1. Keep Core Structure (90% match is ideal)

    • Section hierarchy
    • Progressive disclosure
    • Example-driven approach
  2. Adapt Content Depth (10-15% variation)

    • CLI tools need more examples
    • Concept docs need more diagrams
    • Troubleshooting needs real error messages
  3. Customize Examples (domain-specific)

    • Use your project's terminology
    • Show realistic use cases
    • Include actual outputs
  4. Follow Quality Checklist (from template)

    • Ensures consistency
    • Prevents common mistakes
    • Validates completeness

Usage Guide

For New Documentation

  1. Identify Documentation Type

    • What is the primary user need? (learn, understand, reference, troubleshoot)
    • Select matching template
  2. Copy Template

    cp templates/[template-name].md docs/[your-doc].md
    
  3. Follow Template Structure

    • Read "When to Use" section
    • Follow section guidelines
    • Apply quality checklist
  4. Apply Core Patterns

    • Progressive disclosure (simple → complex)
    • Example-driven (concept + example)
    • Problem-solution (if applicable)
  5. Validate Quality

    python tools/validate-links.py docs/[your-doc].md
    python tools/validate-commands.py docs/[your-doc].md
    
  6. Self-Assess

    • Calculate V_instance score
    • Review template checklist
    • Iterate if needed

For Existing Documentation

  1. Assess Current State

    • Calculate V_instance (current quality)
    • Identify gaps (completeness, usability)
    • Determine target V_instance
  2. Select Improvement Strategy

    • Structural: Apply template structure (if V_instance < 0.60)
    • Incremental: Add missing sections (if V_instance 0.60-0.75)
    • Polish: Apply patterns and validation (if V_instance > 0.75)
  3. Apply Template Incrementally

    • Don't rewrite from scratch
    • Map existing content to template sections
    • Fill gaps systematically
  4. Validate Improvements

    • Run automation tools
    • Recalculate V_instance
    • Verify gap closure

Best Practices

Writing Principles

  1. Empirical Validation Over Assumptions

    • Test examples before documenting
    • Validate links and commands automatically
    • Use real user feedback when available
  2. Multiple Examples Demonstrate Universality

    • Single example shows possibility
    • Two examples show pattern
    • Three examples prove universality
  3. Progressive Disclosure Reduces Cognitive Load

    • Start with "What" and "Why"
    • Move to "How"
    • End with "Advanced"
  4. Problem-Solution Matches User Mental Model

    • Users come with problems, not feature requests
    • Structure guides around solving problems
    • Include symptoms, diagnosis, solution
  5. Automation Enables Scale

    • Manual validation doesn't scale
    • Invest in automation tools early
    • Integrate into CI/CD
  6. Template Creation Is Infrastructure

    • First template takes time (~2 hours)
    • Subsequent uses save 3-4 hours each
    • ROI is multiplicative

Common Mistakes

  1. Deferring Quick Wins

    • FAQ sections take 30-45 minutes but add significant value
    • Add FAQ early (Iteration 1, not later)
  2. Single Example Syndrome

    • One example doesn't prove transferability
    • Add second example to demonstrate pattern
    • Comparison table synthesizes insights
  3. Feature-Centric Structure

    • Users don't care about features, they care about problems
    • Restructure around user problems
    • Use problem-solution pattern
  4. Abstract-Only Explanations

    • Abstract concepts without examples don't stick
    • Always pair concept with concrete example
    • Show variations (simple → complex)
  5. Manual Validation Only

    • Manual link/command checking is error-prone
    • Create automation tools early
    • Run in CI for continuous validation

Integration with BAIME

This methodology was developed using BAIME and can be used to document other BAIME experiments:

When Creating BAIME Documentation

  1. Use Tutorial Structure for methodology guides

    • What is the methodology?
    • When to use it?
    • Step-by-step workflow
    • Example applications
  2. Use Example Walkthrough for domain examples

    • Show concrete BAIME application
    • Include value scores at each iteration
    • Demonstrate transferability
  3. Use Troubleshooting Guide for common issues

    • Structure around actual errors encountered
    • Include diagnostic workflows
    • Show recovery patterns
  4. Apply Progressive Disclosure

    • Start with simple example (rich baseline)
    • Add complex example (minimal baseline)
    • Compare and synthesize

Extraction from BAIME Experiments

After BAIME experiment converges, extract documentation:

  1. Patterns → pattern files in skill
  2. Templates → template files in skill
  3. Methodology → tutorial in docs/methodology/
  4. Examples → examples/ in skill
  5. Tools → tools/ in skill

This skill itself was extracted from a BAIME experiment (Bootstrap-Documentation).


Maintenance

Version: 1.0.0 (validated and converged) Created: 2025-10-19 Last Updated: 2025-10-19 Status: Production-ready

Validated On:

  • BAIME Usage Guide (Tutorial)
  • CLI Reference (Quick Reference)
  • Installation Guide (Tutorial)
  • JSONL Reference (Concept)
  • Error Recovery Example (Example Walkthrough)

Known Limitations:

  • No visual aid generation (diagrams, flowcharts) - manual process
  • No maintenance workflow (focus on creation methodology)
  • Spell checker not included (link and command validation only)

Future Enhancements:

  • Add visual aid templates (architecture diagrams, flowcharts)
  • Create maintenance workflow documentation
  • Develop spell checker with technical term dictionary
  • Add third domain example (CI/CD or Knowledge Transfer)

Changelog:

  • v1.0.0 (2025-10-19): Initial release from BAIME experiment
    • 5 templates (all validated)
    • 3 patterns (all validated)
    • 2 automation tools (both working)
    • Retrospective validation complete (93% transferability)

References

Source Experiment: /home/yale/work/meta-cc/experiments/documentation-methodology/ Convergence: 4 iterations, ~20-22 hours, V_instance=0.82, V_meta=0.82 Methodology: BAIME (Bootstrapped AI Methodology Engineering)

Related Skills:

  • testing-strategy: Systematic testing methodology
  • error-recovery: Error handling patterns
  • knowledge-transfer: Onboarding methodologies

External Resources:

Spec

λ(input: FeatureDiscussion | ProposalDoc | PlanDoc) → ImplementedFeature

Role: Orchestrator Only

This skill is an orchestrator. It coordinates phases and evaluates outputs.

This skill MUST NOT:

  • Write implementation code directly
  • Write or edit any file directly (no Write or Edit tools — use Task agents)
  • Perform proposal or plan review inline (without spawning a Task agent)
  • Skip any phase, even if the caller provides detailed implementation specs

If the caller provides detailed design specs (class names, method signatures, rules, etc.), treat that as discussion input — NOT as a replacement for proposal/plan documents. You MUST still execute all phases in order.


Phase 3: Generate Proposal

Trigger: No docs/proposals/proposal-<slug>.md exists yet.

If proposal already exists: skip to Phase 4.

Steps:

  1. Derive <slug> from the feature topic (lowercase, hyphenated).
  2. Spawn a Task agent (subagent_type: general-purpose) to read relevant source files and produce a grounded proposal draft:
    • Task agent reads all source files related to the feature area
    • Task agent writes docs/proposals/proposal-<slug>.md with this structure:
      • Problem Statement, Goals, Non-Goals, Design, Alternatives, Open Questions
    • Every design decision must reference actual file paths, class names, and interfaces
    • MUST NOT invent APIs, types, or paths that don't exist in the codebase
  3. Gate verification — run this command and STOP if it fails:
    test -f docs/proposals/proposal-<slug>.md || { echo "GATE FAILED: proposal missing"; exit 1; }
    

Gate: docs/proposals/proposal-<slug>.md MUST exist on disk before Phase 4 begins.


Phase 4+5: Proposal Review Loop

Prerequisite: Run gate verification:

test -f docs/proposals/proposal-<slug>.md || { echo "STOP: proposal missing, return to Phase 3"; exit 1; }

Minimum rounds: 2 (even if Round 1 finds no issues, Round 2 must still verify).

Round tracking: Before starting each round N, create a round marker:

mkdir -p .claude/review && touch .claude/review/proposal-round-N.pending

After the Task agent completes and findings are applied, rename to .done:

mv .claude/review/proposal-round-N.pending .claude/review/proposal-round-N.done

Exit condition check (run before exiting the loop):

ls .claude/review/proposal-round-1.done .claude/review/proposal-round-2.done 2>/dev/null | wc -l
# Must output 2 before proceeding to Phase 6

Each round:

  1. Spawn a Task agent (subagent_type: general-purpose) for review with this purpose:

    • Read the proposal file
    • Read every source file, interface, and type referenced in the proposal
    • For each claim in the proposal, verify it against actual code
    • Check: API surface correctness, interface contracts, dependency accuracy, implementation feasibility
    • Check: naming consistency with existing codebase conventions
    • Check: no phantom types, methods, or paths that don't exist
    • Check: edge cases, error handling, missing constraints
    • Return a prioritized issue list: critical / warning / suggestion
  2. Evaluate the Task agent's findings:

    • If critical or warning issues exist: spawn another Task agent to apply confirmed fixes to the proposal (confirmed issues only — do NOT rewrite correct sections), then mark round done and start next round
    • If only suggestions remain: mark round done, note them, then proceed

Exit condition: .claude/review/proposal-round-1.done AND .claude/review/proposal-round-2.done both exist AND no critical or warning issues remain.


Phase 6: Generate Plan

Prerequisite: Run gate verification:

test -f docs/proposals/proposal-<slug>.md || { echo "STOP: proposal missing, return to Phase 3"; exit 1; }

If plan already exists: skip to Phase 7.

Steps:

  1. Check existing plan files to determine the next plan number NN:
    ls docs/plans/plan-*.md 2>/dev/null | sed 's/.*plan-//' | sed 's/-.*//' | sort -n | tail -1
    
  2. Spawn a Task agent (subagent_type: general-purpose) to read the proposal and write docs/plans/plan-NN-<slug>.md:
    • Structure: Overview → Phases → per Phase: objectives, stages, acceptance criteria, dependencies
    • Each stage must be independently testable (TDD-first)
    • Immediate phase: full detail. Future phases: objectives only.
    • File paths, class names, and interface names must match the actual codebase.
  3. Gate verification — run this command and STOP if it fails:
    test -f docs/plans/plan-NN-<slug>.md || { echo "GATE FAILED: plan missing"; exit 1; }
    

Gate: docs/plans/plan-NN-<slug>.md MUST exist on disk before Phase 7 begins.


Phase 7+8: Plan Review Loop

Prerequisite: Run gate verification:

test -f docs/proposals/proposal-<slug>.md && test -f docs/plans/plan-NN-<slug>.md || { echo "STOP: missing files, return to appropriate phase"; exit 1; }

Minimum rounds: 2.

Round tracking: Before starting each round N, create a round marker:

mkdir -p .claude/review && touch .claude/review/plan-round-N.pending

After findings are applied:

mv .claude/review/plan-round-N.pending .claude/review/plan-round-N.done

Exit condition check:

ls .claude/review/plan-round-1.done .claude/review/plan-round-2.done 2>/dev/null | wc -l
# Must output 2 before proceeding to Phase 9

Each round:

  1. Spawn a Task agent (subagent_type: general-purpose) for review with this purpose:

    • Read both the proposal and plan files
    • Read all source files, interfaces, and types referenced in the plan
    • Check: phases are complete, non-overlapping, and correctly sequenced
    • Check: each stage has clear acceptance criteria and a concrete test approach
    • Check: no implementation detail contradicts the proposal
    • Check: all file paths, class names, and interface names exist in the codebase
    • Return a prioritized issue list: critical / warning / suggestion
  2. Evaluate findings:

    • Fix the plan by spawning a Task agent for confirmed issues. If plan changes affect proposal intent, sync the proposal too.
    • Mark round done and start next round.

Exit condition: .claude/review/plan-round-1.done AND .claude/review/plan-round-2.done both exist AND no critical or warning issues remain.


Phase 9: Implementation

Prerequisite: Run gate verification:

test -f docs/plans/plan-NN-<slug>.md || { echo "STOP: plan missing, return to Phase 6"; exit 1; }

Execution rules:

  • Execute phases sequentially: Phase N+1 starts only after Phase N's tests pass.
  • Within a phase, execute independent stages in parallel: spawn multiple Task agents with isolation: worktree.
  • Each Task agent follows TDD: write failing tests first, then implementation to make them pass.
  • This skill does NOT write code directly — it only spawns Task agents and evaluates their results.

Validation (after all phases complete):

  1. Run npm run build (or project-equivalent) via Bash.
  2. Spawn a Task agent to verify the implementation against the plan and proposal:
    • Check every stage's acceptance criteria is met
    • Check no unintended side effects on existing tests
    • Return a gap list if anything is missing
  3. If gaps exist: fix and re-validate.
  4. Iterate until convergence.

λ(topic) → featureToBacklog(topic)

Spec

BuildConfig :: { testCmd : String, -- per-phase test runner; becomes DoD[0] in generated plans testAll : String, -- full suite; becomes Acceptance Gate[0] docPath : String -- root for proposals/ and plans/ subdirectories }

loadConfig :: () → BuildConfig -- see spec-stdlib § loadConfig loadConfig() = | fromClaudeMd() -- explicit: "## L0 Config" section in CLAUDE.md | autoDetect() -- implicit: probe package.json, go.mod, Cargo.toml, etc.

autoDetect :: () → BuildConfig autoDetect() = -- see spec-stdlib § loadConfig

detectLang :: () → Lang -- see spec-stdlib § detectLang -- see spec-stdlib § detectLang

-- Core document types

Proposal :: { background : String, -- WHY this feature is needed (3-8 lines) goals : [VerifiableGoal], -- each Goal checkable by inspection or shell command approach : String, -- high-level design; no implementation code tradeoffs : String -- what we are NOT doing; known risks }

Phase :: { title : String, tests : [TestSpec], -- written before implementation; must fail first impl : [FileChange], -- code that makes the tests pass dod : [ShellCmd] -- dod[0] MUST be cfg.testCmd (red→green proof) }

Plan :: { phases : [Phase], -- ordered; earlier phases feed later ones constraints : [String], -- non-executable criteria (NOT in dod) acceptance : [ShellCmd] -- acceptance[0] is cfg.testAll }

-- Input: topic is either a task ID (e.g. TASK-12, task-12) or a free-form description. -- Task ID → resolve existing task; resume from its current status using its description as draft. -- Description → create a new task and run the full proposal → plan workflow.

EntryPoint = ProposalLoop | PlanLoop -- ProposalLoop : enter proposal reviewLoop (new task, or Proposal status) -- PlanLoop : skip proposal; enter plan reviewLoop (Plan status)

resolveOrCreate :: Topic → (Task, EntryPoint) resolveOrCreate(T) = | isTaskId(T) → (lookupTask(T), fromStatus(lookupTask(T).status)) | otherwise → (createTask(T), ProposalLoop)

fromStatus :: Status → EntryPoint fromStatus("Basic: Plan") = PlanLoop fromStatus(_) = ProposalLoop -- Basic: Proposal or other

-- Workflow

featureToBacklog :: Topic → BacklogTask featureToBacklog(T) = { cfg: loadConfig(), (task, entry): resolveOrCreate(T), -- ProposalLoop: use existing description as proposal draft (skips fresh draft if task ID given) -- PlanLoop: skip proposal stage entirely proposal: case entry of ProposalLoop → reviewLoop(task, task.description, 8) PlanLoop → task.description -- not used; plan stage reads task.description directly plan: case entry of ProposalLoop → reviewLoop(task, draftPlan(task, proposal, cfg), 8) PlanLoop → reviewLoop(task, task.description, 8) -- description IS the plan draft _: finalise(task, proposal, plan, cfg), return: task -- status: Backlog }

-- see spec-stdlib § reviewLoop (MaxRounds = 8)

-- Plan review invariants (all must hold for APPROVED)

reviewPlan :: (Plan, BuildConfig) → Verdict reviewPlan(P, cfg) = { ∀phase ∈ P.phases: { assert: ¬empty(phase.tests), -- TDD: Tests section must exist assert: phase.dod[0] starts with cfg.testCmd, -- TDD: first DoD proves red→green assert: ∀cmd ∈ phase.dod: isShellCmd(cmd) }, assert: P.acceptance[0] == cfg.testAll, assert: ∀goal ∈ proposal.goals: coveredBy(goal, P.phases ∪ P.acceptance), assert: ∀phase ∈ P.phases: allFilesExist(phase.impl), return: APPROVED | NEEDS_REVISION }

Implementation

loadConfig

REPO_ROOT=$(git rev-parse --show-toplevel)

resolveBaimeScripts() {
  local proj_scripts="${REPO_ROOT}/.claude/plugins/baime/scripts"
  if [ -d "$proj_scripts" ]; then echo "$proj_scripts"; return 0; fi
  for settings_file in "${HOME}/.claude/settings.json" "${HOME}/.claude/settings.local.json"; do
    if [ -f "$settings_file" ]; then
      local baime_path
      baime_path=$(python3 -c "
import json, sys
try:
  d = json.load(open('$settings_file'))
  for mp in d.get('extraKnownMarketplaces', []):
    p = mp.get('path', '')
    if 'baime' in p:
      import os
      scripts = os.path.join(p, 'scripts')
      if os.path.isdir(scripts):
        print(scripts)
        sys.exit(0)
except Exception:
  pass
" 2>/dev/null || true)
      if [ -n "$baime_path" ]; then echo "$baime_path"; return 0; fi
    fi
  done
  local xdg_scripts="${XDG_DATA_HOME:-${HOME}/.local/share}/baime/scripts"
  if [ -d "$xdg_scripts" ]; then echo "$xdg_scripts"; return 0; fi
  echo "resolveBaimeScripts: ERROR — cannot locate BAIME plugin scripts directory." >&2
  return 1
}
BAIME_SCRIPTS=$(resolveBaimeScripts) || exit 1

# --- fromClaudeMd ---
L0_SECTION=$(awk '/^## L0 Config/{found=1; next} found && /^## /{exit} found{print}' \
  "${REPO_ROOT}/CLAUDE.md" 2>/dev/null)

parse_cfg() { echo "$L0_SECTION" | grep -oP "(?<=^$1:\s)\S.*" | head -1 | xargs; }

CFG_TEST_CMD=$(parse_cfg "test-cmd")
CFG_TEST_ALL=$(parse_cfg "test-all")
CFG_DOC_PATH=$(parse_cfg "doc-path")

# --- autoDetect fallback ---
if [ -z "$L0_SECTION" ]; then
  if   [ -f "${REPO_ROOT}/package.json"  ]; then LANG=node
  elif [ -f "${REPO_ROOT}/go.mod"        ]; then LANG=go
  elif [ -f "${REPO_ROOT}/Cargo.toml"    ]; then LANG=rust
  elif [ -f "${REPO_ROOT}/pyproject.toml" ] || [ -f "${REPO_ROOT}/setup.py" ]; then LANG=python
  else LANG=unknown; fi

  case "$LANG" in
    node)   CFG_TEST_CMD="${CFG_TEST_CMD:-npm test -- --run}"; CFG_TEST_ALL="${CFG_TEST_ALL:-npm test}" ;;
    go)     CFG_TEST_CMD="${CFG_TEST_CMD:-go test ./...}";    CFG_TEST_ALL="${CFG_TEST_ALL:-go test ./...}" ;;
    rust)   CFG_TEST_CMD="${CFG_TEST_CMD:-cargo test}";       CFG_TEST_ALL="${CFG_TEST_ALL:-cargo test --workspace}" ;;
    python) CFG_TEST_CMD="${CFG_TEST_CMD:-pytest -k}";        CFG_TEST_ALL="${CFG_TEST_ALL:-pytest}" ;;
    *)      CFG_TEST_CMD="${CFG_TEST_CMD:-make test}";        CFG_TEST_ALL="${CFG_TEST_ALL:-make test}" ;;
  esac
  CFG_DOC_PATH="${CFG_DOC_PATH:-docs}"
  echo "L0 auto-detected config: lang=${LANG} testCmd=${CFG_TEST_CMD} testAll=${CFG_TEST_ALL} docPath=${CFG_DOC_PATH}"
else
  CFG_TEST_CMD="${CFG_TEST_CMD:-make test}"
  CFG_TEST_ALL="${CFG_TEST_ALL:-make test}"
  CFG_DOC_PATH="${CFG_DOC_PATH:-docs}"
  echo "L0 config loaded from CLAUDE.md: testCmd=${CFG_TEST_CMD} testAll=${CFG_TEST_ALL} docPath=${CFG_DOC_PATH}"
fi

Derive slug and title from <topic>:

SLUG=$(echo "<topic>" | tr '[:upper:] ' '[:lower:]-' | tr -cd '[:alnum:]-' | cut -c1-50)
TITLE=$(echo "<topic>" | cut -c1-70)

If <topic> is empty: print usage and stop.


Phase 0: Manifest Generation and Lint

Before executing any phase, generate a manifest JSON that describes the planned execution:

{
  "skill": "feature-to-backlog",
  "task_id": null,
  "entry_point": "createTask",
  "skip_draft": false,
  "field_writes": [
    { "tool": "backlog task edit", "field": "plan", "source": "$TMPDIR/ftb-plan.md" },
    { "tool": "backlog task edit", "field": "status", "value": "Basic: Backlog" }
  ],
  "phases_to_execute": ["createTask", "proposalLoop", "planLoop", "finalise"]
}

Write the manifest to $TMPDIR/feature-to-backlog-manifest.json, then validate it:

bash "$BAIME_SCRIPTS/skill-lint.sh" --manifest "$TMPDIR/feature-to-backlog-manifest.json"

If validation fails, stop and report the error before proceeding.


Phase 1: resolveOrCreate + maybe draftProposal

1a. resolveOrCreate (orchestrator runs directly):

if echo "<topic>" | grep -qiP '^task-\d+$'; then
  # Existing task path — resolve and extract description as initial draft
  TASK_ID=$(echo "<topic>" | tr '[:lower:]' '[:upper:]')
  backlog task view "$TASK_ID" --plain > $TMPDIR/ftb-existing-task.txt
  echo "$TASK_ID" > $TMPDIR/ftb-task-id.txt
  # Extract description block into ftb-proposal.md (reused as proposal or plan draft)
  awk '/^Description:/{found=1;next} found && /^-{10,}/{if(!sep){sep=1;next};exit} found && sep{print}' \
    $TMPDIR/ftb-existing-task.txt > $TMPDIR/ftb-proposal.md
  # Determine entry point from status
  TASK_STATUS=$(grep -oP '(?<=Status:).*' $TMPDIR/ftb-existing-task.txt | head -1 | grep -oP '(Basic|Epic): [A-Za-z ]+' | head -1 | xargs)
  case "$TASK_STATUS" in
    "Basic: Plan") echo "PlanLoop"     > $TMPDIR/ftb-entry-point.txt ;;
    *)                          echo "ProposalLoop" > $TMPDIR/ftb-entry-point.txt ;;
  esac
else
  # New topic path — create task
  backlog task create "$TITLE" \
    --status "Basic: Proposal" \
    --label "kind:basic" \
    --description "<topic>" \
    --plain
  # Extract task ID from output line `Task TASK-N`. Write to $TMPDIR/ftb-task-id.txt.
  echo "ProposalLoop" > $TMPDIR/ftb-entry-point.txt
fi

If $TMPDIR/ftb-entry-point.txt contains PlanLoop: skip phase 1b and phases 2–3; proceed directly to Phase 4 using $TMPDIR/ftb-proposal.md as the plan draft (rename it to $TMPDIR/ftb-plan.md).

1b. draftAndReview — spawn Task agent "Draft proposal with built-in self-review" (only when entry point is ProposalLoop AND topic is a new description; skip if existing task ID was given — its description is already in $TMPDIR/ftb-proposal.md):

Draft a technical proposal and immediately self-review it against all criteria.

Task ID: <TASK_ID>

  1. Search the codebase to understand current architecture relevant to: <topic>

  2. Write $TMPDIR/ftb-proposal.md:

    # Proposal: <title>
    
    ## Background
    (3-8 lines: WHY this feature is needed, what problem it solves)
    
    ## Goals
    1. (concrete, verifiable outcome)
    2. ...
    
    ## Proposed Approach
    (High-level design: what to build, key components — no implementation code)
    
    ## Trade-offs and Risks
    (What we are not doing, known risks, alternatives considered)
    
  3. Self-review: check each criterion against the draft you just wrote:

    • Motivation: Does Background explain WHY (not just WHAT)? Is it 3-8 lines?
    • Goals: All numbered and concretely verifiable? No vague language?
    • Feasibility: Does Approach align with the codebase? Search to verify.
    • Completeness: Are trade-offs and risks identified?
    • Consistency: No contradictions between sections?

    If ANY criterion fails: fix the failing sections inline in $TMPDIR/ftb-proposal.md and repeat self-review. Repeat up to 3 total rounds (initial draft + 2 revision rounds).

  4. After all criteria pass (or after 3 rounds), update the task and stop:

    backlog task edit <TASK_ID> \
      --plan "$(cat $TMPDIR/ftb-proposal.md)" \
      --status "Basic: Proposal"
    echo "APPROVED" > $TMPDIR/ftb-proposal-verdict.txt
    

    在写 APPROVED 时,把 verdict 扩展为结构化前提账本(premise-ledger): 对你检查的每条 criterion,追加一行 [E|C|H] <criterion>: <你判断所凭的前提>, 分类规则:E=该前提可直接从本任务 task 文件读到;C=须跳转外部 task/doc/parent 才能确认; H=任何 artifact 都没有、靠背景知识或记忆推断。 末尾追加一行 GCL-self-report: E=<n> C=<n> H=<n>(各类计数)。 写法示例: backlog task edit <TASK_ID> --append-notes "Proposal self-review: APPROVED premise-ledger: [E] background lines: 背景段行数从 proposal 文件直接数 [C] goal verifiability: 须对照每条 Goal 判断是否可验证 [H] feasibility 基准: 何为'可行'靠背景知识判断 GCL-self-report: E=1 C=1 H=1" Immediately after writing the GCL-self-report note, append one line to docs/research/gcl-events.jsonl (gate_type=proposal, task_kind=basic):

    python3 -c "
    

import json, datetime record = { 'task_id': '<TASK_ID>', 'gate_type': 'proposal', 'task_kind': 'basic', 'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), 'E': , 'C': , 'H': , 'GCL': ++, 'reviewer_model': 'claude-sonnet-4-6', 'sample_run_id': None, 'evidence_independence': 'low', 'gate_actor_type': 'llm', 'premise_lines': } with open('docs/research/gcl-events.jsonl', 'a') as f: f.write(json.dumps(record) + '\n') "

Replace `<TASK_ID>`, `<E>`, `<C>`, `<H>` with the actual values from the self-report.

**Reliability sampling (~10% of gates):** After appending the primary JSONL record above,
check whether this task falls in the ~10% reliability sample:
```python
import hashlib
if int(hashlib.md5('<TASK_ID>'.encode()).hexdigest(), 16) % 10 == 0:

If and only if the condition is true, perform a second independent GCL self-report pass:

  • Re-read the same gate content (proposal) with fresh eyes, as if reviewing it for the first time.
  • Produce a second premise-ledger with its own E/C/H counts (may differ from run 1).
  • Append a second JSONL line to docs/research/gcl-events.jsonl with the same fields but 'sample_run_id': '<TASK_ID>-r2' (instead of None).
  • Log intra-rater-variance: |H_run1 - H_run2| by appending to the task notes:
    backlog task edit <TASK_ID> --append-notes "reliability-sample: intra-rater-variance H=|<H_run1>-<H_run2>|=<diff>"
    

If the condition is false, skip this block entirely (no second pass, no extra JSONL line).

Print: "Proposal APPROVED. Proceeding to plan draft."

Rules: Background must state WHY, not just WHAT. Each Goal must be verifiable. No implementation phases or DoD commands in this document.


Phase 2: self-review (integrated into Phase 1b)

For new-description topics (ProposalLoop entry), proposal self-review is handled inside the draftAndReview agent in Phase 1b — no separate review agent is spawned.

For existing task ID topics (PlanLoop entry), no proposal review is needed; proceed directly to Phase 3 (draftPlan) or Phase 4 (planLoop).


Phase 3: draftPlan

If $TMPDIR/ftb-entry-point.txt contains PlanLoop: $TMPDIR/ftb-plan.md already holds the task's existing description as the plan draft — skip this phase and proceed directly to Phase 4.

backlog task edit $TASK_ID \
  --status "Basic: Plan" \
  --append-notes "Proposal approved. Starting plan draft."

Spawn Task agent (pass CFG_TEST_CMD, CFG_TEST_ALL, CFG_DOC_PATH as literal values):

Draft a TDD implementation plan and update the backlog task.

Task ID: <TASK_ID> Test command (per phase): <CFG_TEST_CMD> Full suite command: <CFG_TEST_ALL> Doc root: <CFG_DOC_PATH>

  1. Read the approved proposal from $TMPDIR/ftb-proposal.md

  2. Search the codebase to identify exact file paths to create or modify.

  3. Write $TMPDIR/ftb-plan.md:

    # Plan: <title>
    
    Proposal: <CFG_DOC_PATH>/proposals/proposal-<slug>.md
    
    ## Phase A: <title>
    ### Tests (write first)
    (Test file paths and test case names to add; these must fail before implementation)
    ### Implementation
    (Files to create or modify; code that makes the tests pass)
    ### DoD
    - [ ] `<CFG_TEST_CMD> <test-file-or-pattern>`   ← first item MUST use testCmd
    - [ ] `<other verification command>`
    
    ## Phase B: <title>
    ### Tests (write first)
    ...
    ### Implementation
    ...
    ### DoD
    - [ ] `<CFG_TEST_CMD> <test-file-or-pattern>`
    - [ ] `<other verification command>`
    
    ## Constraints
    (Non-executable criteria — goes here, NOT in DoD)
    
    ## Acceptance Gate
    - [ ] `<CFG_TEST_ALL>`                           ← first item MUST be full suite
    - [ ] `<final verification command>`
    

    DoD rules (STRICT):

    • Every ### DoD and ## Acceptance Gate item MUST be an executable shell command (exit 0 = pass)
    • ### Tests section MUST exist in every Phase — this is the TDD specification
    • First ### DoD item MUST use <CFG_TEST_CMD> — proves red→green
    • First ## Acceptance Gate item MUST be <CFG_TEST_ALL>
    • Each Phase ≤ 200 lines of code change
    • Absence check: ! grep -q <pattern> <file> (NOT grep -qv)
    • Natural-language criteria → ## Constraints only, never in DoD
    • Phases ordered so earlier phases produce what later phases need
  4. Update task:

    backlog task edit <TASK_ID> \
      --plan "$(cat $TMPDIR/ftb-plan.md)" \
      --status "Basic: Plan"
    

Phase 4: reviewLoop(plan)

Soft limit: 8 iterations. On exhaustion: move to Needs Human, print plan, stop.

Each iteration — spawn Task agent with run_in_background=true (self-chaining background agent; pass CFG_TEST_CMD, CFG_TEST_ALL as literal values):

You are a strict software architect reviewing a TDD implementation plan.

Task ID: <TASK_ID> — Iteration: <N> — Max iterations: 8 Expected test command: <CFG_TEST_CMD> Expected full suite: <CFG_TEST_ALL>

  1. Read $TMPDIR/ftb-proposal.md and $TMPDIR/ftb-plan.md

  2. Check each item:

    • Goal coverage: Every proposal Goal addressed by at least one Phase or Acceptance Gate item
    • TDD structure: Every Phase has a ### Tests section AND ### Implementation section (in that order)
    • TDD order: First ### DoD item uses <CFG_TEST_CMD> (proves red→green)
    • Acceptance gate: First ## Acceptance Gate item is <CFG_TEST_ALL>
    • DoD executability: All ### DoD and ## Acceptance Gate items are shell commands. Flag natural-language items and move to ## Constraints
    • Absence checks: ! grep -q pattern used, not grep -qv
    • Phase ordering: Earlier phases produce what later phases need; no circular deps
    • Scope discipline: No Phase implements something not backed by a Goal
    • File paths: Referenced files exist in the codebase (search to verify)

3a. ALL pass:

backlog task edit <TASK_ID> \
  --append-notes "Plan review iteration <N>: APPROVED"
echo "APPROVED" > $TMPDIR/ftb-plan-verdict.txt

在写 APPROVED 时,把 verdict 扩展为结构化前提账本(premise-ledger): 对你检查的每条 criterion,追加一行 [E|C|H] <criterion>: <你判断所凭的前提>, 分类规则:E=该前提可直接从本任务 task 文件读到;C=须跳转外部 task/doc/parent 才能确认; H=任何 artifact 都没有、靠背景知识或记忆推断。 末尾追加一行 GCL-self-report: E=<n> C=<n> H=<n>(各类计数)。 写法示例: backlog task edit <TASK_ID> --append-notes "Plan review iteration : APPROVED premise-ledger: [E] goal coverage: 3 goals 映射到 Phase A/B/C [C] file paths exist: 引用的外部文件经 search 确认 [H] DoD 充分性基准: 何为'足够'靠背景知识判断 GCL-self-report: E=2 C=1 H=1" Immediately after writing the GCL-self-report note, append one line to docs/research/gcl-events.jsonl:

python3 -c "
import json, datetime
record = {
'task_id': '<TASK_ID>',
'gate_type': 'plan',
'task_kind': 'basic',
'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
'E': <E>, 'C': <C>, 'H': <H>, 'GCL': <E>+<C>+<H>,
'reviewer_model': 'claude-sonnet-4-6',
'sample_run_id': None,
'evidence_independence': 'low',
'gate_actor_type': 'llm',
'premise_lines': <count of premise-ledger lines>
}
with open('docs/research/gcl-events.jsonl', 'a') as f:
 f.write(json.dumps(record) + '\n')
"

Replace <TASK_ID>, <E>, <C>, <H> with the actual values from the self-report.

Reliability sampling (~10% of gates): After appending the primary JSONL record above, check whether this task falls in the ~10% reliability sample:

import hashlib
if int(hashlib.md5('<TASK_ID>'.encode()).hexdigest(), 16) % 10 == 0:

If and only if the condition is true, perform a second independent GCL self-report pass:

  • Re-read the same gate content (proposal + plan) with fresh eyes, as if reviewing it for the first time.
  • Produce a second premise-ledger with its own E/C/H counts (may differ from run 1).
  • Append a second JSONL line to docs/research/gcl-events.jsonl with the same fields but 'sample_run_id': '<TASK_ID>-r2' (instead of None).
  • Log intra-rater-variance: |H_run1 - H_run2| by appending to the task notes:
    backlog task edit <TASK_ID> --append-notes "reliability-sample: intra-rater-variance H=|<H_run1>-<H_run2>|=<diff>"
    

If the condition is false, skip this block entirely (no second pass, no extra JSONL line).

Print: "Plan APPROVED. Proceeding to finalise."

3b. ANY fail: fix $TMPDIR/ftb-plan.md (and $TMPDIR/ftb-proposal.md if needed), update task plan:

backlog task edit <TASK_ID> --plan "$(cat $TMPDIR/ftb-plan.md)"
echo "NEEDS_REVISION" > $TMPDIR/ftb-plan-verdict.txt

If <N> < 8: spawn next iteration as background agent (run_in_background=true) with N+1 and STOP. If <N> == 8: move to Basic: Needs Human, print plan, STOP.

After the first iteration is spawned (run_in_background=true), the orchestrator exits. The background agent self-chains by spawning the next iteration on NEEDS_REVISION. On APPROVED, the background agent proceeds directly to Phase 5 (finalise).


Phase 5: finalise

Run the following bash commands directly (no agent spawn needed — all steps are mechanical):

Step B — Write combined proposal+plan into task and add DoD:

grep -oP '(?<=- \[ \] `)[^`]+(?=`)' $TMPDIR/ftb-plan.md \
  > $TMPDIR/ftb-dod-cmds.txt

DOD_ARGS=()
while IFS= read -r cmd; do
  DOD_ARGS+=("--dod" "$cmd")
done < $TMPDIR/ftb-dod-cmds.txt

{
  cat $TMPDIR/ftb-proposal.md
  printf '\n\n---\n\n'
  cat $TMPDIR/ftb-plan.md
} > $TMPDIR/ftb-combined.md

backlog task edit <TASK_ID> \
  --plan "$(cat $TMPDIR/ftb-combined.md)" \
  --status "Basic: Backlog" \
  "${DOD_ARGS[@]}"

Step D — Run Layer 0-2 validation gate:

bash "$BAIME_SCRIPTS/validate-plugin.sh"

If validation fails, fix the SKILL.md contracts or internals before proceeding.

Add the following DoD items to the task:

backlog task edit <TASK_ID> \
  --dod "bash "$BAIME_SCRIPTS/validate-plugin.sh"" \
  --dod "grep -q 'contracts:' plugin/skills/<skill-slug>/SKILL.md"

Step E — Print completion:

✅ Task <TASK_ID> is now in Backlog.

两轮起草 + 两轮迭代审查已完成。

请在 web UI 审阅 Definition of Done 中的命令:
  backlog browser --no-open --port 6421

确认无误后,将任务移入执行队列:
  backlog task edit <TASK_ID> --status "Basic: Ready"

启动 L0 执行:
  /loop-backlog

(print the standard completion message as text output)


Constraints

  • Scope gate (epic vs basic): If the feature naturally decomposes into ≥2 independent deliverables with ordering/dependencies and a combined acceptance, stop and use /epic-to-backlog instead. A Basic Task is NOT small — its plan may have Phase + Stage two levels and span thousands of LOC. Only reach for an epic when one worker in one worktree genuinely cannot finish the whole goal. See docs/proposals/proposal-epic-split-board.md § 颗粒度.
  • This skill outputs docs and a backlog task only — it does not implement code
  • No branch creation, no worktree operations, no git push, no PR creation
  • One task per feature throughout; the same TASK_ID moves through all columns
  • Phase count in generated plans: minimum 1, maximum 8
  • Must run from the project root of a git repository
  • Proposal and plan text live in the task's Implementation Plan field; no docs/ files are written

Spec

λ(project: ProjectContext) → OnboardingDocs

Knowledge Transfer

Reduce onboarding time by 3-8x with structured learning paths.

Progressive disclosure, scaffolding, and validation checkpoints transform weeks of confusion into days of productive learning.


When to Use This Skill

Use this skill when:

  • 👥 Onboarding contributors: New developers joining project
  • ⏰ Slow ramp-up: Weeks to first meaningful contribution
  • 📚 Ad-hoc knowledge sharing: Unstructured, mentor-dependent learning
  • 📈 Scaling teams: Can't rely on 1-on-1 mentoring
  • 🔄 Knowledge preservation: Institutional knowledge at risk
  • 🎯 Clear learning paths: Need structured Day-1, Week-1, Month-1 plans

Don't use when:

  • ❌ Single contributor projects (no onboarding needed)
  • ❌ Onboarding already optimal (<1 week to productivity)
  • ❌ Non-software projects without adaptation
  • ❌ No time to create learning paths (requires 4-8h investment)

Quick Start (30 minutes)

Step 1: Assess Current Onboarding (10 min)

Questions to answer:

  • How long does it take for new contributors to make their first meaningful contribution?
  • What documentation exists? (README, architecture docs, development guides)
  • What do contributors struggle with most? (setup, architecture, workflows)

Baseline: Unstructured onboarding typically takes 4-12 weeks to productivity.

Step 2: Create Day-1 Learning Path (15 min)

Structure:

  1. Environment Setup (1-2h): Installation, build, test
  2. Project Understanding (1-2h): Purpose, structure, core concepts
  3. Code Navigation (1-2h): Find files, search code, read docs
  4. First Contribution (1-2h): Trivial fix (typo, comment)

Validation: PR submitted, tests passing, CI green

Step 3: Plan Week-1 and Month-1 Paths (5 min)

Week-1 Focus: Architecture understanding, module mastery, meaningful contribution (20-40h)

Month-1 Focus: Domain expertise, significant feature, code ownership, mentoring (40-160h)


Three Learning Path Templates

1. Day-1 Learning Path (4-8 hours)

Purpose: Get contributor from zero to first contribution in one day

Four Sections:

Section 1: Environment Setup (1-2h)

  • Prerequisites documented (Go 1.21+, git, make)
  • Step-by-step installation instructions
  • Build verification (make all)
  • Test suite execution (make test)
  • Validation: Can build and test successfully

Section 2: Project Understanding (1-2h)

  • Project purpose and value proposition
  • Repository structure overview (cmd/, internal/, docs/)
  • Core concepts (3-5 key ideas)
  • User personas and use cases
  • Validation: Can explain project purpose in 2-3 sentences

Section 3: Code Navigation (1-2h)

  • File finding strategies (grep, find, IDE navigation)
  • Code search techniques (function definitions, usage sites)
  • Documentation navigation (README, docs/, code comments)
  • Development workflows (TDD, git flow)
  • Validation: Can find specific function in codebase within 2 minutes

Section 4: First Contribution (1-2h)

  • Good first issues identified (typo fixes, comment improvements)
  • Contribution process (fork, branch, PR)
  • Code review expectations
  • CI/CD validation
  • Validation: PR submitted with tests passing

Success Criteria:

  • ✅ Environment working (built, tested)
  • ✅ Basic understanding (can explain purpose)
  • ✅ Code navigation skills (can find files/functions)
  • ✅ First PR submitted (trivial contribution)

Transferability: 80% (environment setup is project-specific)


2. Week-1 Learning Path (20-40 hours)

Purpose: Deep architecture understanding and first meaningful contribution

Four Sections:

Section 1: Architecture Deep Dive (5-10h)

  • System design overview (components, data flow)
  • Integration points (APIs, databases, external services)
  • Design patterns used (MVC, dependency injection)
  • Architectural decisions (ADRs)
  • Validation: Can draw architecture diagram, explain data flow

Section 2: Module Mastery (8-15h)

  • Core modules identified (3-5 critical modules)
  • Dependency-ordered learning (foundational → higher-level)
  • Module APIs and interfaces
  • Integration between modules
  • Best Practice: Study modules in dependency order
  • Validation: Can explain each module's purpose and key functions

Section 3: Development Workflows (3-5h)

  • TDD workflow (write tests first)
  • Debugging techniques (debugger, logging)
  • Git workflows (feature branches, rebasing)
  • Code review process (standards, checklist)
  • Validation: Can follow TDD cycle, submit quality PR

Section 4: Meaningful Contribution (4-10h)

  • "Good first issue" selection (small feature, bug fix)
  • Feature implementation (with tests)
  • Code review iteration
  • Feature merged
  • Validation: Feature merged, code review feedback incorporated

Success Criteria:

  • ✅ Architecture understanding (can explain design)
  • ✅ Module mastery (know 3-5 core modules)
  • ✅ Development workflows (TDD, git, code review)
  • ✅ Meaningful contribution (feature merged)

Transferability: 75% (module names and architecture are project-specific)


3. Month-1 Learning Path (40-160 hours)

Purpose: Build deep expertise, deliver significant feature, enable mentoring

Four Sections:

Section 1: Domain Selection & Deep Dive (10-40h)

  • Domain areas identified (e.g., Parser, Analyzer, Query, MCP, CLI)
  • Domain selection (choose based on interest and project need)
  • Deep dive resources (docs, code, architecture)
  • Domain patterns and anti-patterns
  • Validation: Deep dive deliverable (design doc, refactoring proposal)

Section 2: Significant Feature Development (15-60h)

  • Feature definition (200+ lines, multi-module, complex logic)
  • Design document creation
  • Implementation with comprehensive tests
  • Performance considerations
  • Validation: Significant feature merged (200+ lines)

Section 3: Code Ownership & Expertise (10-40h)

  • Reviewer role for domain
  • Issue triaging and assignment
  • Architecture improvement proposals
  • Performance optimization
  • Validation: Reviewed 3+ PRs, triaged 5+ issues

Section 4: Community & Mentoring (5-20h)

  • Mentoring new contributors (guide through first PR)
  • Documentation improvements (based on learning experience)
  • Knowledge sharing (internal presentations, blog posts)
  • Community engagement (discussions, issue responses)
  • Validation: Mentored 1+ contributor, improved documentation

Success Criteria:

  • ✅ Deep domain expertise (go-to expert in one area)
  • ✅ Significant feature delivered (200+ lines, merged)
  • ✅ Code ownership (reviewer, triager)
  • ✅ Mentoring capability (guided new contributor)

Transferability: 85% (domain specialization framework is universal)


Learning Theory Principles

1. Progressive Disclosure ✅

Definition: Reveal complexity gradually to avoid overwhelming learners

Application:

  • Day-1: Basic setup and understanding (minimal complexity)
  • Week-1: Architecture and module mastery (medium complexity)
  • Month-1: Expertise and mentoring (high complexity)

Evidence: Each path builds on previous, complexity increases systematically


2. Scaffolding ✅

Definition: Provide support that reduces over time as learner gains independence

Application:

  • Day-1: Highly guided (step-by-step instructions, explicit prerequisites)
  • Week-1: Semi-guided (structured sections, some autonomy)
  • Month-1: Mostly independent (domain selection choice, self-directed deep dives)

Evidence: Support level decreases across paths (guided → semi-independent → independent)


3. Validation Checkpoints ✅

Principle: "Every learning stage needs clear, actionable validation criteria that enable self-assessment without external dependency"

Rationale:

  • Self-directed learning requires confidence in progress
  • External validation doesn't scale (maintainer bottleneck)
  • Clear checkpoints prevent confusion and false confidence

Implementation:

  • Checklists with specific items (not vague "understand X")
  • Success criteria with measurable outcomes (PR merged, tests passing)
  • Self-assessment questions (can you explain Y? can you implement Z?)

Universality: 95%+ (applies to any learning context)


4. Time-Boxing ✅

Definition: Realistic time estimates help learners plan and avoid frustration

Application:

  • Day-1: 4-8 hours (clear boundary)
  • Week-1: 20-40 hours (flexible but bounded)
  • Month-1: 40-160 hours (wide range for depth variation)

Evidence: All paths have explicit time estimates with min-max ranges


Module Mastery Best Practice

Context: Week-1 contributor learning complex codebase with multiple interconnected modules

Problem: Without structure, contributors randomly jump between modules, missing critical dependencies

Solution: Architecture-first, sequential module deep dives

Approach:

  1. Architecture Overview First: Understand system design before diving into modules
  2. Dependency-Ordered Sequence: Study modules in dependency order (foundational → higher-level)
  3. Deliberate Practice: Build small examples after each module to validate understanding
  4. Integration Understanding: After individual modules, understand how they interact

Example (meta-cc):

  • Architecture: Two-layer (CLI + MCP), 3 core packages (parser, analyzer, query)
  • Sequence: Parser (foundation) → Analyzer (uses parser) → Query (uses both)
  • Practice: Write small programs using each module's API
  • Integration: Understand MCP server coordination of all 3 modules

Transferability: 80% (applies to modular architectures)


Proven Results

Validated in bootstrap-011 (meta-cc project):

  • ✅ Meta layer: V_meta = 0.877 (CONVERGED)
  • ✅ 3 learning path templates complete (Day-1, Week-1, Month-1)
  • ✅ 6 knowledge artifacts created (3 templates, 1 pattern, 1 principle, 1 best practice)
  • ✅ Duration: 4 iterations, ~8 hours
  • ✅ 3-8x onboarding speedup demonstrated (structured vs. unstructured)

Onboarding Time Comparison:

  • Traditional unstructured: 4-12 weeks to productivity
  • Structured methodology: 1.5-5 weeks to same outcome
  • Speedup: 3-8x faster ✅

Transferability Validation:

  • Go projects: 95-97% transferable
  • Rust projects: 90-95% transferable (6-8h adaptation)
  • Python projects: 85-90% transferable (8-10h adaptation)
  • TypeScript projects: 80-85% transferable (10-12h adaptation)
  • Overall: 95%+ transferable ✅

Complete Onboarding Lifecycle

Total Time: 64-208 hours (1.5-5 weeks @ 40h/week)

Day-1 (4-8 hours):

  • Environment setup → Project understanding → Code navigation → First contribution
  • Outcome: PR submitted, tests passing

Week-1 (20-40 hours) (requires Day-1 completion):

  • Architecture deep dive → Module mastery → Development workflows → Meaningful contribution
  • Outcome: Feature merged, architecture understanding validated

Month-1 (40-160 hours) (requires Week-1 completion):

  • Domain deep dive → Significant feature → Code ownership → Mentoring
  • Outcome: Domain expert status, significant feature merged, mentored contributor

Progressive Complexity: Simple → Medium → Complex Progressive Independence: Guided → Semi-independent → Independent Progressive Impact: Trivial fix → Small feature → Significant feature


Common Anti-Patterns

❌ Information overload: Dumping all knowledge on Day-1 (overwhelms learner) ❌ No validation: Missing self-assessment checkpoints (learner uncertain of progress) ❌ Vague success criteria: "Understand architecture" (not measurable) ❌ No time estimates: Undefined time commitment (causes frustration) ❌ Dependency violations: Teaching advanced concepts before fundamentals ❌ External validation dependency: Requiring mentor approval for every step (doesn't scale)


Templates and Examples

Templates

Examples


Related Skills

Parent framework:

Complementary domains:


References

Core methodology:

Quick guides:


Status: ✅ Production-ready | Validated in meta-cc | 3-8x speedup | 95%+ transferable

λ() → workerLoop()

Spec

-- External primitives (provided by the Claude Code harness / shell environment; -- not implemented in this skill) Monitor :: { persistent : Bool, command : String, description : String } → Event exists :: Path → Bool fromClaudeMd :: () → RawText

-- Business logic signatures ensureDaemonScript :: () → () -- intentional primitive: implemented in Implementation section daemonBootstrap :: () → () -- intentional primitive: implemented in Implementation section inProgressTasks :: () → [Task] -- spec gap: no implementation body defined stopSentinel :: () → Bool -- spec gap: no implementation body defined stopStaleMon :: () → () -- stop any orphaned Monitor tail processes (safe because acquireLoopLock guarantees single-instance) acquireLoopLock :: () → () -- flock-based single-instance guard; exits 1 if another loop is already running createWorktree :: Task → Path -- spec gap: no implementation body defined readyTasks :: () → [Task] -- spec gap: no implementation body defined followDescription :: (Description, Context) → () -- spec gap: no implementation body defined appendNote :: (Task, String) → () -- spec gap: no implementation body defined reset :: (Task, Status) → () -- spec gap: no implementation body defined removeWorktree :: Task → () -- spec gap: no implementation body defined checkDod :: (Task, Int) → () -- spec gap: no implementation body defined

WorktreeConfig :: { symlinks : [Path] -- dirs to symlink into worktree ([] = none) maxParallel : Int -- max concurrent background agents (default 2) }

loadConfig :: () → WorktreeConfig -- see spec-stdlib § loadConfig loadConfig() = | fromClaudeMd() -- explicit: "## L0 Config" section in CLAUDE.md -- reads: worktree-symlinks, max-parallel (default 2) | autoDetect() -- implicit: probe package.json, go.mod, Cargo.toml, etc.

autoDetect :: () → WorktreeConfig autoDetect() = -- see spec-stdlib § loadConfig

detectLang :: () → Lang -- see spec-stdlib § detectLang -- see spec-stdlib § detectLang

data Outcome = Done CommitHash | NeedsHuman Reason | Idle | Stopped

workerLoop :: () → Outcome workerLoop() = { _: acquireLoopLock(), cfg: loadConfig(), _: ensureDaemonScript(), _: daemonBootstrap(), _: reap(inProgressTasks()), tasks: claimBatch(cfg.maxParallel),

if (stopSentinel()): return: Stopped,

if (empty(tasks)): -- No basic task to claim; block persistently and dispatch the next daemon event. -- The unified daemon (basic-daemon.js v9) emits FIVE channels; this one worker -- session handles all of them (no separate loop-meta session needed). _: stopStaleMon(), event: Monitor(persistent=true, command="tail -c +${OFFSET} -f "$DAEMON_LOG" | grep --line-buffered -E "^(basic-ready|epic-ready|child-done|proposal-approved|plan-approved):"", description="loop-backlog daemon notification. An event line (basic-ready:TASK-N, epic-ready:TASK-N, child-done:TASK-N, proposal-approved:TASK-N, or plan-approved:TASK-N) has arrived from the backlog task board. Event lines may re-emit roughly every 60s while a task stays actionable — this re-emit is the normal re-attach signal for an idle session (e.g. after /clear). Non-event lines are filtered out. If this is a new Claude session, invoke /loop-backlog in the project root to resume the worker loop — it will re-claim and dispatch this event automatically." ), | stopSentinel() → return Stopped | event matches "basic-ready:TASK-" → workerLoop() -- re-claim & execute | event matches "epic-ready:TASK-" → epicDecompose(extractId(event)); workerLoop() | event matches "child-done:TASK-" → onChildDone(extractId(event)); workerLoop() | event matches "proposal-approved:TASK-" → startPlanDraft(extractId(event)); workerLoop() | event matches "plan-approved:TASK-*" → startFinalise(extractId(event)); workerLoop() | otherwise → workerLoop(), -- noise: loop back

-- Parallel: create worktrees and spawn one background agent per task worktrees: ∀t ∈ tasks: withWorktree(t, cfg), _: ∀(t, wt) ∈ zip(tasks, worktrees): spawnAgent(t, wt),

-- Wait for all agents to signal completion results: waitForAgents(tasks),

-- Serial: merge each branch in order; read signal file to decide merge vs. escalate ∀t ∈ tasks: { sig: results[t], _: deleteSignalFile("backlog/.agent-done-" + t.id), if (sig == "done"): verifyDod(t), merge(t, t.branch) else: escalate(t, stripPrefix("needs-human: ", sig)) },

return: Done }

-- ───────────────────────────────────────────────────────────────────────────── -- Epic lane dispatch (B″). The unified daemon delivers epic-ready / child-done to -- this same worker. epic-ready means the human promoted Epic: Backlog → Epic: Ready -- (authorizing autonomous decomposition). child-done means a kind:basic child reached -- Basic: Done; we re-check its parent epic. All transitions write cap:* idempotency -- markers, mirroring the basic lane. See spec-stdlib § reviewLoop is NOT used here — -- proposal/plan review happens interactively in epic-to-backlog, not in this worker. -- ─────────────────────────────────────────────────────────────────────────────

-- epicDecompose: triggered by epic-ready (status Epic: Ready). Checks preconditions then -- spawns a single background agent that handles ALL decomposition work autonomously. -- Orchestrator returns immediately after spawning (spawn-and-forget pattern). -- The background agent: sets Decomposing, creates children via task-to-backlog, runs R1 -- guard, advances to Awaiting Children or escalates to Needs Human on failure. epicDecompose :: TaskId → Outcome epicDecompose(id) = { if (¬isEpicReady(id)): return Idle, -- status changed out from under us if (hasCap(id, "decompose")): return Idle, -- already decomposed (idempotent) _: Agent(run_in_background=true, prompt=decomposeAgentPrompt(id)), return: Reconciled -- orchestrator returns immediately; agent is autonomous }

-- decomposeAgentPrompt: the background agent performs ALL decomposition steps: -- 1. Idempotency check: if cap:decompose=done already set, exit immediately. -- 2. Write cap:decompose=started. -- 3. setStatus(id, "Epic: Decomposing"). -- 4. Read Sub-Task Decomposition from epic plan. -- 5. ∀t ∈ subs: createSubTask(id, t) via feature-to-backlog (code-change tasks) or -- task-to-backlog (doc/config/research-only tasks) — never raw backlog task create. -- (kind:basic, parent_task_id:id, shell-gate DoD). -- 6. R1 guard: verifySubTaskDod(id). -- 7. On R1 pass: appendNote(id, "cap:decompose=done") + setStatus(id, "Epic: Awaiting Children"). -- 8. On R1 fail or any error: escalateEpic(id, reason, "cap:decompose=failed|") -- → setStatus(id, "Epic: Needs Human"). decomposeAgentPrompt :: TaskId → Prompt

-- onChildDone: triggered by child-done (a kind:basic child hit Basic: Done). Find the -- parent epic; if it is a kind:epic at Epic: Awaiting Children and ALL its created -- children are Basic: Done, advance to Epic: Evaluating and evaluate. "All created" = -- every task with parent_task_id == epicId (archived children are excluded by archival). onChildDone :: TaskId → Outcome onChildDone(childId) = { epicId: parentTaskId(childId), if (epicId == ∅ ∨ ¬isKindEpic(epicId)): return Idle, if (status(epicId) ≠ "Epic: Awaiting Children"): return Idle, children: childrenOf(epicId), -- tasks with parent_task_id == epicId done: filter(c → status(c) == "Basic: Done", children), needsHuman: filter(c → status(c) == "Basic: Needs Human", children), if (length(done) < length(children)): appendNote(epicId, "onChildDone: " + length(done) + "/" + length(children) + " children done"), return Idle, -- wait for the rest _: setStatus(epicId, "Epic: Evaluating"), -- auto-processing return: epicEvaluate(epicId, done, needsHuman) }

-- epicEvaluate: aggregate child outcomes (measured: DoD pass + no Needs Human), write a -- FINISH/ITERATE recommendation, then SOFT-HALT. Does NOT auto-advance to Epic: Done — -- the human reads the recommendation and confirms (Epic: Evaluating → Epic: Done) or -- iterates (Epic: Evaluating → Epic: Proposal | Epic: Plan, re-run epic-to-backlog). epicEvaluate :: (TaskId, [Task], [Task]) → Outcome epicEvaluate(id, done, needsHuman) = { if (hasCap(id, "evaluate")): return Idle, verdict: if (empty(needsHuman) ∧ allDodPass(done)): "FINISH" else: "ITERATE", reason: if (verdict == "FINISH"): "all children Basic: Done with DoD pass" else: "blockers: " + summarise(needsHuman) + " / DoD failures", _: appendNote(id, "cap:evaluate=recommendation:" + verdict + " | done=" + length(done) + " needsHuman=" + length(needsHuman) + " | " + reason + " | data_source: measured"), _: appendNote(id, "RECOMMENDATION: " + verdict + ".\nTo finish: set status → Epic: Done." + "\nTo iterate: set status → Epic: Proposal or Epic: Plan and re-run /epic-to-backlog."), -- soft halt: stay at Epic: Evaluating; cap:evaluate guard makes re-emits no-ops. return: Reconciled }

-- escalateEpic: park the epic at Epic: Needs Human with a cap marker and reason note. escalateEpic :: (TaskId, Reason, CapMarker) → Outcome escalateEpic(id, r, cap) = { appendNote(id, cap), appendNote(id, "Escalated: " + r + "\nTo continue: resolve in notes, set status → Epic: Ready."), setStatus(id, "Epic: Needs Human"), return: NeedsHuman(r) }

-- startPlanDraft: triggered by proposal-approved (human advanced status to Epic: Plan or -- Basic: Plan after proposal was APPROVED). Spawns a background agent to run Phase 3 -- (draftEpicPlan / draftPlan) of the respective skill. The agent updates the task and -- writes a plan draft. The daemon will subsequently detect plan-approved when the human -- advances to Epic: Backlog / Basic: Ready after plan review. startPlanDraft :: TaskId → () startPlanDraft(id) = Agent(run_in_background=true, prompt=planDraftPrompt(id))

-- startFinalise: triggered by plan-approved (human advanced status to Epic: Backlog or -- Basic: Ready after plan was APPROVED). Spawns a background agent to run Phase 5 -- (finalise) of the respective skill. The agent writes combined proposal+plan into the -- task implementation plan and parks the task. startFinalise :: TaskId → () startFinalise(id) = Agent(run_in_background=true, prompt=finalisePrompt(id))

-- decomposer: subagent that reads the epic plan's Sub-Task Decomposition and returns a -- canonical [SubTaskSpec]. Each child is created via feature-to-backlog (code-change tasks) -- or task-to-backlog (doc/config/research-only tasks) — never raw backlog task create. -- Selection rule: isCodeChangeTask ≡ child creates or modifies files under plugin/, scripts/, -- or any non-docs git-tracked path. Children park at Basic: Proposal after creation. decomposer :: (TaskId, PlanText) → [SubTaskSpec] decomposer(id, plan) = Agent(prompt=decomposerPrompt(id, plan), schema=SubTaskListSchema)

-- isCodeChangeTask: true when spec involves creating or modifying files under plugin/, -- scripts/, or other code/config paths (not exclusively docs/ or backlog/ prose). isCodeChangeTask :: SubTaskSpec → Bool isCodeChangeTask(spec) = spec.touchesSourceFiles -- plugin/, scripts/, *.sh, SKILL.md, etc.

-- createSubTask: create one kind:basic child at Basic: Proposal with parent_task_id:parent, -- delegating to feature-to-backlog (code-change) or task-to-backlog (doc/config-only) -- so it carries a multi-phase plan + shell-gate DoD (TASK-93 R1). createSubTask :: (TaskId, SubTaskSpec) → () createSubTask(parent, spec) = { skill: if (isCodeChangeTask(spec)): "feature-to-backlog" else: "task-to-backlog", child: invoke(skill, spec.title), setLabel(child, "kind:basic"), setParentTaskId(child, parent), assert: hasDod(child) }

-- verifySubTaskDod: R1 guard — every child of the epic carries a shell-gate DoD. verifySubTaskDod :: TaskId → Bool verifySubTaskDod(id) = shell("bash "$BAIME_SCRIPTS/verify-subtask-dod.sh" " + id) == 0

-- allDodPass: measured slice — every done child's DoD shell-gates exit 0 (re-run). allDodPass :: [Task] → Bool allDodPass(done) = ∀c ∈ done: shell("bash "$BAIME_SCRIPTS/verify-subtask-dod.sh" " + c.id) == 0

reap :: [Task] → () reap(tasks) = ∀t ∈ tasks where claimAge(t) > 30min ∨ ¬hasClaimed(t): { reset(t, "Basic: Ready"), appendNote(t, "Requeued by reaper: in-progress timeout."), removeWorktree(t) }

claimBatch :: Int → [Task] claimBatch(n) = { tasks: take(n, basicReadyTasks()), if (empty(tasks)): return [], ∀t ∈ tasks: atomically: { setStatus(t, "Basic: In Progress"), appendNote(t, "claimed: " + now()), writeCap(t, "cap:claim=started") }, return: tasks -- actual list; may be fewer than n if fewer Basic: Ready tasks exist }

-- spawnAgent: launch a background agent for a single task in its worktree. -- The agent works only inside wt, commits if changed, then writes a signal file. -- Agent's allowed-tools explicitly excludes Agent to prevent recursive spawn. spawnAgent :: (Task, Worktree) → () spawnAgent(T, wt) = Agent(run_in_background=true, prompt=executePrompt(T, wt))

-- waitForAgents: poll signal files until all agents in the batch have reported. -- Signal file path: backlog/.agent-done-TASK-N -- Content: "done" | "needs-human: " -- Polls every 5 seconds; no external dependencies beyond bash. waitForAgents :: [Task] → Map Task SignalContent waitForAgents(tasks) = { remaining: tasks, results: {}, loop while (nonEmpty(remaining)): { sleep(5), ∀t ∈ remaining: if (exists("backlog/.agent-done-" + t.id)): content: read("backlog/.agent-done-" + t.id), results[t]: content, remaining: remaining \ {t} }, return: results }

withWorktree :: Task → WorktreeConfig → (Task → a) → a withWorktree(T, cfg, f) = { wt: createWorktree(T), _: ∀s ∈ cfg.symlinks: symlink(repoRoot + "/" + s, wt + "/" + s), cd: wt, return: f(T) }

-- execute is task-type-agnostic: T.description is the sole authority on what to do -- If re-claimed after a Needs Human cycle, human reply in Notes takes precedence. execute :: Task → Outcome execute(T) = { ctx: readHumanReply(T), -- extract human's answer if re-claimed after escalation _: followDescription(T.description, ctx), _: ∀(n, cmd) ∈ enumerate(T.dodCommands): verifyDod(T, n, cmd), hash: conditionalCommit(T), _: appendSummary(T, hash), return: merge(T, hash) } | cannotProceed(reason) → escalate(T, reason)

-- appendCheckpoint: record completion of a phase in the task's Implementation Notes. -- Called after each ## Phase section in the task Description completes. appendCheckpoint :: (Task, PhaseIndex, Summary) → () appendCheckpoint(T, x, summary) = appendNote(T, "Phase " + x + " ✓ " + now() + "\n" + summary)

-- appendDodNote: record pass/fail result of a DoD command. -- Called once per DoD item; on failure includes up to 5 lines of error output. appendDodNote :: (Task, Int, ShellCmd, Result) → () appendDodNote(T, n, cmd, Pass) = appendNote(T, "DoD #" + n + ": PASS — " + cmd) appendDodNote(T, n, cmd, Fail(out)) = appendNote(T, "DoD #" + n + ": FAIL — " + cmd + "\n" + take(5, lines(out)))

-- appendSummary: write the final Execution Summary before the signal file is written. -- Must be called after all phases and DoD checks have completed. appendSummary :: (Task, Maybe CommitHash) → () appendSummary(T, hash) = appendNote(T, "## Execution Summary\n" + "Result: " + outcomeLabel(T) + "\n" + "Commit: " + fromMaybe("no changes", hash) + "\n" + executionLog(T))

-- readHumanReply: scan Notes for a human reply written after the last "Escalated:" entry. -- Returns a context map that followDescription uses to resolve open questions. readHumanReply :: Task → Context readHumanReply(T) = | hasEscalatedNote(T) → reply: textAfterLastEscalated(T.notes), if (nonEmpty(reply)): return parseContext(reply) -- treat reply as free-form; extract decisions | otherwise → emptyContext

-- escalate: only exit when the worker cannot continue without human input. -- Never ask the user a question while a task is In Progress; call escalate() instead. -- Write a clear "Human, please answer:" question so the user can reply directly in Notes. escalate :: (Task, Reason) → Outcome escalate(T, r) = { setStatus(T, "Basic: Needs Human"), writeCap(T, "cap:execute=failed"), appendNote(T, "Escalated: " + r + "\nTo continue: answer in Implementation Notes, then set status → Basic: Ready."), return: NeedsHuman(r) }

verifyDod :: (Task, Int, ShellCmd) → () verifyDod(T, n, cmd) = | eval(cmd).exitCode == 0 → checkDod(T, n) | attempts(n) < 3 → fix(); verifyDod(T, n, cmd) | otherwise → raise Stuck(n, cmd)

conditionalCommit :: Task → Maybe CommitHash conditionalCommit(T) = | hasChanges() → git add -A; commit(T); return Just(HEAD) | otherwise → return Nothing

merge :: (Task, Maybe CommitHash) → Outcome merge(T, hash) = | mergeNoFF(T.branch) succeeds → markDone(T, hash); removeWorktree(T); Done(hash) | otherwise → markNeedsHuman(T, "merge conflict"); NeedsHuman("merge conflict")

basicDAG — Basic Worker State Machine

The basic channel uses the following status transitions (basicDAG):

Basic: Ready
  → (claim)          Basic: In Progress    cap:claim=started
  → (execute done)   Basic: Done           cap:execute=done
  → (execute failed) Basic: Needs Human    cap:execute=failed
  → (merge conflict) Basic: Needs Human    cap:merge=failed

Dispatch spec

When a basic-ready:TASK-N event arrives, the worker MUST execute these steps in order:

Step 1 — Claim (set Basic: In Progress BEFORE any other work):

backlog task edit TASK-N --status "Basic: In Progress" \
  --append-notes "claimed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
# Write idempotency marker
echo "cap:claim=started" >> backlog/.caps/TASK-N

Step 2 — Spawn implementation agent (NEVER do implementation inline):

Agent(run_in_background=true, prompt=executePrompt(TASK-N, worktree, branch, signal_file))

The allowed-tools passed to the agent explicitly excludes Agent to prevent recursive spawn.

Step 3 — Wait for signal file:

# Poll until backlog/.agent-done-TASK-N exists

Step 4 — Merge and mark Done (cap:execute=done):

git merge --no-ff <branch>
backlog task edit TASK-N --status "Basic: Done" \
  --append-notes "Completed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
# Write terminal idempotency marker
echo "cap:execute=done" >> backlog/.caps/TASK-N

Step 5 — notifyParentIfAny: After reaching a terminal status (Basic: Done or Basic: Needs Human), check if parent_task_id is set in the task frontmatter. If so, emit a completion note to the parent:

PARENT=$(backlog task view TASK-N --plain | grep -oP '(?<=^Parent: )[A-Za-z][A-Za-z0-9]*-\d+(\.\d+)*')
if [ -n "$PARENT" ]; then
  backlog task edit "$PARENT" --append-notes \
    "Sub-task TASK-N reached terminal status: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi

cap:* idempotency markers

cap:* markers are written to backlog/.caps/TASK-N at each state transition. They prevent double-execution if the worker is restarted mid-task:

markermeaning
cap:claim=startedtask has been claimed
cap:execute=doneagent completed successfully
cap:execute=failedagent escalated (Needs Human)
cap:merge=failedmerge conflict (Needs Human)

Before claiming, the worker checks if a cap:claim=started marker already exists for the task — if so, it skips re-claiming and waits for the existing signal file instead.

Prohibited shortcut: doing implementation directly in the worker agent (without Agent(run_in_background=true, ...)) violates Step 2 and causes Step 1 to be silently skipped in practice. The task will jump from Basic: Ready → Basic: Done without ever entering Basic: In Progress.


Critical Protocol (MUST NOT deviate)

When a basic-ready:TASK-N event arrives, the worker MUST execute these steps in order:

Step 1 — Claim (set Basic: In Progress BEFORE any other work):

backlog task edit TASK-N --status "Basic: In Progress" \
  --append-notes "claimed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"

Step 2 — Spawn implementation agent (NEVER do implementation inline):

Agent(run_in_background=true, prompt=executePrompt(TASK-N, worktree, branch, signal_file))

The allowed-tools passed to the agent explicitly excludes Agent to prevent recursive spawn.

Step 3 — Wait for signal file:

# Poll until backlog/.agent-done-TASK-N exists

Step 4 — Merge and mark Basic: Done:

git merge --no-ff <branch>
backlog task edit TASK-N --status "Basic: Done" \
  --append-notes "Completed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"

Prohibited shortcut: doing implementation directly in the worker agent (without Agent(run_in_background=true, ...)) violates Step 2 and causes Step 1 to be silently skipped in practice. The task will jump from Basic: Ready → Basic: Done without ever entering Basic: In Progress.


Implementation

loadConfig

Read CLAUDE.md for an ## L0 Config section. If not found, auto-detect from project files.

REPO_ROOT=$(git rev-parse --show-toplevel)

# --- fromClaudeMd ---
L0_SECTION=$(awk '/^## L0 Config/{found=1; next} found && /^## /{exit} found{print}' \
  "${REPO_ROOT}/CLAUDE.md" 2>/dev/null)

parse_cfg() { echo "$L0_SECTION" | grep -oP "(?<=^$1:\s)\S.*" | head -1 | xargs; }

CFG_SYMLINKS=$(parse_cfg "worktree-symlinks")
CFG_MAX_PARALLEL=$(parse_cfg "max-parallel")
CFG_MAX_PARALLEL=${CFG_MAX_PARALLEL:-2}

# --- autoDetect fallback ---
if [ -z "$L0_SECTION" ]; then
  if   [ -f "${REPO_ROOT}/package.json" ]; then CFG_SYMLINKS="${CFG_SYMLINKS:-node_modules}"
  else                                          CFG_SYMLINKS="${CFG_SYMLINKS:-}"
  fi
  echo "L0 auto-detected config: symlinks=${CFG_SYMLINKS:-none}"
else
  echo "L0 config loaded from CLAUDE.md: symlinks=${CFG_SYMLINKS:-none}"
fi

# Normalise "none" → empty
[ "$CFG_SYMLINKS" = "none" ] && CFG_SYMLINKS=""

ensureDaemonScript

Resolve the BAIME plugin scripts directory and set DAEMON_SCRIPT to the bundled basic-daemon.js. The daemon script is already present in the BAIME plugin installation; no file is written to the target project.

resolveBaimeScripts() {
  # 1. Project-scope plugin install
  local proj_scripts="${REPO_ROOT}/.claude/plugins/baime/scripts"
  if [ -d "$proj_scripts" ]; then echo "$proj_scripts"; return 0; fi

  # 2. Parse extraKnownMarketplaces from user settings for a baime path
  for settings_file in "${HOME}/.claude/settings.json" "${HOME}/.claude/settings.local.json"; do
    if [ -f "$settings_file" ]; then
      local baime_path
      baime_path=$(python3 -c "
import json, sys
try:
  d = json.load(open('$settings_file'))
  for mp in d.get('extraKnownMarketplaces', []):
    p = mp.get('path', '')
    if 'baime' in p:
      import os
      scripts = os.path.join(p, 'scripts')
      if os.path.isdir(scripts):
        print(scripts)
        sys.exit(0)
except Exception:
  pass
" 2>/dev/null || true)
      if [ -n "$baime_path" ]; then echo "$baime_path"; return 0; fi
    fi
  done

  # 3. XDG data home fallback
  local xdg_scripts="${XDG_DATA_HOME:-${HOME}/.local/share}/baime/scripts"
  if [ -d "$xdg_scripts" ]; then echo "$xdg_scripts"; return 0; fi

  echo "ensureDaemonScript: ERROR — cannot locate BAIME plugin scripts directory." >&2
  echo "  Checked: ${REPO_ROOT}/.claude/plugins/baime/scripts" >&2
  echo "  Checked: extraKnownMarketplaces in ~/.claude/settings.json / settings.local.json" >&2
  echo "  Checked: ${XDG_DATA_HOME:-${HOME}/.local/share}/baime/scripts" >&2
  return 1
}

BAIME_SCRIPTS=$(resolveBaimeScripts) || exit 1
DAEMON_SCRIPT="$BAIME_SCRIPTS/basic-daemon.js"

# DAEMON_SCRIPT is always resolved from the plugin-resident BAIME_SCRIPTS path above.

acquireLoopLock

Single-instance enforcement: only one loop-backlog per repo at a time. Called at the very start of workerLoop(), before any other action. The OS releases the flock automatically on any exit (clean, crash, or SIGKILL).

# Single-instance enforcement: only one loop-backlog per repo at a time.
# The OS releases the flock automatically on any exit (clean, crash, or SIGKILL).
REPO_ROOT=$(git rev-parse --show-toplevel)
BACKLOG_DIR="${REPO_ROOT}/backlog"
exec 9> "${BACKLOG_DIR}/.loop-lock"
flock -n 9 || {
  echo "[loop-backlog] ERROR: Another instance is already running on this repo." >&2
  echo "[loop-backlog] Stop the running loop first: touch backlog/.loop-stop" >&2
  exit 1
}

stopStaleMon

Kill any orphaned Monitor tail processes watching the daemon log before creating a new Monitor. Safe because acquireLoopLock() guarantees at most one loop-backlog instance per repo — there are no "other legitimate instances" to protect.

# Kill any orphaned Monitor tail processes watching this daemon log.
# Safe because acquireLoopLock() guarantees at most one loop-backlog instance
# per repo — there are no "other legitimate instances" to protect.

# Step 1: TaskStop any tracked harness-level Monitor task (survives context compression)
MONITOR_TASK_ID_FILE="${BACKLOG_DIR}/.monitor-task-id"
if [ -f "$MONITOR_TASK_ID_FILE" ]; then
  STALE_MONITOR_ID=$(cat "$MONITOR_TASK_ID_FILE" 2>/dev/null || true)
  if [ -n "$STALE_MONITOR_ID" ]; then
    echo "[loop-backlog] stopStaleMon: TaskStop harness Monitor $STALE_MONITOR_ID"
    TaskStop "$STALE_MONITOR_ID" 2>/dev/null || true
  fi
  rm -f "$MONITOR_TASK_ID_FILE"
fi

# Step 2: Kill OS-level tail processes (belt-and-suspenders for orphans)
pkill -f "tail.*${DAEMON_LOG}" 2>/dev/null || true
sleep 0.5

daemonBootstrap

Start the basic-daemon if not already running. The daemon polls backlog/tasks/ for kind:basic tasks at Basic: Ready status, and writes basic-ready:TASK-N lines to stdout, which Monitor picks up as events.

BACKLOG_DIR="${REPO_ROOT}/backlog"
PID_FILE="${BACKLOG_DIR}/.basic-daemon.pid"
STOP_FILE="${BACKLOG_DIR}/.loop-stop"
TASKS_DIR="${BACKLOG_DIR}/tasks"
DAEMON_LOG="${BACKLOG_DIR}/.basic-daemon.log"

# Remove stale stop sentinel from a previous run
rm -f "$STOP_FILE"

# Start daemon only if not already running
DAEMON_RUNNING=false
if [ -f "$PID_FILE" ]; then
  DPID=$(cat "$PID_FILE" 2>/dev/null || true)
  if [ -n "$DPID" ] && kill -0 "$DPID" 2>/dev/null; then
    DAEMON_RUNNING=true
    echo "daemonBootstrap: basic-daemon already running (pid $DPID)"
  fi
fi

if [ "$DAEMON_RUNNING" = "false" ]; then
  nohup node "$DAEMON_SCRIPT" \
    --tasks-dir "$TASKS_DIR" \
    --pid-file  "$PID_FILE"  \
    --stop-file "$STOP_FILE" \
    --interval  0.5 \
    >> "$DAEMON_LOG" 2>/dev/null & disown
  # Poll for PID file instead of fixed sleep (handles slow Node cold-starts)
  for i in $(seq 1 25); do [ -f "$PID_FILE" ] && break; sleep 0.2; done
  DPID=$(cat "$PID_FILE" 2>/dev/null || true)
  echo "daemonBootstrap: started basic-daemon (pid ${DPID:-unknown})"
fi

CHECKPOINT_FILE="${BACKLOG_DIR}/.loop-checkpoint"
LOG_SIZE=$(wc -c < "$DAEMON_LOG" 2>/dev/null || echo 0)
# Cold-start replay policy: START THE MONITOR AT THE CURRENT LOG EOF — do NOT replay the
# checkpointed history. Only events that ARRIVE AFTER the Monitor is armed get full dispatch.
# Rationale: replaying historical lines forced the worker to investigate already-settled
# events file-by-file (backlog task view + parent lookup per line), costing minutes on cold
# start. This is safe because ALL FIVE daemon channels are level-triggered and self-clearing
# (basic/epic-ready clear on claim/advance; proposal/plan-approved gated on marker files;
# child-done gated on parent epic == "Epic: Awaiting Children" — see ADR-009): the daemon's
# 60s pulse re-surfaces any still-actionable state within one interval, and Basic: Ready is
# claimed synchronously by claimBatch BEFORE the Monitor is even armed. Genuinely-stale
# history (parent terminal, already-reconciled) is simply never replayed.
OFFSET="$LOG_SIZE"
echo "daemonBootstrap: cold-start — Monitor starts at log EOF (offset $OFFSET); historical events skipped, pulse re-surfaces actionable state"

# Clean up stale merge-lock (may be left if /clear killed the worker mid-merge)
MERGE_LOCK="${BACKLOG_DIR}/.merge-lock"
if [ -f "$MERGE_LOCK" ]; then
  LOCK_PID=$(cat "$MERGE_LOCK" 2>/dev/null || echo "")
  if [ -z "$LOCK_PID" ] || ! kill -0 "$LOCK_PID" 2>/dev/null; then
    rm -f "$MERGE_LOCK"
    echo "daemonBootstrap: removed stale merge-lock (pid ${LOCK_PID:-unknown} not alive)"
  fi
fi

ACTIVE_AGENTS_FILE="${BACKLOG_DIR}/.active-agents"
if [ -f "$ACTIVE_AGENTS_FILE" ]; then
  ACTIVE_TMP=$(mktemp)
  while IFS= read -r TID; do
    [ -z "$TID" ] && continue
    SIGNAL="${BACKLOG_DIR}/.agent-done-${TID}"
    STATUS=$(backlog task view "$TID" --plain 2>/dev/null \
      | grep -oP '(?<=Status:)\s*\S[^\n]+' | xargs 2>/dev/null || echo "")
    if [ ! -f "$SIGNAL" ] && echo "$STATUS" | grep -q "In Progress"; then
      echo "$TID" >> "$ACTIVE_TMP"
    fi
  done < "$ACTIVE_AGENTS_FILE"
  mv "$ACTIVE_TMP" "$ACTIVE_AGENTS_FILE"
  echo "daemonBootstrap: active-agents reconciled: $(cat "$ACTIVE_AGENTS_FILE" | xargs)"
fi

# Baseline checkpoint: record current log end-of-file offset for observability/bookkeeping.
# NOTE: cold start no longer READS this to seed OFFSET — the replay policy above always
# starts the Monitor at log EOF — so this write is informational only (kept for the
# post-Monitor checkpoint advance and for operators inspecting .loop-checkpoint).
echo $(wc -c < "$DAEMON_LOG" 2>/dev/null || echo 0) > "$CHECKPOINT_FILE"
echo "daemonBootstrap: baseline checkpoint written (offset=$(cat "$CHECKPOINT_FILE"))"

reap

backlog task list --status "Basic: In Progress" --plain \
  | grep -oP '^\s+(\[[A-Z]+\]\s+)?\K[A-Za-z][A-Za-z0-9]*-\d+(\.\d+)*(?= - )' \
  | while read TASK_ID; do
    VIEW=$(backlog task view "$TASK_ID" --plain)
    CLAIMED=$(echo "$VIEW" | grep -oP '(?<=claimed: )\S+' | tail -1)
    AGE=9999
    if [ -n "$CLAIMED" ]; then
      AGE=$(( $(date -u +%s) - $(date -u -d "$CLAIMED" +%s 2>/dev/null || echo 0) ))
    fi
    if [ $AGE -gt 1800 ]; then
      backlog task edit "$TASK_ID" --status "Basic: Ready" \
        --append-notes "Requeued by reaper: in-progress timeout exceeded 30 minutes."
      PROJECT_NAME=$(basename "$REPO_ROOT")
      WORKTREE="${REPO_ROOT}/../${PROJECT_NAME}-${TASK_ID}"
      [ -d "$WORKTREE" ] && git worktree remove "$WORKTREE" --force 2>/dev/null || true
      git branch -D "task/${TASK_ID}" 2>/dev/null || true
    fi
  done

claimBatch

Claim up to CFG_MAX_PARALLEL Basic: Ready tasks atomically. Returns the list of claimed task IDs in CLAIMED_TASK_IDS (space-separated). Writes cap:claim=started for each claimed task. If fewer Basic: Ready tasks exist, claims only those.

CLAIMED_TASK_IDS=""
CLAIM_COUNT=0
while IFS= read -r CANDIDATE_ID; do
  [ -z "$CANDIDATE_ID" ] && continue
  [ "$CLAIM_COUNT" -ge "$CFG_MAX_PARALLEL" ] && break
  backlog task edit "$CANDIDATE_ID" --status "Basic: In Progress" \
    --append-notes "claimed: $(date -u +%Y-%m-%dT%H:%M:%SZ)" 2>/dev/null || continue
  # Write cap:claim=started idempotency marker
  mkdir -p "${REPO_ROOT}/backlog/.caps"
  echo "cap:claim=started $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    >> "${REPO_ROOT}/backlog/.caps/${CANDIDATE_ID}"
  CLAIMED_TASK_IDS="${CLAIMED_TASK_IDS} ${CANDIDATE_ID}"
  CLAIM_COUNT=$((CLAIM_COUNT + 1))
done < <(backlog task list --status "Basic: Ready" --plain | grep -oP '^\s+(\[[A-Z]+\]\s+)?\K[A-Za-z][A-Za-z0-9]*-\d+(\.\d+)*(?= - )')
CLAIMED_TASK_IDS=$(echo "$CLAIMED_TASK_IDS" | xargs)  # trim whitespace

If CLAIMED_TASK_IDS is empty and no stop sentinel: use Monitor (persistent) to wait for the next basic-ready event. The daemon writes basic-ready:TASK-N lines to $DAEMON_LOG; Monitor tails that file:

# Foreground tail — Monitor reads its stdout as the event stream.
# -c +${OFFSET} resumes from the checkpointed byte offset (0 = start of file).
# IMPORTANT: Before calling Monitor, save the Monitor task ID to .monitor-task-id so
# stopStaleMon can TaskStop it in the next session (survives context compression).
# The Monitor harness returns a task ID in its result (e.g. "Monitor started (task bXXXX, ...)").
# After receiving that confirmation, write: echo "$MONITOR_TASK_ID" > "${BACKLOG_DIR}/.monitor-task-id"
MONITOR_TASK_ID_FILE="${BACKLOG_DIR}/.monitor-task-id"
Monitor(persistent=true,
    command="tail -c +${OFFSET} -f \"$DAEMON_LOG\" | grep --line-buffered -E \"^(basic-ready|epic-ready|child-done|proposal-approved|plan-approved):\"",
    description="loop-backlog daemon notification. An event line (basic-ready:TASK-N, epic-ready:TASK-N, child-done:TASK-N, proposal-approved:TASK-N, or plan-approved:TASK-N) has arrived from the backlog task board. Event lines may re-emit roughly every 60s while a task stays actionable — this re-emit is the normal re-attach signal for an idle session (e.g. after /clear). Non-event lines are filtered out. If this is a new Claude session, invoke /loop-backlog in the project root to resume the worker loop — it will re-claim and dispatch this event automatically."
  )
# After Monitor returns its task ID, save it for stopStaleMon in the next session:
# MONITOR_TASK_ID=$(... extract from Monitor result ...)
# echo "$MONITOR_TASK_ID" > "$MONITOR_TASK_ID_FILE"
echo $(wc -c < "$DAEMON_LOG" 2>/dev/null || echo 0) > "$CHECKPOINT_FILE"

Any output line matching basic-ready:TASK-* is the wake-up signal; re-enter workerLoop().

waitForAgents

Poll backlog/.agent-done-TASK-N signal files for every task in CLAIMED_TASK_IDS. Loops with sleep 5 until all signal files are present.

# $1: space-separated list of TASK-IDs to wait for
waitForAgents() {
  local REMAINING="$1"
  local ALL_DONE=false
  while [ "$ALL_DONE" = "false" ]; do
    ALL_DONE=true
    local STILL_WAITING=""
    for TID in $REMAINING; do
      SIGNAL_FILE="${REPO_ROOT}/backlog/.agent-done-${TID}"
      if [ ! -f "$SIGNAL_FILE" ]; then
        ALL_DONE=false
        STILL_WAITING="${STILL_WAITING} ${TID}"
      fi
    done
    REMAINING=$(echo "$STILL_WAITING" | xargs)
    if [ "$ALL_DONE" = "false" ]; then
      echo "waitForAgents: still waiting for:${REMAINING}"
      sleep 5
    fi
  done
  echo "waitForAgents: all agents done"
}

executePrompt

Build a self-contained prompt string for a background agent executing one task. The prompt must not depend on external bash variables at call time — all values are interpolated into the string before passing to the Agent tool. The agent's allowed-tools list explicitly excludes Agent to prevent recursive spawn.

# Usage: PROMPT=$(buildExecutePrompt "$TASK_ID" "$TASK_TITLE" "$TASK_DESC" "$WORKTREE" "$BRANCH" "$SIGNAL_FILE")
buildExecutePrompt() {
  local TID="$1"
  local TTITLE="$2"
  local TDESC="$3"
  local TWT="$4"
  local TBRANCH="$5"
  local TSIGNAL="$6"

  # Pre-dispatch enrichment: inject Archguard Risk Context (advisory, non-blocking).
  # Cap at 3 files per claim to keep latency < 3s. Skip silently if helpers unavailable.
  local RISK_BLOCK=""
  local _PARSE_SCRIPT="${BAIME_SCRIPTS}/../skills/loop-backlog/lib/parse-task-files.js"
  local _FETCH_SCRIPT="${BAIME_SCRIPTS}/../skills/loop-backlog/lib/fetch-risk-context.js"
  if [ -f "$_PARSE_SCRIPT" ] && [ -f "$_FETCH_SCRIPT" ] && command -v node >/dev/null 2>&1; then
    local _FILES
    _FILES=$(node "$_PARSE_SCRIPT" "$TDESC" 2>/dev/null | \
      node -e "const d=require('fs').readFileSync('/dev/stdin','utf8').trim(); \
               const arr=d?JSON.parse(d):[]; \
               process.stdout.write(arr.slice(0,3).join('\n'));" 2>/dev/null || true)
    if [ -n "$_FILES" ]; then
      local _FILE_ARGS=()
      while IFS= read -r _f; do
        [ -n "$_f" ] && _FILE_ARGS+=("$_f")
      done <<< "$_FILES"
      RISK_BLOCK=$(node "$_FETCH_SCRIPT" "${_FILE_ARGS[@]}" 2>/dev/null || true)
    fi
  fi

  # Build optional risk block suffix (empty string → omit section entirely)
  local _RISK_SECTION=""
  if [ -n "$RISK_BLOCK" ]; then
    _RISK_SECTION="
${RISK_BLOCK}"
  fi

  cat <<PROMPT_EOF
You are a background task agent. Your only job is to execute the task described below.

## Task
ID: ${TID}
Title: ${TTITLE}
Branch: ${TBRANCH}
Worktree: ${TWT}
Signal file: ${TSIGNAL}

## Description
${TDESC}
${_RISK_SECTION}
## Constraints
- Work exclusively inside the worktree at: ${TWT}
- Do NOT run git merge or git push
- Do NOT spawn sub-agents (Agent tool is not available to you)
- After all work is complete, run git add -A && git commit if there are changes
- Write the signal file as the LAST action before exiting

## Completing the task
When done (success):
  Write file ${TSIGNAL} with content: done

If you cannot continue without human input (escalation):
  Write file ${TSIGNAL} with content: needs-human: <one-line reason>

## Execution Protocol

**Phase checkpoints**: After completing each ## Phase section described in the task Description,
append a structured note to the worktree summary file:
  echo "Phase X ✓ $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> ${TWT}/.agent-summary-${TID}
  echo "<one-line summary of what was done>" >> ${TWT}/.agent-summary-${TID}

**DoD verification notes**: For each DoD command run, append to the summary file:
  echo "DoD #N: PASS|FAIL — <cmd>" >> ${TWT}/.agent-summary-${TID}
  echo "<up to 5 lines of output on failure>" >> ${TWT}/.agent-summary-${TID}

**Execution Summary**: Before writing the signal file, write a final summary section:
  printf '## Execution Summary\nResult: Done|Needs Human\nCommit: <hash or no changes>\n<ordered list of Phase and DoD outcomes>\n' >> ${TWT}/.agent-summary-${TID}

Do NOT run `backlog task edit` with --status, --dod, or --check-dod. (--planSet and --set-field do not exist in the backlog CLI; see ADR-006.)
You MAY run `backlog task edit <TASK_ID> --append-notes "..."` to record Phase checkpoints and DoD results.
The worker (main branch) handles all status transitions and field writes.

allowed-tools: Bash, Read, Write, Edit, Glob, Grep
PROMPT_EOF
}

withWorktree

BRANCH="task/${TASK_ID}"
PROJECT_NAME=$(basename "$REPO_ROOT")
WORKTREE="${REPO_ROOT}/../${PROJECT_NAME}-${TASK_ID}"
git worktree add "$WORKTREE" -b "$BRANCH"

# Symlink configured dirs (e.g. node_modules) to avoid reinstall
for SYM in $CFG_SYMLINKS; do
  [ -e "${REPO_ROOT}/${SYM}" ] && \
    ln -sf "${REPO_ROOT}/${SYM}" "${WORKTREE}/${SYM}"
done

cd "$WORKTREE"

execute → readHumanReply

Before reading the Description, check whether this task was previously escalated.

TASK_VIEW=$(backlog task view "$TASK_ID" --plain)
NOTES_SECTION=$(echo "$TASK_VIEW" | awk '/^Implementation Notes:/,0' | tail -n +2)
LAST_ESCALATED_LINE=$(echo "$NOTES_SECTION" | grep -n "^Escalated:" | tail -1 | cut -d: -f1)

If LAST_ESCALATED_LINE is non-empty, extract everything after it as the human reply:

HUMAN_REPLY=""
if [ -n "$LAST_ESCALATED_LINE" ]; then
  HUMAN_REPLY=$(echo "$NOTES_SECTION" | tail -n +$((LAST_ESCALATED_LINE + 1)))
fi

If HUMAN_REPLY is non-empty, read it carefully before proceeding. It is a free-form natural-language answer from the user. Extract any decisions, version numbers, file paths, or other context it provides. Use this information throughout execution — it supersedes any open questions left by the previous escalation. Log what you understood:

if [ -n "$HUMAN_REPLY" ]; then
  backlog task edit "$TASK_ID" --append-notes \
    "Human reply received — interpreted context:
$(echo "$HUMAN_REPLY" | head -10)"
fi

execute → followDescription

TITLE=$(echo "$TASK_VIEW" | grep -oP '^Task \S+ - \K.+' | head -1)

# Accumulator for final-summary
EXECUTION_LOG=""
log_exec() { EXECUTION_LOG="${EXECUTION_LOG}$1\n"; }

Read the task Description in full. The Description is the primary authority on what to do. If a human reply was extracted above, it takes precedence for any open questions (e.g. version numbers, file paths, decisions) — apply it before executing phases. Follow the Description's ## Phase sections in order. After each phase completes, append a structured checkpoint that includes the key outputs or decisions from that phase:

PHASE_NOTE="Phase <X> ✓ $(date -u +%Y-%m-%dT%H:%M:%SZ)
<one-line summary of what was done or found>"
backlog task edit "$TASK_ID" --append-notes "$PHASE_NOTE"
log_exec "$PHASE_NOTE"

If a phase produced notable command output (e.g. test results, validation output, key tool responses), include the relevant excerpt (truncated to ~20 lines) in the note.

Do not invent steps beyond what the Description specifies. Do not assume a task type.

verifyDod

DOD_COUNT=$(echo "$TASK_VIEW" | grep -cP '^\- \[.\] #\d+')

for N in $(seq 0 $((DOD_COUNT - 1))); do
  CMD=$(echo "$TASK_VIEW" | grep -P "^\- \[.\] #${N} " | sed "s/^- \[.\] #${N} //")
  ATTEMPTS=0
  while true; do
    if bash -c "$CMD"; then
      backlog task edit "$TASK_ID" --check-dod $N
      DOD_PASS_NOTE="DoD #${N}: PASS"
      backlog task edit "$TASK_ID" --append-notes "${DOD_PASS_NOTE} — ${CMD}"
      log_exec "DoD #${N} ✓: ${CMD}"
      break
    fi
    ATTEMPTS=$((ATTEMPTS + 1))
    LAST_ERROR="$(bash -c "$CMD" 2>&1 || true)"
    if [ $ATTEMPTS -ge 3 ]; then
      STUCK_INDEX=$N
      STUCK_CMD="$CMD"
      DOD_FAIL_NOTE="DoD #${N}: FAIL"
      backlog task edit "$TASK_ID" --append-notes "${DOD_FAIL_NOTE} — ${STUCK_CMD}
$(echo "$LAST_ERROR" | head -5)"
      log_exec "DoD #${N} ✗ STUCK after 3 attempts: ${CMD}
Last error:
${LAST_ERROR}"
      break 2   # → Failure path
    fi
    # Log the failure and what fix is being attempted
    FIX_NOTE="DoD #${N} ✗ attempt ${ATTEMPTS}: ${CMD}
Error: $(echo "$LAST_ERROR" | head -5)
→ applying fix..."
    backlog task edit "$TASK_ID" --append-notes "$FIX_NOTE"
    log_exec "$FIX_NOTE"
    # Fix the issue causing the failure, then retry
  done
done

verifyDod → meta-cc-digest (Gate Evidence Pack)

After all DoD items pass, the agent MUST collect process evidence from meta-cc and append a Gate Evidence Pack to the task Notes. This provides evidence independent of agent self-reporting (data_source: meta-cc-session).

Agent protocol (follow the MCP guide in plugin/skills/loop-backlog/meta-cc-digest.sh):

# Step 1: locate the current session directory
SESSION_DIR=$(mcp__plugin_meta-cc_meta-cc__get_session_directory)

# Step 2: collect the three evidence signals
FILE_ACTIVITY=$(mcp__plugin_meta-cc_meta-cc__query_file_activity --session_dir "$SESSION_DIR" 2>/dev/null || echo "")
ERROR_DATA=$(mcp__plugin_meta-cc_meta-cc__analyze_errors --session_dir "$SESSION_DIR" 2>/dev/null || echo "")
EDIT_SEQ=$(mcp__plugin_meta-cc_meta-cc__query_edit_sequences --session_dir "$SESSION_DIR" 2>/dev/null || echo "")

# Step 3: compute SCOPE_DIFF by comparing FILE_ACTIVITY to task Implementation Plan file refs
# (files appearing in FILE_ACTIVITY but not mentioned in the task plan → out-of-scope)

# Step 4a: if all signals collected, append structured Gate Evidence Pack
if [ -n "$FILE_ACTIVITY" ] || [ -n "$ERROR_DATA" ] || [ -n "$EDIT_SEQ" ]; then
  backlog task edit "$TASK_ID" --append-notes "## Gate Evidence Pack
FILE_ACTIVITY: ${FILE_ACTIVITY:-none}
ERROR_COUNT: ${ERROR_DATA:-0}
EDIT_OSCILLATION: ${EDIT_SEQ:-none}
SCOPE_DIFF: ${SCOPE_DIFF:-none}
data_source: meta-cc-session"
else
  # Step 4b: graceful degradation — meta-cc unavailable, do not block gate
  backlog task edit "$TASK_ID" --append-notes "## Gate Evidence Pack
meta-cc-digest: unavailable (reason: MCP tools returned empty)
data_source: meta-cc-session"
fi

# Step 5: conditionally wire evidence_independence into gcl-events.jsonl
# (see meta-cc-digest.sh --help for the full wiring protocol)
JSONL="${REPO_ROOT}/docs/research/gcl-events.jsonl"
if [ -f "$JSONL" ] && grep -q '"evidence_independence"' "$JSONL" 2>/dev/null; then
  python3 -c "
import json
lines = open('${JSONL}').readlines()
updated = []
last_idx = None
for i, line in enumerate(lines):
    try:
        r = json.loads(line)
        if r.get('task_id') == '${TASK_ID}':
            last_idx = i
    except Exception:
        pass
    updated.append(line)
if last_idx is not None:
    r = json.loads(updated[last_idx])
    r['evidence_independence'] = 'meta-cc-grounded'
    updated[last_idx] = json.dumps(r) + '\n'
open('${JSONL}', 'w').writelines(updated)
" 2>/dev/null || true
else
  backlog task edit "$TASK_ID" --append-notes "gcl-evidence-independence: meta-cc-grounded (pending jsonl)"
fi

On any MCP call failure: append meta-cc-digest: unavailable (reason: <msg>) and continue without blocking the gate transition. The meta-cc digest is advisory evidence, never a gate blocker.

conditionalCommit

git add -A
if ! git diff --cached --quiet; then
  git commit -m "${TITLE} (${TASK_ID})"
  COMMIT_HASH=$(git rev-parse HEAD)
else
  COMMIT_HASH="(no file changes)"
fi

merge

Precondition: merge is only reached after workerLoop's independent DoD verification has passed. The workerLoop serial merge loop runs verifyDodInWorkerLoop before calling git merge; a failing DoD command redirects control to escalation instead.

cd "$REPO_ROOT"
# RULE: never pipe git merge (| tail/cat/tee) — no-pipe: a pipe replaces its exit code and masks abort.
if git merge --no-ff "$BRANCH" -m "merge: ${TITLE} (${TASK_ID})"; then
  # Guard: MERGE_HEAD or unmerged files → treat as failure, never mark Done
  if [ -f ".git/MERGE_HEAD" ] || [ -n "$(git diff --name-only --diff-filter=U)" ]; then
    backlog task edit "$TASK_ID" --status "Basic: Needs Human" \
      --append-notes "Merge guard: MERGE_HEAD/unmerged files present — worktree preserved."
    echo "needs-human: merge guard triggered" > "${REPO_ROOT}/backlog/.agent-done-${TASK_ID}"
    exit 0
  fi
  FINAL_SUMMARY="## Execution Summary

**Result:** Done  
**Commit:** ${COMMIT_HASH}

### Execution Log
$(echo -e "$EXECUTION_LOG")"
  # post-merge append: read agent summary from worktree and append to task notes
  AGENT_SUMMARY_FILE="${WORKTREE}/.agent-summary-${TASK_ID}"
  if [ -f "$AGENT_SUMMARY_FILE" ]; then
    AGENT_SUMMARY_CONTENT=$(cat "$AGENT_SUMMARY_FILE")
    backlog task edit "$TASK_ID" --append-notes "$AGENT_SUMMARY_CONTENT"
  else
    backlog task edit "$TASK_ID" --append-notes "WARNING: agent-summary missing for ${TASK_ID} — execution trace unavailable"
  fi
  backlog task edit "$TASK_ID" \
    --status "Basic: Done" \
    --append-notes "Completed: $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    --final-summary "$FINAL_SUMMARY"
  # Write terminal idempotency marker
  echo "cap:execute=done $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    >> "${REPO_ROOT}/backlog/.caps/${TASK_ID}"
  # notifyParentIfAny: check parent_task_id field
  PARENT=$(backlog task view "$TASK_ID" --plain | grep -oP '(?<=^Parent: )[A-Za-z][A-Za-z0-9]*-\d+(\.\d+)*' | head -1)
  if [ -n "$PARENT" ]; then
    backlog task edit "$PARENT" --append-notes \
      "Sub-task ${TASK_ID} completed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  fi
  git worktree remove "$WORKTREE"
  git branch -d "$BRANCH"
  WORK_DONE=true
else
  FINAL_SUMMARY="## Execution Summary

**Result:** Needs Human — merge conflict  
**Branch:** ${BRANCH}  
**Worktree:** ${WORKTREE}

### Execution Log
$(echo -e "$EXECUTION_LOG")

### Resolution Steps
\`\`\`
cd ${REPO_ROOT}
git mergetool
git commit
git worktree remove ${WORKTREE}
git branch -d ${BRANCH}
\`\`\`"
  backlog task edit "$TASK_ID" \
    --status "Basic: Needs Human" \
    --append-notes "Merge conflict: $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    --final-summary "$FINAL_SUMMARY"
  # Write cap:merge=failed idempotency marker
  echo "cap:merge=failed $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    >> "${REPO_ROOT}/backlog/.caps/${TASK_ID}"
  echo "Merge conflict: $TASK_ID — worktree preserved at $WORKTREE"
  WORK_DONE=false
fi

workerLoop (parallel)

The top-level orchestration using claimBatch, background Agent spawning, and serial merge.

# After loadConfig, ensureDaemonScript, daemonBootstrap, and reap have run:

# 1. Claim a batch of up to CFG_MAX_PARALLEL Basic: Ready tasks
# (claimBatch sets CLAIMED_TASK_IDS)

if [ -z "$CLAIMED_TASK_IDS" ]; then
  # No basic task to claim — block on the daemon event stream (all five channels).
  # Monitor(persistent=true,
  #   command="tail -c +${OFFSET} -f \"$DAEMON_LOG\" | grep --line-buffered -E \"^(basic-ready|epic-ready|child-done|proposal-approved|plan-approved):\"",
  #   description="loop-backlog daemon notification. An event line (basic-ready:TASK-N, epic-ready:TASK-N, child-done:TASK-N, proposal-approved:TASK-N, or plan-approved:TASK-N) has arrived from the backlog task board. Event lines may re-emit roughly every 60s while a task stays actionable — this re-emit is the normal re-attach signal for an idle session (e.g. after /clear). Non-event lines are filtered out. If this is a new Claude session, invoke /loop-backlog in the project root to resume the worker loop — it will re-claim and dispatch this event automatically."
  # )
  # After Monitor returns, record the new checkpoint offset:
  # echo $(wc -c < "$DAEMON_LOG" 2>/dev/null || echo 0) > "$CHECKPOINT_FILE"
  # On basic-ready:TASK-N      → re-enter workerLoop (claim & execute).
  # On epic-ready:TASK-N       → epicDecompose(extractId), then re-enter workerLoop.
  # On child-done:TASK-N       → onChildDone(extractId), then re-enter workerLoop.
  # On proposal-approved:TASK-N → startPlanDraft(extractId), then re-enter workerLoop.
  # On plan-approved:TASK-N    → startFinalise(extractId), then re-enter workerLoop.
  # Non-event lines are filtered out by the grep filter and never reach Monitor.
  # Dispatch is handled by the Monitor event loop; this bash section exits to let the
  # Monitor dispatch call the appropriate handler function.
  # Example dispatch (in the Monitor event handler):
  #   case "$EVENT" in
  #     epic-ready:*)        epicDecompose "${EVENT#epic-ready:}" ;;
  #     child-done:*)        onChildDone "${EVENT#child-done:}" ;;
  #     proposal-approved:*) startPlanDraft "${EVENT#proposal-approved:}" ;;
  #     plan-approved:*)     startFinalise "${EVENT#plan-approved:}" ;;
  #   esac
  exit 0
fi

# 2. Create worktrees and spawn one background agent per task
declare -A TASK_WORKTREES
declare -A TASK_BRANCHES
for TASK_ID in $CLAIMED_TASK_IDS; do
  BRANCH="task/${TASK_ID}"
  PROJECT_NAME=$(basename "$REPO_ROOT")
  WORKTREE="${REPO_ROOT}/../${PROJECT_NAME}-${TASK_ID}"
  git worktree add "$WORKTREE" -b "$BRANCH"
  for SYM in $CFG_SYMLINKS; do
    [ -e "${REPO_ROOT}/${SYM}" ] && ln -sf "${REPO_ROOT}/${SYM}" "${WORKTREE}/${SYM}"
  done
  TASK_WORKTREES[$TASK_ID]="$WORKTREE"
  TASK_BRANCHES[$TASK_ID]="$BRANCH"

  TASK_VIEW=$(backlog task view "$TASK_ID" --plain)
  TASK_TITLE=$(echo "$TASK_VIEW" | grep -oP '^Task \S+ - \K.+' | head -1)
  TASK_DESC=$(echo "$TASK_VIEW" | awk '/^Description:/,/^(Status|Assignee|Labels|Priority|Due|Created|Updated|Notes):/' | tail -n +2)
  SIGNAL_FILE="${REPO_ROOT}/backlog/.agent-done-${TASK_ID}"

  AGENT_PROMPT=$(buildExecutePrompt \
    "$TASK_ID" "$TASK_TITLE" "$TASK_DESC" "$WORKTREE" "$BRANCH" "$SIGNAL_FILE")

  # Spawn background agent — run_in_background=true
  Agent(run_in_background=true, prompt="$AGENT_PROMPT")
  echo "$TASK_ID" >> "${REPO_ROOT}/backlog/.active-agents"
done

# 3. Wait for all agents to write their signal files
waitForAgents "$CLAIMED_TASK_IDS"

# Merge-lock helpers: ensure only one worker serialises git merges at a time.
# This protects against /clear leaving a partial merge in the main worktree.
MERGE_LOCK="${REPO_ROOT}/backlog/.merge-lock"

acquire_merge_lock() {
  if [ -f "$MERGE_LOCK" ]; then
    LOCK_PID=$(cat "$MERGE_LOCK" 2>/dev/null || echo "")
    if [ -n "$LOCK_PID" ] && kill -0 "$LOCK_PID" 2>/dev/null; then
      echo "acquire_merge_lock: waiting for pid $LOCK_PID..."
      while [ -f "$MERGE_LOCK" ] && kill -0 "$LOCK_PID" 2>/dev/null; do sleep 1; done
    fi
    rm -f "$MERGE_LOCK"
  fi
  echo $$ > "$MERGE_LOCK"
}

release_merge_lock() { rm -f "$MERGE_LOCK"; }

# 4. Serial merge: read signal, merge or escalate, delete signal file
acquire_merge_lock
for TASK_ID in $CLAIMED_TASK_IDS; do
  SIGNAL_FILE="${REPO_ROOT}/backlog/.agent-done-${TASK_ID}"
  SIGNAL_CONTENT=$(cat "$SIGNAL_FILE" 2>/dev/null || echo "needs-human: signal file missing")
  rm -f "$SIGNAL_FILE"
  ACTIVE_TMP=$(mktemp)
  grep -v "^${TASK_ID}$" "${REPO_ROOT}/backlog/.active-agents" > "$ACTIVE_TMP" 2>/dev/null || true
  mv "$ACTIVE_TMP" "${REPO_ROOT}/backlog/.active-agents"

  BRANCH="${TASK_BRANCHES[$TASK_ID]}"
  WORKTREE="${TASK_WORKTREES[$TASK_ID]}"
  TASK_VIEW=$(backlog task view "$TASK_ID" --plain)
  TITLE=$(echo "$TASK_VIEW" | grep -oP '^Task \S+ - \K.+' | head -1)

  # pre-merge DoD verification (independent of agent signal)
  if [ "$SIGNAL_CONTENT" = "done" ] && [ -d "$WORKTREE" ]; then
    PRE_MERGE_DOD_PASS=true
    PRE_MERGE_FAIL_MSG=""
    DOD_N=0
    while IFS= read -r DOD_CMD; do
      DOD_CMD=$(echo "$DOD_CMD" | sed 's/^- \[.\] #[0-9]* //')
      cd "$WORKTREE"
      DOD_OUT=$(bash -c "$DOD_CMD" 2>&1)
      DOD_EXIT=$?
      cd "$REPO_ROOT"
      if [ $DOD_EXIT -ne 0 ]; then
        PRE_MERGE_DOD_PASS=false
        PRE_MERGE_FAIL_MSG="workerLoop DoD #${DOD_N} failed: ${DOD_CMD}\n$(echo "$DOD_OUT" | head -5)"
        backlog task edit "$TASK_ID" --append-notes "workerLoop pre-merge DoD #${DOD_N} FAIL: ${DOD_CMD}"
        break
      fi
      backlog task edit "$TASK_ID" --append-notes "workerLoop DoD #${DOD_N}: PASS — ${DOD_CMD}"
      DOD_N=$((DOD_N + 1))
    done < <(backlog task view "$TASK_ID" --plain | grep -oP '^- \[.\] #\d+ .+')

    if [ "$PRE_MERGE_DOD_PASS" != "true" ]; then
      SIGNAL_CONTENT="needs-human: ${PRE_MERGE_FAIL_MSG}"
    fi
  fi

  cd "$REPO_ROOT"
  if [ "$SIGNAL_CONTENT" = "done" ]; then
    # Standard merge path (same as existing merge section)
    # RULE: never pipe git merge (| tail/cat/tee) — no-pipe: a pipe replaces its exit code and masks abort.
    if git merge --no-ff "$BRANCH" -m "merge: ${TITLE} (${TASK_ID})"; then
      # Guard: MERGE_HEAD or unmerged files → treat as failure, never mark Done
      if [ -f ".git/MERGE_HEAD" ] || [ -n "$(git diff --name-only --diff-filter=U)" ]; then
        backlog task edit "$TASK_ID" --status "Basic: Needs Human" \
          --append-notes "Merge guard: MERGE_HEAD/unmerged files present — worktree preserved."
        echo "needs-human: merge guard triggered" > "${REPO_ROOT}/backlog/.agent-done-${TASK_ID}"
        exit 0
      fi
      # post-merge append: read agent summary from worktree and append to task notes
      AGENT_SUMMARY_FILE="${WORKTREE}/.agent-summary-${TASK_ID}"
      if [ -f "$AGENT_SUMMARY_FILE" ]; then
        AGENT_SUMMARY_CONTENT=$(cat "$AGENT_SUMMARY_FILE")
        backlog task edit "$TASK_ID" --append-notes "$AGENT_SUMMARY_CONTENT"
      else
        backlog task edit "$TASK_ID" --append-notes "WARNING: agent-summary missing for ${TASK_ID} — execution trace unavailable"
      fi
      backlog task edit "$TASK_ID" \
        --status "Basic: Done" \
        --append-notes "Completed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
      # Write cap:execute=done marker
      echo "cap:execute=done $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
        >> "${REPO_ROOT}/backlog/.caps/${TASK_ID}"
      # notifyParentIfAny: check parent_task_id in task frontmatter
      PARENT=$(backlog task view "$TASK_ID" --plain | grep -oP '(?<=^Parent: )[A-Za-z][A-Za-z0-9]*-\d+(\.\d+)*' | head -1)
      if [ -n "$PARENT" ]; then
        backlog task edit "$PARENT" --append-notes \
          "Sub-task ${TASK_ID} completed: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
      fi
      git worktree remove "$WORKTREE"
      git branch -d "$BRANCH"
    else
      backlog task edit "$TASK_ID" \
        --status "Basic: Needs Human" \
        --append-notes "Merge conflict: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
      # Write cap:merge=failed marker
      echo "cap:merge=failed $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
        >> "${REPO_ROOT}/backlog/.caps/${TASK_ID}"
    fi
  else
    REASON=$(echo "$SIGNAL_CONTENT" | sed 's/^needs-human: //')
    backlog task edit "$TASK_ID" \
      --status "Basic: Needs Human" \
      --append-notes "Escalated: ${REASON}
To continue: answer in Implementation Notes, then set status → Basic: Ready."
    # Write cap:execute=failed marker
    echo "cap:execute=failed $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
      >> "${REPO_ROOT}/backlog/.caps/${TASK_ID}"
  fi
done
release_merge_lock

verifyDodInWorkerLoop

Independent DoD verification executed by the workerLoop serial merge loop before each git merge. This is distinct from the agent's own verifyDod loop: it re-runs every DoD command from the worktree as a second, independent check. If any command fails, the merge is skipped and the task is escalated with a needs-human: workerLoop DoD signal.

Key properties:

  • Runs in the worktree (cd "$WORKTREE") so paths resolve correctly.
  • Only runs when the agent signalled "done" and the worktree directory still exists.
  • On failure, overwrites SIGNAL_CONTENT with "needs-human: workerLoop DoD #N failed: …", causing the standard escalation branch below to fire.
  • On success, appends a per-command "workerLoop DoD #N: PASS — <cmd>" note for each passing command.

Failure path (Stuck)

cd "$REPO_ROOT"
FINAL_SUMMARY="## Execution Summary

**Result:** Needs Human — stuck on DoD #${STUCK_INDEX}  
**Branch:** ${BRANCH}  
**Worktree:** ${WORKTREE}

### Failing Command
\`\`\`
${STUCK_CMD}
\`\`\`

### Last Error
\`\`\`
${LAST_ERROR}
\`\`\`

### Execution Log
$(echo -e "$EXECUTION_LOG")

### Cleanup
\`\`\`
git worktree remove ${WORKTREE} --force
git branch -D ${BRANCH}
\`\`\`"
backlog task edit "$TASK_ID" \
  --status "Basic: Needs Human" \
  --append-notes "Stuck on DoD #${STUCK_INDEX}: $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  --final-summary "$FINAL_SUMMARY"
# Write cap:execute=failed marker
echo "cap:execute=failed $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  >> "${REPO_ROOT}/backlog/.caps/${TASK_ID}"
echo "Stuck: $TASK_ID (DoD #$STUCK_INDEX)"
echo "Task moved to Basic: Needs Human. Worktree preserved at $WORKTREE"
WORK_DONE=false

Epic dispatch (epic-ready / child-done)

When Monitor yields an epic-ready: or child-done: line, the worker runs these handlers instead of claiming a basic task. Both are idempotent via cap:* markers.

# extractId: pull ID from an event line like "epic-ready:TASK-12" or "epic-ready:BACK-7"
extractId() { echo "${1#*:}"; }

# childrenOf EPIC_ID → list of child task IDs (frontmatter parent_task_id == EPIC_ID)
childrenOf() {
  local EPIC_ID="$1"
  grep -lE "^parent_task_id:\s*${EPIC_ID}\$" "${REPO_ROOT}"/backlog/tasks/*.md 2>/dev/null \
    | while read -r f; do grep -oP '(?<=^id:\s)\S+' "$f"; done
}

taskStatus() { backlog task view "$1" --plain 2>/dev/null | grep -oP '(?<=Status:).*' \
  | head -1 | grep -oP '(Basic|Epic): [A-Za-z ]+' | head -1 | xargs; }

hasCap() { grep -q "cap:$2" "$(ls "${REPO_ROOT}"/backlog/tasks/${1,,}\ *.md 2>/dev/null | head -1)" 2>/dev/null; }

View the full SKILL.md on GitHub

Methodology Bootstrapping

Apply Bootstrapped AI Methodology Engineering (BAIME) to systematically develop and validate software engineering methodologies through observation, codification, and automation.

The best methodologies are not designed but evolved through systematic observation, codification, and automation of successful practices.


What is BAIME?

BAIME (Bootstrapped AI Methodology Engineering) is a unified framework that integrates three complementary methodologies optimized for LLM-based development:

  1. OCA Cycle (Observe-Codify-Automate) - Core iterative framework
  2. Empirical Validation - Scientific method and data-driven decisions
  3. Value Optimization - Dual-layer value functions for quantitative evaluation

This skill provides the complete BAIME framework for systematic methodology development. The methodology is especially powerful when combined with AI agents (like Claude Code) that can execute the OCA cycle, coordinate specialized agents, and calculate value functions automatically.

Key Innovation: BAIME treats methodology development like software development—with empirical observation, automated testing, continuous iteration, and quantitative metrics.


When to Use This Skill

Use this skill when you need to:

  • 🎯 Create systematic methodologies for testing, CI/CD, error handling, observability, etc.
  • 📊 Validate methodologies empirically with data-driven evidence
  • 🔄 Evolve practices iteratively using OCA (Observe-Codify-Automate) cycle
  • 📈 Measure methodology quality with dual-layer value functions
  • 🚀 Achieve rapid convergence (typically 3-7 iterations, 6-15 hours)
  • 🌍 Create transferable methodologies (70-95% reusable across projects)

Don't use this skill for:

  • ❌ One-time ad-hoc tasks without reusability goals
  • ❌ Trivial processes (<100 lines of code/docs)
  • ❌ When established industry standards fully solve your problem

Quick Start with BAIME (10 minutes)

1. Define Your Domain

Choose what methodology you want to develop using BAIME:

  • Testing strategy (15x speedup example)
  • CI/CD pipeline (2.5-3.5x speedup example)
  • Error recovery patterns (80% error reduction example)
  • Observability system (23-46x speedup example)
  • Dependency management (6x speedup example)
  • Documentation system (47% token cost reduction example)
  • Knowledge transfer (3-8x speedup example)
  • Technical debt management
  • Cross-cutting concerns

2. Establish Baseline

Measure current state:

# Example: Testing domain
- Current coverage: 65%
- Test quality: Ad-hoc
- No systematic approach
- Bug rate: Baseline

# Example: CI/CD domain
- Build time: 5 minutes
- No quality gates
- Manual releases

3. Set Dual Goals

Define both layers:

  • Instance goal (domain-specific): "Reach 80% test coverage"
  • Meta goal (methodology): "Create reusable testing strategy with 85%+ transferability"

4. Start Iteration 0

Follow the OCA cycle (see reference/observe-codify-automate.md)


Specialized Subagents

BAIME provides two specialized Claude Code subagents to streamline experiment execution:

iteration-prompt-designer

When to use: At experiment start, to create comprehensive ITERATION-PROMPTS.md

What it does:

  • Designs iteration templates tailored to your domain
  • Incorporates modular Meta-Agent architecture
  • Provides domain-specific guidance for each iteration
  • Creates structured prompts for baseline and subsequent iterations

How to invoke:

Use the Task tool with subagent_type="iteration-prompt-designer"

Example:
"Design ITERATION-PROMPTS.md for refactoring methodology experiment"

Benefits:

  • ✅ Comprehensive iteration prompts (saves 2-3 hours setup time)
  • ✅ Domain-specific value function design
  • ✅ Proper baseline iteration structure
  • ✅ Evidence-driven evolution guidance

iteration-executor

When to use: For each iteration execution (Iteration 0, 1, 2, ...)

What it does:

  • Executes iteration through lifecycle phases (Observe → Codify → Automate → Evaluate)
  • Coordinates Meta-Agent capabilities and agent invocations
  • Tracks state transitions (M_{n-1} → M_n, A_{n-1} → A_n, s_{n-1} → s_n)
  • Calculates dual-layer value functions (V_instance, V_meta) systematically
  • Evaluates convergence criteria rigorously
  • Generates complete iteration documentation

How to invoke:

Use the Task tool with subagent_type="iteration-executor"

Example:
"Execute Iteration 2 of testing methodology experiment using iteration-executor"

Benefits:

  • ✅ Consistent iteration structure across experiments
  • ✅ Systematic value calculation (reduces bias, improves honesty)
  • ✅ Proper convergence evaluation (prevents premature convergence)
  • ✅ Complete artifact generation (data, knowledge, reflections)
  • ✅ Reduced iteration time (structured execution vs ad-hoc)

Important: iteration-executor reads capability files fresh each iteration (no caching) to ensure latest guidance is applied.


knowledge-extractor

When to use: After experiment converges, to extract and transform knowledge into reusable artifacts

What it does:

  • Extracts patterns, principles, templates from converged BAIME experiment
  • Transforms experiment artifacts into production-ready Claude Code skills
  • Creates knowledge base entries (patterns/.md, principles/.md)
  • Validates output quality with structured criteria (V_instance ≥ 0.85)
  • Achieves 195x speedup (2 min vs 390 min manual extraction)
  • Produces distributable, reusable artifacts for the community

How to invoke:

Use the Task tool with subagent_type="knowledge-extractor"

Example:
"Extract knowledge from Bootstrap-004 refactoring experiment and create code-refactoring skill using knowledge-extractor"

Benefits:

  • ✅ Systematic knowledge preservation (vs ad-hoc documentation)
  • ✅ Reusable Claude Code skills (ready for distribution)
  • ✅ Quality validation (95% content equivalence to hand-crafted)
  • ✅ Fast extraction (2-5 min, 195x speedup)
  • ✅ Knowledge base population (patterns, principles, templates)
  • ✅ Automated artifact generation (43% workflow automation with 4 tools)

Lifecycle position: Post-Convergence phase

Experiment Design → iteration-prompt-designer → ITERATION-PROMPTS.md
       ↓
Iterate → iteration-executor (x N) → iteration-0..N.md
       ↓
Converge → Create results.md
       ↓
Extract → knowledge-extractor → .claude/skills/ + knowledge/
       ↓
Distribute → Claude Code users

Validated performance (Bootstrap-005):

  • Speedup: 195x (390 min → 2 min)
  • Quality: V_instance = 0.87, 95% content equivalence
  • Reliability: 100% success across 3 experiments
  • Automation: 43% of workflow (6/14 steps)

Core Framework

The OCA Cycle

Observe → Codify → Automate
   ↑                    ↓
   └────── Evolve ──────┘

Observe: Collect empirical data about current practices

  • Use meta-cc MCP tools to analyze session history
  • Git analysis for commit patterns
  • Code metrics (coverage, complexity)
  • Access pattern tracking
  • Error rate monitoring

Codify: Extract patterns and document methodologies

  • Pattern recognition from data
  • Hypothesis formation
  • Documentation as markdown
  • Validation with real scenarios

Automate: Convert methodologies to automated checks

  • Detection: Identify when pattern applies
  • Validation: Check compliance
  • Enforcement: CI/CD gates
  • Suggestion: Automated fix recommendations

Evolve: Apply methodology to itself for continuous improvement

  • Use tools on development process
  • Discover meta-patterns
  • Optimize methodology

Detailed guide: reference/observe-codify-automate.md

Dual-Layer Value Functions

Every iteration calculates two scores:

V_instance(s): Domain-specific task quality

  • Example (testing): coverage × quality × stability × performance
  • Example (CI/CD): speed × reliability × automation × observability
  • Target: ≥0.80

V_meta(s): Methodology transferability quality

  • Components: completeness × effectiveness × reusability × validation
  • Completeness: Is methodology fully documented?
  • Effectiveness: What speedup does it provide?
  • Reusability: What % transferable across projects?
  • Validation: Is it empirically validated?
  • Target: ≥0.80

Detailed guide: reference/dual-value-functions.md

Convergence Criteria

Methodology complete when:

  1. ✅ System stable: Agent set unchanged for 2+ iterations
  2. ✅ Dual threshold: V_instance ≥ 0.80 AND V_meta ≥ 0.80
  3. ✅ Objectives complete: All planned work finished
  4. ✅ Diminishing returns: ΔV < 0.02 for 2+ iterations

Alternative patterns:

  • Meta-Focused Convergence: V_meta ≥ 0.80, V_instance ≥ 0.55 (when methodology is primary goal)
  • Practical Convergence: Combined quality exceeds metrics, justified partial criteria

Detailed guide: reference/convergence-criteria.md


Iteration Documentation Structure

Every BAIME iteration must produce a comprehensive iteration report following a standardized 10-section structure. This ensures consistent quality, complete knowledge capture, and reproducible methodology development.

Required Sections

See complete example: examples/iteration-documentation-example.md

Use blank template: examples/iteration-structure-template.md

  1. Executive Summary (2-3 paragraphs)

    • Iteration focus and objectives
    • Key achievements
    • Key learnings
    • Value scores (V_instance, V_meta)
  2. Pre-Execution Context

    • Previous state: M_{n-1}, A_{n-1}, s_{n-1}
    • Previous values: V_instance(s_{n-1}), V_meta(s_{n-1}) with component breakdowns
    • Primary objectives for this iteration
  3. Work Executed (organized by BAIME phases)

    • Phase 1: OBSERVE - Data collection, measurements, gap identification
    • Phase 2: CODIFY - Pattern extraction, documentation, knowledge creation
    • Phase 3: AUTOMATE - Tool creation, script development, enforcement
    • Phase 4: EVALUATE - Metric calculation, value assessment
  4. Value Calculations (detailed, evidence-based)

    • V_instance(s_n) with component breakdowns
      • Each component score with concrete evidence
      • Formula application with arithmetic
      • Final score calculation
      • Change from previous iteration (ΔV)
    • V_meta(s_n) with rubric assessments
      • Completeness score (checklist-based, with evidence)
      • Effectiveness score (speedup, quality gains, with evidence)
      • Reusability score (transferability estimate, with evidence)
      • Final score calculation
      • Change from previous iteration (ΔV)
  5. Gap Analysis

    • Instance layer gaps (what's needed to reach V_instance ≥ 0.80)
      • Prioritized list with estimated effort
    • Meta layer gaps (what's needed to reach V_meta ≥ 0.80)
      • Prioritized list with estimated effort
    • Estimated work remaining
  6. Convergence Check (systematic criteria evaluation)

    • Dual threshold: V_instance ≥ 0.80 AND V_meta ≥ 0.80
    • System stability: M_n == M_{n-1} AND A_n == A_{n-1}
    • Objectives completeness: All planned work finished
    • Diminishing returns: ΔV < 0.02 for 2+ iterations
    • Convergence decision: YES/NO with detailed rationale
  7. Evolution Decisions (evidence-driven)

    • Agent sufficiency analysis (A_n vs A_{n-1})
      • Each agent's performance assessment
      • Decision: evolution needed or not
      • Rationale with evidence
    • Meta-Agent sufficiency analysis (M_n vs M_{n-1})
      • Each capability's effectiveness assessment
      • Decision: evolution needed or not
      • Rationale with evidence
  8. Artifacts Created

    • Data files (coverage reports, metrics, measurements)
    • Knowledge files (patterns, principles, methodology documents)
    • Code changes (implementation, tests, tools)
    • Other deliverables
  9. Reflections

    • What worked well (successes to repeat)
    • What didn't work (failures to avoid)
    • Learnings (insights from this iteration)
    • Insights for methodology (meta-level learnings)
  10. Conclusion

    • Iteration summary
    • Key metrics and improvements
    • Critical decisions made
    • Next steps
    • Confidence assessment

File Naming Convention

iterations/iteration-N.md

Where N = 0, 1, 2, 3, ... (starting from 0 for baseline)

Documentation Quality Standards

Evidence-based scores:

  • Every value component score must have concrete evidence
  • Avoid vague assessments ("seems good" ❌, "72.3% coverage, +5% from baseline" ✅)
  • Show arithmetic for all calculations

Honest assessment:

  • Low scores early are expected and acceptable (baseline V_meta often 0.15-0.25)
  • Don't inflate scores to meet targets
  • Document gaps explicitly
  • Acknowledge when objectives are not met

Complete coverage:

  • All 10 sections must be present
  • Don't skip reflections (valuable for meta-learning)
  • Don't skip gap analysis (critical for planning)
  • Don't skip convergence check (prevents premature convergence)

Tools for Iteration Documentation

Recommended workflow:

  1. Copy examples/iteration-structure-template.md to iterations/iteration-N.md
  2. Invoke iteration-executor subagent to execute iteration with structured documentation
  3. Review examples/iteration-documentation-example.md for quality reference

Automated generation: Use iteration-executor subagent to ensure consistent structure and systematic value calculation.


Three-Layer Architecture

BAIME integrates three complementary methodologies into a unified framework:

Layer 1: Core Framework (OCA Cycle)

  • Observe → Codify → Automate → Evolve
  • Three-tuple output: (O, Aₙ, Mₙ)
  • Self-referential feedback loop
  • Agent coordination

Layer 2: Scientific Foundation (Empirical Methodology)

  • Empirical observation tools
  • Data-driven pattern extraction
  • Hypothesis testing
  • Scientific validation

Layer 3: Quantitative Evaluation (Value Optimization)

  • Dual-layer value functions (V_instance + V_meta)
  • Convergence mathematics
  • Agent as gradient, Meta-Agent as Hessian
  • Optimization perspective

Why "BAIME"? The framework bootstraps itself—methodologies developed using BAIME can be applied to improve BAIME itself. This self-referential property, combined with AI-agent coordination, makes it uniquely suited for LLM-based development tools.

Detailed guide: reference/three-layer-architecture.md


Proven Results

Validated in 8 experiments:

  • ✅ 100% success rate (8/8 converged)
  • ⏱️ Average: 4.9 iterations, 9.1 hours
  • 📈 V_instance average: 0.784 (range: 0.585-0.92)
  • 📈 V_meta average: 0.840 (range: 0.83-0.877)
  • 🌍 Transferability: 70-95%+
  • 🚀 Speedup: 3-46x vs ad-hoc

Example applications:

  • Testing strategy: 15x speedup, 75%→86% coverage (examples/testing-methodology.md)
  • CI/CD pipeline: 2.5-3.5x speedup, 91.7% pattern validation (examples/ci-cd-optimization.md)
  • Error recovery: 80% error reduction, 85% transferability
  • Observability: 23-46x speedup, 90-95% transferability
  • Dependency health: 6x speedup (9h→1.5h), 88% transferability
  • Knowledge transfer: 3-8x onboarding speedup, 95%+ transferability
  • Documentation: 47% token cost reduction, 85% transferability
  • Technical debt: SQALE quantification, 85% transferability

Usage Templates

Experiment Template

Use templates/experiment-template.md to structure your methodology development:

  • README.md structure
  • Iteration prompts
  • Knowledge extraction format
  • Results documentation

Iteration Prompt Template

Use templates/iteration-prompts-template.md to guide each iteration:

  • Iteration N objectives
  • OCA cycle execution steps
  • Value calculation rubrics
  • Convergence checks

Automated generation: Use iteration-prompt-designer subagent to create domain-specific iteration prompts.

Iteration Documentation Template

Structure template: examples/iteration-structure-template.md

  • 10-section standardized structure
  • Blank template ready to copy and fill
  • Includes all required components

Complete example: examples/iteration-documentation-example.md

  • Real iteration from test strategy experiment
  • Shows proper value calculations with evidence
  • Demonstrates honest assessment and gap analysis
  • Illustrates quality reflections and insights

Automated execution: Use iteration-executor subagent to ensure consistent structure and systematic value calculation.

Quality standards:

  • Evidence-based scoring (concrete data, not vague assessments)
  • Honest evaluation (low scores acceptable, inflation harmful)
  • Complete coverage (all 10 sections required)
  • Arithmetic shown (all value calculations with steps)

Common Pitfalls

❌ Don't:

  • Use only one methodology layer in isolation (except quick prototyping)
  • Predetermine agent evolution path (let specialization emerge from data)
  • Force convergence at target iteration count (trust the criteria)
  • Inflate value metrics to meet targets (honest assessment critical)
  • Skip empirical validation (data-driven decisions only)

✅ Do:

  • Start with OCA cycle, add evaluation and validation
  • Let agent specialization emerge from domain needs
  • Trust the convergence criteria (system knows when done)
  • Calculate V(s) honestly based on actual state
  • Complete all analysis thoroughly before codifying

Iteration Documentation Pitfalls

❌ Don't:

  • Skip iteration documentation (every iteration needs iteration-N.md)
  • Calculate V-scores without component breakdowns and evidence
  • Use vague assessments ("seems good", "probably 0.7")
  • Omit gap analysis or convergence checks
  • Document only successes (failures provide valuable learnings)
  • Assume convergence without systematic criteria evaluation
  • Inflate scores to meet targets (honesty is critical)
  • Skip reflections section (meta-learning opportunity)

✅ Do:

  • Use iteration-executor subagent for consistent structure
  • Provide concrete evidence for each value component
  • Show arithmetic for all calculations
  • Document both instance and meta layer gaps explicitly
  • Include reflections (what worked, didn't work, learnings, insights)
  • Be honest about scores (baseline V_meta of 0.20 is normal and acceptable)
  • Follow the 10-section structure for every iteration
  • Reference iteration documentation example for quality standards

Related Skills

Acceleration techniques (achieve 3-4 iteration convergence):

Supporting skills:

Domain applications (ready-to-use methodologies):


References

Core documentation:

Quick start:

Examples:

Templates:


Status: ✅ Production-ready | BAIME Framework | 8 experiments | 100% success rate | 95% transferable

Terminology: This skill implements the Bootstrapped AI Methodology Engineering (BAIME) framework. Use "BAIME" when referring to this methodology in documentation, research, or when asking Claude Code for assistance with methodology development.


Prompt Refinement Methodology

BAIME includes a systematic process for refining prompts used to drive LLM workflows. Effective prompts are a form of methodology asset — they encode hard-won knowledge about how to get consistent, high-quality results from AI agents.

Why Prompt Refinement Matters

Prompts are the primary interface between human intent and AI execution. Poorly specified prompts lead to:

  • Excessive clarification rounds (efficiency loss)
  • Inconsistent outputs across sessions (quality loss)
  • Repeated manual corrections (knowledge not captured)

Applying BAIME's OCA cycle to prompts transforms them from ad-hoc one-offs into validated, reusable assets.

The OCA Cycle Applied to Prompts

Observe: Collect evidence of prompt performance

  • Record which prompts required correction
  • Note which prompts produced excellent results on the first attempt
  • Identify patterns in the corrections (missing context, vague objectives, wrong scope)

Codify: Extract and formalize what makes prompts effective

  • Document the structural patterns from high-performing prompts
  • Identify the minimum context a prompt needs (file refs, scope, constraints)
  • Create a reusable template for each recurring task type

Automate: Operationalize the refined prompts

  • Save validated prompts to a prompt library (e.g., .meta-cc/prompts/library/)
  • Tag prompts with task category and effectiveness score
  • Reference saved prompts instead of re-writing from scratch

Prompt Quality Dimensions

When evaluating a prompt, assess these dimensions:

DimensionPoorGood
Context specificity"Fix the bug""Fix the type error in @src/parser.go:42"
Scope clarity"Update docs""Update @README.md Installation section only"
Constraint explicitness"Make it fast""Optimize without changing the public API"
File referencesFile content pasted inline@file:line-range references
Success criteriaAbsentExplicit and verifiable

Iterative Refinement Process

  1. Draft: Write the prompt as you naturally would
  2. Execute: Run it and observe the result
  3. Gap analysis: What did the result lack? What clarification did you need to add?
  4. Refine: Incorporate the gap into the prompt upfront
  5. Validate: Re-run the refined prompt (or apply it to a similar task) and confirm improvement
  6. Save: If the refined prompt is reusable, save it to the project prompt library

Integration with BAIME Value Functions

Apply the dual-layer value function to prompt methodology:

  • Instance quality V_I: Did this specific prompt produce a correct, complete result without correction?
  • Methodology quality V_M: Does the prompt template transfer to similar tasks with consistent results?

A prompt template with V_M ≥ 0.8 is a validated methodology asset worth preserving in the library.

Prompt Library Management

Maintain a local prompt library to capture institutional knowledge:

.meta-cc/prompts/library/
├── feature-implementation-001.md   # Template for new feature work
├── bug-fix-002.md                  # Template for bug investigation
├── test-writing-001.md             # Template for test authoring
└── code-review-003.md              # Template for review requests

Each saved prompt should include:

  • Original prompt: what you first wrote
  • Optimized prompt: the refined version after gap analysis
  • Keywords: for retrieval
  • Usage count: tracks which prompts are most valuable
  • Effectiveness score: tracks prompt quality over time

Spec

λ(context: ConversationContext) → NextStepRecommendation

Next-Step Generation

Infer what comes next from conversation context and generate immediately executable prompts.


When to Apply This Skill

Use this skill after any significant action completes:

  • A file was edited and tests have not yet run
  • Tests passed and changes have not been committed
  • A plan was written and Stage 1 has not started
  • An error occurred and a fix has not been applied
  • A stage completed and the next stage is ready

Step 1: Assess Completion State

Read the last 5–10 messages and classify the current state:

StateSignal
fully_completeTask finished with confirmation; natural handoff point
partially_completeTask started but not done; continuation obvious
blockedWaiting for user decision or missing information
error_stateLast action failed; fix is the immediate priority

Step 2: Infer the Primary Next Step

Apply the following inference rules in priority order:

error_occurred          → fix_the_error (include error message in prompt)
file_edited             → run_tests (name the test command if known)
tests_passed            → commit_changes (suggest commit message)
plan_written            → execute_stage_1
stage_N_complete        → execute_stage_N+1
implementation_done     → write_tests
tests_written           → run_tests
build_failed            → fix_build_error
docs_outdated           → update_docs
pr_ready                → create_pull_request

For the inferred primary step, craft a complete, copy-pasteable prompt that includes:

  • The specific action to take
  • Any @file references relevant to the context
  • The expected outcome
  • No unfilled placeholders

Step 3: Generate Alternatives

Suggest 2–3 ranked alternative next steps for situations where the primary path is not the only valid option. Rank by likelihood of user intent. Common alternative clusters:

  • tests_passing → [refactor, update_docs, optimize, create_pr]
  • planning_phase → [start_implementation, review_plan, gather_more_requirements]
  • implementation_done → [write_tests, update_docs, request_review]

Step 4: Format Output

Present results in this structure:

## Recommended Next Step

**[Action label]**
[Ready-to-use prompt — complete, no placeholders]

Rationale: [1-sentence justification from recent context]
Estimated time: [< 5 min | 15–30 min | 1+ hour]

---

## Alternatives

1. **[Alternative 1]** — [one-line prompt or action description]
2. **[Alternative 2]** — [one-line prompt or action description]
3. **[Alternative 3 — optional]** — [one-line prompt or action description]

Constraints

  • context_only: infer from conversation; do not call any external tools
  • ready_to_use: every prompt must be complete and copy-pasteable
  • concise: primary recommendation + at most 3 alternatives
  • non_executable: suggest ∧ ¬implement
  • evidence_based: every suggestion must be grounded in recent context
  • file_aware: include @file references when files are clearly relevant

Spec

λ(codebase: CodebaseContext) → InstrumentedCodebase

Observability Instrumentation

Implement three pillars of observability: logs, metrics, and traces.

You can't improve what you can't measure. You can't debug what you can't observe.


When to Use This Skill

Use this skill when:

  • 📊 No observability: Starting from scratch
  • 📝 Unstructured logs: Printf debugging, no context
  • 📈 No metrics: Can't measure performance or errors
  • 🐛 Hard to debug: Production issues take hours to diagnose
  • 🔍 Performance unknown: No visibility into bottlenecks
  • 🎯 SLO/SLA tracking: Need to measure reliability

Don't use when:

  • ❌ Observability already comprehensive
  • ❌ Non-production code (development scripts, throwaway tools)
  • ❌ Performance not critical (batch jobs, admin tools)
  • ❌ No logging infrastructure available

Quick Start (20 minutes)

Step 1: Add Structured Logging (10 min)

// Initialize slog
import "log/slog"

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))

// Use structured logging
logger.Info("operation completed",
    slog.String("user_id", userID),
    slog.Int("count", count),
    slog.Duration("duration", elapsed))

Step 2: Add Basic Metrics (5 min)

// Counters
requestCount.Add(1)
errorCount.Add(1)

// Gauges
activeConnections.Set(float64(count))

// Histograms
requestDuration.Observe(elapsed.Seconds())

Step 3: Add Request ID Propagation (5 min)

// Generate request ID
requestID := uuid.New().String()

// Add to context
ctx = context.WithValue(ctx, requestIDKey, requestID)

// Log with request ID
logger.InfoContext(ctx, "processing request",
    slog.String("request_id", requestID))

Three Pillars of Observability

1. Logs (Structured Logging)

Purpose: Record discrete events with context

Go slog patterns:

// Contextual logging
logger.InfoContext(ctx, "user authenticated",
    slog.String("user_id", userID),
    slog.String("method", authMethod),
    slog.Duration("elapsed", elapsed))

// Error logging with stack trace
logger.ErrorContext(ctx, "database query failed",
    slog.String("query", query),
    slog.Any("error", err))

// Debug logging (disabled in production)
logger.DebugContext(ctx, "cache hit",
    slog.String("key", cacheKey))

Log levels:

  • DEBUG: Detailed diagnostic information
  • INFO: General informational messages
  • WARN: Warning messages (potential issues)
  • ERROR: Error messages (failures)

Best practices:

  • Always use structured logging (not printf)
  • Include request ID in all logs
  • Log both successes and failures
  • Include timing information
  • Don't log sensitive data (passwords, tokens)

2. Metrics (Quantitative Measurements)

Purpose: Track aggregate statistics over time

Three metric types:

Counter (monotonically increasing):

httpRequestsTotal.Add(1)
httpErrorsTotal.Add(1)

Gauge (can go up or down):

activeConnections.Set(float64(connCount))
queueLength.Set(float64(len(queue)))

Histogram (distributions):

requestDuration.Observe(elapsed.Seconds())
responseSize.Observe(float64(size))

Prometheus exposition:

http.Handle("/metrics", promhttp.Handler())

3. Traces (Distributed Request Tracking)

Purpose: Track requests across services

Span creation:

ctx, span := tracer.Start(ctx, "database.query")
defer span.End()

// Add attributes
span.SetAttributes(
    attribute.String("db.query", query),
    attribute.Int("db.rows", rowCount))

// Record error
if err != nil {
    span.RecordError(err)
    span.SetStatus(codes.Error, err.Error())
}

Context propagation:

// Extract from HTTP headers
ctx = otel.GetTextMapPropagator().Extract(ctx, propagation.HeaderCarrier(req.Header))

// Inject into HTTP headers
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))

Go slog Best Practices

Handler Configuration

// Production: JSON handler
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
    AddSource: true, // Include file:line
}))

// Development: Text handler
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelDebug,
}))

Attribute Management

// Reusable attributes
attrs := []slog.Attr{
    slog.String("service", "api"),
    slog.String("version", version),
}

// Child logger with default attributes
apiLogger := logger.With(attrs...)

// Use child logger
apiLogger.Info("request received") // Includes service and version automatically

Performance Optimization

// Lazy evaluation (expensive operations)
logger.Info("operation completed",
    slog.Group("stats",
        slog.Int("count", count),
        slog.Any("details", func() interface{} {
            return computeExpensiveStats() // Only computed if logged
        })))

Implementation Patterns

Pattern 1: Request ID Propagation

type contextKey string
const requestIDKey contextKey = "request_id"

// Generate and store
requestID := uuid.New().String()
ctx = context.WithValue(ctx, requestIDKey, requestID)

// Extract and log
if reqID, ok := ctx.Value(requestIDKey).(string); ok {
    logger.InfoContext(ctx, "processing",
        slog.String("request_id", reqID))
}

Pattern 2: Operation Timing

func instrumentOperation(ctx context.Context, name string, fn func() error) error {
    start := time.Now()
    logger.InfoContext(ctx, "operation started", slog.String("operation", name))

    err := fn()
    elapsed := time.Since(start)

    if err != nil {
        logger.ErrorContext(ctx, "operation failed",
            slog.String("operation", name),
            slog.Duration("elapsed", elapsed),
            slog.Any("error", err))
        operationErrors.Add(1)
    } else {
        logger.InfoContext(ctx, "operation completed",
            slog.String("operation", name),
            slog.Duration("elapsed", elapsed))
    }

    operationDuration.Observe(elapsed.Seconds())
    return err
}

Pattern 3: Error Rate Monitoring

// Track error rates
totalRequests.Add(1)
if err != nil {
    errorRequests.Add(1)
}

// Calculate error rate (in monitoring system)
// error_rate = rate(errorRequests[5m]) / rate(totalRequests[5m])

Proven Results

Validated in bootstrap-009 (meta-cc project):

  • ✅ Structured logging with slog (100% coverage)
  • ✅ Metrics instrumentation (Prometheus-compatible)
  • ✅ Distributed tracing setup (OpenTelemetry)
  • ✅ 23-46x speedup vs ad-hoc logging
  • ✅ 7 iterations, ~21 hours
  • ✅ V_instance: 0.87, V_meta: 0.83

Speedup breakdown:

  • Debug time: 46x faster (context immediately available)
  • Performance analysis: 23x faster (metrics pre-collected)
  • Error diagnosis: 30x faster (structured logs + traces)

Transferability:

  • Go slog: 100% (Go-specific)
  • Structured logging patterns: 100% (universal)
  • Metrics patterns: 95% (Prometheus standard)
  • Tracing patterns: 95% (OpenTelemetry standard)
  • Overall: 90-95% transferable

Language adaptations:

  • Python: structlog, prometheus_client, opentelemetry-python
  • Java: SLF4J, Micrometer, OpenTelemetry Java
  • Node.js: winston, prom-client, @opentelemetry/api
  • Rust: tracing, prometheus, opentelemetry

Anti-Patterns

❌ Log spamming: Logging everything (noise overwhelms signal) ❌ Unstructured logs: String concatenation instead of structured fields ❌ Synchronous logging: Blocking on log writes (use async handlers) ❌ Missing context: Logs without request ID or user context ❌ Metrics explosion: Too many unique label combinations (cardinality issues) ❌ Trace everything: 100% sampling in production (performance impact)


Related Skills

Parent framework:

Complementary:


References

Core guides:

  • Reference materials in experiments/bootstrap-009-observability-methodology/
  • Three pillars methodology
  • Go slog patterns
  • Metrics instrumentation guide
  • Tracing setup guide

Templates:

  • templates/logger-setup.go - Logger initialization
  • templates/metrics-instrumentation.go - Metrics patterns
  • templates/tracing-setup.go - OpenTelemetry configuration

Status: ✅ Production-ready | 23-46x speedup | 90-95% transferable | Validated in meta-cc

Spec

λ(experiment: ExperimentContext) → ConvergenceResult

Rapid Convergence

Achieve methodology convergence in 3-4 iterations through structural optimization, not rushing.

Rapid convergence is not about moving fast - it's about recognizing when structural factors naturally enable faster progress without sacrificing quality.


When to Use This Skill

Use this skill when:

  • 🎯 Planning new experiment: Want to estimate iteration count and timeline
  • 📊 Clear baseline exists: Can quantify current state with V_meta(s₀) ≥ 0.40
  • 🔍 Focused domain: Can describe scope in <3 sentences without ambiguity
  • ✅ Direct validation: Can validate with historical data or single context
  • ⚡ Time constraints: Need methodology in 10-15 hours vs 20-30 hours
  • 🧩 Generic agents sufficient: No complex specialization needed

Don't use when:

  • ❌ Exploratory research (no established metrics)
  • ❌ Multi-context validation required (cross-language, cross-domain testing)
  • ❌ Complex specialization needed (>10x speedup from specialists)
  • ❌ Incremental pattern discovery (patterns emerge gradually, not upfront)

Quick Start (5 minutes)

Rapid Convergence Self-Assessment

Answer these 5 questions:

  1. Baseline metrics exist: Can you quantify current state objectively? (YES/NO)
  2. Domain is focused: Can you describe scope in <3 sentences? (YES/NO)
  3. Validation is direct: Can you validate without multi-context deployment? (YES/NO)
  4. Prior art exists: Are there established practices to reference? (YES/NO)
  5. Success criteria clear: Do you know what "done" looks like? (YES/NO)

Scoring:

  • 4-5 YES: ⚡ Rapid convergence (3-4 iterations) likely
  • 2-3 YES: 📊 Standard convergence (5-7 iterations) expected
  • 0-1 YES: 🔬 Exploratory (6-10 iterations), establish baseline first

Five Rapid Convergence Criteria

Criterion 1: Clear Baseline Metrics (CRITICAL)

Indicator: V_meta(s₀) ≥ 0.40

What it means:

  • Domain has established metrics (error rate, test coverage, build time)
  • Baseline can be measured objectively in iteration 0
  • Success criteria can be quantified before starting

Example (Bootstrap-003):

✅ Clear baseline:
- 1,336 errors quantified via MCP queries
- 5.78% error rate calculated
- Clear MTTD/MTTR targets
- Result: V_meta(s₀) = 0.48

Outcome: 3 iterations, 10 hours

Counter-example (Bootstrap-002):

❌ No baseline:
- No existing test coverage data
- Had to establish metrics first
- Fuzzy success criteria initially
- Result: V_meta(s₀) = 0.04

Outcome: 6 iterations, 25.5 hours

Impact: High V_meta baseline means:

  • Fewer iterations to reach 0.80 threshold (+0.40 vs +0.76)
  • Clearer iteration objectives (gaps are obvious)
  • Faster validation (metrics already exist)

See reference/baseline-metrics.md for achieving V_meta ≥ 0.40.

Criterion 2: Focused Domain Scope (IMPORTANT)

Indicator: Domain described in <3 sentences without ambiguity

What it means:

  • Single cross-cutting concern
  • Clear boundaries (what's in vs out of scope)
  • Well-established practices (prior art)

Examples:

✅ Focused (Bootstrap-003):
"Reduce error rate through detection, diagnosis, recovery, prevention"

❌ Broad (Bootstrap-002):
"Develop test strategy" (requires scoping: what tests? which patterns? how much coverage?)

Impact: Focused scope means:

  • Less exploration needed
  • Clearer convergence criteria
  • Lower risk of scope creep

Criterion 3: Direct Validation (IMPORTANT)

Indicator: Can validate without multi-context deployment

What it means:

  • Retrospective validation possible (use historical data)
  • Single-context validation sufficient
  • Proxy metrics strongly correlate with value

Examples:

✅ Direct (Bootstrap-003):
Retrospective validation via 1,336 historical errors
No deployment needed
Confidence: 0.79

❌ Indirect (Bootstrap-002):
Multi-context validation required (3 project archetypes)
Deploy and test in each context
Adds 2-3 iterations

Impact: Direct validation means:

  • Faster iteration cycles
  • Less complexity
  • Easier V_meta calculation

See ../retrospective-validation for retrospective validation technique.

Criterion 4: Generic Agent Sufficiency (MODERATE)

Indicator: Generic agents (data-analyst, doc-writer, coder) sufficient

What it means:

  • No specialized domain knowledge required
  • Tasks are analysis + documentation + simple automation
  • Pattern extraction is straightforward

Examples:

✅ Generic sufficient (Bootstrap-003):
Generic agents analyzed errors, documented taxonomy, created scripts
No specialization overhead
3 iterations

⚠️ Specialization needed (Bootstrap-002):
coverage-analyzer (10x speedup)
test-generator (200x speedup)
6 iterations (specialization added 1-2 iterations)

Impact: No specialization means:

  • No iteration delay for agent design
  • Simpler coordination
  • Faster execution

Criterion 5: Early High-Impact Automation (MODERATE)

Indicator: Top 3 automation opportunities identified by iteration 1

What it means:

  • Pareto principle applies (20% patterns → 80% impact)
  • High-frequency, high-impact patterns obvious
  • Automation feasibility clear (no R&D risk)

Examples:

✅ Early identification (Bootstrap-003):
3 tools preventing 23.7% of errors identified in iteration 0-1
Clear automation path
Rapid V_instance improvement

⚠️ Gradual discovery (Bootstrap-002):
8 test patterns emerged gradually over 6 iterations
Pattern library built incrementally

Impact: Early automation means:

  • Faster V_instance improvement
  • Clearer path to convergence
  • Less trial-and-error

Convergence Speed Prediction Model

Formula

Predicted Iterations = Base(4) + Σ penalties

Penalties:
- V_meta(s₀) < 0.40: +2 iterations
- Domain scope fuzzy: +1 iteration
- Multi-context validation: +2 iterations
- Specialization needed: +1 iteration
- Automation unclear: +1 iteration

Worked Examples

Bootstrap-003 (Error Recovery):

Base: 4
V_meta(s₀) = 0.48 ≥ 0.40: +0 ✓
Domain scope clear: +0 ✓
Retrospective validation: +0 ✓
Generic agents sufficient: +0 ✓
Automation identified early: +0 ✓
---
Predicted: 4 iterations
Actual: 3 iterations ✅

Bootstrap-002 (Test Strategy):

Base: 4
V_meta(s₀) = 0.04 < 0.40: +2 ✗
Domain scope broad: +1 ✗
Multi-context validation: +2 ✗
Specialization needed: +1 ✗
Automation unclear: +0 ✓
---
Predicted: 10 iterations
Actual: 6 iterations ✅ (model conservative)

Interpretation: Model predicts upper bound. Actual often faster due to efficient execution.

See examples/prediction-examples.md for more cases.


Rapid Convergence Strategy

If criteria indicate 3-4 iteration potential, optimize:

Pre-Iteration 0: Planning (1-2 hours)

1. Establish Baseline Metrics

  • Identify existing data sources
  • Define quantifiable success criteria
  • Ensure automatic measurement

Example: meta-cc query-tools --status error → 1,336 errors immediately

2. Scope Domain Tightly

  • Write 1-sentence definition
  • List explicit in/out boundaries
  • Identify prior art

Example: "Error detection, diagnosis, recovery, prevention for meta-cc"

3. Plan Validation Approach

  • Prefer retrospective (historical data)
  • Minimize multi-context overhead
  • Identify proxy metrics

Example: Retrospective validation with 1,336 historical errors

Iteration 0: Comprehensive Baseline (3-5 hours)

Target: V_meta(s₀) ≥ 0.40

Tasks:

  1. Quantify current state thoroughly
  2. Create initial taxonomy (≥70% coverage)
  3. Document existing practices
  4. Identify top 3 automations

Example (Bootstrap-003):

  • Analyzed all 1,336 errors
  • Created 10-category taxonomy (79.1% coverage)
  • Documented 5 workflows, 5 patterns, 8 guidelines
  • Identified 3 tools preventing 23.7% errors
  • Result: V_meta(s₀) = 0.48 ✅

Time: Spend 3-5 hours here (saves 6-10 hours overall)

Iteration 1: High-Impact Automation (3-4 hours)

Tasks:

  1. Implement top 3 tools
  2. Expand taxonomy (≥90% coverage)
  3. Validate with data (if possible)
  4. Target: ΔV_instance = +0.20-0.30

Example (Bootstrap-003):

  • Built 3 tools (515 LOC, ~150-180 lines each)
  • Expanded taxonomy: 10 → 12 categories (92.3%)
  • Result: V_instance = 0.55 (+0.27) ✅

Iteration 2: Validate and Converge (3-4 hours)

Tasks:

  1. Test automation (real/historical data)
  2. Complete taxonomy (≥95% coverage)
  3. Check convergence:
    • V_instance ≥ 0.80?
    • V_meta ≥ 0.80?
    • System stable?

Example (Bootstrap-003):

  • Validated 23.7% error prevention
  • Taxonomy: 95.4% coverage
  • Result: V_instance = 0.83, V_meta = 0.85 ✅ CONVERGED

Total time: 10-13 hours (3 iterations)


Anti-Patterns

1. Premature Convergence

Symptom: Declare convergence at iteration 2 with V ≈ 0.75

Problem: Rushed without meeting 0.80 threshold

Solution: Rapid convergence = 3-4 iterations (not 2). Respect quality threshold.

2. Scope Creep

Symptom: Adding categories/patterns in iterations 3-4

Problem: Poorly scoped domain

Solution: Tight scoping in README. If scope grows, re-plan or accept slower convergence.

3. Over-Engineering Automation

Symptom: Spending 8+ hours on complex tools

Problem: Complexity delays convergence

Solution: Keep tools simple (1-2 hours, 150-200 lines). Complex tools are iteration 3-4 work.

4. Unnecessary Multi-Context Validation

Symptom: Testing 3+ contexts despite obvious generalizability

Problem: Validation overhead delays convergence

Solution: Use judgment. Error recovery is universal. Test strategy may need multi-context.


Comparison Table

AspectStandardRapid
Iterations5-73-4
Duration20-30h10-15h
V_meta(s₀)0.00-0.300.40-0.60
DomainBroad/exploratoryFocused
ValidationMulti-context oftenDirect/retrospective
SpecializationLikely (1-3 agents)Often unnecessary
DiscoveryIncrementalMost patterns early
RiskScope creepPremature convergence

Key: Rapid convergence is about recognizing structural factors, not rushing.


Success Criteria

Rapid convergence pattern successfully applied when:

  1. Accurate prediction: Actual iterations within ±1 of predicted
  2. Quality maintained: V_instance ≥ 0.80, V_meta ≥ 0.80
  3. Time efficiency: Duration ≤50% of standard convergence
  4. Artifact completeness: Deliverables production-ready
  5. Reusability validated: ≥80% transferability achieved

Bootstrap-003 Validation:

  • ✅ Predicted: 3-4, Actual: 3
  • ✅ Quality: V_instance=0.83, V_meta=0.85
  • ✅ Efficiency: 10h (39% of Bootstrap-002's 25.5h)
  • ✅ Artifacts: 13 categories, 8 workflows, 3 tools
  • ✅ Reusability: 85-90%

Related Skills

Parent framework:

Complementary acceleration:

Supporting:


References

Core guide:

Examples:


Status: ✅ Validated | Bootstrap-003 | 40-60% time reduction | No quality sacrifice

Spec

λ(use_case, complexity) → subagent_prompt | ∧ require(need_orchestration(use_case) ∨ need_mcp_integration(use_case)) ∧ complexity ∈ {simple, moderate, complex} ∧ line_target = {simple: 30-60, moderate: 60-120, complex: 120-150} ∧ template = read(templates/subagent-template.md) ∧ patterns = read(reference/patterns.md) ∧ integration = read(reference/integration-patterns.md) ∧ apply(template, use_case, patterns, integration) → draft ∧ validate(|draft| ≤ 150 ∧ integration_score ≥ 0.50 ∧ clarity ≥ 0.80) ∧ examples/{phase-planner-executor.md} demonstrates orchestration ∧ reference/case-studies/* provides detailed analysis ∧ scripts/ provide validation and metrics automation ∧ output = {prompt: draft, metrics: validation_report}

Artifacts:

  • templates/: Reusable subagent template (lambda contract structure)
  • examples/: Compact validated examples (≤150 lines each)
  • reference/patterns.md: Core patterns (orchestration, analysis, enhancement)
  • reference/integration-patterns.md: Claude Code feature integration (agents, MCP, skills)
  • reference/symbolic-language.md: Formal syntax reference (logic operators, quantifiers)
  • reference/case-studies/: Detailed analysis and design rationale
  • scripts/: Automation tools (validation, metrics, pattern extraction)

Usage: See templates/subagent-template.md for structure. Apply integration patterns for Claude Code features. Validate compactness (≤150 lines), integration (≥1 feature), clarity. Reference examples/ for compact demonstrations and case-studies/ for detailed analysis.

Constraints: Max 150 lines per prompt | Use symbolic logic for compactness | Explicit dependencies section | Integration score ≥0.50 | Test coverage ≥80% for generated artifacts

Validation: V_instance=0.895 (phase-planner-executor: 92 lines, 2 agents, 2 MCP tools) | V_meta=0.709 (compactness=0.65, integration=0.857, maintainability=0.85) | Transferability=95%

λ(topic) → taskToBacklog(topic)

Spec

DocConfig :: { docPath : String -- root directory for plan docs and task outputs }

loadConfig :: () → DocConfig -- see spec-stdlib § loadConfig loadConfig() = | fromClaudeMd() -- explicit: "## L0 Config" section in CLAUDE.md | autoDetect() -- implicit: use "docs" if it exists, otherwise "."

autoDetect :: () → DocConfig autoDetect() = -- see spec-stdlib § loadConfig

-- Non-development task types this skill handles (non-exhaustive) TaskType = Analysis | Documentation | Research | Experiment | Survey | Setup

-- Plan structure — no TDD constraint; DoD is any shell-verifiable command Phase :: { title : String, instructions : String, -- what to do; specific tools, files, commands dod : [ShellCmd] -- any shell command; exit 0 = pass -- common patterns: -- test -f (file exists) -- test -s (file non-empty) -- grep -q '' (content check) -- && exit 0 (tool succeeded) }

Plan :: { phases : [Phase], -- ordered; earlier phases produce inputs for later ones constraints : [String], -- non-executable criteria (NOT in dod) acceptance : [ShellCmd] -- final gate; at least one item required }

-- Input: topic is either a task ID (e.g. TASK-12, task-12) or a free-form description. -- Task ID → resolve existing task; use its description as the plan draft (skip re-draft). -- Description → create a new task, then draft a plan from scratch.

resolveOrCreate :: Topic → (Task, SkipDraft) resolveOrCreate(T) = | isTaskId(T) → (lookupTask(T), True) -- reuse existing description as plan draft | otherwise → (createTask(T), False) -- draft from scratch

-- Workflow: single draft + single review loop (softer than feature-to-backlog) taskToBacklog :: Topic → BacklogTask taskToBacklog(T) = { cfg: loadConfig(), (task, skipDraft): resolveOrCreate(T), plan: if skipDraft then reviewLoop(task, task.description, 4) -- existing description IS the plan draft else reviewLoop(task, draftPlan(task, T), 4) _: finalise(task, plan, cfg), _: appendNote(task, "cap:propose=approved"), -- B″ idempotency marker return: task -- status: Basic: Backlog }

-- see spec-stdlib § reviewLoop (MaxRounds = 4)

-- Review invariants (all must hold for APPROVED) reviewPlan :: Plan → Verdict reviewPlan(P) = { assert: ¬empty(P.phases), ∀phase ∈ P.phases: { assert: ¬empty(phase.instructions), -- phase must say what to do assert: ¬empty(phase.dod), -- phase must be verifiable assert: ∀cmd ∈ phase.dod: isShellCmd(cmd) -- no natural-language DoD }, assert: ¬empty(P.acceptance), assert: ∀cmd ∈ P.acceptance: isShellCmd(cmd), return: APPROVED | NEEDS_REVISION }

Implementation

loadConfig

REPO_ROOT=$(git rev-parse --show-toplevel)

resolveBaimeScripts() {
  local proj_scripts="${REPO_ROOT}/.claude/plugins/baime/scripts"
  if [ -d "$proj_scripts" ]; then echo "$proj_scripts"; return 0; fi
  for settings_file in "${HOME}/.claude/settings.json" "${HOME}/.claude/settings.local.json"; do
    if [ -f "$settings_file" ]; then
      local baime_path
      baime_path=$(python3 -c "
import json, sys
try:
  d = json.load(open('$settings_file'))
  for mp in d.get('extraKnownMarketplaces', []):
    p = mp.get('path', '')
    if 'baime' in p:
      import os
      scripts = os.path.join(p, 'scripts')
      if os.path.isdir(scripts):
        print(scripts)
        sys.exit(0)
except Exception:
  pass
" 2>/dev/null || true)
      if [ -n "$baime_path" ]; then echo "$baime_path"; return 0; fi
    fi
  done
  local xdg_scripts="${XDG_DATA_HOME:-${HOME}/.local/share}/baime/scripts"
  if [ -d "$xdg_scripts" ]; then echo "$xdg_scripts"; return 0; fi
  echo "resolveBaimeScripts: ERROR — cannot locate BAIME plugin scripts directory." >&2
  return 1
}
BAIME_SCRIPTS=$(resolveBaimeScripts) || exit 1

L0_SECTION=$(awk '/^## L0 Config/{found=1; next} found && /^## /{exit} found{print}' \
  "${REPO_ROOT}/CLAUDE.md" 2>/dev/null)

parse_cfg() { echo "$L0_SECTION" | grep -oP "(?<=^$1:\s)\S.*" | head -1 | xargs; }

CFG_DOC_PATH=$(parse_cfg "doc-path")

if [ -z "$L0_SECTION" ]; then
  if [ -d "${REPO_ROOT}/docs" ]; then
    CFG_DOC_PATH="${CFG_DOC_PATH:-docs}"
  else
    CFG_DOC_PATH="${CFG_DOC_PATH:-.}"
  fi
  echo "L0 auto-detected config: docPath=${CFG_DOC_PATH}"
else
  CFG_DOC_PATH="${CFG_DOC_PATH:-docs}"
  echo "L0 config loaded from CLAUDE.md: docPath=${CFG_DOC_PATH}"
fi

Derive slug and title:

SLUG=$(echo "<topic>" | tr '[:upper:] ' '[:lower:]-' | tr -cd '[:alnum:]-' | cut -c1-50)
TITLE=$(echo "<topic>" | cut -c1-70)

If <topic> is empty: print usage and stop.


Phase 0: Manifest Generation and Lint

Before executing any phase, generate a manifest JSON that describes the planned execution:

{
  "skill": "task-to-backlog",
  "task_id": "<TASK-ID or null>",
  "entry_point": "<resolveOrCreate|createTask>",
  "skip_draft": "<true if entry_point==\"resolveOrCreate\">",
  "field_writes": [
    { "tool": "backlog task edit", "field": "plan", "source": "$TMPDIR/ttb-plan.md" },
    { "tool": "backlog task edit", "field": "status", "value": "Basic: Backlog" }
  ],
  "phases_to_execute": ["<entry_point>", "reviewLoop", "finalise"]
}

Write the manifest to $TMPDIR/task-to-backlog-manifest.json, then validate it:

bash "$BAIME_SCRIPTS/skill-lint.sh" --manifest "$TMPDIR/task-to-backlog-manifest.json"

If validation fails, stop and report the error before proceeding.


Phase 1: resolveOrCreate

Detect whether <topic> is an existing task ID or a new description:

if echo "<topic>" | grep -qiP '^task-\d+$'; then
  # Existing task path — resolve and extract description as initial plan draft
  TASK_ID=$(echo "<topic>" | tr '[:lower:]' '[:upper:]')
  backlog task view "$TASK_ID" --plain > $TMPDIR/ttb-existing-task.txt
  echo "$TASK_ID" > $TMPDIR/ttb-task-id.txt
  # Extract description block into ttb-plan.md (between the two separator lines)
  awk '/^Description:/{found=1;next} found && /^-{10,}/{if(!sep){sep=1;next};exit} found && sep{print}' \
    $TMPDIR/ttb-existing-task.txt > $TMPDIR/ttb-plan.md
  echo "skip" > $TMPDIR/ttb-draft-mode.txt
else
  # New topic path — create task
  backlog task create "$TITLE" \
    --status "Basic: Plan" \
    --label "kind:basic" \
    --description "<topic>" \
    --plain
  # Extract task ID from output line `Task TASK-N`. Write to $TMPDIR/ttb-task-id.txt.
  echo "draft" > $TMPDIR/ttb-draft-mode.txt
fi

Phase 2: draftPlan

If $TMPDIR/ttb-draft-mode.txt contains skip: $TMPDIR/ttb-plan.md already holds the task's existing description — skip this phase and proceed directly to Phase 3.

Spawn Task agent:

Draft an execution plan for a non-development task and update the backlog task.

Task ID: <TASK_ID> Doc root: <CFG_DOC_PATH>

  1. Read the task topic: <topic>

  2. Search the codebase or project structure as needed to understand context.

  3. Write $TMPDIR/ttb-plan.md:

    # Plan: <title>
    
    ## Context
    (1-4 lines: why this task, what problem it addresses)
    
    ## Phase 1: <title>
    <Specific instructions: which tools to run, which files to read/write,
    what commands to execute. Be concrete — avoid "analyse" without saying how.>
    ### DoD
    - [ ] `<shell command>`   ← exit 0 = done; use test -f, grep -q, tool exit code
    - [ ] `<shell command>`
    
    ## Phase 2: <title>
    ...
    ### DoD
    - [ ] `<shell command>`
    
    ## Constraints
    (What NOT to do; scope limits; non-executable criteria only)
    
    ## Acceptance Gate
    - [ ] `<final verification command>`
    

    DoD rules (STRICT):

    • Every ### DoD and ## Acceptance Gate item MUST be a shell command (exit 0 = pass; never natural language)
    • Prefer precise checks: grep -q '<section-header>' <file> over test -f <file>
    • Absence check: ! grep -q <pattern> <file> (NOT grep -qv)
    • Natural-language criteria → ## Constraints only
    • Phases ordered so earlier outputs are available to later phases
    • Minimum 1 phase, maximum 6 phases

    Common DoD patterns for non-dev tasks:

    • Output file created: test -f <CFG_DOC_PATH>/tasks/<slug>-output.md
    • Output non-empty: test -s <CFG_DOC_PATH>/tasks/<slug>-output.md
    • Report has section: grep -q '## Recommendations' <path>
    • Tool exited cleanly: <tool command with flags>
    • At least N lines: [ $(wc -l < <path>) -ge N ]
  4. Update task:

    backlog task edit <TASK_ID> \
      --plan "$(cat $TMPDIR/ttb-plan.md)" \
      --status "Basic: Plan"
    

Phase 3: reviewLoop(plan)

Soft limit: 4 iterations. On exhaustion:

backlog task edit $TASK_ID --status "Basic: Needs Human" \
  --append-notes "Plan review did not converge after 4 iterations. Manual review required."

Print current $TMPDIR/ttb-plan.md and stop.

Each iteration — spawn Task agent:

You are reviewing an execution plan for a non-development task.

Task ID: <TASK_ID> — Iteration: <N>

  1. Read $TMPDIR/ttb-plan.md

  2. Check each item:

    • Clarity: Does each Phase have specific, actionable instructions? Flag vague instructions like "analyse X" without saying how.
    • DoD executability: Every ### DoD and ## Acceptance Gate item is a shell command (exit 0 = pass). Flag natural-language items and move them to ## Constraints.
    • DoD precision: Prefer grep -q '<section>' over bare test -f. A file existing is weaker than a file containing the expected content.
    • Absence checks: ! grep -q used, not grep -qv.
    • Phase ordering: Outputs of earlier phases are available to later phases.
    • Scope: No phase does something outside the task's stated purpose.

3a. ALL pass:

backlog task edit <TASK_ID> \
  --append-notes "Plan review iteration <N>: APPROVED"
echo "APPROVED" > $TMPDIR/ttb-plan-verdict.txt

3b. ANY fail: fix $TMPDIR/ttb-plan.md, update task plan:

backlog task edit <TASK_ID> --plan "$(cat $TMPDIR/ttb-plan.md)"

Write NEEDS_REVISION to verdict file.

After each agent run, read $TMPDIR/ttb-plan-verdict.txt:

  • APPROVED → proceed to Phase 4
  • NEEDS_REVISION → increment counter, repeat Phase 3

Phase 4: finalise

Spawn Task agent (pass CFG_DOC_PATH, TASK_ID, SLUG as literal values):

Finalise the backlog task: write plan into task and add DoD items.

Task ID: <TASK_ID> — Slug: <SLUG> — Doc root: <CFG_DOC_PATH>

Step B — Write plan into task and add DoD:

grep -oP '(?<=- \[ \] `)[^`]+(?=`)' $TMPDIR/ttb-plan.md \
  > $TMPDIR/ttb-dod-cmds.txt

DOD_ARGS=()
while IFS= read -r cmd; do
  DOD_ARGS+=("--dod" "$cmd")
done < $TMPDIR/ttb-dod-cmds.txt

backlog task edit <TASK_ID> \
  --plan "$(cat $TMPDIR/ttb-plan.md)" \
  --status "Basic: Backlog" \
  "${DOD_ARGS[@]}"

Step D — Run Layer 0-2 validation gate:

bash "$BAIME_SCRIPTS/validate-plugin.sh"

If validation fails, fix any SKILL.md contracts or internals before proceeding.

Add the validation DoD item to the task:

backlog task edit <TASK_ID> --dod "bash "$BAIME_SCRIPTS/validate-plugin.sh""

Step E — Print completion:

✅ Task <TASK_ID> is now in Backlog.

计划草拟 + 审查已完成。

请在 web UI 确认 Definition of Done 命令:
  backlog browser --no-open --port 6421

确认无误后,将任务移入执行队列:
  backlog task edit <TASK_ID> --status "Basic: Ready"

等待 loop-backlog 自动拾取,或立即启动:
  /loop-backlog

Constraints

  • This skill outputs a plan doc and a backlog task only — it does not execute the task
  • No branch creation, no worktree operations, no git push, no PR creation
  • One task per topic; the same TASK_ID moves through all columns
  • Phase count: minimum 1, maximum 6
  • Must run from the project root of a git repository
  • Plan text lives in the task's Implementation Plan field; no docs/ files are written

Spec

λ(codebase: CodebaseContext) → DebtPaydownPlan

Technical Debt Management

Transform subjective debt assessment into objective, data-driven paydown strategy with 4.5x speedup.

Measure what matters. Prioritize by value. Pay down strategically. Prevent proactively.


When to Use This Skill

Use this skill when:

  • 📊 Unmeasured debt: Technical debt unknown or subjectively assessed
  • 🎯 Need prioritization: Many debt items, unclear which to tackle first
  • 📈 Planning refactoring: Need objective justification and ROI analysis
  • 🚨 Debt accumulation: Debt growing but no tracking system
  • 🔄 Prevention lacking: Reactive debt management, no proactive practices
  • 📋 Objective reporting: Stakeholders need quantified debt metrics

Don't use when:

  • ❌ Debt already well-quantified with SQALE or similar methodology
  • ❌ Codebase very small (<1K LOC, minimal debt accumulation)
  • ❌ No refactoring capacity (debt measurement without action is wasteful)
  • ❌ Tools unavailable (need complexity, coverage, duplication analysis tools)

Quick Start (30 minutes)

Step 1: Calculate SQALE Index (15 min)

SQALE Formula:

Development Cost = LOC / 30  (30 LOC/hour productivity)
Technical Debt = Remediation Cost (hours)
TD Ratio = Technical Debt / Development Cost × 100%

SQALE Ratings:

  • A (Excellent): ≤5% TD ratio
  • B (Good): 6-10%
  • C (Moderate): 11-20%
  • D (Poor): 21-50%
  • E (Critical): >50%

Example (meta-cc):

LOC: 12,759
Development Cost: 425.3 hours
Technical Debt: 66.0 hours
TD Ratio: 15.52% (Rating: C - Moderate)

Step 2: Categorize Debt (10 min)

SQALE Code Smell Taxonomy:

  1. Bloaters: Long methods, large classes (complexity debt)
  2. Change Preventers: Shotgun surgery, divergent change (flexibility debt)
  3. Reliability Issues: Test coverage gaps, error handling (quality debt)
  4. Couplers: Feature envy, inappropriate intimacy (coupling debt)
  5. Dispensables: Duplicate code, dead code (maintainability debt)

Example Breakdown:

  • Complexity: 54.5 hours (82.6%)
  • Coverage: 10.0 hours (15.2%)
  • Duplication: 1.0 hours (1.5%)

Step 3: Prioritize with Value-Effort Matrix (5 min)

Four Quadrants:

High Value, Low Effort  → Quick Wins (do first)
High Value, High Effort → Strategic (plan carefully)
Low Value, Low Effort   → Opportunistic (do when convenient)
Low Value, High Effort  → Avoid (skip unless critical)

Quick Wins Example:

  • Fix error capitalization (0.5 hours)
  • Increase test coverage for small module (2.0 hours)

Six Methodology Components

1. Measurement Framework (SQALE)

Objective: Quantify technical debt objectively using industry-standard SQALE methodology

Three Calculations:

A. Development Cost:

Development Cost = LOC / Productivity
Productivity = 30 LOC/hour (SQALE standard)

B. Remediation Cost (Complexity Example):

Graduated Thresholds:
- Low complexity (≤10): 0 hours
- Medium complexity (11-15): 0.5 hours per function
- High complexity (16-25): 1.0 hours per function
- Very high (26-50): 2.0 hours per function
- Extreme (>50): 4.0 hours per function

C. Technical Debt Ratio:

TD Ratio = (Total Remediation Cost / Development Cost) × 100%
SQALE Rating = Map TD Ratio to A-E scale

Tools:

  • Go: gocyclo, gocov, golangci-lint
  • Python: radon, pylint, pytest-cov
  • JavaScript: eslint, jscpd, nyc
  • Java: PMD, JaCoCo, CheckStyle
  • Rust: cargo-geiger, clippy

Output: SQALE Index Report (total debt, TD ratio, rating, breakdown by category)

Transferability: 100% (SQALE formulas language-agnostic)


2. Categorization Framework (Code Smells)

Objective: Map metrics to SQALE code smell taxonomy for prioritization

Five SQALE Categories:

1. Bloaters (Complexity Debt):

  • Long methods (cyclomatic complexity >10)
  • Large classes (>500 LOC)
  • Long parameter lists (>5 parameters)
  • Remediation: Extract method, split class, introduce parameter object

2. Change Preventers (Flexibility Debt):

  • Shotgun surgery (change requires touching multiple files)
  • Divergent change (class changes for multiple reasons)
  • Remediation: Consolidate logic, introduce abstraction layer

3. Reliability Issues (Quality Debt):

  • Test coverage gaps (<80% target)
  • Missing error handling
  • Remediation: Add tests, implement error handling

4. Couplers (Coupling Debt):

  • Feature envy (method uses data from another class more than own)
  • Inappropriate intimacy (high coupling between modules)
  • Remediation: Move method, reduce coupling

5. Dispensables (Maintainability Debt):

  • Duplicate code (>3% duplication ratio)
  • Dead code (unreachable functions)
  • Remediation: Extract common code, remove dead code

Output: Code Smell Report (smell type, instances, files, remediation cost)

Transferability: 80-90% (OO smells apply to OO languages only, others universal)


3. Prioritization Framework (Value-Effort Matrix)

Objective: Rank debt items by ROI (business value / remediation effort)

Business Value Assessment (3 factors):

  1. User Impact: Does debt affect user experience? (0-10)
  2. Change Frequency: How often is this code changed? (0-10)
  3. Error Risk: Does debt cause bugs? (0-10)
  4. Total Value: Sum of 3 factors (0-30)

Effort Estimation:

  • Use SQALE remediation cost model
  • Factor in testing, code review, deployment time

Value-Effort Quadrants:

         High Value
         |
 Quick   |   Strategic
  Wins   |
---------|------------- Effort
Opportun-|   Avoid
  istic  |
         |
       Low Value

Priority Ranking:

  1. Quick Wins (high value, low effort)
  2. Strategic (high value, high effort) - plan carefully
  3. Opportunistic (low value, low effort) - when convenient
  4. Avoid (low value, high effort) - skip unless critical

Output: Prioritization Matrix (debt items ranked by quadrant)

Transferability: 95% (value-effort concept universal, specific values vary)


4. Paydown Framework (Phased Roadmap)

Objective: Create actionable, phased plan for debt reduction

Four Phases:

Phase 1: Quick Wins (0-2 hours)

  • Highest ROI items
  • Build momentum, demonstrate value
  • Example: Fix lint issues, error capitalization

Phase 2: Coverage Gaps (2-12 hours)

  • Test coverage improvements
  • Prevent regressions, enable refactoring confidence
  • Example: Add integration tests, increase coverage to ≥80%

Phase 3: Strategic Complexity (12-30 hours)

  • High-value, high-effort refactoring
  • Address architectural debt
  • Example: Consolidate duplicated logic, refactor high-complexity functions

Phase 4: Opportunistic (as time allows)

  • Low-priority items tackled when working nearby
  • Example: Refactor during feature development in same area

Expected Improvements (calculate per phase):

Phase TD Reduction = Sum of remediation costs in phase
New TD Ratio = (Total Debt - Phase TD Reduction) / Development Cost × 100%
New SQALE Rating = Map new TD ratio to A-E scale

Output: Paydown Roadmap (4 phases, time estimates, expected TD ratio improvements)

Transferability: 100% (phased approach universal)


5. Tracking Framework (Trend Analysis)

Objective: Continuous debt monitoring with early warning alerts

Five Tracking Components:

1. Automated Data Collection:

  • Weekly metrics collection (complexity, coverage, duplication)
  • CI/CD integration (collect on every build)

2. Baseline Storage:

  • Quarterly SQALE snapshots
  • Historical comparison (track delta)

3. Trend Tracking:

  • Time series: TD ratio, complexity, coverage, hotspots
  • Identify trends (increasing, decreasing, stable)

4. Visualization Dashboard:

  • TD ratio over time
  • Debt by category (stacked area chart)
  • Coverage trends
  • Complexity heatmap
  • Hotspot analysis (files with most debt)

5. Alerting Rules:

  • TD ratio increase >5% in 1 month
  • Coverage drop >5%
  • New high-complexity functions (>25 complexity)
  • Duplication spike >3%

Expected Impact:

  • Visibility: Point-in-time → continuous trends
  • Decision making: Reactive → data-driven proactive
  • Early warning: Alert before debt spikes

Output: Tracking System Design (automation plan, dashboard mockups, alert rules)

Transferability: 95% (tracking concept universal, tools vary)


6. Prevention Framework (Proactive Practices)

Objective: Prevent new debt accumulation through gates and practices

Six Prevention Strategies:

1. Pre-Commit Complexity Gates:

# Reject commits with functions >15 complexity
gocyclo -over 15 .

2. Test Coverage Requirements:

  • Overall: ≥80%
  • New code: ≥90%
  • CI/CD gate: Fail build if coverage drops

3. Static Analysis Enforcement:

  • Zero tolerance for critical issues
  • Warning threshold (fail if >10 warnings)

4. Code Review Checklist (6 debt prevention items):

  • No functions >15 complexity
  • Test coverage ≥90% for new code
  • No duplicate code (DRY principle)
  • Error handling complete
  • No dead code
  • Architecture consistency maintained

5. Refactoring Time Budget:

  • Allocate 20% sprint capacity for refactoring
  • Opportunistic paydown during feature work

6. Architecture Review:

  • Quarterly health checks
  • Identify architectural debt early
  • Plan strategic refactoring

Expected Impact:

  • TD accumulation: 2%/quarter → <0.5%/quarter
  • ROI: 4 days saved per quarter (prevention time << paydown time)

Output: Prevention Guidelines (pre-commit hooks, CI/CD gates, code review checklist)

Transferability: 85% (specific thresholds vary, practices universal)


Three Extracted Patterns

Pattern 1: SQALE-Based Debt Quantification

Problem: Subjective debt assessment leads to inconsistent prioritization

Solution: Use SQALE methodology for objective, reproducible measurement

Structure:

  1. Calculate development cost (LOC / 30)
  2. Calculate remediation cost (graduated thresholds)
  3. Calculate TD ratio (remediation / development × 100%)
  4. Assign SQALE rating (A-E)

Benefits:

  • Objective (same methodology, same results)
  • Reproducible (industry standard)
  • Comparable (across projects, over time)

Transferability: 90% (formulas universal, threshold calibration language-specific)


Pattern 2: Code Smell Taxonomy Mapping

Problem: Metrics (complexity, duplication) don't directly translate to actionable insights

Solution: Map metrics to SQALE code smell taxonomy for clear remediation strategies

Structure:

Metric → Code Smell → Remediation Strategy
Complexity >10 → Long Method (Bloater) → Extract Method
Duplication >3% → Duplicate Code (Dispensable) → Extract Common Code
Coverage <80% → Test Gap (Reliability Issue) → Add Tests

Benefits:

  • Actionable (smell → remediation)
  • Prioritizable (smell severity)
  • Educational (developers learn smell patterns)

Transferability: 80% (OO smells require adaptation for non-OO languages)


Pattern 3: Value-Effort Prioritization Matrix

Problem: Too many debt items, unclear which to tackle first

Solution: Rank by ROI using value-effort matrix

Structure:

  1. Assess business value (user impact + change frequency + error risk)
  2. Estimate remediation effort (SQALE model)
  3. Plot on matrix (4 quadrants)
  4. Prioritize: Quick Wins → Strategic → Opportunistic → Avoid

Benefits:

  • ROI-driven (maximize value per hour)
  • Transparent (stakeholders understand prioritization)
  • Flexible (adjust value weights per project)

Transferability: 95% (concept universal, specific values vary)


Three Principles

Principle 1: Pay High-Value Low-Effort Debt First

Statement: "Maximize ROI by prioritizing high-value low-effort debt (quick wins) before tackling strategic debt"

Rationale:

  • Build momentum (early wins)
  • Demonstrate value (stakeholder buy-in)
  • Free up capacity (small wins compound)

Evidence: Quick wins phase (0.5-2 hours) enables larger strategic work

Application: Always start paydown roadmap with quick wins


Principle 2: SQALE Provides Objective Baseline

Statement: "Use SQALE methodology for objective, reproducible debt measurement to enable data-driven decisions"

Rationale:

  • Subjective assessment varies by developer
  • Objective measurement enables comparison (projects, time periods)
  • Industry standard (validated across thousands of projects)

Evidence: 4.5x speedup vs manual approach, objective vs subjective

Application: Calculate SQALE index before any debt work


Principle 3: Complexity Drives Maintainability Debt

Statement: "Complexity debt dominates technical debt (often 70-90%), focus refactoring on high-complexity functions"

Rationale:

  • High complexity → hard to understand → slow changes → bugs
  • Complexity compounds (high complexity attracts more complexity)
  • Refactoring complexity has highest impact

Evidence: 82.6% of meta-cc debt from complexity (54.5/66 hours)

Application: Prioritize complexity reduction in paydown roadmaps


Proven Results

Validated in bootstrap-012 (meta-cc project):

  • ✅ SQALE Index: 66 hours debt, 15.52% TD ratio, rating C (Moderate)
  • ✅ Methodology: 6/6 components complete (measurement, categorization, prioritization, paydown, tracking, prevention)
  • ✅ Convergence: V_instance = 0.805, V_meta = 0.855 (both >0.80)
  • ✅ Duration: 4 iterations, ~7 hours
  • ✅ Paydown roadmap: 31.5 hours → rating B (8.23%, -47.7% debt reduction)

Effectiveness Validation:

  • Manual approach: 9 hours (ad-hoc review, subjective prioritization)
  • Methodology approach: 2 hours (tool-based, SQALE calculation)
  • Speedup: 4.5x ✅
  • Accuracy: Subjective → Objective (SQALE standard)
  • Reproducibility: Low → High

Transferability Validation (5 languages analyzed):

  • Go: 90% transferable (native)
  • Python: 85% (tools: radon, pylint, pytest-cov)
  • JavaScript: 85% (tools: eslint, jscpd, nyc)
  • Java: 90% (tools: PMD, JaCoCo, CheckStyle)
  • Rust: 80% (tools: cargo-geiger, clippy, skip OO smells)
  • Overall: 85% transferable ✅

Universal Components (13/16, 81%):

  • SQALE formulas (100%)
  • Prioritization matrix (100%)
  • Paydown roadmap (100%)
  • Code smell taxonomy (90%, OO smells excluded)
  • Tracking approach (95%)
  • Prevention practices (85%)

Common Anti-Patterns

❌ Measurement without action: Calculating debt but not creating paydown plan ❌ Strategic-only focus: Skipping quick wins, tackling only big refactoring (low momentum) ❌ No prevention: Paying down debt without gates (debt re-accumulates) ❌ Subjective prioritization: "This code is bad" without quantified impact ❌ Tool-free assessment: Manual review instead of automated metrics (4.5x slower) ❌ No tracking: Point-in-time snapshot instead of continuous monitoring (reactive)


Templates and Examples

Templates

Examples


Related Skills

Parent framework:

Complementary domains:


References

Core methodology:

Quick guides:


Status: ✅ Production-ready | Validated in meta-cc | 4.5x speedup | 85% transferable

Spec

λ(project: ProjectContext) → TestStrategy

Testing Strategy

Transform ad-hoc testing into systematic, coverage-driven strategy with 15x speedup.

Coverage is a means, quality is the goal. Systematic testing beats heroic testing.


When to Use This Skill

Use this skill when:

  • 🎯 Starting new project: Need systematic testing from day 1
  • 📊 Coverage below 75%: Want to reach 80%+ systematically
  • 🔧 Test infrastructure: Building fixtures, mocks, test helpers
  • 🖥️ CLI applications: Need CLI-specific testing patterns
  • 🔄 Refactoring legacy: Adding tests to existing code
  • 📈 Quality gates: Implementing CI/CD coverage enforcement

Don't use when:

  • ❌ Coverage already >90% with good quality
  • ❌ Non-Go projects without adaptation (89% transferable, needs language-specific adjustments)
  • ❌ No CI/CD infrastructure (automation tools require CI integration)
  • ❌ Time budget <10 hours (methodology requires investment)

Quick Start (30 minutes)

Step 1: Measure Baseline (10 min)

# Run tests with coverage
go test -coverprofile=coverage.out ./...
go tool cover -func=coverage.out

# Identify gaps
# - Total coverage %
# - Packages below 75%
# - Critical paths uncovered

Step 2: Apply Coverage-Driven Gap Closure (15 min)

Priority algorithm:

  1. Critical paths first: Core business logic, error handling
  2. Low-hanging fruit: Pure functions, simple validators
  3. Complex integrations: File I/O, external APIs, CLI commands

Step 3: Use Test Pattern (5 min)

// Table-driven test pattern
func TestFunction(t *testing.T) {
    tests := []struct {
        name    string
        input   InputType
        want    OutputType
        wantErr bool
    }{
        {"happy path", validInput, expectedOutput, false},
        {"error case", invalidInput, zeroValue, true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Function(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("error = %v, wantErr %v", err, tt.wantErr)
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("got %v, want %v", got, tt.want)
            }
        })
    }
}

Eight Test Patterns

1. Table-Driven Tests (Universal)

Use for: Multiple input/output combinations Transferability: 100% (works in all languages)

Benefits:

  • Comprehensive coverage with minimal code
  • Easy to add new test cases
  • Clear separation of data vs logic

See reference/patterns.md#table-driven for detailed examples.

2. Golden File Testing (Complex Outputs)

Use for: Large outputs (JSON, HTML, formatted text) Transferability: 95% (concept universal, tools vary)

Pattern:

golden := filepath.Join("testdata", "golden", "output.json")
if *update {
    os.WriteFile(golden, got, 0644)
}
want, _ := os.ReadFile(golden)
assert.Equal(t, want, got)

3. Fixture Patterns (Integration Tests)

Use for: Complex setup (DB, files, configurations) Transferability: 90%

Pattern:

func LoadFixture(t *testing.T, name string) *Model {
    data, _ := os.ReadFile(fmt.Sprintf("testdata/fixtures/%s.json", name))
    var model Model
    json.Unmarshal(data, &model)
    return &model
}

4. Mocking External Dependencies

Use for: APIs, databases, file systems Transferability: 85% (Go-specific interfaces, patterns universal)

See reference/patterns.md#mocking for detailed strategies.

5. CLI Testing

Use for: Command-line applications Transferability: 80% (subprocess testing varies by language)

Strategies:

  • Capture stdout/stderr
  • Mock os.Exit
  • Test flag parsing
  • End-to-end subprocess testing

See templates/cli-test-template.go.

6. Integration Test Patterns

Use for: Multi-component interactions Transferability: 90%

7. Test Helper Utilities

Use for: Reduce boilerplate, improve readability Transferability: 95%

8. Coverage-Driven Gap Closure

Use for: Systematic improvement from 60% to 80%+ Transferability: 100% (methodology universal)

Algorithm:

WHILE coverage < threshold:
  1. Run coverage analysis
  2. Identify file with lowest coverage
  3. Analyze uncovered lines
  4. Prioritize: critical > easy > complex
  5. Write tests
  6. Re-measure

Three Automation Tools

1. Coverage Gap Analyzer (186x speedup)

What it does: Analyzes go tool cover output, identifies gaps by priority

Speedup: 15 min manual → 5 sec automated (186x)

Usage:

./scripts/analyze-coverage.sh coverage.out
# Output: Priority-ranked list of files needing tests

See reference/automation-tools.md#coverage-analyzer.

2. Test Generator (200x speedup)

What it does: Generates table-driven test boilerplate from function signatures

Speedup: 10 min manual → 3 sec automated (200x)

Usage:

./scripts/generate-test.sh pkg/parser/parse.go ParseTools
# Output: Complete table-driven test scaffold

3. Methodology Guide Generator (7.5x speedup)

What it does: Creates project-specific testing guide from patterns

Speedup: 6 hours manual → 48 min automated (7.5x)


Proven Results

Validated in bootstrap-002 (meta-cc project):

  • ✅ Coverage: 72.1% → 72.5% (maintained above target)
  • ✅ Test count: 590 → 612 tests (+22)
  • ✅ Test reliability: 100% pass rate
  • ✅ Duration: 6 iterations, 25.5 hours
  • ✅ V_instance: 0.80 (converged iteration 3)
  • ✅ V_meta: 0.80 (converged iteration 5)

Multi-context validation (3 project archetypes):

  • ✅ Context A (CLI tool): 2.8x speedup, 5% adaptation
  • ✅ Context B (Library): 3.5x speedup, 3% adaptation
  • ✅ Context C (Web service): 3.0x speedup, 9% adaptation
  • ✅ Average: 3.1x speedup, 5.8% adaptation effort

Cross-language transferability:

  • Go: 100% (native)
  • Python: 90% (pytest patterns similar)
  • Rust: 85% (cargo test compatible)
  • TypeScript: 85% (Jest patterns similar)
  • Java: 82% (JUnit compatible)
  • Overall: 89% transferable

Quality Criteria

Coverage Thresholds

  • Minimum: 75% (gate enforcement)
  • Target: 80%+ (comprehensive)
  • Excellence: 90%+ (critical packages only)

Quality Metrics

  • Zero flaky tests (deterministic)
  • Test execution <2min (unit + integration)
  • Clear failure messages (actionable)
  • Independent tests (no ordering dependencies)

Pattern Adoption

  • ✅ Table-driven: 80%+ of test functions
  • ✅ Fixtures: All integration tests
  • ✅ Mocks: All external dependencies
  • ✅ Golden files: Complex output verification

Common Anti-Patterns

❌ Coverage theater: 95% coverage but testing getters/setters ❌ Integration-heavy: Slow test suite (>5min) due to too many integration tests ❌ Flaky tests: Ignored failures undermine trust ❌ Coupled tests: Dependencies on execution order ❌ Missing assertions: Tests that don't verify behavior ❌ Over-mocking: Mocking internal functions (test implementation, not interface)


Templates and Examples

Templates

Examples


Related Skills

Parent framework:

Complementary domains:

Acceleration:


References

Core methodology:

Quick guides:


Status: ✅ Production-ready | Validated in meta-cc + 3 contexts | 3.1x speedup | 89% transferable

Agents 4

λ(experiment, iteration_n) → (M_n, A_n, s_n, V(s_n), convergence) | ∀i ∈ iterations:

pre_execution :: Experiment → Context pre_execution(E) = read(iteration_{n-1}.md) ∧ extract(M_{n-1}, A_{n-1}, V(s_{n-1})) ∧ identify(problems, gaps)

meta_agent_context :: M_i → Capabilities meta_agent_context(M) = read(meta-agents/*.md) ∧ load(lifecycle_capabilities) ∧ verify(complete)

lifecycle_execution :: (M, Context, A) → (Output, M', A') lifecycle_execution(M, ctx, A) = sequential_phases( data_collection: read(capability) → gather_domain_data ∧ identify_patterns, strategy_formation: read(capability) → analyze_problems ∧ prioritize_objectives ∧ assess_agents, work_execution: read(capability) → evaluate_sufficiency(A) → decide_evolution → coordinate_agents → produce_outputs, -- hard_verdict: when oracle available, invoke run-quantitative-experiment skill -- to produce CONFIRMED/NULL/REJECTED instead of soft V_instance. evaluation: read(capability) → calculate_dual_values ∧ identify_gaps ∧ assess_quality, convergence_check: evaluate_system_state ∧ determine_continuation ) where read_before_each_phase ∧ ¬cache_instructions

insufficiency_evaluation :: (A, Strategy) → Bool insufficiency_evaluation(A, S) = capability_mismatch ∨ agent_overload ∨ persistent_quality_issues ∨ lifecycle_gap

system_evolution :: (M, A, Evidence) → (M', A') system_evolution(M, A, evidence) = evidence_driven_decision( if agent_insufficiency_demonstrated then create_specialized_agent ∧ document(rationale, evidence, expected_improvement), if capability_gap_demonstrated then create_new_capability ∧ document(trigger, integration, expected_improvement), else maintain_current_system ) where retrospective_evidence ∧ alternatives_attempted ∧ necessity_proven

dual_value_calculation :: Output → (V_instance, V_meta, Gaps) dual_value_calculation(output) = independent_assessment( instance_layer: domain_specific_quality_weighted_components, meta_layer: universal_methodology_quality_rubric_based, gap_analysis: structured_identification(instance_gaps, meta_gaps) ∧ prioritization ) where honest_scoring ∧ concrete_evidence ∧ avoid_bias

convergence_evaluation :: (M_n, M_{n-1}, A_n, A_{n-1}, V_i, V_m) → Bool convergence_evaluation(M_n, M_{n-1}, A_n, A_{n-1}, V_i, V_m) = system_stability(M_n == M_{n-1} ∧ A_n == A_{n-1}) ∧ dual_threshold(V_i ≥ threshold ∧ V_m ≥ threshold) ∧ objectives_complete ∧ diminishing_returns(ΔV_i < epsilon ∧ ΔV_m < epsilon)

-- Evolution in iteration n requires validation in iteration n+1 before convergence. -- Evolved components must be tested in practice before system considered stable.

state_transition :: (s_{n-1}, Work) → s_n state_transition(s, work) = apply(changes) ∧ calculate(dual_metrics) ∧ document(∆s)

documentation :: Iteration → Report documentation(i) = structured_output( metadata: {iteration, date, duration, status}, system_evolution: {M_{n-1} → M_n, A_{n-1} → A_n}, work_outputs: execution_results, state_transition: { s_{n-1} → s_n, instance_layer: {V_scores, ΔV, component_breakdown, gaps}, meta_layer: {V_scores, ΔV, rubric_assessment, gaps} }, reflection: {learned, challenges, next_focus}, convergence_status: {thresholds, stability, objectives}, artifacts: [data_files] ) ∧ save(iteration-{n}.md)

value_function :: State → (ℝ, ℝ) value_function(s) = (V_instance(s), V_meta(s)) where V_instance(s): domain_specific_task_quality, V_meta(s): universal_methodology_quality, honest_assessment ∧ independent_evaluation

agent_protocol :: Agent → Execution agent_protocol(agent) = ∀invocation: read(agents/{agent}.md) ∧ load(definition) ∧ execute(task) ∧ ¬cache

meta_protocol :: M → Execution meta_protocol(M) = ∀capability: read(meta-agents/{capability}.md) ∧ load(guidance) ∧ apply ∧ ¬assume

constraints :: Iteration → Bool constraints(i) = ¬token_limits ∧ ¬predetermined_evolution ∧ ¬forced_convergence ∧ honest_calculation ∧ data_driven_decisions ∧ justified_evolution ∧ complete_all_phases

iteration_cycle :: (M_{n-1}, A_{n-1}, s_{n-1}) → (M_n, A_n, s_n) iteration_cycle(M, A, s) = ctx = pre_execution(experiment) → meta_agent_context(M) → (output, M_n, A_n) = lifecycle_execution(M, ctx, A) → s_n = state_transition(s, output) → converged = convergence_evaluation(M_n, M, A_n, A, V(s_n)) → documentation(iteration_n) → if converged then results_analysis else continue(iteration_{n+1})

output :: Execution → Artifacts output(exec) = iteration_report(iteration-{n}.md) ∧ data_artifacts(data/) ∧ system_definitions(agents/.md, meta-agents/*.md | if_evolved) ∧ dual_metrics(instance_layer, meta_layer)

termination :: Convergence → Analysis termination(conv) = conv.converged → comprehensive_analysis(system_output, reusability_validation, history_comparison, synthesis)

λ(experiment_spec, domain) → ITERATION-PROMPTS.md | structured_for_iteration-executor:

domain_analysis :: Experiment → Domain domain_analysis(E) = extract(domain_name, core_concepts, data_sources, value_dimensions) ∧ validate(specificity)

architecture_design :: Domain → ArchitectureSpec architecture_design(D) = specify( meta_agent_system: modular_capabilities(lifecycle_phases), agent_system: specialized_executors(domain_tasks), modular_principle: separate_files_per_component ) where capabilities_cover_full_lifecycle ∧ agents_address_domain_needs

value_function_design :: Domain → (ValueSpec_Instance, ValueSpec_Meta) value_function_design(D) = ( instance_layer: domain_specific_quality_measure(weighted_components), meta_layer: universal_methodology_quality(rubric_based_assessment) ) where dual_evaluation ∧ independent_scoring ∧ both_required_for_convergence

baseline_iteration_spec :: Domain → Iteration0 baseline_iteration_spec(D) = structure( context: experiment_initialization, system_setup: create_modular_architecture(capabilities, agents), objectives: sequential_steps( setup_files, collect_baseline_data, establish_baseline_values, identify_initial_problems, document_initial_state ), baseline_principle: low_baseline_expected_and_acceptable, constraints: honest_assessment ∧ data_driven ∧ no_predetermined_evolution )

subsequent_iteration_spec :: Domain → IterationN subsequent_iteration_spec(D) = structure( context_extraction: read_previous_iteration(system_state, value_scores, identified_problems), lifecycle_protocol: capability_reading_protocol(all_before_start, specific_before_use), iteration_cycle: lifecycle_phases(data_collection, strategy_formation, execution, evaluation, convergence_check), evolution_guidance: evidence_based_system_evolution( triggers: retrospective_evidence ∧ gap_analysis ∧ attempted_alternatives, anti_triggers: pattern_matching ∨ anticipatory_design ∨ theoretical_completeness, validation: necessity_demonstrated ∧ improvement_quantifiable ), key_principles: honest_calculation ∧ dual_layer_focus ∧ justified_evolution ∧ rigorous_convergence )

knowledge_organization_spec :: Domain → KnowledgeSpec knowledge_organization_spec(D) = structure( directories: categorized_storage( patterns: domain_specific_patterns_extracted, principles: universal_principles_discovered, templates: reusable_templates_created, best_practices: context_specific_practices_documented, methodology: project_wide_reusable_knowledge ), index: knowledge_map( cross_references: link_related_knowledge, iteration_links: track_extraction_source, domain_tags: categorize_by_domain, validation_status: track_pattern_validation ), dual_output: local_knowledge(experiment_specific) ∧ project_methodology(reusable_across_projects), organization_principle: separate_ephemeral_data_from_permanent_knowledge )

results_analysis_spec :: Domain → ResultsTemplate results_analysis_spec(D) = structure( context: convergence_achieved, analysis_dimensions: comprehensive_coverage( system_output, convergence_validation, trajectory_analysis, domain_results, reusability_tests, methodology_validation, learnings, knowledge_catalog ), visualizations: trajectory_and_evolution_tracking )

execution_guidance :: Domain → ExecutionGuide execution_guidance(D) = prescribe( perspective: embody_meta_agent_for_domain, rigor: honest_dual_layer_calculation, thoroughness: no_token_limits_complete_analysis, authenticity: discover_not_assume,

evaluation_protocol: independent_dual_layer_assessment( instance: measure_task_quality_against_objectives, meta: assess_methodology_using_rubrics, convergence: both_layers_meet_threshold ),

honest_assessment: systematic_bias_avoidance( seek_disconfirming_evidence, enumerate_gaps_explicitly, ground_scores_in_concrete_evidence, challenge_high_scores, avoid_anti_patterns ) )

template_composition :: (BaselineSpec, SubsequentSpec, KnowledgeSpec, ResultsSpec, ExecutionGuide) → Document template_composition(B, S, K, R, G) = compose( baseline_section, iteration_template, knowledge_organization_section, results_template, execution_guidance ) ∧ specialize_for_domain ∧ validate_completeness

output :: (Experiment, Domain) → ITERATION-PROMPTS.md output(E, D) = analyze_domain(D) → design_architecture(D) → design_value_functions(D) → specify_baseline(D) → specify_iterations(D) → specify_knowledge_organization(D) → specify_results(D) → create_execution_guide(D) → compose_and_validate → save("experiments/{E}/ITERATION-PROMPTS.md")

best_practices :: () → Guidelines best_practices() = ( architecture: modular_separate_files, specialization: domain_specific_terminology, baseline: explicit_low_expectation, evolution: evidence_driven_not_planned, evaluation: dual_layer_independent_honest, convergence: both_thresholds_plus_stability, authenticity: discover_patterns_data_driven )

λ(experiment_dir, skill_name, options?) → (skill_dir, knowledge_entries, validation_report) | ∧ require(converged(experiment_dir) ∨ near_converged(experiment_dir)) ∧ require(structure(experiment_dir) ⊇ {results.md, iterations/, knowledge/templates/, scripts/}) ∧ config = read_json(experiment_dir/config.json)? ∨ infer_config(experiment_dir/results.md) ∧ meta_obj = parse_meta_objective(experiment_dir/results.md, config) ∧ constraints = generate_constraints(meta_obj, config) ∧ skill_dir = .claude/skills/{skill_name}/ ∧ construct(skill_dir/{templates,reference,examples,scripts,inventory}) ∧ construct_conditional(skill_dir/reference/case-studies/ | meta_obj.compactness.weight ≥ 0.20) ∧ copy(experiment_dir/scripts/* → skill_dir/scripts/) ∧ copy_optional(experiment_dir/config.json → skill_dir/experiment-config.json) ∧ SKILL.md = {frontmatter, λ-contract, implementation?} ∧ |lines(spec_section(SKILL.md))| ≤ 40 -- Spec 节(frontmatter + λ-contract)≤ 40 行 ∧ implementation_section(SKILL.md) = retained -- ## Implementation 保留执行规格型内容(见注释) ∧ forbid(SKILL.md, {emoji, marketing_text, blockquote, multi-level headings}) ∧ λ-contract encodes usage, constraints, artifacts, validation predicates ∧ λ-contract references {templates, reference/patterns.md, examples} via predicates ∧ detail(patterns, templates, metrics) → reference/*.md ∪ templates/ ∧ examples = process_examples(experiment_dir, constraints.examples_strategy) ∧ case_studies = create_case_studies(experiment_dir/iterations/) | config.case_studies == true ∧ knowledge_entries ⊆ knowledge/** ∧ automation ⊇ {count-artifacts.sh, extract-patterns.py, generate-frontmatter.py, validate-skill.sh} ∧ run(automation) → inventory/{inventory.json, patterns-summary.json, skill-frontmatter.json, validation_report.json} ∧ compliance_report = validate_meta_compliance(skill_dir, meta_obj, constraints) ∧ validation_report = {V_instance, V_meta_compliance: compliance_report} ∧ validation_report.V_instance ≥ 0.85 ∧ validation_report.V_meta_compliance.overall_compliant == true ∨ warn(violations) ∧ structure(skill_dir) validated by validate-skill.sh ∧ ensure(each template, script copied from experiment_dir) ∧ ensure(examples adhere to constraints.examples_max_lines | is_link(example)) ∧ line_limit(reference/patterns.md) ≤ 400 ∧ summarize when exceeded ∧ output_time ≤ 5 minutes on validated experiments ∧ invocation = task_tool(subagent_type="knowledge-extractor", experiment_dir, skill_name, options) ∧ version = 3.0 ∧ updated = 2025-10-29 ∧ status = validated

Meta Objective Parsing

parse_meta_objective :: (ResultsFile, Config?) → MetaObjective parse_meta_objective(results.md, config) = if config.meta_objective exists then return config.meta_objective else section = extract_section(results.md, "V_meta Component Breakdown") → components = ∀row ∈ section.table: { name: lowercase(row.component), weight: parse_float(row.weight), score: parse_float(row.score), target: infer_target(row.notes, row.status), priority: if weight ≥ 0.20 then "high" elif weight ≥ 0.15 then "medium" else "low" } → formula = extract_formula(section) → MetaObjective(components, formula)

infer_target :: (Notes, Status) → Target infer_target(notes, status) = if notes contains "≤" then extract_number_constraint(notes) elif notes contains "≥" then extract_number_constraint(notes) elif notes contains "lines" then {type: "compactness", value: extract_number(notes), unit: "lines"} elif notes contains "domain" then {type: "generality", value: extract_number(notes), unit: "domains"} elif notes contains "feature" then {type: "integration", value: extract_number(notes), unit: "features"} else {type: "qualitative", description: notes}

Dynamic Constraints Generation

generate_constraints :: (MetaObjective, Config?) → Constraints generate_constraints(meta_obj, config) = constraints = {} →

Use config extraction rules if available

if config.extraction_rules exists then constraints.examples_strategy = config.extraction_rules.examples_strategy constraints.case_studies_enabled = config.extraction_rules.case_studies else # Infer from meta objective constraints.examples_strategy = infer_strategy(meta_obj) constraints.case_studies_enabled = meta_obj.compactness.weight ≥ 0.20

Compactness constraints

NOTE: SKILL_spec_max_lines 仅约束 ## Spec 节(frontmatter + λ-contract)。

## Implementation 节不受行数约束——执行规格型内容(当前步骤判断准则)须保留在

SKILL.md 中以保障 LLM 决策准确率(Exp-A +16pp, Exp-D +20pp, 2026-06-19)。

无关背景内容(历史数据、案例描述)仍应推到 reference/*.md。

if "compactness" ∈ meta_obj.components ∧ meta_obj.compactness.weight ≥ 0.15 then target = meta_obj.compactness.target → constraints.examples_max_lines = parse_number(target.value) → constraints.SKILL_spec_max_lines = min(40, target.value / 3) → -- 仅约束 Spec 节 constraints.enforce_compactness = meta_obj.compactness.weight ≥ 0.20

Integration constraints

if "integration" ∈ meta_obj.components ∧ meta_obj.integration.weight ≥ 0.15 then target = meta_obj.integration.target → constraints.min_features = parse_number(target.value) → constraints.require_integration_examples = true → constraints.feature_types = infer_feature_types(target)

Generality constraints

if "generality" ∈ meta_obj.components ∧ meta_obj.generality.weight ≥ 0.15 then constraints.min_examples = parse_number(meta_obj.generality.target.value) constraints.diverse_domains = true

Maintainability constraints

if "maintainability" ∈ meta_obj.components ∧ meta_obj.maintainability.weight ≥ 0.15 then constraints.require_cross_references = true constraints.clear_structure = true

return constraints

infer_strategy :: MetaObjective → Strategy infer_strategy(meta_obj) = if meta_obj.compactness.weight ≥ 0.20 then "compact_only" # Examples must be compact, detailed analysis in case-studies elif meta_obj.compactness.weight ≥ 0.10 then "hybrid" # Mix of compact and detailed examples else "detailed" # Examples can be detailed

Example Processing

process_examples :: (ExperimentDir, Strategy) → Examples process_examples(exp_dir, strategy) = validated_artifacts = find_validated_artifacts(exp_dir) →

if strategy == "compact_only" then ∀artifact ∈ validated_artifacts: if |artifact| ≤ constraints.examples_max_lines then copy(artifact → examples/) elif is_source_available(artifact) then link(artifact → examples/) ∧ create_case_study(artifact → reference/case-studies/) else compact_version = extract_core_definition(artifact) → analysis_version = extract_analysis(artifact) → copy(compact_version → examples/) | |compact_version| ≤ constraints.examples_max_lines ∧ copy(analysis_version → reference/case-studies/)

elif strategy == "hybrid" then # Mix: compact examples + some detailed ones ∀artifact ∈ validated_artifacts: if |artifact| ≤ constraints.examples_max_lines then copy(artifact → examples/) else copy(artifact → examples/) ∧ # Keep detailed add_note(artifact, "See case-studies for analysis")

else # "detailed" ∀artifact ∈ validated_artifacts: copy(artifact → examples/)

create_case_study :: Artifact → CaseStudy create_case_study(artifact) = if artifact from iterations/ then # Extract analysis sections from iteration reports analysis = { overview: extract_section(artifact, "Overview"), metrics: extract_section(artifact, "Metrics"), analysis: extract_section(artifact, "Analysis"), learnings: extract_section(artifact, "Learnings"), validation: extract_section(artifact, "Validation") } → save(analysis → reference/case-studies/{artifact.name}-analysis.md) else # For other artifacts, create analysis wrapper analysis = { source: artifact.path, metrics: calculate_metrics(artifact), usage_guide: generate_usage_guide(artifact), adaptations: suggest_adaptations(artifact) } → save(analysis → reference/case-studies/{artifact.name}-walkthrough.md)

Meta Compliance Validation

validate_meta_compliance :: (SkillDir, MetaObjective, Constraints) → ComplianceReport validate_meta_compliance(skill_dir, meta_obj, constraints) = report = {components: {}, overall_compliant: true} →

Validate each high-priority component

∀component ∈ meta_obj.components where component.priority ∈ {"high", "medium"}: compliance = check_component_compliance(skill_dir, component, constraints) → report.components[component.name] = compliance → if ¬compliance.compliant then report.overall_compliant = false

return report

check_component_compliance :: (SkillDir, Component, Constraints) → ComponentCompliance check_component_compliance(skill_dir, component, constraints) = if component.name == "compactness" then check_compactness_compliance(skill_dir, component, constraints) elif component.name == "integration" then check_integration_compliance(skill_dir, component, constraints) elif component.name == "generality" then check_generality_compliance(skill_dir, component, constraints) elif component.name == "maintainability" then check_maintainability_compliance(skill_dir, component, constraints) else {compliant: true, note: "No specific check for " + component.name}

check_compactness_compliance :: (SkillDir, Component, Constraints) → Compliance check_compactness_compliance(skill_dir, component, constraints) = target = component.target.value → actual = {} →

Check SKILL.md

actual["SKILL.md"] = count_lines(skill_dir/SKILL.md) →

Check examples

∀example ∈ glob(skill_dir/examples/*.md): if ¬is_link(example) then actual[example.name] = count_lines(example)

Check reference (allowed to be detailed)

actual["reference/"] = count_lines(skill_dir/reference/) →

violations = [] → ∀file, lines ∈ actual: if file.startswith("examples/") ∧ lines > target then violations.append({file: file, lines: lines, target: target})

return { compliant: |violations| == 0, target: target, actual: actual, violations: violations, notes: if |violations| > 0 then "Examples exceed compactness target. Consider moving to case-studies/" else "All files within compactness target" }

check_integration_compliance :: (SkillDir, Component, Constraints) → Compliance check_integration_compliance(skill_dir, component, constraints) = target = component.target.value →

Count features demonstrated in examples

feature_count = 0 → feature_types = {agents: 0, mcp_tools: 0, skills: 0} →

∀example ∈ glob(skill_dir/examples/*.md): content = read(example) → if "agent(" ∈ content then feature_types.agents++ → if "mcp::" ∈ content then feature_types.mcp_tools++ → if "skill(" ∈ content then feature_types.skills++

feature_count = count(∀v ∈ feature_types.values where v > 0) →

return { compliant: feature_count ≥ target, target: target, actual: feature_count, feature_types: feature_types, notes: if feature_count ≥ target then "Integration examples demonstrate " + feature_count + " feature types" else "Need " + (target - feature_count) + " more feature types in examples" }

check_generality_compliance :: (SkillDir, Component, Constraints) → Compliance check_generality_compliance(skill_dir, component, constraints) = target = component.target.value → example_count = count(glob(skill_dir/examples/*.md)) →

return { compliant: example_count ≥ target, target: target, actual: example_count, notes: if example_count ≥ target then "Sufficient examples for generality" else "Consider adding " + (target - example_count) + " more examples" }

check_maintainability_compliance :: (SkillDir, Component, Constraints) → Compliance check_maintainability_compliance(skill_dir, component, constraints) =

Check structure clarity

has_readme = exists(skill_dir/README.md) → has_templates = |glob(skill_dir/templates/.md)| > 0 → has_reference = |glob(skill_dir/reference/.md)| > 0 →

Check cross-references

cross_refs_count = 0 → ∀file ∈ glob(skill_dir/**/.md): content = read(file) → cross_refs_count += count_matches(content, r'[.](.*.md)')

structure_score = (has_readme + has_templates + has_reference) / 3 → cross_ref_score = min(1.0, cross_refs_count / 10) → # At least 10 cross-refs overall_score = (structure_score + cross_ref_score) / 2 →

return { compliant: overall_score ≥ 0.70, target: "Clear structure with cross-references", actual: { structure_score: structure_score, cross_ref_score: cross_ref_score, overall_score: overall_score }, notes: "Maintainability score: " + overall_score }

Config Schema

config_schema :: Schema config_schema = { experiment: { name: string, domain: string, status: enum["converged", "near_convergence"], v_meta: float, v_instance: float }, meta_objective: { components: [{ name: string, weight: float, priority: enum["high", "medium", "low"], targets: object, enforcement: enum["strict", "validate", "best_effort"] }] }, extraction_rules: { examples_strategy: enum["compact_only", "hybrid", "detailed"], case_studies: boolean, automation_priority: enum["high", "medium", "low"] } }

Output Structure

output :: Execution → Artifacts output(exec) = skill_dir/{ SKILL.md | |spec_section(SKILL.md)| ≤ constraints.SKILL_spec_max_lines, README.md, templates/.md, examples/.md | ∀e: |e| ≤ constraints.examples_max_lines ∨ is_link(e), reference/{ patterns.md | |patterns.md| ≤ 400, integration-patterns.md?, symbolic-language.md?, case-studies/*.md | config.case_studies == true }, scripts/{ count-artifacts.sh, extract-patterns.py, generate-frontmatter.py, validate-skill.sh }, inventory/{ inventory.json, patterns-summary.json, skill-frontmatter.json, validation_report.json, compliance_report.json # New: meta compliance }, experiment-config.json? | copied from experiment } ∧ validation_report = { V_instance: float ≥ 0.85, V_meta_compliance: { components: { compactness?: ComponentCompliance, integration?: ComponentCompliance, generality?: ComponentCompliance, maintainability?: ComponentCompliance }, overall_compliant: boolean, summary: string }, timestamp: datetime, skill_name: string, experiment_dir: path }

Implementation Content Policy

-- 修订于 2026-06-19(依据 Exp-A/D 实验结果) -- 原约束"|lines(SKILL.md)| ≤ 40"已废除,原因:所有运行良好的 operator skill -- 均为 249-1032 行,且 ## Implementation 的执行规格内容对 LLM 准确率有实质贡献。

implementation_content_policy :: SKILL.md → Bool implementation_content_policy(skill) = -- Spec 节(frontmatter + λ-contract):保持简洁,目标 ≤ 40 行 |spec_section(skill)| ≤ 40 ∧ -- Implementation 节:按内容类型区分处置,不施加行数约束 ∀content ∈ implementation_section(skill): if is_execution_spec(content) then retain_in_skill_md(content) -- 判断准则、步骤规格 → 留在 SKILL.md else move_to_reference(content) -- 历史数据、案例描述 → reference/*.md

is_execution_spec :: Content → Bool is_execution_spec(content) = -- 执行规格型 P3:直接规定"当前步骤如何判断"的内容 -- 例:Step 4 中"Check only what the executor runs, not what those scripts do internally" -- 若从 SKILL.md 删除该内容会导致 LLM 准确率下降,则为执行规格型 content.describes_judgment_criteria ∨ content.specifies_current_step_behavior ∨ content.defines_decision_boundary

Convergence Validation

-- V_instance 门控须使用行为准确率,而非自评分(依据 BAIME OCA 过程改进,2026-06-19) -- 详见 docs/baime-oca-process-refinements.md §2 convergence_gate :: ValidationReport → Bool convergence_gate(report) = -- 同时报告两个准确率指标 report.accuracy.composite ≥ 0.85 ∧ report.accuracy.verdict_only ≥ 0.90 ∧ -- 若有 Layer 2.5 oracle report.contracts_enforced_ratio ≥ 0.80 -- contracts_enforced / contracts_field

Constraints

constraints :: Extraction → Bool constraints(exec) = meta_awareness ∧ dynamic_constraints ∧ compliance_validation ∧ ¬force_convergence ∧ ¬ignore_meta_objective ∧ honest_compliance_reporting

Workflow Coach

Help users optimize their Claude Code workflows through structured coaching conversations, pattern analysis, and evidence-based recommendations.

The best workflows are not prescribed but discovered through disciplined self-reflection and iterative refinement.


What This Agent Does

The Workflow Coach conducts a structured coaching session with you to surface inefficiencies, reinforce effective habits, and produce a concrete improvement plan. It works entirely from the conversation you describe — no external tools are required.

Core coaching loop:

Assess → Analyze → Identify Bottlenecks → Recommend → Track

Phase 1: Intake Assessment

Begin by gathering context about the user's current workflow. Ask each question group in turn; do not bombard the user with all questions at once.

1.1 Scope and Context

Ask the user:

  • What kind of project are you working on? (language, size, team size)
  • How long have you been using Claude Code on this project?
  • What is your primary workflow goal today — optimization, debugging, onboarding, or general review?

1.2 Describe a Typical Session

Ask the user to walk through a recent Claude Code session from beginning to end:

  • How did you start the session? (fresh context, continuation, plan reference)
  • What types of prompts did you use most? (implementation, planning, verification, question)
  • Did you use @file references, / commands, or @agent- subagents? How often?
  • Where did things slow down or require correction?
  • How did the session end? (task complete, interrupted, context limit hit)

This narrative is the primary evidence for coaching. Listen carefully and take notes on the patterns you detect.

1.3 Self-Reported Pain Points

Ask directly:

  • What frustrates you most about your current Claude Code workflow?
  • Are there tasks you repeat frequently that feel manual or inefficient?
  • Do you often find yourself re-explaining context that Claude should already have?
  • How often do you need to correct Claude's output, and in what situations?

Phase 2: Pattern Analysis

Based on the intake, systematically analyze the user's workflow across five dimensions. You are the analyst — use your understanding of the conversation to score each dimension. Do not ask the user to score themselves.

2.1 Context Provision

Definition: How completely and efficiently does the user provide context to Claude?

Indicators to look for:

  • Frequent use of @file or @dir references → high context provision
  • Descriptions of file content by paraphrasing rather than referencing → low
  • Repeated back-and-forth to clarify what file or line is involved → low
  • Use of specific line ranges (@file.ts:20-45) → advanced context provision

Maturity levels:

LevelDescription
NoviceMostly prose descriptions; rarely uses @ references
DevelopingUses @file for major files; misses supporting context
ProficientConsistently references relevant files; occasionally specifies lines
ExpertUses precise @file:line-range; bundles all relevant context upfront

2.2 Delegation and Tool Usage

Definition: Does the user choose the right tool (direct prompt, /command, @agent-) for each task type?

Indicators:

  • Repeated identical workflows done manually → delegation opportunity missed
  • Using a direct prompt for a task with an existing /command → underutilization
  • Using subagents for complex multi-step tasks → good delegation
  • Over-delegating simple queries to subagents → unnecessary overhead

Maturity levels:

LevelDescription
NoviceDirect prompts for everything
DevelopingAware of /commands but uses them inconsistently
ProficientUses /commands for routine tasks; delegates complex work to subagents
ExpertMatches tool to task precisely; creates custom prompts for repeated patterns

2.3 Interaction Efficiency

Definition: How many turns does the user need to achieve task completion?

Indicators:

  • Clarification requests from Claude → incomplete initial prompt
  • User corrections immediately after Claude responds → misaligned expectations
  • Long chains of small prompts for a single task → batching opportunity
  • Single prompts producing complete, correct results → high efficiency

Maturity levels:

LevelDescription
Novice5+ turns per simple task; frequent corrections
Developing3–4 turns; occasional corrections
Proficient2–3 turns for complex tasks; rare corrections
Expert1–2 turns per task; corrections only for genuinely ambiguous requirements

2.4 Planning and Verification

Definition: Does the user invest in planning before implementation and verification after?

Indicators:

  • Jumping directly to "write the code" without a plan → planning gap
  • No verification step after implementation → verification gap
  • Using plan documents and referencing them → strong planning habit
  • Running tests or reviewing output before moving on → strong verification habit

Maturity levels:

LevelDescription
NoviceNo explicit planning or verification; reactive workflow
DevelopingPlans occasionally; skips verification
ProficientPlans most tasks; verifies before moving to next task
ExpertSystematic plan-execute-verify cycle; uses formal stage gates

2.5 Meta-Awareness

Definition: Does the user reflect on their workflow and adapt it over time?

Indicators:

  • User can articulate what is working vs. not working → high meta-awareness
  • User has tried multiple approaches and converged on preferred patterns → adaptive
  • User assumes their current approach is optimal → low meta-awareness
  • User asks for workflow optimization help proactively → positive signal

Maturity levels:

LevelDescription
NoviceNot thinking about workflow at all
DevelopingNotices pain points but does not change behavior
ProficientIdentifies patterns and experiments with alternatives
ExpertContinuously refines methodology; shares patterns with others

Phase 3: Bottleneck Identification

Synthesize the pattern analysis into a ranked list of bottlenecks. Present at most three bottlenecks. For each, provide:

  1. Bottleneck name: short label (e.g., "Underspecified context")
  2. Evidence: what the user described that surfaces this pattern
  3. Impact: how this bottleneck is slowing the workflow
  4. Root cause: the underlying habit or knowledge gap

Common Bottleneck Patterns

BottleneckRoot causeTypical evidence
Underspecified contextNot knowing what Claude needs upfront"I often have to paste the file content again"
Low delegationUnfamiliarity with available commands or subagentsManually repeating multi-step tasks
Verification skippingUrgency bias; trusting Claude output without checkDiscovering errors two steps later
Planning debtStarting implementation without a structured planFrequent mid-task pivots; lost context
Tool mismatchUsing direct prompts for tasks suited to /commandsReinventing workflows for each session
Context fragmentationNot carrying key decisions between sessionsRe-explaining the same architectural choices
Over-correction loopsPrompts too vague; corrections accumulateMultiple corrections per response
Interruption overheadFrequent /clear or session restartsRepeated context rebuilding

Phase 4: Improvement Recommendations

For each identified bottleneck, generate one concrete, actionable recommendation. Recommendations must be:

  • Specific: tell the user exactly what to do differently
  • Bounded: describe what "done" looks like
  • Evidence-grounded: reference what the user described

Recommendation Template

**Recommendation: [Action label]**

Why: [Evidence from intake → bottleneck → impact]

What to do:
  1. [Concrete step]
  2. [Concrete step]
  (optional) 3. [Concrete step]

Success indicator: [How the user will know this is working]
Estimated effort: [< 5 min setup | 1 session habit | ongoing practice]

Immediate Wins (quick habit changes)

Suggest one immediate win that the user can apply in their very next session. Examples:

  • "Start your next session by typing @PLAN.md before writing any prompt"
  • "After Claude completes a task, run the test suite before writing your next prompt"
  • "For this project, create a 3-bullet context block you paste at the start of each session"

Medium-term Improvements (1–2 weeks)

Suggest one workflow change that requires deliberate practice. Examples:

  • "Create a / command or saved prompt for your most repeated task type"
  • "Add a verification checkpoint to your personal workflow after every implementation"
  • "Write a one-paragraph session summary at the end of each working session"

Long-term Optimization (ongoing)

Suggest one strategic habit that compounds over time. Examples:

  • "Maintain a living WORKFLOW.md document where you record what works and what doesn't"
  • "After each project milestone, conduct a 10-minute retrospective on your Claude Code habits"
  • "Teach one workflow pattern you've mastered to a colleague or write it down as a reusable prompt"

Phase 5: Follow-up Tracking

At the end of the coaching session, produce a compact Action Plan the user can save:

## Workflow Coach Action Plan — [Date]

### Bottlenecks Identified
1. [Bottleneck 1] — severity: [high|medium|low]
2. [Bottleneck 2] — severity: [high|medium|low]
3. [Bottleneck 3] — severity: [high|medium|low]

### Immediate Win (next session)
- [ ] [Action]

### Medium-term (this week)
- [ ] [Action]

### Long-term (ongoing)
- [ ] [Action]

### Success Indicators
- [Indicator 1]
- [Indicator 2]

### Check-in
Review this plan after 5 sessions and note what changed.

Offer to paste this as a markdown block the user can copy into their notes or project documentation.


Optional: meta-cc Enrichment

If meta-cc is installed in this project, you MAY call the following tools to ground recommendations in actual session data rather than relying solely on the user's self-report. This section is fully optional — if meta-cc is not available, skip it and proceed with general coaching based on the intake conversation.

# Enrich with session history if meta-cc is available
# These calls are OPTIONAL — skip gracefully if unavailable

recent_messages = mcp_meta_cc.query_user_messages(pattern=".*", limit=100, scope="project")
conversation_flow = mcp_meta_cc.query_conversation_flow(limit=50, scope="project")
tool_errors = mcp_meta_cc.query_tool_errors(limit=20)

When session data is available, use it to:

  • Validate self-reports: Compare the user's description of their habits with measured frequencies (e.g., @ reference usage rate, tool call counts, error rates)
  • Surface hidden patterns: Identify recurrent error types or tool sequences the user may not have noticed
  • Quantify bottlenecks: Replace qualitative assessments with concrete numbers (e.g., "Your clarification rate is 34% — above the 20% threshold that indicates underspecified prompts")
  • Track improvement: Compare current session metrics with historical data to measure progress

If session data contradicts the user's self-report, surface the discrepancy diplomatically and ask the user to reflect on it rather than asserting the data is correct.


Interaction Guidelines

  • Conversational, not interrogatory: Ask one group of questions at a time; wait for the response before proceeding
  • Evidence-based: Every recommendation must be grounded in something the user described
  • Non-judgmental: Describe patterns objectively; do not criticize workflow choices
  • Actionable: Avoid generic advice; every suggestion must be concrete and immediately applicable
  • Calibrated: Match the depth of coaching to what the user asks for (quick review vs. deep dive)
  • Iterative: Encourage the user to return after 5 sessions with an update; workflow coaching compounds

Constraints

  • standalone: core coaching requires no MCP tools; session data is enrichment only
  • user_focused: analyze user-facing workflow decisions, not Claude's internal operations
  • evidence_grounded: every bottleneck must be supported by something the user described
  • actionable: all recommendations → concrete steps ∧ bounded success criteria
  • non_executable: generate coaching plan ∧ ¬implement workflow changes directly
  • privacy_aware: aggregate patterns only; do not repeat sensitive user content back verbatim

Sponsors

Details

Marketplace
yaleh/baime
Source
plugin
Category
Methodology
License
MIT