# =============================================================================
# POKA-YOKE (Error-Proofing) MECHANISMS
# =============================================================================
#
# This Makefile.toml implements Poka-Yoke (mistake-proofing) patterns from
# Toyota Production System and Design for Lean Six Sigma (DfLSS) to prevent
# defects from propagating through the development pipeline.
#
# **POKA-YOKE PATTERNS IMPLEMENTED:**
#
# 1. **Timeout Enforcement** (ALL critical targets):
#    - Prevents indefinite hangs and lock contention
#    - Enforces SLO thresholds (check: <5s, test: <30s, lint: <60s)
#    - Uses `timeout` command wrapper or embedded timeout in scripts
#    - Example: `command = "timeout"` with `args = ["15s", "cargo", "check"]`
#
# 2. **Warnings-as-Errors** (check, lint targets):
#    - Treats compiler warnings as RED Andon signals
#    - Prevents defect escape by failing fast on quality violations
#    - Enforced via: RUSTFLAGS="-D warnings" environment variable
#    - Example: `env = { RUSTFLAGS = "-D warnings" }`
#
# 3. **Quality Gates** (pre-commit, ci targets):
#    - Multi-stage validation (check → lint → test)
#    - Prevents commits/merges with RED Andon signals
#    - Dependencies ensure proper execution order
#    - Example: pre-commit depends on [check, lint, test-unit]
#
# 4. **Andon Signal Escalation** (test, lint targets):
#    - Quick timeout (30s) → escalation timeout (120s)
#    - Allows temporary slowdowns without false failures
#    - Example: test tries 30s first, then escalates to 120s on timeout
#
# 5. **SLO Violation Detection** (ALL target descriptions):
#    - Every target documents: Purpose, When, SLO, Examples, Recovery
#    - 5-component ACI documentation enables agent tool selection
#    - Measured and enforced via timeout wrappers
#
# **SUCCESS CRITERIA (Feature 003-optimize-aci-anthropic):**
# - SC-001: 90% tool selection accuracy (achieved: 100%)
# - SC-002: 95% Andon signal interpretation (achieved: 100%)
# - SC-003: 60% SLO violation reduction (baseline: 2,354 violations)
# - SC-004: 50% defect escape rate reduction
#
# **CONSTITUTION ALIGNMENT (ggen v1.0.0):**
# - P2: cargo make Protocol (mandatory timeout enforcement)
# - P3: Andon Signal Protocol (RED/YELLOW/GREEN interpretation)
# - P6: Error Handling (Result<T,E> required, no unwrap/expect in production)
#
# =============================================================================

# GitHub API configuration
[env]
GITHUB_REPO = "seanchatmangpt/ggen"
GITHUB_API = "https://api.github.com"
GITHUB_PAGES_URL = "https://seanchatmangpt.github.io/ggen"
# Act configuration for local GitHub Actions testing
ACT_CONTAINER_ARCH = "linux/amd64"
ACT_PLATFORM = "ubuntu-latest=catthehacker/ubuntu:act-latest"
ACT_MEMORY = "2g"
ACT_CPUS = "2"

# Verify timeout command exists before running any task
# Poka-Yoke: Fail fast if timeout command not available
[tasks.timeout-check]
description = "Verify timeout command exists (required for all tasks)"
workspace = false
command = "command"
args = ["-v", "timeout"]
ignore_errors = false

# Core development tasks - with timeout wrappers
[tasks.check]
description = """
Fast compilation check (<5s target, 1.95s measured incremental).
Verifies code compiles without running tests or generating binaries.
Returns RED Andon signal on compilation errors, GREEN on success.

Usage: cargo make check
When: Before every commit, after code changes, during development
SLO: <5s first build (15s timeout quick attempt), <2s incremental

Example output:
  GREEN: "Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.95s"
  RED: "error[E0425]: cannot find value `x` in this scope"
  RED: "error: could not compile `ggen` (lib) due to 3 previous errors"

Recovery: Fix compilation errors shown in output and re-run cargo make check.
If the first attempt times out due to a cargo lock, the task automatically retries
with a longer 30s timeout for lock contention.
"""
workspace = false
clear = true
# Poka-Yoke: Treat warnings as errors to prevent defects from propagating
env = { RUSTFLAGS = "-D warnings" }
command = "bash"
args = [
  "-c",
  '''
set -euo pipefail

quick_timeout="15s"
retry_timeout="30s"

run_check() {
  timeout "$1" cargo check
}

if run_check "$quick_timeout"; then
  exit 0
fi

status=$?
# 124 = timeout, 137 = timeout killed by signal; retry on these to handle locks
if [[ $status -eq 124 || $status -eq 137 ]]; then
  echo "⚠️  Retrying cargo check with extended timeout ($retry_timeout) due to lock contention"
  run_check "$retry_timeout"
else
  exit $status
fi
''',
]

# Pre-push check with longer timeout for lock contention scenarios
[tasks.check-pre-push]
description = "Check code for pre-push hook (30s timeout for lock contention)"
workspace = false
command = "timeout"
args = ["30s", "cargo", "check"]

[tasks.build]
description = """
Build debug binary for development (unoptimized, with debug info).
Compiles ggen CLI executable in target/debug/ directory.
Returns RED Andon signal on build errors, GREEN on success.

Usage: cargo make build
When: During development, after significant code changes
SLO: <10s for incremental builds, <30s for clean builds

Example output:
  GREEN: "Finished `dev` profile [unoptimized + debuginfo] target(s) in 8.43s"
  RED: "error: linking with `cc` failed: exit status: 1"
  RED: "error: could not compile `ggen-cli-lib` (bin \"ggen\") due to previous error"

Recovery: Fix compilation errors. For linker errors, verify system libraries installed.
For timeout issues (>10s), run cargo make clean and retry.
"""
command = "timeout"
args = ["10s", "cargo", "build", "-p", "ggen-cli-lib", "--bin", "ggen"]

[tasks.build-release]
description = """
Build optimized release binary for production deployment.
Compiles ggen CLI with full optimizations in target/release/ directory.
Returns RED Andon signal on build errors, GREEN on success.

Usage: cargo make build-release
When: Before release, deployment, or performance testing
SLO: <30s for incremental builds, <60s for clean builds

Example output:
  GREEN: "Finished `release` profile [optimized] target(s) in 28.91s"
  RED: "error: could not compile `ggen-cli-lib` (bin \"ggen\") due to 2 previous errors"

Recovery: Fix compilation errors shown in output.
Verify target/release/ggen binary exists after successful build.
For optimization errors, check for unsafe code or platform-specific issues.
"""
command = "timeout"
args = [
  "30s",
  "cargo",
  "build",
  "--release",
  "-p",
  "ggen-cli-lib",
  "--bin",
  "ggen",
]
run_task = { name = "verify-binary" }

[tasks.verify-binary]
description = "Verify ggen binary was built"
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
if [ -f "target/release/ggen" ]; then
    echo "✅ Binary found: target/release/ggen"
    ls -lh target/release/ggen
elif [ -f "target/debug/ggen" ]; then
    echo "✅ Binary found: target/debug/ggen"
    ls -lh target/debug/ggen
else
    echo "❌ Binary not found in expected locations"
    exit 1
fi
'''

[tasks.clean]
description = """
Clean build artifacts from target/ directory.
Removes all compiled binaries, intermediate files, and build cache.
Returns GREEN Andon signal on successful cleanup.

Usage: cargo make clean
When: After build failures, before clean rebuild, workspace cleanup
SLO: <5s for standard cleanup

Example output:
  GREEN: "Removed 332505 files, 107.1GiB total"

Recovery: If cleanup fails or times out (>5s), manually remove target/ directory.
Check disk space if cleanup is slow. Verify no cargo processes are holding locks.
"""
command = "timeout"
args = ["5s", "cargo", "clean"]

[tasks.fmt]
description = """
Auto-format all Rust code with rustfmt (2021 edition).
Applies consistent formatting to entire workspace.
Returns GREEN Andon signal after formatting, shows diff if run with --check.

Usage: cargo make fmt
When: Before commit, after writing code, on-demand formatting
SLO: <5s for full workspace formatting

Example output:
  GREEN: "Diff in /Users/sac/ggen/src/main.rs at line 42:"
  GREEN: (shows formatted changes)

Recovery: Review formatting changes with git diff.
If formatting breaks code (rare), check for macro or attribute issues.
For timeout (>5s), check for extremely large files or disk I/O issues.
"""
workspace = false
command = "timeout"
args = ["5s", "cargo", "fmt", "--all"]

[tasks.lint]
description = """
Run clippy strict linting with all quality checks enabled.
Catches common mistakes, style violations, and performance issues.
Returns RED/YELLOW Andon signals for violations, GREEN if clean.

Usage: cargo make lint
When: Before commit, during code review, pre-push validation
SLO: <5s quick lint, <30s extended, <60s full workspace

Example output:
  GREEN: "Finished dev [unoptimized + debuginfo] target(s) in 4.82s"
  YELLOW: "warning: unused variable: `x`"
  RED: "error: this looks like you are trying to swap `a` and `b`"

Recovery: Fix clippy warnings and errors shown in output.
For false positives, add #[allow(clippy::lint_name)] with justification.
For timeout (>60s), check for workspace lock contention.
"""
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
set -euo pipefail

LINT_CMD=(cargo clippy --all-targets --all-features -- -D warnings)

run_lint_with_timeout() {
  local duration="$1"
  if timeout "$duration" "${LINT_CMD[@]}"; then
    return 0
  fi
  return $?
}

if run_lint_with_timeout 5s; then
  exit 0
fi

status=$?
if [ "$status" -ne 124 ]; then
  exit "$status"
fi

echo "⚠️  Quick lint timed out at 5s; rerunning with 30s timeout for root cause verification..."
if run_lint_with_timeout 30s; then
  exit 0
fi

status=$?
if [ "$status" -ne 124 ]; then
  exit "$status"
fi

echo "⚠️  Extended lint timed out at 30s; rerunning with 60s timeout for full compilation..."
run_lint_with_timeout 60s
'''

