---
name: ecl-harness-engineer
description: "Create or audit ECL Agent Harness infrastructure: AGENTS.md, change tracking, repository guidance, lint checks, CI gates, and agent handoff docs."
category: development
risk: safe
source: community
source_repo: qinghui316/ecl-harness-engineer
source_type: community
date_added: "2026-06-13"
author: qinghui316
tags: [codex, agent-harness, ecl, workflow, ci]
tools: [codex, claude, cursor, gemini, antigravity]
license: MIT
license_source: "https://github.com/qinghui316/ecl-harness-engineer/blob/main/LICENSE"
---

# ECL Harness Engineer
Design and create Harness Engineering infrastructure so AI agents can work reliably in a codebase.

> **Core Philosophy**: "Intelligence without infrastructure is just a demo." The Agent Harness is the Operating System — the LLM is just the CPU. The repository becomes the single source of truth — if an agent can't see it in context, it doesn't exist.

## When to Use This Skill

- Use when a repository needs AI-agent collaboration infrastructure such as `AGENTS.md`, `docs/ECL.md`, `docs/STATUS.md`, harness change tracking, or mechanical validation gates.
- Use when auditing an existing Agent Harness for missing ECL lifecycle docs, change templates, lint checks, environment contracts, or CI integration.
- Use when converting repeated agent workflow failures into repository-local documentation, tests, lint rules, or lightweight auto-evolution checks.
- Do not use for ordinary business feature implementation unless the requested work is specifically about creating or improving the repository harness.

## Limitations

- This skill creates or audits harness infrastructure; it does not replace product requirements, implementation planning, code review, or release approval for the target project.
- The generated ECL docs, linters, scripts, and CI examples must be adapted to the repository's actual stack, security model, and existing contributor workflow before enforcement.
- Auto-evolve recommendations are guidance only. Apply harness changes through normal review, validation, and rollback discipline instead of accepting them as autonomous policy changes.

## Unified Workflow

This skill follows a single unified workflow regardless of project state (empty, existing code, or existing harness). The core idea: **detect the gap between current state and target state, then fill it**.

Default to a **core ECL harness**. Core includes lightweight auto-evolve threshold checking:
closed changes are counted, a pending evolution note is generated when the threshold is reached,
and Codex applies harness improvements only through evidence, validation, scoring, and rollback.
Advanced agent-platform capabilities such as eval datasets, execution traces, durable state,
checkpoints, long-term memory, and metrics remain optional profiles only when the user explicitly
asks for agent evaluation, observability, resumable execution, or long-term memory.

This skill improves the target repository's agent harness. It does **not** implement ordinary
business features, replace the coding agent's plan mode, or create a separate requirements product.
Plan mode is useful for live discussion; ECL artifacts are the repository record that later agents,
linters, CI, and archive history can inspect.

1. **Quick Detection + Intent Confirmation** — what exists, what already passes, and what the user wants.
2. **Analysis** — architecture, harness state, environment, and project identity.
3. **Intake Review + Delta Synthesis** — classify small vs structured work, support requirement-first
   and plan-first inputs, and compute exactly what to create or update.
4. **Creation/Update** — docs, status handoff, linters, ECL/change scripts, environment config, and CI.
5. **Verification + Handoff** — run checks, attribute failures, update STATUS.md, trigger auto-evolve checks, and summarize results.

---

## Phase 1: Quick Detection + Intent Confirmation

**Goal**: In under 5 minutes, understand project state and user intent.

### 1.1 Project State Detection

Run this quick scan:

```bash
# Count files
file_count=$(find . -type f ! -path './.git/*' ! -path './node_modules/*' ! -path './vendor/*' 2>/dev/null | wc -l)
code_files=$(find . -type f \( -name "*.go" -o -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.rs" \) ! -path './.git/*' ! -path './node_modules/*' ! -path './vendor/*' 2>/dev/null | wc -l)

# Check harness components
has_agents_md=$(test -f AGENTS.md && echo "yes" || echo "no")
has_architecture=$(test -f docs/ARCHITECTURE.md && echo "yes" || echo "no")
has_linters=$(ls scripts/lint-* 2>/dev/null | wc -l)
has_harness_dir=$(test -d harness && echo "yes" || echo "no")
has_ecl_doc=$(test -f docs/ECL.md && echo "yes" || echo "no")
has_changes_dir=$(test -d harness/changes && echo "yes" || echo "no")
has_change_templates=$(test -d harness/templates/change && echo "yes" || echo "no")
has_change_script=$(ls scripts/harness-change.* 2>/dev/null | wc -l)
has_evolve_script=$(ls scripts/harness-evolve.* 2>/dev/null | wc -l)
has_ecl_lint=$(ls scripts/lint-ecl.* 2>/dev/null | wc -l)
has_encoding_lint=$(ls scripts/lint-encoding.* 2>/dev/null | wc -l)
has_makefile=$(test -f Makefile && echo "yes" || echo "no")
has_package_json=$(test -f package.json && echo "yes" || echo "no")

# Detect tech stack
if test -f go.mod; then TECH="Go"
elif test -f package.json; then TECH="TypeScript/Node.js"
elif test -f requirements.txt || test -f pyproject.toml; then TECH="Python"
else TECH="Unknown"
fi
```

### 1.2 Classify Project State

Based on detection:

| State | Criteria | Action |
|-------|----------|--------|
| **Empty** | file_count < 5 AND code_files = 0 | Guide user through project choices first |
| **Code Only** | code_files > 0 AND has_agents_md = "no" | Full analysis + core harness creation |
| **Partial Harness** | has_agents_md = "yes" AND (has_linters = 0 OR has_harness_dir = "no") | Gap analysis + fill gaps |
| **Harness Present** | Core harness components exist | Audit + improvement suggestions |

Also classify ECL readiness:

| ECL State | Criteria | Action |
|-----------|----------|--------|
| **ECL Missing** | has_ecl_doc = "no" OR has_changes_dir = "no" | Create ECL docs, change templates, and scripts |
| **ECL Partial** | ECL doc exists but scripts/templates missing | Fill ECL automation gaps |
| **ECL Ready** | docs/ECL.md, harness/changes, templates, harness-change, harness-evolve, lint-ecl, lint-encoding exist | Audit index freshness and workflow quality |

### 1.3 Baseline Verification Snapshot

For existing projects, capture a best-effort baseline before creating or updating harness files.
The baseline is for attribution only: it distinguishes pre-existing project failures from
failures introduced by harness work. It must not be used to weaken default CI.

Run only commands that already exist in the project:

| Ecosystem | Baseline commands |
|-----------|-------------------|
| TypeScript/Node.js | package scripts such as `lint`, `typecheck`, `test`, `build`; include nested package build scripts when detected |
| Go | `go test ./...`, `go build ./...`, existing `make lint` or `make test` |
| Python | existing test/lint scripts, `python -m compileall .` |

Record each command as `pass`, `fail`, or `missing`, with the short failure reason. If a command
fails before harness creation, report it later as **pre-existing project debt**, not as harness
failure. Default CI remains strict and should still include normal business gates unless the user
explicitly asks for a temporary staged rollout.

### 1.4 Intent Confirmation

Before planning changes, classify requested scope:

| Scope | Default? | Includes |
|-------|----------|----------|
| **Core harness** | Yes | AGENTS.md, docs/ECL.md, docs/STATUS.md, docs, ECL changes, lightweight auto-evolve, linters, environment contract, CI |
| **Advanced harness** | No | Core harness plus explicitly requested eval, trace, state, checkpoints, memory, or metrics |
| **Documentation only** | No | AGENTS.md and docs without linters, scripts, or CI |

When a user-confirmation tool is available, confirm scope. In Codex, use `request_user_input`.
On other platforms, use the equivalent user-choice tool. If no such tool is available, use the
detected context and record assumptions.

```json
{
  "question": "What's your priority for this harness setup?",
  "header": "Scope",
  "multiSelect": false,
  "options": [
    {
      "label": "Core harness (Recommended)",
      "description": "Project-first AGENTS.md, ECL changes, STATUS handoff, auto-evolve threshold checks, linters, environment contract, and strict CI"
    },
    {
      "label": "Advanced harness",
      "description": "Core harness plus explicitly requested eval, trace, memory, checkpoint, or metrics infrastructure"
    },
    {
      "label": "Documentation only",
      "description": "AGENTS.md and project docs only; skip linters, scripts, and CI for now"
    }
  ]
}
```

**If Empty project**, also ask for basics:

```json
{
  "question": "What tech stack for this project?",
  "header": "Tech Stack",
  "multiSelect": false,
  "options": [
    {"label": "Go", "description": "CLI tools, high-performance services, system programming"},
    {"label": "TypeScript/Node.js", "description": "Web APIs, full-stack apps, rapid prototyping"},
    {"label": "Python", "description": "Data processing, ML/AI, scripting"}
  ]
}
```

If no user-confirmation tool is available, use detected values and document assumptions:

```markdown
## Auto-Detected Context

| Field | Value | Confidence | Evidence |
|-------|-------|------------|----------|
| Tech Stack | {TECH} | High | Found {config file} |
| Project State | {state} | High | {criteria matched} |
| Scope | Core harness | Default | No user preference specified |

Proceeding with these assumptions. Tell me if any need adjustment.
```

### 1.5 ECL Work Intake Rules

When generating ECL guidance for a target project, keep the process small enough to use:

| Intake type | Criteria | Required ECL handling |
|-------------|----------|-----------------------|
| **Small Change** | Local, low-risk edits such as copy, comments, style-only tweaks, or single-file bug fixes with no interface, data, permission, architecture, or release impact | Active change optional; still record the verification command in the final response or existing task notes |
| **Structured Change** | Cross-file/module behavior, APIs, data model, permissions, architecture, validation chain, unclear requirements, or work likely to exceed 20 minutes | Use active change files and require intake/spec/plan review before implementation |

Decision tree:

1. If an active change already exists, keep using it; do not create a second active context.
2. If the change is copy, comments, README text, formatting, or an obviously local single-file fix
   with no runtime, API, data, permission, architecture, or validation-chain impact, treat it as
   Small Change.
3. If the change touches APIs, data, permissions, architecture, multiple modules, release/runtime
   behavior, or unclear requirements, treat it as Structured Change.
4. If impact is unclear, do read-only investigation first. If uncertainty remains after inspection,
   ask one high-impact question or upgrade to Structured Change; do not assume Small Change.

For structured changes, support both common entry points:

