MCPInstall

model-first-reasoning

Apply Model-First Reasoning (MFR) to code generation tasks. Use when the user requests "model-first", "MFR", "formal modeling before coding", "model then implement", or when tasks involve complex logic, state machines, constraint systems, or any implementation requiring formal correctness guarantees. Enforces strict separation between modeling and implementation phases.

Installs
44
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/petekp/agent-skills --skill model-first-reasoning
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads model-first-reasoning automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Model-First Reasoning (MFR)

A rigorous methodology that REQUIRES constructing an explicit problem MODEL before any reasoning or implementation. The model becomes a frozen contract that governs all downstream work.

Based on Kumar & Rana (2025), "Model-First Reasoning LLM Agents: Reducing Hallucinations through Explicit Problem Modeling" (arXiv:2512.14474)

Why MFR Works

Hallucination is not merely the generation of false statements—it is a symptom of reasoning performed without a clearly defined model of the problem space.

Reasoning does not create structure; it operates on structure. When that structure is implicit or unstable, reasoning becomes unreliable. MFR provides "soft symbolic grounding"—enough structure to stabilize reasoning without imposing rigid formalism.

Core Principle

Phase 1 produces the MODEL. Phase 2 reasons/implements ONLY within the model.

This prevents the common failure mode where reasoning introduces ad-hoc decisions, missing constraints, or invented behavior not grounded in the problem definition.

Non-Negotiable Rules

  1. Phase 1 (Model) produces NO code, no solution steps—only the formal model
  2. Phase 2 (Implement) may NOT introduce new entities, state, actions, or constraints
  3. If you need something not in the model: output exactly MODEL INCOMPLETE + what to add, then STOP
  4. No invented APIs or dependencies. If not provided, either ask (unknowns) or create a stub clearly marked STUB

The Model as Contract

After creating the model, run a MODEL AUDIT before coding:

Audit Checks

CheckDescription
CoverageEvery user requirement is represented in exactly one of: a constraint, the goal/acceptance criteria, or an action precondition/effect
OperabilityEvery operation your plan would require is present as an action
ConsistencyConstraints don't contradict each other; action effects don't violate invariants
TestabilityEvery constraint has ≥1 test oracle

If any audit check fails, revise the model (still Phase 1) until it passes.

Freeze Rule

Once the audit passes, treat the model as read-only source of truth.

If later you discover missing info during implementation:

  1. Emit a MODEL PATCH (minimal change)
  2. Restart Phase 2 from scratch using the updated model

Validation

After creating the model, write it to model.json and run the validator:

python scripts/validate-model.py model.json

Exit codes:

  • 0 = Valid, ready for Phase 2
  • 1 = Invalid structure (fix and retry)
  • 2 = Valid but has unknowns (STOP after Phase 1)

Output Format

Phase 1: MODEL

The model may be expressed in natural language, semi-structured text, or JSON. Flexibility improves compliance—what matters is that the representation is explicit, inspectable, and stable.

For code generation tasks, the structured format below is recommended. Use MODEL_TEMPLATE.json as a reference:

{
  "deliverable": {
    "description": "What we're building",
    "files_expected": ["path/to/file.ts", ...]
  },
  "entities": [
    {"name": "EntityName", "description": "...", "properties": [...]}
  ],
  "state_variables": [
    {"name": "varName", "type": "...", "initial": "...", "description": "..."}
  ],
  "actions": [
    {
      "name": "actionName",
      "description": "...",
      "preconditions": ["..."],
      "effects": ["..."],
      "parameters": [...]
    }
  ],
  "constraints": [
    {"id": "C1", "statement": "...", "type": "invariant|precondition|postcondition"}
  ],
  "initial_state": ["description of starting conditions"],
  "goal": ["acceptance criteria"],
  "assumptions": ["things we assume to be true"],
  "unknowns": ["questions that must be answered before proceeding"],
  "requirement_trace": [
    {
      "requirement": "<verbatim from user>",
      "represented_as": "goal|constraint|action",
      "ref": "C1|action_name|goal_item"
    }
  ],
  "test_oracles": [
    {"id": "T1", "maps_to": ["C1"], "description": "how to verify constraint"}
  ]
}

Critical: If unknowns is non-empty, STOP after Phase 1. Do not implement until unknowns are resolved.

Phase 1.5: MODEL AUDIT

Return:

{
  "audit_pass": true|false,
  "issues": [
    {"type": "coverage|operability|consistency|testability", "detail": "..."}
  ]
}

If audit_pass is false, STOP and return to Phase 1 to revise the model.

Phase 2: IMPLEMENTATION

Using ONLY the frozen model:

A) PLAN

Numbered steps where each step must be an instance of a defined action:

Step 1: [action_name]
  - Preconditions check: [list which preconditions are satisfied]
  - Effects applied: [what state changes]
  - Constraints check: [C1, C2, ...]

B) CODE

Create all files in deliverable.files_expected:

Model ElementCode Translation
entities / state_variablesTypes, interfaces, data models
actionsFunctions/modules with validation + explicit failure modes
constraintsRuntime checks, defensive parsing, invariants

C) TESTS

Implement all test_oracles. Every constraint must be covered by ≥1 test.

D) VERIFICATION MAP

For each constraint, document:

  • Where it is enforced in code (file:line)
  • Which tests cover it

When to Use MFR

MFR is most valuable for:

  • Complex state machines — where transitions must be valid
  • Business logic with invariants — rules that must never be violated
  • Data transformations — where input/output contracts matter
  • Multi-step workflows — with dependencies between steps
  • Safety-critical features — where bugs have high cost
  • Collaborative specifications — where the model serves as documentation