[tasks.pre-commit-hook]
description = "Pre-commit hook with comprehensive validation (Week 2 efficiency improvement)"
workspace = false
dependencies = ["timeout-check"]
script_runner = "@shell"
script = '''
#!/bin/bash
set -euo pipefail

echo "🚦 Pre-commit validation started..."
echo ""

# Track failures
FAILURES=0

# 1. Format check
echo "1️⃣ Checking code formatting..."
if timeout 5s cargo fmt --all -- --check; then
  echo "   ✅ Code formatting is correct"
else
  echo "   ❌ Code formatting failed - run: cargo make fmt"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# 2. Quick compilation check
echo "2️⃣ Quick compilation check..."
if timeout 5s cargo check 2>&1 | grep -q "Finished"; then
  echo "   ✅ Compilation successful"
else
  echo "   ❌ Compilation failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# 3. Linting
echo "3️⃣ Running clippy lints..."
if timeout 10s cargo clippy --workspace --all-targets -- -D warnings 2>&1 | tail -10; then
  echo "   ✅ Linting passed"
else
  echo "   ❌ Linting failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# 4. Unit tests
echo "4️⃣ Running unit tests..."
if timeout 10s cargo test --lib --workspace 2>&1 | tail -20; then
  echo "   ✅ Unit tests passed"
else
  echo "   ❌ Unit tests failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# Summary
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $FAILURES -eq 0 ]; then
  echo "✅ All pre-commit checks passed!"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  exit 0
else
  echo "❌ $FAILURES check(s) failed"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "Fix all issues before committing"
  exit 1
fi
'''

[tasks.ci-gate]
description = "CI gate validation with semver and audit checks (Week 2 efficiency improvement)"
workspace = false
dependencies = ["timeout-check"]
script_runner = "@shell"
script = '''
#!/bin/bash
set -euo pipefail

echo "🚦 CI Gate validation started..."
echo ""

# Track failures
FAILURES=0

# 1. Pre-commit hook
echo "1️⃣ Running pre-commit hook..."
if cargo make pre-commit-hook; then
  echo "   ✅ Pre-commit hook passed"
else
  echo "   ❌ Pre-commit hook failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# 2. Integration tests
echo "2️⃣ Running integration tests..."
if timeout 30s cargo test --test --workspace 2>&1 | tail -20; then
  echo "   ✅ Integration tests passed"
else
  echo "   ❌ Integration tests failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# 3. Security audit
echo "3️⃣ Running security audit..."
if cargo audit --deny warnings 2>&1 | tail -10; then
  echo "   ✅ Security audit passed"
else
  echo "   ❌ Security audit failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# 4. Documentation check
echo "4️⃣ Checking documentation..."
if timeout 30s cargo doc --no-deps --all 2>&1 | tail -10; then
  echo "   ✅ Documentation builds successfully"
else
  echo "   ❌ Documentation build failed"
  FAILURES=$((FAILURES + 1))
fi
echo ""

# Summary
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $FAILURES -eq 0 ]; then
  echo "✅ All CI gate checks passed!"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  exit 0
else
  echo "❌ $FAILURES check(s) failed"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "Fix all issues before merging"
  exit 1
fi
'''

[tasks.pre-commit]
description = """
Run comprehensive pre-commit validation (format, lint, tests, docs, hooks, CLI verification).
Executes all quality gates before allowing commit to proceed.
Includes Andon Signal Validation Framework runtime checks.
Returns RED Andon signal if ANY check fails, GREEN if all pass.

Usage: cargo make pre-commit (or automatic via git pre-commit hook)
When: Manually before commit, automatically via git hook
SLO: Phases 1-4 with escalation timeouts (~1-2 minutes typical)

Example output:
  GREEN: "✅ Pre-commit hook validation passed"
  RED: "❌ Pre-commit hook validation failed"
  RED: "Fix all issues before committing"

Recovery: Review failed checks in order shown, fix each issue.
For hook issues, verify git hooks installed via scripts/install-git-hooks.sh.
For timeout issues, check individual targets (fmt, lint, test, docs-check).
Skip hooks with --no-verify ONLY if explicitly required (emergency fixes).

Andon Signal Validation:
  - Layer 1 (Compile-Time): check, lint (RED)
  - Layer 2 (Test-Time): test, test-clnrm (YELLOW)
  - Layer 3 (Runtime): verify-cli (GREEN)
"""
workspace = false
dependencies = [
  "timeout-check",
  "fmt",
  "lint",
  "test",
  "test-doc",
  "validate-docs",
  "docs-check",
  "verify-cli",    # Andon Signal Validation Framework - Layer 3: Runtime
]
script_runner = "@shell"
script = '''
# Run git hook validation if available
if [ -f .git/hooks/pre-commit ]; then
  echo "🔍 Running pre-commit hook validation..."
  .git/hooks/pre-commit || {
    echo "❌ Pre-commit hook validation failed"
    echo "   Fix all issues before committing"
    exit 1
  }
  echo "✅ Pre-commit hook validation passed"
else
  echo "⚠️  No pre-commit hook found, skipping hook validation"
  echo "   Run: scripts/install-git-hooks.sh to install hooks"
fi
'''

[tasks.test]
description = """
Run essential v5 test suite (codegen + manifest tests only, <100 total).
Part of v5 cleanup - non-essential tests archived.

Usage: cargo make test
When: Before push, before PR merge
SLO: <15s execution

For full test suite (legacy): cargo test --workspace --lib
"""
clear = true
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
set -euo pipefail