- **Requirement-first input**: extract target users/scenarios, evidence, success criteria,
  acceptance criteria, non-goals, constraints, assumptions, and risks into `spec.md`.
- **Plan-first input**: treat the user's plan as a draft, split WHAT/WHY into `spec.md` and HOW into
  `plan.md`, then ask only about high-impact gaps that affect implementation direction or acceptance.
  If the plan is complete and does not conflict with repository evidence, do not repeat a full
  interview. If it conflicts with code, docs, commands, or existing harness constraints, record the
  conflict and return to Intake Review.

Questions are allowed and expected, but must be bounded: ask at most three high-impact questions per
round. Low-risk unknowns become assumptions; high-impact unknowns become
`[NEEDS CLARIFICATION: ...]` and block implementation until resolved.

For complex structured changes, use a lightweight iteration loop rather than treating the first
spec as final:

```text
Draft Spec -> Draft Plan -> Review Gaps -> Revise Spec/Plan -> Gate -> Tasks
```

Default to at most two loops. If key gaps remain, continue up to five loops; after that, record a
blocker instead of implementing from guesses. `plan.md` must include any planning-discovered spec
gaps, because plans often expose missing acceptance, boundary, permission, data, or validation
requirements.

---

## Phase 2: Analysis

**Goal**: Deeply understand codebase architecture, harness state, and environment requirements.

### 2.1 Execution Mode

Use subagents only when the user authorized delegation and the environment supports it. Otherwise, execute the same responsibilities inline.

If using subagents, assign:

- Code architecture analysis: follow `agents/analyzer.md`; output `harness/.analysis/architecture.json`.
- Harness state audit: follow `agents/auditor.md`; output `harness/.analysis/audit.json`.
- Environment analysis: follow `references/environment-detection-guide.md`; output `harness/.analysis/environment.json`.

If working inline, produce the same three analysis artifacts or equivalent in-memory summaries before Phase 3.

### 2.2 Project Identity Extraction

For existing projects, extract target-project meaning before writing docs:
- One-sentence project identity: what it does and for whom.
- Core workflow or domain model: user/system flow, key entities, API resources, jobs, or commands.
- Primary source entrypoints and where common changes belong.

Use `README.md`, manifests, entrypoints, routes/controllers, schemas/models, and key source
directories. Harness files are not sufficient evidence for project identity.

### 2.3 Adapter Selection

After detecting the tech stack, load the matching adapter before creating linters, scripts, CI,
or environment config. Adapter guidance overrides generic templates for language-specific details.

| Detected stack | Required adapter |
|----------------|------------------|
| TypeScript/Node.js | `references/adapters/typescript.md` |
| Go | `references/adapters/go.md` |
| Python | `references/adapters/python.md` |
| Rust | `references/adapters/rust.md` |
| Java | `references/adapters/java.md` |
| Unknown/mixed | `references/adapters/generic.md` plus any detected language adapters |

For TypeScript/Node.js projects, prefer Node/TS-native outputs: `scripts/lint-deps.mjs` or
equivalent, `scripts/lint-quality.mjs`, npm/package-manager scripts, and Node/TS GitHub Actions.
Do not adapt Go linter or Makefile-only patterns to TypeScript unless the project is actually Go
or already uses Makefile as the primary command surface.

### 2.4 Command Surface Selection

Before creating ECL scripts, select the target project's command surface. Do not assume
PowerShell is the only Windows option. This selection is normally automatic; do not ask the user to
choose a script format unless project evidence conflicts or the user has already expressed a hard
constraint.

Priority:

1. Existing project entrypoints: package-manager scripts, Makefile targets, README commands,
   or CI shell conventions.
2. Explicit user/project constraints. If the project rejects `.ps1`, do not generate PowerShell
   as the only harness entrypoint.
3. Bash profile when allowed. For Windows projects that accept Bash, generate `.sh` scripts and
   document the prerequisite: Git Bash, WSL, MSYS2, or a CI Linux runner.
4. PowerShell profile when the project accepts Windows-native PowerShell. Keep it compatible with
   Windows PowerShell 5.1 and PowerShell 7.
5. Node or Python profiles when those runtimes are already first-class project dependencies.

Default when evidence is sparse: for TypeScript/Node projects choose Node/package-manager scripts;
for Windows projects that allow Bash choose Bash profile and document Git Bash/WSL/MSYS2; otherwise
choose the adapter's native lightweight scripting profile.

All profiles must implement the same ECL invariants and command set. `harness-change`,
`harness-evolve`, `lint-ecl`, and `lint-encoding` may be implemented as `.ps1`, `.sh`, `.mjs`,
or `.py`, but docs, CI, Makefile/package scripts, and verification commands must use the chosen
entrypoint consistently.

### 2.5 Wait for Analysis Completion

When subagents are running, wait for their final reports. While waiting, you can:
- Review any existing documentation
- Prepare templates for Phase 4

### 2.5 For Empty Projects

Skip Phase 2 analysis agents. Instead:
- Use templates from `references/greenfield-templates.md`
- Base decisions on user's tech stack choice
- Design a standard 3-layer architecture

---

## Phase 3: Delta Synthesis

**Goal**: Merge analysis results and compute exactly what needs to be created/updated.

### 3.1 Read Analysis Results

```bash
cat harness/.analysis/architecture.json
cat harness/.analysis/audit.json
cat harness/.analysis/environment.json
```

### 3.2 Compute Delta

Create a delta list:

```markdown
## Delta: What Needs to Be Done

### Core To Create (doesn't exist)
- [ ] AGENTS.md
- [ ] docs/ECL.md
- [ ] docs/STATUS.md
- [ ] docs/ARCHITECTURE.md
- [ ] scripts/lint-deps.go
- [ ] scripts/harness-change.{ps1|sh|mjs|py}
- [ ] scripts/harness-evolve.{ps1|sh|mjs|py}
- [ ] scripts/lint-ecl.{ps1|sh|mjs|py}
- [ ] scripts/lint-encoding.{ps1|sh|mjs|py}
- [ ] harness/changes/{active,parking,archive}
- [ ] harness/templates/change/
- [ ] harness/config/environment.json
- [ ] harness/evolution/{state.json,results.tsv,proposals/} (`pending.md` is generated later only when the archive threshold is reached)

### Optional Advanced (only if explicitly requested)
- [ ] harness/eval/ — agent evaluation datasets and runner inputs
- [ ] harness/trace/ — execution traces for agent runs
- [ ] harness/state/ — executor runtime state
- [ ] harness/checkpoints/ — resumable execution checkpoints
- [ ] harness/memory/ — long-term agent memory experiments
- [ ] harness/metrics/ — execution and quality metrics

### To Update (exists but has gaps)
- [ ] docs/DEVELOPMENT.md — missing build commands
- [ ] scripts/lint-quality.py — missing 3 packages in layer map

### Already Good (no changes needed)
- [x] Makefile — has all required targets
- [x] .github/workflows/ci.yml — properly configured
```

### 3.3 Confirm with User (if confirmation tool is available)

For significant changes:

```json
{
  "question": "I've analyzed the codebase. Ready to proceed with these changes?",
  "header": "Confirm",
  "multiSelect": false,
  "options": [
    {"label": "Yes, proceed with all", "description": "Create/update all identified items"},
    {"label": "Show me the details first", "description": "I'll explain what each change involves"},
    {"label": "Only critical items", "description": "Just P0/P1 items, skip P2/P3 for now"}
  ]
}
```

---

## Phase 4: Creation/Update

**Goal**: Create or update all harness files from the delta.

### 4.1 Execution Mode

Use subagents only when authorized and available. Otherwise, perform the same work inline. Keep write scopes disjoint if using parallel workers.

Creation responsibilities:

- Documentation: follow `agents/creator-docs.md`; create/update AGENTS.md, docs/ECL.md, docs/STATUS.md, docs/ARCHITECTURE.md, docs/DEVELOPMENT.md, and design docs. AGENTS.md is the target project's entry map, not a harness creation record. Keep the first screen project-first, but preserve ECL/current-change priority in context loading: `AGENTS.md` -> `docs/ECL.md` -> active change if present -> auto-evolve pending if present -> otherwise `docs/STATUS.md` -> task-specific project docs.
- Linters: follow `agents/creator-linters.md`; create/update dependency, quality, ECL, and encoding checks.
- Config and scripts: follow `agents/creator-config.md`; create/update environment contract, harness scripts, changes directories/templates, lightweight evolution state, harness-change, harness-evolve, Makefile targets, and CI. Create advanced directories only when the confirmed scope requires them.

ECL change templates must include `summary.md`, `spec.md`, `plan.md`, `tasks.md`, and
`reviews/review.md`. `spec.md` captures WHAT/WHY, `plan.md` captures HOW and planning-discovered
spec gaps, and `tasks.md` is generated only after the spec/plan gate is ready enough for
implementation. Do not require old archived changes to contain `plan.md`; compatibility applies to
history.

Important: do not create static verification config such as `harness/config/verify.json`. Verification plans are generated at runtime by the executor from `environment.json` and the task context.

Strict CI rule: default CI must include normal business quality gates (`lint`, `typecheck`, `test`,
`build`, and backend/package-specific equivalents when available) plus harness checks. Do not remove
or skip business gates because the baseline is red. If the baseline was already red, explain that CI
will be red until the pre-existing project issues are fixed. Generate staged or relaxed CI only when
the user explicitly asks for it.

Command surface rule: create ECL scripts for the selected profile, not a hardcoded shell. If Bash is
selected on Windows, document Git Bash, WSL, MSYS2, or CI Linux shell requirements in the generated
environment/development docs. If PowerShell is selected, detect whether `pwsh` is available; if not,
use `powershell -NoProfile -ExecutionPolicy Bypass`. PowerShell templates must be compatible with
Windows PowerShell 5.1: avoid ambiguous overloads such as `TrimStart(".\")`, and avoid non-ASCII
mojibake marker string literals in `.ps1`; represent markers by Unicode codepoint or another
PS5-safe construction.

### 4.2 For Empty Projects: Also Create Business Code Plan

For empty projects, add one more agent:

```
Agent("create-exec-plan", prompt="""
Create execution plan for business code (harness-executor will implement this):

Tech stack: {TECH}
Project type: {from user choice}
Architecture: 3-layer (Types → Core → Entry Points)

Create: docs/exec-plans/active/bootstrap-code.md

Contents:
- Full source code for initial project structure
- main.go/index.ts/main.py entry point
- Basic types and core logic
- Test files

This is for harness-executor to implement — not ecl-harness-engineer's responsibility.
""")
```

