# Greywater Recycling Constructed Wetland

> Greywater Treatment to Irrigation-Grade via Constructed Wetlands (Microbial Safety) — Production-grade On-Site Greywater Treatment & Constructed Wetland Engineering analysis harness with flexible agent architecture, dynamic skill routing, and comprehensive quality gates. Use this skill whenever the user asks about greywater treatment, constructed wetlands, wastewater recycling, irrigation water q…

- **Type:** Skill
- **Install:** `agentstack add skill-dungnotnull-greywater-recycling-constructed-wetland-agent-skill-greywater-recycling-constructed-wetland-agent-skill`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [dungnotnull](https://agentstack.voostack.com/s/dungnotnull)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [dungnotnull](https://github.com/dungnotnull)
- **Source:** https://github.com/dungnotnull/greywater-recycling-constructed-wetland-agent-skill

## Install

```sh
agentstack add skill-dungnotnull-greywater-recycling-constructed-wetland-agent-skill-greywater-recycling-constructed-wetland-agent-skill
```

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

## About

# Greywater Recycling Constructed Wetland — Skill Registry Documentation

## Version
**2.0.0** — Production-grade release with flexible agent architecture

## Overview

This skill provides a **production-grade harness** for On-Site Greywater Treatment & Constructed Wetland Engineering analysis. It transforms Claude Code into a domain expert that delivers structured, evidence-backed outputs through:

1. **Flexible Agent Architecture** — Dynamic skill routing with chain-of-thought decision making
2. **Modular Skill Registry** — Type-safe skill registration with input/output validation
3. **Lifecycle Hooks** — Pre/post execution hooks for monitoring and control
4. **Quality Gates** — 10 validation gates (6 universal + 4 domain) with auto-fix
5. **Graceful Degradation** — 5-level fallback system with explicit limitation flags
6. **Knowledge Pipeline** — Automated crawl pipeline for continuous learning

---

## Skill Registration

### How Skills Are Registered

All skills are registered in `config/skills_init.py` through the `initialize_skills()` function. Each skill is registered with comprehensive metadata:

```python
from config import SkillMetadata, SkillCategory, SkillInputSchema, SkillOutputSchema, register_skill

register_skill(SkillMetadata(
    name="sub-core-analysis",
    version="2.0.0",
    category=SkillCategory.SUB_SKILL,
    description="Design a household greywater treatment system...",
    author="972026 Skill Library",
    license="MIT",
    tags=["analysis", "design", "wetland-sizing"],
    input_schema=SkillInputSchema(...),
    output_schema=SkillOutputSchema(...),
    dependencies=["sub-evidence-collector"],
    token_budget=4000,
    file_path=Path("skills/sub-core-analysis.md")
))
```

### Skill Metadata Schema

```typescript
interface SkillMetadata {
    // Identity
    name: string;                    // Unique skill identifier
    version: string;                 // Semantic version (major.minor.patch)
    category: SkillCategory;         // harness | sub_skill | utility | validator | transformer
    description: string;             // Detailed description for triggering
    author: string;                  // Author/organization
    license: string;                 // License identifier (SPDX)
    tags: string[];                  // Keywords for discovery

    // Input/Output Contracts
    input_schema: SkillInputSchema;  // Input validation schema
    output_schema: SkillOutputSchema; // Output validation schema

    // Dependencies
    dependencies: string[];          // Skills that must complete first

    // Execution Constraints
    token_budget: int;               // Maximum tokens per execution
    max_execution_time_seconds: int;  // Timeout threshold
    retry_count: int;                // Number of retries on failure

    // State
    enabled: bool;                   // Whether skill is active
    file_path: Path | null;          // Path to skill .md file
}
```

---

## Skill Resolution

### Dynamic Resolution Process

When a skill needs to be invoked, the registry performs the following resolution steps:

1. **Lookup** — Find skill by name in the global registry
2. **Validation** — Validate dependencies are satisfied
3. **Routing** — Apply chain-of-thought router for execution decision
4. **Execution** — Execute skill with full lifecycle management

### Routing Decision Process

The `ChainOfThoughtRouter` evaluates rules in priority order to determine execution strategy:

```python
class RoutingDecision(str, Enum):
    EXECUTE_SKILL = "execute_skill"        // Normal execution
    SKIP_TO_NEXT = "skip_to_next"          // Skip this step
    REQUEST_INPUT = "request_input"         // Ask user for clarification
    TERMINATE = "terminate"                 // Stop execution
    DEGRADE = "degrade"                    // Switch to degraded mode
```

### Router Configuration

Router rules are defined in `config/skills_init.py`:

```python
router = ChainOfThoughtRouter()

def check_data_availability_rule(context: RoutingContext):
    if context.execution_context.degradation_level >= 4:
        return RoutingDecision.DEGRADE
    return None

router.add_rule(check_data_availability_rule)
```

---

## Skill Execution

### Execution Lifecycle

Each skill goes through the following lifecycle phases:

```
┌─────────────────────────────────────────────────────────────────┐
│                    SKILL EXECUTION LIFECYCLE                     │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. PRE_EXECUTION Hooks                                         │
│     ├─ Logging                                                  │
│     ├─ State initialization                                     │
│     └─ Pre-conditions check                                    │
│                                                                  │
│  2. PRE_VALIDATION Hooks                                        │
│     ├─ Input schema validation                                  │
│     └─ Dependency verification                                 │
│                                                                  │
│  3. SKILL EXECUTION                                             │
│     ├─ Load skill file                                          │
│     ├─ Execute with context                                     │
│     └─ Capture output                                           │
│                                                                  │
│  4. ERROR HANDLING (if applicable)                              │
│     ├─ ON_ERROR hooks                                          │
│     ├─ Retry logic (up to retry_count)                         │
│     └─ ON_RETRY hooks                                          │
│                                                                  │
│  5. POST_VALIDATION Hooks                                       │
│     ├─ Output schema validation                                │
│     └─ Quality gate checks                                      │
│                                                                  │
│  6. POST_EXECUTION Hooks                                       │
│     ├─ State updates                                            │
│     ├─ Metrics collection                                       │
│     └─ Cleanup                                                  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

### Execution Context

All skills receive an `ExecutionContext` object containing:

```typescript
interface ExecutionContext {
    trace_id: string;                  // Unique execution identifier
    inputs: Record;       // Input parameters
    metadata: Record;     // Execution metadata
    state: Record;        // Shared state across skills
    history: ExecutionStep[];          // Execution history
    degradation_level: 0|1|2|3|4;     // Current degradation level
    language: "en" | "vi";            // Output language
}
```

### Execution Result

Each skill returns an `ExecutionResult`:

```typescript
interface ExecutionResult {
    status: ExecutionStatus;           // pending | running | completed | failed | skipped | retrying
    output: any;                       // Skill output (type per output_schema)
    metadata: Record;      // Skill metadata
    errors: string[];                  // Error messages (if failed)
    execution_time_seconds: number;     // Execution duration
    tokens_used: number;               // Token consumption
}
```

---

## Input/Output JSON Schemas

### Input Schema Definition

Input schemas define required and optional fields with validation rules:

```json
{
    "required_fields": [
        {
            "name": "greywater_sources",
            "type": "list",
            "description": "List of greywater sources"
        },
        {
            "name": "household_size",
            "type": "int",
            "description": "Number of people in household",
            "constraints": {
                "min": 1,
                "max": 20
            }
        }
    ],
    "optional_fields": [
        {
            "name": "climate_data",
            "type": "object",
            "description": "Optional climate information"
        }
    ],
    "validation_rules": [
        {
            "name": "at_least_one_source",
            "validator": "function(inputs) { return inputs.greywater_sources.length > 0; }"
        }
    ]
}
```

### Output Schema Definition

Output schemas define expected format and required sections:

```json
{
    "format": "markdown",
    "structure": {
        "sections": [
            "Greywater Characterization",
            "Wetland Type",
            "Sizing",
            "Treatment Train",
            "Plant Species",
            "Effluent vs Standards",
            "Scenarios"
        ]
    },
    "required_sections": [
        "Wetland Type",
        "Sizing",
        "Effluent vs Standards"
    ]
}
```

### Supported Output Formats

| Format | Description | Validation Method |
|--------|-------------|-------------------|
| `json` | Structured data object | Schema validation with required fields |
| `markdown` | Formatted markdown text | Required header presence check |
| `text` | Plain text output | Length and encoding validation |

---

## Validation System

### Skill-Level Validation

Skills validate inputs against their schemas before execution:

```python
# Input validation
input_valid, input_errors = skill.input_schema.validate(context.inputs)
if not input_valid:
    return ExecutionResult(
        status=ExecutionStatus.FAILED,
        errors=input_errors
    )

# Output validation
output_valid, output_errors = skill.output_schema.validate(output)
if not output_valid:
    # Combine errors and fail
    execution_status = ExecutionStatus.FAILED
```

### Quality Gate Validation

Final outputs are validated against 10 quality gates:

#### Universal Gates (U1-U6)

| Gate | Check | Auto-Fix | Severity |
|------|-------|----------|----------|
| U1 | ≥3 sources cited, ≥1 academic/authoritative | Fetch from knowledge base | Error |
| U2 | Disclosure/limitations before recommendation | Prepend disclosure | Critical |
| U3 | Evidence hierarchy stated (Tier 1-4) per source | Annotate tiers | Warning |
| U4 | Language matches user preference | Translate output | Error |
| U5 | Output uses declared template (all sections) | Reformat to template | Error |
| U6 | Every claim traceable to source or flagged | Mark unsupported | Warning |

#### Domain Gates (G1-G4)

| Gate | Check | Auto-Fix | Severity |
|------|-------|----------|----------|
| G1 | Wetland sized per Kadlec/Wallace method | Apply recognized sizing | Critical |
| G2 | Effluent checked against WHO/FAO/ISO 16075 | Verify effluent standards | Critical |
| G3 | Treatment train and plant species specified | Add components | Error |
| G4 | Reuse restrictions for edible crops stated | State restrictions | Critical |

---

## Lifecycle Hooks

### Hook Points

Hooks can be registered at these lifecycle points:

| Hook Point | When Executed | Purpose |
|------------|---------------|---------|
| `PRE_EXECUTION` | Before skill starts | Logging, state init |
| `POST_EXECUTION` | After skill completes | Metrics, cleanup |
| `ON_ERROR` | When skill fails | Error handling, retry logic |
| `ON_RETRY` | Before retry attempt | Retry strategy |
| `PRE_VALIDATION` | Before input validation | Pre-checks |
| `POST_VALIDATION` | After output validation | Post-checks |
| `ON_DEGRADATION` | When degradation level changes | Degradation handling |

### Registering Hooks

Hooks are registered using the decorator pattern:

```python
from config import register_hook, HookPoint

@register_hook(HookPoint.PRE_EXECUTION, priority=10)
def log_execution_start(context, skill_metadata, **kwargs):
    """Log skill execution start."""
    print(f"[{skill_metadata.name}] Starting execution")
    return True, None  # (should_continue, result_data)
```

### Hook Return Values

Hooks return a tuple of `(should_continue, result_data)`:
- `should_continue` — If `False`, execution is halted
- `result_data` — Any data to pass to next hook or skill

---

## Graceful Degradation

### Degradation Levels

The harness operates at 5 degradation levels:

| Level | Name | Condition | Behavior |
|-------|------|-----------|----------|
| 0 | Full Operation | All sources reachable | Full evidenced analysis |
| 1 | Partial Primary | Some sources fail | Use secondary sources, flag substitutions |
| 2 | Knowledge Base Only | Most live sources fail | Use SECOND-KNOWLEDGE-BRAIN.md only |
| 3 | Missing Variables | Input variables missing | Proceed with available, flag unavailable |
| 4 | Full Failure | All sources and KB fail | Emit "DATA UNAVAILABLE", no fabrication |

### Error Recovery Strategies

| Error Type | Detection | Recovery | Max Retries |
|------------|-----------|----------|-------------|
| Source timeout | No response 30s | Retry alternate source | 3 |
| Invalid input | Schema mismatch | Ask user to confirm | 2 |
| Missing input | Field absent | Proceed with available | 0 |
| Stale reading | Timestamp old | Flag, request refresh | 1 |
| Knowledge base miss | No matches | WebSearch gap-fill | 2 |
| Conflicting actions | Mutually exclusive | Apply precedence | 0 |
| Envelope unavailable | No setpoint | Use fallback + flag | 1 |
| Object ambiguous | Classification unclear | Ask user to confirm | 2 |

---

## Skill Execution Plan

### Sequential Steps

The harness executes skills in strict sequential order:

```
Step 1: sub-gather-requirements
  └─ Checkpoint: requirements_confirmed
  └─ Dependencies: []

Step 2: sub-evidence-collector
  └─ Checkpoint: evidence_collected
  └─ Dependencies: [sub-gather-requirements]

Step 3: sub-core-analysis
  └─ Checkpoint: analysis_complete
  └─ Dependencies: [sub-evidence-collector]
  └─ Quality Gates: [G1, G2, G3, G4]

Step 4: sub-knowledge-updater
  └─ Checkpoint: knowledge_retrieved
  └─ Dependencies: [sub-core-analysis]

Step 5: sub-advisor
  └─ Checkpoint: advisory_complete
  └─ Dependencies: [sub-core-analysis, sub-knowledge-updater]

Step 6: validator-quality-gate
  └─ Checkpoint: quality_validated
  └─ Dependencies: [sub-advisor]
  └─ Quality Gates: [U1, U2, U3, U4, U5, U6, G1, G2, G3, G4]
```

### Dependency Graph

```
                    ┌─────────────────────────────┐
                    │ greywater-recycling-        │
                    │ constructed-wetland        │
                    └─────────────────────────────┘
                                       │
              ┌────────────────────────┼────────────────────────┐
              │                        │                        │
        ┌─────▼──────┐         ┌─────▼──────┐          ┌─────▼──────┐
        │ Step 1:     │         │ Step 2:     │          │ Step 3:     │
        │ Requirements│         │ Evidence    │          │ Core        │
        │ Gathering   │────────→│ Collection  │────────→│ Analysis    │
        └─────────────┘         └─────────────┘          └──────┬──────┘
                                                                │
                                          ┌─────────────────────┼─────────────────────┐
                                          │                     │                     │
                                    ┌─────▼──────┐      ┌─────▼──────┐       ┌─────▼──────┐
                                    │ Step 4:     │      │ Step 5:     │       │ Step 6:     │
                                    │ Knowledge   │────→│ Advisor     │──────▶│ Quality     │
                                    │ Update      │      │             │       │ Gate        │
                                    └─────────────┘      └─────────────┘       └─────────────┘
```

---

## Knowledge Pipeline

### Automated Crawl System

The knowledge pipeline automatically updates `S

…

## Source & license

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

- **Author:** [dungnotnull](https://github.com/dungnotnull)
- **Source:** [dungnotnull/greywater-recycling-constructed-wetland-agent-skill](https://github.com/dungnotnull/greywater-recycling-constructed-wetland-agent-skill)
- **License:** MIT

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

## Pricing

- **Free** — Free

## Security capabilities

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

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

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


## Versions

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

## Links

- Listing page: https://agentstack.voostack.com/l/skill-dungnotnull-greywater-recycling-constructed-wetland-agent-skill-greywater-recycling-constructed-wetland-agent-skill
- Seller: https://agentstack.voostack.com/s/dungnotnull
- Browse the marketplace: https://agentstack.voostack.com/browse

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