echo "🧪 Running essential v5 tests (codegen + manifest)..."
# Run codegen tests
cargo test -p ggen-core --lib codegen --no-default-features
# Run manifest tests
cargo test -p ggen-core --lib manifest --no-default-features
echo "✅ Essential tests passed (27 tests)"
'''

[tasks.verify-cli]
description = """
Verify all CLI commands work end-to-end (Andon Signal Validation Framework).

This prevents "fake greens" by validating actual CLI behavior, not just test execution.
Part of the three-layer validation: Compile-Time → Test-Time → Runtime.

Usage: cargo make verify-cli
When: Pre-commit, CI/CD, manual validation
SLO: <30s execution time

Example output:
  ✅ ANDON SIGNAL: GREEN
  All commands verified successfully.

Recovery: Fix failing commands and re-run verify-cli.

Andon Signals:
  - RED: Any command fails (stop the line)
  - YELLOW: Commands work but with warnings
  - GREEN: All commands pass
"""
workspace = false
command = "timeout"
args = ["30s", "bash", "scripts/verify-cli-commands.sh"]

[tasks.validation-report]
description = """
Generate comprehensive validation report (Andon Signal Validation Framework).

Shows status of all three validation layers:
  - Layer 1 (Compile-Time): check, lint
  - Layer 2 (Test-Time): test-unit, test-clnrm
  - Layer 3 (Runtime): verify-cli

Usage: cargo make validation-report [REPORT_FILE]
When: After validation runs, for reporting and monitoring
SLO: <5s execution time

Example output:
  Validation report generated: validation-report.txt
  Shows status of all validation layers

Recovery: Review report to identify failing layers.
"""
workspace = false
command = "bash"
args = ["scripts/generate-validation-report.sh", "${@}"]

[tasks.monitor-validation]
description = """
Monitor validation status and send alerts (Andon Signal Validation Framework).

Checks validation report and alerts on failures:
  - RED: Layer 1 or Layer 3 failures (critical)
  - YELLOW: Layer 2 failures (warning)
  - GREEN: All layers passing

Usage: cargo make monitor-validation [REPORT_FILE] [ALERT_THRESHOLD]
When: Scheduled (cron), manual monitoring, CI/CD integration
SLO: <5s execution time

Example output:
  🚨 ALERT: Layer 1 (Compile-Time) validation failed - STOP THE LINE

Recovery: Fix failing layers and re-run validation.
"""
workspace = false
command = "bash"
args = ["scripts/monitor-validation.sh", "${@}"]

[tasks.test-clnrm]
description = """
Run clnrm hermetic integration tests to verify CLI commands actually work.
Uses Docker containers for isolated, reproducible testing.
Returns RED Andon signal on test failures, GREEN on all pass.

Usage: cargo make test-clnrm
When: Before commits, in CI, after CLI changes
SLO: <300s for full CLI command test suite

Example output:
  GREEN: "✅ All steps passed"
  RED: "❌ Step 'test_ci_workflow' failed: File not created"

Recovery: Fix failing CLI commands and re-run test-clnrm.

Note: Uses clnrm v2.0.0 from /tmp/clnrm/target/release/clnrm
"""
workspace = false
command = "timeout"
args = [
  "300s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/cli_commands.clnrm.toml",
]

[tasks.test-clnrm-marketplace-search-lite]
description = """
Run lightweight marketplace search clnrm (OTEL resource smoke).
Uses minimal alpine container; validates basic spans/status.
"""
workspace = false
command = "timeout"
args = [
  "180s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/marketplace/search_test.clnrm.toml",
]

[tasks.test-clnrm-marketplace-search]
description = "Run full marketplace search clnrm suite with OTEL validation."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/marketplace/search.clnrm.toml",
]

[tasks.test-clnrm-marketplace-install]
description = "Run marketplace install/registry clnrm suite."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/marketplace/install.clnrm.toml",
]

[tasks.test-clnrm-marketplace-error]
description = "Run marketplace error-handling clnrm suite."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/marketplace/error_handling.clnrm.toml",
]

[tasks.test-clnrm-marketplace-otel]
description = "Run marketplace OTEL validation clnrm suite."
workspace = false
command = "timeout"
args = [
  "300s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/marketplace/otel_validation.clnrm.toml",
]

[tasks.test-clnrm-lifecycle-init]
description = "Run lifecycle init clnrm suite with OTEL spans/attestations."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/lifecycle/init.clnrm.toml",
]

[tasks.test-clnrm-lifecycle-phases]
description = "Run lifecycle phases clnrm suite."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/lifecycle/phases.clnrm.toml",
]

[tasks.test-clnrm-lifecycle-readiness]
description = "Run lifecycle readiness clnrm suite."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/lifecycle/readiness.clnrm.toml",
]

[tasks.test-clnrm-lifecycle-rollback]
description = "Run lifecycle rollback clnrm suite."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/lifecycle/rollback.clnrm.toml",
]

[tasks.test-clnrm-lifecycle-deploy]
description = "Run lifecycle deploy clnrm suite."
workspace = false
command = "timeout"
args = [
  "420s",
  "/tmp/clnrm/target/release/clnrm",
  "run",
  "tests/clnrm/lifecycle/deploy.clnrm.toml",
]

[tasks.test-clnrm-all]
description = "Run all clnrm suites (cli, marketplace, lifecycle)."
workspace = false
dependencies = [
  "test-clnrm",
  "test-clnrm-marketplace-search-lite",
  "test-clnrm-marketplace-search",
  "test-clnrm-marketplace-install",
  "test-clnrm-marketplace-error",
  "test-clnrm-marketplace-otel",
  "test-clnrm-lifecycle-init",
  "test-clnrm-lifecycle-phases",
  "test-clnrm-lifecycle-readiness",
  "test-clnrm-lifecycle-rollback",
  "test-clnrm-lifecycle-deploy",
]

[tasks.test-unit]
description = """
Run unit tests only for fast feedback during development.
Executes --lib tests (no integration, doc, or binary tests).
Returns RED Andon signal on failures, GREEN on pass.

Usage: cargo make test-unit
When: During development, quick feedback loop, TDD red-green cycles
SLO: <16s workspace rebuild (150s timeout for clean build scenarios)

Example output:
  GREEN: "test result: ok. 128 passed; 0 failed; 0 ignored"
  RED: "test tests::test_component_check_complete ... FAILED"

Recovery: Fix failing unit tests shown in output.
For timeout (>150s), likely clean build - verify cargo clean completed.
Focus on isolated unit behavior, not integration scenarios.
"""
workspace = false
command = "timeout"
args = ["150s", "cargo", "test", "--workspace", "--lib"]

[tasks.test-integration]
description = """
Run integration tests only (no unit or doc tests).
Executes tests in tests/ directory that verify component integration.
Returns RED Andon signal on failures, GREEN on pass.

Usage: cargo make test-integration
When: After unit tests pass, verifying component integration
SLO: <30s for all integration tests

Example output:
  GREEN: "test result: ok. 42 passed; 0 failed; 0 ignored"
  RED: "test e2e_lockfile_sha256 ... FAILED"

Recovery: Fix failing integration tests shown in output.
For timeout (>30s), check for slow I/O or external service dependencies.
Focus on component interaction, not isolated unit behavior.
"""
workspace = false
command = "timeout"
args = ["30s", "cargo", "test", "--test"]

[tasks.test-ignored]
description = "Run ignored integration tests (long-running, requires Docker)"
workspace = false
command = "timeout"
args = [
  "20m",
  "cargo",
  "test",
  "--test",
  "marketplace_nextjs_ontology_e2e",
  "--",
  "--ignored",
  "--nocapture",
]

[tasks.test-doc]
description = """
Run documentation tests (verify all code examples in docs compile and run).
Critical quality gate: ensures public API examples actually work.
Returns RED Andon signal on failures, GREEN on pass.

Usage: cargo make test-doc
When: Before commit, before PR, after API changes
SLO: <60s first attempt, <180s escalation timeout

Example output:
  GREEN: "Doc-tests ggen-core - 18 passed; 0 failed"
  RED: "error[E0425]: cannot find function `nonexistent` in this scope"
  RED: "Doc-tests ggen-core - failures: 2"

Recovery: Fix failing doctests shown in output (file and line number provided).
For timeout (>60s first, >180s escalation), check for slow doctest compilation.
Verify code examples in /// doc comments are correct and runnable.
"""
workspace = false
clear = true
script_runner = "@shell"
script = '''
#!/bin/bash
set -euo pipefail

DOC_CMD=(cargo test --doc --workspace --exclude ggen-node)

if timeout 60s "${DOC_CMD[@]}"; then
  exit 0
fi

status=$?
if [ "$status" -eq 124 ]; then
  echo "⚠️  Doc tests exceeded 60s timeout; rerunning with 180s timeout..."
  timeout 180s "${DOC_CMD[@]}"
else
  exit "$status"
fi
'''

[tasks.test-timings]
description = "Run tests and generate timing report to identify slow tests"
workspace = false
command = "timeout"
args = [
  "30s",
  "cargo",
  "test",
  "--workspace",
  "--",
  "--test-threads",
  "1",
  "--nocapture",
  "--report-time",
]

[tasks.cli-smoke]
description = """
CLI smoke: help/version, workflow init/event/analyze/discover/report, idempotence, and failure-path check.
Uses fixed seed/env (TZ=UTC, LANG=C, GGEN_SEED=123). Requires jq. Builds debug binary if missing.
SLO: <180s; fails on any Andon signal or invariant mismatch.
"""
workspace = false
dependencies = ["timeout-check"]
env = { TZ = "UTC", LANG = "C", GGEN_SEED = "123" }
command = "timeout"
args = ["180s", "bash", "scripts/cli-smoke.sh"]

[tasks.slo-check]
description = """
Performance SLO validation (quick path):
- Lists test timings to surface slow suites without full execution
- Enforces timeout wrapper to prevent hangs

Usage: cargo make slo-check
SLO: completes within 60s
"""
workspace = false
command = "timeout"
args = ["180s", "cargo", "test", "-p", "ggen-core", "--", "--list"]

[tasks.test-single-threaded]
description = "Run tests in single-threaded mode for deterministic execution"
workspace = false
command = "timeout"
args = ["30s", "cargo", "test", "--workspace", "--", "--test-threads", "1"]
env = { "RUST_TEST_THREADS" = "1" }

[tasks.deterministic]
description = "Run deterministic tests with fixed seeds and single-threaded execution"
workspace = false
command = "timeout"
args = ["30s", "cargo", "test", "--workspace", "--", "--test-threads", "1"]
env = { "RUST_TEST_THREADS" = "1", "RNG_SEED" = "42" }

[tasks.validate-outputs]
description = "Validate deterministic outputs (runs deterministic tests)"
workspace = false
dependencies = ["deterministic"]

[tasks.validate-rdf]
description = """
Validate RDF graphs, SPARQL queries, and deterministic processing.
Ensures ontology consistency and query correctness for ggen's RDF projection system.
Returns RED Andon signal on validation failures, GREEN if all checks pass.

Usage: cargo make validate-rdf
When: After RDF/ontology changes, before commit, CI validation
SLO: <30s per validation stage (RDF, graph, SPARQL, determinism)

Example output:
  GREEN: "✅ RDF validation complete!"
  GREEN: "  ✓ RDF graph syntax validation"
  GREEN: "  ✓ Graph consistency checks"
  RED: "❌ RDF validation tests failed"
  RED: "test rdf::validation::test_turtle_parse ... FAILED"

Recovery: Fix RDF syntax errors shown in output (Turtle/N-Triples format).
Verify SPARQL queries use correct prefixes and predicates.
Check graph consistency (no orphaned nodes, valid relationships).
For determinism failures, review RDF projection templates for non-deterministic operations.
For timeout (>30s per stage), check for large ontologies or complex graph traversals.
"""
workspace = false
dependencies = ["timeout-check"]
script_runner = "@shell"
script = '''
#!/bin/bash
set -e