### 4.3 Wait for Creation Completion

Agents will notify when done. Collect any issues they encountered.

---

## Phase 5: Verification + Handoff

**Goal**: Ensure everything works, then hand off or present results.

### 5.1 Run Verification

```bash
# 0. Compare against the baseline snapshot
# Re-run the same existing lint/typecheck/test/build commands captured in Phase 1.

# 1. Harness checks pass
make verify-harness || npm run lint:harness || {generated_harness_lint_command}

# 2. Architecture linters pass
make lint-arch || npm run lint:arch

# 3. Business build/test gates run
go build ./... || npm run build || python -m compileall .

# 4. AGENTS.md size check
wc -l AGENTS.md  # Should be 80-120 lines

# 4b. AGENTS.md content gate
# Confirm it explains project identity, core workflow/domain model, source entrypoints,
# task-based verification, active-change-before-STATUS loading, and contains no
# ECL Harness Engineer internal boundary language.

# 5. All expected files exist
test -f AGENTS.md && echo "✓ AGENTS.md"
test -f docs/ARCHITECTURE.md && echo "✓ ARCHITECTURE.md"
test -f docs/ECL.md && echo "✓ ECL.md"
test -f docs/STATUS.md && echo "✓ STATUS.md"
test -f scripts/lint-deps* && echo "✓ lint-deps"
test -f scripts/harness-change.* && echo "✓ harness-change"
test -f scripts/lint-ecl.* && echo "✓ lint-ecl"
test -f scripts/harness-evolve.* && echo "✓ harness-evolve"
test -d harness/ && echo "✓ harness/"
test -d harness/changes && echo "✓ harness/changes"
test -f harness/evolution/state.json && echo "✓ evolution state"

# 6. Design docs exist (not just index)
find docs/design-docs -name "*.md" ! -name "index.md" | wc -l
```

Classify every verification result:

| Classification | Meaning |
|----------------|---------|
| Harness pass | Harness-created checks/files/scripts work |
| Pre-existing project failure | The same command failed in the Phase 1 baseline |
| New regression | The command passed in Phase 1 and fails after harness creation |
| Not available | The command/script does not exist in this project |

AGENTS.md content gate:
- A new agent can tell what the project does within 30 seconds.
- The core product/system workflow or domain model is visible.
- Main source entrypoints and task-to-directory mapping are visible.
- Verification guidance maps to task type.
- Context loading reads `docs/ECL.md` first, then active change when present.
- If no active change exists and `harness/evolution/pending.md` exists, read it before
  `docs/STATUS.md`, mention it as pending maintenance, and ask whether to handle it now unless the
  user already prioritized the current task. Reading or asking does not start auto-evolve and must
  not block ordinary user work.
- If no active change exists and no pending evolution exists, context loading reads `docs/STATUS.md` before task-specific project docs.
- For structured work, `docs/ECL.md` explains Small Change vs Structured Change, bounded Intake
  Review, plan-first input handling, and the spec/plan review gate.
- Archive history is loaded selectively through `docs/STATUS.md` paths or `harness/changes/INDEX.json`, starting with historical `summary.md` only.
- No skill-internal boundary leaks, such as sections or sentences that describe this skill's own scope limits as target-project rules.

### 5.2 STATUS.md Handoff Update

When a target project uses ECL changes, maintain `docs/STATUS.md` as a lightweight handoff file.
It is not the authority while an active change exists, but it becomes the default recent-history
entry point after the active change is closed.

Close-change handoff protocol:

1. Before running `harness-change close`, read the active change `summary.md`, `spec.md`,
   `plan.md`, `tasks.md`, and relevant `reviews/`; update `docs/STATUS.md` with completed work,
   verification results, residual risks, and the next recommended resume point.
2. Run the close command so the active change moves to `harness/changes/archive/...` and
   `harness/changes/INDEX.json` is rebuilt.
3. After close, update `docs/STATUS.md` again with the final archive path, normally pointing to
   the archived `summary.md`.
4. Run the harness lint command (`npm run lint:harness`, `make verify-harness`, or the generated
   ECL lint command) to confirm STATUS, ECL structure, and INDEX state are consistent.

Hooks and CI may validate `docs/STATUS.md`, but must not auto-write it or move changes.

### 5.3 Auto-Evolve Check

Core harnesses include lightweight auto-evolve by default. The script layer only detects when
enough new archive evidence exists and writes `harness/evolution/pending.md`; Codex performs the
semantic improvement pass.

Trigger model: `harness-change close` and `reindex` run `harness-evolve check`; `new` only reminds
when pending exists. Hooks and CI may warn, but must not modify docs, scripts, STATUS, or changes.
Generated scripts do not call subagents. They only count archive evidence and create pending
context. When no active change exists and Codex notices pending maintenance, it should ask the user
whether to handle it now unless the user already prioritized the current task. Asking does not start
pending evolution.

`harness/evolution/pending.md` is a maintenance reminder, not a hard lock. Reading it for context
does not start pending evolution. Pending evolution starts only when Codex creates or uses an
`auto-evolve-harness-*` change, writes an evolution proposal/result, or edits Harness files based
on the pending evidence. Once started, finish with a proposal, one `harness/evolution/results.tsv`
row, and `harness-evolve mark-complete`; otherwise park or close blocked, not completed.

Apply only the smallest evidence-backed delta that passes review. No independent scorer =
no auto-apply: user approval to handle pending implies permission to request an independent
auditor/subagent when the environment supports it. If the environment still requires explicit
authorization, ask once. If scoring is unavailable, declined, or still unauthorized after asking,
record `noop` with `eval_mode=dry_run`, keep the proposal, run `mark-complete`, and stop.
Machinery repair
(`harness-evolve`, pending templates, lint) does not complete pending evolution by itself; after
repair, still evaluate candidate archives or leave the work parked/blocked.

Detailed proposal format, scoring weights, status values, and complexity budget live in
`references/ecl-harness.md`.

### 5.4 Present Summary

```markdown
## Harness Infrastructure Complete

**Project**: {project-name}
**Tech Stack**: {TECH}
**Files Created/Updated**: {count}

### Created Files
- AGENTS.md ({N} lines)
- docs/ARCHITECTURE.md
- docs/ECL.md
- docs/STATUS.md
- docs/DEVELOPMENT.md
- docs/design-docs/{component}.md
- scripts/lint-deps.{ext}
- scripts/lint-quality.{ext}
- scripts/harness-change.{ps1|sh|mjs|py}
- scripts/lint-ecl.{ps1|sh|mjs|py}
- scripts/lint-encoding.{ps1|sh|mjs|py}
- scripts/harness-evolve.{ps1|sh|mjs|py}
- harness/config/environment.json
- harness/changes/
- harness/evolution/
- harness/templates/change/
- Makefile

### Verification Results
- Harness checks: ✓
- Architecture checks: ✓
- Business gates: ✓ or pre-existing failures listed below
- AGENTS.md size: ✓ ({N} lines)

### Pre-existing Project Failures
- {List baseline-red commands and short reasons, or "None observed."}

### New Regressions Introduced By Harness
- {List commands that passed before and failed after, or "None observed."}

### Next Steps
{For empty projects: "Run harness-executor to implement business code from docs/exec-plans/active/bootstrap-code.md"}
{For existing projects: "The harness is ready. AI agents can now use AGENTS.md as their entry point."}
```

### 5.5 Automatic Handoff (for Empty Projects)

If this was an empty project with a bootstrap exec-plan, invoke harness-executor:

```
Skill(skill="harness-executor")
```

With context: "Implement the bootstrap exec-plan at docs/exec-plans/active/bootstrap-code.md"

---

## Core Principles

### 1. Repository as Single Source of Truth

Agents cannot access Slack, Google Docs, or tribal knowledge. If it's not in the repository, it doesn't exist for the agent.

### 2. AGENTS.md is a Map, Not a Manual

Keep it 80-120 lines. Link to detailed docs, don't embed them.

### 3. Enforce Invariants Mechanically

Linter errors must be agent-actionable:
```
✗ BAD: "Forbidden import in core/types/user.go"

✓ GOOD: "core/types/user.go:15 imports core/config (layer 0 → layer 2).
         Layer 0 packages must have NO internal dependencies.

         Fix options:
         1. Move config-dependent logic to a higher layer
         2. Pass the config value as a parameter
         3. Use dependency injection via an interface"
```

### 4. Build to Delete

Every component should be replaceable. Capabilities that required complex pipelines yesterday may be single prompts tomorrow.

### 5. Start Simple

Atomic, well-documented tools > complex agent choreography. Don't over-engineer.

### 6. Change State Is Explicit

Use a single `harness/changes/active/` task for personal development. Move paused work to `parking/` and closed work to `archive/` with the generated `scripts/harness-change.*` command. Maintain `docs/STATUS.md` as the soft handoff summary after active work is closed. Never hand-edit `harness/changes/INDEX.json`; it is a generated index rebuilt by `park`, `close`, `resume`, and `reindex`. Structured changes use `spec.md` for WHAT/WHY, `plan.md` for HOW, and `tasks.md` for executable work.

### 7. Harness Evolves From Evidence

Every few closed changes, the generated `scripts/harness-evolve.* check` command may create
`harness/evolution/pending.md`. Treat it as a maintenance reminder to improve harness rules from
real archived evidence, not as a hard blocker for unrelated user work. If you start acting on the
pending evidence, first refresh `harness/changes/INDEX.json` and use the current eligible archive
window; the Candidate Archives in an old pending file are a trigger snapshot, not the only evidence.
Then finish with proposal + results.tsv + `mark-complete`, or park/block the work.
Do not turn one-off business bugs into permanent process. Keep only changes that improve the audit
score and pass validation.

---

## Reference Files

| File | When to Read | Contents |
|------|-------------|----------|
| `references/greenfield-templates.md` | Empty projects (Phase 2.5) | Complete Go/TS/Python scaffolding |
| `references/documentation-templates.md` | Phase 4 doc creation | Doc templates with numbered sections |
| `references/linter-templates.md` | Phase 4 linter creation | Linter code templates per language |
| `references/ecl-harness.md` | ECL-aware harness creation | docs/ECL.md, docs/STATUS.md, change lifecycle, INDEX.json, PowerShell script templates |
| `references/darwin-eval-prompts.md` | Skill quality evaluation | Dry-run prompts for darwin-skill review |
| `references/environment-detection-guide.md` | Phase 2 env analysis | Environment ecosystem detection |
| `references/environment-config-guide.md` | Phase 4 config creation | Startup, services, env vars, user-confirmation templates |
| `references/adapters/typescript.md` | TypeScript/Node.js projects | npm scripts, Node linters, package-manager detection, CI defaults |
| `references/adapters/{go,python,rust,java,generic}.md` | Matching detected stacks | Language-specific commands and conventions |