When NOT to use: Simple, single-step tasks where the overhead of explicit modeling exceeds its benefit.

Relationship to Other Reasoning Strategies

MFR is complementary, not competing:

  • With Chain-of-Thought: Use CoT within Phase 2 for step-by-step reasoning over the model
  • With ReAct: Treat the model as persistent state that actions operate on
  • With planning agents: The model provides the domain specification that planners reason over

MFR provides a foundational layer that improves robustness of any reasoning strategy in constraint-heavy domains.

Example Workflow

User: Build a shopping cart that enforces: max 10 items, no duplicate SKUs,
      total can't exceed $1000

You: [PHASE 1: MODEL]
{
  "entities": [
    {"name": "CartItem", "properties": ["sku", "price", "quantity"]}
  ],
  "constraints": [
    {"id": "C1", "statement": "cart.items.length <= 10", "type": "invariant"},
    {"id": "C2", "statement": "all SKUs in cart are unique", "type": "invariant"},
    {"id": "C3", "statement": "sum(items.price * items.quantity) <= 1000", "type": "invariant"}
  ],
  "actions": [
    {
      "name": "addItem",
      "preconditions": ["cart.items.length < 10", "sku not in cart", "new total <= 1000"],
      "effects": ["item added to cart"]
    }
  ],
  ...
}

[PHASE 1.5: MODEL AUDIT]
{
  "audit_pass": true,
  "issues": []
}

[PHASE 2: IMPLEMENTATION]
// Now implementing strictly from the model...

Remember

The model is not overhead—it IS the specification. Most failures in complex reasoning are representational, not inferential: the reasoning was fine, but it operated on an incomplete or unstable understanding of the problem.

By externalizing the model, we make assumptions inspectable, constraints enforceable, and errors diagnosable. The model becomes the contract between intent and implementation.

Model first. Then reason. Never invert this.

FAQ

What does the model-first-reasoning skill do?

Apply Model-First Reasoning (MFR) to code generation tasks. Use when the user requests "model-first", "MFR", "formal modeling before coding", "model then implement", or when tasks involve complex logic, state machines, constraint systems, or any implementation requiring formal correctness guarantees. Enforces strict separation between modeling and implementation phases.

How do I install model-first-reasoning?

Run npx skills add https://github.com/petekp/agent-skills --skill model-first-reasoning in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/model-first-reasoning/ (personal) or .claude/skills/model-first-reasoning/ (project).

Which AI agents can use model-first-reasoning?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is model-first-reasoning safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains model-first-reasoning?

It is published by petekp in petekp/agent-skills. It has 44 recorded installs.

More from petekp/agent-skills

View all →

typography

petekp/agent-skills

Apply professional typography principles to create readable, hierarchical, and aesthetically refined interfaces. Use when setting type scales, choosing fonts, adjusting spacing, designing text-heavy layouts, implementing dark mode typography, or when asked about readability, font pairing, line height, measure, typographic hierarchy, variable fonts, font loading, or OpenType features.

Frontend & Design522 installs

macos-app-design

petekp/agent-skills

Open the skill to read its SKILL.md instructions.

AI & Agents398 installs

optimize-agent-docs

petekp/agent-skills

Build a retrieval-optimized knowledge layer over agent documentation in dotfiles (.claude, .codex, .cursor, .aider). Use when asked to "optimize docs", "improve agent knowledge", "make docs more efficient", or when documentation has accumulated and retrieval feels inefficient. Generates a manifest mapping task-contexts to knowledge chunks, optimizes information density, and creates compiled artifacts for efficient agent consumption.

Docs & Writing314 installs

codebase-study-guide

petekp/agent-skills

Generate a pedagogically-grounded study guide for learning an unfamiliar codebase. Use when the user wants to onboard onto a codebase, understand a project's architecture, create learning materials for a team, or asks things like "help me learn this codebase", "create an onboarding guide", "I'm new to this project", "how does this system work", "study guide for this repo", or "explain this codebase to me". Produces a structured document that builds understanding from purpose to systems to patterns, using evidence-based learning techniques (elaborative interrogation, concept mapping, threshold concepts, worked examples, progressive disclosure).

unix-macos-engineer

petekp/agent-skills

Open the skill to read its SKILL.md instructions.

AI & Agents114 installs

explainer-visuals

petekp/agent-skills

Create high-quality animated explainer visuals for essays and blog posts. Use when the user wants to visualize concepts, processes, data, or ideas with interactive web animations. Triggers on requests like "create a visual for", "animate this concept", "make an explainer", "visualize this idea", "diagram this process", "show this data", or when essay content would benefit from visual explanation. Handles abstract concepts (mental models, frameworks), technical processes (algorithms, systems), and data visualization (trends, comparisons). Outputs self-contained HTML/CSS/JS that embeds directly in web content.

Frontend & Design101 installs

Popular ai & agents skills

View category →

google-agents-cli-publish

google/agents-cli

This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).

AI & Agents513.9K installs

google-agents-cli-eval

google/agents-cli

This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).

AI & Agents513.5K installs

skill-creator

anthropics/skills

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

OfficialAI & Agents416.4K installs

codex-pet

prime-skills/runcomfy-agent-skills

Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.

AI & Agents402.1K installs

full-output-enforcement

leonxlnx/taste-skill

Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.

AI & Agents401K installs

executing-plans

obra/superpowers

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

AI & Agents245.7K installs