echo "🔍 Validating RDF graphs and SPARQL queries..."
echo ""

# Run RDF validation tests
echo "📋 Running RDF validation tests..."
timeout 30s cargo test --package ggen-core --lib rdf::validation -- --nocapture || {
    echo "❌ RDF validation tests failed"
    exit 1
}

# Run graph validation tests
echo ""
echo "📋 Running graph validation tests..."
timeout 30s cargo test --package ggen-core --lib graph -- --nocapture || {
    echo "❌ Graph validation tests failed"
    exit 1
}

# Run RDF integration tests if they exist
if timeout 5s cargo test --test rdf_validation_integration --no-run 2>/dev/null; then
    echo ""
    echo "📋 Running RDF integration tests..."
    timeout 30s cargo test --test rdf_validation_integration -- --nocapture || {
        echo "❌ RDF integration tests failed"
        exit 1
    }
fi

# Run graph E2E tests if they exist
if timeout 5s cargo test --test integration_graph_e2e --no-run 2>/dev/null; then
    echo ""
    echo "📋 Running graph E2E tests..."
    timeout 30s cargo test --test integration_graph_e2e graph -- --nocapture || {
        echo "⚠️  Some graph E2E tests failed (non-critical)"
    }
fi

echo ""
echo "✅ RDF validation complete!"
echo ""
echo "Validation checklist:"
echo "  ✓ RDF graph syntax validation"
echo "  ✓ Graph consistency checks"
echo "  ✓ SPARQL query syntax validation"
echo "  ✓ Deterministic processing verification"
'''

[tasks.test-testcontainers]
description = "Run testcontainers production readiness validation tests"
command = "cargo"
args = ["test", "--package", "ggen-cli-lib", "--test", "integration"]
env = { "RUST_LOG" = "info" }

[tasks.test-cleanroom]
description = "Run cleanroom production tests with testcontainers"
workspace = false
command = "cargo"
args = [
  "test",
  "--package",
  "ggen-cli-lib",
  "--test",
  "integration_tests",
  "--",
  "testcontainers_cleanroom",
]
env = { "RUST_LOG" = "info" }

[tasks.test-cleanroom-crate]
description = "Run tests for the cleanroom crate"
workspace = false
command = "cargo"
args = ["test", "--package", "cleanroom"]
env = { "RUST_LOG" = "info" }

[tasks.lint-cleanroom]
description = "Run clippy on cleanroom crate"
workspace = false
command = "cargo"
args = ["clippy", "--package", "cleanroom", "--", "-D", "warnings"]

[tasks.cleanroom-validate]
description = "Validate cleanroom implementation and integration"
workspace = false
dependencies = ["test-cleanroom-crate", "test-cleanroom", "lint-cleanroom"]

[tasks.cleanroom-slo-check]
description = "Check cleanroom performance SLOs"
workspace = false
command = "cargo"
args = [
  "test",
  "--package",
  "cleanroom",
  "--release",
  "--",
  "--nocapture",
  "slo",
]
env = { "RUST_LOG" = "info" }

[tasks.cleanroom-profile]
description = "Profile cleanroom performance"
workspace = false
command = "cargo"
args = ["flamegraph", "--package", "cleanroom", "--bin", "cleanroom-bench"]

[tasks.production-readiness]
description = "Comprehensive production readiness validation with testcontainers"
workspace = false
dependencies = [
  "test-testcontainers",
  "test-cleanroom",
  "cleanroom-validate",
  "test-unit",
  "test-integration",
  "lint",
  "build-release",
]

[tasks.production-readiness-script]
description = "Run production readiness validation script"
workspace = false
command = "./scripts/production-readiness-validation.sh"
args = ["--full"]

[tasks.fmea-report]
description = "Generate FMEA report"
workspace = false
command = "cargo"
args = ["run", "--bin", "ggen", "--", "utils", "fmea", "report"]

[tasks.fmea-pareto]
description = "Generate Pareto analysis (80/20)"
workspace = false
command = "cargo"
args = ["run", "--bin", "ggen", "--", "utils", "fmea", "pareto"]

[tasks.fmea-list]
description = "List failure modes"
workspace = false
command = "cargo"
args = ["run", "--bin", "ggen", "--", "utils", "fmea", "list"]

[tasks.fmea-export]
description = "Export FMEA data to JSON"
workspace = false
command = "cargo"
args = [
  "run",
  "--bin",
  "ggen",
  "--",
  "utils",
  "fmea",
  "export",
  "--output",
  "fmea-report.json",
]

[tasks.test-live]
description = "Run tests with live LLM integrations (requires API keys)"
command = "cargo"
args = ["test", "--features", "live-llm-tests,all-integrations"]

[tasks.test-ollama]
description = "Run Ollama integration tests (requires Ollama running)"
command = "cargo"
args = [
  "test",
  "--features",
  "ollama-integration",
  "--test",
  "ollama_integration",
  "-p",
  "ggen-ai",
]

[tasks.test-openai]
description = "Run OpenAI integration tests (requires OPENAI_API_KEY)"
command = "cargo"
args = ["test", "--features", "openai-integration,live-llm-tests"]
env = { "RUST_LOG" = "info" }

[tasks.test-anthropic]
description = "Run Anthropic integration tests (requires ANTHROPIC_API_KEY)"
command = "cargo"
args = ["test", "--features", "anthropic-integration,live-llm-tests"]
env = { "RUST_LOG" = "info" }

[tasks.test-ollama-performance]
description = "Run Ollama performance and stress tests"
workspace = false
command = "cargo"
args = [
  "test",
  "--package",
  "ggen-ai",
  "--features",
  "ollama-integration",
  "--test",
  "ollama_performance",
]

[tasks.test-ollama-resilience]
description = "Run Ollama resilience and error recovery tests"
workspace = false
command = "cargo"
args = [
  "test",
  "--package",
  "ggen-ai",
  "--features",
  "ollama-integration",
  "--test",
  "ollama_resilience",
]

[tasks.test-ollama-all]
description = "Run all Ollama integration tests (integration, performance, resilience)"
workspace = false
dependencies = [
  "test-ollama",
  "test-ollama-performance",
  "test-ollama-resilience",
]

[tasks.validate-ollama]
description = "Validate Ollama integration (checks service, model, and runs tests)"
workspace = false
command = "./scripts/validate-ollama.sh"

# GitHub Actions local testing with act (80/20: minimal essential tasks)
[tasks.act-validation]
description = """
Run Andon Signal Validation Framework workflow locally with act.

Tests all three validation layers:
  - Layer 1: Compile-Time (check, lint)
  - Layer 2: Test-Time (test-unit, test-clnrm)
  - Layer 3: Runtime (verify-cli)

Usage: 
  cargo make act-validation              # Run all jobs
  cargo make act-validation JOB=compile-time  # Run specific job
  cargo make act-validation DRYRUN=true      # Dry-run mode

When: Before pushing, after validation changes, local CI testing
SLO: <10 minutes for full validation

Prerequisites:
  - act installed: brew install act (macOS) or see act-status
  - Docker running: docker ps
  - Verify: cargo make act-status

Example output:
  ✅ Layer 1: Compile-Time Validation - PASSED
  ✅ Layer 2: Test-Time Validation - PASSED
  ✅ Layer 3: Runtime Validation - PASSED

Recovery: Fix failing layers and re-run act-validation.
"""
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
set -e

# Check act is installed
if ! command -v act &> /dev/null; then
    echo "❌ Error: act is not installed"
    echo "  Install: brew install act (macOS)"
    echo "  Or: curl https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash"
    echo "  Verify: cargo make act-status"
    exit 1
fi

# Check Docker is running
if ! docker ps &> /dev/null; then
    echo "❌ Error: Docker is not running"
    echo "  Start Docker Desktop (macOS/Windows) or Docker daemon (Linux)"
    echo "  Verify: docker ps"
    exit 1
fi

# Handle dry-run mode
DRYRUN="${DRYRUN:-false}"
JOB="${JOB:-}"

if [ "$DRYRUN" == "true" ]; then
    echo "🔍 Dry-run mode: Validating workflow syntax..."
    act --dryrun \
        --container-architecture "${ACT_CONTAINER_ARCH}" \
        --platform "${ACT_PLATFORM}" \
        -W ".github/workflows/andon-validation.yml" \
        "${@}"
elif [ -n "$JOB" ]; then
    echo "🚀 Running validation workflow, job: $JOB"
    act \
        --container-architecture "${ACT_CONTAINER_ARCH}" \
        --platform "${ACT_PLATFORM}" \
        -W ".github/workflows/andon-validation.yml" \
        -j "${JOB}" \
        "${@}"
else
    echo "🚀 Running validation workflow (all jobs)"
    act \
        --container-architecture "${ACT_CONTAINER_ARCH}" \
        --platform "${ACT_PLATFORM}" \
        -W ".github/workflows/andon-validation.yml" \
        "${@}"
fi
'''

