[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AVJHNX160RWBY0KHE1WR4K":3,"skill-same:01M7AVJHNX160RWBY0KHE1WR4K":85},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7AVJHNX160RWBY0KHE1WR4K","ai-agent-engineer",null,"Architect, scope, compose, and evaluate production-grade autonomous systems using the 4-Level Ladder, 60 architectural patterns, and substrate harness isolation. Do not use for simple deterministic scripts or single-turn prompts.","SpectreDeath\u002FBrain-Harness","SpectreDeath","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F207463416?v=4","01M7AVGR1D4X8ADT47APKGVH2Z","JL","01M7AVGR2HSGD23BA5DBTJJTVN",0,"MIT","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: ai-agent-engineer\ndescription: Architect, scope, compose, and evaluate production-grade autonomous systems using the 4-Level Ladder, 60 architectural patterns, and substrate harness isolation. Do not use for simple deterministic scripts or single-turn prompts.\n---\n\n# AI Agent Engineer: Autonomous Systems Architecture & Design\n\n`ai-agent-engineer` is the architectural and operational skill for engineering production-grade autonomous agentic systems. Distilled from Vahe Aslanyan's (*The AI Agent Engineer's Guide: 60 Patterns for Building Autonomous Systems*, LUNARTECH) foundational pattern catalog and Chidiebere Njoku's dynamic model routing architecture, this skill enforces rigorous engineering discipline over generative AI hype.\n\nRather than treating agents as prompt-engineering novelties or personality wrappers, `ai-agent-engineer` enforces the **Capability-Composition Frontier**:\n1. **The Four-Level Ladder**: Always pick the lowest level that solves the problem (Static Prompt -> Deterministic Workflow -> Bounded Agent -> Full Agent).\n2. **Deterministic Harness, Stochastic Policy**: Wrap probabilistic LLM calls in invariant code boundaries with structural input\u002Finstruction separation.\n3. **Session-Level Evaluation**: The fundamental unit of evaluation for an agent is the *session*, not the prompt.\n4. **Corrigibility by Design**: Every action-taking agent must maintain an explicit, sub-second human off-switch and transactional rollback semantics.\n\n---\n\n## The 5-Stage Operational Progression\n\n```\n[1. Qualify & Ladder] → [2. Capability Profile & Model Routing] → [3. Substrate & Structural Gates] → [4. Bounded Context & Loops] → [5. Session Eval & Corrigibility]\n```\n\nSee [CARD.md](CARD.md) for the companion quick-reference card and diagnostic checklist.\nSee [config.default.yaml](config.default.yaml) for operational step budgets, token thresholds, and model tier specifications.\nSee [references\u002Fpatterns-catalog.md](references\u002Fpatterns-catalog.md) for the catalog of all 60 canonical patterns across the 8 capabilities.\nSee [references\u002Ffour-level-ladder-guide.md](references\u002Ffour-level-ladder-guide.md) for in-depth level selection heuristics.\nSee [references\u002Ffailure-modes-antidotes.md](references\u002Ffailure-modes-antidotes.md) for the 5 canonical failure modes and structural antidotes.\nSee [references\u002Fmodel-routing-lifecycle.md](references\u002Fmodel-routing-lifecycle.md) for the 3-tier dynamic model switching guide.\n\n---\n\n## 1. Pre-Agent Qualification & The Four-Level Ladder\n\nBefore authoring code or selecting patterns, evaluate the candidate problem against the **Four-Level Ladder**:\n\n| Level | Architecture | Best Suited When... | Typical Examples |\n|---|---|---|---|\n| **Level 1** | **Static Prompt** | Single model call, static prompt template, no state-changing tools, no memory. Input in, output out. | Summarization, format translation, classification, extraction from known shapes. |\n| **Level 2** | **Deterministic Workflow** | Fixed sequence of steps (Step A -> Step B -> Step C). Content varies, but flow is invariant. Fits on a napkin. | Content pipelines (research -> draft -> cite), data enrichment, ETL extraction. |\n| **Level 3** | **Bounded Agent** | State-dependent next actions, small toolset (\u003C 15 tools), small step budget (\u003C 20 steps), easily reversible actions. | Ticket triage with tools, SQL QA against known schema, document inspection with standard ops. |\n| **Level 4** | **Full Agent** | Goal held across long horizons, dynamic recovery from unexpected failures, multi-turn tool interaction. | Autonomous software migration, end-to-end repository refactoring, deep investigative research. |\n\n> **Heuristic**: *The right level is the lowest one that solves the problem.* If Level 1 or Level 2 works, building an agent is pure overhead.\n\n### Executable Seam: `scripts\u002Fladder_evaluator.py`\nRun the automated ladder evaluator to classify tasks and validate the 5 Pre-Flight Questions:\n```python\nfrom scripts.ladder_evaluator import LadderEvaluator, TaskScopingInput\n\ntask = TaskScopingInput(\n    task_description=\"Triage customer support tickets and execute database lookups\",\n    candidate_tools=[\"lookup_customer\", \"search_kb\", \"update_ticket\"],\n    estimated_steps=5,\n    state_dependent_decisions=True,\n    success_metric=\">= 90% resolution rate without escalation\",\n    worst_case_blast_radius=\"Bounded to test sandbox; no customer emails dispatched\",\n    cost_ceiling_per_session=0.25,\n    evaluation_harness_description=\"Replay of 50 labeled customer support sessions\",\n    off_switch_description=\"Instant SIGINT with transactional ticket rollback in \u003C 200ms\",\n)\nresult = LadderEvaluator.evaluate(task)\nassert result.approved_for_implementation is True\n```\n\n> **Completion Criterion**: Documented level assignment (Level 1–4) and all 5 pre-flight scoping questions answered with quantitative metrics via `LadderEvaluator`.\n\n---\n\n## 2. Capability Profiling & Dynamic Model Routing\n\nFormulate a one-page **Capability Profile** selecting exact architectural patterns from the 8 core capabilities:\n\n### The 8 Capabilities Matrix\n- **Perception (Patterns 1–7)**: Turning raw signals into typed percepts (*Multimodal Grounding, Document Layout, Temporal Sensor-Fusion, Anomaly-Spotter, Visual Decomposition, Ambient Context, Schema-Inference*).\n- **Reasoning (Patterns 8–15)**: Inferring beyond the given (*CoT Auditor, Counterfactual Reasoner, Analogical Mapping, Constraint-Satisfaction Solver, Causal Graph Builder, Symbolic-Neural Bridge, Probabilistic Belief Updater, Self-Consistency Voter*).\n- **Planning (Patterns 16–22)**: From goal to sequenced actions (*Hierarchical Decomposer, ReAct Loop, Tree-of-Thought Explorer, Plan-Then-Execute, Adaptive Replanner, Resource-Aware Scheduler, Backward Goal-Regression*).\n- **Memory (Patterns 23–29)**: Persistence across time (*Episodic Buffer, Semantic Memory Curator, Working-Memory Manager, Forgetting-Policy, Memory-of-Self, Vector-Store Curator, Persistent Identity*).\n- **Tool Use (Patterns 30–37)**: Reaching outside the model (*Tool Selector, API-Schema Adapter, Code Sandbox, Shell-Operator, Browser-Driver, DB Query Synthesizer, File-System Curator, Side-Effect Auditor*).\n- **Coordination (Patterns 38–45)**: Multi-agent and human synchronization (*Router\u002FDispatcher, Debate Moderator, Consensus-Builder, Pipeline Orchestrator, Human-in-the-Loop Liaison, Negotiation, Auctioneer, Supervisor-Worker*).\n- **Learning (Patterns 46–52)**: Improving through experience (*Feedback Loop, Reflection, Skill-Library Builder, Curriculum Designer, Few-Shot Prompt Tuner, Distillation, Active Learner*).\n- **Alignment (Patterns 53–60)**: Behaving by design (*Constitution-Bound, Refusal Calibrator, Provenance Tracker, Red-Team Auditor, Privacy-Preserving, Explainer, Drift Detector, Off-Switch-Compatible*).\n\n### Executable Seam: `scripts\u002Fcapability_profiler.py`\nValidate the capability profile against architectural composition invariants:\n```python\nfrom scripts.capability_profiler import CapabilityProfiler, CapabilityProfile\n\nprofile = CapabilityProfile(\n    agent_name=\"ticket_triager\",\n    target_level=3,\n    declared_patterns=[17, 25, 30, 37, 53, 60],\n    tools_count=6,\n    has_external_mutations=True,\n    estimated_session_steps=8,\n)\nreport = CapabilityProfiler.validate_profile(profile)\nassert report.valid is True\n```\n\n### Executable Seam: `scripts\u002Fdynamic_model_router.py`\nOperationalize Chidiebere Njoku's 3-Tier model routing architecture:\n```python\nfrom scripts.dynamic_model_router import DynamicModelRouter\n\ncomplexity = DynamicModelRouter.analyze_complexity(\n    prompt=\"Explain this database schema and propose index optimizations\",\n    candidate_tools=[\"sql_explain\"]\n)\ndecision = DynamicModelRouter.route_model(complexity, cost_ceiling=0.50)\nexec_res = DynamicModelRouter.simulate_fallback_chain(decision)\nassert exec_res.status == \"SUCCESS\"\n```\n\n> **Completion Criterion**: 1-Page Capability Profile validated via `CapabilityProfiler` and 3-tier dynamic model routing confirmed via `DynamicModelRouter`.\n\n---\n\n## 3. Substrate Isolation & Structural Guardrails\n\nWrap the stochastic model policy within a deterministic software harness. Every production agent framework converges on five abstractions:\n1. **Client**: The transport layer to the model provider, handling retries, timeouts, and streaming.\n2. **Registry**: The catalog of typed tools, schemas, and parameter validators.\n3. **Prompt**: The per-step context assembler combining invariants, role instructions, working memory, and tool observations.\n4. **Memory**: The persistence substrate across turns and sessions.\n5. **Loop**: The deterministic state machine driving observation -> thought -> action execution.\n\n### Structural Guardrails\n- **Constitutional Gating (Pattern 53)**: Intercept all proposed tool invocations inside a pre-execution hook. Assert tool call arguments against strict negative boundaries (e.g. no destructive deletes, no outbound network calls to unauthorized IPs). If violation detected, reject the tool call *before* execution.\n- **Side-Effect Auditing & Transactional Rollback (Pattern 37)**: Record every tool invocation into an append-only transaction log. On tool error or agent failure, execute automated rollback handlers (`rollback_transaction()`) to restore filesystem and database state.\n- **Structural Input\u002FInstruction Separation**: Wrap user-supplied data and retrieved documents in structured data containers (e.g. XML tags `\u003Cuser_document>...\u003C\u002Fuser_document>`). Instruct policy that instructions inside data blocks are non-executable content.\n\n> **Completion Criterion**: Deterministic harness abstractions established, Constitutional pre-execution gates active, and transactional rollback mechanisms declared.\n\n---\n\n## 4. Context Boundedness & Execution Loops\n\nUnbounded context growth and infinite loops are fatal production failure modes. Enforce rigid boundaries:\n\n### Working Memory Management (Pattern 25)\n- **Token Budget Allocation**: Dedicate max 60% of model context window to conversation trajectory. Reserve 20% for system invariants\u002Ftools, and 20% for output generation.\n- **Progressive Middle-Out Tool Pruning**: If tool observation exceeds token thresholds (e.g. > 2,000 tokens), retain first 50 lines (header context) and last 50 lines (tail results), replacing the middle with structured truncation summaries.\n- **AST Repo Map \u002F Graph Injection**: Never dump entire codebases or directories into context. Inject PageRanked structural skeleton maps showing only relevant function signatures and types.\n\n### Bounded ReAct Loop (Pattern 17) & Adaptive Replanning (Pattern 20)\n- **Hard Step Caps**: Set a mandatory step ceiling (N_max \u003C= 20 for Level 3; N_max \u003C= 40 for Level 4).\n- **Progress Delta Assertion**: At each iteration k, compute state distance to goal. If state delta delta_S = 0 for 3 consecutive steps (repeated tool calls with identical parameters or no new percepts), trigger **Adaptive Replanner (Pattern 20)** to reformulate strategy or halt.\n\n> **Completion Criterion**: Active context budget bounded under 60% of window across 50 steps; ReAct loop instrumented with step caps and progress delta checks.\n\n---\n\n## 5. Session-Level Evaluation & Production Corrigibility\n\nStatic prompt evaluation is insufficient. Validate the agent across the **Four Evaluation Surfaces**:\n1. **Static Evaluation**: Benchmark against labeled inputs measuring pass rate, latency, and token cost.\n2. **Trajectory Replay Evaluation**: Replay historical multi-turn sessions with frozen tool outputs to detect behavioral regressions in tool-selection order.\n3. **Perturbation & Noise Testing**: Inject unexpected tool errors, malformed JSON, and network timeouts to assert graceful recovery without crash.\n4. **Live Shadowing**: Run candidate agent policy in parallel with production systems, comparing proposed actions without executing side effects.\n\n### The 5 Canonical Failures Audit\nBefore production deployment, verify immunity against the 5 canonical failure modes:\n1. *Looped Reasoning* -> Verified step cap and stagnation replanner active.\n2. *Tool Spoofing* -> Verified structural data separation and Constitutional action validation.\n3. *Context Exhaustion* -> Verified per-step working memory compaction and middle-out pruning.\n4. *Goal Drift* -> Verified explicit immutable goal anchor preserved across all steps.\n5. *Silent Success on Wrong Task* -> Verified dual-check reflection comparing final deliverable to original intake request.\n\n### Corrigibility & Off-Switch Invariant (Pattern 60)\n- Expose an immediate human interrupt signal (`SIGINT`, web UI abort button, or CLI kill command).\n- On abort signal, the agent proactor must drain subprocess pipes, serialize in-flight working memory to disk, trigger transactional cleanup, and exit cleanly within \u003C= 500 ms.\n\n> **Completion Criterion**: 4-surface evaluation suite passing baseline thresholds; zero unhandled canonical failure modes; sub-second off-switch verified.\n\n---\n\n## The Visual Brief Specification\n\nWhen formulating architectural proposals or major agent refactors, generate an interactive HTML Visual Brief:\n1. **Target Path**: Render to `%TEMP%\\ai-agent-engineer-\u003Ctimestamp>.html`.\n2. **Visual Assets**: Include Tailwind CSS and Mermaid.js diagrams illustrating the proposed agent topology, capability profile, and fallback chains.\n3. **Diagnostic Tables**: Embed the 5 pre-flight questions scorecard, the capability contract table, and the failure mode antidote matrix.\n4. **Delivery**: Verify file generation and deliver a clickable `file:\u002F\u002F\u002F` link to the user.\n\n---\n\n## Mandatory Checkpoint Gate\n\nBefore executing irreversible structural changes, external side effects, or deploying autonomous agents:\n1. **Present Implementation Plan**: Author a comprehensive plan artifact detailing the target capability profile, model routing tiers, and blast-radius mitigations.\n2. **Set Feedback Header**: Set `RequestFeedback: true` in artifact metadata.\n3. **Human Sign-Off Invariant**: STOP and wait for explicit human review and approval before executing transactions.\n\n---\n\n## Anti-Patterns\n\n- **Agent-as-Marketing** — Building an autonomous agent for PR or trend-following when a static prompt or deterministic script solves the problem with higher reliability.\n- **Multi-Agent Swarm Vanity** — Deploying complex multi-agent communicating swarms where agents spend the majority of token budgets exchanging polite coordination messages.\n- **Prompt-Only Guardrails** — Relying on system prompt instructions like \"never delete user data\" instead of code-level constitutional interceptors and OS sandboxes.\n- **Context Flooding Memory** — Dumping entire unpruned conversation logs and raw tool observations into prompt context until model degradation occurs.\n- **Unbounded Autonomy** — Running agent loops without hard step caps, monetary ceilings, or progress delta monitoring.\n- **Single-Model Dependency** — Coupling production agent operations to a single frontier model provider without multi-tier fallback chains and circuit breakers.\n- **Missing Off-Switch** — Deploying autonomous action-taking systems without sub-second operator kill-switches and transactional rollback semantics.\n","# AI Agent Engineer: Autonomous Systems Architecture & Design\n\n`ai-agent-engineer` is the architectural and operational skill for engineering production-grade autonomous agentic systems. Distilled from Vahe Aslanyan's (*The AI Agent Engineer's Guide: 60 Patterns for Building Autonomous Systems*, LUNARTECH) foundational pattern catalog and Chidiebere Njoku's dynamic model routing architecture, this skill enforces rigorous engineering discipline over generative AI hype.\n\nRather than treating agents as prompt-engineering novelties or personality wrappers, `ai-agent-engineer` enforces the **Capability-Composition Frontier**:\n1. **The Four-Level Ladder**: Always pick the lowest level that solves the problem (Static Prompt -> Deterministic Workflow -> Bounded Agent -> Full Agent).\n2. **Deterministic Harness, Stochastic Policy**: Wrap probabilistic LLM calls in invariant code boundaries with structural input\u002Finstruction separation.\n3. **Session-Level Evaluation**: The fundamental unit of evaluation for an agent is the *session*, not the prompt.\n4. **Corrigibility by Design**: Every action-taking agent must maintain an explicit, sub-second human off-switch and transactional rollback semantics.\n\n---\n\n## The 5-Stage Operational Progression\n\n```\n[1. Qualify & Ladder] → [2. Capability Profile & Model Routing] → [3. Substrate & Structural Gates] → [4. Bounded Context & Loops] → [5. Session Eval & Corrigibility]\n```\n\nSee [CARD.md](CARD.md) for the companion quick-reference card and diagnostic checklist.\nSee [config.default.yaml](config.default.yaml) for operational step budgets, token thresholds, and model tier specifications.\nSee [references\u002Fpatterns-catalog.md](references\u002Fpatterns-catalog.md) for the catalog of all 60 canonical patterns across the 8 capabilities.\nSee [references\u002Ffour-level-ladder-guide.md](references\u002Ffour-level-ladder-guide.md) for in-depth level selection heuristics.\nSee [references\u002Ffailure-modes-antidotes.md](references\u002Ffailure-modes-antidotes.md) for the 5 canonical failure modes and structural antidotes.\nSee [references\u002Fmodel-routing-lifecycle.md](references\u002Fmodel-routing-lifecycle.md) for the 3-tier dynamic model switching guide.\n\n---\n\n## 1. Pre-Agent Qualification & The Four-Level Ladder\n\nBefore authoring code or selecting patterns, evaluate the candidate problem against the **Four-Level Ladder**:\n\n| Level | Architecture | Best Suited When... | Typical Examples |\n|---|---|---|---|\n| **Level 1** | **Static Prompt** | Single model call, static prompt template, no state-changing tools, no memory. Input in, output out. | Summarization, format translation, classification, extraction from known shapes. |\n| **Level 2** | **Deterministic Workflow** | Fixed sequence of steps (Step A -> Step B -> Step C). Content varies, but flow is invariant. Fits on a napkin. | Content pipelines (research -> draft -> cite), data enrichment, ETL extraction. |\n| **Level 3** | **Bounded Agent** | State-dependent next actions, small toolset (\u003C 15 tools), small step budget (\u003C 20 steps), easily reversible actions. | Ticket triage with tools, SQL QA against known schema, document inspection with standard ops. |\n| **Level 4** | **Full Agent** | Goal held across long horizons, dynamic recovery from unexpected failures, multi-turn tool interaction. | Autonomous software migration, end-to-end repository refactoring, deep investigative research. |\n\n> **Heuristic**: *The right level is the lowest one that solves the problem.* If Level 1 or Level 2 works, building an agent is pure overhead.\n\n### Executable Seam: `scripts\u002Fladder_evaluator.py`\nRun the automated ladder evaluator to classify tasks and validate the 5 Pre-Flight Questions:\n```python\nfrom scripts.ladder_evaluator import LadderEvaluator, TaskScopingInput\n\ntask = TaskScopingInput(\n    task_description=\"Triage customer support tickets and execute database lookups\",\n    candidate_tools=[\"lookup_customer\", \"search_kb\", \"update_ticket\"],\n    estimated_steps=5,\n    state_dependent_decisions=True,\n    success_metric=\">= 90% resolution rate without escalation\",\n    worst_case_blast_radius=\"Bounded to test sandbox; no customer emails dispatched\",\n    cost_ceiling_per_session=0.25,\n    evaluation_harness_description=\"Replay of 50 labeled customer support sessions\",\n    off_switch_description=\"Instant SIGINT with transactional ticket rollback in \u003C 200ms\",\n)\nresult = LadderEvaluator.evaluate(task)\nassert result.approved_for_implementation is True\n```\n\n> **Completion Criterion**: Documented level assignment (Level 1–4) and all 5 pre-flight scoping questions answered with quantitative metrics via `LadderEvaluator`.\n\n---\n\n## 2. Capability Profiling & Dynamic Model Routing\n\nFormulate a one-page **Capability Profile** selecting exact architectural patterns from the 8 core capabilities:\n\n### The 8 Capabilities Matrix\n- **Perception (Patterns 1–7)**: Turning raw signals into typed percepts (*Multimodal Grounding, Document Layout, Temporal Sensor-Fusion, Anomaly-Spotter, Visual Decomposition, Ambient Context, Schema-Inference*).\n- **Reasoning (Patterns 8–15)**: Inferring beyond the given (*CoT Auditor, Counterfactual Reasoner, Analogical Mapping, Constraint-Satisfaction Solver, Causal Graph Builder, Symbolic-Neural Bridge, Probabilistic Belief Updater, Self-Consistency Voter*).\n- **Planning (Patterns 16–22)**: From goal to sequenced actions (*Hierarchical Decomposer, ReAct Loop, Tree-of-Thought Explorer, Plan-Then-Execute, Adaptive Replanner, Resource-Aware Scheduler, Backward Goal-Regression*).\n- **Memory (Patterns 23–29)**: Persistence across time (*Episodic Buffer, Semantic Memory Curator, Working-Memory Manager, Forgetting-Policy, Memory-of-Self, Vector-Store Curator, Persistent Identity*).\n- **Tool Use (Patterns 30–37)**: Reaching outside the model (*Tool Selector, API-Schema Adapter, Code Sandbox, Shell-Operator, Browser-Driver, DB Query Synthesizer, File-System Curator, Side-Effect Auditor*).\n- **Coordination (Patterns 38–45)**: Multi-agent and human synchronization (*Router\u002FDispatcher, Debate Moderator, Consensus-Builder, Pipeline Orchestrator, Human-in-the-Loop Liaison, Negotiation, Auctioneer, Supervisor-Worker*).\n- **Learning (Patterns 46–52)**: Improving through experience (*Feedback Loop, Reflection, Skill-Library Builder, Curriculum Designer, Few-Shot Prompt Tuner, Distillation, Active Learner*).\n- **Alignment (Patterns 53–60)**: Behaving by design (*Constitution-Bound, Refusal Calibrator, Provenance Tracker, Red-Team Auditor, Privacy-Preserving, Explainer, Drift Detector, Off-Switch-Compatible*).\n\n### Executable Seam: `scripts\u002Fcapability_profiler.py`\nValidate the capability profile against architectural composition invariants:\n```python\nfrom scripts.capability_profiler import CapabilityProfiler, CapabilityProfile\n\nprofile = CapabilityProfile(\n    agent_name=\"ticket_triager\",\n    target_level=3,\n    declared_patterns=[17, 25, 30, 37, 53, 60],\n    tools_count=6,\n    has_external_mutations=True,\n    estimated_session_steps=8,\n)\nreport = CapabilityProfiler.validate_profile(profile)\nassert report.valid is True\n```\n\n### Executable Seam: `scripts\u002Fdynamic_model_router.py`\nOperationalize Chidiebere Njoku's 3-Tier model routing architecture:\n```python\nfrom scripts.dynamic_model_router import DynamicModelRouter\n\ncomplexity = DynamicModelRouter.analyze_complexity(\n    prompt=\"Explain this database schema and propose index optimizations\",\n    candidate_tools=[\"sql_explain\"]\n)\ndecision = DynamicModelRouter.route_model(complexity, cost_ceiling=0.50)\nexec_res = DynamicModelRouter.simulate_fallback_chain(decision)\nassert exec_res.status == \"SUCCESS\"\n```\n\n> **Completion Criterion**: 1-Page Capability Profile validated via `CapabilityProfiler` and 3-tier dynamic model routing confirmed via `DynamicModelRouter`.\n\n---\n\n## 3. Substrate Isolation & Structural Guardrails\n\nWrap the stochastic model policy within a deterministic software harness. Every production agent framework converges on five abstractions:\n1. **Client**: The transport layer to the model provider, handling retries, timeouts, and streaming.\n2. **Registry**: The catalog of typed tools, schemas, and parameter validators.\n3. **Prompt**: The per-step context assembler combining invariants, role instructions, working memory, and tool observations.\n4. **Memory**: The persistence substrate across turns and sessions.\n5. **Loop**: The deterministic state machine driving observation -> thought -> action execution.\n\n### Structural Guardrails\n- **Constitutional Gating (Pattern 53)**: Intercept all proposed tool invocations inside a pre-execution hook. Assert tool call arguments against strict negative boundaries (e.g. no destructive deletes, no outbound network calls to unauthorized IPs). If violation detected, reject the tool call *before* execution.\n- **Side-Effect Auditing & Transactional Rollback (Pattern 37)**: Record every tool invocation into an append-only transaction log. On tool error or agent failure, execute automated rollback handlers (`rollback_transaction()`) to restore filesystem and database state.\n- **Structural Input\u002FInstruction Separation**: Wrap user-supplied data and retrieved documents in structured data containers (e.g. XML tags `\u003Cuser_document>...\u003C\u002Fuser_document>`). Instruct policy that instructions inside data blocks are non-executable content.\n\n> **Completion Criterion**: Deterministic harness abstractions established, Constitutional pre-execution gates active, and transactional rollback mechanisms declared.\n\n---\n\n## 4. Context Boundedness & Execution Loops\n\nUnbounded context growth and infinite loops are fatal production failure modes. Enforce rigid boundaries:\n\n### Working Memory Management (Pattern 25)\n- **Token Budget Allocation**: Dedicate max 60% of model context window to conversation trajectory. Reserve 20% for system invariants\u002Ftools, and 20% for output generation.\n- **Progressive Middle-Out Tool Pruning**: If tool observation exceeds token thresholds (e.g. > 2,000 tokens), retain first 50 lines (header context) and last 50 lines (tail results), replacing the middle with structured truncation summaries.\n- **AST Repo Map \u002F Graph Injection**: Never dump entire codebases or directories into context. Inject PageRanked structural skeleton maps showing only relevant function signatures and types.\n\n### Bounded ReAct Loop (Pattern 17) & Adaptive Replanning (Pattern 20)\n- **Hard Step Caps**: Set a mandatory step ceiling (N_max \u003C= 20 for Level 3; N_max \u003C= 40 for Level 4).\n- **Progress Delta Assertion**: At each iteration k, compute state distance to goal. If state delta delta_S = 0 for 3 consecutive steps (repeated tool calls with identical parameters or no new percepts), trigger **Adaptive Replanner (Pattern 20)** to reformulate strategy or halt.\n\n> **Completion Criterion**: Active context budget bounded under 60% of window across 50 steps; ReAct loop instrumented with step caps and progress delta checks.\n\n---\n\n## 5. Session-Level Evaluation & Production Corrigibility\n\nStatic prompt evaluation is insufficient. Validate the agent across the **Four Evaluation Surfaces**:\n1. **Static Evaluation**: Benchmark against labeled inputs measuring pass rate, latency, and token cost.\n2. **Trajectory Replay Evaluation**: Replay historical multi-turn sessions with frozen tool outputs to detect behavioral regressions in tool-selection order.\n3. **Perturbation & Noise Testing**: Inject unexpected tool errors, malformed JSON, and network timeouts to assert graceful recovery without crash.\n4. **Live Shadowing**: Run candidate agent policy in parallel with production systems, comparing proposed actions without executing side effects.\n\n### The 5 Canonical Failures Audit\nBefore production deployment, verify immunity against the 5 canonical failure modes:\n1. *Looped Reasoning* -> Verified step cap and stagnation replanner active.\n2. *Tool Spoofing* -> Verified structural data separation and Constitutional action validation.\n3. *Context Exhaustion* -> Verified per-step working memory compaction and middle-out pruning.\n4. *Goal Drift* -> Verified explicit immutable goal anchor preserved across all steps.\n5. *Silent Success on Wrong Task* -> Verified dual-check reflection comparing final deliverable to original intake request.\n\n### Corrigibility & Off-Switch Invariant (Pattern 60)\n- Expose an immediate human interrupt signal (`SIGINT`, web UI abort button, or CLI kill command).\n- On abort signal, the agent proactor must drain subprocess pipes, serialize in-flight working memory to disk, trigger transactional cleanup, and exit cleanly within \u003C= 500 ms.\n\n> **Completion Criterion**: 4-surface evaluation suite passing baseline thresholds; zero unhandled canonical failure modes; sub-second off-switch verified.\n\n---\n\n## The Visual Brief Specification\n\nWhen formulating architectural proposals or major agent refactors, generate an interactive HTML Visual Brief:\n1. **Target Path**: Render to `%TEMP%\\ai-agent-engineer-\u003Ctimestamp>.html`.\n2. **Visual Assets**: Include Tailwind CSS and Mermaid.js diagrams illustrating the proposed agent topology, capability profile, and fallback chains.\n3. **Diagnostic Tables**: Embed the 5 pre-flight questions scorecard, the capability contract table, and the failure mode antidote matrix.\n4. **Delivery**: Verify file generation and deliver a clickable `file:\u002F\u002F\u002F` link to the user.\n\n---\n\n## Mandatory Checkpoint Gate\n\nBefore executing irreversible structural changes, external side effects, or deploying autonomous agents:\n1. **Present Implementation Plan**: Author a comprehensive plan artifact detailing the target capability profile, model routing tiers, and blast-radius mitigations.\n2. **Set Feedback Header**: Set `RequestFeedback: true` in artifact metadata.\n3. **Human Sign-Off Invariant**: STOP and wait for explicit human review and approval before executing transactions.\n\n---\n\n## Anti-Patterns\n\n- **Agent-as-Marketing** — Building an autonomous agent for PR or trend-following when a static prompt or deterministic script solves the problem with higher reliability.\n- **Multi-Agent Swarm Vanity** — Deploying complex multi-agent communicating swarms where agents spend the majority of token budgets exchanging polite coordination messages.\n- **Prompt-Only Guardrails** — Relying on system prompt instructions like \"never delete user data\" instead of code-level constitutional interceptors and OS sandboxes.\n- **Context Flooding Memory** — Dumping entire unpruned conversation logs and raw tool observations into prompt context until model degradation occurs.\n- **Unbounded Autonomy** — Running agent loops without hard step caps, monetary ceilings, or progress delta monitoring.\n- **Single-Model Dependency** — Coupling production agent operations to a single frontier model provider without multi-tier fallback chains and circuit breakers.\n- **Missing Off-Switch** — Deploying autonomous action-taking systems without sub-second operator kill-switches and transactional rollback semantics.\n",{"name":5,"description":7},"main","eff3b00e36d1d233ad4a4389605c82fbfa0326d3",".agents\u002Fskills\u002Fai-agent-engineer","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness","https:\u002F\u002Fgithub.com\u002FSpectreDeath","I'm here to manage stress so I wouldn't expect earth shattering break throughs I'm just an enthusiast that likes making stuff. ","2026-11-15 05:32:58",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add SpectreDeath\u002FBrain-Harness --skill ai-agent-engineer",{"tool":37,"command":38},"bunx","bunx skills add SpectreDeath\u002FBrain-Harness --skill ai-agent-engineer",{"tool":40,"command":41},"pnpm","pnpm dlx skills add SpectreDeath\u002FBrain-Harness --skill ai-agent-engineer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002FSKILL.md",true,[45,51,55,59,63,67,71,77,81],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"CARD.md","REFERENCE","参考文档",4967,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002FCARD.md",{"path":52,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":53,"sourceHtmlUrl":54},"config.default.yaml",1194,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Fconfig.default.yaml",{"path":56,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":57,"sourceHtmlUrl":58},"references\u002Ffailure-modes-antidotes.md",3066,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Freferences\u002Ffailure-modes-antidotes.md",{"path":60,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":61,"sourceHtmlUrl":62},"references\u002Ffour-level-ladder-guide.md",4050,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Freferences\u002Ffour-level-ladder-guide.md",{"path":64,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Fmodel-routing-lifecycle.md",2861,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Freferences\u002Fmodel-routing-lifecycle.md",{"path":68,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fpatterns-catalog.md",7943,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Freferences\u002Fpatterns-catalog.md",{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"scripts\u002Fcapability_profiler.py","SCRIPT","脚本",13078,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Fscripts\u002Fcapability_profiler.py",{"path":78,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":79,"sourceHtmlUrl":80},"scripts\u002Fdynamic_model_router.py",6702,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Fscripts\u002Fdynamic_model_router.py",{"path":82,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":83,"sourceHtmlUrl":84},"scripts\u002Fladder_evaluator.py",8336,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fai-agent-engineer\u002Fscripts\u002Fladder_evaluator.py",[86,93,100,107,114,121],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7E0W6FR68J2N9CXCZTAQJFX","ui-behavior-primitive-architect","Architect, audit, and verify zero-dependency headless UI behavior primitives, WebMCP agent bridges, WAI-ARIA\u002FSSR\u002FRTL tri-modal checks, and framework expert routing. Do not use for static CSS theme styling or backend database migrations.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fui-behavior-primitive-architect\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7E0VZ7JQNW34G271DENFGYP","trustgraph-ontology-governor","Govern knowledge graphs, SHACL-AF triple policies, OntologyRAG subclass validation, PROV-O dual named graphs, and Laya entropy decision scoring. Do not use for relational SQL queries or generic web scraping.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftrustgraph-ontology-governor\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M7E0VQ6Z7R45Q8QAZ4MT39EK","shim-harness-governor","Govern universal CLI agent loops, 4-tier tool permissions, ancestor-symlink workspace sandboxes, deterministic-first command routing, collision-safe MCP namespacing, and layered skill loading. Do not use for static UI styling or external SQL analytics.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fshim-harness-governor\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M7E0VC18NMP1QBSRJ3TPQ7MB","graphiti-zep-memory-governor","Govern bi-temporal knowledge graphs with Graphiti future-edge clamping, MinHash\u002FLSH entity dedup, RRF\u002FMMR reranking, and Zep typed ontologies. Do not use for static SQL joins or generic web crawling.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgraphiti-zep-memory-governor\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":19},"01M7E0V12ABE1RW3ZRCST8VH5Z","agora-mcp-workbench-architect","Architect, audit, and orchestrate Agora Workbench MCP servers, loopback sidecars, unified state graphs, gateway\u002Fdispatcher connectors, and policy-enforced data lakes. Do not use for static frontend CSS styling or non-MCP desktop GUI automation.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fagora-mcp-workbench-architect\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":19},"01M7BFYG6QT3484VC57TZ19V7P","skill-eval-assurance-runner","Evaluate and assure agent skills using small-N Wilson confidence intervals, unbiased pass^k reliability, deterministic trajectory graders, preflight boundary honesty, and sealed digest verification. Do not use for subjective prose review or unconstrained production deployment.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fskill-eval-assurance-runner\u002FSKILL.md",[],[]]