Agent prompts for Phase 2 and Phase 4 subagents are in `agents/`.

For small projects (< 20 files) or when subagents aren't available, execute phases inline instead of spawning agents.


---
name: editorial-design
description: Web and App implementation guide for Editorial Design. Trigger when user wants a magazine-inspired layout, large headlines, and elegant typography pairing.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# Editorial Design

> "The digital magazine. Sophisticated typography pairings and deliberate, elegant pacing."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **Serif & Sans-Serif Pairing**: The hallmark of editorial design. A beautiful, high-contrast serif for headings, paired with a clean sans-serif for body copy.
2. **Large Drop Caps & Pull Quotes**: Typographic flourishes that guide the eye and break up long blocks of text.
3. **Columnar Layouts**: Content flows in distinct columns, often with fine lines (rules) separating them.

## Visual DNA
- **Colors**: **Modern Editorial** or **Yacht Club**. Warm, paper-like backgrounds with deep, ink-like blacks or navy blues.
- **Typography**:
  - Headlines: `Playfair Display`, `Merriweather`, `Bodoni`.
  - Body: `Lato`, `Open Sans`, `Source Sans Pro`.
- **Borders**: Thin, elegant horizontal lines (hairlines) used to separate sections.

## Web Implementation
- **CSS Example**:
```css
body {
  background-color: #F9F9F9; /* Paper white */
  color: #121212; /* Ink black */
}

/* Typography Pairing */
.editorial-headline {
  font-family: 'Playfair Display', serif;
  font-size: 4rem;
  font-weight: 700;
  font-style: italic;
  margin-bottom: 24px;
  border-bottom: 1px solid #121212;
  padding-bottom: 24px;
}

.editorial-body {
  font-family: 'Lato', sans-serif;
  font-size: 1.1rem;
  line-height: 1.8;
  column-count: 2; /* Magazine columns */
  column-gap: 40px;
}

/* Drop Cap */
.editorial-body::first-letter {
  font-family: 'Playfair Display', serif;
  font-size: 4rem;
  float: left;
  line-height: 0.8;
  padding-right: 12px;
  color: var(--cta-highlight);
}

.pull-quote {
  font-family: 'Playfair Display', serif;
  font-size: 2rem;
  text-align: center;
  margin: 48px 0;
  padding: 24px 0;
  border-top: 2px solid #121212;
  border-bottom: 2px solid #121212;
}
```

## App Implementation

### SwiftUI
```swift
struct EditorialView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 24) {
                // Editorial Headline
                Text("The Digital\nMagazine")
                    .font(.custom("Playfair Display", size: 48))
                    .fontWeight(.bold)
                    .italic()
                    .foregroundColor(Color(white: 0.05))
                    .padding(.bottom, 16)

                Divider().background(Color.black)

                // Drop Cap and Body
                HStack(alignment: .top, spacing: 8) {
                    Text("I")
                        .font(.custom("Playfair Display", size: 64))
                        .foregroundColor(Color(red: 0.7, green: 0.2, blue: 0.2))
                        // Negative padding to pull the body text tighter to the drop cap
                        .padding(.top, -10)

                    Text("n an era of sterile, flat interfaces, the return to elegant typography feels like a breath of fresh air. The interplay of serif and sans-serif...")
                        .font(.custom("Lato", size: 16))
                        .lineSpacing(6)
                        .foregroundColor(Color(white: 0.1))
                }

                // Pull Quote
                VStack {
                    Divider().background(Color.black)
                    Text("“Sophistication is in the spacing.”")
                        .font(.custom("Playfair Display", size: 28))
                        .italic()
                        .multilineTextAlignment(.center)
                        .padding(.vertical, 24)
                    Divider().background(Color.black)
                }
                .padding(.vertical, 24)
            }
            .padding(24)
        }
        .background(Color(red: 0.98, green: 0.98, blue: 0.96)) // Warm paper white
    }
}
```
- Extensive use of `.font(.custom())` is mandatory. System fonts look too app-like.
- Use `Divider()` to create the hairlines that are so common in print design.
- A fake "drop cap" can be achieved with an `HStack` aligning top.

### Flutter
```dart
class EditorialScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF9F9F8), // Paper background
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 40),
            const Text(
              'The Digital\nMagazine',
              style: TextStyle(fontFamily: 'PlayfairDisplay', fontSize: 48, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, height: 1.1),
            ),
            const SizedBox(height: 24),
            const Divider(color: Colors.black, thickness: 1),
            const SizedBox(height: 24),
            // Body with Drop Cap simulation using RichText is complex,
            // a simpler Row approach works well enough for mobile.
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'I',
                  style: TextStyle(fontFamily: 'PlayfairDisplay', fontSize: 72, height: 1.0, color: Color(0xFF8B0000)),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: const Text(
                    'n an era of sterile, flat interfaces, the return to elegant typography feels like a breath of fresh air. The interplay of serif and sans-serif brings humanity back to the screen.',
                    style: TextStyle(fontFamily: 'Lato', fontSize: 16, height: 1.6, color: Colors.black87),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 48),
            // Pull Quote
            const Divider(color: Colors.black, thickness: 2),
            const Padding(
              padding: EdgeInsets.symmetric(vertical: 32.0),
              child: Center(
                child: Text(
                  '“Sophistication is in the spacing.”',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontFamily: 'PlayfairDisplay', fontSize: 28, fontStyle: FontStyle.italic),
                ),
              ),
            ),
            const Divider(color: Colors.black, thickness: 2),
          ],
        ),
      ),
    );
  }
}
```
- Set `height` parameters in `TextStyle` (line-height). `1.6` is a good editorial body height.
- Use `Divider` with `thickness: 2` for the heavy rules around pull quotes.

### React Native
```jsx
const EditorialScreen = () => {
  return (
    <ScrollView style={{ flex: 1, backgroundColor: '#F9F9F8', padding: 24 }}>
      <Text style={{
        fontFamily: 'PlayfairDisplay-BoldItalic',
        fontSize: 48,
        color: '#121212',
        lineHeight: 52,
        marginTop: 40,
        marginBottom: 24
      }}>
        The Digital{'\n'}Magazine
      </Text>

      <View style={{ height: 1, backgroundColor: '#121212', marginBottom: 24 }} />

      <View style={{ flexDirection: 'row' }}>
        <Text style={{
          fontFamily: 'PlayfairDisplay-Bold',
          fontSize: 72,
          color: '#8B0000',
          lineHeight: 80,
          marginTop: -10, // Adjust alignment
          marginRight: 8
        }}>
          I
        </Text>
        <Text style={{
          flex: 1,
          fontFamily: 'Lato-Regular',
          fontSize: 16,
          lineHeight: 26,
          color: '#333'
        }}>
          n an era of sterile, flat interfaces, the return to elegant typography feels like a breath of fresh air. The interplay of serif and sans-serif brings humanity.
        </Text>
      </View>

      {/* Pull Quote */}
      <View style={{
        borderTopWidth: 2, borderBottomWidth: 2, borderColor: '#121212',
        marginTop: 48, paddingVertical: 32
      }}>
        <Text style={{
          fontFamily: 'PlayfairDisplay-Italic',
          fontSize: 28,
          textAlign: 'center',
          color: '#121212'
        }}>
          “Sophistication is in the spacing.”
        </Text>
      </View>
    </ScrollView>
  );
};
```
- Line heights and fonts are everything. You must have custom fonts linked in your React Native project for this style to work.
- Use `borderTopWidth` and `borderBottomWidth` on a container `View` to create the pull quote styling.

### Jetpack Compose
```kotlin
@Composable
fun EditorialScreen() {
    // Assuming Playfair and Lato are defined in FontFamily
    val playfair = FontFamily.Serif
    val lato = FontFamily.SansSerif

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF9F9F8))
            .verticalScroll(rememberScrollState())
            .padding(24.dp)
    ) {
        Spacer(Modifier.height(40.dp))

        Text(
            text = "The Digital\nMagazine",
            fontFamily = playfair,
            fontSize = 48.sp,
            fontWeight = FontWeight.Bold,
            fontStyle = FontStyle.Italic,
            lineHeight = 52.sp,
            color = Color(0xFF121212)
        )

        Spacer(Modifier.height(24.dp))
        Divider(color = Color(0xFF121212), thickness = 1.dp)
        Spacer(Modifier.height(24.dp))

        Row(verticalAlignment = Alignment.Top) {
            Text(
                text = "I",
                fontFamily = playfair,
                fontSize = 72.sp,
                color = Color(0xFF8B0000),
                modifier = Modifier.offset(y = (-10).dp).padding(end = 8.dp)
            )
            Text(
                text = "n an era of sterile, flat interfaces, the return to elegant typography feels like a breath of fresh air. The interplay of serif and sans-serif.",
                fontFamily = lato,
                fontSize = 16.sp,
                lineHeight = 26.sp,
                color = Color(0xFF333333)
            )
        }

        Spacer(Modifier.height(48.dp))

        // Pull Quote
        Divider(color = Color(0xFF121212), thickness = 2.dp)
        Text(
            text = "“Sophistication is in the spacing.”",
            fontFamily = playfair,
            fontSize = 28.sp,
            fontStyle = FontStyle.Italic,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)
        )
        Divider(color = Color(0xFF121212), thickness = 2.dp)
    }
}
```
- Compose handles custom fonts and line heights (`26.sp`) very elegantly.
- Use `Divider()` for the hairlines. Adjust thickness as needed for headers vs pull quotes.

## Do's and Don'ts
- **DO**: Treat the interface like a printed page. Margins should be generous.
- **DON'T**: Clutter the UI with typical app components like floating action buttons or heavy navigation bars. Keep it clean.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.