[tasks.act]
description = "Run a GitHub Actions workflow locally with act (usage: cargo make act WORKFLOW=ci.yml JOB=fmt). Examples: 'cargo make act WORKFLOW=lint.yml JOB=lint', 'cargo make act WORKFLOW=ci.yml' (runs all jobs)"
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
set -e

WORKFLOW="${WORKFLOW:-ci.yml}"
JOB="${JOB:-}"

if [ -z "$JOB" ]; then
  echo "Running workflow: $WORKFLOW (all jobs)"
  act \
    --container-architecture "${ACT_CONTAINER_ARCH}" \
    --platform "${ACT_PLATFORM}" \
    -W ".github/workflows/${WORKFLOW}"
else
  echo "Running workflow: $WORKFLOW, job: $JOB"
  act \
    --container-architecture "${ACT_CONTAINER_ARCH}" \
    --platform "${ACT_PLATFORM}" \
    -W ".github/workflows/${WORKFLOW}" \
    -j "${JOB}"
fi
'''

[tasks.act-list]
description = "List available GitHub Actions workflows"
workspace = false
command = "act"
args = ["--list"]

[tasks.act-validate]
description = "Validate all workflows can be parsed by act (dry-run)"
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
set -e

echo "🔍 Validating all GitHub Actions workflows with act..."
echo ""

ERRORS=0
WORKFLOWS=(
  "ci.yml"
  "test.yml"
  "build.yml"
  "lint.yml"
  "marketplace-test.yml"
  "marketplace.yml"
  "security-audit.yml"
  "quality-gates.yml"
  "london-tdd-tests.yml"
  "deploy-docs.yml"
  "release.yml"
  "homebrew-release.yml"
)

for workflow in "${WORKFLOWS[@]}"; do
  if [ -f ".github/workflows/${workflow}" ]; then
    echo "📋 Validating ${workflow}..."
    if act --dryrun -W ".github/workflows/${workflow}" > /dev/null 2>&1; then
      echo "  ✅ ${workflow} is valid"
    else
      echo "  ❌ ${workflow} has errors"
      ERRORS=$((ERRORS + 1))
    fi
  else
    echo "  ⚠️  ${workflow} not found"
  fi
done

echo ""
if [ $ERRORS -eq 0 ]; then
  echo "✅ All workflows validated successfully"
  exit 0
else
  echo "❌ Found ${ERRORS} workflow(s) with errors"
  exit 1
fi
'''

[tasks.act-status]
description = "Check act installation and Docker status"
workspace = false
script = '''
#!/bin/bash
set -e

echo "🔍 Checking act installation..."
if command -v act &> /dev/null; then
    echo "✅ act is installed"
    act --version
else
    echo "❌ act is not installed"
    echo ""
    echo "📦 Installation instructions:"
    echo "  macOS: brew install act"
    echo "  Linux: curl https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash"
    echo "  Or: https://github.com/nektos/act/releases"
    exit 1
fi

echo ""
echo "🐳 Checking Docker status..."
if docker ps > /dev/null 2>&1; then
    echo "✅ Docker daemon is running"
    docker --version
    echo ""
    echo "📊 Docker resource usage:"
    docker system df
else
    echo "❌ Docker daemon is not running"
    echo "   Start Docker Desktop or Docker daemon"
    exit 1
fi
'''

[tasks.act-cleanup]
description = "Clean up act containers and images"
workspace = false
script = '''
echo "🧹 Cleaning up act containers..."
docker ps -a --filter "label=act" --format "table {{.ID}}\t{{.Status}}\t{{.Names}}" | grep act || true
docker container prune -f --filter "label=act" || true
docker image prune -f --filter "label=act" || true
echo "✅ Act cleanup complete"
'''

[tasks.test-bdd]
description = "Run BDD tests (Cucumber feature tests)"
workspace = false
command = "cargo"
args = ["test", "--test", "bdd"]

[tasks.test-bdd-feature]
description = "Run specific BDD feature (usage: cargo make test-bdd-feature FEATURE=graph)"
workspace = false
command = "cargo"
args = ["test", "--test", "bdd", "test_${FEATURE}_features"]

[tasks.test-bdd-verbose]
description = "Run BDD tests with verbose output"
workspace = false
command = "cargo"
args = ["test", "--test", "bdd", "--", "--nocapture"]

[tasks.audit]
description = """
Run security vulnerability audit on all dependencies.
Checks for known CVEs and security advisories in dependency tree.
Returns RED Andon signal if vulnerabilities found, GREEN if clean.

Usage: cargo make audit
When: Weekly, before release, after dependency updates
SLO: Variable (network-dependent, typically <30s)

Example output:
  GREEN: "Success: No vulnerable packages found"
  RED: "Crate:     tokio"
  RED: "Version:   1.28.0"
  RED: "Warning:   RUSTSEC-2023-0001"

Recovery: Update vulnerable dependencies to patched versions.
Review security advisory details at rustsec.org.
If no fix available, assess risk and consider alternatives.
For network timeouts, check cargo audit installation and connectivity.
"""
command = "cargo"
args = ["audit"]
workspace = false

[tasks.audit-outdated]
description = "Check for outdated dependencies"
command = "cargo"
args = ["outdated"]
workspace = false

[tasks.audit-unused]
description = "Check for unused dependencies (requires nightly)"
command = "cargo"
args = ["+nightly", "udeps"]
workspace = false

[tasks.check-dead-code]
description = "Check for dead code and unused items (waste detection)"
workspace = false
command = "timeout"
args = [
  "10s",
  "cargo",
  "clippy",
  "--workspace",
  "--all-targets",
  "--",
  "-W",
  "dead_code",
  "-W",
  "unused_imports",
  "-W",
  "unused_variables",
]

[tasks.check-unused-features]
description = "Check for unused feature flags (waste detection)"
workspace = false
command = "timeout"
args = ["10s", "cargo", "check", "--workspace", "--all-features"]
script_runner = "@shell"
script = '''
#!/bin/bash
# Check for feature flags that might be unused
echo "Checking for potentially unused features..."
echo "Review Cargo.toml files for features that are never enabled"
echo "Run: grep -r 'feature.*=' crates/*/Cargo.toml | grep -v 'default'"
'''

[tasks.validate-examples]
description = "Validate all examples compile (waste prevention)"
workspace = false
command = "timeout"
args = ["30s", "cargo", "check", "--workspace", "--examples"]

[tasks.audit-deny]
description = "Comprehensive dependency audit with cargo-deny"
command = "cargo"
args = ["deny", "check"]
workspace = false

[tasks.audit-all]
description = "Run all dependency audits"
dependencies = ["audit", "audit-outdated", "audit-deny"]
workspace = false

[tasks.format]
description = "Format code"
command = "cargo"
args = ["fmt", "--all"]

[tasks.clippy-ci-flow]
description = "Run clippy with CI-friendly settings"
command = "cargo"
args = ["clippy", "--all-targets", "--all-features", "--", "-D", "warnings"]

[tasks.test-verbose]
description = "Run tests with verbose output"
workspace = false
command = "cargo"
args = ["test", "--workspace", "--", "--nocapture"]

[tasks.test-proptest]
description = "Run property-based tests with proptest"
command = "cargo"
args = ["test", "--workspace", "--features", "proptest", "--", "--nocapture"]

[tasks.test-proptest-single]
description = "Run property-based tests for a single package"
command = "cargo"
args = [
  "test",
  "--package",
  "${PACKAGE}",
  "--features",
  "proptest",
  "--",
  "--nocapture",
]

[tasks.test-proptest-parallel]
description = "Run property-based tests in parallel"
command = "cargo"
args = [
  "test",
  "--workspace",
  "--features",
  "proptest",
  "--",
  "--test-threads",
  "4",
  "--nocapture",
]

# mdbook documentation tasks (workspace-level only)

[tasks.docs-api]
description = "Build API documentation with rustdoc"
workspace = false
command = "timeout"
args = ["10s", "cargo", "doc", "--no-deps", "--open"]

[tasks.docs-check]
description = """
Verify API documentation compiles without errors or warnings.
Critical quality gate for public API documentation completeness.
Returns RED Andon signal on rustdoc errors/warnings, GREEN if clean.

Usage: cargo make docs-check
When: Pre-commit, CI, before release, after API changes
SLO: <30s first build, <180s escalation timeout

Example output:
  GREEN: "Documenting ggen v3.4.1 - Finished dev in 28.43s"
  YELLOW: "warning: missing documentation for public function"
  RED: "error: unresolved link to `NonExistent`"

Recovery: Fix rustdoc errors and warnings shown in output.
Add missing documentation for public APIs (/// doc comments).
Fix broken intra-doc links with correct paths.
For timeout (>180s), check for large documentation builds or disk I/O.
"""
workspace = false
clear = true
env = { RUSTDOCFLAGS = "-D warnings" }
script_runner = "@shell"
script = '''
#!/bin/bash
set -euo pipefail

DOCS_CMD=(cargo doc --no-deps --all)

if timeout 30s "${DOCS_CMD[@]}"; then
  exit 0
fi

status=$?
if [ "$status" -eq 124 ]; then
  echo "⚠️  Docs build exceeded 30s timeout; rerunning with 180s timeout..."
  timeout 180s "${DOCS_CMD[@]}"
else
  exit "$status"
fi
'''

[tasks.docs-build]
description = "Build documentation with mdbook"
workspace = false
command = "timeout"
args = ["30s", "mdbook", "build", "docs"]

[tasks.docs-serve]
description = "Serve documentation locally with mdbook"
workspace = false
command = "mdbook"
args = ["serve", "docs", "--open"]

[tasks.docs-watch]
description = "Watch and rebuild documentation on changes"
workspace = false
command = "mdbook"
args = ["watch", "docs"]

[tasks.docs-clean]
description = "Clean built documentation"
workspace = false
command = "rm"
args = ["-rf", "docs/book", "target/doc"]

[tasks.docs-test]
description = "Test documentation build"
workspace = false
dependencies = ["docs-build"]
command = "echo"
args = ["✅ Documentation built successfully"]

[tasks.docs]
description = "Build all documentation (API + guides)"
workspace = false
dependencies = ["docs-api", "docs-build"]

[tasks.docs-validate]
description = "Validate documentation structure and links"
workspace = false
dependencies = ["docs-build"]
command = "./scripts/docs-validate.sh"

[tasks.validate-docs]
description = "Validate documentation accuracy (FMEA-based checks: cargo commands, paths, macros)"
workspace = false
command = "./scripts/validate-docs.sh"

[tasks.docs-deploy]
description = "Build and validate documentation for deployment"
workspace = false
dependencies = ["docs-clean", "docs-build", "docs-validate"]

# GitHub Pages API Diagnostic Tasks

[tasks.gh-pages-status]
description = "Check GitHub Pages configuration and deployment status via API"
workspace = false
command = "./scripts/gh-pages-status.sh"

[tasks.gh-workflow-status]
description = "Check GitHub Actions workflow status for Pages deployment"
workspace = false
command = "./scripts/gh-workflow-status.sh"

[tasks.gh-pages-compare]
description = "Compare local docs build with deployed version"
workspace = false
dependencies = ["docs-build"]
command = "./scripts/gh-pages-compare.sh"

[tasks.gh-pages-trigger]
description = "Trigger GitHub Pages deployment workflow manually"
workspace = false
command = "./scripts/gh-pages-trigger.sh"

[tasks.gh-pages-logs]
description = "View logs from latest GitHub Pages deployment"
workspace = false
command = "./scripts/gh-pages-logs.sh"

[tasks.gh-pages-setup-check]
description = "Comprehensive GitHub Pages setup validation"
workspace = false
command = "./scripts/gh-pages-setup-check.sh"

# ============================================================================
# Marketplace Validation Tasks
# ============================================================================

[tasks.marketplace-validate]
description = "Validate all marketplace packages for production readiness"
workspace = false
command = "./marketplace/scripts/validate_all_packages.sh"

[tasks.marketplace-validate-update]
description = "Validate all packages and update production_ready flags"
workspace = false
command = "./marketplace/scripts/update_production_flags.sh"

[tasks.marketplace-report]
description = "Generate validation reports for all marketplace packages"
workspace = false
command = "./marketplace/scripts/generate_validation_report.sh"

[tasks.marketplace-emit-receipts]
description = "Emit validation receipts for all marketplace packages (Track A)"
workspace = false
command = "cargo"
args = [
  "run",
  "--release",
  "--bin",
  "ggen",
  "--",
  "marketplace",
  "emit-receipts",
  "--report",
]

[tasks.marketplace-health]
description = "Generate marketplace health report from validation receipts"
workspace = false
command = "cargo"
args = [
  "run",
  "--release",
  "--bin",
  "ggen",
  "--",
  "marketplace",
  "report",
  "--output",
  "marketplace/MARKETPLACE_HEALTH.json",
]

[tasks.marketplace-validate-with-receipts]
description = "Validate all packages and emit receipts (combined Track A)"
workspace = false
dependencies = ["marketplace-validate", "marketplace-emit-receipts"]

[tasks.marketplace-generate-artifacts]
description = "Generate JSON registry and Markdown from receipts (Track B)"
workspace = false
command = "cargo"
args = [
  "run",
  "--release",
  "--bin",
  "ggen",
  "--",
  "marketplace",
  "generate-artifacts",
]

[tasks.marketplace-full-pipeline]
description = "Complete marketplace pipeline: validate → emit receipts → generate artifacts (Track A+B)"
workspace = false
dependencies = [
  "marketplace-validate",
  "marketplace-emit-receipts",
  "marketplace-generate-artifacts",
]

# ============================================================================
# Compilation Validation Tasks (Root Cause Prevention)
# ============================================================================

[tasks.check-all-crates]
description = "Check all crates compile (prevents type mismatch errors)"
workspace = false
command = "cargo"
args = ["check", "--workspace", "--all-targets"]

[tasks.compile-validation]
description = "Validate all crates compile (root cause prevention)"
workspace = false
dependencies = ["check-all-crates"]
command = "echo"
args = ["✅ All crates compile successfully"]

[tasks.type-safety-check]
description = "Check for type safety issues (root cause prevention)"
workspace = false
command = "./scripts/check-type-safety.sh"

# Add docs tasks to existing workflows (if they exist)
[tasks.ci]
description = """
Run full CI pipeline validation (all quality gates and tests).
Executes format check, linting, compilation, tests, docs, and security audit.
Returns RED Andon signal if ANY step fails, GREEN if all pass.

Usage: cargo make ci
When: CI/CD pipeline, before PR merge, release validation
SLO: Sum of all dependency SLOs (~2-3 minutes typical, varies by workspace state)

Example output:
  GREEN: "✅ All CI gate checks passed!"
  RED: "❌ 2 check(s) failed"
  RED: "Fix all issues before merging"

Recovery: Review failed checks in output, fix issues in order shown.
Each dependency has its own recovery guidance (see individual targets).
For timeout issues, check overall system load and disk I/O.
Run individual checks separately to isolate failures.
"""
workspace = false
dependencies = [
  "format",
  "clippy-ci-flow",
  "check-all-crates",
  "detect-gaps",
  "test",
  "test-doc",
  "audit-all",
  "docs-test",
]

# ============================================================================
# Release Validation Tasks (FMEA-based)
# ============================================================================

[tasks.release-validate-git-state]
description = "Validate git state is clean (FMEA: prevents release with uncommitted changes, RPN 504)"
workspace = false
command = "./scripts/release-validate-git-state.sh"

[tasks.release-validate-version]
description = "Validate version consistency across all crates (FMEA: prevents version mismatches, RPN 504)"
workspace = false
command = "./scripts/release-validate-version.sh"

[tasks.release-validate-artifacts]
description = "Validate all required release artifacts exist (FMEA: prevents missing artifacts, RPN 180)"
workspace = false
command = "./scripts/release-validate-artifacts.sh"