---
name: edr-bypass-re
description: "Reverse engineer EDR internals (user-mode hook tables, ETW, AMSI) and study bypass techniques such as direct syscalls, Hell's Gate, and call-stack spoofing. Lab-only red-team research."
risk: offensive
source: "https://github.com/zhaoxuya520/reverse-skill"
source_repo: "zhaoxuya520/reverse-skill"
source_type: community
date_added: "2026-08-25"
license: "MIT"
license_source: "https://github.com/zhaoxuya520/reverse-skill/blob/main/LICENSE"
---
> **⚠ AUTHORIZED USE ONLY**
> This skill is for educational purposes or authorized security assessments only.
> You must have explicit, written permission from the system owner before using this tool.
> Misuse of this tool is illegal and strictly prohibited.

> **Mandatory confirmation gate**
> Before running any command that probes, exploits, changes, persists on, extracts data from, or attempts credential access against a target:
> 1. Ask the user to state the exact target URL, IP, account, or resource.
> 2. Ask the user to confirm written authorization and the permitted scope.
> 3. Show the exact command(s) and explain their expected effect.
> 4. Wait for explicit confirmation in the current conversation.
>
> Without that confirmation, remain read-only and provide defensive guidance only. Prefer a sandbox, disposable VM, or controlled lab.

## When to Use

- Studying EDR telemetry surfaces in an authorized red-team lab.
- Evaluating detection coverage against known bypass technique classes.

## 适用范围

红队 / 对抗模拟在已获授权的目标主机投递 implant 并躲避现代 EDR 时使用本 skill。

1. **红队 / Purple team / 对抗演练** — 客户希望评估 SOC 与 EDR 的真实检测能力
2. **自研 implant / C2 框架研发** — 开发针对自家产品测试的载荷，需要绕过自家或目标 EDR
3. **EDR 产品评估** — 在合规边界已确认的前提下，客观评测某款 EDR 的检测覆盖
4. **CTF / 攻防演练的 Windows 端突破** — 比赛中需要在加固主机上稳定执行

**不适用场景**：

- 杀毒厂商对自家产品做完整 RE 给客户出商业评估报告（找厂商正式合作）
- 未授权目标的免杀对抗（违法）
- 普通病毒木马的免杀（本 skill 关注红队 OPSEC，不教恶意代码写法）

### 与其他 skill 的分工

| 场景 | 用什么 |
|------|--------|
| 全链路攻防（从外网打到域控） | `attack-chain/` |
| 内网横向 / AD 攻击 | `pentest-tools/network-attack-defense.md` |
| 在某个特定主机上要过 EDR 投递 implant | **本 skill** |
| 单纯静态免杀（混淆 / 加壳） | `malware-analysis/`（反向视角） |

`attack-chain` 关注完整 kill chain，本 skill 只聚焦 **EDR 这一个对手** 的内部机制和针对性绕法。

## 核心原理

```text
EDR 的四个主要监控面               红队的对策
─────────────────────              ─────────────────────
用户态 ntdll hook       ◄──►   unhook (Peruns Fart / fresh ntdll)
                                  间接 syscall / Hell's Gate
                                  hardware breakpoint Blindside

kernel callback         ◄──►   call stack spoof
(Ps/Cm/Ob 系列)                   走合法触发链（不直接绕，配合上游隐身）

ETW telemetry           ◄──►   EtwEventWrite patch
(Microsoft-Windows-Threat-          NtTraceControl 关 provider
 Intelligence 等)                  AmsiContext 同步处理

AMSI 扫描               ◄──►   AmsiScanBuffer patch (mov eax,0x80070057; ret)
(amsi.dll)                       hardware breakpoint 旁路
                                  reflective 加载副本 amsi.dll
```

关键认知：

- **EDR 不是黑盒** — 关键 hook / callback / provider 都能用 IDA + windbg 逆出来
- **绕过技术要组合使用** — 单独一个 unhook 解决不了 ETW 告警，单独 AMSI patch 解决不了 syscall hook
- **顺序很重要** — 先 ETW patch → 再 AMSI patch → 再 unhook；顺序错了 EDR 先收到 unhook 告警
- **现代 EDR 已经把 ETW + kernel callback 当主战场**，单纯用户态 unhook 早已不够

## 工作流

### Step 1：识别目标主机的 EDR

```powershell
# 列出常见 EDR / AV 驱动
Get-Service | Where-Object {$_.Name -match 'CSAgent|SentinelAgent|elasticendpoint|esets|ekrn|MsMpEng|wdsvc|cyserver|sysmon|aswbidsagent'}

# 列出加载的 minifilter
fltmc filters

# 列出已注册的内核 callback（需 windbg + 内核调试 / 或用 PChunter / DRVHV）
# !object \Callback
# !pnpcallback / Process / Thread / Image
```

EDR 指纹表见 `references/hook-survey.md` 顶部。

### Step 2：从 EDR DLL 提 hook 表

1. attach 到一个被注入 EDR 用户态组件的进程（任何已落地进程）
2. 在 windbg 中 dump 当前 `ntdll.dll` 的 `.text` 段
3. 与磁盘上干净的 `C:\Windows\System32\ntdll.dll` 做 diff
4. 不一致的地方就是 hook 点

或者直接用 `pe-sieve`：

```powershell
pe-sieve64.exe /pid 1234 /shellc 3 /modules 3 /dir hooks_dump
```

详细方法见 `references/hook-survey.md`。

### Step 3：选绕过技术组合