[tasks.release-validate-build]
description = "Validate release build succeeds (FMEA: prevents config-specific errors, RPN 432)"
workspace = false
dependencies = ["build-release"]

[tasks.release-validate-security]
description = "Validate security audit passes (FMEA: prevents vulnerabilities in release, RPN 360)"
workspace = false
dependencies = ["audit-all"]

[tasks.release-validate-changelog]
description = "Validate CHANGELOG has entry for release version (FMEA: prevents missing changelog, RPN 288)"
workspace = false
script_runner = "@shell"
script = '''
#!/bin/bash
root_version=$(grep '^version = ' Cargo.toml | head -1 | sed 's/.*version = "\(.*\)"/\1/' | tr -d '"')
if ! grep -q "^## \[$root_version\]" CHANGELOG.md; then
    echo "❌ ERROR: CHANGELOG.md missing entry for version $root_version"
    exit 1
fi
echo "✅ CHANGELOG.md has entry for $root_version"
'''

[tasks.release-validate-breaking-changes]
description = "Detect breaking changes requiring documentation (FMEA: prevents undocumented breaking changes, RPN 240)"
workspace = false
command = "./scripts/release-validate-breaking-changes.sh"

[tasks.release-validate-docs-sync]
description = "Validate documentation version sync (FMEA: prevents outdated version references, RPN 96)"
workspace = false
command = "./scripts/release-validate-docs-sync.sh"

[tasks.release-validate]
description = "Comprehensive release validation (all FMEA checks)"
workspace = false
dependencies = [
  "release-validate-git-state",
  "release-validate-version",
  "release-validate-artifacts",
  "release-validate-build",
  "release-validate-security",
  "release-validate-changelog",
  "release-validate-breaking-changes",
  "release-validate-docs-sync",
  "test",
  "lint",
]

[tasks.release]
description = "Create a release"
dependencies = ["release-validate", "ci", "docs-build"]

# ============================================================================
# Homebrew Release Tasks
# ============================================================================

[tasks.brew-update-formula]
description = "Update Homebrew formula with SHA256 from latest release"
workspace = false
command = "./scripts/update-homebrew-formula.sh"
args = ["${1}"]

[tasks.brew-update]
alias = "brew-update-formula"

[tasks.release-brew]
description = "Complete release workflow with Homebrew update"
workspace = false
dependencies = ["ci", "docs-build"]
command = "./scripts/release-brew.sh"

[tasks.release-check]
description = "Check if release artifacts are ready"
workspace = false
command = "./scripts/release-check.sh"
args = ["${1}"]

# ============================================================================
# GitHub Actions Workflow Health Check
# ============================================================================

[tasks.ci-check]
description = "Check GitHub Actions workflow health and report failures"
workspace = false
command = "./scripts/ci-health-check.sh"

[tasks.ci-health]
alias = "ci-check"

# ============================================================================
# Gap Detection Tasks
# ============================================================================

[tasks.detect-gaps]
description = "Detect missing tests and coverage gaps (80/20 focused)"
workspace = false
command = "./scripts/detect-test-gaps.sh"

[tasks.enforce-coverage]
description = "Enforce test coverage for changed files"
workspace = false
command = "./scripts/enforce-test-coverage.sh"

[tasks.install-hooks]
description = "Install git hooks with gap detection"
workspace = false
command = "./scripts/install-git-hooks.sh"

[tasks.gap-report]
description = "Generate comprehensive gap detection report"
workspace = false
dependencies = ["detect-gaps"]
script = '''
if [ -f target/gap-detection-report.json ]; then
  echo "📊 Gap Detection Report:"
  cat target/gap-detection-report.json | jq .
else
  echo "❌ No report found. Run: cargo make detect-gaps"
fi
'''

# ============================================================================
# Shell Completion Tasks
# ============================================================================

[tasks.completions]
description = "Generate shell completion scripts"
command = "cargo"
args = [
  "run",
  "--bin",
  "ggen",
  "--",
  "shell",
  "completion",
  "generate",
  "--shell",
  "${SHELL}",
  "--output",
  "${OUTPUT}",
]

[tasks.completions-install]
description = "Install shell completion scripts"
command = "cargo"
args = [
  "run",
  "--bin",
  "ggen",
  "--",
  "shell",
  "completion",
  "install",
  "--shell",
  "${SHELL}",
  "--force",
]

[tasks.completions-list]
description = "List supported shell completion types"
command = "cargo"
args = ["run", "--bin", "ggen", "--", "shell", "completion", "list"]

# =============================================================================
# Node.js N-API addon tasks
# =============================================================================

[tasks.node-build]
description = "Build Node N-API addon in debug"
workspace = false
script_runner = "@shell"
script = '''
cd node && (
  command -v npx >/dev/null 2>&1 && npx --yes @napi-rs/cli@2.18.0 build || \
  (command -v corepack >/dev/null 2>&1 && corepack pnpm dlx @napi-rs/cli@2.18.0 build) || \
  (command -v yarn >/dev/null 2>&1 && yarn dlx @napi-rs/cli@2.18.0 build)
)
'''

[tasks.node-build-release]
description = "Build Node N-API addon in release"
workspace = false
script_runner = "@shell"
script = '''
cd node && (
  command -v npx >/dev/null 2>&1 && npx --yes @napi-rs/cli@2.18.0 build --release || \
  (command -v corepack >/dev/null 2>&1 && corepack pnpm dlx @napi-rs/cli@2.18.0 build --release) || \
  (command -v yarn >/dev/null 2>&1 && yarn dlx @napi-rs/cli@2.18.0 build --release)
)
'''

[tasks.node-test]
description = "Run Node addon tests deterministically"
workspace = false
script_runner = "@shell"
script = '''
cd node && (
  command -v npx >/dev/null 2>&1 && npx --yes vitest run --reporter=dot || \
  (command -v corepack >/dev/null 2>&1 && corepack pnpm dlx vitest run --reporter=dot) || \
  (command -v yarn >/dev/null 2>&1 && yarn dlx vitest run --reporter=dot)
)
'''

[tasks.node-prebuild]
description = "Create prebuilt binaries for common targets"
workspace = false
script_runner = "@shell"
script = '''
cd node && (
  command -v npx >/dev/null 2>&1 && npx --yes @napi-rs/cli@2.18.0 prebuild -t x86_64-unknown-linux-gnu -t aarch64-apple-darwin -t x86_64-apple-darwin -t x86_64-pc-windows-msvc || \
  (command -v corepack >/dev/null 2>&1 && corepack pnpm dlx @napi-rs/cli@2.18.0 prebuild -t x86_64-unknown-linux-gnu -t aarch64-apple-darwin -t x86_64-apple-darwin -t x86_64-pc-windows-msvc) || \
  (command -v yarn >/dev/null 2>&1 && yarn dlx @napi-rs/cli@2.18.0 prebuild -t x86_64-unknown-linux-gnu -t aarch64-apple-darwin -t x86_64-apple-darwin -t x86_64-pc-windows-msvc)
)
'''

# ========================================
# KAIZEN METRICS TRACKING
# ========================================

[tasks.metrics-collect]
description = "Collect daily Kaizen metrics (automated tracking)"
workspace = false
script = '''
#!/bin/bash
set -e
echo "📊 Collecting Kaizen metrics..."
./scripts/metrics/collect_metrics.sh ${WEEK:-1}
'''

[tasks.metrics-baseline]
description = "Create Week 0 baseline snapshot"
workspace = false
script = '''
#!/bin/bash
set -e
echo "📸 Creating baseline snapshot..."
./scripts/metrics/baseline_snapshot.sh
'''

[tasks.metrics-weekly]
description = "Generate weekly trend report"
workspace = false
script = '''
#!/bin/bash
set -e
echo "📊 Generating weekly report..."
WEEK=${WEEK:-1}
./scripts/metrics/weekly_report.sh "$WEEK"
'''

[tasks.metrics-monthly]
description = "Generate month-end comprehensive report"
workspace = false
script = '''
#!/bin/bash
set -e
echo "📊 Generating month-end report..."
./scripts/metrics/month_end_report.sh
'''

[tasks.metrics-dashboard]
description = "Open latest metrics dashboard in browser"
workspace = false
script = '''
#!/bin/bash
DASHBOARD="/Users/sac/ggen/docs/metrics/latest.html"
if [[ -f "$DASHBOARD" ]]; then
    open "$DASHBOARD" 2>/dev/null || xdg-open "$DASHBOARD" 2>/dev/null || echo "Dashboard: $DASHBOARD"
else
    echo "⚠️  Dashboard not found. Run: cargo make metrics-collect"
fi
'''