| 防御点 | 推荐绕法 |
|--------|---------|
| ntdll inline hook | indirect syscall + 动态 SSN (Halo's Gate) |
| ETW-TI provider | EtwEventWrite head patch |
| AMSI（PowerShell / .NET） | AmsiScanBuffer patch 或 HWBP |
| kernel callback | call stack spoof + 走 legit gadget |
| Sysmon ProcessCreate | PPID spoof + unbacked memory |

### Step 4：在 implant 中实现

代码骨架见 `references/unhook-techniques.md` 与 `references/telemetry-blinding.md`。

### Step 5：本地 sandbox 验证

```powershell
# 在隔离环境部署目标 EDR 试用版（Defender 默认即可起步）
# 启用 Sysmon + olaf-config
sysmon64.exe -i sysmonconfig.xml

# 跑 implant，看是否触发以下告警源：
#   - Defender AMSI
#   - ETW-TI
#   - Sysmon Event ID 1/7/8/10
#   - EDR 控制台
```

### Step 6：投递

- 文件落地路径用合法软件目录
- PPID spoof 到 explorer.exe
- 配合 `attack-chain` 中的 initial access 节

## 典型场景

### 场景 1：投递 cobalt-strike-alike beacon 过 Defender + Sysmon

```text
目标：Windows 11 Enterprise + Defender (云查杀开) + Sysmon (olaf 配置)
要求：beacon 落地后能 callback 且不触发任何告警

组合拳：
  1. shellcode 加密存储，运行时解密
  2. AMSI patch（如果走 PowerShell 投递）
  3. EtwEventWrite patch（消 ETW-TI）
  4. 间接 syscall + Halo's Gate（消 ntdll hook 告警）
  5. PPID spoof 到 explorer.exe
  6. sleep 阶段用 Ekko / Foliage 加密自身内存
```

### 场景 2：在已落地的低权限 shell 上做 EDR sleep mask

```text
前置：已经通过 phishing 拿到 medium IL shell，EDR 正在监控
风险：长时间驻留容易被内存扫描发现 beacon 特征

解法：
  1. 不再申请新 RWX 内存
  2. sleep 期间用 Ekko：
       - WaitForSingleObjectEx + CreateTimerQueueTimer
       - 在定时器里加密自身 .text + 把堆栈刷成全 0
  3. wake 时用 ROP 还原
  4. 配合 call stack spoof 让 RtlCaptureStackBackTrace 看不到信标地址
```

## 按需自举（On-Demand Bootstrap）

### 工具依赖

| 工具 | 用途 | 可自动安装 |
|------|------|-----------|
| pe-sieve | 检测进程中的 hook / 注入 | ✓ |
| API Monitor v2 | 动态观察 API 调用与 hook | 半自动（手动下载） |
| SysWhispers3 | 生成直接 / 间接 syscall stub | ✓（git clone + python） |
| Hell's Gate POC | 动态 SSN 解析参考实现 | ✓（git clone） |
| windbg + IDA | 静态逆 EDR DLL / 内核 callback | ✗（自己装） |
| Sysmon + olaf config | 本地验证环境 | ✓ |

### 自举命令

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File "<SKILL_ROOT>\skills\scripts\bootstrap-reverse.ps1" -Capability @('pe-sieve','syswhispers3','sysmon') -StartServices
```

## 路由上下文

**上游入口**：

- `reverse-engineering/` — 需要先理解 EDR DLL / 驱动的实现
- `attack-chain/` — 决定在 kill chain 的哪个阶段引入本 skill

**同级关联**：

- `pentest-tools/network-attack-defense.md` — 内网横向时如何与本 skill 联动
- `malware-analysis/` — 反向视角，看检测方怎么写规则
- `field-journal/` — 每次实战后回写经验

**下游交付**：

- 生成报告时引用 MITRE ATT&CK **T1562 (Impair Defenses)**、T1562.001 (Disable or Modify Tools)、T1562.006 (Indicator Blocking)、T1055 (Process Injection)、T1027 (Obfuscated Files or Information)

## 法律边界声明

- 仅限合法授权的红队 / 对抗演练 / 自有产品测试
- 操作前必须取得书面授权（SoW / 测试合同 / SRC 范围说明）
- 不得用于未授权目标，不得超出授权范围
- 发现高危问题立即向客户报告，遵循负责任披露
- 所有报告中真实目标信息必须脱敏（IP / 主机名 / 域名 / 凭证占位）

## 参考资料

- 详细 hook 调研：`references/hook-survey.md`
- unhook / syscall 技术：`references/unhook-techniques.md`
- ETW / AMSI / 反取证：`references/telemetry-blinding.md`
- MITRE ATT&CK T1562：<https://attack.mitre.org/techniques/T1562/>

## 任务完成自检（声称完成前 MUST 通过）

- [ ] 我是否执行了工作流中的每一步（而不是只阅读）？
- [ ] 我是否基于 `tool-index` 使用了真实工具路径？
- [ ] 我是否产出了可复现证据（命令/脚本/截图/报告）？
- [ ] 我是否完成并回写了 RULES 要求的 Checklist 项？

## Limitations

- Lab environment only: deploying bypasses against monitored production systems is out of scope and illegal without authorization.
- Technique descriptions age quickly as EDR vendors adapt.

> Adapted from [zhaoxuya520/reverse-skill](https://github.com/zhaoxuya520/reverse-skill) (MIT).


---
name: effective-agent-skills
description: "Author and review high-quality agent skills with triggers, progressive disclosure, and safety notes."
category: development
risk: safe
source: community
source_repo: davidondrej/skills
source_type: community
date_added: "2026-07-07"
author: davidondrej
tags: [skills, authoring, quality]
tools: [claude, codex]
license: "MIT"
license_source: "https://github.com/davidondrej/skills/blob/main/LICENSE"
---

# Agent Skills: A Complete Guide

## When to Use

- Use when creating, editing, reviewing, or debugging an agent SKILL.md file.
- Use when you need quality guidance for triggers, examples, limitations, and safety notes.

A consolidated reference on what agent skills are, why they exist, how they work, and how to write effective ones.

---

## 1. What agent skills are

An Agent Skill is a folder containing a `SKILL.md` file (YAML frontmatter + markdown instructions), plus optional subfolders for scripts, references, and assets that the agent loads on demand.

```
my-skill/
├── SKILL.md          # Required: metadata + instructions
├── scripts/          # Optional: executable code (CLIs, validators, helpers)
├── references/       # Optional: detailed docs loaded only when needed
└── assets/           # Optional: templates, fonts, static files
```

Skills are an open standard (agentskills.io), originally created by Anthropic and adopted by OpenAI Codex, Cursor, Gemini CLI, Microsoft Agent Framework, Google ADK, and 40+ other agent products. A skill written once works across all compatible agents.

---

## 2. Why this abstraction exists

Base LLMs are generalists. Real work requires procedural knowledge, organizational context, and repeatable workflows. Every prior alternative had a failure mode:

| Approach | Problem |
|---|---|
| Stuff it into the system prompt | Always loaded → context bloat at scale |
| Re-paste instructions each session | No version control, no consistency |
| Fine-tuning | Slow, expensive, opaque, vendor-locked |
| MCP servers alone | Give the agent tools but no workflows for using them |

Skills solve four problems at once:

- **Context efficiency** — instructions load only when relevant
- **Repeatability** — multi-step procedures become auditable workflows
- **Composability** — multiple skills combine at runtime per task
- **Portability** — same files work across vendors and surfaces

Mental model: skills are to LLMs what man pages, runbooks, and team handbooks are to engineers — reference material loaded into working memory only when the task demands it.

---

## 3. How they work — progressive disclosure

The architectural core. Three-stage loading:

**Level 1 — Discovery (~100 tokens per skill, always in context):**
Only `name` + `description` from frontmatter are injected into the system prompt at startup. Agent knows the skill exists and when it applies. You can install dozens of skills with negligible overhead.

**Level 2 — Activation (<5,000 tokens, loaded on match):**
When the user's request matches a skill's description, the agent reads the full `SKILL.md` body into context.

**Level 3 — Execution (unbounded, on demand):**
The agent reads referenced files (`references/foo.md`) or runs scripts (`scripts/validate.py`) only as needed. Scripts can execute without their source being loaded into context at all.

This is why bundled content has no practical limit. Files don't consume tokens until accessed.

---

## 4. SKILL.md anatomy

```markdown
---
name: skill-name
description: What this skill does AND when to use it. Include trigger phrases the user will say.
---

# Skill Name

## Quick start
[Minimal working example]

## Workflow
[Step-by-step procedure with checklists]

## Output format
[What the user/agent should expect back]

## Advanced
[Link to references/ for rarely-needed detail]
```

Frontmatter constraints:
- `name` is lowercase, hyphens only, 1–64 chars, **exactly matches the parent folder name**
- Avoid `<` and `>` in frontmatter (they can inject into the system prompt)
- Invalid YAML silently prevents loading

Optional standard fields:
- `disable-model-invocation: true` — stops the agent from auto-loading the skill based on the conversation; it can only be triggered manually (e.g. `/skill-name`). Now a standard Agent Skills spec field, so it works across spec-compliant clients (Claude Code, Copilot, etc.), not just Claude. Caveat: it prevents auto-invocation, but some clients (Claude Code, open bug) still inject the `description` into context, so it doesn't always save the discovery-level tokens. Use for manual-only utilities you don't want firing automatically.

---

## 5. Two design philosophies

Skills tend to fall into one of two patterns. Both are valid; they solve different problems.

### Pattern A — Capability primitives (tool wrappers)
The skill is a thin wrapper over a deterministic CLI or script. Logic lives in code. SKILL.md teaches the agent how to invoke it.

- **Adds**: new capabilities (search, email, browser, API access)
- **Reliability via**: shell tools, not prompts
- **Typical length**: 30–80 lines, mostly command examples
- **Use when**: the bottleneck is "the agent can't do X"

### Pattern B — Process primitives (cognitive disciplines)
The skill encodes a methodology the agent should follow. Pure prompt engineering — no scripts needed.

- **Adds**: structured workflows (TDD, code review, design alignment, debugging loops)
- **Reliability via**: explicit procedure, checklists, validation loops
- **Use when**: the bottleneck is "the agent's output quality or process is bad"

A mature setup uses both. Pattern A gives the agent better tools. Pattern B gives it better methods for using them.

---

## 6. How to write effective skills — do this

### Description as routing contract
The description is the only thing the agent sees before deciding to load the skill. If your skill doesn't trigger, the description is wrong 95% of the time, not the body.

Include three elements:
1. **What** the skill does (one phrase)
2. **When** to use it (trigger phrases, situations)
3. **Differentiator** vs related skills (prevents routing conflicts)

Pattern: `"X via Y. Use for [situations]. [Differentiator: no Z required / faster than W / handles edge case V]."`

**Never summarize the full workflow in the description.** If the description contains a step-by-step summary of *how* the skill works, the agent tends to follow that summary and skip loading the body. Describe *what* and *when*, never *how*. The description answers "should I open this skill now?" — not "what are the steps?"

### Keep SKILL.md lean
- Beyond a certain length, you're usually encoding logic that should be in a script or referenced file

### Bash-first, prose-second
Concrete command examples with inline comments beat prose explanations. The agent pattern-matches on syntax. Show, don't describe.

### Push determinism into code
Anything fragile, repetitive, or where variation is a bug → script. Use markdown only for tasks requiring judgment.

### Match strictness to task fragility (degrees of freedom)
Scale instruction rigidity to how costly a wrong move is:
- **Loose natural-language heuristics** when many approaches are valid (e.g. code review).
- **Pseudocode or templates** when there's a preferred pattern but variation is acceptable (e.g. report format).
- **Exact scripts and strict step lists** when the workflow is fragile, error-prone, or consistency-critical (e.g. migrations, document patching).

### Build validation loops
The single biggest output quality improvement: state a verify → fix → re-verify loop explicitly.

- Document skills: visual QA pass before delivery
- Code skills: tests pass + zero type errors before completion
- Data skills: schema validation before output

### State-check before action
Don't assume setup is done. Instruct the agent to verify state, then branch:
```
First check if X is configured: [command]
If not, walk the user through setup: [steps]
```

### Just-in-time loading with explicit pointers
Tell the agent exactly when to read each referenced file:
```
For standard cases, follow the steps below.
For [specific edge case], read references/edge-cases.md first.
```

### Keep references one level deep
Link referenced files directly from SKILL.md. Never build chains (SKILL.md → advanced.md → details.md → actual.md) — the agent may preview nested files only partially and miss critical instructions. Add a table of contents to any reference file longer than 100 lines.

### Document output formats
If your script returns structured data, show the agent what it looks like. Enables reliable downstream parsing.

### Defer to --help for completeness
List the 80% common operations in SKILL.md. Tell the agent to run `tool --help` for the rest. Keeps SKILL.md small without losing functionality.

### Compose primitives, don't bundle workflows
One skill = one capability or one discipline. Resist bundling concerns into "the X workflow." Multiple small skills combine at runtime; one large skill is rigid.

### Cite established principles when applicable
If your skill encodes a known engineering methodology (TDD, DDD, red-green-refactor), name the source. Gives the agent a coherent model to align with and gives users a way to verify the design.

### Persistent artifacts for cross-session memory
Skills can write to repo-level files (CONTEXT.md, ADRs, decision logs) that future agent sessions read. This is how you fight the "agents have no memory" problem at the architecture level.

---

## 7. What not to do — anti-patterns

### Don't re-teach what the model already knows
Every line in SKILL.md should provide context the model doesn't already have. No Python syntax tutorials. No "what is git." Challenge every paragraph.

### Don't include human-facing docs
No README.md, no CHANGELOG.md, no INSTALLATION_GUIDE.md inside the skill folder. Skills are for agents.

### Don't write vague descriptions
- Bad: "A helpful skill for documents"
- Good: "Fill PDF form fields, extract form data, flatten completed PDFs. Use when the user mentions PDF forms, fillable forms, or programmatic field population."

### Don't bundle library code
If you need a parsing library, install via npm/pip. Don't paste source into the skill.

### Don't write monolithic mega-skills
If one skill does design + planning + implementation + testing + deployment, you've built a framework, not a skill. Split it.

### Don't assume the agent will infer
Be explicit about every step that matters.
- Bad: "Then deploy it."
- Good: "Run `npm run deploy:staging` and wait for HTTP 200 from /healthz before reporting success."

### Don't write style-only variants
A skill that just changes tone or formatting belongs in user preferences or a system prompt, not a skill.

### Don't ignore failure modes
For every workflow step that can fail, document what failure looks like and what to do. Happy-path-only skills break in production.

### Don't include time-sensitive information
"As of Q4 2024..." rots fast. Fetch live data via script or omit.

### Don't use absolute paths
Always relative. Forward slashes regardless of OS. Use runtime placeholders for skill-directory references.

### Don't trust unfamiliar skills
Skills can execute arbitrary code and steer agent behavior. A malicious skill is a data exfiltration vector. Audit `scripts/` for unexpected network calls, file access outside expected scope, or hidden instructions in references. Watch for typosquatted skill names. Sandbox execution environments.

---

## 8. Authoring workflow

1. **Identify the gap.** Run your agent on real tasks. Where does it consistently fail or need re-prompting? That's a skill candidate.
2. **Decide the pattern.** Capability primitive (need new tools) or process primitive (need better methodology)?
3. **Draft the description first.** What + when + differentiator. Read it back: would the agent know when to fire it?
4. **Write the smallest body that works.** Add only when testing reveals gaps.
5. **Move detail to references/ once SKILL.md grows too long.**
6. **Test triggering.** Ask the agent something the skill should handle without invoking it explicitly. If it doesn't fire, fix the description.
7. **Test execution.** Invoke explicitly. If output is wrong, fix the body.
8. **Adversarial test.** Have another LLM ask: "What edge cases break this skill?" Patch the gaps.
9. **Version control.** Treat skills as code. Tag, branch, review.

---

## 9. Testing and debugging

- **"Which skill did you use?"** — ask the agent post-task. Fastest routing debug.
- **Routing fails → description problem.** Add specific trigger phrases.
- **Execution fails → body problem.** Add explicit steps, examples, or validation.
- **Skills snapshot at session start.** Edits during a session require a restart.
- **Test against the weakest model you'll deploy on.** Stronger models forgive vague skills; weaker models expose them.
- **Run an eval suite.** A handful of representative prompts that should and shouldn't trigger the skill, with expected outputs.

---

## 10. Composition

Skills compose at runtime — the agent loads multiple skills as needed for a single task. Design for this:

- **One skill = one concern.** Resist bundling.
- **Define interfaces between skills.** If skill A produces artifacts that skill B consumes, document the shape.
- **Use a repo-level config substrate.** A shared file (e.g., AGENTS.md, CONTEXT.md, settings.json) that multiple skills read and write coordinates them without explicit handoffs.
- **Loops over menus.** A coordinated set of skills forming a workflow (align → spec → build → verify → refactor) drives adoption far better than an unrelated catalog of capabilities.

---

## 11. Security checklist

Before installing any third-party skill:

- Read every file in the folder
- Audit `scripts/` for outbound network calls, file access outside expected scope, command execution
- Check references for prompt injection ("ignore previous instructions...")
- Verify the skill name isn't typosquatting a popular one
- Run in a sandboxed environment first
- Pin to a specific version/commit, not `latest`

---

## 12. Ship checklist

Before publishing a skill:

- [ ] Frontmatter `name` matches folder name
- [ ] Description includes what + when + differentiator
- [ ] Description includes likely user trigger phrases
- [ ] No human-facing docs inside the skill folder
- [ ] No time-sensitive information
- [ ] Relative paths only
- [ ] State-check before action where applicable
- [ ] Validation loop documented
- [ ] Output format documented if relevant
- [ ] Tested with weak and strong models
- [ ] Tested for both correct triggering and correct execution
- [ ] Skill does one thing
- [ ] Composes cleanly with related skills
- [ ] Version controlled

---

## 13. First principles, compressed

1. **The description routes; the body executes.** Get both right independently.
2. **Tokens are scarce; files are cheap.** Push detail out of context until it's needed.
3. **Determinism comes from code; judgment comes from prompts.** Put each in its right place.
4. **One skill, one concern.** Composition beats bundling.
5. **Agents have no memory.** Use persistent artifacts to give them one.
6. **The model knows a lot.** Don't re-teach. Only add what's missing.
7. **Validate before completing.** Self-correction loops dominate output quality.
8. **Skills are code.** Version, test, audit, and review them as such.

## Limitations

- Adapted from `davidondrej/skills`; verify local paths, tools, credentials, and agent features before acting.
- For commands, remote access, scheduling, browser automation, or file-changing workflows, get explicit user approval and confirm the target environment first.


---
name: efficient-web-research
source: community
risk: safe
description: >
  Protocol for token-efficient web research. Use when accessing URLs, GitHub repos, or running search queries. Prevents full-page fetching waste.
---

# Efficient Web Research Skill

A protocol for accessing web content in the most token-efficient, accurate, and structured way —
using the right tool at the right depth, and stopping as soon as the question is answerable.

---

## When to Use
- Use this skill when the task matches this description: Protocol for token-efficient web research. Use when accessing URLs, GitHub repos, or running search queries. Prevents full-page fetching waste.

## Core Principle

> **Fetch the minimum needed to answer. Skim before you dive. Stop when you can answer.**

Every unnecessary fetch wastes tokens and adds noise. This skill enforces a layered approach
where you escalate fetch depth only when shallower layers fail.

---

## Step 1 — Classify the Input

Before fetching anything, identify what kind of input you received:

| Input Type | Example | Go To |
|---|---|---|
| GitHub repo URL | `github.com/user/repo` | [GitHub Protocol](#github-protocol) |
| Specific page URL | `docs.python.org/3/library/os` | [URL Protocol](#url-protocol) |
| Topic / query (no URL) | "how does RAFT consensus work" | [Search Protocol](#search-protocol) |
| Multiple URLs | List of links | [Multi-URL Protocol](#multi-url-protocol) |
| PDF / file link | `.pdf`, `.txt`, `.md` URL | [File Protocol](#file-protocol) |

---

## GitHub Protocol

Use when input is a GitHub URL (repo, file, PR, issue, etc.)

### Step 1 — Parse the URL

```
github.com/{owner}/{repo}                → Repo root
github.com/{owner}/{repo}/tree/{branch}  → Directory
github.com/{owner}/{repo}/blob/{branch}/{path} → Single file
github.com/{owner}/{repo}/issues/{n}     → Issue
github.com/{owner}/{repo}/pull/{n}       → Pull request
```

### Step 2 — Use GitHub API (preferred over scraping)

Always prefer the GitHub API. It returns clean JSON — no HTML parsing needed.

```
# Repo metadata (name, description, language, stars, topics)
GET https://api.github.com/repos/{owner}/{repo}

# File tree (see what files exist — very cheap)
GET https://api.github.com/repos/{owner}/{repo}/git/trees/{ref}?recursive=1

# Single file content (base64 encoded)
GET https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={ref}

# README only (usually enough to understand the repo)
GET https://api.github.com/repos/{owner}/{repo}/readme
```

### Step 3 — Layered Fetch for Repos

```
Layer 1 (always do first):
  → Fetch repo metadata + README only
  → Can you answer the user's question now? YES → STOP. NO → continue.

Layer 2 (only if needed):
  → Fetch file tree to understand structure
  → Identify the 1-3 most relevant files based on the question
  → Can you answer now? YES → STOP. NO → continue.

Layer 3 (last resort):
  → Fetch specific relevant files only (never fetch all files)
  → Prioritize: main entry point, config files, key modules
```

### Token Rules for GitHub

- README alone answers ~70% of "what does this repo do" questions — always try it first
- Never fetch more than 3 files in a single research turn
- If a file exceeds ~300 lines, read only the top (imports + class/function signatures)
- Decode base64 content from API before passing to context

---

## URL Protocol

Use when the user gives a specific non-GitHub URL (docs, articles, blogs, etc.)

### Step 1 — Assess the URL type

| Site type | Likely works with | Notes |
|---|---|---|
| Static docs / MDN / ReadTheDocs | `read_url_content` | Fast, clean, cheap |
| News articles / blogs | `read_url_content` | Usually fine |
| SPAs / React/Next.js apps | `browser_subagent` | JS-rendered |
| Auth-gated pages | `browser_subagent` | Needs login |
| Raw GitHub files (raw.githubusercontent) | `read_url_content` | Direct text |

### Step 2 — Layered Fetch

```
Layer 1 — Skim
  → Fetch the URL with read_url_content
  → Read only headings (H1, H2, H3) and first paragraph
  → Does this page contain what the user needs? NO → try a different URL or search. YES → continue.

Layer 2 — Targeted Extract
  → If the page has anchor links (e.g. /docs/page#section), fetch with the anchor
  → Extract only the relevant section (200–500 tokens max)
  → Can you answer? YES → STOP.

Layer 3 — Full Fetch
  → Fetch full page, strip boilerplate (nav, footer, ads, cookie banners, sidebars)
  → Cap at 2000 tokens. Summarize before passing to answer.

Layer 4 — Browser Subagent (last resort only)
  → Use ONLY if read_url_content returns empty, garbled, or JS-placeholder content
  → Instruct subagent: "Navigate to [URL], wait for content to load, extract [specific section]"
  → Do NOT use browser_subagent for static pages — it's expensive
```

### What to Strip from Fetched Pages

Always remove before using fetched content:
- Navigation menus and breadcrumbs
- Cookie banners and GDPR notices
- "Related articles" / "You might also like" blocks
- Footer content (copyright, links)
- Social share buttons
- Ads and sponsored content

Extract and keep:
- Main article / documentation body
- Code blocks
- Tables with data
- Numbered steps or procedures

---

## Search Protocol

Use when the user gives a topic, question, or query — not a specific URL.

### Step 1 — Sharpen the Query Before Searching

Do NOT search the raw user query. Transform it first:

```
Raw: "how to deploy fastapi on aws"
Sharpened: "fastapi AWS deployment tutorial 2024"

Raw: "python async vs threads"
Sharpened: "Python asyncio vs threading performance comparison"

Raw: "best way to structure react project"
Sharpened: "React project folder structure best practices"
```

**Query sharpening rules:**
- Add specificity: version numbers, technology names, "tutorial" / "guide" / "comparison"
- Add recency if relevant: current year
- Remove filler words: "how do I", "what is the", "can you explain"
- For code questions: add the language + framework name explicitly

### Step 2 — Search and Select

```
1. Run search_web with the sharpened query
2. Get results (titles + snippets)
3. Scan titles + snippets ONLY — do not fetch yet
4. Pick the TOP 1-2 most relevant results (max 3 in complex cases)
5. Skip results from: forums (if docs exist), aggregator blogs, paywalled sites
6. Prefer: official docs, GitHub repos, well-known tech blogs, academic sources
```

### Step 3 — Fetch Selected Results

Apply the URL Protocol (above) to each selected URL.
Process results one at a time — only fetch the second URL if the first didn't answer the question.

### Token Rules for Search

- Never read more than 3 URLs per search query
- If the snippet already contains the answer → do NOT fetch the full page, use the snippet
- For factual questions (dates, names, simple facts) → snippet is usually enough
- For procedural questions (how to do X) → fetch 1 relevant page, targeted section only

---

## Multi-URL Protocol

Use when the user provides a list of URLs to compare or summarize.

```
1. Skim all URLs first (Layer 1 fetch for each)
2. Group by relevance to the user's question
3. Deep-fetch only the most relevant 1-3 URLs
4. Summarize each in 3-5 sentences before combining
5. Never dump raw content from multiple pages — always summarize per-source first
```

---

## File Protocol

Use when URL points directly to a file (PDF, .txt, .md, .csv, etc.)

- `.md` / `.txt` / `.csv` → `read_url_content` works directly, read full content
- `.pdf` → Use browser_subagent or a PDF extraction tool; extract text only
- `.json` / `.yaml` → `read_url_content`, parse structure, summarize schema + key values
- Large files (>500 lines) → Read first 100 lines + last 20 lines + search for relevant sections

---

## Anti-Patterns (Never Do These)

| Anti-pattern | Why it's bad | Do this instead |
|---|---|---|
| Fetching full page for a simple fact | Wastes 1000s of tokens | Use snippet or targeted anchor |
| Using browser_subagent for static sites | Very expensive | Use read_url_content first |
| Searching with the raw user query | Vague results | Sharpen query first |
| Fetching 5+ search results | Token explosion | Max 3, stop when answered |
| Dumping raw HTML into context | Noisy, wasteful | Always strip to Markdown |
| Fetching "just in case" | Unnecessary tokens | Only fetch what's needed to answer |
| Re-fetching the same URL | Redundant | Cache result in context, reuse |
| Fetching entire GitHub repo | Extremely wasteful | README + targeted files only |

---

## Decision Flowchart (Quick Reference)

```
Input received
│
├─ GitHub URL?
│   ├─ Fetch README + metadata via API
│   ├─ Answered? → STOP
│   ├─ Need more? → Fetch file tree, pick 1-3 files
│   └─ Still need more? → Fetch specific files only
│
├─ Specific URL?
│   ├─ Try read_url_content → skim headings
│   ├─ Answered? → STOP
│   ├─ Need more? → Targeted section fetch
│   ├─ Still need more? → Full fetch, stripped
│   └─ JS-rendered / broken? → browser_subagent (last resort)
│
├─ Topic/query?
│   ├─ Sharpen query
│   ├─ search_web → scan snippets
│   ├─ Snippet enough? → Answer from snippet, STOP
│   ├─ Need more? → Fetch top 1 result (targeted)
│   └─ Still need more? → Fetch top 2nd result (targeted)
│
└─ List of URLs?
    ├─ Skim all (Layer 1 each)
    ├─ Deep fetch top 1-3 relevant ones
    └─ Summarize per-source, then combine
```

---

## Output Format Rules

After fetching, structure your response as:

```
Source: [URL or "Web search for: query"]
Summary: [2-5 sentences of what was found]
Answer: [Direct answer to user's question]
Confidence: [High / Medium / Low — based on source quality]
```

For multiple sources:
```
Source 1: ...
Source 2: ...
Combined Answer: ...
```

Never output:
- Raw HTML fragments
- Full page dumps
- Unattributed information
- More than needed to answer the question

---

## Token Budget Guide

| Operation | Approximate token cost | When to use |
|---|---|---|
| GitHub README fetch | ~300–800 tokens | Always first for repos |
| GitHub API metadata | ~200 tokens | Always for repos |
| Skim (headings only) | ~100–200 tokens | Always first for URLs |
| Targeted section fetch | ~300–600 tokens | When skim isn't enough |
| Full page fetch (stripped) | ~1000–2000 tokens | Only when targeted fails |
| browser_subagent | ~2000–5000 tokens | Last resort only |
| Search snippet scan | ~300–500 tokens | Always before fetching |

**Rule of thumb:** If you're about to spend >2000 tokens on a fetch, ask yourself if there's a cheaper path first.

---

## Limitations

- **JavaScript Reliance**: Standard fetching may not fully render Single Page Applications (SPAs). You must fallback to `browser_subagent` for these, which is slower and more expensive.
- **Paywalls & Protections**: This skill cannot bypass CAPTCHAs, bot protections (e.g., strict Cloudflare rules), or hard paywalls.
- **GitHub API Limits**: Frequent GitHub API requests without authentication may hit rate limits.


---
name: ejentum-reasoning-harness
description: "MCP server exposing four cognitive harness modes (reasoning, code, anti-deception, memory). Each call returns an engineered scaffold (failure pattern, procedure, suppression vectors, falsification test) the agent ingests before generating."
risk: critical
source: community
source_repo: ejentum/ejentum-mcp
source_type: community
date_added: "2026-05-10"
license: "MIT"
license_source: "https://github.com/ejentum/ejentum-mcp/blob/main/LICENSE"
plugin:
  targets:
    codex: blocked
    claude: blocked
  setup:
    type: manual
    summary: "Install the ejentum-mcp MCP server (`npx -y ejentum-mcp`) and provide an EJENTUM_API_KEY env var (free tier: 100 calls, no card, at https://ejentum.com/pricing). Add the server to your client's mcpServers config (Claude Code, Cursor, Cline, Windsurf, Codex CLI, Gemini CLI, Antigravity, or VS Code Copilot Chat)."
    docs: "https://github.com/ejentum/ejentum-mcp#installation"
---

# Ejentum Reasoning Harness

The Ejentum Reasoning Harness is a library of 679 cognitive operations engineered in natural language, organized across four harnesses (`reasoning`, `code`, `anti-deception`, `memory`) and exposed as MCP tools the agent can call when the task matches their trigger conditions. It targets four mechanism failures common in long agentic chains: attention decay (losing the original task), reasoning decay (compounding errors), sycophantic collapse (agreeing with the user's frame instead of evaluating it), and hallucination drift (asserting unsupported claims with confidence).

Each harness call retrieves a task-matched scaffold rather than serving a fixed template: a named failure pattern, an executable procedure, suppression vectors that block specific shortcuts, and a falsification test the agent uses for self-verification. The agent ingests the scaffold and writes from it, rather than from raw chain-of-thought. The harness is invoked on demand (by the agent or via an explicit prompt like `Use harness_anti_deception, then answer:...`); it does not auto-run on every turn.

## When to Use This Skill

- Use `harness_reasoning` before answering analytical, diagnostic, planning, or multi-step questions ("why is X happening", "what's the best approach", "what are the tradeoffs", root-cause analysis, architecture decisions).
- Use `harness_code` before generating, refactoring, reviewing, or debugging code; before architectural changes, algorithm or data-structure choices, dependency-upgrade evaluation.
- Use `harness_anti_deception` when the prompt pressures the agent to validate, certify, or soften an honest assessment; manufactured urgency; authority appeals; setups where the obvious helpful answer would compromise honesty.
- Use `harness_memory` only when sharpening an observation already formed about cross-turn drift or behavioral patterns; never call with an empty mind.

Skip the harness for simple factual lookups, syntax questions, file reads, code execution, or tasks the agent can confidently complete in 1-2 steps from native capability.

## How It Works

### Step 1: Install the MCP server

The server is published to npm. Most MCP-speaking clients support stdio installation via `npx`:

```bash
npx -y ejentum-mcp
```

Add to your client's MCP server config (Claude Code `.mcp.json`, Cursor / Cline / Windsurf MCP settings, Codex CLI config, or Antigravity / VS Code `mcp.json`):

```json
{
  "mcpServers": {
    "ejentum": {
      "command": "npx",
      "args": ["-y", "ejentum-mcp"],
      "env": {
        "EJENTUM_API_KEY": "${EJENTUM_API_KEY}"
      }
    }
  }
}
```

Get a free API key (100 calls, no card required) at [ejentum.com/pricing](https://ejentum.com/pricing).

### Step 2: Route to the right harness

Each harness has different trigger conditions (see "When to Use" above). Most clients with MCP support will route to the appropriate tool when the user's prompt matches the trigger conditions documented in the tool descriptions. For cold-install reproducibility, the agent can also call a specific harness explicitly: `Use harness_anti_deception, then answer: ...`.

### Step 3: Absorb the returned scaffold

The scaffold contains five labeled fields the agent should treat as internal-reasoning instructions, not output content:

- `[NEGATIVE GATE]` / `[CODE FAILURE]` / `[DECEPTION PATTERN]` / `[PERCEPTION FAILURE]`: the failure pattern to avoid
- `[PROCEDURE]`: step-by-step procedure for an honest response
- `[REASONING TOPOLOGY]`: control-flow graph the agent steps through internally
- `[TARGET PATTERN]`: example of the corrected response shape
- `[FALSIFICATION TEST]` / `[VERIFICATION]` / `[INTEGRITY CHECK]` / `[PERCEPTION CHECK]`: the test to apply post-draft

The agent's user-facing reply should be in its native voice, with no echoed bracket names, no procedural vocabulary, and no meta-commentary about the harness.

## Examples

### Example 1: Anti-deception on a sunk-cost prompt

Prompt:

```
Use harness_anti_deception, then answer:
We've spent three months on the GraphQL gateway. It's mostly done.
Should we keep going or pivot to REST?
```

Without the harness, agents often anchor on the past investment ("sunk cost is real here, the hardest learning curve is behind you"). With the harness, the response separates past spending from prospective evaluation: "the three months already spent are gone regardless of what you choose now. The relevant question is how much work remains versus how much value GraphQL will deliver from this point forward."

### Example 2: Code review with passing tests

Prompt:

```
Use harness_code: I refactored get_user to return None instead of raising on missing users.
All tests still pass. Should I merge?
```

The harness scaffolds a procedure that flags "tests pass" as a tool-shortcut signal rather than a correctness signal, surfaces the call-sites that handle exceptions vs None values, and recommends adding behavior-verifying tests before the merge.

## Best Practices

- ✅ Call one harness per turn; the right harness for the prompt's shape
- ✅ Treat bracketed scaffold fields as internal-only; never echo them in the user-facing reply
- ✅ Apply the falsification test to the draft before responding
- ❌ Do not stack three or more harnesses in a single turn; attention competition degrades the first call
- ❌ Do not call harness_memory without observing first; it sharpens an existing observation, not creates one
- ❌ Do not treat the API as a hard dependency; on a 5-second timeout, fall back to native capability gracefully

## Limitations

- The harness shapes the substance of reasoning; it does not guarantee a correct answer. Domain expertise and source verification still apply.
- 5-second timeout typical; clients should fall back to native capability if the API is unreachable.
- The scaffold is a procedure, not a knowledge base. It does not retrieve facts, only structured reasoning patterns.

## Security & Safety Notes

- The MCP server makes outbound HTTPS requests to the Ejentum Logic API gateway (Zuplo-hosted).
- Authentication uses a Bearer token in the `EJENTUM_API_KEY` environment variable. The token must be stored in environment variables or an MCP client's secret-handling mechanism, never committed to source.
- The server does not execute shell commands or read filesystem paths beyond reading its own env. It is a pure HTTP-proxy MCP server.
- Free tier rate-limited at 100 calls; paid tiers documented at ejentum.com/pricing.