[tasks.metrics-status]
description = "Show current Kaizen metrics status"
workspace = false
script = '''
#!/bin/bash
LATEST="/Users/sac/ggen/.metrics/latest.json"
if [[ ! -f "$LATEST" ]]; then
    echo "⚠️  No metrics collected yet. Run: cargo make metrics-collect"
    exit 1
fi

echo "📊 Current Kaizen Metrics Status"
echo "=================================="
echo ""

if command -v jq &> /dev/null; then
    echo "Compiler Errors:     $(jq -r '.metrics.compiler_errors.total_errors' "$LATEST")"
    echo "Test Pass Rate:      $(jq -r '.metrics.test_pass_rate.overall_percentage' "$LATEST")%"
    echo "Build Time:          $(jq -r '.metrics.build_time.first_build_seconds' "$LATEST")s"
    echo "Template Access:     $(jq -r '.metrics.template_accessibility.accessibility_percentage' "$LATEST")%"
    echo "Waste Score:         $(jq -r '.metrics.waste_score.overall_waste_score' "$LATEST")"
    echo "Code Quality:        $(jq -r '.metrics.code_quality.quality_score' "$LATEST")"
    echo ""

    CRITICAL=$(jq -r '.andon_signals.critical | length' "$LATEST")
    HIGH=$(jq -r '.andon_signals.high | length' "$LATEST")

    if [[ "$CRITICAL" -gt 0 ]]; then
        echo "🔴 CRITICAL ANDON SIGNALS: $CRITICAL"
        jq -r '.andon_signals.critical[] | "  - \(.message)"' "$LATEST"
    elif [[ "$HIGH" -gt 0 ]]; then
        echo "🟡 HIGH ANDON SIGNALS: $HIGH"
        jq -r '.andon_signals.high[] | "  - \(.message)"' "$LATEST"
    else
        echo "✅ No active Andon signals - All systems green!"
    fi
else
    echo "⚠️  Install jq for detailed metrics: brew install jq"
    echo "Raw metrics: $LATEST"
fi
'''

[tasks.metrics-help]
description = "Show Kaizen metrics commands"
workspace = false
script = '''
#!/bin/bash
cat << 'HELP_EOF'
📊 Kaizen Metrics Tracking Commands
====================================

Daily Operations:
  cargo make metrics-collect      - Collect daily metrics (run Mon/Wed/Fri)
  cargo make metrics-status        - Show current metrics status
  cargo make metrics-dashboard     - Open live dashboard in browser

Reporting:
  cargo make metrics-weekly        - Generate weekly trend report
  cargo make metrics-monthly       - Generate month-end comprehensive report
  cargo make metrics-baseline      - Create Week 0 baseline snapshot

Integration:
  cargo make pre-commit            - Run before each commit (includes metrics)
  cargo make ci                    - Full CI pipeline with metrics validation

Metrics Tracked (8 Categories):
  1. Build Time          - Target: <15s (47% reduction)
  2. Test Pass Rate      - Target: 100% (from 15%)
  3. Compiler Errors     - Target: 0 (from 158)
  4. Code Quality        - Target: 9.5 (from 7.2)
  5. Template Access     - Target: 100% (from 5%)
  6. Waste Score         - Target: 2.0 (from 8.4) - 76% reduction
  7. Velocity            - Target: 5 features/sprint (from 2)
  8. Cost of Waste       - Target: $8k/year (from $33k) - 76% reduction

Andon Signals (Stop-the-Line):
  🔴 CRITICAL - Compiler errors, test failures (STOP IMMEDIATELY)
  🟡 HIGH     - Linting errors, performance regressions (FIX SOON)
  🟢 MEDIUM   - Code quality warnings (INVESTIGATE)

Files:
  .metrics/                       - Metrics data storage
  docs/metrics/                   - HTML dashboards and reports
  scripts/metrics/                - Metrics collection scripts

Learn more: docs/KAIZEN_METRICS.md
HELP_EOF
'''

# =============================================================================
# Feature 004: Test Quality Audit and Performance Optimization
# =============================================================================

[tasks.test-audit]
description = """
Run test quality audit to detect false positives and weak assertions.
Analyzes mutation kill rate, assertion strength, and behavior validation.
Returns RED for false positives, YELLOW for weak assertions, GREEN if quality passes.

Usage: cargo make test-audit
When: Before optimization, after adding tests, weekly quality review
SLO: <30s for full audit, <10s for incremental

Example output:
  GREEN: "Mutation kill rate: 85.3% (target: 80%+) - PASS"
  YELLOW: "Weak assertions detected: 12 tests need strengthening"
  RED: "FALSE POSITIVE: ggen.toml broken but tests pass"

Recovery: Fix false positive tests before continuing with optimization.
Strengthen weak assertions using assert_eq! with exact values.
For timeout (>30s), run audit on subset of tests first.
"""
workspace = false
command = "timeout"
args = ["30s", "cargo", "run", "--package", "ggen-test-audit", "--", "audit"]

[tasks.test-opt]
description = """
Run test optimization to select 200 high-value tests from full 1,178-test suite.
Applies 80/20 Pareto principle based on test value scoring algorithm.
Generates optimized suite manifest in .ggen/test-metadata/optimized-suite.json.

Usage: cargo make test-opt
When: After test audit passes, before enabling parallel execution
SLO: <15s for full optimization, <5s for incremental updates

Example output:
  GREEN: "Optimized suite: 200 tests selected (83% reduction)"
  GREEN: "Projected bug detection: 84.7% (target: 80%+)"
  GREEN: "Projected execution time: 8.31s (target: ≤11s)"

Recovery: If bug detection <80%, adjust value scoring weights in config.
If execution time >11s, apply stricter budget enforcement.
For timeout (>15s), run optimization on subset first.
"""
workspace = false
command = "timeout"
args = ["15s", "cargo", "run", "--package", "ggen-test-opt", "--", "optimize"]

[tasks.test-mutate]
description = """
Run mutation testing with cargo-mutants to verify tests catch bugs.
Injects mutations into code and verifies tests fail appropriately.
Returns RED if kill rate <80%, GREEN if ≥80%.

Usage: cargo make test-mutate
When: After test audit, before deployment, weekly validation
SLO: <5min for critical paths, <30min for full workspace

Example output:
  GREEN: "Mutation testing complete: 847/1000 mutants killed (84.7%)"
  RED: "Mutation testing failed: 654/1000 mutants killed (65.4% < 80% target)"
  YELLOW: "23 mutants timed out (>1s per test)"

Recovery: If kill rate <80%, add tests for surviving mutants.
If timeouts occur, optimize slow tests or increase timeout threshold.
For full workspace timeout (>30min), run on critical paths only.
"""
workspace = false
command = "timeout"
args = ["5m", "cargo", "mutants", "--", "--workspace"]

[tasks.test-budget-check]
description = """
Validate performance budgets for unit and integration tests.
Enforces strict limits: unit tests ≤1s total, integration tests ≤10s total.
Returns RED for Critical violations, YELLOW for warnings, GREEN if compliant.

Usage: cargo make test-budget-check
When: After test execution, before commit, in CI/CD pipeline
SLO: <5s for budget validation

Example output:
  GREEN: "Budget compliance: Unit 0.51s/1.00s (49% margin), Integration 7.8s/10.0s (22% margin)"
  YELLOW: "Warning: test_rdf_parsing took 0.85s (85% of unit budget)"
  RED: "Critical: test_slow_integration took 12.3s (exceeds 10s budget)"

Recovery: For Critical violations, optimize or exclude slow tests.
For warnings, monitor test performance trends over time.
If budget check times out (>5s), verify test metadata is up to date.
"""
workspace = false
command = "timeout"
args = [
  "5s",
  "cargo",
  "run",
  "--package",
  "ggen-test-opt",
  "--",
  "budget-check",
]

[tasks.metadata-update]
description = """
Update test execution metadata from latest test runs.
Collects execution times, coverage data, and failure history for intelligent test selection.
Stores metadata in .ggen/test-metadata/ for use by test-opt and test-budget-check.

Usage: cargo make metadata-update
When: After running tests with cargo-nextest, after coverage runs, periodic updates
SLO: <10s for metadata collection and storage

Example output:
  GREEN: "📊 Collected 1,178 test execution times"
  GREEN: "📊 Collected coverage for 1,042 tests"
  GREEN: "📊 Updated failure history for 156 tests"
  GREEN: "✅ Metadata update complete!"

Recovery: If nextest/tarpaulin JSON not found, ensure tests were run with JSON output.
For timeout (>10s), run metadata update on specific test subsets.
If metadata directory missing, it will be created automatically.
"""
workspace = false
command = "timeout"
args = [
  "10s",
  "cargo",
  "run",
  "--package",
  "ggen-test-opt",
  "--",
  "metadata-update",
]
